r548 - Add new setting twirssi_always_shorten to force all URLs to be shortened
[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: 548 $' =~ /(\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:45:47 -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                   [ MSGLEVEL_PUBLIC, "tweet", $account, $meta{nick}, "", $_ ];
929             } elsif ( $meta{type} eq 'search' ) {
930                 push @lines,
931                   [
932                     ( MSGLEVEL_PUBLIC | $hilight ),
933                     $meta{type}, $account, $meta{topic},
934                     $meta{nick}, $marker,  $_
935                   ];
936                 if (
937                     exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
938                     and $meta{id} >
939                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
940                 {
941                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
942                       $meta{id};
943                 }
944             } elsif ( $meta{type} eq 'dm' ) {
945                 push @lines,
946                   [
947                     ( MSGLEVEL_MSGS | $hilight ),
948                     $meta{type}, $account, $meta{nick}, $_
949                   ];
950             } elsif ( $meta{type} eq 'searchid' ) {
951                 print "Search '$meta{topic}' returned id $meta{id}" if &debug;
952                 if (
953                     exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
954                     and $meta{id} >=
955                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
956                 {
957                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
958                       $meta{id};
959                 } elsif (&debug) {
960                     print "Search '$meta{topic}' returned invalid id $meta{id}";
961                 }
962             } elsif ( $meta{type} eq 'error' ) {
963                 push @lines, [ MSGLEVEL_MSGS, $_ ];
964             } elsif ( $meta{type} eq 'debug' ) {
965                 print "$_" if &debug,;
966             } else {
967                 print "Unknown line type $meta{type}: $_" if &debug,;
968             }
969         }
970
971         %friends = ();
972         while (<FILE>) {
973             if (/^\d+$/) {
974                 $new_last_poll = $_;
975                 last;
976             }
977             my ( $f, $t ) = split ' ', $_;
978             $nicks{$f} = $friends{$f} = $t;
979         }
980
981         if ($new_last_poll) {
982             print "new last_poll = $new_last_poll" if &debug;
983             if ($suppress) {
984                 print "First call, not printing updates" if &debug;
985             } else {
986                 foreach my $line (@lines) {
987                     $window->printformat(
988                         $line->[0],
989                         "twirssi_" . $line->[1],
990                         @$line[ 2 .. $#$line ]
991                     );
992                 }
993             }
994
995             close FILE;
996             unlink $filename
997               or warn "Failed to remove $filename: $!"
998               unless &debug;
999
1000             # commit the pending cache lines to the actual cache, now that
1001             # we've printed our output
1002             %tweet_cache = ( %tweet_cache, %new_cache );
1003
1004             # keep enough cached tweets, to make sure we don't show duplicates.
1005             foreach ( keys %tweet_cache ) {
1006                 next if $tweet_cache{$_} >= $last_poll - 3600;
1007                 delete $tweet_cache{$_};
1008             }
1009             $last_poll = $new_last_poll;
1010
1011             # save id_map hash
1012             if ( keys %id_map
1013                 and my $file =
1014                 Irssi::settings_get_str("twirssi_replies_store") )
1015             {
1016                 if ( open JSON, ">$file" ) {
1017                     print JSON JSON::Any->objToJson( \%id_map );
1018                     close JSON;
1019                 } else {
1020                     &ccrap("Failed to write replies to $file: $!");
1021                 }
1022             }
1023             $failwhale = 0;
1024             return;
1025         }
1026     }
1027
1028     close FILE;
1029
1030     if ( $attempt < 24 ) {
1031         Irssi::timeout_add_once( 5000, 'monitor_child',
1032             [ $filename, $attempt + 1 ] );
1033     } else {
1034         print "Giving up on polling $filename" if &debug;
1035         unlink $filename unless &debug;
1036
1037         return unless Irssi::settings_get_bool("twirssi_notify_timeouts");
1038
1039         my $since;
1040         my @time = localtime($last_poll);
1041         if ( time - $last_poll < 24 * 60 * 60 ) {
1042             $since = sprintf( "%d:%02d", @time[ 2, 1 ] );
1043         } else {
1044             $since = scalar localtime($last_poll);
1045         }
1046
1047         if ( not $failwhale and time - $last_poll > 60 * 60 ) {
1048             foreach my $whale (
1049                 q{     v  v        v},
1050                 q{     |  |  v     |  v},
1051                 q{     | .-, |     |  |},
1052                 q{  .--./ /  |  _.---.| },
1053                 q{   '-. (__..-"       \\},
1054                 q{      \\          a    |},
1055                 q{       ',.__.   ,__.-'/},
1056                 q{         '--/_.'----'`}
1057               )
1058             {
1059                 &ccrap($whale);
1060             }
1061             $failwhale = 1;
1062         }
1063         &ccrap("Haven't been able to get updated tweets since $since");
1064     }
1065 }
1066
1067 sub debug {
1068     return Irssi::settings_get_bool("twirssi_debug");
1069 }
1070
1071 sub notice {
1072     $window->print( "%R***%n @_", MSGLEVEL_PUBLIC );
1073 }
1074
1075 sub ccrap {
1076     $window->print( "%R***%n @_", MSGLEVEL_CLIENTCRAP );
1077 }
1078
1079 sub update_away {
1080     my $data = shift;
1081
1082     if (    Irssi::settings_get_bool("tweet_to_away")
1083         and $data !~ /\@\w/
1084         and $data !~ /^[dD] / )
1085     {
1086         my $server =
1087           Irssi::server_find_tag( Irssi::settings_get_str("bitlbee_server") );
1088         if ($server) {
1089             $server->send_raw("away :$data");
1090             return 1;
1091         } else {
1092             &ccrap( "Can't find bitlbee server.",
1093                 "Update bitlbee_server or disable tweet_to_away" );
1094             return 0;
1095         }
1096     }
1097
1098     return 0;
1099 }
1100
1101 sub too_long {
1102     my $data    = shift;
1103     my $noalert = shift;
1104
1105     if ( length $data > 140 ) {
1106         &notice( "Tweet too long (" . length($data) . " characters) - aborted" )
1107           unless $noalert;
1108         return 1;
1109     }
1110
1111     return 0;
1112 }
1113
1114 sub valid_username {
1115     my $username = shift;
1116
1117     unless ( exists $twits{$username} ) {
1118         &notice("Unknown username $username");
1119         return 0;
1120     }
1121
1122     return 1;
1123 }
1124
1125 sub logged_in {
1126     my $obj = shift;
1127     unless ($obj) {
1128         &notice("Not logged in!  Use /twitter_login username pass!");
1129         return 0;
1130     }
1131
1132     return 1;
1133 }
1134
1135 sub sig_complete {
1136     my ( $complist, $window, $word, $linestart, $want_space ) = @_;
1137
1138     if (
1139         $linestart =~ /^\/twitter_reply(?:_as)?\s*$/
1140         or ( Irssi::settings_get_bool("twirssi_use_reply_aliases")
1141             and $linestart =~ /^\/reply(?:_as)?\s*$/ )
1142       )
1143     {    # /twitter_reply gets a nick:num
1144         $word =~ s/^@//;
1145         @$complist = map { "$_:$id_map{__indexes}{$_}" }
1146           sort { $nicks{$b} <=> $nicks{$a} }
1147           grep /^\Q$word/i,
1148           keys %{ $id_map{__indexes} };
1149     }
1150
1151     # /tweet, /tweet_as, /dm, /dm_as - complete @nicks (and nicks as the first
1152     # arg to dm)
1153     if ( $linestart =~ /^\/(?:tweet|dm)/ ) {
1154         my $prefix = $word =~ s/^@//;
1155         $prefix = 0 if $linestart eq '/dm' or $linestart eq '/dm_as';
1156         push @$complist, grep /^\Q$word/i,
1157           sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1158         @$complist = map { "\@$_" } @$complist if $prefix;
1159     }
1160 }
1161
1162 sub event_send_text {
1163     my ( $line, $server, $win ) = @_;
1164     my $awin = Irssi::active_win();
1165
1166     # if the window where we got our text was the twitter window, and the user
1167     # wants to be lazy, tweet away!
1168     if ( ( $awin->get_active_name() eq $window->{name} )
1169         and Irssi::settings_get_bool("tweet_window_input") )
1170     {
1171         &cmd_tweet( $line, $server, $win );
1172     }
1173 }
1174
1175 sub get_poll_time {
1176     my $poll = Irssi::settings_get_int("twitter_poll_interval");
1177     return $poll if $poll >= 60;
1178     return 60;
1179 }
1180
1181 sub hilight {
1182     my $text = shift;
1183
1184     if ( Irssi::settings_get_str("twirssi_nick_color") ) {
1185         my $c = Irssi::settings_get_str("twirssi_nick_color");
1186         $c = $irssi_to_mirc_colors{$c};
1187         $text =~ s/(^|\W)\@([-\w]+)/$1\cC$c\@$2\cO/g if $c;
1188     }
1189     if ( Irssi::settings_get_str("twirssi_topic_color") ) {
1190         my $c = Irssi::settings_get_str("twirssi_topic_color");
1191         $c = $irssi_to_mirc_colors{$c};
1192         $text =~ s/(^|\W)\#([-\w]+)/$1\cC$c\#$2\cO/g if $c;
1193     }
1194     $text =~ s/[\n\r]/ /g;
1195
1196     return $text;
1197 }
1198
1199 sub shorten {
1200     my $data = shift;
1201
1202     my $provider = Irssi::settings_get_str("short_url_provider");
1203     if (
1204         (
1205             Irssi::settings_get_bool("twirssi_always_shorten")
1206             or &too_long( $data, 1 )
1207         )
1208         and $provider
1209       )
1210     {
1211         my @args;
1212         if ( $provider eq 'Bitly' ) {
1213             @args[ 1, 2 ] = split ',',
1214               Irssi::settings_get_str("short_url_args"), 2;
1215             unless ( @args == 3 ) {
1216                 &ccrap(
1217                     "WWW::Shorten::Bitly requires a username and API key.",
1218                     "Set short_url_args to username,API_key or change your",
1219                     "short_url_provider."
1220                 );
1221                 return $data;
1222             }
1223         }
1224
1225         foreach my $url ( $data =~ /(https?:\/\/\S+[\w\/])/g ) {
1226             eval {
1227                 $args[0] = $url;
1228                 my $short = makeashorterlink(@args);
1229                 if ($short) {
1230                     $data =~ s/\Q$url/$short/g;
1231                 } else {
1232                     &notice("Failed to shorten $url!");
1233                 }
1234             };
1235         }
1236     }
1237
1238     return $data;
1239 }
1240
1241 Irssi::signal_add( "send text", "event_send_text" );
1242
1243 Irssi::theme_register(
1244     [
1245         'twirssi_tweet',  '[$0%B@$1%n$2] $3',
1246         'twirssi_search', '[$0%r$1%n:%B@$2%n$3] $4',
1247         'twirssi_reply',  '[$0\--> %B@$1%n$2] $3',
1248         'twirssi_dm',     '[$0%r@$1%n (%WDM%n)] $2',
1249         'twirssi_error',  'ERROR: $0',
1250     ]
1251 );
1252
1253 Irssi::settings_add_int( "twirssi", "twitter_poll_interval", 300 );
1254 Irssi::settings_add_str( "twirssi", "twitter_window",      "twitter" );
1255 Irssi::settings_add_str( "twirssi", "bitlbee_server",      "bitlbee" );
1256 Irssi::settings_add_str( "twirssi", "short_url_provider",  "TinyURL" );
1257 Irssi::settings_add_str( "twirssi", "short_url_args",      undef );
1258 Irssi::settings_add_str( "twirssi", "twitter_usernames",   undef );
1259 Irssi::settings_add_str( "twirssi", "twitter_passwords",   undef );
1260 Irssi::settings_add_str( "twirssi", "twirssi_nick_color",  "%B" );
1261 Irssi::settings_add_str( "twirssi", "twirssi_topic_color", "%r" );
1262 Irssi::settings_add_str( "twirssi", "twirssi_location",
1263     ".irssi/scripts/twirssi.pl" );
1264 Irssi::settings_add_str( "twirssi", "twirssi_replies_store",
1265     ".irssi/scripts/twirssi.json" );
1266 Irssi::settings_add_bool( "twirssi", "twirssi_upgrade_beta",      0 );
1267 Irssi::settings_add_bool( "twirssi", "tweet_to_away",             0 );
1268 Irssi::settings_add_bool( "twirssi", "show_reply_context",        0 );
1269 Irssi::settings_add_bool( "twirssi", "show_own_tweets",           1 );
1270 Irssi::settings_add_bool( "twirssi", "twirssi_debug",             0 );
1271 Irssi::settings_add_bool( "twirssi", "twirssi_first_run",         1 );
1272 Irssi::settings_add_bool( "twirssi", "twirssi_track_replies",     1 );
1273 Irssi::settings_add_bool( "twirssi", "twirssi_replies_autonick",  1 );
1274 Irssi::settings_add_bool( "twirssi", "twirssi_use_reply_aliases", 0 );
1275 Irssi::settings_add_bool( "twirssi", "twirssi_notify_timeouts",   1 );
1276 Irssi::settings_add_bool( "twirssi", "twirssi_hilights",          1 );
1277 Irssi::settings_add_bool( "twirssi", "twirssi_always_shorten",    0 );
1278 Irssi::settings_add_bool( "twirssi", "tweet_window_input",        0 );
1279
1280 $last_poll = time - &get_poll_time;
1281 $window = Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
1282 if ( !$window ) {
1283     Irssi::active_win()
1284       ->print( "Couldn't find a window named '"
1285           . Irssi::settings_get_str('twitter_window')
1286           . "', trying to create it." );
1287     $window =
1288       Irssi::Windowitem::window_create(
1289         Irssi::settings_get_str('twitter_window'), 1 );
1290     $window->set_name( Irssi::settings_get_str('twitter_window') );
1291 }
1292
1293 if ($window) {
1294     Irssi::command_bind( "dm",                         "cmd_direct" );
1295     Irssi::command_bind( "dm_as",                      "cmd_direct_as" );
1296     Irssi::command_bind( "tweet",                      "cmd_tweet" );
1297     Irssi::command_bind( "tweet_as",                   "cmd_tweet_as" );
1298     Irssi::command_bind( "twitter_reply",              "cmd_reply" );
1299     Irssi::command_bind( "twitter_reply_as",           "cmd_reply_as" );
1300     Irssi::command_bind( "twitter_login",              "cmd_login" );
1301     Irssi::command_bind( "twitter_logout",             "cmd_logout" );
1302     Irssi::command_bind( "twitter_switch",             "cmd_switch" );
1303     Irssi::command_bind( "twitter_subscribe",          "cmd_add_search" );
1304     Irssi::command_bind( "twitter_unsubscribe",        "cmd_del_search" );
1305     Irssi::command_bind( "twitter_list_subscriptions", "cmd_list_search" );
1306     Irssi::command_bind( "twirssi_upgrade",            "cmd_upgrade" );
1307     if ( Irssi::settings_get_bool("twirssi_use_reply_aliases") ) {
1308         Irssi::command_bind( "reply",    "cmd_reply" );
1309         Irssi::command_bind( "reply_as", "cmd_reply_as" );
1310     }
1311     Irssi::command_bind(
1312         "twirssi_dump",
1313         sub {
1314             print "twits: ", join ", ",
1315               map { "u: $_->{username}" } values %twits;
1316             print "friends: ", join ", ", sort keys %friends;
1317             print "nicks: ",   join ", ", sort keys %nicks;
1318             print "searches: ", Dumper \%{ $id_map{__searches} };
1319             print "last poll: $last_poll";
1320             if ( open DUMP, ">/tmp/twirssi.cache.txt" ) {
1321                 print DUMP Dumper \%tweet_cache;
1322                 close DUMP;
1323                 print "cache written out to /tmp/twirssi.cache.txt";
1324             }
1325         }
1326     );
1327     Irssi::command_bind(
1328         "twirssi_version",
1329         sub {
1330             &notice("Twirssi v$VERSION (r$REV); "
1331                   . "Net::Twitter v$Net::Twitter::VERSION. "
1332                   . "JSON in use: "
1333                   . JSON::Any::handler()
1334                   . ".  See details at http://twirssi.com/" );
1335         }
1336     );
1337     Irssi::command_bind(
1338         "twitter_friend",
1339         &gen_cmd(
1340             "/twitter_friend <username>",
1341             "create_friend",
1342             sub { &notice("Following $_[0]"); $nicks{ $_[0] } = time; }
1343         )
1344     );
1345     Irssi::command_bind(
1346         "twitter_unfriend",
1347         &gen_cmd(
1348             "/twitter_unfriend <username>",
1349             "destroy_friend",
1350             sub { &notice("Stopped following $_[0]"); delete $nicks{ $_[0] }; }
1351         )
1352     );
1353     Irssi::command_bind( "twitter_updates", "get_updates" );
1354     Irssi::signal_add_last( 'complete word' => \&sig_complete );
1355
1356     &notice("  %Y<%C(%B^%C)%N                   TWIRSSI v%R$VERSION%N (r$REV)");
1357     &notice("   %C(_(\\%N           http://twirssi.com/ for full docs");
1358     &notice(
1359         "    %Y||%C `%N Log in with /twitter_login, send updates with /tweet");
1360
1361     my $file = Irssi::settings_get_str("twirssi_replies_store");
1362     if ( $file and -r $file ) {
1363         if ( open( JSON, $file ) ) {
1364             local $/;
1365             my $json = <JSON>;
1366             close JSON;
1367             eval {
1368                 my $ref = JSON::Any->jsonToObj($json);
1369                 %id_map = %$ref;
1370                 my $num = keys %{ $id_map{__indexes} };
1371                 &notice( sprintf "Loaded old replies from %d contact%s.",
1372                     $num, ( $num == 1 ? "" : "s" ) );
1373                 &cmd_list_search;
1374             };
1375         } else {
1376             &notice("Failed to load old replies from $file: $!");
1377         }
1378     }
1379
1380     if ( my $provider = Irssi::settings_get_str("short_url_provider") ) {
1381         &notice("Loading WWW::Shorten::$provider...");
1382         eval "use WWW::Shorten::$provider;";
1383
1384         if ($@) {
1385             &notice(
1386                 "Failed to load WWW::Shorten::$provider - either clear",
1387                 "short_url_provider or install the CPAN module"
1388             );
1389         }
1390     }
1391
1392     if (    my $autouser = Irssi::settings_get_str("twitter_usernames")
1393         and my $autopass = Irssi::settings_get_str("twitter_passwords") )
1394     {
1395         &cmd_login();
1396         &get_updates;
1397     }
1398
1399 } else {
1400     Irssi::active_win()
1401       ->print( "Create a window named "
1402           . Irssi::settings_get_str('twitter_window')
1403           . " or change the value of twitter_window.  Then, reload twirssi." );
1404 }
1405
1406 # vim: set sts=4 expandtab: