r487 - Remove since_id from friend_timeline call; extend the duplicate cache an hour...
[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::Twitter;
10 $Data::Dumper::Indent = 1;
11
12 use vars qw($VERSION %IRSSI);
13
14 $VERSION = "2.0.6";
15 my ($REV) = '$Rev: 487 $' =~ /(\d+)/;
16 %IRSSI = (
17     authors     => 'Dan Boger',
18     contact     => 'zigdon@gmail.com',
19     name        => 'twirssi',
20     description => 'Send twitter updates using /tweet.  '
21       . 'Can optionally set your bitlbee /away message to same',
22     license => 'GNU GPL v2',
23     url     => 'http://twirssi.com',
24     changed => '$Date: 2009-02-24 11:27:26 -0800 (Tue, 24 Feb 2009) $',
25 );
26
27 my $window;
28 my $twit;
29 my %twits;
30 my $user;
31 my $poll;
32 my $last_poll;
33 my %nicks;
34 my %friends;
35 my %tweet_cache;
36 my %id_map;
37 my $failwhale            = 0;
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 {
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_login {
348     my ( $data, $server, $win ) = @_;
349     my $pass;
350     if ($data) {
351         ( $user, $pass ) = split ' ', $data, 2;
352     } elsif ( my $autouser = Irssi::settings_get_str("twitter_usernames")
353         and my $autopass = Irssi::settings_get_str("twitter_passwords") )
354     {
355         my @user = split /\s*,\s*/, $autouser;
356         my @pass = split /\s*,\s*/, $autopass;
357         if ( @user != @pass ) {
358             &notice("Number of usernames doesn't match "
359                   . "the number of passwords - auto-login failed" );
360         } else {
361             my ( $u, $p );
362             while ( @user and @pass ) {
363                 $u = shift @user;
364                 $p = shift @pass;
365                 &cmd_login("$u $p");
366             }
367             return;
368         }
369     } else {
370         &notice("/twitter_login requires either a username and password "
371               . "or twitter_usernames and twitter_passwords to be set." );
372         return;
373     }
374
375     %friends = %nicks = ();
376
377     $twit = Net::Twitter->new(
378         username => $user,
379         password => $pass,
380         source   => "twirssi"
381     );
382
383     unless ( $twit->verify_credentials() ) {
384         &notice("Login as $user failed");
385         $twit = undef;
386         if ( keys %twits ) {
387             &cmd_switch( ( keys %twits )[0], $server, $win );
388         }
389         return;
390     }
391
392     if ($twit) {
393         my $rate_limit = $twit->rate_limit_status();
394         if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
395             &notice(
396                 "Rate limit exceeded, try again after $rate_limit->{reset_time}"
397             );
398             $twit = undef;
399             return;
400         }
401
402         $twits{$user} = $twit;
403         Irssi::timeout_remove($poll) if $poll;
404         $poll = Irssi::timeout_add( &get_poll_time * 1000, \&get_updates, "" );
405         &notice("Logged in as $user, loading friends list...");
406         &load_friends();
407         &notice( "loaded friends: ", scalar keys %friends );
408         if ( Irssi::settings_get_bool("twirssi_first_run") ) {
409             Irssi::settings_set_bool( "twirssi_first_run", 0 );
410             unless ( exists $friends{twirssi} ) {
411                 &notice("Welcome to twirssi!"
412                       . "  Perhaps you should add \@twirssi to your friends list,"
413                       . " so you can be notified when a new version is release?"
414                       . "  Just type /twitter_friend twirssi." );
415             }
416         }
417         %nicks = %friends;
418         $nicks{$user} = 0;
419         &get_updates;
420     } else {
421         &notice("Login failed");
422     }
423 }
424
425 sub cmd_add_search {
426     my ( $data, $server, $win ) = @_;
427
428     unless ( $twit and $twit->can('search') ) {
429         &notice("ERROR: Your version of Net::Twitter ($Net::Twitter::VERSION) "
430               . "doesn't support searches." );
431         return;
432     }
433
434     $data =~ s/^\s+|\s+$//;
435     $data = lc $data;
436
437     unless ($data) {
438         &notice("Usage: /twitter_subscribe <topic>");
439         return;
440     }
441
442     if ( exists $id_map{__searches}{$user}{$data} ) {
443         &notice("Already had a subscription for '$data'");
444         return;
445     }
446
447     $id_map{__searches}{$user}{$data} = 1;
448     &notice("Added subscription for '$data'");
449 }
450
451 sub cmd_del_search {
452     my ( $data, $server, $win ) = @_;
453
454     unless ( $twit and $twit->can('search') ) {
455         &notice("ERROR: Your version of Net::Twitter ($Net::Twitter::VERSION) "
456               . "doesn't support searches." );
457         return;
458     }
459     $data =~ s/^\s+|\s+$//;
460     $data = lc $data;
461
462     unless ($data) {
463         &notice("Usage: /twitter_unsubscribe <topic>");
464         return;
465     }
466
467     unless ( exists $id_map{__searches}{$user}{$data} ) {
468         &notice("No subscription found for '$data'");
469         return;
470     }
471
472     delete $id_map{__searches}{$user}{$data};
473     &notice("Removed subscription for '$data'");
474 }
475
476 sub cmd_list_search {
477     my ( $data, $server, $win ) = @_;
478
479     my $found = 0;
480     foreach my $suser ( sort keys %{ $id_map{__searches} } ) {
481         my $topics;
482         foreach my $topic ( sort keys %{ $id_map{__searches}{$suser} } ) {
483             $topics = $topics ? "$topics, $topic" : $topic;
484         }
485         if ($topics) {
486             $found = 1;
487             &notice("Search subscriptions for \@$suser: $topics");
488         }
489     }
490
491     unless ($found) {
492         &notice("No search subscriptions set up");
493     }
494 }
495
496 sub cmd_upgrade {
497     my ( $data, $server, $win ) = @_;
498
499     my $loc = Irssi::settings_get_str("twirssi_location");
500     unless ( -w $loc ) {
501         &notice(
502 "$loc isn't writable, can't upgrade.  Perhaps you need to /set twirssi_location?"
503         );
504         return;
505     }
506
507     my $md5;
508     unless ($data) {
509         eval { use Digest::MD5; };
510
511         if ($@) {
512             &notice(
513 "Failed to load Digest::MD5.  Try '/twirssi_upgrade nomd5' to skip MD5 verification"
514             );
515             return;
516         }
517
518         $md5 = get("http://twirssi.com/md5sum");
519         chomp $md5;
520         $md5 =~ s/ .*//;
521         unless ($md5) {
522             &notice("Failed to download md5sum from peeron!  Aborting.");
523             return;
524         }
525
526         unless ( open( CUR, $loc ) ) {
527             &notice(
528 "Failed to read $loc.  Check that /set twirssi_location is set to the correct location."
529             );
530             return;
531         }
532
533         my $cur_md5 = Digest::MD5::md5_hex(<CUR>);
534         close CUR;
535
536         if ( $cur_md5 eq $md5 ) {
537             &notice("Current twirssi seems to be up to date.");
538             return;
539         }
540     }
541
542     my $URL = "http://twirssi.com/twirssi.pl";
543     &notice("Downloading twirssi from $URL");
544     LWP::Simple::getstore( $URL, "$loc.upgrade" );
545
546     unless ($data) {
547         unless ( open( NEW, "$loc.upgrade" ) ) {
548             &notice(
549 "Failed to read $loc.upgrade.  Check that /set twirssi_location is set to the correct location."
550             );
551             return;
552         }
553
554         my $new_md5 = Digest::MD5::md5_hex(<NEW>);
555         close NEW;
556
557         if ( $new_md5 ne $md5 ) {
558             &notice("MD5 verification failed. expected $md5, got $new_md5");
559             return;
560         }
561     }
562
563     rename $loc, "$loc.backup"
564       or &notice("Failed to back up $loc: $!.  Aborting")
565       and return;
566     rename "$loc.upgrade", $loc
567       or &notice("Failed to rename $loc.upgrade: $!.  Aborting")
568       and return;
569
570     my ( $dir, $file ) = ( $loc =~ m{(.*)/([^/]+)$} );
571     if ( -e "$dir/autorun/$file" ) {
572         &notice("Updating $dir/autorun/$file");
573         unlink "$dir/autorun/$file"
574           or &notice("Failed to remove old $file from autorun: $!");
575         symlink "../$file", "$dir/autorun/$file"
576           or &notice("Failed to create symlink in autorun directory: $!");
577     }
578
579     &notice("Download complete.  Reload twirssi with /script load $file");
580 }
581
582 sub load_friends {
583     my $fh   = shift;
584     my $page = 1;
585     my %new_friends;
586     eval {
587         while (1)
588         {
589             print $fh "type:debug Loading friends page $page...\n"
590               if ( $fh and &debug );
591             my $friends = $twit->friends( { page => $page } );
592             last unless $friends;
593             $new_friends{ $_->{screen_name} } = time foreach @$friends;
594             $page++;
595             last if @$friends == 0 or $page == 10;
596         }
597     };
598
599     if ($@) {
600         print $fh "type:debug Error during friends list update.  Aborted.\n";
601         return;
602     }
603
604     my ( $added, $removed ) = ( 0, 0 );
605     print $fh "type:debug Scanning for new friends...\n" if ( $fh and &debug );
606     foreach ( keys %new_friends ) {
607         next if exists $friends{$_};
608         $friends{$_} = time;
609         $added++;
610     }
611
612     print $fh "type:debug Scanning for removed friends...\n"
613       if ( $fh and &debug );
614     foreach ( keys %friends ) {
615         next if exists $new_friends{$_};
616         delete $friends{$_};
617         $removed++;
618     }
619
620     return ( $added, $removed );
621 }
622
623 sub get_updates {
624     print scalar localtime, " - get_updates starting" if &debug;
625
626     $window =
627       Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
628     unless ($window) {
629         Irssi::active_win()
630           ->print( "Can't find a window named '"
631               . Irssi::settings_get_str('twitter_window')
632               . "'.  Create it or change the value of twitter_window" );
633     }
634
635     return unless &logged_in($twit);
636
637     my ( $fh, $filename ) = File::Temp::tempfile();
638     binmode( $fh, ":utf8" );
639     my $pid = fork();
640
641     if ($pid) {    # parent
642         Irssi::timeout_add_once( 5000, 'monitor_child', [ $filename, 0 ] );
643         Irssi::pidwait_add($pid);
644     } elsif ( defined $pid ) {    # child
645         close STDIN;
646         close STDOUT;
647         close STDERR;
648
649         my $new_poll = time;
650
651         my $error = 0;
652         $error += &do_updates( $fh, $user, $twit );
653         foreach ( keys %twits ) {
654             next if $_ eq $user;
655             $error += &do_updates( $fh, $_, $twits{$_} );
656         }
657
658         my ( $added, $removed ) = &load_friends($fh);
659         if ( $added + $removed ) {
660             print $fh "type:debug %R***%n Friends list updated: ",
661               join( ", ",
662                 sprintf( "%d added",   $added ),
663                 sprintf( "%d removed", $removed ) ),
664               "\n";
665         }
666         print $fh "__friends__\n";
667         foreach ( sort keys %friends ) {
668             print $fh "$_ $friends{$_}\n";
669         }
670
671         if ($error) {
672             print $fh "type:debug Update encountered errors.  Aborted\n";
673             print $fh $last_poll;
674         } else {
675             print $fh $new_poll;
676         }
677         close $fh;
678         exit;
679     }
680     print scalar localtime, " - get_updates ends" if &debug;
681 }
682
683 sub do_updates {
684     my ( $fh, $username, $obj ) = @_;
685
686     my $rate_limit = $obj->rate_limit_status();
687     if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
688         &notice("Rate limit exceeded for $username");
689         return 1;
690     }
691
692     print scalar localtime, " - Polling for updates for $username" if &debug;
693     my $tweets;
694     eval { $tweets = $obj->friends_timeline(); };
695
696     if ($@) {
697         print $fh
698           "type:debug Error during friends_timeline call: $@.  Aborted.\n";
699         return 1;
700     }
701
702     unless ( ref $tweets ) {
703         if ( $obj->can("get_error") ) {
704             my $error;
705             eval { $error = JSON::Any->jsonToObj( $obj->get_error() ) };
706             if ($@) { $error = $obj->get_error() }
707             print $fh "type:debug API Error during friends_timeline call: ",
708               "$error  Aborted.\n";
709         } else {
710             print $fh
711               "type:debug API Error during friends_timeline call. Aborted.\n";
712         }
713         return 1;
714     }
715
716     foreach my $t ( reverse @$tweets ) {
717         my $text = decode_entities( $t->{text} );
718         $text = &hilight($text);
719         my $reply = "tweet";
720         if (    Irssi::settings_get_bool("show_reply_context")
721             and $t->{in_reply_to_screen_name} ne $username
722             and $t->{in_reply_to_screen_name}
723             and not exists $friends{ $t->{in_reply_to_screen_name} } )
724         {
725             $nicks{ $t->{in_reply_to_screen_name} } = time;
726             my $context;
727             eval {
728                 $context = $obj->show_status( $t->{in_reply_to_status_id} );
729             };
730
731             if ($context) {
732                 my $ctext = decode_entities( $context->{text} );
733                 $ctext = &hilight($ctext);
734                 printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
735                   $context->{id}, $username,
736                   $context->{user}{screen_name}, $ctext;
737                 $reply = "reply";
738             } elsif ($@) {
739                 print $fh "type:debug request to get context failed: $@";
740             } else {
741                 print $fh
742 "type:debug Failed to get context from $t->{in_reply_to_screen_name}\n"
743                   if &debug;
744             }
745         }
746         next
747           if $t->{user}{screen_name} eq $username
748               and not Irssi::settings_get_bool("show_own_tweets");
749         printf $fh "id:%d account:%s nick:%s type:%s %s\n",
750           $t->{id}, $username, $t->{user}{screen_name}, $reply, $text;
751     }
752
753     print scalar localtime, " - Polling for replies" if &debug;
754     eval {
755         $tweets = $obj->replies( { since => HTTP::Date::time2str($last_poll) } )
756           || [];
757     };
758
759     if ($@) {
760         print $fh "type:debug Error during replies call.  Aborted.\n";
761         return 1;
762     }
763
764     foreach my $t ( reverse @$tweets ) {
765         next
766           if exists $friends{ $t->{user}{screen_name} };
767
768         my $text = decode_entities( $t->{text} );
769         $text = &hilight($text);
770         printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
771           $t->{id}, $username, $t->{user}{screen_name}, $text;
772     }
773
774     print scalar localtime, " - Polling for DMs" if &debug;
775     eval {
776         $tweets =
777           $obj->direct_messages( { since => HTTP::Date::time2str($last_poll) } )
778           || [];
779     };
780
781     if ($@) {
782         print $fh "type:debug Error during direct_messages call.  Aborted.\n";
783         return 1;
784     }
785
786     foreach my $t ( reverse @$tweets ) {
787         my $text = decode_entities( $t->{text} );
788         $text = &hilight($text);
789         printf $fh "id:%d account:%s nick:%s type:dm %s\n",
790           $t->{id}, $username, $t->{sender_screen_name}, $text;
791     }
792
793     print scalar localtime, " - Polling for subscriptions" if &debug;
794     if ( $obj->can('search') and $id_map{__searches}{$username} ) {
795         my $search;
796         foreach my $topic ( sort keys %{ $id_map{__searches}{$username} } ) {
797             print $fh "type:debug searching for $topic since ",
798               "$id_map{__searches}{$username}{$topic}\n";
799             eval {
800                 $search = $obj->search(
801                     {
802                         q        => $topic,
803                         since_id => $id_map{__searches}{$username}{$topic}
804                     }
805                 );
806             };
807
808             if ($@) {
809                 print $fh
810                   "type:debug Error during search($topic) call.  Aborted.\n";
811                 return 1;
812             }
813
814             unless ( $search->{max_id} ) {
815                 print $fh
816 "type:debug Invalid search results when searching for $topic.",
817                   "  Aborted.\n";
818                 return 1;
819             }
820
821             $id_map{__searches}{$username}{$topic} = $search->{max_id};
822             printf $fh "id:%d account:%s type:searchid topic:%s\n",
823               $search->{max_id}, $username, $topic;
824
825             foreach my $t ( reverse @{ $search->{results} } ) {
826                 my $text = decode_entities( $t->{text} );
827                 $text = &hilight($text);
828                 printf $fh "id:%d account:%s nick:%s type:search topic:%s %s\n",
829                   $t->{id}, $username, $t->{from_user}, $topic, $text;
830             }
831         }
832     }
833
834     print scalar localtime, " - Done" if &debug;
835
836     return 0;
837 }
838
839 sub monitor_child {
840     my ($data)   = @_;
841     my $filename = $data->[0];
842     my $attempt  = $data->[1];
843
844     print scalar localtime, " - checking child log at $filename ($attempt)"
845       if &debug;
846     my $new_last_poll;
847     if ( open FILE, $filename ) {
848         my @lines;
849         while (<FILE>) {
850             chomp;
851             last if /^__friends__/;
852             my $hilight = 0;
853             my %meta;
854             foreach my $key (qw/id account nick type topic/) {
855                 if (s/^$key:(\S+)\s*//) {
856                     $meta{$key} = $1;
857                 }
858             }
859
860             if ( not $meta{type} or $meta{type} ne 'searchid' ) {
861                 next if exists $meta{id} and exists $tweet_cache{ $meta{id} };
862                 $tweet_cache{ $meta{id} } = time;
863             }
864
865             my $account = "";
866             if ( $meta{account} ne $user ) {
867                 $account = "$meta{account}: ";
868             }
869
870             my $marker = "";
871             if (    $meta{type} ne 'dm'
872                 and Irssi::settings_get_bool("twirssi_track_replies")
873                 and $meta{nick}
874                 and $meta{id} )
875             {
876                 $marker = ( $id_map{__indexes}{ $meta{nick} } + 1 ) % 100;
877                 $id_map{ lc $meta{nick} }[$marker] = $meta{id};
878                 $id_map{__indexes}{ $meta{nick} }  = $marker;
879                 $marker                            = ":$marker";
880             }
881
882             my $hilight_color =
883               $irssi_to_mirc_colors{ Irssi::settings_get_str("hilight_color") };
884             if ( ( $_ =~ /\@$meta{account}\W/i )
885                 && Irssi::settings_get_bool("twirssi_hilights") )
886             {
887                 $meta{nick} = "\cC$hilight_color$meta{nick}\cO";
888                 $hilight = MSGLEVEL_HILIGHT;
889             }
890
891             if ( $meta{type} =~ /tweet|reply/ ) {
892                 push @lines,
893                   [
894                     ( MSGLEVEL_PUBLIC | $hilight ),
895                     $meta{type}, $account, $meta{nick}, $marker, $_
896                   ];
897             } elsif ( $meta{type} eq 'search' ) {
898                 push @lines,
899                   [
900                     ( MSGLEVEL_PUBLIC | $hilight ),
901                     $meta{type}, $account, $meta{topic},
902                     $meta{nick}, $marker,  $_
903                   ];
904                 if ( $meta{id} >
905                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
906                 {
907                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
908                       $meta{id};
909                 }
910             } elsif ( $meta{type} eq 'dm' ) {
911                 push @lines,
912                   [
913                     ( MSGLEVEL_MSGS | $hilight ),
914                     $meta{type}, $account, $meta{nick}, $_
915                   ];
916             } elsif ( $meta{type} eq 'searchid' ) {
917                 print "Search '$meta{topic}' returned id $meta{id}" if &debug;
918                 if ( $meta{id} >=
919                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
920                 {
921                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
922                       $meta{id};
923                 } elsif (&debug) {
924                     print "Search '$meta{topic}' returned invalid id $meta{id}";
925                 }
926             } elsif ( $meta{type} eq 'error' ) {
927                 push @lines, [ MSGLEVEL_MSGS, $_ ];
928             } elsif ( $meta{type} eq 'debug' ) {
929                 print "$_" if &debug,;
930             } else {
931                 print "Unknown line type $meta{type}: $_" if &debug,;
932             }
933         }
934
935         %friends = ();
936         while (<FILE>) {
937             if (/^\d+$/) {
938                 $new_last_poll = $_;
939                 last;
940             }
941             my ( $f, $t ) = split ' ', $_;
942             $nicks{$f} = $friends{$f} = $t;
943         }
944
945         if ($new_last_poll) {
946             print "new last_poll = $new_last_poll" if &debug;
947             for my $line (@lines) {
948                 $window->printformat(
949                     $line->[0],
950                     "twirssi_" . $line->[1],
951                     @$line[ 2 .. $#$line ]
952                 );
953             }
954
955             close FILE;
956             unlink $filename
957               or warn "Failed to remove $filename: $!"
958               unless &debug;
959
960             # keep enough cached tweets, to make sure we don't show duplicates.
961             foreach ( keys %tweet_cache ) {
962                 next if $tweet_cache{$_} >= $last_poll - 3600;
963                 delete $tweet_cache{$_};
964             }
965             $last_poll = $new_last_poll;
966
967             # save id_map hash
968             if ( keys %id_map
969                 and my $file =
970                 Irssi::settings_get_str("twirssi_replies_store") )
971             {
972                 if ( open JSON, ">$file" ) {
973                     print JSON JSON::Any->objToJson( \%id_map );
974                     close JSON;
975                 } else {
976                     &notice("Failed to write replies to $file: $!");
977                 }
978             }
979             $failwhale = 0;
980             return;
981         }
982     }
983
984     close FILE;
985
986     if ( $attempt < 24 ) {
987         Irssi::timeout_add_once( 5000, 'monitor_child',
988             [ $filename, $attempt + 1 ] );
989     } else {
990         print "Giving up on polling $filename" if &debug;
991         unlink $filename unless &debug;
992
993         return unless Irssi::settings_get_bool("twirssi_notify_timeouts");
994
995         my $since;
996         my @time = localtime($last_poll);
997         if ( time - $last_poll < 24 * 60 * 60 ) {
998             $since = sprintf( "%d:%02d", @time[ 2, 1 ] );
999         } else {
1000             $since = scalar localtime($last_poll);
1001         }
1002
1003         if ( not $failwhale and time - $last_poll > 60 * 60 ) {
1004             foreach my $whale (
1005                 q{     v  v        v},
1006                 q{     |  |  v     |  v},
1007                 q{     | .-, |     |  |},
1008                 q{  .--./ /  |  _.---.| },
1009                 q{   '-. (__..-"       \\},
1010                 q{      \\          a    |},
1011                 q{       ',.__.   ,__.-'/},
1012                 q{         '--/_.'----'`}
1013               )
1014             {
1015                 &notice($whale);
1016             }
1017             $failwhale = 1;
1018         }
1019         &notice("Haven't been able to get updated tweets since $since");
1020     }
1021 }
1022
1023 sub debug {
1024     return Irssi::settings_get_bool("twirssi_debug");
1025 }
1026
1027 sub notice {
1028     $window->print( "%R***%n @_", MSGLEVEL_PUBLIC );
1029 }
1030
1031 sub update_away {
1032     my $data = shift;
1033
1034     if (    Irssi::settings_get_bool("tweet_to_away")
1035         and $data !~ /\@\w/
1036         and $data !~ /^[dD] / )
1037     {
1038         my $server =
1039           Irssi::server_find_tag( Irssi::settings_get_str("bitlbee_server") );
1040         if ($server) {
1041             $server->send_raw("away :$data");
1042             return 1;
1043         } else {
1044             &notice( "Can't find bitlbee server.",
1045                 "Update bitlbee_server or disable tweet_to_away" );
1046             return 0;
1047         }
1048     }
1049
1050     return 0;
1051 }
1052
1053 sub too_long {
1054     my $data    = shift;
1055     my $noalert = shift;
1056
1057     if ( length $data > 140 ) {
1058         &notice( "Tweet too long (" . length($data) . " characters) - aborted" )
1059           unless $noalert;
1060         return 1;
1061     }
1062
1063     return 0;
1064 }
1065
1066 sub valid_username {
1067     my $username = shift;
1068
1069     unless ( exists $twits{$username} ) {
1070         &notice("Unknown username $username");
1071         return 0;
1072     }
1073
1074     return 1;
1075 }
1076
1077 sub logged_in {
1078     my $obj = shift;
1079     unless ($obj) {
1080         &notice("Not logged in!  Use /twitter_login username pass!");
1081         return 0;
1082     }
1083
1084     return 1;
1085 }
1086
1087 sub sig_complete {
1088     my ( $complist, $window, $word, $linestart, $want_space ) = @_;
1089
1090     if (
1091         $linestart =~ /^\/twitter_reply(?:_as)?\s*$/
1092         or ( Irssi::settings_get_bool("twirssi_use_reply_aliases")
1093             and $linestart =~ /^\/reply(?:_as)?\s*$/ )
1094       )
1095     {    # /twitter_reply gets a nick:num
1096         $word =~ s/^@//;
1097         @$complist = map { "$_:$id_map{__indexes}{$_}" } grep /^\Q$word/i,
1098           sort keys %{ $id_map{__indexes} };
1099     }
1100
1101     # /tweet, /tweet_as, /dm, /dm_as - complete @nicks (and nicks as the first
1102     # arg to dm)
1103     if ( $linestart =~ /^\/(?:tweet|dm)/ ) {
1104         my $prefix = $word =~ s/^@//;
1105         $prefix = 0 if $linestart eq '/dm' or $linestart eq '/dm_as';
1106         push @$complist, grep /^\Q$word/i,
1107           sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1108         @$complist = map { "\@$_" } @$complist if $prefix;
1109     }
1110 }
1111
1112 sub event_send_text {
1113     my ( $line, $server, $win ) = @_;
1114     my $awin = Irssi::active_win();
1115
1116     # if the window where we got our text was the twitter window, and the user
1117     # wants to be lazy, tweet away!
1118     if ( ( $awin->get_active_name() eq $window->{name} )
1119         and Irssi::settings_get_bool("tweet_window_input") )
1120     {
1121         &cmd_tweet( $line, $server, $win );
1122     }
1123 }
1124
1125 sub get_poll_time {
1126     my $poll = Irssi::settings_get_int("twitter_poll_interval");
1127     return $poll if $poll >= 60;
1128     return 60;
1129 }
1130
1131 sub hilight {
1132     my $text = shift;
1133
1134     if ( Irssi::settings_get_str("twirssi_nick_color") ) {
1135         my $c = Irssi::settings_get_str("twirssi_nick_color");
1136         $c = $irssi_to_mirc_colors{$c};
1137         $text =~ s/(^|\W)\@([-\w]+)/$1\cC$c\@$2\cO/g if $c;
1138     }
1139     if ( Irssi::settings_get_str("twirssi_topic_color") ) {
1140         my $c = Irssi::settings_get_str("twirssi_topic_color");
1141         $c = $irssi_to_mirc_colors{$c};
1142         $text =~ s/(^|\W)\#([-\w]+)/$1\cC$c\#$2\cO/g if $c;
1143     }
1144     $text =~ s/[\n\r]/ /g;
1145
1146     return $text;
1147 }
1148
1149 Irssi::signal_add( "send text", "event_send_text" );
1150
1151 Irssi::theme_register(
1152     [
1153         'twirssi_tweet',  '[$0%B@$1%n$2] $3',
1154         'twirssi_search', '[$0%r$1%n:%B@$2%n$3] $4',
1155         'twirssi_reply',  '[$0\--> %B@$1%n$2] $3',
1156         'twirssi_dm',     '[$0%r@$1%n (%WDM%n)] $2',
1157         'twirssi_error',  'ERROR: $0',
1158     ]
1159 );
1160
1161 Irssi::settings_add_int( "twirssi", "twitter_poll_interval", 300 );
1162 Irssi::settings_add_str( "twirssi", "twitter_window",     "twitter" );
1163 Irssi::settings_add_str( "twirssi", "bitlbee_server",     "bitlbee" );
1164 Irssi::settings_add_str( "twirssi", "short_url_provider", "TinyURL" );
1165 Irssi::settings_add_str( "twirssi", "twirssi_location",
1166     ".irssi/scripts/twirssi.pl" );
1167 Irssi::settings_add_str( "twirssi", "twitter_usernames", undef );
1168 Irssi::settings_add_str( "twirssi", "twitter_passwords", undef );
1169 Irssi::settings_add_str( "twirssi", "twirssi_replies_store",
1170     ".irssi/scripts/twirssi.json" );
1171 Irssi::settings_add_str( "twirssi", "twirssi_nick_color",  "%B" );
1172 Irssi::settings_add_str( "twirssi", "twirssi_topic_color", "%r" );
1173 Irssi::settings_add_bool( "twirssi", "tweet_to_away",             0 );
1174 Irssi::settings_add_bool( "twirssi", "show_reply_context",        0 );
1175 Irssi::settings_add_bool( "twirssi", "show_own_tweets",           1 );
1176 Irssi::settings_add_bool( "twirssi", "twirssi_debug",             0 );
1177 Irssi::settings_add_bool( "twirssi", "twirssi_first_run",         1 );
1178 Irssi::settings_add_bool( "twirssi", "twirssi_track_replies",     1 );
1179 Irssi::settings_add_bool( "twirssi", "twirssi_replies_autonick",  1 );
1180 Irssi::settings_add_bool( "twirssi", "twirssi_use_reply_aliases", 0 );
1181 Irssi::settings_add_bool( "twirssi", "twirssi_notify_timeouts",   1 );
1182 Irssi::settings_add_bool( "twirssi", "twirssi_hilights",          1 );
1183 Irssi::settings_add_bool( "twirssi", "tweet_window_input",        0 );
1184
1185 $last_poll = time - &get_poll_time;
1186 $window = Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
1187 if ( !$window ) {
1188     $window =
1189       Irssi::Windowitem::window_create(
1190         Irssi::settings_get_str('twitter_window'), 1 );
1191     $window->set_name( Irssi::settings_get_str('twitter_window') );
1192 }
1193
1194 if ($window) {
1195     Irssi::command_bind( "dm",                         "cmd_direct" );
1196     Irssi::command_bind( "dm_as",                      "cmd_direct_as" );
1197     Irssi::command_bind( "tweet",                      "cmd_tweet" );
1198     Irssi::command_bind( "tweet_as",                   "cmd_tweet_as" );
1199     Irssi::command_bind( "twitter_reply",              "cmd_reply" );
1200     Irssi::command_bind( "twitter_reply_as",           "cmd_reply_as" );
1201     Irssi::command_bind( "twitter_login",              "cmd_login" );
1202     Irssi::command_bind( "twitter_logout",             "cmd_logout" );
1203     Irssi::command_bind( "twitter_switch",             "cmd_switch" );
1204     Irssi::command_bind( "twitter_subscribe",          "cmd_add_search" );
1205     Irssi::command_bind( "twitter_unsubscribe",        "cmd_del_search" );
1206     Irssi::command_bind( "twitter_list_subscriptions", "cmd_list_search" );
1207     Irssi::command_bind( "twirssi_upgrade",            "cmd_upgrade" );
1208     if ( Irssi::settings_get_bool("twirssi_use_reply_aliases") ) {
1209         Irssi::command_bind( "reply",    "cmd_reply" );
1210         Irssi::command_bind( "reply_as", "cmd_reply_as" );
1211     }
1212     Irssi::command_bind(
1213         "twirssi_dump",
1214         sub {
1215             print "twits: ", join ", ",
1216               map { "u: $_->{username}" } values %twits;
1217             print "friends: ", join ", ", sort keys %friends;
1218             print "nicks: ",   join ", ", sort keys %nicks;
1219             print "searches: ", Dumper \%{ $id_map{__searches} };
1220             print "last poll: $last_poll";
1221         }
1222     );
1223     Irssi::command_bind(
1224         "twirssi_version",
1225         sub {
1226             &notice("Twirssi v$VERSION (r$REV); "
1227                   . "Net::Twitter v$Net::Twitter::VERSION. "
1228                   . "JSON in use: "
1229                   . JSON::Any::handler()
1230                   . ".  See details at http://twirssi.com/" );
1231         }
1232     );
1233     Irssi::command_bind(
1234         "twitter_friend",
1235         &gen_cmd(
1236             "/twitter_friend <username>",
1237             "create_friend",
1238             sub { &notice("Following $_[0]"); $nicks{ $_[0] } = time; }
1239         )
1240     );
1241     Irssi::command_bind(
1242         "twitter_unfriend",
1243         &gen_cmd(
1244             "/twitter_unfriend <username>",
1245             "destroy_friend",
1246             sub { &notice("Stopped following $_[0]"); delete $nicks{ $_[0] }; }
1247         )
1248     );
1249     Irssi::command_bind( "twitter_updates", "get_updates" );
1250     Irssi::signal_add_last( 'complete word' => \&sig_complete );
1251
1252     &notice("  %Y<%C(%B^%C)%N                   TWIRSSI v%R$VERSION%N (r$REV)");
1253     &notice("   %C(_(\\%N           http://twirssi.com/ for full docs");
1254     &notice(
1255         "    %Y||%C `%N Log in with /twitter_login, send updates with /tweet");
1256
1257     my $file = Irssi::settings_get_str("twirssi_replies_store");
1258     if ( $file and -r $file ) {
1259         if ( open( JSON, $file ) ) {
1260             local $/;
1261             my $json = <JSON>;
1262             close JSON;
1263             eval {
1264                 my $ref = JSON::Any->jsonToObj($json);
1265                 %id_map = %$ref;
1266                 my $num = keys %{ $id_map{__indexes} };
1267                 &notice( sprintf "Loaded old replies from %d contact%s.",
1268                     $num, ( $num == 1 ? "" : "s" ) );
1269             };
1270         } else {
1271             &notice("Failed to load old replies from $file: $!");
1272         }
1273     }
1274
1275     if ( my $provider = Irssi::settings_get_str("short_url_provider") ) {
1276         eval "use WWW::Shorten::$provider;";
1277
1278         if ($@) {
1279             &notice(
1280 "Failed to load WWW::Shorten::$provider - either clear short_url_provider or install the CPAN module"
1281             );
1282         }
1283     }
1284
1285     if (    my $autouser = Irssi::settings_get_str("twitter_usernames")
1286         and my $autopass = Irssi::settings_get_str("twitter_passwords") )
1287     {
1288         &cmd_login();
1289     }
1290
1291 } else {
1292     Irssi::active_win()
1293       ->print( "Create a window named "
1294           . Irssi::settings_get_str('twitter_window')
1295           . " or change the value of twitter_window.  Then, reload twirssi." );
1296 }
1297
1298 # vim: set sts=4 expandtab: