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