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