7ba9fe92b5175847a1d7e8a6ff5eaf0c7581ba57
[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.2";
15 my ($REV) = '$Rev: 454 $' =~ /(\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-04 13:35:29 -0800 (Wed, 04 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 %irssi_to_mirc_colors = (
38     '%k' => '01',
39     '%r' => '05',
40     '%g' => '03',
41     '%y' => '07',
42     '%b' => '02',
43     '%m' => '06',
44     '%c' => '10',
45     '%w' => '15',
46     '%K' => '14',
47     '%R' => '04',
48     '%G' => '09',
49     '%Y' => '08',
50     '%B' => '12',
51     '%M' => '13',
52     '%C' => '11',
53     '%W' => '00',
54 );
55
56 sub cmd_direct {
57     my ( $data, $server, $win ) = @_;
58
59     return unless &logged_in($twit);
60
61     my ( $target, $text ) = split ' ', $data, 2;
62     unless ( $target and $text ) {
63         &notice("Usage: /dm <nick> <message>");
64         return;
65     }
66
67     &cmd_direct_as( "$user $data", $server, $win );
68 }
69
70 sub cmd_direct_as {
71     my ( $data, $server, $win ) = @_;
72
73     return unless &logged_in($twit);
74
75     my ( $username, $target, $text ) = split ' ', $data, 3;
76     unless ( $username and $target and $text ) {
77         &notice("Usage: /dm_as <username> <nick> <message>");
78         return;
79     }
80
81     return unless &valid_username($username);
82
83     eval {
84         unless ( $twits{$username}
85             ->new_direct_message( { user => $target, text => $text } ) )
86         {
87             &notice("DM to $target failed");
88             return;
89         }
90     };
91
92     if ($@) {
93         &notice("DM caused an error.  Aborted");
94         return;
95     }
96
97     &notice("DM sent to $target");
98     $nicks{$target} = time;
99 }
100
101 sub cmd_tweet {
102     my ( $data, $server, $win ) = @_;
103
104     return unless &logged_in($twit);
105
106     $data =~ s/^\s+|\s+$//;
107     unless ($data) {
108         &notice("Usage: /tweet <update>");
109         return;
110     }
111
112     &cmd_tweet_as( "$user $data", $server, $win );
113 }
114
115 sub cmd_tweet_as {
116     my ( $data, $server, $win ) = @_;
117
118     return unless &logged_in($twit);
119
120     $data =~ s/^\s+|\s+$//;
121     my ( $username, $data ) = split ' ', $data, 2;
122
123     unless ( $username and $data ) {
124         &notice("Usage: /tweet_as <username> <update>");
125         return;
126     }
127
128     return unless &valid_username($username);
129
130     if ( &too_long( $data, 1 )
131         and Irssi::settings_get_str("short_url_provider") )
132     {
133         foreach my $url ( $data =~ /(https?:\/\/\S+[\w\/])/g ) {
134             eval {
135                 my $short = makeashorterlink($url);
136                 $data =~ s/\Q$url/$short/g;
137             };
138         }
139     }
140
141     return if &too_long($data);
142
143     eval {
144         unless ( $twits{$username}->update($data) )
145         {
146             &notice("Update failed");
147             return;
148         }
149     };
150
151     if ($@) {
152         &notice("Update caused an error.  Aborted.");
153         return;
154     }
155
156     foreach ( $data =~ /@([-\w]+)/ ) {
157         $nicks{$1} = time;
158     }
159
160     my $away = &update_away($data);
161
162     &notice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
163 }
164
165 sub cmd_reply {
166     my ( $data, $server, $win ) = @_;
167
168     return unless &logged_in($twit);
169
170     $data =~ s/^\s+|\s+$//;
171     unless ($data) {
172         &notice("Usage: /reply <nick[:num]> <update>");
173         return;
174     }
175
176     $data =~ s/^\s+|\s+$//;
177     my ( $id, $data ) = split ' ', $data, 2;
178     unless ( $id and $data ) {
179         &notice("Usage: /reply_as <nick[:num]> <update>");
180         return;
181     }
182
183     &cmd_reply_as( "$user $id $data", $server, $win );
184 }
185
186 sub cmd_reply_as {
187     my ( $data, $server, $win ) = @_;
188
189     unless ( Irssi::settings_get_bool("twirssi_track_replies") ) {
190         &notice("twirssi_track_replies is required in order to reply to "
191               . "specific tweets.  Either enable it, or just use /tweet "
192               . "\@username <text>." );
193         return;
194     }
195
196     return unless &logged_in($twit);
197
198     $data =~ s/^\s+|\s+$//;
199     my ( $username, $id, $data ) = split ' ', $data, 3;
200
201     unless ( $username and $data ) {
202         &notice("Usage: /reply_as <username> <nick[:num]> <update>");
203         return;
204     }
205
206     return unless &valid_username($username);
207
208     my $nick;
209     $id =~ s/[^\w\d\-:]+//g;
210     ( $nick, $id ) = split /:/, $id;
211     unless ( exists $id_map{ lc $nick } ) {
212         &notice("Can't find a tweet from $nick to reply to!");
213         return;
214     }
215
216     $id = $id_map{__indexes}{$nick} unless $id;
217     unless ( $id_map{ lc $nick }[$id] ) {
218         &notice("Can't find a tweet numbered $id from $nick to reply to!");
219         return;
220     }
221
222     if ( Irssi::settings_get_bool("twirssi_replies_autonick") ) {
223
224         # remove any @nick at the beginning of the reply, as we'll add it anyway
225         $data =~ s/^\s*\@?$nick\s*//;
226         $data = "\@$nick " . $data;
227     }
228
229     if ( Irssi::settings_get_str("short_url_provider") ) {
230         foreach my $url ( $data =~ /(https?:\/\/\S+[\w\/])/g ) {
231             eval {
232                 my $short = makeashorterlink($url);
233                 $data =~ s/\Q$url/$short/g;
234             };
235         }
236     }
237
238     return if &too_long($data);
239
240     eval {
241         unless (
242             $twits{$username}->update(
243                 {
244                     status                => $data,
245                     in_reply_to_status_id => $id_map{ lc $nick }[$id]
246                 }
247             )
248           )
249         {
250             &notice("Update failed");
251             return;
252         }
253     };
254
255     if ($@) {
256         &notice("Update caused an error.  Aborted");
257         return;
258     }
259
260     foreach ( $data =~ /@([-\w]+)/ ) {
261         $nicks{$1} = time;
262     }
263
264     my $away = &update_away($data);
265
266     &notice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
267 }
268
269 sub gen_cmd {
270     my ( $usage_str, $api_name, $post_ref ) = @_;
271
272     return sub {
273         my ( $data, $server, $win ) = @_;
274
275         return unless &logged_in($twit);
276
277         $data =~ s/^\s+|\s+$//;
278         unless ($data) {
279             &notice("Usage: $usage_str");
280             return;
281         }
282
283         eval {
284             unless ( $twit->$api_name($data) )
285             {
286                 &notice("$api_name failed");
287                 return;
288             }
289         };
290
291         if ($@) {
292             &notice("$api_name caused an error.  Aborted.");
293             return;
294         }
295
296         &$post_ref($data) if $post_ref;
297       }
298 }
299
300 sub cmd_switch {
301     my ( $data, $server, $win ) = @_;
302
303     $data =~ s/^\s+|\s+$//g;
304     if ( exists $twits{$data} ) {
305         &notice("Switching to $data");
306         $twit = $twits{$data};
307         $user = $data;
308     } else {
309         &notice("Unknown user $data");
310     }
311 }
312
313 sub cmd_logout {
314     my ( $data, $server, $win ) = @_;
315
316     $data =~ s/^\s+|\s+$//g;
317     $data = $user unless $data;
318     return unless &valid_username($data);
319
320     &notice("Logging out $data...");
321     $twits{$data}->end_session();
322     delete $twits{$data};
323     undef $twit;
324     if ( keys %twits ) {
325         &cmd_switch( ( keys %twits )[0], $server, $win );
326     } else {
327         Irssi::timeout_remove($poll) if $poll;
328         undef $poll;
329     }
330 }
331
332 sub cmd_login {
333     my ( $data, $server, $win ) = @_;
334     my $pass;
335     if ($data) {
336         ( $user, $pass ) = split ' ', $data, 2;
337     } elsif ( my $autouser = Irssi::settings_get_str("twitter_usernames")
338         and my $autopass = Irssi::settings_get_str("twitter_passwords") )
339     {
340         my @user = split /\s*,\s*/, $autouser;
341         my @pass = split /\s*,\s*/, $autopass;
342         if ( @user != @pass ) {
343             &notice("Number of usernames doesn't match "
344                   . "the number of passwords - auto-login failed" );
345         } else {
346             my ( $u, $p );
347             while ( @user and @pass ) {
348                 $u = shift @user;
349                 $p = shift @pass;
350                 &cmd_login("$u $p");
351             }
352             return;
353         }
354     } else {
355         &notice("/twitter_login requires either a username and password "
356               . "or twitter_usernames and twitter_passwords to be set." );
357         return;
358     }
359
360     %friends = %nicks = ();
361
362     $twit = Net::Twitter->new(
363         username => $user,
364         password => $pass,
365         source   => "twirssi"
366     );
367
368     unless ( $twit->verify_credentials() ) {
369         &notice("Login as $user failed");
370         $twit = undef;
371         if ( keys %twits ) {
372             &cmd_switch( ( keys %twits )[0], $server, $win );
373         }
374         return;
375     }
376
377     if ($twit) {
378         my $rate_limit = $twit->rate_limit_status();
379         if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
380             &notice(
381                 "Rate limit exceeded, try again after $rate_limit->{reset_time}"
382             );
383             $twit = undef;
384             return;
385         }
386
387         $twits{$user} = $twit;
388         Irssi::timeout_remove($poll) if $poll;
389         $poll = Irssi::timeout_add( &get_poll_time * 1000, \&get_updates, "" );
390         &notice("Logged in as $user, loading friends list...");
391         &load_friends();
392         &notice( "loaded friends: ", scalar keys %friends );
393         if ( Irssi::settings_get_bool("twirssi_first_run") ) {
394             Irssi::settings_set_bool( "twirssi_first_run", 0 );
395             unless ( exists $friends{twirssi} ) {
396                 &notice("Welcome to twirssi!"
397                       . "  Perhaps you should add \@twirssi to your friends list,"
398                       . " so you can be notified when a new version is release?"
399                       . "  Just type /twitter_friend twirssi." );
400             }
401         }
402         %nicks = %friends;
403         $nicks{$user} = 0;
404         &get_updates;
405     } else {
406         &notice("Login failed");
407     }
408 }
409
410 sub cmd_add_search {
411     my ( $data, $server, $win ) = @_;
412
413     unless ( $twit and $twit->can('search') ) {
414         &notice("ERROR: Your version of Net::Twitter ($Net::Twitter::VERSION) "
415               . "doesn't support searches." );
416         return;
417     }
418
419     $data =~ s/^\s+|\s+$//;
420     $data = lc $data;
421
422     unless ($data) {
423         &notice("Usage: /twitter_subscribe <topic>");
424         return;
425     }
426
427     if ( exists $id_map{__searches}{$user}{$data} ) {
428         &notice("Already had a subscription for '$data'");
429         return;
430     }
431
432     $id_map{__searches}{$user}{$data} = 1;
433     &notice("Added subscription for '$data'");
434 }
435
436 sub cmd_del_search {
437     my ( $data, $server, $win ) = @_;
438
439     unless ( $twit and $twit->can('search') ) {
440         &notice("ERROR: Your version of Net::Twitter ($Net::Twitter::VERSION) "
441               . "doesn't support searches." );
442         return;
443     }
444     $data =~ s/^\s+|\s+$//;
445     $data = lc $data;
446
447     unless ($data) {
448         &notice("Usage: /twitter_unsubscribe <topic>");
449         return;
450     }
451
452     unless ( exists $id_map{__searches}{$user}{$data} ) {
453         &notice("No subscription found for '$data'");
454         return;
455     }
456
457     delete $id_map{__searches}{$user}{$data};
458     &notice("Removed subscription for '$data'");
459 }
460
461 sub cmd_list_search {
462     my ( $data, $server, $win ) = @_;
463
464     my $found = 0;
465     foreach my $suser ( sort keys %{ $id_map{__searches} } ) {
466         my $topics;
467         foreach my $topic ( sort keys %{ $id_map{__searches}{$suser} } ) {
468             $topics = $topics ? "$topics, $topic" : $topic;
469         }
470         if ($topics) {
471             $found = 1;
472             &notice("Search subscriptions for \@$suser: $topics");
473         }
474     }
475
476     unless ($found) {
477         &notice("No search subscriptions set up");
478     }
479 }
480
481 sub cmd_upgrade {
482     my ( $data, $server, $win ) = @_;
483
484     my $loc = Irssi::settings_get_str("twirssi_location");
485     unless ( -w $loc ) {
486         &notice(
487 "$loc isn't writable, can't upgrade.  Perhaps you need to /set twirssi_location?"
488         );
489         return;
490     }
491
492     if ( not -x "/usr/bin/md5sum" and not $data ) {
493         &notice(
494 "/usr/bin/md5sum can't be found - try '/twirssi_upgrade nomd5' to skip MD5 verification"
495         );
496         return;
497     }
498
499     my $md5;
500     unless ($data) {
501         eval { use Digest::MD5; };
502
503         if ($@) {
504             &notice(
505 "Failed to load Digest::MD5.  Try '/twirssi_upgrade nomd5' to skip MD5 verification"
506             );
507             return;
508         }
509
510         $md5 = get("http://twirssi.com/md5sum");
511         chomp $md5;
512         $md5 =~ s/ .*//;
513         unless ($md5) {
514             &notice("Failed to download md5sum from peeron!  Aborting.");
515             return;
516         }
517
518         unless ( open( CUR, $loc ) ) {
519             &notice(
520 "Failed to read $loc.  Check that /set twirssi_location is set to the correct location."
521             );
522             return;
523         }
524
525         my $cur_md5 = Digest::MD5::md5_hex(<CUR>);
526         close CUR;
527
528         if ( $cur_md5 eq $md5 ) {
529             &notice("Current twirssi seems to be up to date.");
530             return;
531         }
532     }
533
534     my $URL = "http://twirssi.com/twirssi.pl";
535     &notice("Downloading twirssi from $URL");
536     LWP::Simple::getstore( $URL, "$loc.upgrade" );
537
538     unless ($data) {
539         unless ( open( NEW, "$loc.upgrade" ) ) {
540             &notice(
541 "Failed to read $loc.upgrade.  Check that /set twirssi_location is set to the correct location."
542             );
543             return;
544         }
545
546         my $new_md5 = Digest::MD5::md5_hex(<NEW>);
547         close NEW;
548
549         if ( $new_md5 ne $md5 ) {
550             &notice("MD5 verification failed. expected $md5, got $new_md5");
551             return;
552         }
553     }
554
555     rename $loc, "$loc.backup"
556       or &notice("Failed to back up $loc: $!.  Aborting")
557       and return;
558     rename "$loc.upgrade", $loc
559       or &notice("Failed to rename $loc.upgrade: $!.  Aborting")
560       and return;
561
562     my ( $dir, $file ) = ( $loc =~ m{(.*)/([^/]+)$} );
563     if ( -e "$dir/autorun/$file" ) {
564         &notice("Updating $dir/autorun/$file");
565         unlink "$dir/autorun/$file"
566           or &notice("Failed to remove old $file from autorun: $!");
567         symlink "../$file", "$dir/autorun/$file"
568           or &notice("Failed to create symlink in autorun directory: $!");
569     }
570
571     &notice("Download complete.  Reload twirssi with /script load $file");
572 }
573
574 sub load_friends {
575     my $fh   = shift;
576     my $page = 1;
577     my %new_friends;
578     eval {
579         while (1)
580         {
581             print $fh "type:debug Loading friends page $page...\n"
582               if ( $fh and &debug );
583             my $friends = $twit->friends( { page => $page } );
584             last unless $friends;
585             $new_friends{ $_->{screen_name} } = time foreach @$friends;
586             $page++;
587             last if @$friends == 0 or $page == 10;
588         }
589     };
590
591     if ($@) {
592         print $fh "type:debug Error during friends list update.  Aborted.\n";
593         return;
594     }
595
596     my ( $added, $removed ) = ( 0, 0 );
597     print $fh "type:debug Scanning for new friends...\n" if ( $fh and &debug );
598     foreach ( keys %new_friends ) {
599         next if exists $friends{$_};
600         $friends{$_} = time;
601         $added++;
602     }
603
604     print $fh "type:debug Scanning for removed friends...\n"
605       if ( $fh and &debug );
606     foreach ( keys %friends ) {
607         next if exists $new_friends{$_};
608         delete $friends{$_};
609         $removed++;
610     }
611
612     return ( $added, $removed );
613 }
614
615 sub get_updates {
616     print scalar localtime, " - get_updates starting" if &debug;
617
618     $window =
619       Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
620     unless ($window) {
621         Irssi::active_win()
622           ->print( "Can't find a window named '"
623               . Irssi::settings_get_str('twitter_window')
624               . "'.  Create it or change the value of twitter_window" );
625     }
626
627     return unless &logged_in($twit);
628
629     my ( $fh, $filename ) = File::Temp::tempfile();
630     my $pid = fork();
631
632     if ($pid) {    # parent
633         Irssi::timeout_add_once( 5000, 'monitor_child', [ $filename, 0 ] );
634         Irssi::pidwait_add($pid);
635     } elsif ( defined $pid ) {    # child
636         close STDIN;
637         close STDOUT;
638         close STDERR;
639
640         my $new_poll = time;
641
642         my $error = 0;
643         $error += &do_updates( $fh, $user, $twit );
644         foreach ( keys %twits ) {
645             next if $_ eq $user;
646             $error += &do_updates( $fh, $_, $twits{$_} );
647         }
648
649         my ( $added, $removed ) = &load_friends($fh);
650         if ( $added + $removed ) {
651             print $fh "type:debug %R***%n Friends list updated: ",
652               join( ", ",
653                 sprintf( "%d added",   $added ),
654                 sprintf( "%d removed", $removed ) ),
655               "\n";
656         }
657         print $fh "__friends__\n";
658         foreach ( sort keys %friends ) {
659             print $fh "$_ $friends{$_}\n";
660         }
661
662         if ($error) {
663             print $fh "type:debug Update encountered errors.  Aborted\n";
664             print $fh $last_poll;
665         } else {
666             print $fh $new_poll;
667         }
668         close $fh;
669         exit;
670     }
671     print scalar localtime, " - get_updates ends" if &debug;
672 }
673
674 sub do_updates {
675     my ( $fh, $username, $obj ) = @_;
676
677     my $rate_limit = $obj->rate_limit_status();
678     if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
679         &notice("Rate limit exceeded for $username");
680         return 1;
681     }
682
683     print scalar localtime, " - Polling for updates for $username" if &debug;
684     my $tweets;
685     eval {
686         $tweets = $obj->friends_timeline(
687             { since => HTTP::Date::time2str($last_poll) } );
688     };
689
690     if ($@) {
691         print $fh "type:debug Error during friends_timeline call.  Aborted.\n";
692         return 1;
693     }
694
695     unless ( ref $tweets ) {
696         if ( $obj->can("get_error") ) {
697             my $error;
698             eval { $error = JSON::Any->jsonToObj( $obj->get_error() ) };
699             if ($@) { $error = $obj->get_error() }
700             print $fh "type:debug API Error during friends_timeline call: ",
701               "$error  Aborted.\n";
702         } else {
703             print $fh
704               "type:debug API Error during friends_timeline call. Aborted.\n";
705         }
706         return 1;
707     }
708
709     foreach my $t ( reverse @$tweets ) {
710         my $text = decode_entities( $t->{text} );
711         $text = &hilight($text);
712         my $reply = "tweet";
713         if (    Irssi::settings_get_bool("show_reply_context")
714             and $t->{in_reply_to_screen_name} ne $username
715             and $t->{in_reply_to_screen_name}
716             and not exists $friends{ $t->{in_reply_to_screen_name} } )
717         {
718             $nicks{ $t->{in_reply_to_screen_name} } = time;
719             my $context;
720             eval {
721                 $context = $obj->show_status( $t->{in_reply_to_status_id} );
722             };
723
724             if ($context) {
725                 my $ctext = decode_entities( $context->{text} );
726                 $ctext = &hilight($ctext);
727                 printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
728                   $context->{id}, $username,
729                   $context->{user}{screen_name}, $ctext;
730                 $reply = "reply";
731             } elsif ($@) {
732                 print $fh "type:debug request to get context failed: $@";
733             } else {
734                 print $fh
735 "type:debug Failed to get context from $t->{in_reply_to_screen_name}\n"
736                   if &debug;
737             }
738         }
739         next
740           if $t->{user}{screen_name} eq $username
741               and not Irssi::settings_get_bool("show_own_tweets");
742         printf $fh "id:%d account:%s nick:%s type:%s %s\n",
743           $t->{id}, $username, $t->{user}{screen_name}, $reply, $text;
744     }
745
746     print scalar localtime, " - Polling for replies" if &debug;
747     eval {
748         $tweets = $obj->replies( { since => HTTP::Date::time2str($last_poll) } )
749           || [];
750     };
751
752     if ($@) {
753         print $fh "type:debug Error during replies call.  Aborted.\n";
754         return 1;
755     }
756
757     foreach my $t ( reverse @$tweets ) {
758         next
759           if exists $friends{ $t->{user}{screen_name} };
760
761         my $text = decode_entities( $t->{text} );
762         $text = &hilight($text);
763         printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
764           $t->{id}, $username, $t->{user}{screen_name}, $text;
765     }
766
767     print scalar localtime, " - Polling for DMs" if &debug;
768     eval {
769         $tweets =
770           $obj->direct_messages( { since => HTTP::Date::time2str($last_poll) } )
771           || [];
772     };
773
774     if ($@) {
775         print $fh "type:debug Error during direct_messages call.  Aborted.\n";
776         return 1;
777     }
778
779     foreach my $t ( reverse @$tweets ) {
780         my $text = decode_entities( $t->{text} );
781         $text = &hilight($text);
782         printf $fh "id:%d account:%s nick:%s type:dm %s\n",
783           $t->{id}, $username, $t->{sender_screen_name}, $text;
784     }
785
786     print scalar localtime, " - Polling for subscriptions" if &debug;
787     if ( $obj->can('search') and $id_map{__searches}{$username} ) {
788         my $search;
789         foreach my $topic ( sort keys %{ $id_map{__searches}{$username} } ) {
790             print $fh "type:debug searching for $topic since ",
791               "$id_map{__searches}{$username}{$topic}\n";
792             eval {
793                 $search = $obj->search(
794                     {
795                         q        => $topic,
796                         since_id => $id_map{__searches}{$username}{$topic}
797                     }
798                 );
799             };
800
801             if ($@) {
802                 print $fh
803                   "type:debug Error during search($topic) call.  Aborted.\n";
804                 return 1;
805             }
806
807             unless ( $search->{max_id} ) {
808                 print $fh
809 "type:debug Invalid search results when searching for $topic.",
810                   "  Aborted.\n";
811                 return 1;
812             }
813
814             $id_map{__searches}{$username}{$topic} = $search->{max_id};
815             printf $fh "id:%d account:%s type:searchid topic:%s\n",
816               $search->{max_id}, $username, $topic;
817
818             foreach my $t ( reverse @{ $search->{results} } ) {
819                 my $text = decode_entities( $t->{text} );
820                 $text = &hilight($text);
821                 printf $fh "id:%d account:%s nick:%s type:search topic:%s %s\n",
822                   $t->{id}, $username, $t->{from_user}, $topic, $text;
823             }
824         }
825     }
826
827     print scalar localtime, " - Done" if &debug;
828
829     return 0;
830 }
831
832 sub monitor_child {
833     my ($data)   = @_;
834     my $filename = $data->[0];
835     my $attempt  = $data->[1];
836
837     print scalar localtime, " - checking child log at $filename ($attempt)"
838       if &debug;
839     my $new_last_poll;
840     if ( open FILE, $filename ) {
841         my @lines;
842         while (<FILE>) {
843             chomp;
844             last if /^__friends__/;
845             my $hilight = 0;
846             my %meta;
847             foreach my $key (qw/id account nick type topic/) {
848                 if (s/^$key:(\S+)\s*//) {
849                     $meta{$key} = $1;
850                 }
851             }
852
853             if (not $meta{type} or $meta{type} ne 'searchid') {
854                 next if exists $meta{id} and exists $tweet_cache{ $meta{id} };
855                 $tweet_cache{ $meta{id} } = time;
856             }
857
858             my $account = "";
859             if ( $meta{account} ne $user ) {
860                 $account = "$meta{account}: ";
861             }
862
863             my $marker = "";
864             if (    $meta{type} ne 'dm'
865                 and Irssi::settings_get_bool("twirssi_track_replies")
866                 and $meta{nick}
867                 and $meta{id} )
868             {
869                 $marker = ( $id_map{__indexes}{ $meta{nick} } + 1 ) % 100;
870                 $id_map{ lc $meta{nick} }[$marker] = $meta{id};
871                 $id_map{__indexes}{ $meta{nick} }  = $marker;
872                 $marker                            = ":$marker";
873             }
874
875             my $hilight_color =
876               $irssi_to_mirc_colors{ Irssi::settings_get_str("hilight_color") };
877             if ( $_ =~ /\@$meta{account}\W/i ) {
878                 $meta{nick} = "\cC$hilight_color$meta{nick}\cO";
879                 $hilight = MSGLEVEL_HILIGHT;
880             }
881
882             if ( $meta{type} =~ /tweet|reply/ ) {
883                 push @lines,
884                   [
885                     ( MSGLEVEL_PUBLIC | $hilight ),
886                     $meta{type}, $account, $meta{nick}, $marker, $_
887                   ];
888             } elsif ( $meta{type} eq 'search' ) {
889                 push @lines,
890                   [
891                     ( MSGLEVEL_PUBLIC | $hilight ),
892                     $meta{type}, $account, $meta{topic},
893                     $meta{nick}, $marker,  $_
894                   ];
895                 if ( $meta{id} >
896                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
897                 {
898                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
899                       $meta{id};
900                 }
901             } elsif ( $meta{type} eq 'dm' ) {
902                 push @lines,
903                   [
904                     ( MSGLEVEL_MSGS | $hilight ),
905                     $meta{type}, $account, $meta{nick}, $_
906                   ];
907             } elsif ( $meta{type} eq 'searchid' ) {
908                 print "Search '$meta{topic}' returned id $meta{id}" if &debug;
909                 if ( $meta{id} >=
910                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
911                 {
912                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
913                       $meta{id};
914                 } elsif (&debug) {
915                     print "Search '$meta{topic}' returned invalid id $meta{id}";
916                 }
917             } elsif ( $meta{type} eq 'error' ) {
918                 push @lines, [ MSGLEVEL_MSGS, $_ ];
919             } elsif ( $meta{type} eq 'debug' ) {
920                 print "$_" if &debug,;
921             } else {
922                 print "Unknown line type $meta{type}: $_" if &debug,;
923             }
924         }
925
926         %friends = ();
927         while (<FILE>) {
928             if (/^\d+$/) {
929                 $new_last_poll = $_;
930                 last;
931             }
932             my ( $f, $t ) = split ' ', $_;
933             $nicks{$f} = $friends{$f} = $t;
934         }
935
936         if ($new_last_poll) {
937             print "new last_poll = $new_last_poll" if &debug;
938             for my $line (@lines) {
939                 $window->printformat(
940                     $line->[0],
941                     "twirssi_" . $line->[1],
942                     @$line[ 2 .. $#$line ]
943                 );
944             }
945
946             close FILE;
947             unlink $filename
948               or warn "Failed to remove $filename: $!"
949               unless &debug;
950
951             # keep enough cached tweets, to make sure we don't show duplicates.
952             foreach ( keys %tweet_cache ) {
953                 next if $tweet_cache{$_} >= $last_poll;
954                 delete $tweet_cache{$_};
955             }
956             $last_poll = $new_last_poll;
957
958             # save id_map hash
959             if ( keys %id_map
960                 and my $file =
961                 Irssi::settings_get_str("twirssi_replies_store") )
962             {
963                 if ( open JSON, ">$file" ) {
964                     print JSON JSON::Any->objToJson( \%id_map );
965                     close JSON;
966                 } else {
967                     &notice("Failed to write replies to $file: $!");
968                 }
969             }
970             return;
971         }
972     }
973
974     close FILE;
975
976     if ( $attempt < 12 ) {
977         Irssi::timeout_add_once( 5000, 'monitor_child',
978             [ $filename, $attempt + 1 ] );
979     } else {
980         &notice("Giving up on polling $filename");
981         unlink $filename unless &debug;
982     }
983 }
984
985 sub debug {
986     return Irssi::settings_get_bool("twirssi_debug");
987 }
988
989 sub notice {
990     $window->print( "%R***%n @_", MSGLEVEL_PUBLIC );
991 }
992
993 sub update_away {
994     my $data = shift;
995
996     if (    Irssi::settings_get_bool("tweet_to_away")
997         and $data !~ /\@\w/
998         and $data !~ /^[dD] / )
999     {
1000         my $server =
1001           Irssi::server_find_tag( Irssi::settings_get_str("bitlbee_server") );
1002         if ($server) {
1003             $server->send_raw("away :$data");
1004             return 1;
1005         } else {
1006             &notice( "Can't find bitlbee server.",
1007                 "Update bitlbee_server or disable tweet_to_away" );
1008             return 0;
1009         }
1010     }
1011
1012     return 0;
1013 }
1014
1015 sub too_long {
1016     my $data    = shift;
1017     my $noalert = shift;
1018
1019     if ( length $data > 140 ) {
1020         &notice( "Tweet too long (" . length($data) . " characters) - aborted" )
1021           unless $noalert;
1022         return 1;
1023     }
1024
1025     return 0;
1026 }
1027
1028 sub valid_username {
1029     my $username = shift;
1030
1031     unless ( exists $twits{$username} ) {
1032         &notice("Unknown username $username");
1033         return 0;
1034     }
1035
1036     return 1;
1037 }
1038
1039 sub logged_in {
1040     my $obj = shift;
1041     unless ($obj) {
1042         &notice("Not logged in!  Use /twitter_login username pass!");
1043         return 0;
1044     }
1045
1046     return 1;
1047 }
1048
1049 sub sig_complete {
1050     my ( $complist, $window, $word, $linestart, $want_space ) = @_;
1051
1052     if (
1053         $linestart =~ /^\/twitter_reply(?:_as)?\s*$/
1054         or ( Irssi::settings_get_bool("twirssi_use_reply_aliases")
1055             and $linestart =~ /^\/reply(?:_as)?\s*$/ )
1056       )
1057     {    # /twitter_reply gets a nick:num
1058         $word =~ s/^@//;
1059         @$complist = map { "$_:$id_map{__indexes}{$_}" } grep /^\Q$word/i,
1060           sort keys %{ $id_map{__indexes} };
1061     }
1062
1063     # /tweet, /tweet_as, /dm, /dm_as - complete @nicks (and nicks as the first
1064     # arg to dm)
1065     if ( $linestart =~ /^\/(?:tweet|dm)/ ) {
1066         my $prefix = $word =~ s/^@//;
1067         $prefix = 0 if $linestart eq '/dm' or $linestart eq '/dm_as';
1068         push @$complist, grep /^\Q$word/i,
1069           sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1070         @$complist = map { "\@$_" } @$complist if $prefix;
1071     }
1072 }
1073
1074 sub event_send_text {
1075     my ( $line, $server, $win ) = @_;
1076     my $awin = Irssi::active_win();
1077
1078     # if the window where we got our text was the twitter window, and the user
1079     # wants to be lazy, tweet away!
1080     if ( ( $awin->get_active_name() eq $window->{name} )
1081         and Irssi::settings_get_bool("tweet_window_input") )
1082     {
1083         &cmd_tweet( $line, $server, $win );
1084     }
1085 }
1086
1087 sub get_poll_time {
1088     my $poll = Irssi::settings_get_int("twitter_poll_interval");
1089     return $poll if $poll >= 60;
1090     return 60;
1091 }
1092
1093 sub hilight {
1094     my $text = shift;
1095
1096     $text =~ s/(^|\W)\@([-\w]+)/$1\cC12\@$2\cO/g;
1097     $text =~ s/(^|\W)\#([-\w]+)/$1\cC5\#$2\cO/g;
1098     $text =~ s/[\n\r]/ /g;
1099
1100     return $text;
1101 }
1102
1103 Irssi::signal_add( "send text", "event_send_text" );
1104
1105 Irssi::theme_register(
1106     [
1107         'twirssi_tweet',  '[$0%B@$1%n$2] $3',
1108         'twirssi_search', '[$0%r$1%n:%B@$2%n$3] $4',
1109         'twirssi_reply',  '[$0\--> %B@$1%n$2] $3',
1110         'twirssi_dm',     '[$0%r@$1%n (%WDM%n)] $2',
1111         'twirssi_error',  'ERROR: $0',
1112     ]
1113 );
1114
1115 Irssi::settings_add_int( "twirssi", "twitter_poll_interval", 300 );
1116 Irssi::settings_add_str( "twirssi", "twitter_window",     "twitter" );
1117 Irssi::settings_add_str( "twirssi", "bitlbee_server",     "bitlbee" );
1118 Irssi::settings_add_str( "twirssi", "short_url_provider", "TinyURL" );
1119 Irssi::settings_add_str( "twirssi", "twirssi_location",
1120     ".irssi/scripts/twirssi.pl" );
1121 Irssi::settings_add_str( "twirssi", "twitter_usernames", undef );
1122 Irssi::settings_add_str( "twirssi", "twitter_passwords", undef );
1123 Irssi::settings_add_str( "twirssi", "twirssi_replies_store",
1124     ".irssi/scripts/twirssi.json" );
1125 Irssi::settings_add_bool( "twirssi", "tweet_to_away",             0 );
1126 Irssi::settings_add_bool( "twirssi", "show_reply_context",        0 );
1127 Irssi::settings_add_bool( "twirssi", "show_own_tweets",           1 );
1128 Irssi::settings_add_bool( "twirssi", "twirssi_debug",             0 );
1129 Irssi::settings_add_bool( "twirssi", "twirssi_first_run",         1 );
1130 Irssi::settings_add_bool( "twirssi", "twirssi_track_replies",     1 );
1131 Irssi::settings_add_bool( "twirssi", "twirssi_replies_autonick",  1 );
1132 Irssi::settings_add_bool( "twirssi", "twirssi_use_reply_aliases", 0 );
1133 Irssi::settings_add_bool( "twirssi", "tweet_window_input",        0 );
1134
1135 $last_poll = time - &get_poll_time;
1136 $window = Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
1137 if ( !$window ) {
1138     $window =
1139       Irssi::Windowitem::window_create(
1140         Irssi::settings_get_str('twitter_window'), 1 );
1141     $window->set_name( Irssi::settings_get_str('twitter_window') );
1142 }
1143
1144 if ($window) {
1145     Irssi::command_bind( "dm",                         "cmd_direct" );
1146     Irssi::command_bind( "dm_as",                      "cmd_direct_as" );
1147     Irssi::command_bind( "tweet",                      "cmd_tweet" );
1148     Irssi::command_bind( "tweet_as",                   "cmd_tweet_as" );
1149     Irssi::command_bind( "twitter_reply",              "cmd_reply" );
1150     Irssi::command_bind( "twitter_reply_as",           "cmd_reply_as" );
1151     Irssi::command_bind( "twitter_login",              "cmd_login" );
1152     Irssi::command_bind( "twitter_logout",             "cmd_logout" );
1153     Irssi::command_bind( "twitter_switch",             "cmd_switch" );
1154     Irssi::command_bind( "twitter_subscribe",          "cmd_add_search" );
1155     Irssi::command_bind( "twitter_unsubscribe",        "cmd_del_search" );
1156     Irssi::command_bind( "twitter_list_subscriptions", "cmd_list_search" );
1157     Irssi::command_bind( "twirssi_upgrade",            "cmd_upgrade" );
1158     if ( Irssi::settings_get_bool("twirssi_use_reply_aliases") ) {
1159         Irssi::command_bind( "reply",    "cmd_reply" );
1160         Irssi::command_bind( "reply_as", "cmd_reply_as" );
1161     }
1162     Irssi::command_bind(
1163         "twirssi_dump",
1164         sub {
1165             print "twits: ", join ", ",
1166               map { "u: $_->{username}" } values %twits;
1167             print "friends: ", join ", ", sort keys %friends;
1168             print "nicks: ",   join ", ", sort keys %nicks;
1169             print "searches: ", Dumper \%{ $id_map{__searches} };
1170             print "last poll: $last_poll";
1171         }
1172     );
1173     Irssi::command_bind(
1174         "twirssi_version",
1175         sub {
1176             &notice("Twirssi v$VERSION (r$REV); "
1177                   . "Net::Twitter v$Net::Twitter::VERSION. "
1178                   . "JSON in use: "
1179                   . JSON::Any::handler()
1180                   . ".  See details at http://twirssi.com/" );
1181         }
1182     );
1183     Irssi::command_bind(
1184         "twitter_friend",
1185         &gen_cmd(
1186             "/twitter_friend <username>",
1187             "create_friend",
1188             sub { &notice("Following $_[0]"); $nicks{ $_[0] } = time; }
1189         )
1190     );
1191     Irssi::command_bind(
1192         "twitter_unfriend",
1193         &gen_cmd(
1194             "/twitter_unfriend <username>",
1195             "destroy_friend",
1196             sub { &notice("Stopped following $_[0]"); delete $nicks{ $_[0] }; }
1197         )
1198     );
1199     Irssi::command_bind( "twitter_updates", "get_updates" );
1200     Irssi::signal_add_last( 'complete word' => \&sig_complete );
1201
1202     &notice("  %Y<%C(%B^%C)%N                   TWIRSSI v%R$VERSION%N (r$REV)");
1203     &notice("   %C(_(\\%N           http://twirssi.com/ for full docs");
1204     &notice(
1205         "    %Y||%C `%N Log in with /twitter_login, send updates with /tweet");
1206
1207     my $file = Irssi::settings_get_str("twirssi_replies_store");
1208     if ( $file and -r $file ) {
1209         if ( open( JSON, $file ) ) {
1210             local $/;
1211             my $json = <JSON>;
1212             close JSON;
1213             eval {
1214                 my $ref = JSON::Any->jsonToObj($json);
1215                 %id_map = %$ref;
1216                 my $num = keys %{ $id_map{__indexes} };
1217                 &notice( sprintf "Loaded old replies from %d contact%s.",
1218                     $num, ( $num == 1 ? "" : "s" ) );
1219             };
1220         } else {
1221             &notice("Failed to load old replies from $file: $!");
1222         }
1223     }
1224
1225     if ( my $provider = Irssi::settings_get_str("short_url_provider") ) {
1226         eval "use WWW::Shorten::$provider;";
1227
1228         if ($@) {
1229             &notice(
1230 "Failed to load WWW::Shorten::$provider - either clear short_url_provider or install the CPAN module"
1231             );
1232         }
1233     }
1234
1235     if (    my $autouser = Irssi::settings_get_str("twitter_usernames")
1236         and my $autopass = Irssi::settings_get_str("twitter_passwords") )
1237     {
1238         &cmd_login();
1239     }
1240
1241 } else {
1242     Irssi::active_win()
1243       ->print( "Create a window named "
1244           . Irssi::settings_get_str('twitter_window')
1245           . " or change the value of twitter_window.  Then, reload twirssi." );
1246 }
1247
1248 # vim: set sts=4 expandtab: