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