Merge branch 'master' of git://github.com/faemir/twirssi
[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 Net::Identica;
10 use Net::Twitter;
11 $Data::Dumper::Indent = 1;
12
13 use vars qw($VERSION %IRSSI);
14
15 $VERSION = "2.0.6";
16 my ($REV) = '$Rev: 484 $' =~ /(\d+)/;
17 %IRSSI = (
18     authors     => 'Dan Boger',
19     contact     => 'zigdon@gmail.com',
20     name        => 'twirssi',
21     description => 'Send twitter/identica updates using /tweet or /dent.  '
22       . 'Can optionally set your bitlbee /away message to same',
23     license => 'GNU GPL v2',
24     url     => 'http://twirssi.com',
25     changed => '$Date: 2009-02-21 13:53:25 -0800 (Sat, 21 Feb 2009) $',
26 );
27
28 my $window;
29 my $twit;
30 my %twits;
31 my $user;
32 my $poll;
33 my $last_poll;
34 my %nicks;
35 my %friends;
36 my %tweet_cache;
37 my %id_map;
38 my %irssi_to_mirc_colors = (
39     '%k' => '01',
40     '%r' => '05',
41     '%g' => '03',
42     '%y' => '07',
43     '%b' => '02',
44     '%m' => '06',
45     '%c' => '10',
46     '%w' => '15',
47     '%K' => '14',
48     '%R' => '04',
49     '%G' => '09',
50     '%Y' => '08',
51     '%B' => '12',
52     '%M' => '13',
53     '%C' => '11',
54     '%W' => '00',
55 );
56
57 sub cmd_direct {
58     my ( $data, $server, $win ) = @_;
59
60     return unless &logged_in($twit);
61
62     my ( $target, $text ) = split ' ', $data, 2;
63     unless ( $target and $text ) {
64         &notice("Usage: /dm <nick> <message>");
65         return;
66     }
67
68     &cmd_direct_as( "$user $data", $server, $win );
69 }
70
71 sub cmd_direct_as {
72     my ( $data, $server, $win ) = @_;
73
74     return unless &logged_in($twit);
75
76     my ( $username, $target, $text ) = split ' ', $data, 3;
77     unless ( $username and $target and $text ) {
78         &notice("Usage: /dm_as <username> <nick> <message>");
79         return;
80     }
81
82     return unless &valid_username($username);
83
84     eval {
85         if ( $twits{$username}
86             ->new_direct_message( { user => $target, text => $text } ) )
87         {
88             &notice("DM sent to $target");
89             $nicks{$target} = time;
90         } else {
91             my $error;
92             eval {
93                 $error = JSON::Any->jsonToObj( $twits{$username}->get_error() );
94                 $error = $error->{error};
95             };
96             die $error if $error;
97             &notice("DM to $target failed");
98         }
99     };
100
101     if ($@) {
102         &notice("DM caused an error: $@");
103         return;
104     }
105 }
106
107 sub cmd_tweet {
108     my ( $data, $server, $win ) = @_;
109
110     return unless &logged_in($twit);
111
112     $data =~ s/^\s+|\s+$//;
113     unless ($data) {
114         &notice("Usage: /tweet <update>");
115         return;
116     }
117
118     &cmd_tweet_as( "$user $data", $server, $win );
119 }
120
121 sub cmd_tweet_as {
122     my ( $data, $server, $win ) = @_;
123
124     return unless &logged_in($twit);
125
126     $data =~ s/^\s+|\s+$//;
127     $data =~ s/\s\s+/ /g;
128     my ( $username, $data ) = split ' ', $data, 2;
129
130     unless ( $username and $data ) {
131         &notice("Usage: /tweet_as <username> <update>");
132         return;
133     }
134
135     return unless &valid_username($username);
136
137     if ( &too_long( $data, 1 )
138         and Irssi::settings_get_str("short_url_provider") )
139     {
140         foreach my $url ( $data =~ /(https?:\/\/\S+[\w\/])/g ) {
141             eval {
142                 my $short = makeashorterlink($url);
143                 $data =~ s/\Q$url/$short/g;
144             };
145         }
146     }
147
148     return if &too_long($data);
149
150     my $success = 1;
151     eval {
152         unless ( $twits{$username}->update($data) )
153         {
154             &notice("Update failed");
155             $success = 0;
156         }
157     };
158     return unless $success;
159
160     if ($@) {
161         &notice("Update caused an error: $@.  Aborted.");
162         return;
163     }
164
165     foreach ( $data =~ /@([-\w]+)/ ) {
166         $nicks{$1} = time;
167     }
168
169     my $away = &update_away($data);
170
171     &notice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
172 }
173
174 sub cmd_reply {
175     my ( $data, $server, $win ) = @_;
176
177     return unless &logged_in($twit);
178
179     $data =~ s/^\s+|\s+$//;
180     unless ($data) {
181         &notice("Usage: /reply <nick[:num]> <update>");
182         return;
183     }
184
185     $data =~ s/^\s+|\s+$//;
186     my ( $id, $data ) = split ' ', $data, 2;
187     unless ( $id and $data ) {
188         &notice("Usage: /reply_as <nick[:num]> <update>");
189         return;
190     }
191
192     &cmd_reply_as( "$user $id $data", $server, $win );
193 }
194
195 sub cmd_reply_as {
196     my ( $data, $server, $win ) = @_;
197
198     unless ( Irssi::settings_get_bool("twirssi_track_replies") ) {
199         &notice("twirssi_track_replies is required in order to reply to "
200               . "specific tweets.  Either enable it, or just use /tweet "
201               . "\@username <text>." );
202         return;
203     }
204
205     return unless &logged_in($twit);
206
207     $data =~ s/^\s+|\s+$//;
208     my ( $username, $id, $data ) = split ' ', $data, 3;
209
210     unless ( $username and $data ) {
211         &notice("Usage: /reply_as <username> <nick[:num]> <update>");
212         return;
213     }
214
215     return unless &valid_username($username);
216
217     my $nick;
218     $id =~ s/[^\w\d\-:]+//g;
219     ( $nick, $id ) = split /:/, $id;
220     unless ( exists $id_map{ lc $nick } ) {
221         &notice("Can't find a tweet from $nick to reply to!");
222         return;
223     }
224
225     $id = $id_map{__indexes}{$nick} unless $id;
226     unless ( $id_map{ lc $nick }[$id] ) {
227         &notice("Can't find a tweet numbered $id from $nick to reply to!");
228         return;
229     }
230
231     if ( Irssi::settings_get_bool("twirssi_replies_autonick") ) {
232
233         # remove any @nick at the beginning of the reply, as we'll add it anyway
234         $data =~ s/^\s*\@?$nick\s*//;
235         $data = "\@$nick " . $data;
236     }
237
238     if ( &too_long( $data, 1 ) ) {
239         if ( Irssi::settings_get_str("short_url_provider") ) {
240             foreach my $url ( $data =~ /(https?:\/\/\S+[\w\/])/g ) {
241                 eval {
242                     my $short = makeashorterlink($url);
243                     $data =~ s/\Q$url/$short/g;
244                 };
245             }
246         }
247     }
248
249     return if &too_long($data);
250
251     my $success = 1;
252     eval {
253         unless (
254             $twits{$username}->update(
255                 {
256                     status                => $data,
257                     in_reply_to_status_id => $id_map{ lc $nick }[$id]
258                 }
259             )
260           )
261         {
262             &notice("Update failed");
263             $success = 0;
264         }
265     };
266     return unless $success;
267
268     if ($@) {
269         &notice("Update caused an error: $@.  Aborted");
270         return;
271     }
272
273     foreach ( $data =~ /@([-\w]+)/ ) {
274         $nicks{$1} = time;
275     }
276
277     my $away = &update_away($data);
278
279     &notice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
280 }
281
282 sub gen_cmd {
283     my ( $usage_str, $api_name, $post_ref ) = @_;
284
285     return sub {
286         my ( $data, $server, $win ) = @_;
287
288         return unless &logged_in($twit);
289
290         $data =~ s/^\s+|\s+$//;
291         unless ($data) {
292             &notice("Usage: $usage_str");
293             return;
294         }
295
296         my $success = 1;
297         eval {
298             unless ( $twit->$api_name($data) )
299             {
300                 &notice("$api_name failed");
301                 $success = 0;
302             }
303         };
304         return unless $success;
305
306         if ($@) {
307             &notice("$api_name caused an error.  Aborted.");
308             return;
309         }
310
311         &$post_ref($data) if $post_ref;
312       }
313 }
314
315 sub cmd_switch {
316     my ( $data, $server, $win ) = @_;
317
318     $data =~ s/^\s+|\s+$//g;
319     if ( exists $twits{$data} ) {
320         &notice("Switching to $data");
321         $twit = $twits{$data};
322         $user = $data;
323     } else {
324         &notice("Unknown user $data");
325     }
326 }
327
328 sub cmd_logout_twitter {
329     my ( $data, $server, $win ) = @_;
330
331     $data =~ s/^\s+|\s+$//g;
332     $data = $user unless $data;
333     return unless &valid_username($data);
334
335     &notice("Logging out $data...");
336     $twits{$data}->end_session();
337     delete $twits{$data};
338     undef $twit;
339     if ( keys %twits ) {
340         &cmd_switch( ( keys %twits )[0], $server, $win );
341     } else {
342         Irssi::timeout_remove($poll) if $poll;
343         undef $poll;
344     }
345 }
346
347 sub cmd_logout_identica {
348     my ( $data, $server, $win ) = @_;
349
350     $data =~ s/^\s+|\s+$//g;
351     $data = $user unless $data;
352     return unless &valid_username($data);
353
354     &notice("Logging out $data...");
355     $twits{$data}->end_session();
356     delete $twits{$data};
357     undef $twit;
358     if ( keys %twits ) {
359         &cmd_switch( ( keys %twits )[0], $server, $win );
360     } else {
361         Irssi::timeout_remove($poll) if $poll;
362         undef $poll;
363     }
364 }
365
366 sub cmd_login_twitter {
367     my ( $data, $server, $win ) = @_;
368     my $pass;
369     if ($data) {
370         ( $user, $pass ) = split ' ', $data, 2;
371     } elsif ( my $autouser = Irssi::settings_get_str("twitter_usernames_twitter")
372         and my $autopass = Irssi::settings_get_str("twitter_passwords_twitter") )
373     {
374         my @user = split /\s*,\s*/, $autouser;
375         my @pass = split /\s*,\s*/, $autopass;
376         if ( @user != @pass ) {
377             &notice("Number of usernames doesn't match "
378                   . "the number of passwords - auto-login failed" );
379         } else {
380             my ( $u, $p );
381             while ( @user and @pass ) {
382                 $u = shift @user;
383                 $p = shift @pass;
384                 &cmd_login_twitter("$u $p");
385             }
386             return;
387         }
388     } else {
389         &notice("/twitter_login requires either a username and password "
390               . "or twitter_usernames_twitter and twitter_passwords_twitter to be set." );
391         return;
392     }
393
394     %friends = %nicks = ();
395
396     $twit = Net::Twitter->new(
397         username => $user,
398         password => $pass,
399         source   => "twirssi"
400     );
401
402     unless ( $twit->verify_credentials() ) {
403         &notice("Login as $user failed");
404         $twit = undef;
405         if ( keys %twits ) {
406             &cmd_switch( ( keys %twits )[0], $server, $win );
407         }
408         return;
409     }
410
411     if ($twit) {
412         my $rate_limit = $twit->rate_limit_status();
413         if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
414             &notice(
415                 "Rate limit exceeded, try again after $rate_limit->{reset_time}"
416             );
417             $twit = undef;
418             return;
419         }
420
421         $twits{$user} = $twit;
422         Irssi::timeout_remove($poll) if $poll;
423         $poll = Irssi::timeout_add( &get_poll_time * 1000, \&get_updates, "" );
424         &notice("Logged in as $user, loading friends list...");
425         &load_friends();
426         &notice( "loaded friends: ", scalar keys %friends );
427         if ( Irssi::settings_get_bool("twirssi_first_run") ) {
428             Irssi::settings_set_bool( "twirssi_first_run", 0 );
429             unless ( exists $friends{twirssi} ) {
430                 &notice("Welcome to twirssi!"
431                       . "  Perhaps you should add \@twirssi to your friends list,"
432                       . " so you can be notified when a new version is release?"
433                       . "  Just type /twitter_friend twirssi." );
434             }
435         }
436         %nicks = %friends;
437         $nicks{$user} = 0;
438         &get_updates;
439     } else {
440         &notice("Login failed");
441     }
442 }
443
444 sub cmd_login_identica {
445     my ( $data, $server, $win ) = @_;
446     my $pass;
447     if ($data) {
448         ( $user, $pass ) = split ' ', $data, 2;
449     } elsif ( my $autouser = Irssi::settings_get_str("twitter_usernames_identica")
450         and my $autopass = Irssi::settings_get_str("twitter_passwords_identica") )
451     {
452         my @user = split /\s*,\s*/, $autouser;
453         my @pass = split /\s*,\s*/, $autopass;
454         if ( @user != @pass ) {
455             &notice("Number of usernames doesn't match "
456                   . "the number of passwords - auto-login failed" );
457         } else {
458             my ( $u, $p );
459             while ( @user and @pass ) {
460                 $u = shift @user;
461                 $p = shift @pass;
462                 &cmd_login_identica("$u $p");
463             }
464             return;
465         }
466     } else {
467         &notice("/identica_login requires either a username and password "
468               . "or twitter_usernames_identica and twitter_passwords_identica to be set." );
469         return;
470     }
471
472     %friends = %nicks = ();
473
474     $twit = Net::Identica->new(
475         username => $user,
476         password => $pass,
477         source   => "twirssi"
478     );
479
480     unless ( $twit->verify_credentials() ) {
481         &notice("Login as $user failed");
482         $twit = undef;
483         if ( keys %twits ) {
484             &cmd_switch( ( keys %twits )[0], $server, $win );
485         }
486         return;
487     }
488
489     if ($twit) {
490         my $rate_limit = $twit->rate_limit_status();
491         if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
492             &notice(
493                 "Rate limit exceeded, try again after $rate_limit->{reset_time}"
494             );
495             $twit = undef;
496             return;
497         }
498
499         $twits{$user} = $twit;
500         Irssi::timeout_remove($poll) if $poll;
501         $poll = Irssi::timeout_add( &get_poll_time * 1000, \&get_updates, "" );
502         &notice("Logged in as $user, loading friends list...");
503         &load_friends();
504         &notice( "loaded friends: ", scalar keys %friends );
505         if ( Irssi::settings_get_bool("twirssi_first_run") ) {
506             Irssi::settings_set_bool( "twirssi_first_run", 0 );
507             unless ( exists $friends{twirssi} ) {
508                 &notice("Welcome to twirssi!"
509                       . "  Perhaps you should add \@twirssi to your friends list,"
510                       . " so you can be notified when a new version is release?"
511                       . "  Just type /twitter_friend twirssi." );
512             }
513         }
514         %nicks = %friends;
515         $nicks{$user} = 0;
516         &get_updates;
517     } else {
518         &notice("Login failed");
519     }
520 }
521
522 sub cmd_add_search_twitter {
523     my ( $data, $server, $win ) = @_;
524
525     unless ( $twit and $twit->can('search') ) {
526         &notice("ERROR: Your version of Net::Twitter ($Net::Twitter::VERSION) "
527               . "doesn't support searches." );
528         return;
529     }
530
531     $data =~ s/^\s+|\s+$//;
532     $data = lc $data;
533
534     unless ($data) {
535         &notice("Usage: /twitter_subscribe <topic>");
536         return;
537     }
538
539     if ( exists $id_map{__searches}{$user}{$data} ) {
540         &notice("Already had a subscription for '$data'");
541         return;
542     }
543
544     $id_map{__searches}{$user}{$data} = 1;
545     &notice("Added subscription for '$data'");
546 }
547
548 sub cmd_add_search_identica {
549     my ( $data, $server, $win ) = @_;
550
551     unless ( $twit and $twit->can('search') ) {
552         &notice("ERROR: Your version of Net::Identica ($Net::Identica::VERSION) "
553               . "doesn't support searches." );
554         return;
555     }
556
557     $data =~ s/^\s+|\s+$//;
558     $data = lc $data;
559
560     unless ($data) {
561         &notice("Usage: /twitter_subscribe <topic>");
562         return;
563     }
564
565     if ( exists $id_map{__searches}{$user}{$data} ) {
566         &notice("Already had a subscription for '$data'");
567         return;
568     }
569
570     $id_map{__searches}{$user}{$data} = 1;
571     &notice("Added subscription for '$data'");
572 }
573
574 sub cmd_del_search_twitter {
575     my ( $data, $server, $win ) = @_;
576
577     unless ( $twit and $twit->can('search') ) {
578         &notice("ERROR: Your version of Net::Twitter ($Net::Twitter::VERSION) "
579               . "doesn't support searches." );
580         return;
581     }
582     $data =~ s/^\s+|\s+$//;
583     $data = lc $data;
584
585     unless ($data) {
586         &notice("Usage: /twitter_unsubscribe <topic>");
587         return;
588     }
589
590     unless ( exists $id_map{__searches}{$user}{$data} ) {
591         &notice("No subscription found for '$data'");
592         return;
593     }
594
595     delete $id_map{__searches}{$user}{$data};
596     &notice("Removed subscription for '$data'");
597 }
598
599 sub cmd_del_search_identica {
600     my ( $data, $server, $win ) = @_;
601
602     unless ( $twit and $twit->can('search') ) {
603         &notice("ERROR: Your version of Net::Identica ($Net::Identica::VERSION) "
604               . "doesn't support searches." );
605         return;
606     }
607     $data =~ s/^\s+|\s+$//;
608     $data = lc $data;
609
610     unless ($data) {
611         &notice("Usage: /identica_unsubscribe <topic>");
612         return;
613     }
614
615     unless ( exists $id_map{__searches}{$user}{$data} ) {
616         &notice("No subscription found for '$data'");
617         return;
618     }
619
620     delete $id_map{__searches}{$user}{$data};
621     &notice("Removed subscription for '$data'");
622 }
623
624 sub cmd_list_search {
625     my ( $data, $server, $win ) = @_;
626
627     my $found = 0;
628     foreach my $suser ( sort keys %{ $id_map{__searches} } ) {
629         my $topics;
630         foreach my $topic ( sort keys %{ $id_map{__searches}{$suser} } ) {
631             $topics = $topics ? "$topics, $topic" : $topic;
632         }
633         if ($topics) {
634             $found = 1;
635             &notice("Search subscriptions for \@$suser: $topics");
636         }
637     }
638
639     unless ($found) {
640         &notice("No search subscriptions set up");
641     }
642 }
643
644 sub cmd_upgrade {
645     my ( $data, $server, $win ) = @_;
646
647     my $loc = Irssi::settings_get_str("twirssi_location");
648     unless ( -w $loc ) {
649         &notice(
650 "$loc isn't writable, can't upgrade.  Perhaps you need to /set twirssi_location?"
651         );
652         return;
653     }
654
655     my $md5;
656     unless ($data) {
657         eval { use Digest::MD5; };
658
659         if ($@) {
660             &notice(
661 "Failed to load Digest::MD5.  Try '/twirssi_upgrade nomd5' to skip MD5 verification"
662             );
663             return;
664         }
665
666         $md5 = get("http://twirssi.com/md5sum");
667         chomp $md5;
668         $md5 =~ s/ .*//;
669         unless ($md5) {
670             &notice("Failed to download md5sum from peeron!  Aborting.");
671             return;
672         }
673
674         unless ( open( CUR, $loc ) ) {
675             &notice(
676 "Failed to read $loc.  Check that /set twirssi_location is set to the correct location."
677             );
678             return;
679         }
680
681         my $cur_md5 = Digest::MD5::md5_hex(<CUR>);
682         close CUR;
683
684         if ( $cur_md5 eq $md5 ) {
685             &notice("Current twirssi seems to be up to date.");
686             return;
687         }
688     }
689
690     my $URL = "http://twirssi.com/twirssi.pl";
691     &notice("Downloading twirssi from $URL");
692     LWP::Simple::getstore( $URL, "$loc.upgrade" );
693
694     unless ($data) {
695         unless ( open( NEW, "$loc.upgrade" ) ) {
696             &notice(
697 "Failed to read $loc.upgrade.  Check that /set twirssi_location is set to the correct location."
698             );
699             return;
700         }
701
702         my $new_md5 = Digest::MD5::md5_hex(<NEW>);
703         close NEW;
704
705         if ( $new_md5 ne $md5 ) {
706             &notice("MD5 verification failed. expected $md5, got $new_md5");
707             return;
708         }
709     }
710
711     rename $loc, "$loc.backup"
712       or &notice("Failed to back up $loc: $!.  Aborting")
713       and return;
714     rename "$loc.upgrade", $loc
715       or &notice("Failed to rename $loc.upgrade: $!.  Aborting")
716       and return;
717
718     my ( $dir, $file ) = ( $loc =~ m{(.*)/([^/]+)$} );
719     if ( -e "$dir/autorun/$file" ) {
720         &notice("Updating $dir/autorun/$file");
721         unlink "$dir/autorun/$file"
722           or &notice("Failed to remove old $file from autorun: $!");
723         symlink "../$file", "$dir/autorun/$file"
724           or &notice("Failed to create symlink in autorun directory: $!");
725     }
726
727     &notice("Download complete.  Reload twirssi with /script load $file");
728 }
729
730 sub load_friends {
731     my $fh   = shift;
732     my $page = 1;
733     my %new_friends;
734     eval {
735         while (1)
736         {
737             print $fh "type:debug Loading friends page $page...\n"
738               if ( $fh and &debug );
739             my $friends = $twit->friends( { page => $page } );
740             last unless $friends;
741             $new_friends{ $_->{screen_name} } = time foreach @$friends;
742             $page++;
743             last if @$friends == 0 or $page == 10;
744         }
745     };
746
747     if ($@) {
748         print $fh "type:debug Error during friends list update.  Aborted.\n";
749         return;
750     }
751
752     my ( $added, $removed ) = ( 0, 0 );
753     print $fh "type:debug Scanning for new friends...\n" if ( $fh and &debug );
754     foreach ( keys %new_friends ) {
755         next if exists $friends{$_};
756         $friends{$_} = time;
757         $added++;
758     }
759
760     print $fh "type:debug Scanning for removed friends...\n"
761       if ( $fh and &debug );
762     foreach ( keys %friends ) {
763         next if exists $new_friends{$_};
764         delete $friends{$_};
765         $removed++;
766     }
767
768     return ( $added, $removed );
769 }
770
771 sub get_updates {
772     print scalar localtime, " - get_updates starting" if &debug;
773
774     $window =
775       Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
776     unless ($window) {
777         Irssi::active_win()
778           ->print( "Can't find a window named '"
779               . Irssi::settings_get_str('twitter_window')
780               . "'.  Create it or change the value of twitter_window" );
781     }
782
783     return unless &logged_in($twit);
784
785     my ( $fh, $filename ) = File::Temp::tempfile();
786     binmode($fh, ":utf8");
787     my $pid = fork();
788
789     if ($pid) {    # parent
790         Irssi::timeout_add_once( 5000, 'monitor_child', [ $filename, 0 ] );
791         Irssi::pidwait_add($pid);
792     } elsif ( defined $pid ) {    # child
793         close STDIN;
794         close STDOUT;
795         close STDERR;
796
797         my $new_poll = time;
798
799         my $error = 0;
800         $error += &do_updates( $fh, $user, $twit );
801         foreach ( keys %twits ) {
802             next if $_ eq $user;
803             $error += &do_updates( $fh, $_, $twits{$_} );
804         }
805
806         my ( $added, $removed ) = &load_friends($fh);
807         if ( $added + $removed ) {
808             print $fh "type:debug %R***%n Friends list updated: ",
809               join( ", ",
810                 sprintf( "%d added",   $added ),
811                 sprintf( "%d removed", $removed ) ),
812               "\n";
813         }
814         print $fh "__friends__\n";
815         foreach ( sort keys %friends ) {
816             print $fh "$_ $friends{$_}\n";
817         }
818
819         if ($error) {
820             print $fh "type:debug Update encountered errors.  Aborted\n";
821             print $fh $last_poll;
822         } else {
823             print $fh $new_poll;
824         }
825         close $fh;
826         exit;
827     }
828     print scalar localtime, " - get_updates ends" if &debug;
829 }
830
831 sub do_updates {
832     my ( $fh, $username, $obj ) = @_;
833
834     my $rate_limit = $obj->rate_limit_status();
835     if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
836         &notice("Rate limit exceeded for $username");
837         return 1;
838     }
839
840     print scalar localtime, " - Polling for updates for $username" if &debug;
841     my $tweets;
842     eval {
843         $tweets = $obj->friends_timeline(
844             { since => HTTP::Date::time2str($last_poll) } );
845     };
846
847     if ($@) {
848         print $fh
849           "type:debug Error during friends_timeline call: $@.  Aborted.\n";
850         return 1;
851     }
852
853     unless ( ref $tweets ) {
854         if ( $obj->can("get_error") ) {
855             my $error;
856             eval { $error = JSON::Any->jsonToObj( $obj->get_error() ) };
857             if ($@) { $error = $obj->get_error() }
858             print $fh "type:debug API Error during friends_timeline call: ",
859               "$error  Aborted.\n";
860         } else {
861             print $fh
862               "type:debug API Error during friends_timeline call. Aborted.\n";
863         }
864         return 1;
865     }
866
867     foreach my $t ( reverse @$tweets ) {
868         my $text = decode_entities( $t->{text} );
869         $text = &hilight($text);
870         my $reply = "tweet";
871         if (    Irssi::settings_get_bool("show_reply_context")
872             and $t->{in_reply_to_screen_name} ne $username
873             and $t->{in_reply_to_screen_name}
874             and not exists $friends{ $t->{in_reply_to_screen_name} } )
875         {
876             $nicks{ $t->{in_reply_to_screen_name} } = time;
877             my $context;
878             eval {
879                 $context = $obj->show_status( $t->{in_reply_to_status_id} );
880             };
881
882             if ($context) {
883                 my $ctext = decode_entities( $context->{text} );
884                 $ctext = &hilight($ctext);
885                 printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
886                   $context->{id}, $username,
887                   $context->{user}{screen_name}, $ctext;
888                 $reply = "reply";
889             } elsif ($@) {
890                 print $fh "type:debug request to get context failed: $@";
891             } else {
892                 print $fh
893 "type:debug Failed to get context from $t->{in_reply_to_screen_name}\n"
894                   if &debug;
895             }
896         }
897         next
898           if $t->{user}{screen_name} eq $username
899               and not Irssi::settings_get_bool("show_own_tweets");
900         printf $fh "id:%d account:%s nick:%s type:%s %s\n",
901           $t->{id}, $username, $t->{user}{screen_name}, $reply, $text;
902     }
903
904     print scalar localtime, " - Polling for replies" if &debug;
905     eval {
906         $tweets = $obj->replies( { since => HTTP::Date::time2str($last_poll) } )
907           || [];
908     };
909
910     if ($@) {
911         print $fh "type:debug Error during replies call.  Aborted.\n";
912         return 1;
913     }
914
915     foreach my $t ( reverse @$tweets ) {
916         next
917           if exists $friends{ $t->{user}{screen_name} };
918
919         my $text = decode_entities( $t->{text} );
920         $text = &hilight($text);
921         printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
922           $t->{id}, $username, $t->{user}{screen_name}, $text;
923     }
924
925     print scalar localtime, " - Polling for DMs" if &debug;
926     eval {
927         $tweets =
928           $obj->direct_messages( { since => HTTP::Date::time2str($last_poll) } )
929           || [];
930     };
931
932     if ($@) {
933         print $fh "type:debug Error during direct_messages call.  Aborted.\n";
934         return 1;
935     }
936
937     foreach my $t ( reverse @$tweets ) {
938         my $text = decode_entities( $t->{text} );
939         $text = &hilight($text);
940         printf $fh "id:%d account:%s nick:%s type:dm %s\n",
941           $t->{id}, $username, $t->{sender_screen_name}, $text;
942     }
943
944     print scalar localtime, " - Polling for subscriptions" if &debug;
945     if ( $obj->can('search') and $id_map{__searches}{$username} ) {
946         my $search;
947         foreach my $topic ( sort keys %{ $id_map{__searches}{$username} } ) {
948             print $fh "type:debug searching for $topic since ",
949               "$id_map{__searches}{$username}{$topic}\n";
950             eval {
951                 $search = $obj->search(
952                     {
953                         q        => $topic,
954                         since_id => $id_map{__searches}{$username}{$topic}
955                     }
956                 );
957             };
958
959             if ($@) {
960                 print $fh
961                   "type:debug Error during search($topic) call.  Aborted.\n";
962                 return 1;
963             }
964
965             unless ( $search->{max_id} ) {
966                 print $fh
967 "type:debug Invalid search results when searching for $topic.",
968                   "  Aborted.\n";
969                 return 1;
970             }
971
972             $id_map{__searches}{$username}{$topic} = $search->{max_id};
973             printf $fh "id:%d account:%s type:searchid topic:%s\n",
974               $search->{max_id}, $username, $topic;
975
976             foreach my $t ( reverse @{ $search->{results} } ) {
977                 my $text = decode_entities( $t->{text} );
978                 $text = &hilight($text);
979                 printf $fh "id:%d account:%s nick:%s type:search topic:%s %s\n",
980                   $t->{id}, $username, $t->{from_user}, $topic, $text;
981             }
982         }
983     }
984
985     print scalar localtime, " - Done" if &debug;
986
987     return 0;
988 }
989
990 sub monitor_child {
991     my ($data)   = @_;
992     my $filename = $data->[0];
993     my $attempt  = $data->[1];
994
995     print scalar localtime, " - checking child log at $filename ($attempt)"
996       if &debug;
997     my $new_last_poll;
998     if ( open FILE, $filename ) {
999         my @lines;
1000         while (<FILE>) {
1001             chomp;
1002             last if /^__friends__/;
1003             my $hilight = 0;
1004             my %meta;
1005             foreach my $key (qw/id account nick type topic/) {
1006                 if (s/^$key:(\S+)\s*//) {
1007                     $meta{$key} = $1;
1008                 }
1009             }
1010
1011             if ( not $meta{type} or $meta{type} ne 'searchid' ) {
1012                 next if exists $meta{id} and exists $tweet_cache{ $meta{id} };
1013                 $tweet_cache{ $meta{id} } = time;
1014             }
1015
1016             my $account = "";
1017             if ( $meta{account} ne $user ) {
1018                 $account = "$meta{account}: ";
1019             }
1020
1021             my $marker = "";
1022             if (    $meta{type} ne 'dm'
1023                 and Irssi::settings_get_bool("twirssi_track_replies")
1024                 and $meta{nick}
1025                 and $meta{id} )
1026             {
1027                 $marker = ( $id_map{__indexes}{ $meta{nick} } + 1 ) % 100;
1028                 $id_map{ lc $meta{nick} }[$marker] = $meta{id};
1029                 $id_map{__indexes}{ $meta{nick} }  = $marker;
1030                 $marker                            = ":$marker";
1031             }
1032
1033             my $hilight_color =
1034               $irssi_to_mirc_colors{ Irssi::settings_get_str("hilight_color") };
1035             if ( ( $_ =~ /\@$meta{account}\W/i )
1036                 && Irssi::settings_get_bool("twirssi_hilights") )
1037             {
1038                 $meta{nick} = "\cC$hilight_color$meta{nick}\cO";
1039                 $hilight = MSGLEVEL_HILIGHT;
1040             }
1041
1042             if ( $meta{type} =~ /tweet|reply/ ) {
1043                 push @lines,
1044                   [
1045                     ( MSGLEVEL_PUBLIC | $hilight ),
1046                     $meta{type}, $account, $meta{nick}, $marker, $_
1047                   ];
1048             } elsif ( $meta{type} eq 'search' ) {
1049                 push @lines,
1050                   [
1051                     ( MSGLEVEL_PUBLIC | $hilight ),
1052                     $meta{type}, $account, $meta{topic},
1053                     $meta{nick}, $marker,  $_
1054                   ];
1055                 if ( $meta{id} >
1056                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
1057                 {
1058                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
1059                       $meta{id};
1060                 }
1061             } elsif ( $meta{type} eq 'dm' ) {
1062                 push @lines,
1063                   [
1064                     ( MSGLEVEL_MSGS | $hilight ),
1065                     $meta{type}, $account, $meta{nick}, $_
1066                   ];
1067             } elsif ( $meta{type} eq 'searchid' ) {
1068                 print "Search '$meta{topic}' returned id $meta{id}" if &debug;
1069                 if ( $meta{id} >=
1070                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
1071                 {
1072                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
1073                       $meta{id};
1074                 } elsif (&debug) {
1075                     print "Search '$meta{topic}' returned invalid id $meta{id}";
1076                 }
1077             } elsif ( $meta{type} eq 'error' ) {
1078                 push @lines, [ MSGLEVEL_MSGS, $_ ];
1079             } elsif ( $meta{type} eq 'debug' ) {
1080                 print "$_" if &debug,;
1081             } else {
1082                 print "Unknown line type $meta{type}: $_" if &debug,;
1083             }
1084         }
1085
1086         %friends = ();
1087         while (<FILE>) {
1088             if (/^\d+$/) {
1089                 $new_last_poll = $_;
1090                 last;
1091             }
1092             my ( $f, $t ) = split ' ', $_;
1093             $nicks{$f} = $friends{$f} = $t;
1094         }
1095
1096         if ($new_last_poll) {
1097             print "new last_poll = $new_last_poll" if &debug;
1098             for my $line (@lines) {
1099                 $window->printformat(
1100                     $line->[0],
1101                     "twirssi_" . $line->[1],
1102                     @$line[ 2 .. $#$line ]
1103                 );
1104             }
1105
1106             close FILE;
1107             unlink $filename
1108               or warn "Failed to remove $filename: $!"
1109               unless &debug;
1110
1111             # keep enough cached tweets, to make sure we don't show duplicates.
1112             foreach ( keys %tweet_cache ) {
1113                 next if $tweet_cache{$_} >= $last_poll;
1114                 delete $tweet_cache{$_};
1115             }
1116             $last_poll = $new_last_poll;
1117
1118             # save id_map hash
1119             if ( keys %id_map
1120                 and my $file =
1121                 Irssi::settings_get_str("twirssi_replies_store") )
1122             {
1123                 if ( open JSON, ">$file" ) {
1124                     print JSON JSON::Any->objToJson( \%id_map );
1125                     close JSON;
1126                 } else {
1127                     &notice("Failed to write replies to $file: $!");
1128                 }
1129             }
1130             return;
1131         }
1132     }
1133
1134     close FILE;
1135
1136     if ( $attempt < 24 ) {
1137         Irssi::timeout_add_once( 5000, 'monitor_child',
1138             [ $filename, $attempt + 1 ] );
1139     } else {
1140         print "Giving up on polling $filename" if &debug;
1141         unlink $filename unless &debug;
1142
1143         return unless Irssi::settings_get_bool("twirssi_notify_timeouts");
1144
1145         my $since;
1146         my @time = localtime($last_poll);
1147         if ( time - $last_poll < 24 * 60 * 60 ) {
1148             $since = sprintf( "%d:%02d", @time[ 2, 1 ] );
1149         } else {
1150             $since = scalar localtime($last_poll);
1151         }
1152         &notice("Haven't been able to get updated tweets since $since");
1153     }
1154 }
1155
1156 sub debug {
1157     return Irssi::settings_get_bool("twirssi_debug");
1158 }
1159
1160 sub notice {
1161     $window->print( "%R***%n @_", MSGLEVEL_PUBLIC );
1162 }
1163
1164 sub update_away {
1165     my $data = shift;
1166
1167     if (    Irssi::settings_get_bool("tweet_to_away")
1168         and $data !~ /\@\w/
1169         and $data !~ /^[dD] / )
1170     {
1171         my $server =
1172           Irssi::server_find_tag( Irssi::settings_get_str("bitlbee_server") );
1173         if ($server) {
1174             $server->send_raw("away :$data");
1175             return 1;
1176         } else {
1177             &notice( "Can't find bitlbee server.",
1178                 "Update bitlbee_server or disable tweet_to_away" );
1179             return 0;
1180         }
1181     }
1182
1183     return 0;
1184 }
1185
1186 sub too_long {
1187     my $data    = shift;
1188     my $noalert = shift;
1189
1190     if ( length $data > 140 ) {
1191         &notice( "Tweet too long (" . length($data) . " characters) - aborted" )
1192           unless $noalert;
1193         return 1;
1194     }
1195
1196     return 0;
1197 }
1198
1199 sub valid_username {
1200     my $username = shift;
1201
1202     unless ( exists $twits{$username} ) {
1203         &notice("Unknown username $username");
1204         return 0;
1205     }
1206
1207     return 1;
1208 }
1209
1210 sub logged_in {
1211     my $obj = shift;
1212     unless ($obj) {
1213         &notice("Not logged in!  Use /twitter_login username pass!");
1214         return 0;
1215     }
1216
1217     return 1;
1218 }
1219
1220 sub sig_complete {
1221     my ( $complist, $window, $word, $linestart, $want_space ) = @_;
1222
1223     if (
1224         $linestart =~ /^\/twitter_reply(?:_as)?\s*$/
1225         or ( Irssi::settings_get_bool("twirssi_use_reply_aliases")
1226             and $linestart =~ /^\/reply(?:_as)?\s*$/ )
1227       )
1228     {    # /twitter_reply gets a nick:num
1229         $word =~ s/^@//;
1230         @$complist = map { "$_:$id_map{__indexes}{$_}" } grep /^\Q$word/i,
1231           sort keys %{ $id_map{__indexes} };
1232     }
1233
1234     # /tweet, /tweet_as, /dm, /dm_as - complete @nicks (and nicks as the first
1235     # arg to dm)
1236     if ( $linestart =~ /^\/(?:tweet|dm)/ ) {
1237         my $prefix = $word =~ s/^@//;
1238         $prefix = 0 if $linestart eq '/dm' or $linestart eq '/dm_as';
1239         push @$complist, grep /^\Q$word/i,
1240           sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1241         @$complist = map { "\@$_" } @$complist if $prefix;
1242     }
1243 }
1244
1245 sub event_send_text {
1246     my ( $line, $server, $win ) = @_;
1247     my $awin = Irssi::active_win();
1248
1249     # if the window where we got our text was the twitter window, and the user
1250     # wants to be lazy, tweet away!
1251     if ( ( $awin->get_active_name() eq $window->{name} )
1252         and Irssi::settings_get_bool("tweet_window_input") )
1253     {
1254         &cmd_tweet( $line, $server, $win );
1255     }
1256 }
1257
1258 sub get_poll_time {
1259     my $poll = Irssi::settings_get_int("twitter_poll_interval");
1260     return $poll if $poll >= 60;
1261     return 60;
1262 }
1263
1264 sub hilight {
1265     my $text = shift;
1266
1267     if ( Irssi::settings_get_str("twirssi_nick_color") ) {
1268         my $c = Irssi::settings_get_str("twirssi_nick_color");
1269         $c = $irssi_to_mirc_colors{$c};
1270         $text =~ s/(^|\W)\@([-\w]+)/$1\cC$c\@$2\cO/g if $c;
1271     }
1272     if ( Irssi::settings_get_str("twirssi_topic_color") ) {
1273         my $c = Irssi::settings_get_str("twirssi_topic_color");
1274         $c = $irssi_to_mirc_colors{$c};
1275         $text =~ s/(^|\W)\#([-\w]+)/$1\cC$c\#$2\cO/g if $c;
1276     }
1277     $text =~ s/[\n\r]/ /g;
1278
1279     return $text;
1280 }
1281
1282 Irssi::signal_add( "send text", "event_send_text" );
1283
1284 Irssi::theme_register(
1285     [
1286         'twirssi_tweet',  '[$0%B@$1%n$2] $3',
1287         'twirssi_search', '[$0%r$1%n:%B@$2%n$3] $4',
1288         'twirssi_reply',  '[$0\--> %B@$1%n$2] $3',
1289         'twirssi_dm',     '[$0%r@$1%n (%WDM%n)] $2',
1290         'twirssi_error',  'ERROR: $0',
1291     ]
1292 );
1293
1294 Irssi::settings_add_int( "twirssi", "twitter_poll_interval", 300 );
1295 Irssi::settings_add_str( "twirssi", "twitter_window",     "twitter" );
1296 Irssi::settings_add_str( "twirssi", "bitlbee_server",     "bitlbee" );
1297 Irssi::settings_add_str( "twirssi", "short_url_provider", "TinyURL" );
1298 Irssi::settings_add_str( "twirssi", "twirssi_location",
1299     ".irssi/scripts/twirssi.pl" );
1300 Irssi::settings_add_str( "twirssi", "twitter_usernames", undef );
1301 Irssi::settings_add_str( "twirssi", "twitter_passwords", undef );
1302 Irssi::settings_add_str( "twirssi", "twirssi_replies_store",
1303     ".irssi/scripts/twirssi.json" );
1304 Irssi::settings_add_str( "twirssi", "twirssi_nick_color",  "%B" );
1305 Irssi::settings_add_str( "twirssi", "twirssi_topic_color", "%r" );
1306 Irssi::settings_add_bool( "twirssi", "tweet_to_away",             0 );
1307 Irssi::settings_add_bool( "twirssi", "show_reply_context",        0 );
1308 Irssi::settings_add_bool( "twirssi", "show_own_tweets",           1 );
1309 Irssi::settings_add_bool( "twirssi", "twirssi_debug",             0 );
1310 Irssi::settings_add_bool( "twirssi", "twirssi_first_run",         1 );
1311 Irssi::settings_add_bool( "twirssi", "twirssi_track_replies",     1 );
1312 Irssi::settings_add_bool( "twirssi", "twirssi_replies_autonick",  1 );
1313 Irssi::settings_add_bool( "twirssi", "twirssi_use_reply_aliases", 0 );
1314 Irssi::settings_add_bool( "twirssi", "twirssi_notify_timeouts",   1 );
1315 Irssi::settings_add_bool( "twirssi", "twirssi_hilights",          1 );
1316 Irssi::settings_add_bool( "twirssi", "tweet_window_input",        0 );
1317
1318 $last_poll = time - &get_poll_time;
1319 $window = Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
1320 if ( !$window ) {
1321     $window =
1322       Irssi::Windowitem::window_create(
1323         Irssi::settings_get_str('twitter_window'), 1 );
1324     $window->set_name( Irssi::settings_get_str('twitter_window') );
1325 }
1326
1327 if ($window) {
1328     Irssi::command_bind( "dm",                         "cmd_direct" );
1329     Irssi::command_bind( "dm_as",                      "cmd_direct_as" );
1330     Irssi::command_bind( "tweet",                      "cmd_tweet" );
1331     Irssi::command_bind( "dent",                       "cmd_tweet" );
1332     Irssi::command_bind( "tweet_as",                   "cmd_tweet_as" );
1333     Irssi::command_bind( "dent_as",                   "cmd_tweet_as" );
1334     Irssi::command_bind( "twitter_reply",              "cmd_reply" );
1335     Irssi::command_bind( "identica_reply",             "cmd_reply" );
1336     Irssi::command_bind( "twitter_reply_as",           "cmd_reply_as" );
1337     Irssi::command_bind( "identica_reply_as",          "cmd_reply_as" );
1338     Irssi::command_bind( "twitter_login",              "cmd_login_twitter" );
1339     Irssi::command_bind( "twitter_logout",             "cmd_logout_twitter" );
1340     Irssi::command_bind( "identica_login",             "cmd_login_identica" );
1341     Irssi::command_bind( "identica_logout",            "cmd_logout_identica" );
1342     Irssi::command_bind( "twitter_switch",             "cmd_switch" );
1343     Irssi::command_bind( "twitter_subscribe",          "cmd_add_search_twitter" );
1344     Irssi::command_bind( "identica_subscribe",         "cmd_add_search_identica" );
1345     Irssi::command_bind( "twitter_unsubscribe",        "cmd_del_search_twitter" );
1346     Irssi::command_bind( "identica_unsubscribe",       "cmd_del_search_identica" );
1347     Irssi::command_bind( "twitter_list_subscriptions", "cmd_list_search" );
1348     Irssi::command_bind( "twirssi_upgrade",            "cmd_upgrade" );
1349     if ( Irssi::settings_get_bool("twirssi_use_reply_aliases") ) {
1350         Irssi::command_bind( "reply",    "cmd_reply" );
1351         Irssi::command_bind( "reply_as", "cmd_reply_as" );
1352     }
1353     Irssi::command_bind(
1354         "twirssi_dump",
1355         sub {
1356             print "twits: ", join ", ",
1357               map { "u: $_->{username}" } values %twits;
1358             print "friends: ", join ", ", sort keys %friends;
1359             print "nicks: ",   join ", ", sort keys %nicks;
1360             print "searches: ", Dumper \%{ $id_map{__searches} };
1361             print "last poll: $last_poll";
1362         }
1363     );
1364     Irssi::command_bind(
1365         "twirssi_version",
1366         sub {
1367             &notice("Twirssi v$VERSION (r$REV); "
1368                   . "Net::Identica v$Net::Identica::VERSION. "
1369                   . "Net::Twitter v$Net::Twitter::VERSION."
1370                   . "JSON in use: "
1371                   . JSON::Any::handler()
1372                   . ".  See details at http://twirssi.com/" );
1373         }
1374     );
1375     Irssi::command_bind(
1376         "twitter_friend",
1377         &gen_cmd(
1378             "/twitter_friend <username>",
1379             "create_friend",
1380             sub { &notice("Following $_[0]"); $nicks{ $_[0] } = time; }
1381         )
1382     );
1383     Irssi::command_bind(
1384         "twitter_unfriend",
1385         &gen_cmd(
1386             "/twitter_unfriend <username>",
1387             "destroy_friend",
1388             sub { &notice("Stopped following $_[0]"); delete $nicks{ $_[0] }; }
1389         )
1390     );
1391     Irssi::command_bind( "twitter_updates", "get_updates" );
1392     Irssi::signal_add_last( 'complete word' => \&sig_complete );
1393
1394     &notice("  %Y<%C(%B^%C)%N                   TWIRSSI v%R$VERSION%N (r$REV)");
1395     &notice("   %C(_(\\%N           http://twirssi.com/ for full docs");
1396     &notice(
1397         "    %Y||%C `%N Log in with /twitter_login or /identica_login, send updates with /tweet or /dent");
1398
1399     my $file = Irssi::settings_get_str("twirssi_replies_store");
1400     if ( $file and -r $file ) {
1401         if ( open( JSON, $file ) ) {
1402             local $/;
1403             my $json = <JSON>;
1404             close JSON;
1405             eval {
1406                 my $ref = JSON::Any->jsonToObj($json);
1407                 %id_map = %$ref;
1408                 my $num = keys %{ $id_map{__indexes} };
1409                 &notice( sprintf "Loaded old replies from %d contact%s.",
1410                     $num, ( $num == 1 ? "" : "s" ) );
1411             };
1412         } else {
1413             &notice("Failed to load old replies from $file: $!");
1414         }
1415     }
1416
1417     if ( my $provider = Irssi::settings_get_str("short_url_provider") ) {
1418         eval "use WWW::Shorten::$provider;";
1419
1420         if ($@) {
1421             &notice(
1422 "Failed to load WWW::Shorten::$provider - either clear short_url_provider or install the CPAN module"
1423             );
1424         }
1425     }
1426
1427     if (    my $autouser = Irssi::settings_get_str("twitter_usernames_twitter")
1428         and my $autopass = Irssi::settings_get_str("twitter_passwords_twitter") )
1429     {
1430         &cmd_login_twitter();
1431     }
1432
1433     if (    my $autouser = Irssi::settings_get_str("twitter_usernames_identica")
1434         and my $autopass = Irssi::settings_get_str("twitter_passwords_identica") )
1435     {
1436         &cmd_login_identica();
1437     }
1438
1439 } else {
1440     Irssi::active_win()
1441       ->print( "Create a window named "
1442           . Irssi::settings_get_str('twitter_window')
1443           . " or change the value of twitter_window.  Then, reload twirssi." );
1444 }