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