added preliminary support for identi.ca
[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: 483 $' =~ /(\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-20 14:37:28 -0800 (Fri, 20 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     my $pid = fork();
787
788     if ($pid) {    # parent
789         Irssi::timeout_add_once( 5000, 'monitor_child', [ $filename, 0 ] );
790         Irssi::pidwait_add($pid);
791     } elsif ( defined $pid ) {    # child
792         close STDIN;
793         close STDOUT;
794         close STDERR;
795
796         my $new_poll = time;
797
798         my $error = 0;
799         $error += &do_updates( $fh, $user, $twit );
800         foreach ( keys %twits ) {
801             next if $_ eq $user;
802             $error += &do_updates( $fh, $_, $twits{$_} );
803         }
804
805         my ( $added, $removed ) = &load_friends($fh);
806         if ( $added + $removed ) {
807             print $fh "type:debug %R***%n Friends list updated: ",
808               join( ", ",
809                 sprintf( "%d added",   $added ),
810                 sprintf( "%d removed", $removed ) ),
811               "\n";
812         }
813         print $fh "__friends__\n";
814         foreach ( sort keys %friends ) {
815             print $fh "$_ $friends{$_}\n";
816         }
817
818         if ($error) {
819             print $fh "type:debug Update encountered errors.  Aborted\n";
820             print $fh $last_poll;
821         } else {
822             print $fh $new_poll;
823         }
824         close $fh;
825         exit;
826     }
827     print scalar localtime, " - get_updates ends" if &debug;
828 }
829
830 sub do_updates {
831     my ( $fh, $username, $obj ) = @_;
832
833     my $rate_limit = $obj->rate_limit_status();
834     if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
835         &notice("Rate limit exceeded for $username");
836         return 1;
837     }
838
839     print scalar localtime, " - Polling for updates for $username" if &debug;
840     my $tweets;
841     eval {
842         $tweets = $obj->friends_timeline(
843             { since => HTTP::Date::time2str($last_poll) } );
844     };
845
846     if ($@) {
847         print $fh
848           "type:debug Error during friends_timeline call: $@.  Aborted.\n";
849         return 1;
850     }
851
852     unless ( ref $tweets ) {
853         if ( $obj->can("get_error") ) {
854             my $error;
855             eval { $error = JSON::Any->jsonToObj( $obj->get_error() ) };
856             if ($@) { $error = $obj->get_error() }
857             print $fh "type:debug API Error during friends_timeline call: ",
858               "$error  Aborted.\n";
859         } else {
860             print $fh
861               "type:debug API Error during friends_timeline call. Aborted.\n";
862         }
863         return 1;
864     }
865
866     foreach my $t ( reverse @$tweets ) {
867         my $text = decode_entities( $t->{text} );
868         $text = &hilight($text);
869         my $reply = "tweet";
870         if (    Irssi::settings_get_bool("show_reply_context")
871             and $t->{in_reply_to_screen_name} ne $username
872             and $t->{in_reply_to_screen_name}
873             and not exists $friends{ $t->{in_reply_to_screen_name} } )
874         {
875             $nicks{ $t->{in_reply_to_screen_name} } = time;
876             my $context;
877             eval {
878                 $context = $obj->show_status( $t->{in_reply_to_status_id} );
879             };
880
881             if ($context) {
882                 my $ctext = decode_entities( $context->{text} );
883                 $ctext = &hilight($ctext);
884                 printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
885                   $context->{id}, $username,
886                   $context->{user}{screen_name}, $ctext;
887                 $reply = "reply";
888             } elsif ($@) {
889                 print $fh "type:debug request to get context failed: $@";
890             } else {
891                 print $fh
892 "type:debug Failed to get context from $t->{in_reply_to_screen_name}\n"
893                   if &debug;
894             }
895         }
896         next
897           if $t->{user}{screen_name} eq $username
898               and not Irssi::settings_get_bool("show_own_tweets");
899         printf $fh "id:%d account:%s nick:%s type:%s %s\n",
900           $t->{id}, $username, $t->{user}{screen_name}, $reply, $text;
901     }
902
903     print scalar localtime, " - Polling for replies" if &debug;
904     eval {
905         $tweets = $obj->replies( { since => HTTP::Date::time2str($last_poll) } )
906           || [];
907     };
908
909     if ($@) {
910         print $fh "type:debug Error during replies call.  Aborted.\n";
911         return 1;
912     }
913
914     foreach my $t ( reverse @$tweets ) {
915         next
916           if exists $friends{ $t->{user}{screen_name} };
917
918         my $text = decode_entities( $t->{text} );
919         $text = &hilight($text);
920         printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
921           $t->{id}, $username, $t->{user}{screen_name}, $text;
922     }
923
924     print scalar localtime, " - Polling for DMs" if &debug;
925     eval {
926         $tweets =
927           $obj->direct_messages( { since => HTTP::Date::time2str($last_poll) } )
928           || [];
929     };
930
931     if ($@) {
932         print $fh "type:debug Error during direct_messages call.  Aborted.\n";
933         return 1;
934     }
935
936     foreach my $t ( reverse @$tweets ) {
937         my $text = decode_entities( $t->{text} );
938         $text = &hilight($text);
939         printf $fh "id:%d account:%s nick:%s type:dm %s\n",
940           $t->{id}, $username, $t->{sender_screen_name}, $text;
941     }
942
943     print scalar localtime, " - Polling for subscriptions" if &debug;
944     if ( $obj->can('search') and $id_map{__searches}{$username} ) {
945         my $search;
946         foreach my $topic ( sort keys %{ $id_map{__searches}{$username} } ) {
947             print $fh "type:debug searching for $topic since ",
948               "$id_map{__searches}{$username}{$topic}\n";
949             eval {
950                 $search = $obj->search(
951                     {
952                         q        => $topic,
953                         since_id => $id_map{__searches}{$username}{$topic}
954                     }
955                 );
956             };
957
958             if ($@) {
959                 print $fh
960                   "type:debug Error during search($topic) call.  Aborted.\n";
961                 return 1;
962             }
963
964             unless ( $search->{max_id} ) {
965                 print $fh
966 "type:debug Invalid search results when searching for $topic.",
967                   "  Aborted.\n";
968                 return 1;
969             }
970
971             $id_map{__searches}{$username}{$topic} = $search->{max_id};
972             printf $fh "id:%d account:%s type:searchid topic:%s\n",
973               $search->{max_id}, $username, $topic;
974
975             foreach my $t ( reverse @{ $search->{results} } ) {
976                 my $text = decode_entities( $t->{text} );
977                 $text = &hilight($text);
978                 printf $fh "id:%d account:%s nick:%s type:search topic:%s %s\n",
979                   $t->{id}, $username, $t->{from_user}, $topic, $text;
980             }
981         }
982     }
983
984     print scalar localtime, " - Done" if &debug;
985
986     return 0;
987 }
988
989 sub monitor_child {
990     my ($data)   = @_;
991     my $filename = $data->[0];
992     my $attempt  = $data->[1];
993
994     print scalar localtime, " - checking child log at $filename ($attempt)"
995       if &debug;
996     my $new_last_poll;
997     if ( open FILE, $filename ) {
998         my @lines;
999         while (<FILE>) {
1000             chomp;
1001             last if /^__friends__/;
1002             my $hilight = 0;
1003             my %meta;
1004             foreach my $key (qw/id account nick type topic/) {
1005                 if (s/^$key:(\S+)\s*//) {
1006                     $meta{$key} = $1;
1007                 }
1008             }
1009
1010             if ( not $meta{type} or $meta{type} ne 'searchid' ) {
1011                 next if exists $meta{id} and exists $tweet_cache{ $meta{id} };
1012                 $tweet_cache{ $meta{id} } = time;
1013             }
1014
1015             my $account = "";
1016             if ( $meta{account} ne $user ) {
1017                 $account = "$meta{account}: ";
1018             }
1019
1020             my $marker = "";
1021             if (    $meta{type} ne 'dm'
1022                 and Irssi::settings_get_bool("twirssi_track_replies")
1023                 and $meta{nick}
1024                 and $meta{id} )
1025             {
1026                 $marker = ( $id_map{__indexes}{ $meta{nick} } + 1 ) % 100;
1027                 $id_map{ lc $meta{nick} }[$marker] = $meta{id};
1028                 $id_map{__indexes}{ $meta{nick} }  = $marker;
1029                 $marker                            = ":$marker";
1030             }
1031
1032             my $hilight_color =
1033               $irssi_to_mirc_colors{ Irssi::settings_get_str("hilight_color") };
1034             if ( ( $_ =~ /\@$meta{account}\W/i )
1035                 && Irssi::settings_get_bool("twirssi_hilights") )
1036             {
1037                 $meta{nick} = "\cC$hilight_color$meta{nick}\cO";
1038                 $hilight = MSGLEVEL_HILIGHT;
1039             }
1040
1041             if ( $meta{type} =~ /tweet|reply/ ) {
1042                 push @lines,
1043                   [
1044                     ( MSGLEVEL_PUBLIC | $hilight ),
1045                     $meta{type}, $account, $meta{nick}, $marker, $_
1046                   ];
1047             } elsif ( $meta{type} eq 'search' ) {
1048                 push @lines,
1049                   [
1050                     ( MSGLEVEL_PUBLIC | $hilight ),
1051                     $meta{type}, $account, $meta{topic},
1052                     $meta{nick}, $marker,  $_
1053                   ];
1054                 if ( $meta{id} >
1055                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
1056                 {
1057                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
1058                       $meta{id};
1059                 }
1060             } elsif ( $meta{type} eq 'dm' ) {
1061                 push @lines,
1062                   [
1063                     ( MSGLEVEL_MSGS | $hilight ),
1064                     $meta{type}, $account, $meta{nick}, $_
1065                   ];
1066             } elsif ( $meta{type} eq 'searchid' ) {
1067                 print "Search '$meta{topic}' returned id $meta{id}" if &debug;
1068                 if ( $meta{id} >=
1069                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
1070                 {
1071                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
1072                       $meta{id};
1073                 } elsif (&debug) {
1074                     print "Search '$meta{topic}' returned invalid id $meta{id}";
1075                 }
1076             } elsif ( $meta{type} eq 'error' ) {
1077                 push @lines, [ MSGLEVEL_MSGS, $_ ];
1078             } elsif ( $meta{type} eq 'debug' ) {
1079                 print "$_" if &debug,;
1080             } else {
1081                 print "Unknown line type $meta{type}: $_" if &debug,;
1082             }
1083         }
1084
1085         %friends = ();
1086         while (<FILE>) {
1087             if (/^\d+$/) {
1088                 $new_last_poll = $_;
1089                 last;
1090             }
1091             my ( $f, $t ) = split ' ', $_;
1092             $nicks{$f} = $friends{$f} = $t;
1093         }
1094
1095         if ($new_last_poll) {
1096             print "new last_poll = $new_last_poll" if &debug;
1097             for my $line (@lines) {
1098                 $window->printformat(
1099                     $line->[0],
1100                     "twirssi_" . $line->[1],
1101                     @$line[ 2 .. $#$line ]
1102                 );
1103             }
1104
1105             close FILE;
1106             unlink $filename
1107               or warn "Failed to remove $filename: $!"
1108               unless &debug;
1109
1110             # keep enough cached tweets, to make sure we don't show duplicates.
1111             foreach ( keys %tweet_cache ) {
1112                 next if $tweet_cache{$_} >= $last_poll;
1113                 delete $tweet_cache{$_};
1114             }
1115             $last_poll = $new_last_poll;
1116
1117             # save id_map hash
1118             if ( keys %id_map
1119                 and my $file =
1120                 Irssi::settings_get_str("twirssi_replies_store") )
1121             {
1122                 if ( open JSON, ">$file" ) {
1123                     print JSON JSON::Any->objToJson( \%id_map );
1124                     close JSON;
1125                 } else {
1126                     &notice("Failed to write replies to $file: $!");
1127                 }
1128             }
1129             return;
1130         }
1131     }
1132
1133     close FILE;
1134
1135     if ( $attempt < 24 ) {
1136         Irssi::timeout_add_once( 5000, 'monitor_child',
1137             [ $filename, $attempt + 1 ] );
1138     } else {
1139         print "Giving up on polling $filename" if &debug;
1140         unlink $filename unless &debug;
1141
1142         return unless Irssi::settings_get_bool("twirssi_notify_timeouts");
1143
1144         my $since;
1145         my @time = localtime($last_poll);
1146         if ( time - $last_poll < 24 * 60 * 60 ) {
1147             $since = sprintf( "%d:%02d", @time[ 2, 1 ] );
1148         } else {
1149             $since = scalar localtime($last_poll);
1150         }
1151         &notice("Haven't been able to get updated tweets since $since");
1152     }
1153 }
1154
1155 sub debug {
1156     return Irssi::settings_get_bool("twirssi_debug");
1157 }
1158
1159 sub notice {
1160     $window->print( "%R***%n @_", MSGLEVEL_PUBLIC );
1161 }
1162
1163 sub update_away {
1164     my $data = shift;
1165
1166     if (    Irssi::settings_get_bool("tweet_to_away")
1167         and $data !~ /\@\w/
1168         and $data !~ /^[dD] / )
1169     {
1170         my $server =
1171           Irssi::server_find_tag( Irssi::settings_get_str("bitlbee_server") );
1172         if ($server) {
1173             $server->send_raw("away :$data");
1174             return 1;
1175         } else {
1176             &notice( "Can't find bitlbee server.",
1177                 "Update bitlbee_server or disable tweet_to_away" );
1178             return 0;
1179         }
1180     }
1181
1182     return 0;
1183 }
1184
1185 sub too_long {
1186     my $data    = shift;
1187     my $noalert = shift;
1188
1189     if ( length $data > 140 ) {
1190         &notice( "Tweet too long (" . length($data) . " characters) - aborted" )
1191           unless $noalert;
1192         return 1;
1193     }
1194
1195     return 0;
1196 }
1197
1198 sub valid_username {
1199     my $username = shift;
1200
1201     unless ( exists $twits{$username} ) {
1202         &notice("Unknown username $username");
1203         return 0;
1204     }
1205
1206     return 1;
1207 }
1208
1209 sub logged_in {
1210     my $obj = shift;
1211     unless ($obj) {
1212         &notice("Not logged in!  Use /twitter_login username pass!");
1213         return 0;
1214     }
1215
1216     return 1;
1217 }
1218
1219 sub sig_complete {
1220     my ( $complist, $window, $word, $linestart, $want_space ) = @_;
1221
1222     if (
1223         $linestart =~ /^\/twitter_reply(?:_as)?\s*$/
1224         or ( Irssi::settings_get_bool("twirssi_use_reply_aliases")
1225             and $linestart =~ /^\/reply(?:_as)?\s*$/ )
1226       )
1227     {    # /twitter_reply gets a nick:num
1228         $word =~ s/^@//;
1229         @$complist = map { "$_:$id_map{__indexes}{$_}" } grep /^\Q$word/i,
1230           sort keys %{ $id_map{__indexes} };
1231     }
1232
1233     # /tweet, /tweet_as, /dm, /dm_as - complete @nicks (and nicks as the first
1234     # arg to dm)
1235     if ( $linestart =~ /^\/(?:tweet|dm)/ ) {
1236         my $prefix = $word =~ s/^@//;
1237         $prefix = 0 if $linestart eq '/dm' or $linestart eq '/dm_as';
1238         push @$complist, grep /^\Q$word/i,
1239           sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1240         @$complist = map { "\@$_" } @$complist if $prefix;
1241     }
1242 }
1243
1244 sub event_send_text {
1245     my ( $line, $server, $win ) = @_;
1246     my $awin = Irssi::active_win();
1247
1248     # if the window where we got our text was the twitter window, and the user
1249     # wants to be lazy, tweet away!
1250     if ( ( $awin->get_active_name() eq $window->{name} )
1251         and Irssi::settings_get_bool("tweet_window_input") )
1252     {
1253         &cmd_tweet( $line, $server, $win );
1254     }
1255 }
1256
1257 sub get_poll_time {
1258     my $poll = Irssi::settings_get_int("twitter_poll_interval");
1259     return $poll if $poll >= 60;
1260     return 60;
1261 }
1262
1263 sub hilight {
1264     my $text = shift;
1265
1266     if ( Irssi::settings_get_str("twirssi_nick_color") ) {
1267         my $c = Irssi::settings_get_str("twirssi_nick_color");
1268         $c = $irssi_to_mirc_colors{$c};
1269         $text =~ s/(^|\W)\@([-\w]+)/$1\cC$c\@$2\cO/g if $c;
1270     }
1271     if ( Irssi::settings_get_str("twirssi_topic_color") ) {
1272         my $c = Irssi::settings_get_str("twirssi_topic_color");
1273         $c = $irssi_to_mirc_colors{$c};
1274         $text =~ s/(^|\W)\#([-\w]+)/$1\cC$c\#$2\cO/g if $c;
1275     }
1276     $text =~ s/[\n\r]/ /g;
1277
1278     return $text;
1279 }
1280
1281 Irssi::signal_add( "send text", "event_send_text" );
1282
1283 Irssi::theme_register(
1284     [
1285         'twirssi_tweet',  '[$0%B@$1%n$2] $3',
1286         'twirssi_search', '[$0%r$1%n:%B@$2%n$3] $4',
1287         'twirssi_reply',  '[$0\--> %B@$1%n$2] $3',
1288         'twirssi_dm',     '[$0%r@$1%n (%WDM%n)] $2',
1289         'twirssi_error',  'ERROR: $0',
1290     ]
1291 );
1292
1293 Irssi::settings_add_int( "twirssi", "twitter_poll_interval", 300 );
1294 Irssi::settings_add_str( "twirssi", "twitter_window",     "twitter" );
1295 Irssi::settings_add_str( "twirssi", "bitlbee_server",     "bitlbee" );
1296 Irssi::settings_add_str( "twirssi", "short_url_provider", "TinyURL" );
1297 Irssi::settings_add_str( "twirssi", "twirssi_location",
1298     ".irssi/scripts/twirssi.pl" );
1299 Irssi::settings_add_str( "twirssi", "twitter_usernames", undef );
1300 Irssi::settings_add_str( "twirssi", "twitter_passwords", undef );
1301 Irssi::settings_add_str( "twirssi", "twirssi_replies_store",
1302     ".irssi/scripts/twirssi.json" );
1303 Irssi::settings_add_str( "twirssi", "twirssi_nick_color",  "%B" );
1304 Irssi::settings_add_str( "twirssi", "twirssi_topic_color", "%r" );
1305 Irssi::settings_add_bool( "twirssi", "tweet_to_away",             0 );
1306 Irssi::settings_add_bool( "twirssi", "show_reply_context",        0 );
1307 Irssi::settings_add_bool( "twirssi", "show_own_tweets",           1 );
1308 Irssi::settings_add_bool( "twirssi", "twirssi_debug",             0 );
1309 Irssi::settings_add_bool( "twirssi", "twirssi_first_run",         1 );
1310 Irssi::settings_add_bool( "twirssi", "twirssi_track_replies",     1 );
1311 Irssi::settings_add_bool( "twirssi", "twirssi_replies_autonick",  1 );
1312 Irssi::settings_add_bool( "twirssi", "twirssi_use_reply_aliases", 0 );
1313 Irssi::settings_add_bool( "twirssi", "twirssi_notify_timeouts",   1 );
1314 Irssi::settings_add_bool( "twirssi", "twirssi_hilights",          1 );
1315 Irssi::settings_add_bool( "twirssi", "tweet_window_input",        0 );
1316
1317 $last_poll = time - &get_poll_time;
1318 $window = Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
1319 if ( !$window ) {
1320     $window =
1321       Irssi::Windowitem::window_create(
1322         Irssi::settings_get_str('twitter_window'), 1 );
1323     $window->set_name( Irssi::settings_get_str('twitter_window') );
1324 }
1325
1326 if ($window) {
1327     Irssi::command_bind( "dm",                         "cmd_direct" );
1328     Irssi::command_bind( "dm_as",                      "cmd_direct_as" );
1329     Irssi::command_bind( "tweet",                      "cmd_tweet" );
1330     Irssi::command_bind( "dent",                       "cmd_tweet" );
1331     Irssi::command_bind( "tweet_as",                   "cmd_tweet_as" );
1332     Irssi::command_bind( "dent_as",                   "cmd_tweet_as" );
1333     Irssi::command_bind( "twitter_reply",              "cmd_reply" );
1334     Irssi::command_bind( "identica_reply",             "cmd_reply" );
1335     Irssi::command_bind( "twitter_reply_as",           "cmd_reply_as" );
1336     Irssi::command_bind( "identica_reply_as",          "cmd_reply_as" );
1337     Irssi::command_bind( "twitter_login",              "cmd_login_twitter" );
1338     Irssi::command_bind( "twitter_logout",             "cmd_logout_twitter" );
1339     Irssi::command_bind( "identica_login",             "cmd_login_identica" );
1340     Irssi::command_bind( "identica_logout",            "cmd_logout_identica" );
1341     Irssi::command_bind( "twitter_switch",             "cmd_switch" );
1342     Irssi::command_bind( "twitter_subscribe",          "cmd_add_search_twitter" );
1343     Irssi::command_bind( "identica_subscribe",         "cmd_add_search_identica" );
1344     Irssi::command_bind( "twitter_unsubscribe",        "cmd_del_search_twitter" );
1345     Irssi::command_bind( "identica_unsubscribe",       "cmd_del_search_identica" );
1346     Irssi::command_bind( "twitter_list_subscriptions", "cmd_list_search" );
1347     Irssi::command_bind( "twirssi_upgrade",            "cmd_upgrade" );
1348     if ( Irssi::settings_get_bool("twirssi_use_reply_aliases") ) {
1349         Irssi::command_bind( "reply",    "cmd_reply" );
1350         Irssi::command_bind( "reply_as", "cmd_reply_as" );
1351     }
1352     Irssi::command_bind(
1353         "twirssi_dump",
1354         sub {
1355             print "twits: ", join ", ",
1356               map { "u: $_->{username}" } values %twits;
1357             print "friends: ", join ", ", sort keys %friends;
1358             print "nicks: ",   join ", ", sort keys %nicks;
1359             print "searches: ", Dumper \%{ $id_map{__searches} };
1360             print "last poll: $last_poll";
1361         }
1362     );
1363     Irssi::command_bind(
1364         "twirssi_version",
1365         sub {
1366             &notice("Twirssi v$VERSION (r$REV); "
1367                   . "Net::Identica v$Net::Identica::VERSION. "
1368                   . "Net::Twitter v$Net::Twitter::VERSION."
1369                   . "JSON in use: "
1370                   . JSON::Any::handler()
1371                   . ".  See details at http://twirssi.com/" );
1372         }
1373     );
1374     Irssi::command_bind(
1375         "twitter_friend",
1376         &gen_cmd(
1377             "/twitter_friend <username>",
1378             "create_friend",
1379             sub { &notice("Following $_[0]"); $nicks{ $_[0] } = time; }
1380         )
1381     );
1382     Irssi::command_bind(
1383         "twitter_unfriend",
1384         &gen_cmd(
1385             "/twitter_unfriend <username>",
1386             "destroy_friend",
1387             sub { &notice("Stopped following $_[0]"); delete $nicks{ $_[0] }; }
1388         )
1389     );
1390     Irssi::command_bind( "twitter_updates", "get_updates" );
1391     Irssi::signal_add_last( 'complete word' => \&sig_complete );
1392
1393     &notice("  %Y<%C(%B^%C)%N                   TWIRSSI v%R$VERSION%N (r$REV)");
1394     &notice("   %C(_(\\%N           http://twirssi.com/ for full docs");
1395     &notice(
1396         "    %Y||%C `%N Log in with /twitter_login or /identica_login, send updates with /tweet or /dent");
1397
1398     my $file = Irssi::settings_get_str("twirssi_replies_store");
1399     if ( $file and -r $file ) {
1400         if ( open( JSON, $file ) ) {
1401             local $/;
1402             my $json = <JSON>;
1403             close JSON;
1404             eval {
1405                 my $ref = JSON::Any->jsonToObj($json);
1406                 %id_map = %$ref;
1407                 my $num = keys %{ $id_map{__indexes} };
1408                 &notice( sprintf "Loaded old replies from %d contact%s.",
1409                     $num, ( $num == 1 ? "" : "s" ) );
1410             };
1411         } else {
1412             &notice("Failed to load old replies from $file: $!");
1413         }
1414     }
1415
1416     if ( my $provider = Irssi::settings_get_str("short_url_provider") ) {
1417         eval "use WWW::Shorten::$provider;";
1418
1419         if ($@) {
1420             &notice(
1421 "Failed to load WWW::Shorten::$provider - either clear short_url_provider or install the CPAN module"
1422             );
1423         }
1424     }
1425
1426     if (    my $autouser = Irssi::settings_get_str("twitter_usernames_twitter")
1427         and my $autopass = Irssi::settings_get_str("twitter_passwords_twitter") )
1428     {
1429         &cmd_login_twitter();
1430     }
1431
1432     if (    my $autouser = Irssi::settings_get_str("twitter_usernames_identica")
1433         and my $autopass = Irssi::settings_get_str("twitter_passwords_identica") )
1434     {
1435         &cmd_login_identica();
1436     }
1437
1438 } else {
1439     Irssi::active_win()
1440       ->print( "Create a window named "
1441           . Irssi::settings_get_str('twitter_window')
1442           . " or change the value of twitter_window.  Then, reload twirssi." );
1443 }