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