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