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