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