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