60257b49e4915ce30b23c4d303d5b39c43260b1c
[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.1";
15 my ($REV) = '$Rev: 494 $' =~ /(\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 15:20:08 -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 or Irssi::settings_get_bool("twirssi_upgrade_beta") ) {
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                 if ( exists $meta{id} and exists $new_cache{ $meta{id} } ) {
872                     next;
873                 }
874
875                 $new_cache{ $meta{id} } = time;
876
877                 if ( exists $meta{id} and exists $tweet_cache{ $meta{id} } ) {
878                     next;
879                 }
880             }
881
882             my $account = "";
883             if ( $meta{account} ne $user ) {
884                 $account = "$meta{account}: ";
885             }
886
887             my $marker = "";
888             if (    $meta{type} ne 'dm'
889                 and Irssi::settings_get_bool("twirssi_track_replies")
890                 and $meta{nick}
891                 and $meta{id} )
892             {
893                 $marker = ( $id_map{__indexes}{ $meta{nick} } + 1 ) % 100;
894                 $id_map{ lc $meta{nick} }[$marker] = $meta{id};
895                 $id_map{__indexes}{ $meta{nick} }  = $marker;
896                 $marker                            = ":$marker";
897             }
898
899             my $hilight_color =
900               $irssi_to_mirc_colors{ Irssi::settings_get_str("hilight_color") };
901             if ( ( $_ =~ /\@$meta{account}\W/i )
902                 && Irssi::settings_get_bool("twirssi_hilights") )
903             {
904                 $meta{nick} = "\cC$hilight_color$meta{nick}\cO";
905                 $hilight = MSGLEVEL_HILIGHT;
906             }
907
908             if ( $meta{type} =~ /tweet|reply/ ) {
909                 push @lines,
910                   [
911                     ( MSGLEVEL_PUBLIC | $hilight ),
912                     $meta{type}, $account, $meta{nick}, $marker, $_
913                   ];
914             } elsif ( $meta{type} eq 'search' ) {
915                 push @lines,
916                   [
917                     ( MSGLEVEL_PUBLIC | $hilight ),
918                     $meta{type}, $account, $meta{topic},
919                     $meta{nick}, $marker,  $_
920                   ];
921                 if (
922                     exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
923                     and $meta{id} >
924                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
925                 {
926                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
927                       $meta{id};
928                 }
929             } elsif ( $meta{type} eq 'dm' ) {
930                 push @lines,
931                   [
932                     ( MSGLEVEL_MSGS | $hilight ),
933                     $meta{type}, $account, $meta{nick}, $_
934                   ];
935             } elsif ( $meta{type} eq 'searchid' ) {
936                 print "Search '$meta{topic}' returned id $meta{id}" if &debug;
937                 if (
938                     exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
939                     and $meta{id} >=
940                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
941                 {
942                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
943                       $meta{id};
944                 } elsif (&debug) {
945                     print "Search '$meta{topic}' returned invalid id $meta{id}";
946                 }
947             } elsif ( $meta{type} eq 'error' ) {
948                 push @lines, [ MSGLEVEL_MSGS, $_ ];
949             } elsif ( $meta{type} eq 'debug' ) {
950                 print "$_" if &debug,;
951             } else {
952                 print "Unknown line type $meta{type}: $_" if &debug,;
953             }
954         }
955
956         %friends = ();
957         while (<FILE>) {
958             if (/^\d+$/) {
959                 $new_last_poll = $_;
960                 last;
961             }
962             my ( $f, $t ) = split ' ', $_;
963             $nicks{$f} = $friends{$f} = $t;
964         }
965
966         if ($new_last_poll) {
967             print "new last_poll = $new_last_poll" if &debug;
968             if ($suppress) {
969                 print "First call, not printing updates" if &debug;
970             } else {
971                 foreach my $line (@lines) {
972                     $window->printformat(
973                         $line->[0],
974                         "twirssi_" . $line->[1],
975                         @$line[ 2 .. $#$line ]
976                     );
977                 }
978             }
979
980             close FILE;
981             unlink $filename
982               or warn "Failed to remove $filename: $!"
983               unless &debug;
984
985             # commit the pending cache lines to the actual cache, now that
986             # we've printed our output
987             %tweet_cache = ( %tweet_cache, %new_cache );
988
989             # keep enough cached tweets, to make sure we don't show duplicates.
990             foreach ( keys %tweet_cache ) {
991                 next if $tweet_cache{$_} >= $last_poll - 3600;
992                 delete $tweet_cache{$_};
993             }
994             $last_poll = $new_last_poll;
995
996             # save id_map hash
997             if ( keys %id_map
998                 and my $file =
999                 Irssi::settings_get_str("twirssi_replies_store") )
1000             {
1001                 if ( open JSON, ">$file" ) {
1002                     print JSON JSON::Any->objToJson( \%id_map );
1003                     close JSON;
1004                 } else {
1005                     &notice("Failed to write replies to $file: $!");
1006                 }
1007             }
1008             $failwhale = 0;
1009             return;
1010         }
1011     }
1012
1013     close FILE;
1014
1015     if ( $attempt < 24 ) {
1016         Irssi::timeout_add_once( 5000, 'monitor_child',
1017             [ $filename, $attempt + 1 ] );
1018     } else {
1019         print "Giving up on polling $filename" if &debug;
1020         unlink $filename unless &debug;
1021
1022         return unless Irssi::settings_get_bool("twirssi_notify_timeouts");
1023
1024         my $since;
1025         my @time = localtime($last_poll);
1026         if ( time - $last_poll < 24 * 60 * 60 ) {
1027             $since = sprintf( "%d:%02d", @time[ 2, 1 ] );
1028         } else {
1029             $since = scalar localtime($last_poll);
1030         }
1031
1032         if ( not $failwhale and time - $last_poll > 60 * 60 ) {
1033             foreach my $whale (
1034                 q{     v  v        v},
1035                 q{     |  |  v     |  v},
1036                 q{     | .-, |     |  |},
1037                 q{  .--./ /  |  _.---.| },
1038                 q{   '-. (__..-"       \\},
1039                 q{      \\          a    |},
1040                 q{       ',.__.   ,__.-'/},
1041                 q{         '--/_.'----'`}
1042               )
1043             {
1044                 &notice($whale);
1045             }
1046             $failwhale = 1;
1047         }
1048         &notice("Haven't been able to get updated tweets since $since");
1049     }
1050 }
1051
1052 sub debug {
1053     return Irssi::settings_get_bool("twirssi_debug");
1054 }
1055
1056 sub notice {
1057     $window->print( "%R***%n @_", MSGLEVEL_PUBLIC );
1058 }
1059
1060 sub update_away {
1061     my $data = shift;
1062
1063     if (    Irssi::settings_get_bool("tweet_to_away")
1064         and $data !~ /\@\w/
1065         and $data !~ /^[dD] / )
1066     {
1067         my $server =
1068           Irssi::server_find_tag( Irssi::settings_get_str("bitlbee_server") );
1069         if ($server) {
1070             $server->send_raw("away :$data");
1071             return 1;
1072         } else {
1073             &notice( "Can't find bitlbee server.",
1074                 "Update bitlbee_server or disable tweet_to_away" );
1075             return 0;
1076         }
1077     }
1078
1079     return 0;
1080 }
1081
1082 sub too_long {
1083     my $data    = shift;
1084     my $noalert = shift;
1085
1086     if ( length $data > 140 ) {
1087         &notice( "Tweet too long (" . length($data) . " characters) - aborted" )
1088           unless $noalert;
1089         return 1;
1090     }
1091
1092     return 0;
1093 }
1094
1095 sub valid_username {
1096     my $username = shift;
1097
1098     unless ( exists $twits{$username} ) {
1099         &notice("Unknown username $username");
1100         return 0;
1101     }
1102
1103     return 1;
1104 }
1105
1106 sub logged_in {
1107     my $obj = shift;
1108     unless ($obj) {
1109         &notice("Not logged in!  Use /twitter_login username pass!");
1110         return 0;
1111     }
1112
1113     return 1;
1114 }
1115
1116 sub sig_complete {
1117     my ( $complist, $window, $word, $linestart, $want_space ) = @_;
1118
1119     if (
1120         $linestart =~ /^\/twitter_reply(?:_as)?\s*$/
1121         or ( Irssi::settings_get_bool("twirssi_use_reply_aliases")
1122             and $linestart =~ /^\/reply(?:_as)?\s*$/ )
1123       )
1124     {    # /twitter_reply gets a nick:num
1125         $word =~ s/^@//;
1126         @$complist = map { "$_:$id_map{__indexes}{$_}" } grep /^\Q$word/i,
1127           sort keys %{ $id_map{__indexes} };
1128     }
1129
1130     # /tweet, /tweet_as, /dm, /dm_as - complete @nicks (and nicks as the first
1131     # arg to dm)
1132     if ( $linestart =~ /^\/(?:tweet|dm)/ ) {
1133         my $prefix = $word =~ s/^@//;
1134         $prefix = 0 if $linestart eq '/dm' or $linestart eq '/dm_as';
1135         push @$complist, grep /^\Q$word/i,
1136           sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1137         @$complist = map { "\@$_" } @$complist if $prefix;
1138     }
1139 }
1140
1141 sub event_send_text {
1142     my ( $line, $server, $win ) = @_;
1143     my $awin = Irssi::active_win();
1144
1145     # if the window where we got our text was the twitter window, and the user
1146     # wants to be lazy, tweet away!
1147     if ( ( $awin->get_active_name() eq $window->{name} )
1148         and Irssi::settings_get_bool("tweet_window_input") )
1149     {
1150         &cmd_tweet( $line, $server, $win );
1151     }
1152 }
1153
1154 sub get_poll_time {
1155     my $poll = Irssi::settings_get_int("twitter_poll_interval");
1156     return $poll if $poll >= 60;
1157     return 60;
1158 }
1159
1160 sub hilight {
1161     my $text = shift;
1162
1163     if ( Irssi::settings_get_str("twirssi_nick_color") ) {
1164         my $c = Irssi::settings_get_str("twirssi_nick_color");
1165         $c = $irssi_to_mirc_colors{$c};
1166         $text =~ s/(^|\W)\@([-\w]+)/$1\cC$c\@$2\cO/g if $c;
1167     }
1168     if ( Irssi::settings_get_str("twirssi_topic_color") ) {
1169         my $c = Irssi::settings_get_str("twirssi_topic_color");
1170         $c = $irssi_to_mirc_colors{$c};
1171         $text =~ s/(^|\W)\#([-\w]+)/$1\cC$c\#$2\cO/g if $c;
1172     }
1173     $text =~ s/[\n\r]/ /g;
1174
1175     return $text;
1176 }
1177
1178 Irssi::signal_add( "send text", "event_send_text" );
1179
1180 Irssi::theme_register(
1181     [
1182         'twirssi_tweet',  '[$0%B@$1%n$2] $3',
1183         'twirssi_search', '[$0%r$1%n:%B@$2%n$3] $4',
1184         'twirssi_reply',  '[$0\--> %B@$1%n$2] $3',
1185         'twirssi_dm',     '[$0%r@$1%n (%WDM%n)] $2',
1186         'twirssi_error',  'ERROR: $0',
1187     ]
1188 );
1189
1190 Irssi::settings_add_int( "twirssi", "twitter_poll_interval", 300 );
1191 Irssi::settings_add_str( "twirssi", "twitter_window",     "twitter" );
1192 Irssi::settings_add_str( "twirssi", "bitlbee_server",     "bitlbee" );
1193 Irssi::settings_add_str( "twirssi", "short_url_provider", "TinyURL" );
1194 Irssi::settings_add_str( "twirssi", "twirssi_location",
1195     ".irssi/scripts/twirssi.pl" );
1196 Irssi::settings_add_str( "twirssi", "twitter_usernames", undef );
1197 Irssi::settings_add_str( "twirssi", "twitter_passwords", undef );
1198 Irssi::settings_add_str( "twirssi", "twirssi_replies_store",
1199     ".irssi/scripts/twirssi.json" );
1200 Irssi::settings_add_str( "twirssi", "twirssi_nick_color",  "%B" );
1201 Irssi::settings_add_str( "twirssi", "twirssi_topic_color", "%r" );
1202 Irssi::settings_add_bool( "twirssi", "twirssi_upgrade_beta",      0 );
1203 Irssi::settings_add_bool( "twirssi", "tweet_to_away",             0 );
1204 Irssi::settings_add_bool( "twirssi", "show_reply_context",        0 );
1205 Irssi::settings_add_bool( "twirssi", "show_own_tweets",           1 );
1206 Irssi::settings_add_bool( "twirssi", "twirssi_debug",             0 );
1207 Irssi::settings_add_bool( "twirssi", "twirssi_first_run",         1 );
1208 Irssi::settings_add_bool( "twirssi", "twirssi_track_replies",     1 );
1209 Irssi::settings_add_bool( "twirssi", "twirssi_replies_autonick",  1 );
1210 Irssi::settings_add_bool( "twirssi", "twirssi_use_reply_aliases", 0 );
1211 Irssi::settings_add_bool( "twirssi", "twirssi_notify_timeouts",   1 );
1212 Irssi::settings_add_bool( "twirssi", "twirssi_hilights",          1 );
1213 Irssi::settings_add_bool( "twirssi", "tweet_window_input",        0 );
1214
1215 $last_poll = time - &get_poll_time;
1216 $window = Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
1217 if ( !$window ) {
1218     $window =
1219       Irssi::Windowitem::window_create(
1220         Irssi::settings_get_str('twitter_window'), 1 );
1221     $window->set_name( Irssi::settings_get_str('twitter_window') );
1222 }
1223
1224 if ($window) {
1225     Irssi::command_bind( "dm",                         "cmd_direct" );
1226     Irssi::command_bind( "dm_as",                      "cmd_direct_as" );
1227     Irssi::command_bind( "tweet",                      "cmd_tweet" );
1228     Irssi::command_bind( "tweet_as",                   "cmd_tweet_as" );
1229     Irssi::command_bind( "twitter_reply",              "cmd_reply" );
1230     Irssi::command_bind( "twitter_reply_as",           "cmd_reply_as" );
1231     Irssi::command_bind( "twitter_login",              "cmd_login" );
1232     Irssi::command_bind( "twitter_logout",             "cmd_logout" );
1233     Irssi::command_bind( "twitter_switch",             "cmd_switch" );
1234     Irssi::command_bind( "twitter_subscribe",          "cmd_add_search" );
1235     Irssi::command_bind( "twitter_unsubscribe",        "cmd_del_search" );
1236     Irssi::command_bind( "twitter_list_subscriptions", "cmd_list_search" );
1237     Irssi::command_bind( "twirssi_upgrade",            "cmd_upgrade" );
1238     if ( Irssi::settings_get_bool("twirssi_use_reply_aliases") ) {
1239         Irssi::command_bind( "reply",    "cmd_reply" );
1240         Irssi::command_bind( "reply_as", "cmd_reply_as" );
1241     }
1242     Irssi::command_bind(
1243         "twirssi_dump",
1244         sub {
1245             print "twits: ", join ", ",
1246               map { "u: $_->{username}" } values %twits;
1247             print "friends: ", join ", ", sort keys %friends;
1248             print "nicks: ",   join ", ", sort keys %nicks;
1249             print "searches: ", Dumper \%{ $id_map{__searches} };
1250             print "last poll: $last_poll";
1251             if ( open DUMP, ">/tmp/twirssi.cache.txt" ) {
1252                 print DUMP Dumper \%tweet_cache;
1253                 close DUMP;
1254                 print "cache written out to /tmp/twirssi.cache.txt";
1255             }
1256         }
1257     );
1258     Irssi::command_bind(
1259         "twirssi_version",
1260         sub {
1261             &notice("Twirssi v$VERSION (r$REV); "
1262                   . "Net::Twitter v$Net::Twitter::VERSION. "
1263                   . "JSON in use: "
1264                   . JSON::Any::handler()
1265                   . ".  See details at http://twirssi.com/" );
1266         }
1267     );
1268     Irssi::command_bind(
1269         "twitter_friend",
1270         &gen_cmd(
1271             "/twitter_friend <username>",
1272             "create_friend",
1273             sub { &notice("Following $_[0]"); $nicks{ $_[0] } = time; }
1274         )
1275     );
1276     Irssi::command_bind(
1277         "twitter_unfriend",
1278         &gen_cmd(
1279             "/twitter_unfriend <username>",
1280             "destroy_friend",
1281             sub { &notice("Stopped following $_[0]"); delete $nicks{ $_[0] }; }
1282         )
1283     );
1284     Irssi::command_bind( "twitter_updates", "get_updates" );
1285     Irssi::signal_add_last( 'complete word' => \&sig_complete );
1286
1287     &notice("  %Y<%C(%B^%C)%N                   TWIRSSI v%R$VERSION%N (r$REV)");
1288     &notice("   %C(_(\\%N           http://twirssi.com/ for full docs");
1289     &notice(
1290         "    %Y||%C `%N Log in with /twitter_login, send updates with /tweet");
1291
1292     my $file = Irssi::settings_get_str("twirssi_replies_store");
1293     if ( $file and -r $file ) {
1294         if ( open( JSON, $file ) ) {
1295             local $/;
1296             my $json = <JSON>;
1297             close JSON;
1298             eval {
1299                 my $ref = JSON::Any->jsonToObj($json);
1300                 %id_map = %$ref;
1301                 my $num = keys %{ $id_map{__indexes} };
1302                 &notice( sprintf "Loaded old replies from %d contact%s.",
1303                     $num, ( $num == 1 ? "" : "s" ) );
1304                 &cmd_list_search;
1305             };
1306         } else {
1307             &notice("Failed to load old replies from $file: $!");
1308         }
1309     }
1310
1311     if ( my $provider = Irssi::settings_get_str("short_url_provider") ) {
1312         eval "use WWW::Shorten::$provider;";
1313
1314         if ($@) {
1315             &notice(
1316 "Failed to load WWW::Shorten::$provider - either clear short_url_provider or install the CPAN module"
1317             );
1318         }
1319     }
1320
1321     if (    my $autouser = Irssi::settings_get_str("twitter_usernames")
1322         and my $autopass = Irssi::settings_get_str("twitter_passwords") )
1323     {
1324         &cmd_login();
1325         &get_updates;
1326     }
1327
1328 } else {
1329     Irssi::active_win()
1330       ->print( "Create a window named "
1331           . Irssi::settings_get_str('twitter_window')
1332           . " or change the value of twitter_window.  Then, reload twirssi." );
1333 }
1334
1335 # vim: set sts=4 expandtab: