r491 - Add a new setting, twirssi_upgrade_beta. If true, will upgrade from git....
[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.1.1beta";
15 my ($REV) = '$Rev: 491 $' =~ /(\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-25 10:44:26 -0800 (Wed, 25 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         return 1;
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 or Irssi::settings_get_bool("twirssi_upgrade_beta") ) {
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 =
543       Irssi::settings_get_bool("twirssi_upgrade_beta")
544       ? "http://github.com/zigdon/twirssi/raw/master/twirssi.pl"
545       : "http://twirssi.com/twirssi.pl";
546     &notice("Downloading twirssi from $URL");
547     LWP::Simple::getstore( $URL, "$loc.upgrade" );
548
549     unless ($data) {
550         unless ( open( NEW, "$loc.upgrade" ) ) {
551             &notice(
552 "Failed to read $loc.upgrade.  Check that /set twirssi_location is set to the correct location."
553             );
554             return;
555         }
556
557         my $new_md5 = Digest::MD5::md5_hex(<NEW>);
558         close NEW;
559
560         if ( $new_md5 ne $md5 ) {
561             &notice("MD5 verification failed. expected $md5, got $new_md5");
562             return;
563         }
564     }
565
566     rename $loc, "$loc.backup"
567       or &notice("Failed to back up $loc: $!.  Aborting")
568       and return;
569     rename "$loc.upgrade", $loc
570       or &notice("Failed to rename $loc.upgrade: $!.  Aborting")
571       and return;
572
573     my ( $dir, $file ) = ( $loc =~ m{(.*)/([^/]+)$} );
574     if ( -e "$dir/autorun/$file" ) {
575         &notice("Updating $dir/autorun/$file");
576         unlink "$dir/autorun/$file"
577           or &notice("Failed to remove old $file from autorun: $!");
578         symlink "../$file", "$dir/autorun/$file"
579           or &notice("Failed to create symlink in autorun directory: $!");
580     }
581
582     &notice("Download complete.  Reload twirssi with /script load $file");
583 }
584
585 sub load_friends {
586     my $fh   = shift;
587     my $page = 1;
588     my %new_friends;
589     eval {
590         while (1)
591         {
592             print $fh "type:debug Loading friends page $page...\n"
593               if ( $fh and &debug );
594             my $friends = $twit->friends( { page => $page } );
595             last unless $friends;
596             $new_friends{ $_->{screen_name} } = time foreach @$friends;
597             $page++;
598             last if @$friends == 0 or $page == 10;
599         }
600     };
601
602     if ($@) {
603         print $fh "type:debug Error during friends list update.  Aborted.\n";
604         return;
605     }
606
607     my ( $added, $removed ) = ( 0, 0 );
608     print $fh "type:debug Scanning for new friends...\n" if ( $fh and &debug );
609     foreach ( keys %new_friends ) {
610         next if exists $friends{$_};
611         $friends{$_} = time;
612         $added++;
613     }
614
615     print $fh "type:debug Scanning for removed friends...\n"
616       if ( $fh and &debug );
617     foreach ( keys %friends ) {
618         next if exists $new_friends{$_};
619         delete $friends{$_};
620         $removed++;
621     }
622
623     return ( $added, $removed );
624 }
625
626 sub get_updates {
627     print scalar localtime, " - get_updates starting" if &debug;
628
629     $window =
630       Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
631     unless ($window) {
632         Irssi::active_win()
633           ->print( "Can't find a window named '"
634               . Irssi::settings_get_str('twitter_window')
635               . "'.  Create it or change the value of twitter_window" );
636     }
637
638     return unless &logged_in($twit);
639
640     my ( $fh, $filename ) = File::Temp::tempfile();
641     binmode( $fh, ":utf8" );
642     my $pid = fork();
643
644     if ($pid) {    # parent
645         Irssi::timeout_add_once( 5000, 'monitor_child', [ $filename, 0 ] );
646         Irssi::pidwait_add($pid);
647     } elsif ( defined $pid ) {    # child
648         close STDIN;
649         close STDOUT;
650         close STDERR;
651
652         my $new_poll = time;
653
654         my $error = 0;
655         $error += &do_updates( $fh, $user, $twit );
656         foreach ( keys %twits ) {
657             next if $_ eq $user;
658             $error += &do_updates( $fh, $_, $twits{$_} );
659         }
660
661         my ( $added, $removed ) = &load_friends($fh);
662         if ( $added + $removed ) {
663             print $fh "type:debug %R***%n Friends list updated: ",
664               join( ", ",
665                 sprintf( "%d added",   $added ),
666                 sprintf( "%d removed", $removed ) ),
667               "\n";
668         }
669         print $fh "__friends__\n";
670         foreach ( sort keys %friends ) {
671             print $fh "$_ $friends{$_}\n";
672         }
673
674         if ($error) {
675             print $fh "type:debug Update encountered errors.  Aborted\n";
676             print $fh $last_poll;
677         } else {
678             print $fh $new_poll;
679         }
680         close $fh;
681         exit;
682     }
683     print scalar localtime, " - get_updates ends" if &debug;
684 }
685
686 sub do_updates {
687     my ( $fh, $username, $obj ) = @_;
688
689     my $rate_limit = $obj->rate_limit_status();
690     if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
691         &notice("Rate limit exceeded for $username");
692         return 1;
693     }
694
695     print scalar localtime, " - Polling for updates for $username" if &debug;
696     my $tweets;
697     eval { $tweets = $obj->friends_timeline(); };
698
699     if ($@) {
700         print $fh
701           "type:debug Error during friends_timeline call: $@.  Aborted.\n";
702         return 1;
703     }
704
705     unless ( ref $tweets ) {
706         if ( $obj->can("get_error") ) {
707             my $error;
708             eval { $error = JSON::Any->jsonToObj( $obj->get_error() ) };
709             if ($@) { $error = $obj->get_error() }
710             print $fh "type:debug API Error during friends_timeline call: ",
711               "$error  Aborted.\n";
712         } else {
713             print $fh
714               "type:debug API Error during friends_timeline call. Aborted.\n";
715         }
716         return 1;
717     }
718
719     foreach my $t ( reverse @$tweets ) {
720         my $text = decode_entities( $t->{text} );
721         $text = &hilight($text);
722         my $reply = "tweet";
723         if (    Irssi::settings_get_bool("show_reply_context")
724             and $t->{in_reply_to_screen_name} ne $username
725             and $t->{in_reply_to_screen_name}
726             and not exists $friends{ $t->{in_reply_to_screen_name} } )
727         {
728             $nicks{ $t->{in_reply_to_screen_name} } = time;
729             my $context;
730             eval {
731                 $context = $obj->show_status( $t->{in_reply_to_status_id} );
732             };
733
734             if ($context) {
735                 my $ctext = decode_entities( $context->{text} );
736                 $ctext = &hilight($ctext);
737                 printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
738                   $context->{id}, $username,
739                   $context->{user}{screen_name}, $ctext;
740                 $reply = "reply";
741             } elsif ($@) {
742                 print $fh "type:debug request to get context failed: $@";
743             } else {
744                 print $fh
745 "type:debug Failed to get context from $t->{in_reply_to_screen_name}\n"
746                   if &debug;
747             }
748         }
749         next
750           if $t->{user}{screen_name} eq $username
751               and not Irssi::settings_get_bool("show_own_tweets");
752         printf $fh "id:%d account:%s nick:%s type:%s %s\n",
753           $t->{id}, $username, $t->{user}{screen_name}, $reply, $text;
754     }
755
756     print scalar localtime, " - Polling for replies" if &debug;
757     eval {
758         $tweets = $obj->replies( { since => HTTP::Date::time2str($last_poll) } )
759           || [];
760     };
761
762     if ($@) {
763         print $fh "type:debug Error during replies call.  Aborted.\n";
764         return 1;
765     }
766
767     foreach my $t ( reverse @$tweets ) {
768         next
769           if exists $friends{ $t->{user}{screen_name} };
770
771         my $text = decode_entities( $t->{text} );
772         $text = &hilight($text);
773         printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
774           $t->{id}, $username, $t->{user}{screen_name}, $text;
775     }
776
777     print scalar localtime, " - Polling for DMs" if &debug;
778     eval {
779         $tweets =
780           $obj->direct_messages( { since => HTTP::Date::time2str($last_poll) } )
781           || [];
782     };
783
784     if ($@) {
785         print $fh "type:debug Error during direct_messages call.  Aborted.\n";
786         return 1;
787     }
788
789     foreach my $t ( reverse @$tweets ) {
790         my $text = decode_entities( $t->{text} );
791         $text = &hilight($text);
792         printf $fh "id:%d account:%s nick:%s type:dm %s\n",
793           $t->{id}, $username, $t->{sender_screen_name}, $text;
794     }
795
796     print scalar localtime, " - Polling for subscriptions" if &debug;
797     if ( $obj->can('search') and $id_map{__searches}{$username} ) {
798         my $search;
799         foreach my $topic ( sort keys %{ $id_map{__searches}{$username} } ) {
800             print $fh "type:debug searching for $topic since ",
801               "$id_map{__searches}{$username}{$topic}\n";
802             eval {
803                 $search = $obj->search(
804                     {
805                         q        => $topic,
806                         since_id => $id_map{__searches}{$username}{$topic}
807                     }
808                 );
809             };
810
811             if ($@) {
812                 print $fh
813                   "type:debug Error during search($topic) call.  Aborted.\n";
814                 return 1;
815             }
816
817             unless ( $search->{max_id} ) {
818                 print $fh
819 "type:debug Invalid search results when searching for $topic.",
820                   "  Aborted.\n";
821                 return 1;
822             }
823
824             $id_map{__searches}{$username}{$topic} = $search->{max_id};
825             printf $fh "id:%d account:%s type:searchid topic:%s\n",
826               $search->{max_id}, $username, $topic;
827
828             foreach my $t ( reverse @{ $search->{results} } ) {
829                 my $text = decode_entities( $t->{text} );
830                 $text = &hilight($text);
831                 printf $fh "id:%d account:%s nick:%s type:search topic:%s %s\n",
832                   $t->{id}, $username, $t->{from_user}, $topic, $text;
833             }
834         }
835     }
836
837     print scalar localtime, " - Done" if &debug;
838
839     return 0;
840 }
841
842 sub monitor_child {
843     my ($data)   = @_;
844     my $filename = $data->[0];
845     my $attempt  = $data->[1];
846
847     print scalar localtime, " - checking child log at $filename ($attempt)"
848       if &debug;
849     my $new_last_poll;
850
851     # first time we run we don't want to print out *everything*, so we just
852     # pretend
853     my $suppress = 0;
854     $suppress = 1 unless keys %tweet_cache;
855
856     if ( open FILE, $filename ) {
857         my @lines;
858         my %new_cache;
859         while (<FILE>) {
860             chomp;
861             last if /^__friends__/;
862             my $hilight = 0;
863             my %meta;
864             foreach my $key (qw/id account nick type topic/) {
865                 if (s/^$key:(\S+)\s*//) {
866                     $meta{$key} = $1;
867                 }
868             }
869
870             if ( not $meta{type} or $meta{type} ne 'searchid' ) {
871                 $new_cache{ $meta{id} } = time;
872
873                 if ( exists $meta{id} and exists $tweet_cache{ $meta{id} } ) {
874                     next;
875                 }
876             }
877
878             my $account = "";
879             if ( $meta{account} ne $user ) {
880                 $account = "$meta{account}: ";
881             }
882
883             my $marker = "";
884             if (    $meta{type} ne 'dm'
885                 and Irssi::settings_get_bool("twirssi_track_replies")
886                 and $meta{nick}
887                 and $meta{id} )
888             {
889                 $marker = ( $id_map{__indexes}{ $meta{nick} } + 1 ) % 100;
890                 $id_map{ lc $meta{nick} }[$marker] = $meta{id};
891                 $id_map{__indexes}{ $meta{nick} }  = $marker;
892                 $marker                            = ":$marker";
893             }
894
895             my $hilight_color =
896               $irssi_to_mirc_colors{ Irssi::settings_get_str("hilight_color") };
897             if ( ( $_ =~ /\@$meta{account}\W/i )
898                 && Irssi::settings_get_bool("twirssi_hilights") )
899             {
900                 $meta{nick} = "\cC$hilight_color$meta{nick}\cO";
901                 $hilight = MSGLEVEL_HILIGHT;
902             }
903
904             if ( $meta{type} =~ /tweet|reply/ ) {
905                 push @lines,
906                   [
907                     ( MSGLEVEL_PUBLIC | $hilight ),
908                     $meta{type}, $account, $meta{nick}, $marker, $_
909                   ];
910             } elsif ( $meta{type} eq 'search' ) {
911                 push @lines,
912                   [
913                     ( MSGLEVEL_PUBLIC | $hilight ),
914                     $meta{type}, $account, $meta{topic},
915                     $meta{nick}, $marker,  $_
916                   ];
917                 if (
918                     exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
919                     and $meta{id} >
920                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
921                 {
922                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
923                       $meta{id};
924                 }
925             } elsif ( $meta{type} eq 'dm' ) {
926                 push @lines,
927                   [
928                     ( MSGLEVEL_MSGS | $hilight ),
929                     $meta{type}, $account, $meta{nick}, $_
930                   ];
931             } elsif ( $meta{type} eq 'searchid' ) {
932                 print "Search '$meta{topic}' returned id $meta{id}" if &debug;
933                 if (
934                     exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
935                     and $meta{id} >=
936                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
937                 {
938                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
939                       $meta{id};
940                 } elsif (&debug) {
941                     print "Search '$meta{topic}' returned invalid id $meta{id}";
942                 }
943             } elsif ( $meta{type} eq 'error' ) {
944                 push @lines, [ MSGLEVEL_MSGS, $_ ];
945             } elsif ( $meta{type} eq 'debug' ) {
946                 print "$_" if &debug,;
947             } else {
948                 print "Unknown line type $meta{type}: $_" if &debug,;
949             }
950         }
951
952         %friends = ();
953         while (<FILE>) {
954             if (/^\d+$/) {
955                 $new_last_poll = $_;
956                 last;
957             }
958             my ( $f, $t ) = split ' ', $_;
959             $nicks{$f} = $friends{$f} = $t;
960         }
961
962         if ($new_last_poll) {
963             print "new last_poll = $new_last_poll" if &debug;
964             if ($suppress) {
965                 print "First call, not printing updates" if &debug;
966             } else {
967                 foreach my $line (@lines) {
968                     $window->printformat(
969                         $line->[0],
970                         "twirssi_" . $line->[1],
971                         @$line[ 2 .. $#$line ]
972                     );
973                 }
974             }
975
976             close FILE;
977             unlink $filename
978               or warn "Failed to remove $filename: $!"
979               unless &debug;
980
981             # commit the pending cache lines to the actual cache, now that
982             # we've printed our output
983             %tweet_cache = ( %tweet_cache, %new_cache );
984
985             # keep enough cached tweets, to make sure we don't show duplicates.
986             foreach ( keys %tweet_cache ) {
987                 next if $tweet_cache{$_} >= $last_poll - 3600;
988                 delete $tweet_cache{$_};
989             }
990             $last_poll = $new_last_poll;
991
992             # save id_map hash
993             if ( keys %id_map
994                 and my $file =
995                 Irssi::settings_get_str("twirssi_replies_store") )
996             {
997                 if ( open JSON, ">$file" ) {
998                     print JSON JSON::Any->objToJson( \%id_map );
999                     close JSON;
1000                 } else {
1001                     &notice("Failed to write replies to $file: $!");
1002                 }
1003             }
1004             $failwhale = 0;
1005             return;
1006         }
1007     }
1008
1009     close FILE;
1010
1011     if ( $attempt < 24 ) {
1012         Irssi::timeout_add_once( 5000, 'monitor_child',
1013             [ $filename, $attempt + 1 ] );
1014     } else {
1015         print "Giving up on polling $filename" if &debug;
1016         unlink $filename unless &debug;
1017
1018         return unless Irssi::settings_get_bool("twirssi_notify_timeouts");
1019
1020         my $since;
1021         my @time = localtime($last_poll);
1022         if ( time - $last_poll < 24 * 60 * 60 ) {
1023             $since = sprintf( "%d:%02d", @time[ 2, 1 ] );
1024         } else {
1025             $since = scalar localtime($last_poll);
1026         }
1027
1028         if ( not $failwhale and time - $last_poll > 60 * 60 ) {
1029             foreach my $whale (
1030                 q{     v  v        v},
1031                 q{     |  |  v     |  v},
1032                 q{     | .-, |     |  |},
1033                 q{  .--./ /  |  _.---.| },
1034                 q{   '-. (__..-"       \\},
1035                 q{      \\          a    |},
1036                 q{       ',.__.   ,__.-'/},
1037                 q{         '--/_.'----'`}
1038               )
1039             {
1040                 &notice($whale);
1041             }
1042             $failwhale = 1;
1043         }
1044         &notice("Haven't been able to get updated tweets since $since");
1045     }
1046 }
1047
1048 sub debug {
1049     return Irssi::settings_get_bool("twirssi_debug");
1050 }
1051
1052 sub notice {
1053     $window->print( "%R***%n @_", MSGLEVEL_PUBLIC );
1054 }
1055
1056 sub update_away {
1057     my $data = shift;
1058
1059     if (    Irssi::settings_get_bool("tweet_to_away")
1060         and $data !~ /\@\w/
1061         and $data !~ /^[dD] / )
1062     {
1063         my $server =
1064           Irssi::server_find_tag( Irssi::settings_get_str("bitlbee_server") );
1065         if ($server) {
1066             $server->send_raw("away :$data");
1067             return 1;
1068         } else {
1069             &notice( "Can't find bitlbee server.",
1070                 "Update bitlbee_server or disable tweet_to_away" );
1071             return 0;
1072         }
1073     }
1074
1075     return 0;
1076 }
1077
1078 sub too_long {
1079     my $data    = shift;
1080     my $noalert = shift;
1081
1082     if ( length $data > 140 ) {
1083         &notice( "Tweet too long (" . length($data) . " characters) - aborted" )
1084           unless $noalert;
1085         return 1;
1086     }
1087
1088     return 0;
1089 }
1090
1091 sub valid_username {
1092     my $username = shift;
1093
1094     unless ( exists $twits{$username} ) {
1095         &notice("Unknown username $username");
1096         return 0;
1097     }
1098
1099     return 1;
1100 }
1101
1102 sub logged_in {
1103     my $obj = shift;
1104     unless ($obj) {
1105         &notice("Not logged in!  Use /twitter_login username pass!");
1106         return 0;
1107     }
1108
1109     return 1;
1110 }
1111
1112 sub sig_complete {
1113     my ( $complist, $window, $word, $linestart, $want_space ) = @_;
1114
1115     if (
1116         $linestart =~ /^\/twitter_reply(?:_as)?\s*$/
1117         or ( Irssi::settings_get_bool("twirssi_use_reply_aliases")
1118             and $linestart =~ /^\/reply(?:_as)?\s*$/ )
1119       )
1120     {    # /twitter_reply gets a nick:num
1121         $word =~ s/^@//;
1122         @$complist = map { "$_:$id_map{__indexes}{$_}" } grep /^\Q$word/i,
1123           sort keys %{ $id_map{__indexes} };
1124     }
1125
1126     # /tweet, /tweet_as, /dm, /dm_as - complete @nicks (and nicks as the first
1127     # arg to dm)
1128     if ( $linestart =~ /^\/(?:tweet|dm)/ ) {
1129         my $prefix = $word =~ s/^@//;
1130         $prefix = 0 if $linestart eq '/dm' or $linestart eq '/dm_as';
1131         push @$complist, grep /^\Q$word/i,
1132           sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1133         @$complist = map { "\@$_" } @$complist if $prefix;
1134     }
1135 }
1136
1137 sub event_send_text {
1138     my ( $line, $server, $win ) = @_;
1139     my $awin = Irssi::active_win();
1140
1141     # if the window where we got our text was the twitter window, and the user
1142     # wants to be lazy, tweet away!
1143     if ( ( $awin->get_active_name() eq $window->{name} )
1144         and Irssi::settings_get_bool("tweet_window_input") )
1145     {
1146         &cmd_tweet( $line, $server, $win );
1147     }
1148 }
1149
1150 sub get_poll_time {
1151     my $poll = Irssi::settings_get_int("twitter_poll_interval");
1152     return $poll if $poll >= 60;
1153     return 60;
1154 }
1155
1156 sub hilight {
1157     my $text = shift;
1158
1159     if ( Irssi::settings_get_str("twirssi_nick_color") ) {
1160         my $c = Irssi::settings_get_str("twirssi_nick_color");
1161         $c = $irssi_to_mirc_colors{$c};
1162         $text =~ s/(^|\W)\@([-\w]+)/$1\cC$c\@$2\cO/g if $c;
1163     }
1164     if ( Irssi::settings_get_str("twirssi_topic_color") ) {
1165         my $c = Irssi::settings_get_str("twirssi_topic_color");
1166         $c = $irssi_to_mirc_colors{$c};
1167         $text =~ s/(^|\W)\#([-\w]+)/$1\cC$c\#$2\cO/g if $c;
1168     }
1169     $text =~ s/[\n\r]/ /g;
1170
1171     return $text;
1172 }
1173
1174 Irssi::signal_add( "send text", "event_send_text" );
1175
1176 Irssi::theme_register(
1177     [
1178         'twirssi_tweet',  '[$0%B@$1%n$2] $3',
1179         'twirssi_search', '[$0%r$1%n:%B@$2%n$3] $4',
1180         'twirssi_reply',  '[$0\--> %B@$1%n$2] $3',
1181         'twirssi_dm',     '[$0%r@$1%n (%WDM%n)] $2',
1182         'twirssi_error',  'ERROR: $0',
1183     ]
1184 );
1185
1186 Irssi::settings_add_int( "twirssi", "twitter_poll_interval", 300 );
1187 Irssi::settings_add_str( "twirssi", "twitter_window",     "twitter" );
1188 Irssi::settings_add_str( "twirssi", "bitlbee_server",     "bitlbee" );
1189 Irssi::settings_add_str( "twirssi", "short_url_provider", "TinyURL" );
1190 Irssi::settings_add_str( "twirssi", "twirssi_location",
1191     ".irssi/scripts/twirssi.pl" );
1192 Irssi::settings_add_str( "twirssi", "twitter_usernames", undef );
1193 Irssi::settings_add_str( "twirssi", "twitter_passwords", undef );
1194 Irssi::settings_add_str( "twirssi", "twirssi_replies_store",
1195     ".irssi/scripts/twirssi.json" );
1196 Irssi::settings_add_str( "twirssi", "twirssi_nick_color",  "%B" );
1197 Irssi::settings_add_str( "twirssi", "twirssi_topic_color", "%r" );
1198 Irssi::settings_add_bool( "twirssi", "twirssi_upgrade_beta",      0 );
1199 Irssi::settings_add_bool( "twirssi", "tweet_to_away",             0 );
1200 Irssi::settings_add_bool( "twirssi", "show_reply_context",        0 );
1201 Irssi::settings_add_bool( "twirssi", "show_own_tweets",           1 );
1202 Irssi::settings_add_bool( "twirssi", "twirssi_debug",             0 );
1203 Irssi::settings_add_bool( "twirssi", "twirssi_first_run",         1 );
1204 Irssi::settings_add_bool( "twirssi", "twirssi_track_replies",     1 );
1205 Irssi::settings_add_bool( "twirssi", "twirssi_replies_autonick",  1 );
1206 Irssi::settings_add_bool( "twirssi", "twirssi_use_reply_aliases", 0 );
1207 Irssi::settings_add_bool( "twirssi", "twirssi_notify_timeouts",   1 );
1208 Irssi::settings_add_bool( "twirssi", "twirssi_hilights",          1 );
1209 Irssi::settings_add_bool( "twirssi", "tweet_window_input",        0 );
1210
1211 $last_poll = time - &get_poll_time;
1212 $window = Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
1213 if ( !$window ) {
1214     $window =
1215       Irssi::Windowitem::window_create(
1216         Irssi::settings_get_str('twitter_window'), 1 );
1217     $window->set_name( Irssi::settings_get_str('twitter_window') );
1218 }
1219
1220 if ($window) {
1221     Irssi::command_bind( "dm",                         "cmd_direct" );
1222     Irssi::command_bind( "dm_as",                      "cmd_direct_as" );
1223     Irssi::command_bind( "tweet",                      "cmd_tweet" );
1224     Irssi::command_bind( "tweet_as",                   "cmd_tweet_as" );
1225     Irssi::command_bind( "twitter_reply",              "cmd_reply" );
1226     Irssi::command_bind( "twitter_reply_as",           "cmd_reply_as" );
1227     Irssi::command_bind( "twitter_login",              "cmd_login" );
1228     Irssi::command_bind( "twitter_logout",             "cmd_logout" );
1229     Irssi::command_bind( "twitter_switch",             "cmd_switch" );
1230     Irssi::command_bind( "twitter_subscribe",          "cmd_add_search" );
1231     Irssi::command_bind( "twitter_unsubscribe",        "cmd_del_search" );
1232     Irssi::command_bind( "twitter_list_subscriptions", "cmd_list_search" );
1233     Irssi::command_bind( "twirssi_upgrade",            "cmd_upgrade" );
1234     if ( Irssi::settings_get_bool("twirssi_use_reply_aliases") ) {
1235         Irssi::command_bind( "reply",    "cmd_reply" );
1236         Irssi::command_bind( "reply_as", "cmd_reply_as" );
1237     }
1238     Irssi::command_bind(
1239         "twirssi_dump",
1240         sub {
1241             print "twits: ", join ", ",
1242               map { "u: $_->{username}" } values %twits;
1243             print "friends: ", join ", ", sort keys %friends;
1244             print "nicks: ",   join ", ", sort keys %nicks;
1245             print "searches: ", Dumper \%{ $id_map{__searches} };
1246             print "last poll: $last_poll";
1247             if ( open DUMP, ">/tmp/twirssi.cache.txt" ) {
1248                 print DUMP Dumper \%tweet_cache;
1249                 close DUMP;
1250                 print "cache written out to /tmp/twirssi.cache.txt";
1251             }
1252         }
1253     );
1254     Irssi::command_bind(
1255         "twirssi_version",
1256         sub {
1257             &notice("Twirssi v$VERSION (r$REV); "
1258                   . "Net::Twitter v$Net::Twitter::VERSION. "
1259                   . "JSON in use: "
1260                   . JSON::Any::handler()
1261                   . ".  See details at http://twirssi.com/" );
1262         }
1263     );
1264     Irssi::command_bind(
1265         "twitter_friend",
1266         &gen_cmd(
1267             "/twitter_friend <username>",
1268             "create_friend",
1269             sub { &notice("Following $_[0]"); $nicks{ $_[0] } = time; }
1270         )
1271     );
1272     Irssi::command_bind(
1273         "twitter_unfriend",
1274         &gen_cmd(
1275             "/twitter_unfriend <username>",
1276             "destroy_friend",
1277             sub { &notice("Stopped following $_[0]"); delete $nicks{ $_[0] }; }
1278         )
1279     );
1280     Irssi::command_bind( "twitter_updates", "get_updates" );
1281     Irssi::signal_add_last( 'complete word' => \&sig_complete );
1282
1283     &notice("  %Y<%C(%B^%C)%N                   TWIRSSI v%R$VERSION%N (r$REV)");
1284     &notice("   %C(_(\\%N           http://twirssi.com/ for full docs");
1285     &notice(
1286         "    %Y||%C `%N Log in with /twitter_login, send updates with /tweet");
1287
1288     my $file = Irssi::settings_get_str("twirssi_replies_store");
1289     if ( $file and -r $file ) {
1290         if ( open( JSON, $file ) ) {
1291             local $/;
1292             my $json = <JSON>;
1293             close JSON;
1294             eval {
1295                 my $ref = JSON::Any->jsonToObj($json);
1296                 %id_map = %$ref;
1297                 my $num = keys %{ $id_map{__indexes} };
1298                 &notice( sprintf "Loaded old replies from %d contact%s.",
1299                     $num, ( $num == 1 ? "" : "s" ) );
1300                 &cmd_list_search;
1301             };
1302         } else {
1303             &notice("Failed to load old replies from $file: $!");
1304         }
1305     }
1306
1307     if ( my $provider = Irssi::settings_get_str("short_url_provider") ) {
1308         eval "use WWW::Shorten::$provider;";
1309
1310         if ($@) {
1311             &notice(
1312 "Failed to load WWW::Shorten::$provider - either clear short_url_provider or install the CPAN module"
1313             );
1314         }
1315     }
1316
1317     if (    my $autouser = Irssi::settings_get_str("twitter_usernames")
1318         and my $autopass = Irssi::settings_get_str("twitter_passwords") )
1319     {
1320         &cmd_login();
1321         &get_updates;
1322     }
1323
1324 } else {
1325     Irssi::active_win()
1326       ->print( "Create a window named "
1327           . Irssi::settings_get_str('twitter_window')
1328           . " or change the value of twitter_window.  Then, reload twirssi." );
1329 }
1330
1331 # vim: set sts=4 expandtab: