lib/Android/ElectricSheep/Automator/Plugins/Apps/Viber.pm

filter: Statementstmt 100% 9 / 9 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 3 / 3 Podpod n/a totaltotal 100% 12 / 12 CC 1 SCAR 0.0
CC
1
Cov
100%
BEGIN
1.0
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« lib/Android/ElectricSheep/Automator.pm ↑ Summary
1 package Android::ElectricSheep::Automator::Plugins::Apps::Viber;
2  
3 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 1 ▶use parent 'Android::ElectricSheep::Automator::Plugins::Apps::Base';
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 use Time::HiRes qw/usleep/;
9 use Encode qw/encode_utf8 decode_utf8/;
10 use Data::Roundtrip qw/perl2dump no-unicode-escape-permanently/;
11  
12 use Android::ElectricSheep::Automator::XMLParsers;
13  
14 sub new {
15 my ($class, $params) = @_;
16 my $self = $class->SUPER::new({
17 %$params,
18 'child-class' => $class,
19 });
20 $self->{'_private'}->{'appname'} = 'com.viber.voip';
21  
22 return $self;
23 }
24  
25 # keeps pressing the back-arrow at the top of the app to hopefully
26 # arrive at the main activity of the app,
27 # TODO: is there a way to tell it to go to main activity ? WelcomeActivity does not seem to work
28 # returns 1 on failure, 0 on success.
29 sub navigate_to_viber_home_activity {
30 my ($self, $params) = @_;
31 my $parent = ( caller(1) )[3] || "N/A";
32 my $whoami = ( caller(0) )[3];
33 my $log = $self->log();
34 my $verbosity = $self->verbosity();
35  
36 my ($outbase, $outfile);
37 # for debugging purposes, save each UI we get here
38 $outbase = exists($params->{'outbase'}) ? $params->{'outbase'} : undef;
39  
40 my ($ui, $dom, $xc, $asel, @nodes, $N, $node, $boundstr, $bounds);
41  
42 my $repeats = 3;
43 my $repeatsUI = 3;
44 ONBACKARROW:
45 while(--$repeats > 0){
46 # we assume the app is open and at the foreground
47 # get the UI
48 $outfile = defined($outbase) ? $outbase.'_main.xml' : undef;
49 do {
50 $ui = $self->mother->dump_current_screen_ui({'filename'=>$outfile});
51 usleep(0.75);
52 } while( ($repeatsUI-- > 0) && ! defined($ui) );
53 if( ! defined $ui ){ $log->error("${whoami} (via $parent), line ".__LINE__." : error, failed to dump the UI, call to ".'dump_current_screen_ui()'." has failed after a number of repeats. I am not sure what the problem is, most likely a race condition ..."); return undef }
54  
55 $dom = $ui->{'XML::LibXML'};
56 $xc = $ui->{'XML::LibXML::XPathContext'};
57 $asel = '//node'
58 . '['
59 . ' matches(@content-desc,\'navigate\s+up\',"i")'
60 . ' and matches(@class,\'ImageButton\',"i")'
61 . ' and @package="com.viber.voip"'
62 . ' and matches(@bounds,\'^\[\',"i")'
63 . ']'
64 ;
65 @nodes = $xc->findnodes($asel);
66 $N = scalar @nodes;
67 if( $N == 0 ){
68 if( $verbosity > 0 ){ $log->info("${whoami} (via $parent), line ".__LINE__." : no nodes matching this XPath selector (for getting the 'back-arrow' icon, hopefully, this means we reached home-page of the app): ${asel}") }
69 last ONBACKARROW;
70 } elsif( $N > 1 ){ $log->error("--begin matched nodes:\n".join("\n", @nodes)."\n--end nodes matched.\n\n${whoami} (via $parent), line ".__LINE__." : error, matched more than one node (see above) with this XPath selector (for getting the 'Chats' icon: ${asel}"); return 1 }
71 $node = $nodes[0];
72  
73 # click the 'back-arrow' at the top
74 $boundstr = $node->getAttribute('bounds');
75 if( ! defined $boundstr ){ $log->error("${node}\n\n${whoami} (via $parent), line ".__LINE__." : error, above node does not have attribute 'bounds'."); return 1 }
76 if( $boundstr !~ /\[\s*(\d+)\s*,\s*(\d+)\]\s*\[\s*(\d+)\s*,\s*(\d+)\]/ ){ $log->error("${whoami} (via $parent), line ".__LINE__." : error, failed to parse bounds string: '$boundstr'."); return 1 }
77 $bounds = [[$1,$2],[$3,$4]];
78 # click it
79 if( $verbosity > 0 ){ $log->info("${whoami} (via $parent), line ".__LINE__." : clicking the back-arrow ...") }
80 if( $self->mother->tap({'bounds' => $bounds}) ){ $log->error("${whoami} (via $parent), line ".__LINE__." : error, failed to tap on $bounds."); return 1 }
81 usleep(0.75);
82 }
83  
84 if( $verbosity > 0 ){ $log->info("${whoami} (via $parent), line ".__LINE__." : hopefully we are now at the very first screen of the app.") }
85 return 0 # success
86 }
87  
88 # "type" the specified message into
89 # the message will be sanitised in input_text(), spaces will be replaced with %s
90 # unicode is not supported
91 sub send_message {
92 my ($self, $params) = @_;
93 my $parent = ( caller(1) )[3] || "N/A";
94 my $whoami = ( caller(0) )[3];
95 my $log = $self->log();
96 my $verbosity = $self->verbosity();
97  
98 my ($recipient, $message, $outbase, $outfile);
99 if( ! exists($params->{'recipient'}) || ! defined($recipient=$params->{'recipient'}) ){ $log->error("${whoami} (via $parent), line ".__LINE__." : error, input parameter 'recipient' was not specified."); return undef }
100 if( ! exists($params->{'message'}) || ! defined($message=$params->{'message'}) ){ $log->error("${whoami} (via $parent), line ".__LINE__." : error, input parameter 'message' was not specified."); return undef }
101 # for debugging purposes, save each UI we get here
102 $outbase = exists($params->{'outbase'}) ? $params->{'outbase'} : undef;
103 # do everything except clicking the send button
104 my $mock = exists($params->{'mock'}) ? $params->{'mock'} : 0;
105  
106 my ($dom, $xc, $asel, @nodes, $N, $node, $boundstr, $bounds);
107  
108 if( $self->navigate_to_viber_home_activity({'outbase'=>$outbase}) ){ $log->error("${whoami} (via $parent), line ".__LINE__." : error, call to ".'navigate_to_viber_home_activity()'." has failed."); return undef }
109 usleep(1.5);
110  
111 # we assume the app is open and at the foreground
112 # get the UI
113 $outfile = defined($outbase) ? $outbase.'_main.xml' : undef;
114 # there is always the chance you get 'Is taking too long'...
115 # and all will fail TODO!
116 my $ui;
117 my $repeatsUI = 3;
118 do {
119 if( $verbosity > 0 ){ $log->info("${whoami} (via $parent), line ".__LINE__." : calling ".'dump_current_screen_ui()'." for at repeat $repeatsUI ...") }
120 $ui = $self->mother->dump_current_screen_ui({'filename'=>$outfile});
121 usleep(0.75);
122 } while( ($repeatsUI-- > 0) && (! defined($ui)) );
123 if( ! defined $ui ){ $log->error("${whoami} (via $parent), line ".__LINE__." : error, failed to dump the UI, call to ".'dump_current_screen_ui()'." has failed after a number of repeats. I am not sure what the problem is, most likely a race condition ..."); return undef }
124  
125 $dom = $ui->{'XML::LibXML'};
126 $asel = '//node[@text="Chats" and @resource-id="com.viber.voip:id/bottomBarItemTitle"]';
127 @nodes = $dom->findnodes($asel);
128 $N = scalar @nodes;
129 if( $N == 0 ){ $log->error("${whoami} (via $parent), line ".__LINE__." : error, failed to find any nodes matching this XPath selector (for getting the 'Chats' icon): ${asel}"); return undef }
130 elsif( $N > 1 ){ $log->error("--begin matched nodes:\n".join("\n", @nodes)."\n--end nodes matched.\n\n${whoami} (via $parent), line ".__LINE__." : error, matched more than one node (see above) with this XPath selector (for getting the 'Chats' icon): ${asel}"); return undef }
131 $node = $nodes[0];
132  
133 # click the 'Chats' at the bottom
134 $boundstr = $node->getAttribute('bounds');
135 if( ! defined $boundstr ){ $log->error("${node}\n\n${whoami} (via $parent), line ".__LINE__." : error, above node does not have attribute 'bounds'."); return undef }
136 if( $boundstr !~ /\[\s*(\d+)\s*,\s*(\d+)\]\s*\[\s*(\d+)\s*,\s*(\d+)\]/ ){ $log->error("${whoami} (via $parent), line ".__LINE__." : error, failed to parse bounds string: '$boundstr'."); return undef }
137 $bounds = [[$1,$2],[$3,$4]];
138 # click it
139 if( $self->mother->tap({'bounds' => $bounds}) ){ $log->error("${whoami} (via $parent), line ".__LINE__." : error, failed to tap on $bounds."); return undef }
140 sleep(1);
141  
142 # now we are on the chats screen, in the centre pane there are all our contacts
143 # get the ui for this screen
144 $outfile = defined($outbase) ? $outbase.'_chats.xml' : undef;
145 $ui = $self->mother->dump_current_screen_ui({'filename'=>$outfile});
146 $dom = $ui->{'XML::LibXML'};
147 $xc = $ui->{'XML::LibXML::XPathContext'};
148 $asel = '//node'
149 . '['
150 . '@text'
151 . ' and matches(@text,\''.$params->{'recipient'}.'\',"i")'
152 . ' and @resource-id="com.viber.voip:id/from"'
153 . ']'
154 ;
155 @nodes = $xc->findnodes($asel);
156 $N = scalar @nodes;
157 if( $N == 0 ){ $log->error("${whoami} (via $parent), line ".__LINE__." : error, failed to find any nodes matching this XPath selector (for getting the recipient (".$params->{'recipient'}.") from the contacts on the central pane: ${asel}"); return undef }
158 elsif( $N > 1 ){ $log->error("--begin matched nodes:\n".join("\n", @nodes)."\n--end nodes matched.\n\n${whoami} (via $parent), line ".__LINE__." : error, matched more than one node (see above) with this XPath selector (for getting the recipient (".$params->{'recipient'}.") from the contacts on the central pane: ${asel}"); return undef }
159 $node = $nodes[0];
160  
161 # click the Recipient contact name at the bottom
162 $boundstr = $node->getAttribute('bounds');
163 if( ! defined $boundstr ){ $log->error("${node}\n\n${whoami} (via $parent), line ".__LINE__." : error, above node does not have attribute 'bounds'."); return undef }
164 if( $boundstr !~ /\[\s*(\d+)\s*,\s*(\d+)\]\s*\[\s*(\d+)\s*,\s*(\d+)\]/ ){ $log->error("${whoami} (via $parent), line ".__LINE__." : error, failed to parse bounds string: '$boundstr'."); return undef }
165 $bounds = [[$1,$2],[$3,$4]];
166 # click it
167 if( $self->mother->tap({'bounds' => $bounds}) ){ $log->error("${whoami} (via $parent), line ".__LINE__." : error, failed to tap on $bounds."); return undef }
168 usleep(1.5);
169  
170 # Put the text into the text-edit Message... (note: ... is unicode ellipses something)
171 # get the UI
172 $outfile = defined($outbase) ? $outbase.'_chat.xml' : undef;
173 $ui = $self->mother->dump_current_screen_ui({'filename'=>$outfile});
174 $dom = $ui->{'XML::LibXML'};
175 $xc = $ui->{'XML::LibXML::XPathContext'};
176 $asel = '//node'
177 . '['
178 . ' matches(@class,\'EditText$\',"i")'
179 . ' and @resource-id="com.viber.voip:id/send_text"'
180 . ' and @package="com.viber.voip"'
181 . ']'
182 ;
183 @nodes = $xc->findnodes($asel);
184 $N = scalar @nodes;
185 if( $N == 0 ){ $log->error("${whoami} (via $parent), line ".__LINE__." : error, failed to find any nodes matching this XPath selector (for getting the specified recipient (".$params->{'recipient'}."): ${asel}"); return undef }
186 elsif( $N > 1 ){ $log->error("--begin matched nodes:\n".join("\n", @nodes)."\n--end nodes matched.\n\n${whoami} (via $parent), line ".__LINE__." : error, matched more than one node (see above) with this XPath selector (for getting the specified recipient (".$params->{'recipient'}.")): ${asel}"); return undef }
187 $node = $nodes[0];
188 $boundstr = $node->getAttribute('bounds');
189 if( ! defined $boundstr ){ $log->error("${node}\n\n${whoami} (via $parent), line ".__LINE__." : error, above node does not have attribute 'bounds'."); return undef }
190 if( $boundstr !~ /\[\s*(\d+)\s*,\s*(\d+)\]\s*\[\s*(\d+)\s*,\s*(\d+)\]/ ){ $log->error("${whoami} (via $parent), line ".__LINE__." : error, failed to parse bounds string: '$boundstr'."); return undef }
191 $bounds = [[$1,$2],[$3,$4]];
192  
193 # add the text in the node
194 # the message will be sanitised in input_text(), spaces will be replaced with %s
195 # unicode is not supported
196 # TODO: perhaps warn about unicode in message?
197 if( $self->mother->input_text({'bounds' => $bounds, 'text' => $message}) ){ $log->error("${whoami} (via $parent), line ".__LINE__." : error, failed to input text on ${boundstr}. Note that there may be a maximum length for the message. Your message was ".length($message)." chars long."); return undef }
198 sleep(1);
199  
200 # and send!
201 # on the same XML we search for the send button
202 $asel = '//node'
203 . '['
204 . ' matches(@class,\'FrameLayout$\',"i")'
205 . ' and @resource-id="com.viber.voip:id/btn_send"'
206 . ' and @package="com.viber.voip"'
207 . ']'
208 ;
209 @nodes = $xc->findnodes($asel);
210 $N = scalar @nodes;
211 if( $N == 0 ){ $log->error("${whoami} (via $parent), line ".__LINE__." : error, failed to find any nodes matching this XPath selector (for getting the recipient (".$params->{'recipient'}.") from the contacts on the central pane: ${asel}"); return undef }
212 elsif( $N > 1 ){ $log->error("--begin matched nodes:\n".join("\n", @nodes)."\n--end nodes matched.\n\n${whoami} (via $parent), line ".__LINE__." : error, matched more than one node (see above) with this XPath selector (for getting the recipient (".$params->{'recipient'}.") from the contacts on the central pane: ${asel}"); return undef }
213 $node = $nodes[0];
214 # click the Send button
215 $boundstr = $node->getAttribute('bounds');
216 if( ! defined $boundstr ){ $log->error("${node}\n\n${whoami} (via $parent), line ".__LINE__." : error, above node does not have attribute 'bounds'."); return undef }
217 if( $boundstr !~ /\[\s*(\d+)\s*,\s*(\d+)\]\s*\[\s*(\d+)\s*,\s*(\d+)\]/ ){ $log->error("${whoami} (via $parent), line ".__LINE__." : error, failed to parse bounds string: '$boundstr'."); return undef }
218 $bounds = [[$1,$2],[$3,$4]];
219 # I know it does not support sending unicode to a textbox but ...
220 # TODO: check with a unicode recipient handle to see if this works
221 if( $verbosity > 0 ){ $log->info("To: '".Encode::decode_utf8($recipient)."'\nMessage:\n".Encode::decode_utf8($message)."\n--end message.\n${whoami} (via $parent), line ".__LINE__." : about to send the above message ...") }
222 if( $mock == 0 ){
223 # click it if not mocking
224 if( $self->mother->tap({'bounds' => $bounds}) ){ $log->error("${whoami} (via $parent), line ".__LINE__." : error, failed to tap on $bounds."); return undef }
225 } else {
226 $log->warn("${whoami} (via $parent), line ".__LINE__." : The 'Send' button was not clicked because mock is ON.")
227 }
228 usleep(0.8);
229  
230 return {};
231 }
232  
233 # only pod below
234 =pod
235  
236 =encoding utf8
237  
238 =head1 NAME
239  
240 Android::ElectricSheep::Automator::Plugins::Apps::Viber - Control the Viber app from your desktop via the ElectricSheep Automator
241  
242 =head1 VERSION
243  
244 Version 0.09
245  
246 =head1 WARNING
247  
248 Current distribution is extremely alpha. API may change.
249  
250 =head1 SYNOPSIS
251  
252 An L<Android::ElectricSheep::Automator> plugin which
253 interacts with the Viber app from the desktop.
254  
255 use Android::ElectricSheep::Automator::Plugins::Apps::Viber;
256  
257 my $viber = Android::ElectricSheep::Automator::Plugins::Apps::Viber->new({
258 'configfile' => $configfile,
259 'verbosity' => 1,
260 # we already have a device connected and ready to control
261 'device-is-connected' => 1,
262 });
263  
264 # go to home screen to start fresh
265 $plugobj->mother->home_screen();
266  
267 # open the viber app
268 $plugobj->open_app() or die
269  
270 # is the app running now?
271 $plugobj->is_app_running() or die
272  
273 $plugobj->send_message({
274 'recipient' => 'My Notes', # some of your contacts
275 # 1) no unicode, 2) each space must be converted to '%s'
276 'message' => 'thank%syou'
277 }) or die;
278  
279 =head1 MOTIVATION
280  
281 I wanted to send viber messages from my beloved Linux Desktop
282 using the command line. I did not want to install Viber app on
283 my smartphone. I do not use a smartphone except for
284 reading the news.
285  
286 =head1 INSTALLING VIBER
287  
288 Firstly, I installed an Android emulator
289 in my desktop computer, as described here
290 L<https://metacpan.org/pod/Android::ElectricSheep::Automator#Android-Emulators>
291  
292 Note that some Android emulators do not allow access to
293 Google App Store (whatever is called). You can only install apps
294 via third party which is not very safe (even for your emulator).
295 See this for how to enable the App Store:
296  
297 L<https://stackoverflow.com/questions/71815181/how-can-i-get-google-play-to-work-on-android-emulator-in-android-studio-bumblebe>
298  
299 Fortunately, Viber offers a version of its app from its website,
300 calling it an "update". And you will not need to give any personal
301 details to Google to download it.
302  
303 It is located here
304 L<https://download.cdn.viber.com/android/android_32_64/viber-lst.apk>
305 (via L<https://www.viber.com/en/download-android-update>).
306  
307  
308 =head1 CONSTRUCTOR
309  
310 =head2 new($params)
311  
312 Creates a new C<Android::ElectricSheep::Automator::Plugins::Apps::Viber> object. C<$params>
313 is a hash reference used to pass initialization options. These options are
314 passed onto the main constructor.
315 Refer to the documentation of
316 L<Android::ElectricSheep::Automator#new($params)> for
317  
318 A configuration file or hash is required.
319  
320 Here is an example configuration file to get you started:
321  
322 </* $VERSION = '0.01'; */>
323 </* comments are allowed */>
324 </* and <% vars %> and <% verbatim sections %> */>
325 {
326 "Android::ElectricSheep::Automator" : {
327 "adb" : {
328 "path-to-executable" : "/usr/local/android-sdk/platform-tools/adb"
329 },
330 "debug" : {
331 "verbosity" : 0,
332 </* cleanup temp files on exit */>
333 "cleanup" : 1
334 },
335 "logger" : {
336 </* log to file if you uncomment this */>
337 </* "filename" : "..." */>
338 }
339 </* config for our plugins (each can go to separate file also) */>
340 },
341 "Android::ElectricSheep::Automator::Plugins::Apps::Viber" : {
342 }
343 }
344  
345 All sections are mandatory. Setting C<"adb"> to the wrong path will
346 yield in problems.
347  
348  
349 =head1 METHODS
350  
351  
352 =head2 send_message($params)
353  
354 It sends a message to one of your contacts.
355  
356 It returns C<undef> on failure or a hashref on success.
357  
358 C<$params> is a HASH_REF which may or should contain:
359  
360 =over 4
361  
362 =item B<C<recipient>>
363  
364 Required name of the recipient which must be in your contacts.
365 (Note, I am not sure if a recipient not in the contacts can
366 still be used).
367  
368 =item B<C<message>>
369  
370 Require, the message to send. At the moment B<the message can not be unicode>.
371 And it can not contain any space character unless it is encoded as C< %s >.
372  
373 =item B<C<mock>>
374  
375 Optionally, set this flag to C<1> in order to do everything except hitting
376 the send button. No message will be sent. For debugging purposes.
377  
378 =item B<C<outbase>>
379  
380 Optionally, specify the basename to form filenames for saving UI
381 dumps. For debugging purposes.
382  
383 =back
384  
385 It needs that L<Android::ElectricSheep::Automator#connect_device($params)> to have been called prior to this call.
386  
387 It returns C<undef> on failure or an (empty) hash on success.
388  
389 =head2 navigate_to_viber_home_activity($params)
390  
391 It navigates to the viber app's home screen. E.g.
392 if you are in your contacts screen, calling this method
393 will land you to the app's home screen.
394 It achieves this by continually pressing
395 the app's back-button (the left arrow at the top)
396 until it arrives at the home screen of the viber app.
397  
398 It returns C<1> on failure or a C<0> on success.
399  
400 C<$params> is a HASH_REF which may or should contain:
401  
402 =over 4
403  
404 =item B<C<outbase>>
405  
406 Optionally, specify the basename to form filenames for saving UI
407 dumps. For debugging purposes.
408  
409 =back
410  
411 It needs that connect_device() to have been called prior to this call.
412  
413 It returns C<1> on failure or C<0> on success.
414  
415  
416 =head1 AUTHOR
417  
418 Andreas Hadjiprocopis, C<< <bliako at cpan.org> >>
419  
420  
421 =head1 BUGS
422  
423 Please report any bugs or feature requests to C<bug-Android-ElectricSheep-Automator at rt.cpan.org>, or through
424 the web interface at
425 L<https://rt.cpan.org/NoAuth/ReportBug.html?Queue=Android-ElectricSheep-Automator>.
426 I will be notified, and then you'll
427 automatically be notified of progress on your bug as I make changes.
428  
429  
430 =head1 SUPPORT
431  
432 You can find documentation for this module with the perldoc command.
433  
434 perldoc Android::ElectricSheep::Automator::Plugins::Apps::Viber
435  
436  
437 You can also look for information at:
438  
439 =over 4
440  
441 =item * RT: CPAN's request tracker (report bugs here)
442  
443 L<https://rt.cpan.org/NoAuth/Bugs.html?Dist=Android-ElectricSheep-Automator>
444  
445 =item * AnnoCPAN: Annotated CPAN documentation
446  
447 L<http://annocpan.org/dist/Android-ElectricSheep-Automator>
448  
449 =item * Search CPAN
450  
451 L<https://metacpan.org/release/Android-ElectricSheep-Automator>
452  
453 =back
454  
455 =head1 SEE ALSO
456  
457 =over 4
458  
459 =item * L<Android::ADB> is a thin wrapper of the C<adb> command
460 created by Marius Gavrilescu, C<marius@ieval.ro>.
461 It is used by current module, albeit modified.
462  
463 =back
464  
465 =head1 HUGS
466  
467 =over 4
468  
469 =item * Πτηνού, my chicken, now laying in the big coop in the sky ...
470  
471 =back
472  
473  
474 =head1 LICENSE AND COPYRIGHT
475  
476 This software is Copyright (c) 2025 by Andreas Hadjiprocopis.
477  
478 This is free software, licensed under:
479  
480 The Artistic License 2.0 (GPL Compatible)
481  
482  
483 =cut
484  
485 1; # End of Android::ElectricSheep::Automator::Plugins::Apps::Viber
486  
487  
488 1;
« lib/Android/ElectricSheep/Automator.pm ↑ Summary