ee06ff6d7fe2c5f57a610b4d9d103323a42d7e12
[twirssi-net-twitter-lite.git] / twirssi.pl
1 use strict;
2 use Irssi;
3 use Irssi::Irc;
4 use HTTP::Date;
5 use HTML::Entities;
6 use File::Temp;
7 use LWP::Simple;
8 use Data::Dumper;
9 use Encode;
10 $Data::Dumper::Indent = 1;
11
12 use vars qw($VERSION %IRSSI);
13
14 $VERSION = "2.3.4beta";
15 %IRSSI   = (
16     authors     => 'Dan Boger',
17     contact     => 'zigdon@gmail.com',
18     name        => 'twirssi',
19     description => 'Send twitter updates using /tweet.  '
20       . 'Can optionally set your bitlbee /away message to same',
21     license => 'GNU GPL v2',
22     url     => 'http://twirssi.com',
23     changed => '$Date: 2009-08-07 01:24:53 -0700 (Fri, 07 Aug 2009) $',
24 );
25
26 my $window;
27 my $twit;
28 my %twits;
29 my $user;
30 my $defservice;
31 my $poll;
32 my $last_poll;
33 my $last_friends_poll = 0;
34 my %nicks;
35 my %friends;
36 my %tweet_cache;
37 my %id_map;
38 my $failwhale  = 0;
39 my $first_call = 1;
40 my $child_pid;
41 my %fix_replies_index;
42
43 my %irssi_to_mirc_colors = (
44     '%k' => '01',
45     '%r' => '05',
46     '%g' => '03',
47     '%y' => '07',
48     '%b' => '02',
49     '%m' => '06',
50     '%c' => '10',
51     '%w' => '15',
52     '%K' => '14',
53     '%R' => '04',
54     '%G' => '09',
55     '%Y' => '08',
56     '%B' => '12',
57     '%M' => '13',
58     '%C' => '11',
59     '%W' => '00',
60 );
61
62 sub cmd_direct {
63     my ( $data, $server, $win ) = @_;
64
65     return unless &logged_in($twit);
66
67     my ( $target, $text ) = split ' ', $data, 2;
68     unless ( $target and $text ) {
69         &notice("Usage: /dm <nick> <message>");
70         return;
71     }
72
73     &cmd_direct_as( "$user $data", $server, $win );
74 }
75
76 sub cmd_direct_as {
77     my ( $data, $server, $win ) = @_;
78
79     return unless &logged_in($twit);
80
81     my ( $username, $target, $text ) = split ' ', $data, 3;
82     unless ( $username and $target and $text ) {
83         &notice("Usage: /dm_as <username> <nick> <message>");
84         return;
85     }
86
87     return unless $username = &valid_username($username);
88
89     eval {
90         if ( $twits{$username}
91             ->new_direct_message( { user => $target, text => $text } ) )
92         {
93             &notice("DM sent to $target: $text");
94             $nicks{$target} = time;
95         } else {
96             my $error;
97             eval {
98                 $error = JSON::Any->jsonToObj( $twits{$username}->get_error() );
99                 $error = $error->{error};
100             };
101             die $error if $error;
102             &notice("DM to $target failed");
103         }
104     };
105
106     if ($@) {
107         &notice("DM caused an error: $@");
108         return;
109     }
110 }
111
112 sub cmd_retweet {
113     my ( $data, $server, $win ) = @_;
114
115     return unless &logged_in($twit);
116
117     $data =~ s/^\s+|\s+$//;
118     unless ($data) {
119         &notice("Usage: /retweet <nick[:num]> [comment]");
120         return;
121     }
122
123     my ( $id, $data ) = split ' ', $data, 2;
124
125     &cmd_retweet_as( "$user $id $data", $server, $win );
126 }
127
128 sub cmd_retweet_as {
129     my ( $data, $server, $win ) = @_;
130
131     unless ( Irssi::settings_get_bool("twirssi_track_replies") ) {
132         &notice("twirssi_track_replies is required in order to reteet.");
133         return;
134     }
135
136     return unless &logged_in($twit);
137
138     $data =~ s/^\s+|\s+$//;
139     my ( $username, $id, $data ) = split ' ', $data, 3;
140
141     unless ($username) {
142         &notice("Usage: /retweet_as <username> <nick[:num]> [comment]");
143         return;
144     }
145
146     return unless $username = &valid_username($username);
147
148     my $nick;
149     $id =~ s/[^\w\d\-:]+//g;
150     ( $nick, $id ) = split /:/, $id;
151     unless ( exists $id_map{ lc $nick } ) {
152         &notice("Can't find a tweet from $nick to retweet!");
153         return;
154     }
155
156     $id = $id_map{__indexes}{$nick} unless $id;
157     unless ( $id_map{ lc $nick }[$id] ) {
158         &notice("Can't find a tweet numbered $id from $nick to retweet!");
159         return;
160     }
161
162     unless ( $id_map{__tweets}{ lc $nick }[$id] ) {
163         &notice("The text of this tweet isn't saved, sorry!");
164         return;
165     }
166
167 # Irssi::settings_add_str( "twirssi", "twirssi_retweet_format", 'RT $n: $t ${-- $c$}' );
168     my $text = Irssi::settings_get_str("twirssi_retweet_format");
169     $text =~ s/\$n/\@$nick/g;
170     if ($data) {
171         $text =~ s/\${|\$}//g;
172         $text =~ s/\$c/$data/;
173     } else {
174         $text =~ s/\${.*?\$}//;
175     }
176     $text =~ s/\$t/$id_map{__tweets}{ lc $nick }[$id]/;
177
178     my $modified = $data;
179     $data = &shorten($text);
180
181     return if $modified and &too_long($data);
182
183     my $success = 1;
184     eval {
185         if ($modified)
186         {
187             $success = $twits{$username}->update(
188                 {
189                     status => $data,
190
191                     # in_reply_to_status_id => $id_map{ lc $nick }[$id]
192                 }
193             );
194         } else {
195             $success =
196               $twits{$username}->retweet( { id => $id_map{ lc $nick }[$id] } );
197             $success = $success->{id} if ref $success;
198         }
199         &notice("Update failed") unless $success;
200     };
201     return unless $success;
202
203     if ($@) {
204         &notice("Update caused an error: $@.  Aborted");
205         return;
206     }
207
208     foreach ( $data =~ /@([-\w]+)/ ) {
209         $nicks{$1} = time;
210     }
211
212     &notice("Retweet sent");
213 }
214
215 sub cmd_tweet {
216     my ( $data, $server, $win ) = @_;
217
218     return unless &logged_in($twit);
219
220     $data =~ s/^\s+|\s+$//;
221     unless ($data) {
222         &notice("Usage: /tweet <update>");
223         return;
224     }
225
226     &cmd_tweet_as( "$user\@$defservice $data", $server, $win );
227 }
228
229 sub cmd_tweet_as {
230     my ( $data, $server, $win ) = @_;
231
232     return unless &logged_in($twit);
233
234     $data =~ s/^\s+|\s+$//;
235     $data =~ s/\s\s+/ /g;
236     my ( $username, $data ) = split ' ', $data, 2;
237
238     unless ( $username and $data ) {
239         &notice("Usage: /tweet_as <username> <update>");
240         return;
241     }
242
243     return unless $username = &valid_username($username);
244
245     $data = &shorten($data);
246
247     return if &too_long($data);
248
249     my $success = 1;
250     eval {
251         unless ( $twits{$username}->update($data) )
252         {
253             &notice("Update failed");
254             $success = 0;
255         }
256     };
257     return unless $success;
258
259     if ($@) {
260         &notice("Update caused an error: $@.  Aborted.");
261         return;
262     }
263
264     foreach ( $data =~ /@([-\w]+)/ ) {
265         $nicks{$1} = time;
266     }
267
268     my $away = &update_away($data);
269
270     &notice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
271 }
272
273 sub cmd_reply {
274     my ( $data, $server, $win ) = @_;
275
276     return unless &logged_in($twit);
277
278     $data =~ s/^\s+|\s+$//;
279     unless ($data) {
280         &notice("Usage: /reply <nick[:num]> <update>");
281         return;
282     }
283
284     my ( $id, $data ) = split ' ', $data, 2;
285     unless ( $id and $data ) {
286         &notice("Usage: /reply <nick[:num]> <update>");
287         return;
288     }
289
290     &cmd_reply_as( "$user $id $data", $server, $win );
291 }
292
293 sub cmd_reply_as {
294     my ( $data, $server, $win ) = @_;
295
296     unless ( Irssi::settings_get_bool("twirssi_track_replies") ) {
297         &notice("twirssi_track_replies is required in order to reply to "
298               . "specific tweets.  Either enable it, or just use /tweet "
299               . "\@username <text>." );
300         return;
301     }
302
303     return unless &logged_in($twit);
304
305     $data =~ s/^\s+|\s+$//;
306     my ( $username, $id, $data ) = split ' ', $data, 3;
307
308     unless ( $username and $data ) {
309         &notice("Usage: /reply_as <username> <nick[:num]> <update>");
310         return;
311     }
312
313     return unless $username = &valid_username($username);
314
315     my $nick;
316     $id =~ s/[^\w\d\-:]+//g;
317     ( $nick, $id ) = split /:/, $id;
318     unless ( exists $id_map{ lc $nick } ) {
319         &notice("Can't find a tweet from $nick to reply to!");
320         return;
321     }
322
323     $id = $id_map{__indexes}{$nick} unless $id;
324     unless ( $id_map{ lc $nick }[$id] ) {
325         &notice("Can't find a tweet numbered $id from $nick to reply to!");
326         return;
327     }
328
329     if ( Irssi::settings_get_bool("twirssi_replies_autonick") ) {
330
331         # remove any @nick at the beginning of the reply, as we'll add it anyway
332         $data =~ s/^\s*\@?$nick\s*//;
333         $data = "\@$nick " . $data;
334     }
335
336     $data = &shorten($data);
337
338     return if &too_long($data);
339
340     my $success = 1;
341     eval {
342         unless (
343             $twits{$username}->update(
344                 {
345                     status                => $data,
346                     in_reply_to_status_id => $id_map{ lc $nick }[$id]
347                 }
348             )
349           )
350         {
351             &notice("Update failed");
352             $success = 0;
353         }
354     };
355     return unless $success;
356
357     if ($@) {
358         &notice("Update caused an error: $@.  Aborted");
359         return;
360     }
361
362     foreach ( $data =~ /@([-\w]+)/ ) {
363         $nicks{$1} = time;
364     }
365
366     my $away = &update_away($data);
367
368     &notice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
369 }
370
371 sub gen_cmd {
372     my ( $usage_str, $api_name, $post_ref ) = @_;
373
374     return sub {
375         my ( $data, $server, $win ) = @_;
376
377         return unless &logged_in($twit);
378
379         $data =~ s/^\s+|\s+$//;
380         unless ($data) {
381             &notice("Usage: $usage_str");
382             return;
383         }
384
385         my $success = 1;
386         eval {
387             unless ( $twit->$api_name($data) )
388             {
389                 &notice("$api_name failed");
390                 $success = 0;
391             }
392         };
393         return unless $success;
394
395         if ($@) {
396             &notice("$api_name caused an error.  Aborted.");
397             return;
398         }
399
400         &$post_ref($data) if $post_ref;
401       }
402 }
403
404 sub cmd_switch {
405     my ( $data, $server, $win ) = @_;
406
407     $data =~ s/^\s+|\s+$//g;
408     $data = &normalize_username($data);
409     if ( exists $twits{$data} ) {
410         &notice("Switching to $data");
411         $twit = $twits{$data};
412         if ( $data =~ /(.*)\@(.*)/ ) {
413             $user       = $1;
414             $defservice = $2;
415         } else {
416             &notice("Couldn't figure out what service '$data' is on");
417         }
418     } else {
419         &notice("Unknown user $data");
420     }
421 }
422
423 sub cmd_logout {
424     my ( $data, $server, $win ) = @_;
425
426     $data =~ s/^\s+|\s+$//g;
427     $data = $user unless $data;
428     return unless $data = &valid_username($data);
429
430     &notice("Logging out $data...");
431     $twits{$data}->end_session();
432     delete $twits{$data};
433     undef $twit;
434     if ( keys %twits ) {
435         &cmd_switch( ( keys %twits )[0], $server, $win );
436     } else {
437         Irssi::timeout_remove($poll) if $poll;
438         undef $poll;
439     }
440 }
441
442 sub cmd_login {
443     my ( $data, $server, $win ) = @_;
444     my $pass;
445     if ($data) {
446         ( $user, $pass ) = split ' ', $data, 2;
447         unless ($pass) {
448             &notice("usage: /twitter_login <username>[\@<service>] <password>");
449             return;
450         }
451     } elsif ( my $autouser = Irssi::settings_get_str("twitter_usernames")
452         and my $autopass = Irssi::settings_get_str("twitter_passwords") )
453     {
454         my @user = split /\s*,\s*/, $autouser;
455         my @pass = split /\s*,\s*/, $autopass;
456
457         # if a password ends with a '\', it was meant to escape the comma, and
458         # it should be concatinated with the next one
459         my @unescaped;
460         while (@pass) {
461             my $p = shift @pass;
462             while ( $p =~ /\\$/ and @pass ) {
463                 $p .= "," . shift @pass;
464             }
465             push @unescaped, $p;
466         }
467
468         if ( @user != @unescaped ) {
469             &notice("Number of usernames doesn't match "
470                   . "the number of passwords - auto-login failed" );
471         } else {
472             my ( $u, $p );
473             while ( @user and @unescaped ) {
474                 $u = shift @user;
475                 $p = shift @unescaped;
476                 &cmd_login("$u $p");
477             }
478             return;
479         }
480     } else {
481         &notice("/twitter_login requires either a username and password "
482               . "or twitter_usernames and twitter_passwords to be set." );
483         return;
484     }
485
486     %friends = %nicks = ();
487
488     my $service;
489     if ( $user =~ /^(.*)@(twitter|identica)$/ ) {
490         ( $user, $service ) = ( $1, $2 );
491     } else {
492         $service = Irssi::settings_get_str("twirssi_default_service");
493     }
494     $defservice = $service = ucfirst lc $service;
495
496     eval "use Net::$service 3.05";
497     if ($@) {
498         &notice(
499             "Failed to load Net::$service when trying to log in as $user: $@");
500         return;
501     }
502
503     $twit = "Net::$service"->new(
504         username => $user,
505         password => $pass,
506         source   => "twirssi",
507         ssl      => Irssi::settings_get_bool("twirssi_avoid_ssl") ? 0 : 1,
508     );
509
510     unless ($twit) {
511         &notice("Failed to create Net::$service object!  Aborting.");
512         return;
513     }
514
515     if ( my $timeout = Irssi::settings_get_int("twitter_timeout")
516         and $twit->can('ua') )
517     {
518         $twit->ua->timeout($timeout);
519         &notice("Twitter timeout set to $timeout");
520     }
521
522     unless ( $twit->verify_credentials() ) {
523         &notice("Login as $user\@$service failed");
524
525         if ( not Irssi::settings_get_bool("twirssi_avoid_ssl") ) {
526             &notice(
527                 "It's possible you're missing one of the modules required for "
528                   . "SSL logins.  Try setting twirssi_avoid_ssl to on.  See "
529                   . "http://cpansearch.perl.org/src/GAAS/libwww-perl-5.831/README.SSL "
530                   . "for the detailed requirements." );
531         }
532
533         $twit = undef;
534         if ( keys %twits ) {
535             &cmd_switch( ( keys %twits )[0], $server, $win );
536         }
537         return;
538     }
539
540     if ($twit) {
541         my $rate_limit = $twit->rate_limit_status();
542         if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
543             &notice(
544                 "Rate limit exceeded, try again after $rate_limit->{reset_time}"
545             );
546             $twit = undef;
547             return;
548         }
549
550         $twits{"$user\@$service"} = $twit;
551         Irssi::timeout_remove($poll) if $poll;
552         $poll = Irssi::timeout_add( &get_poll_time * 1000, \&get_updates, "" );
553         &notice("Logged in as $user\@$service, loading friends list...");
554         &load_friends();
555         &notice( "loaded friends: ", scalar keys %friends );
556         if ( Irssi::settings_get_bool("twirssi_first_run") ) {
557             Irssi::settings_set_bool( "twirssi_first_run", 0 );
558         }
559         %nicks = %friends;
560         $nicks{$user} = 0;
561         return 1;
562     } else {
563         &notice("Login failed");
564     }
565 }
566
567 sub cmd_add_follow {
568     my ( $data, $server, $win ) = @_;
569
570     unless ($data) {
571         &notice("Usage: /twitter_add_follow_extra <username>");
572         return;
573     }
574
575     $data =~ s/^\s+|\s+$//;
576     $data =~ s/^\@//;
577     $data = lc $data;
578
579     if ( exists $id_map{__fixreplies}{"$user\@$defservice"}{$data} ) {
580         &notice("Already following all replies by \@$data");
581         return;
582     }
583
584     $id_map{__fixreplies}{"$user\@$defservice"}{$data} = 1;
585     &notice("Will now follow all replies by \@$data");
586 }
587
588 sub cmd_del_follow {
589     my ( $data, $server, $win ) = @_;
590
591     unless ($data) {
592         &notice("Usage: /twitter_del_follow_extra <username>");
593         return;
594     }
595
596     $data =~ s/^\s+|\s+$//;
597     $data =~ s/^\@//;
598     $data = lc $data;
599
600     unless ( exists $id_map{__fixreplies}{"$user\@$defservice"}{$data} ) {
601         &notice("Wasn't following all replies by \@$data");
602         return;
603     }
604
605     delete $id_map{__fixreplies}{"$user\@$defservice"}{$data};
606     &notice("Will no longer follow all replies by \@$data");
607 }
608
609 sub cmd_list_follow {
610     my ( $data, $server, $win ) = @_;
611
612     my $found = 0;
613     foreach my $suser ( sort keys %{ $id_map{__fixreplies} } ) {
614         my $frusers;
615         foreach my $fruser ( sort keys %{ $id_map{__fixreplies}{$suser} } ) {
616             $frusers = $frusers ? "$frusers, $fruser" : $fruser;
617         }
618         if ($frusers) {
619             $found = 1;
620             &notice("Following all replies as \@$suser: $frusers");
621         }
622     }
623
624     unless ($found) {
625         &notice("Not following all replies by anyone");
626     }
627 }
628
629 sub cmd_add_search {
630     my ( $data, $server, $win ) = @_;
631
632     unless ( $twit and $twit->can('search') ) {
633         &notice("ERROR: Your version of Net::Twitter ($Net::Twitter::VERSION) "
634               . "doesn't support searches." );
635         return;
636     }
637
638     $data =~ s/^\s+|\s+$//;
639     $data = lc $data;
640
641     unless ($data) {
642         &notice("Usage: /twitter_subscribe <topic>");
643         return;
644     }
645
646     if ( exists $id_map{__searches}{"$user\@$defservice"}{$data} ) {
647         &notice("Already had a subscription for '$data'");
648         return;
649     }
650
651     $id_map{__searches}{"$user\@$defservice"}{$data} = 1;
652     &notice("Added subscription for '$data'");
653 }
654
655 sub cmd_del_search {
656     my ( $data, $server, $win ) = @_;
657
658     unless ( $twit and $twit->can('search') ) {
659         &notice("ERROR: Your version of Net::Twitter ($Net::Twitter::VERSION) "
660               . "doesn't support searches." );
661         return;
662     }
663     $data =~ s/^\s+|\s+$//;
664     $data = lc $data;
665
666     unless ($data) {
667         &notice("Usage: /twitter_unsubscribe <topic>");
668         return;
669     }
670
671     unless ( exists $id_map{__searches}{"$user\@$defservice"}{$data} ) {
672         &notice("No subscription found for '$data'");
673         return;
674     }
675
676     delete $id_map{__searches}{"$user\@$defservice"}{$data};
677     &notice("Removed subscription for '$data'");
678 }
679
680 sub cmd_list_search {
681     my ( $data, $server, $win ) = @_;
682
683     my $found = 0;
684     foreach my $suser ( sort keys %{ $id_map{__searches} } ) {
685         my $topics;
686         foreach my $topic ( sort keys %{ $id_map{__searches}{$suser} } ) {
687             $topics = $topics ? "$topics, $topic" : $topic;
688         }
689         if ($topics) {
690             $found = 1;
691             &notice("Search subscriptions for \@$suser: $topics");
692         }
693     }
694
695     unless ($found) {
696         &notice("No search subscriptions set up");
697     }
698 }
699
700 sub cmd_upgrade {
701     my ( $data, $server, $win ) = @_;
702
703     my $loc = Irssi::settings_get_str("twirssi_location");
704     unless ( -w $loc ) {
705         &notice("$loc isn't writable, can't upgrade."
706               . "  Perhaps you need to /set twirssi_location?" );
707         return;
708     }
709
710     my $md5;
711     unless ( $data or Irssi::settings_get_bool("twirssi_upgrade_beta") ) {
712         eval { use Digest::MD5; };
713
714         if ($@) {
715             &notice("Failed to load Digest::MD5."
716                   . "  Try '/twirssi_upgrade nomd5' to skip MD5 verification" );
717             return;
718         }
719
720         $md5 = get("http://twirssi.com/md5sum");
721         chomp $md5;
722         $md5 =~ s/ .*//;
723         unless ($md5) {
724             &notice("Failed to download md5sum from peeron!  Aborting.");
725             return;
726         }
727
728         unless ( open( CUR, $loc ) ) {
729             &notice("Failed to read $loc."
730                   . "  Check that /set twirssi_location is set to the correct location."
731             );
732             return;
733         }
734
735         my $cur_md5 = Digest::MD5::md5_hex(<CUR>);
736         close CUR;
737
738         if ( $cur_md5 eq $md5 ) {
739             &notice("Current twirssi seems to be up to date.");
740             return;
741         }
742     }
743
744     my $URL =
745       Irssi::settings_get_bool("twirssi_upgrade_beta")
746       ? "http://github.com/zigdon/twirssi/raw/master/twirssi.pl"
747       : "http://twirssi.com/twirssi.pl";
748     &notice("Downloading twirssi from $URL");
749     LWP::Simple::getstore( $URL, "$loc.upgrade" );
750
751     unless ( -s "$loc.upgrade" ) {
752         &notice("Failed to save $loc.upgrade."
753               . "  Check that /set twirssi_location is set to the correct location."
754         );
755         return;
756     }
757
758     unless ( $data or Irssi::settings_get_bool("twirssi_upgrade_beta") ) {
759         unless ( open( NEW, "$loc.upgrade" ) ) {
760             &notice("Failed to read $loc.upgrade."
761                   . "  Check that /set twirssi_location is set to the correct location."
762             );
763             return;
764         }
765
766         my $new_md5 = Digest::MD5::md5_hex(<NEW>);
767         close NEW;
768
769         if ( $new_md5 ne $md5 ) {
770             &notice("MD5 verification failed. expected $md5, got $new_md5");
771             return;
772         }
773     }
774
775     rename $loc, "$loc.backup"
776       or &notice("Failed to back up $loc: $!.  Aborting")
777       and return;
778     rename "$loc.upgrade", $loc
779       or &notice("Failed to rename $loc.upgrade: $!.  Aborting")
780       and return;
781
782     my ( $dir, $file ) = ( $loc =~ m{(.*)/([^/]+)$} );
783     if ( -e "$dir/autorun/$file" ) {
784         &notice("Updating $dir/autorun/$file");
785         unlink "$dir/autorun/$file"
786           or &notice("Failed to remove old $file from autorun: $!");
787         symlink "../$file", "$dir/autorun/$file"
788           or &notice("Failed to create symlink in autorun directory: $!");
789     }
790
791     &notice("Download complete.  Reload twirssi with /script load $file");
792 }
793
794 sub load_friends {
795     my $fh     = shift;
796     my $cursor = -1;
797     my $page   = 1;
798     my %new_friends;
799     eval {
800         while ( $page < 11 and $cursor ne "0" )
801         {
802             print $fh "type:debug Loading friends page $page...\n"
803               if ( $fh and &debug );
804             my $friends;
805             if ( ref $twit =~ /^Net::Twitter/ ) {
806                 $friends = $twit->friends( { cursor => $cursor } );
807                 last unless $friends;
808                 $cursor  = $friends->{next_cursor};
809                 $friends = $friends->{users};
810             } else {
811                 $friends = $twit->friends( { page => $page } );
812                 last unless $friends;
813             }
814             $new_friends{ $_->{screen_name} } = time foreach @$friends;
815             $page++;
816         }
817     };
818
819     if ($@) {
820         print $fh "type:debug Error during friends list update.  Aborted.\n";
821         return;
822     }
823
824     my ( $added, $removed ) = ( 0, 0 );
825     print $fh "type:debug Scanning for new friends...\n" if ( $fh and &debug );
826     foreach ( keys %new_friends ) {
827         next if exists $friends{$_};
828         $friends{$_} = time;
829         $added++;
830     }
831
832     print $fh "type:debug Scanning for removed friends...\n"
833       if ( $fh and &debug );
834     foreach ( keys %friends ) {
835         next if exists $new_friends{$_};
836         delete $friends{$_};
837         $removed++;
838     }
839
840     return ( $added, $removed );
841 }
842
843 sub get_updates {
844     print scalar localtime, " - get_updates starting" if &debug;
845
846     $window =
847       Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
848     unless ($window) {
849         Irssi::active_win()
850           ->print( "Can't find a window named '"
851               . Irssi::settings_get_str('twitter_window')
852               . "'.  Create it or change the value of twitter_window" );
853     }
854
855     return unless &logged_in($twit);
856
857     my ( $fh, $filename ) = File::Temp::tempfile();
858     binmode( $fh, ":utf8" );
859     $child_pid = fork();
860
861     if ($child_pid) {    # parent
862         Irssi::timeout_add_once( 5000, 'monitor_child',
863             [ "$filename.done", 0 ] );
864         Irssi::pidwait_add($child_pid);
865     } elsif ( defined $child_pid ) {    # child
866         close STDIN;
867         close STDOUT;
868         close STDERR;
869
870         my $new_poll = time;
871
872         my $error = 0;
873         my %context_cache;
874         foreach ( keys %twits ) {
875             $error++ unless &do_updates( $fh, $_, $twits{$_}, \%context_cache );
876
877             if ( $id_map{__fixreplies}{$_} ) {
878                 my @frusers = sort keys %{ $id_map{__fixreplies}{$_} };
879
880                 $error++
881                   unless &get_timeline( $fh, $frusers[ $fix_replies_index{$_} ],
882                     $_, $twits{$_}, \%context_cache );
883
884                 $fix_replies_index{$_}++;
885                 $fix_replies_index{$_} = 0
886                   if $fix_replies_index{$_} >= @frusers;
887                 print $fh "id:$fix_replies_index{$_} ",
888                   "account:$_ type:fix_replies_index\n";
889             }
890         }
891
892         print $fh "__friends__\n";
893         if (
894             time - $last_friends_poll >
895             Irssi::settings_get_int('twitter_friends_poll') )
896         {
897             print $fh "__updated ", time, "\n";
898             my ( $added, $removed ) = &load_friends($fh);
899             if ( $added + $removed ) {
900                 print $fh "type:debug %R***%n Friends list updated: ",
901                   join( ", ",
902                     sprintf( "%d added",   $added ),
903                     sprintf( "%d removed", $removed ) ),
904                   "\n";
905             }
906         }
907
908         foreach ( sort keys %friends ) {
909             print $fh "$_ $friends{$_}\n";
910         }
911
912         if ($error) {
913             print $fh "type:debug Update encountered errors.  Aborted\n";
914             print $fh "-- $last_poll";
915         } else {
916             print $fh "-- $new_poll";
917         }
918         close $fh;
919         rename $filename, "$filename.done";
920         exit;
921     } else {
922         &ccrap("Failed to fork for updating: $!");
923     }
924     print scalar localtime, " - get_updates ends" if &debug;
925 }
926
927 sub do_updates {
928     my ( $fh, $username, $obj, $cache ) = @_;
929
930     my $rate_limit = $obj->rate_limit_status();
931     if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
932         &notice("Rate limit exceeded for $username");
933         return undef;
934     }
935
936     print scalar localtime, " - Polling for updates for $username" if &debug;
937     my $tweets;
938     my $new_poll_id = 0;
939     eval {
940         if ( $id_map{__last_id}{$username}{timeline} )
941         {
942             $tweets = $obj->home_timeline( { count => 100 } );
943         } else {
944             $tweets = $obj->home_timeline();
945         }
946     };
947
948     if ($@) {
949         print $fh "type:debug Error during home_timeline call: Aborted.\n";
950         print $fh "type:debug : $_\n" foreach split /\n/, Dumper($@);
951         return undef;
952     }
953
954     unless ( ref $tweets ) {
955         if ( $obj->can("get_error") ) {
956             my $error = "Unknown error";
957             eval { $error = JSON::Any->jsonToObj( $obj->get_error() ) };
958             unless ($@) { $error = $obj->get_error() }
959             print $fh
960               "type:debug API Error during home_timeline call: Aborted\n";
961             print $fh "type:debug : $_\n" foreach split /\n/, Dumper($error);
962
963         } else {
964             print $fh
965               "type:debug API Error during home_timeline call. Aborted.\n";
966         }
967         return undef;
968     }
969
970     foreach my $t ( reverse @$tweets ) {
971         my $text =
972           decode_entities( $t->{retweeted_status}{text} || $t->{text} );
973         $text =~ s/[\n\r]/ /g;
974         my $reply = "tweet";
975         if (    Irssi::settings_get_bool("show_reply_context")
976             and $t->{in_reply_to_screen_name} ne $username
977             and $t->{in_reply_to_screen_name}
978             and not exists $friends{ $t->{in_reply_to_screen_name} } )
979         {
980             $nicks{ $t->{in_reply_to_screen_name} } = time;
981             my $context;
982             unless ( $cache->{ $t->{in_reply_to_status_id} } ) {
983                 eval {
984                     $cache->{ $t->{in_reply_to_status_id} } =
985                       $obj->show_status( $t->{in_reply_to_status_id} );
986                 };
987
988             }
989             $context = $cache->{ $t->{in_reply_to_status_id} };
990
991             if ($context) {
992                 my $ctext =
993                   decode_entities( $context->{retweeted_status}{text}
994                       || $context->{text} );
995                 $ctext =~ s/[\n\r]/ /g;
996                 if ( $context->{truncated} and ref($obj) ne 'Net::Identica' ) {
997                     $ctext .=
998                         " -- http://twitter.com/$context->{user}{screen_name}"
999                       . "/status/$context->{id}";
1000                 }
1001                 printf $fh "id:%s account:%s nick:%s type:tweet %s\n",
1002                   $context->{id}, $username,
1003                   $context->{user}{screen_name}, $ctext;
1004                 $reply = "reply";
1005             }
1006         }
1007         next
1008           if $t->{user}{screen_name} eq $username
1009               and not Irssi::settings_get_bool("show_own_tweets");
1010         if ( $t->{truncated} and ref($obj) ne 'Net::Identica' ) {
1011             $text .= " -- http://twitter.com/$t->{user}{screen_name}"
1012               . "/status/$t->{id}";
1013         }
1014         printf $fh "id:%s account:%s nick:%s type:%s %s\n",
1015           $t->{id}, $username, $t->{user}{screen_name}, $reply, $text;
1016         $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
1017     }
1018     printf $fh "id:%s account:%s type:last_id timeline\n",
1019       $new_poll_id, $username;
1020
1021     print scalar localtime, " - Polling for replies since ",
1022       $id_map{__last_id}{$username}{reply}
1023       if &debug;
1024     $new_poll_id = 0;
1025     eval {
1026         if ( $id_map{__last_id}{$username}{reply} )
1027         {
1028             $tweets = $obj->replies(
1029                 { since_id => $id_map{__last_id}{$username}{reply} } )
1030               || [];
1031         } else {
1032             $tweets = $obj->replies() || [];
1033         }
1034     };
1035
1036     if ($@) {
1037         print $fh "type:debug Error during replies call.  Aborted.\n";
1038         return undef;
1039     }
1040
1041     foreach my $t ( reverse @$tweets ) {
1042         next
1043           if exists $friends{ $t->{user}{screen_name} };
1044
1045         my $text =
1046           decode_entities( $t->{retweeted_status}{text} || $t->{text} );
1047         $text =~ s/[\n\r]/ /g;
1048         if ( $t->{truncated} ) {
1049             $text .= " -- http://twitter.com/$t->{user}{screen_name}"
1050               . "/status/$t->{id}";
1051         }
1052         printf $fh "id:%s account:%s nick:%s type:tweet %s\n",
1053           $t->{id}, $username, $t->{user}{screen_name}, $text;
1054         $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
1055     }
1056     printf $fh "id:%s account:%s type:last_id reply\n", $new_poll_id, $username;
1057
1058     print scalar localtime, " - Polling for DMs" if &debug;
1059     $new_poll_id = 0;
1060     eval {
1061         if ( $id_map{__last_id}{$username}{dm} )
1062         {
1063             $tweets = $obj->direct_messages(
1064                 { since_id => $id_map{__last_id}{$username}{dm} } )
1065               || [];
1066         } else {
1067             $tweets = $obj->direct_messages() || [];
1068         }
1069     };
1070
1071     if ($@) {
1072         print $fh "type:debug Error during direct_messages call.  Aborted.\n";
1073         return undef;
1074     }
1075
1076     foreach my $t ( reverse @$tweets ) {
1077         my $text = decode_entities( $t->{text} );
1078         $text =~ s/[\n\r]/ /g;
1079         printf $fh "id:%s account:%s nick:%s type:dm %s\n",
1080           $t->{id}, $username, $t->{sender_screen_name}, $text;
1081         $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
1082     }
1083     printf $fh "id:%s account:%s type:last_id dm\n", $new_poll_id, $username;
1084
1085     print scalar localtime, " - Polling for subscriptions" if &debug;
1086     if ( $obj->can('search') and $id_map{__searches}{$username} ) {
1087         my $search;
1088         foreach my $topic ( sort keys %{ $id_map{__searches}{$username} } ) {
1089             print $fh "type:debug searching for $topic since ",
1090               "$id_map{__searches}{$username}{$topic}\n";
1091             eval {
1092                 $search = $obj->search(
1093                     {
1094                         q        => $topic,
1095                         since_id => $id_map{__searches}{$username}{$topic}
1096                     }
1097                 );
1098             };
1099
1100             if ($@) {
1101                 print $fh
1102                   "type:debug Error during search($topic) call.  Aborted.\n";
1103                 return undef;
1104             }
1105
1106             unless ( $search->{max_id} ) {
1107                 print $fh "type:debug Invalid search results when searching",
1108                   " for $topic. Aborted.\n";
1109                 return undef;
1110             }
1111
1112             $id_map{__searches}{$username}{$topic} = $search->{max_id};
1113             printf $fh "id:%s account:%s type:searchid topic:%s\n",
1114               $search->{max_id}, $username, $topic;
1115
1116             foreach my $t ( reverse @{ $search->{results} } ) {
1117                 my $text =
1118                   decode_entities( $t->{retweeted_status}{text} || $t->{text} );
1119                 $text =~ s/[\n\r]/ /g;
1120                 printf $fh "id:%s account:%s nick:%s type:search topic:%s %s\n",
1121                   $t->{id}, $username, $t->{from_user}, $topic, $text;
1122                 $new_poll_id = $t->{id}
1123                   if not $new_poll_id
1124                       or $t->{id} < $new_poll_id;
1125             }
1126         }
1127     }
1128
1129     print scalar localtime, " - Done" if &debug;
1130
1131     return 1;
1132 }
1133
1134 sub get_timeline {
1135     my ( $fh, $target, $username, $obj, $cache ) = @_;
1136     my $tweets;
1137     my $last_id = $id_map{__last_id}{$username}{$target};
1138
1139     print $fh "type:debug get_timeline("
1140       . "$fix_replies_index{$username}=$target > $last_id) started."
1141       . "  username = $username\n";
1142     eval {
1143         $tweets = $obj->user_timeline(
1144             {
1145                 id => $target,
1146                 ( $last_id ? ( since_id => $last_id ) : () ),
1147             }
1148         );
1149     };
1150
1151     if ($@) {
1152         print $fh
1153           "type:debug Error during user_timeline($target) call: Aborted.\n";
1154         print $fh "type:debug : $_\n" foreach split /\n/, Dumper($@);
1155         return undef;
1156     }
1157
1158     unless ($tweets) {
1159         print $fh
1160           "type:debug user_timeline($target) call returned undef!  Aborted\n";
1161         return 1;
1162     }
1163
1164     foreach my $t ( reverse @$tweets ) {
1165         my $text =
1166           decode_entities( $t->{retweeted_status}{text} || $t->{text} );
1167         $text =~ s/[\n\r]/ /g;
1168         my $reply = "tweet";
1169         if (    Irssi::settings_get_bool("show_reply_context")
1170             and $t->{in_reply_to_screen_name} ne $username
1171             and $t->{in_reply_to_screen_name}
1172             and not exists $friends{ $t->{in_reply_to_screen_name} } )
1173         {
1174             $nicks{ $t->{in_reply_to_screen_name} } = time;
1175             my $context;
1176             unless ( $cache->{ $t->{in_reply_to_status_id} } ) {
1177                 eval {
1178                     $cache->{ $t->{in_reply_to_status_id} } =
1179                       $obj->show_status( $t->{in_reply_to_status_id} );
1180                 };
1181
1182             }
1183             $context = $cache->{ $t->{in_reply_to_status_id} };
1184
1185             if ($context) {
1186                 my $ctext =
1187                   decode_entities( $context->{retweeted_status}{text}
1188                       || $context->{text} );
1189                 $ctext =~ s/[\n\r]/ /g;
1190                 if ( $context->{truncated} and ref($obj) ne 'Net::Identica' ) {
1191                     $ctext .=
1192                         " -- http://twitter.com/$context->{user}{screen_name}"
1193                       . "/status/$context->{id}";
1194                 }
1195                 printf $fh "id:%s account:%s nick:%s type:tweet %s\n",
1196                   $context->{id}, $username,
1197                   $context->{user}{screen_name}, $ctext;
1198                 $reply = "reply";
1199             }
1200         }
1201         if ( $t->{truncated} and ref($obj) ne 'Net::Identica' ) {
1202             $text .= " -- http://twitter.com/$t->{user}{screen_name}"
1203               . "/status/$t->{id}";
1204         }
1205         printf $fh "id:%s account:%s nick:%s type:%s %s\n",
1206           $t->{id}, $username, $t->{user}{screen_name}, $reply, $text;
1207         $last_id = $t->{id} if $last_id < $t->{id};
1208     }
1209     printf $fh "id:%s account:%s type:last_id_fixreplies %s\n",
1210       $last_id, $username, $target;
1211
1212     return 1;
1213 }
1214
1215 sub monitor_child {
1216     my ($data)   = @_;
1217     my $filename = $data->[0];
1218     my $attempt  = $data->[1];
1219
1220     print scalar localtime, " - checking child log at $filename ($attempt)"
1221       if &debug;
1222     my ($new_last_poll);
1223
1224     # first time we run we don't want to print out *everything*, so we just
1225     # pretend
1226
1227     if ( open FILE, $filename ) {
1228         binmode FILE, ":utf8";
1229         my @lines;
1230         my %new_cache;
1231         while (<FILE>) {
1232             last if /^__friends__/;
1233             unless (/\n$/) {    # skip partial lines
1234                                 # print "Skipping partial line: $_" if &debug;
1235                 next;
1236             }
1237             chomp;
1238             my $hilight = 0;
1239             my %meta;
1240
1241             foreach my $key (qw/id account nick type topic/) {
1242                 if (s/^$key:(\S+)\s*//) {
1243                     $meta{$key} = $1;
1244                 }
1245             }
1246
1247             if ( $meta{type} and $meta{type} eq 'fix_replies_index' ) {
1248                 $fix_replies_index{ $meta{account} } = $meta{id};
1249                 print "fix_replies_index for $meta{account} set to $meta{id}"
1250                   if &debug;
1251                 next;
1252             }
1253
1254             if ( not $meta{type} or $meta{type} !~ /searchid|last_id/ ) {
1255                 if ( exists $meta{id} and exists $new_cache{ $meta{id} } ) {
1256                     next;
1257                 }
1258
1259                 $new_cache{ $meta{id} } = time;
1260
1261                 if ( exists $meta{id} and exists $tweet_cache{ $meta{id} } ) {
1262                     next;
1263                 }
1264             }
1265
1266             my $account = "";
1267             $meta{account} =~ s/\@(\w+)$//;
1268             $meta{service} = $1;
1269             if (
1270                 lc $meta{service} eq
1271                 lc Irssi::settings_get_str("twirssi_default_service") )
1272             {
1273                 $account = "$meta{account}: "
1274                   if lc "$meta{account}\@$meta{service}" ne lc
1275                       "$user\@$defservice";
1276             } else {
1277                 $account = "$meta{account}\@$meta{service}: ";
1278             }
1279
1280             my $marker = "";
1281             if (    $meta{type} ne 'dm'
1282                 and Irssi::settings_get_bool("twirssi_track_replies")
1283                 and $meta{nick}
1284                 and $meta{id} )
1285             {
1286                 $marker = ( $id_map{__indexes}{ $meta{nick} } + 1 ) % 100;
1287                 $id_map{ lc $meta{nick} }[$marker]           = $meta{id};
1288                 $id_map{__indexes}{ $meta{nick} }            = $marker;
1289                 $id_map{__tweets}{ lc $meta{nick} }[$marker] = $_;
1290                 $marker                                      = ":$marker";
1291             }
1292
1293             my $hilight_color =
1294               $irssi_to_mirc_colors{ Irssi::settings_get_str("hilight_color") };
1295             my $nick = "\@$meta{account}";
1296             if ( $_ =~ /\Q$nick\E(?:\W|$)/i
1297                 and Irssi::settings_get_bool("twirssi_hilights") )
1298             {
1299                 $meta{nick} = "\cC$hilight_color$meta{nick}\cO";
1300                 $hilight = MSGLEVEL_HILIGHT;
1301             }
1302
1303             if ( $meta{type} =~ /tweet|reply/ ) {
1304                 push @lines,
1305                   [
1306                     ( MSGLEVEL_PUBLIC | $hilight ),
1307                     $meta{type}, $account, $meta{nick}, $marker, $_
1308                   ];
1309             } elsif ( $meta{type} eq 'search' ) {
1310                 push @lines,
1311                   [
1312                     ( MSGLEVEL_PUBLIC | $hilight ),
1313                     $meta{type}, $account, $meta{topic},
1314                     $meta{nick}, $marker,  $_
1315                   ];
1316                 if (
1317                     exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
1318                     and $meta{id} >
1319                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
1320                 {
1321                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
1322                       $meta{id};
1323                 }
1324             } elsif ( $meta{type} eq 'dm' ) {
1325                 push @lines,
1326                   [
1327                     ( MSGLEVEL_MSGS | $hilight ),
1328                     $meta{type}, $account, $meta{nick}, $_
1329                   ];
1330             } elsif ( $meta{type} eq 'searchid' ) {
1331                 print "Search '$meta{topic}' returned id $meta{id}" if &debug;
1332                 if (
1333                     not
1334                     exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
1335                     or $meta{id} >=
1336                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
1337                 {
1338                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
1339                       $meta{id};
1340                 } elsif (&debug) {
1341                     print "Search '$meta{topic}' returned invalid id $meta{id}";
1342                 }
1343             } elsif ( $meta{type} eq 'last_id' ) {
1344                 $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} =
1345                   $meta{id}
1346                   if $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} <
1347                       $meta{id};
1348             } elsif ( $meta{type} eq 'last_id_fixreplies' ) {
1349                 $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} =
1350                   $meta{id}
1351                   if $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} <
1352                       $meta{id};
1353             } elsif ( $meta{type} eq 'error' ) {
1354                 push @lines, [ MSGLEVEL_MSGS, $_ ];
1355             } elsif ( $meta{type} eq 'debug' ) {
1356                 print "$_" if &debug,;
1357             } else {
1358                 print "Unknown line type $meta{type}: $_" if &debug,;
1359             }
1360         }
1361
1362         %friends = ();
1363         while (<FILE>) {
1364             if (/^__updated (\d+)$/) {
1365                 $last_friends_poll = $1;
1366                 print "Friend list updated" if &debug;
1367                 next;
1368             }
1369
1370             if (/^-- (\d+)$/) {
1371                 $new_last_poll = $1;
1372                 if ( $new_last_poll >= $last_poll ) {
1373                     last;
1374                 } else {
1375                     print "Impossible!  ",
1376                       "new_last_poll=$new_last_poll < last_poll=$last_poll!"
1377                       if &debug;
1378                     undef $new_last_poll;
1379                     next;
1380                 }
1381             }
1382             my ( $f, $t ) = split ' ', $_;
1383             $nicks{$f} = $friends{$f} = $t;
1384         }
1385
1386         if ($new_last_poll) {
1387             print "new last_poll    = $new_last_poll" if &debug;
1388             print "new last_poll_id = ", Dumper( $id_map{__last_id} ) if &debug;
1389             if ($first_call) {
1390                 print "First call, not printing updates" if &debug;
1391             } else {
1392                 foreach my $line (@lines) {
1393                     $window->printformat(
1394                         $line->[0],
1395                         "twirssi_" . $line->[1],
1396                         @$line[ 2 .. $#$line - 1 ],
1397                         &hilight( $line->[-1] )
1398                     );
1399                 }
1400             }
1401
1402             close FILE;
1403             unlink $filename
1404               or warn "Failed to remove $filename: $!"
1405               unless &debug;
1406
1407             # commit the pending cache lines to the actual cache, now that
1408             # we've printed our output
1409             %tweet_cache = ( %tweet_cache, %new_cache );
1410
1411             # keep enough cached tweets, to make sure we don't show duplicates.
1412             foreach ( keys %tweet_cache ) {
1413                 next if $tweet_cache{$_} >= $last_poll - 3600;
1414                 delete $tweet_cache{$_};
1415             }
1416             $last_poll = $new_last_poll;
1417
1418             # make sure the pid is removed from the waitpid list
1419             Irssi::pidwait_remove($child_pid);
1420
1421             # and that we don't leave any zombies behind, somehow
1422             wait();
1423
1424             # save id_map hash
1425             if ( keys %id_map
1426                 and my $file =
1427                 Irssi::settings_get_str("twirssi_replies_store") )
1428             {
1429                 if ( open JSON, ">$file" ) {
1430                     print JSON JSON::Any->objToJson( \%id_map );
1431                     close JSON;
1432                 } else {
1433                     &ccrap("Failed to write replies to $file: $!");
1434                 }
1435             }
1436             $failwhale  = 0;
1437             $first_call = 0;
1438             return;
1439         }
1440     }
1441
1442     close FILE;
1443
1444     if ( $attempt < 24 ) {
1445         Irssi::timeout_add_once( 5000, 'monitor_child',
1446             [ $filename, $attempt + 1 ] );
1447     } else {
1448         print "Giving up on polling $filename" if &debug;
1449         Irssi::pidwait_remove($child_pid);
1450         wait();
1451         unlink $filename unless &debug;
1452
1453         return unless Irssi::settings_get_bool("twirssi_notify_timeouts");
1454
1455         my $since;
1456         my @time = localtime($last_poll);
1457         if ( time - $last_poll < 24 * 60 * 60 ) {
1458             $since = sprintf( "%d:%02d", @time[ 2, 1 ] );
1459         } else {
1460             $since = scalar localtime($last_poll);
1461         }
1462
1463         if ( not $failwhale and time - $last_poll > 60 * 60 ) {
1464             foreach my $whale (
1465                 q{     v  v        v},
1466                 q{     |  |  v     |  v},
1467                 q{     | .-, |     |  |},
1468                 q{  .--./ /  |  _.---.| },
1469                 q{   '-. (__..-"       \\},
1470                 q{      \\          a    |},
1471                 q{       ',.__.   ,__.-'/},
1472                 q{         '--/_.'----'`}
1473               )
1474             {
1475                 &ccrap($whale);
1476             }
1477             $failwhale = 1;
1478         }
1479
1480         if ( time - $last_poll < 600 ) {
1481             &ccrap("Haven't been able to get updated tweets since $since");
1482         }
1483     }
1484 }
1485
1486 sub debug {
1487     return Irssi::settings_get_bool("twirssi_debug");
1488 }
1489
1490 sub notice {
1491     $window->print( "%R***%n @_", MSGLEVEL_PUBLIC );
1492 }
1493
1494 sub ccrap {
1495     $window->print( "%R***%n @_", MSGLEVEL_CLIENTCRAP );
1496 }
1497
1498 sub update_away {
1499     my $data = shift;
1500
1501     if (    Irssi::settings_get_bool("tweet_to_away")
1502         and $data !~ /\@\w/
1503         and $data !~ /^[dD] / )
1504     {
1505         my $server =
1506           Irssi::server_find_tag( Irssi::settings_get_str("bitlbee_server") );
1507         if ($server) {
1508             $server->send_raw("away :$data");
1509             return 1;
1510         } else {
1511             &ccrap( "Can't find bitlbee server.",
1512                 "Update bitlbee_server or disable tweet_to_away" );
1513             return 0;
1514         }
1515     }
1516
1517     return 0;
1518 }
1519
1520 sub too_long {
1521     my $data    = shift;
1522     my $noalert = shift;
1523
1524     if ( length $data > 140 ) {
1525         &notice( "Tweet too long (" . length($data) . " characters) - aborted" )
1526           unless $noalert;
1527         return 1;
1528     }
1529
1530     return 0;
1531 }
1532
1533 sub valid_username {
1534     my $username = shift;
1535
1536     $username = &normalize_username($username);
1537
1538     unless ( exists $twits{$username} ) {
1539         &notice("Unknown username $username");
1540         return undef;
1541     }
1542
1543     return $username;
1544 }
1545
1546 sub logged_in {
1547     my $obj = shift;
1548     unless ($obj) {
1549         &notice("Not logged in!  Use /twitter_login username pass!");
1550         return 0;
1551     }
1552
1553     return 1;
1554 }
1555
1556 sub sig_complete {
1557     my ( $complist, $window, $word, $linestart, $want_space ) = @_;
1558
1559     if (
1560         $linestart =~ /^\/(?:retweet|twitter_reply)(?:_as)?\s*$/
1561         or ( Irssi::settings_get_bool("twirssi_use_reply_aliases")
1562             and $linestart =~ /^\/reply(?:_as)?\s*$/ )
1563       )
1564     {    # /twitter_reply gets a nick:num
1565         $word =~ s/^@//;
1566         @$complist = map { "$_:$id_map{__indexes}{$_}" }
1567           sort { $nicks{$b} <=> $nicks{$a} }
1568           grep /^\Q$word/i,
1569           keys %{ $id_map{__indexes} };
1570     }
1571
1572     if ( $linestart =~
1573 /^\/(twitter_unfriend|twitter_add_follow_extra|twitter_del_follow_extra)\s*$/
1574       )
1575     {    # /twitter_unfriend gets a nick
1576         $word =~ s/^@//;
1577         push @$complist, grep /^\Q$word/i,
1578           sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1579     }
1580
1581     # /tweet, /tweet_as, /dm, /dm_as - complete @nicks (and nicks as the first
1582     # arg to dm)
1583     if ( $linestart =~ /^\/(?:tweet|dm)/ ) {
1584         my $prefix = $word =~ s/^@//;
1585         $prefix = 0 if $linestart eq '/dm' or $linestart eq '/dm_as';
1586         push @$complist, grep /^\Q$word/i,
1587           sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1588         @$complist = map { "\@$_" } @$complist if $prefix;
1589     }
1590 }
1591
1592 sub event_send_text {
1593     my ( $line, $server, $win ) = @_;
1594     my $awin = Irssi::active_win();
1595
1596     # if the window where we got our text was the twitter window, and the user
1597     # wants to be lazy, tweet away!
1598     if ( ( $awin->get_active_name() eq $window->{name} )
1599         and Irssi::settings_get_bool("tweet_window_input") )
1600     {
1601         &cmd_tweet( $line, $server, $win );
1602     }
1603 }
1604
1605 sub get_poll_time {
1606     my $poll = Irssi::settings_get_int("twitter_poll_interval");
1607     return $poll if $poll >= 60;
1608     return 60;
1609 }
1610
1611 sub hilight {
1612     my $text = shift;
1613
1614     if ( Irssi::settings_get_str("twirssi_nick_color") ) {
1615         my $c = Irssi::settings_get_str("twirssi_nick_color");
1616         $c = $irssi_to_mirc_colors{$c};
1617         $text =~ s/(^|\W)\@(\w+)/$1\cC$c\@$2\cO/g if $c;
1618     }
1619     if ( Irssi::settings_get_str("twirssi_topic_color") ) {
1620         my $c = Irssi::settings_get_str("twirssi_topic_color");
1621         $c = $irssi_to_mirc_colors{$c};
1622         $text =~ s/(^|\W)(\#|\!)([-\w]+)/$1\cC$c$2$3\cO/g if $c;
1623     }
1624     $text =~ s/[\n\r]/ /g;
1625
1626     return $text;
1627 }
1628
1629 sub shorten {
1630     my $data = shift;
1631
1632     my $provider = Irssi::settings_get_str("short_url_provider");
1633     if (
1634         (
1635             Irssi::settings_get_bool("twirssi_always_shorten")
1636             or &too_long( $data, 1 )
1637         )
1638         and $provider
1639       )
1640     {
1641         my @args;
1642         if ( $provider eq 'Bitly' ) {
1643             @args[ 1, 2 ] = split ',',
1644               Irssi::settings_get_str("short_url_args"), 2;
1645             unless ( @args == 3 ) {
1646                 &ccrap(
1647                     "WWW::Shorten::Bitly requires a username and API key.",
1648                     "Set short_url_args to username,API_key or change your",
1649                     "short_url_provider."
1650                 );
1651                 return decode "utf8", $data;
1652             }
1653         }
1654
1655         foreach my $url ( $data =~ /(https?:\/\/\S+[\w\/])/g ) {
1656             eval {
1657                 $args[0] = $url;
1658                 my $short = makeashorterlink(@args);
1659                 if ($short) {
1660                     $data =~ s/\Q$url/$short/g;
1661                 } else {
1662                     &notice("Failed to shorten $url!");
1663                 }
1664             };
1665         }
1666     }
1667
1668     return decode "utf8", $data;
1669 }
1670
1671 sub normalize_username {
1672     my $user = shift;
1673
1674     my ( $username, $service ) = split /\@/, $user, 2;
1675     if ($service) {
1676         $service = ucfirst lc $service;
1677     } else {
1678         $service =
1679           ucfirst lc Irssi::settings_get_str("twirssi_default_service");
1680         unless ( exists $twits{"$username\@$service"} ) {
1681             $service = undef;
1682             foreach my $t ( sort keys %twits ) {
1683                 next unless $t =~ /^\Q$username\E\@(Twitter|Identica)/;
1684                 $service = $1;
1685                 last;
1686             }
1687
1688             unless ($service) {
1689                 &notice("Can't find a logged in user '$user'");
1690             }
1691         }
1692     }
1693
1694     return "$username\@$service";
1695 }
1696
1697 Irssi::signal_add( "send text", "event_send_text" );
1698
1699 Irssi::theme_register(
1700     [
1701         'twirssi_tweet',  '[$0%B@$1%n$2] $3',
1702         'twirssi_search', '[$0%r$1%n:%B@$2%n$3] $4',
1703         'twirssi_reply',  '[$0\--> %B@$1%n$2] $3',
1704         'twirssi_dm',     '[$0%r@$1%n (%WDM%n)] $2',
1705         'twirssi_error',  'ERROR: $0',
1706     ]
1707 );
1708
1709 Irssi::settings_add_int( "twirssi", "twitter_poll_interval", 300 );
1710 Irssi::settings_add_str( "twirssi", "twitter_window",          "twitter" );
1711 Irssi::settings_add_str( "twirssi", "bitlbee_server",          "bitlbee" );
1712 Irssi::settings_add_str( "twirssi", "short_url_provider",      "TinyURL" );
1713 Irssi::settings_add_str( "twirssi", "short_url_args",          undef );
1714 Irssi::settings_add_str( "twirssi", "twitter_usernames",       undef );
1715 Irssi::settings_add_str( "twirssi", "twitter_passwords",       undef );
1716 Irssi::settings_add_str( "twirssi", "twirssi_default_service", "Twitter" );
1717 Irssi::settings_add_str( "twirssi", "twirssi_nick_color",      "%B" );
1718 Irssi::settings_add_str( "twirssi", "twirssi_topic_color",     "%r" );
1719 Irssi::settings_add_str( "twirssi", "twirssi_retweet_format",
1720     'RT $n: "$t" ${-- $c$}' );
1721 Irssi::settings_add_str( "twirssi", "twirssi_location",
1722     ".irssi/scripts/twirssi.pl" );
1723 Irssi::settings_add_str( "twirssi", "twirssi_replies_store",
1724     ".irssi/scripts/twirssi.json" );
1725
1726 Irssi::settings_add_int( "twirssi", "twitter_friends_poll", 600 );
1727 Irssi::settings_add_int( "twirssi", "twitter_timeout",      30 );
1728
1729 Irssi::settings_add_bool( "twirssi", "twirssi_upgrade_beta",      0 );
1730 Irssi::settings_add_bool( "twirssi", "tweet_to_away",             0 );
1731 Irssi::settings_add_bool( "twirssi", "show_reply_context",        0 );
1732 Irssi::settings_add_bool( "twirssi", "show_own_tweets",           1 );
1733 Irssi::settings_add_bool( "twirssi", "twirssi_debug",             0 );
1734 Irssi::settings_add_bool( "twirssi", "twirssi_first_run",         1 );
1735 Irssi::settings_add_bool( "twirssi", "twirssi_track_replies",     1 );
1736 Irssi::settings_add_bool( "twirssi", "twirssi_replies_autonick",  1 );
1737 Irssi::settings_add_bool( "twirssi", "twirssi_use_reply_aliases", 0 );
1738 Irssi::settings_add_bool( "twirssi", "twirssi_notify_timeouts",   1 );
1739 Irssi::settings_add_bool( "twirssi", "twirssi_hilights",          1 );
1740 Irssi::settings_add_bool( "twirssi", "twirssi_always_shorten",    0 );
1741 Irssi::settings_add_bool( "twirssi", "tweet_window_input",        0 );
1742 Irssi::settings_add_bool( "twirssi", "twirssi_avoid_ssl",         0 );
1743
1744 $last_poll = time - &get_poll_time;
1745 $window = Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
1746 if ( !$window ) {
1747     Irssi::active_win()
1748       ->print( "Couldn't find a window named '"
1749           . Irssi::settings_get_str('twitter_window')
1750           . "', trying to create it." );
1751     $window =
1752       Irssi::Windowitem::window_create(
1753         Irssi::settings_get_str('twitter_window'), 1 );
1754     $window->set_name( Irssi::settings_get_str('twitter_window') );
1755 }
1756
1757 if ($window) {
1758     Irssi::command_bind( "dm",                         "cmd_direct" );
1759     Irssi::command_bind( "dm_as",                      "cmd_direct_as" );
1760     Irssi::command_bind( "tweet",                      "cmd_tweet" );
1761     Irssi::command_bind( "tweet_as",                   "cmd_tweet_as" );
1762     Irssi::command_bind( "retweet",                    "cmd_retweet" );
1763     Irssi::command_bind( "retweet_as",                 "cmd_retweet_as" );
1764     Irssi::command_bind( "twitter_reply",              "cmd_reply" );
1765     Irssi::command_bind( "twitter_reply_as",           "cmd_reply_as" );
1766     Irssi::command_bind( "twitter_login",              "cmd_login" );
1767     Irssi::command_bind( "twitter_logout",             "cmd_logout" );
1768     Irssi::command_bind( "twitter_switch",             "cmd_switch" );
1769     Irssi::command_bind( "twitter_subscribe",          "cmd_add_search" );
1770     Irssi::command_bind( "twitter_unsubscribe",        "cmd_del_search" );
1771     Irssi::command_bind( "twitter_list_subscriptions", "cmd_list_search" );
1772     Irssi::command_bind( "twirssi_upgrade",            "cmd_upgrade" );
1773     Irssi::command_bind( "twitter_updates",            "get_updates" );
1774     Irssi::command_bind( "twitter_add_follow_extra",   "cmd_add_follow" );
1775     Irssi::command_bind( "twitter_del_follow_extra",   "cmd_del_follow" );
1776     Irssi::command_bind( "twitter_list_follow_extra",  "cmd_list_follow" );
1777     Irssi::command_bind( "bitlbee_away",               "update_away" );
1778     if ( Irssi::settings_get_bool("twirssi_use_reply_aliases") ) {
1779         Irssi::command_bind( "reply",    "cmd_reply" );
1780         Irssi::command_bind( "reply_as", "cmd_reply_as" );
1781     }
1782     Irssi::command_bind(
1783         "twirssi_dump",
1784         sub {
1785             print "twits: ", join ", ",
1786               map { "u: $_->{username}\@" . ref($_) } values %twits;
1787             print "selected: $user\@$defservice";
1788             print "friends: ", join ", ", sort keys %friends;
1789             print "nicks: ",   join ", ", sort keys %nicks;
1790             print "searches: ", Dumper \%{ $id_map{__searches} };
1791             print "last poll: $last_poll";
1792             if ( open DUMP, ">/tmp/twirssi.cache.txt" ) {
1793                 print DUMP Dumper \%tweet_cache;
1794                 close DUMP;
1795                 print "cache written out to /tmp/twirssi.cache.txt";
1796             }
1797         }
1798     );
1799     Irssi::command_bind(
1800         "twirssi_version",
1801         sub {
1802             &notice(
1803                 "Twirssi v$VERSION; "
1804                   . (
1805                     $Net::Twitter::VERSION
1806                     ? "Net::Twitter v$Net::Twitter::VERSION. "
1807                     : ""
1808                   )
1809                   . (
1810                     $Net::Identica::VERSION
1811                     ? "Net::Identica v$Net::Identica::VERSION. "
1812                     : ""
1813                   )
1814                   . "JSON in use: "
1815                   . JSON::Any::handler()
1816                   . ".  See details at http://twirssi.com/"
1817             );
1818         }
1819     );
1820     Irssi::command_bind(
1821         "twitter_follow",
1822         &gen_cmd(
1823             "/twitter_follow <username>",
1824             "create_friend",
1825             sub { &notice("Following $_[0]"); $nicks{ $_[0] } = time; }
1826         )
1827     );
1828     Irssi::command_bind(
1829         "twitter_unfollow",
1830         &gen_cmd(
1831             "/twitter_unfriend <username>",
1832             "destroy_friend",
1833             sub { &notice("Stopped following $_[0]"); delete $nicks{ $_[0] }; }
1834         )
1835     );
1836     Irssi::command_bind(
1837         "twitter_device_updates",
1838         &gen_cmd(
1839             "/twitter_device_updates none|im|sms",
1840             "update_delivery_device",
1841             sub { &notice("Device updated to $_[0]"); }
1842         )
1843     );
1844     Irssi::command_bind(
1845         "twitter_block",
1846         &gen_cmd(
1847             "/twitter_block <username>",
1848             "create_block",
1849             sub { &notice("Blocked $_[0]"); }
1850         )
1851     );
1852     Irssi::command_bind(
1853         "twitter_unblock",
1854         &gen_cmd(
1855             "/twitter_unblock <username>",
1856             "destroy_block",
1857             sub { &notice("Unblock $_[0]"); }
1858         )
1859     );
1860     Irssi::signal_add_last( 'complete word' => \&sig_complete );
1861
1862     &notice("  %Y<%C(%B^%C)%N                   TWIRSSI v%R$VERSION%N");
1863     &notice("   %C(_(\\%N           http://twirssi.com/ for full docs");
1864     &notice(
1865         "    %Y||%C `%N Log in with /twitter_login, send updates with /tweet");
1866
1867     my $file = Irssi::settings_get_str("twirssi_replies_store");
1868     if ( $file and -r $file ) {
1869         if ( open( JSON, $file ) ) {
1870             local $/;
1871             my $json = <JSON>;
1872             close JSON;
1873             eval {
1874                 my $ref = JSON::Any->jsonToObj($json);
1875                 %id_map = %$ref;
1876                 my $num = keys %{ $id_map{__indexes} };
1877                 &notice( sprintf "Loaded old replies from %d contact%s.",
1878                     $num, ( $num == 1 ? "" : "s" ) );
1879                 &cmd_list_search;
1880                 &cmd_list_follow;
1881             };
1882         } else {
1883             &notice("Failed to load old replies from $file: $!");
1884         }
1885     }
1886
1887     if ( my $provider = Irssi::settings_get_str("short_url_provider") ) {
1888         &notice("Loading WWW::Shorten::$provider...");
1889         eval "use WWW::Shorten::$provider;";
1890
1891         if ($@) {
1892             &notice(
1893                 "Failed to load WWW::Shorten::$provider - either clear",
1894                 "short_url_provider or install the CPAN module"
1895             );
1896         }
1897     }
1898
1899     if (    my $autouser = Irssi::settings_get_str("twitter_usernames")
1900         and my $autopass = Irssi::settings_get_str("twitter_passwords") )
1901     {
1902         &cmd_login();
1903         &get_updates;
1904     }
1905
1906 } else {
1907     Irssi::active_win()
1908       ->print( "Create a window named "
1909           . Irssi::settings_get_str('twitter_window')
1910           . " or change the value of twitter_window.  Then, reload twirssi." );
1911 }
1912
1913 # vim: set sts=4 expandtab: