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