776091a7227d6948c87682dbe5196c3e1e98dd26
[twirssi-net-twitter-lite.git] / twirssi.pl
1 use strict;
2 use Irssi;
3 use Irssi::Irc;
4 use Net::Twitter;
5 use HTTP::Date;
6 use HTML::Entities;
7 use File::Temp;
8 use LWP::Simple;
9 use Data::Dumper;
10 $Data::Dumper::Indent = 1;
11
12 use vars qw($VERSION %IRSSI);
13
14 $VERSION = "1.7.1";
15 my ($REV) = '$Rev: 346 $' =~ /(\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://tinyurl.com/twirssi',
24     changed => '$Date: 2009-01-06 07:14:23 -0800 (Tue, 06 Jan 2009) $',
25 );
26
27 my $window;
28 my $twit;
29 my %twits;
30 my $user;
31 my $poll;
32 my %nicks;
33 my %friends;
34 my $last_poll = time - 300;
35 my %tweet_cache;
36 my %id_map;
37
38 sub cmd_direct {
39     my ( $data, $server, $win ) = @_;
40
41     unless ($twit) {
42         &notice("Not logged in!  Use /twitter_login username pass!");
43         return;
44     }
45
46     my ( $target, $text ) = split ' ', $data, 2;
47     unless ( $target and $text ) {
48         &notice("Usage: /dm <nick> <message>");
49         return;
50     }
51
52     &cmd_direct_as( "$user $data", $server, $win );
53 }
54
55 sub cmd_direct_as {
56     my ( $data, $server, $win ) = @_;
57
58     unless ($twit) {
59         &notice("Not logged in!  Use /twitter_login username pass!");
60         return;
61     }
62
63     my ( $username, $target, $text ) = split ' ', $data, 3;
64     unless ( $username and $target and $text ) {
65         &notice("Usage: /dm_as <username> <nick> <message>");
66         return;
67     }
68
69     unless ( exists $twits{$username} ) {
70         &notice("Unknown username $username");
71         return;
72     }
73
74     eval {
75         unless ( $twits{$username}
76             ->new_direct_message( { user => $target, text => $text } ) )
77         {
78             &notice("DM to $target failed");
79             return;
80         }
81     };
82
83     if ($@) {
84         &notice("DM caused an error.  Aborted");
85         return;
86     }
87
88     &notice("DM sent to $target");
89     $nicks{$target} = time;
90 }
91
92 sub cmd_tweet {
93     my ( $data, $server, $win ) = @_;
94
95     unless ($twit) {
96         &notice("Not logged in!  Use /twitter_login username pass!");
97         return;
98     }
99
100     $data =~ s/^\s+|\s+$//;
101     unless ($data) {
102         &notice("Usage: /tweet <update>");
103         return;
104     }
105
106     &cmd_tweet_as( "$user $data", $server, $win );
107 }
108
109 sub cmd_tweet_as {
110     my ( $data, $server, $win ) = @_;
111
112     unless ($twit) {
113         &notice("Not logged in!  Use /twitter_login username pass!");
114         return;
115     }
116
117     $data =~ s/^\s+|\s+$//;
118     my ( $username, $data ) = split ' ', $data, 2;
119
120     unless ( $username and $data ) {
121         &notice("Usage: /tweet_as <username> <update>");
122         return;
123     }
124
125     unless ( exists $twits{$username} ) {
126         &notice("Unknown username $username");
127         return;
128     }
129
130     if ( 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     if ( length $data > 140 ) {
140         &notice(
141             "Tweet too long (" . length($data) . " characters) - aborted" );
142         return;
143     }
144
145     eval {
146         unless ( $twits{$username}->update($data) )
147         {
148             &notice("Update failed");
149             return;
150         }
151     };
152
153     if ($@) {
154         &notice("Update caused an error.  Aborted.");
155         return;
156     }
157
158     foreach ( $data =~ /@([-\w]+)/ ) {
159         $nicks{$1} = time;
160     }
161
162     my $away = 0;
163     if (    Irssi::settings_get_bool("tweet_to_away")
164         and $data !~ /\@\w/
165         and $data !~ /^[dD] / )
166     {
167         my $server =
168           Irssi::server_find_tag( Irssi::settings_get_str("bitlbee_server") );
169         if ($server) {
170             $server->send_raw("away :$data");
171             $away = 1;
172         } else {
173             &notice( "Can't find bitlbee server.",
174                 "Update bitlbee_server or disable tweet_to_away" );
175         }
176     }
177
178     &notice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
179 }
180
181 sub cmd_reply {
182     my ( $data, $server, $win ) = @_;
183
184     unless ($twit) {
185         &notice("Not logged in!  Use /twitter_login username pass!");
186         return;
187     }
188
189     $data =~ s/^\s+|\s+$//;
190     unless ($data) {
191         &notice("Usage: /reply <nick[:num]> <update>");
192         return;
193     }
194
195     $data =~ s/^\s+|\s+$//;
196     my ( $id, $data ) = split ' ', $data, 2;
197     unless ( $id and $data ) {
198         &notice("Usage: /reply_as <nick[:num]> <update>");
199         return;
200     }
201
202     &cmd_reply_as( "$user $id $data", $server, $win );
203 }
204
205 sub cmd_reply_as {
206     my ( $data, $server, $win ) = @_;
207
208     unless ( Irssi::settings_get_bool("twirssi_track_replies") ) {
209         &notice("twirssi_track_replies is required in order to reply to "
210               . "specific tweets.  Either enable it, or just use /tweet "
211               . "\@username <text>." );
212         return;
213     }
214
215     unless ($twit) {
216         &notice("Not logged in!  Use /twitter_login username pass!");
217         return;
218     }
219
220     $data =~ s/^\s+|\s+$//;
221     my ( $username, $id, $data ) = split ' ', $data, 3;
222
223     unless ( $username and $data ) {
224         &notice("Usage: /reply_as <username> <nick[:num]> <update>");
225         return;
226     }
227
228     unless ( exists $twits{$username} ) {
229         &notice("Unknown username $username");
230         return;
231     }
232
233     my $nick;
234     $id =~ s/[^\w\d\-:]+//g;
235     ( $nick, $id ) = split /:/, $id;
236     unless ( exists $id_map{ lc $nick } ) {
237         &notice("Can't find a tweet from $nick to reply to!");
238         return;
239     }
240
241     $id = $id_map{__indexes}{$nick} unless $id;
242     unless ( $id_map{ lc $nick }[$id] ) {
243         &notice("Can't find a tweet numbered $id from $nick to reply to!");
244         return;
245     }
246
247     # remove any @nick at the beginning of the reply, as we'll add it anyway
248     $data =~ s/^\s*\@?$nick\s*//;
249     $data = "\@$nick " . $data;
250
251     if ( Irssi::settings_get_str("short_url_provider") ) {
252         foreach my $url ( $data =~ /(https?:\/\/\S+[\w\/])/g ) {
253             eval {
254                 my $short = makeashorterlink($url);
255                 $data =~ s/\Q$url/$short/g;
256             };
257         }
258     }
259
260     if ( length $data > 140 ) {
261         &notice(
262             "Tweet too long (" . length($data) . " characters) - aborted" );
263         return;
264     }
265
266     eval {
267         unless (
268             $twits{$username}->update(
269                 {
270                     status                => $data,
271                     in_reply_to_status_id => $id_map{ lc $nick }[$id]
272                 }
273             )
274           )
275         {
276             &notice("Update failed");
277             return;
278         }
279     };
280
281     if ($@) {
282         &notice("Update caused an error.  Aborted");
283         return;
284     }
285
286     foreach ( $data =~ /@([-\w]+)/ ) {
287         $nicks{$1} = time;
288     }
289
290     my $away = 0;
291     if (    Irssi::settings_get_bool("tweet_to_away")
292         and $data !~ /\@\w/
293         and $data !~ /^[dD] / )
294     {
295         my $server =
296           Irssi::server_find_tag( Irssi::settings_get_str("bitlbee_server") );
297         if ($server) {
298             $server->send_raw("away :$data");
299             $away = 1;
300         } else {
301             &notice( "Can't find bitlbee server.",
302                 "Update bitlbee_server or disalbe tweet_to_away" );
303         }
304     }
305
306     &notice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
307 }
308
309 sub gen_cmd {
310     my ( $usage_str, $api_name, $post_ref ) = @_;
311
312     return sub {
313         my ( $data, $server, $win ) = @_;
314
315         unless ($twit) {
316             &notice("Not logged in!  Use /twitter_login username pass!");
317             return;
318         }
319
320         $data =~ s/^\s+|\s+$//;
321         unless ($data) {
322             &notice("Usage: $usage_str");
323             return;
324         }
325
326         eval {
327             unless ( $twit->$api_name($data) )
328             {
329                 &notice("$api_name failed");
330                 return;
331             }
332         };
333
334         if ($@) {
335             &notice("$api_name caused an error.  Aborted.");
336             return;
337         }
338
339         &$post_ref($data) if $post_ref;
340       }
341 }
342
343 sub cmd_switch {
344     my ( $data, $server, $win ) = @_;
345
346     $data =~ s/^\s+|\s+$//g;
347     if ( exists $twits{$data} ) {
348         &notice("Switching to $data");
349         $twit = $twits{$data};
350         $user = $data;
351     } else {
352         &notice("Unknown user $data");
353     }
354 }
355
356 sub cmd_logout {
357     my ( $data, $server, $win ) = @_;
358
359     $data =~ s/^\s+|\s+$//g;
360     if ( $data and exists $twits{$data} ) {
361         &notice("Logging out $data...");
362         $twits{$data}->end_session();
363         delete $twits{$data};
364     } elsif ($data) {
365         &notice("Unknown username '$data'");
366     } else {
367         &notice("Logging out $user...");
368         $twit->end_session();
369         undef $twit;
370         delete $twits{$user};
371         if ( keys %twits ) {
372             &cmd_switch( ( keys %twits )[0], $server, $win );
373         } else {
374             Irssi::timeout_remove($poll) if $poll;
375             undef $poll;
376         }
377     }
378 }
379
380 sub cmd_login {
381     my ( $data, $server, $win ) = @_;
382     my $pass;
383     if ($data) {
384         ( $user, $pass ) = split ' ', $data, 2;
385     } elsif ( my $autouser = Irssi::settings_get_str("twitter_usernames")
386         and my $autopass = Irssi::settings_get_str("twitter_passwords") )
387     {
388         my @user = split /\s*,\s*/, $autouser;
389         my @pass = split /\s*,\s*/, $autopass;
390         if ( @user != @pass ) {
391             &notice("Number of usernames doesn't match "
392                   . "the number of passwords - auto-login failed" );
393         } else {
394             my ( $u, $p );
395             while ( @user and @pass ) {
396                 $u = shift @user;
397                 $p = shift @pass;
398                 &cmd_login("$u $p");
399             }
400             return;
401         }
402     } else {
403         &notice("/twitter_login requires either a username and password "
404               . "or twitter_usernames and twitter_passwords to be set." );
405         return;
406     }
407
408     %friends = %nicks = ();
409
410     $twit = Net::Twitter->new(
411         username => $user,
412         password => $pass,
413         source   => "twirssi"
414     );
415
416     unless ( $twit->verify_credentials() ) {
417         &notice("Login as $user failed");
418         $twit = undef;
419         if ( keys %twits ) {
420             &cmd_switch( ( keys %twits )[0], $server, $win );
421         }
422         return;
423     }
424
425     if ($twit) {
426         my $rate_limit = $twit->rate_limit_status();
427         if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
428             &notice("Rate limit exceeded, try again later");
429             $twit = undef;
430             return;
431         }
432
433         $twits{$user} = $twit;
434         Irssi::timeout_remove($poll) if $poll;
435         $poll = Irssi::timeout_add( 300 * 1000, \&get_updates, "" );
436         &notice("Logged in as $user, loading friends list...");
437         &load_friends();
438         &notice( "loaded friends: ", scalar keys %friends );
439         if ( Irssi::settings_get_bool("twirssi_first_run") ) {
440             Irssi::settings_set_bool( "twirssi_first_run", 0 );
441             unless ( exists $friends{twirssi} ) {
442                 &notice("Welcome to twirssi!"
443                       . "  Perhaps you should add \@twirssi to your friends list,"
444                       . " so you can be notified when a new version is release?"
445                       . "  Just type /twitter_friend twirssi." );
446             }
447         }
448         %nicks = %friends;
449         $nicks{$user} = 0;
450         &get_updates;
451     } else {
452         &notice("Login failed");
453     }
454 }
455
456 sub cmd_upgrade {
457     my ( $data, $server, $win ) = @_;
458
459     my $loc = Irssi::settings_get_str("twirssi_location");
460     unless ( -w $loc ) {
461         &notice(
462 "$loc isn't writable, can't upgrade.  Perhaps you need to /set twirssi_location?"
463         );
464         return;
465     }
466
467     if ( not -x "/usr/bin/md5sum" and not $data ) {
468         &notice(
469 "/usr/bin/md5sum can't be found - try '/twirssi_upgrade nomd5' to skip MD5 verification"
470         );
471         return;
472     }
473
474     my $md5;
475     unless ($data) {
476         eval { use Digest::MD5; };
477
478         if ($@) {
479             &notice(
480 "Failed to load Digest::MD5.  Try '/twirssi_upgrade nomd5' to skip MD5 verification"
481             );
482             return;
483         }
484
485         $md5 = get("http://twirssi.com/md5sum");
486         chomp $md5;
487         $md5 =~ s/ .*//;
488         unless ($md5) {
489             &notice("Failed to download md5sum from peeron!  Aborting.");
490             return;
491         }
492
493         unless ( open( CUR, $loc ) ) {
494             &notice(
495 "Failed to read $loc.  Check that /set twirssi_location is set to the correct location."
496             );
497             return;
498         }
499
500         my $cur_md5 = Digest::MD5::md5_hex(<CUR>);
501         close CUR;
502
503         if ( $cur_md5 eq $md5 ) {
504             &notice("Current twirssi seems to be up to date.");
505             return;
506         }
507     }
508
509     my $URL = "http://twirssi.com/twirssi.pl";
510     &notice("Downloading twirssi from $URL");
511     LWP::Simple::getstore( $URL, "$loc.upgrade" );
512
513     unless ($data) {
514         unless ( open( NEW, "$loc.upgrade" ) ) {
515             &notice(
516 "Failed to read $loc.upgrade.  Check that /set twirssi_location is set to the correct location."
517             );
518             return;
519         }
520
521         my $new_md5 = Digest::MD5::md5_hex(<NEW>);
522         close NEW;
523
524         if ( $new_md5 ne $md5 ) {
525             &notice("MD5 verification failed. expected $md5, got $new_md5");
526             return;
527         }
528     }
529
530     rename $loc, "$loc.backup"
531       or &notice("Failed to back up $loc: $!.  Aborting")
532       and return;
533     rename "$loc.upgrade", $loc
534       or &notice("Failed to rename $loc.upgrade: $!.  Aborting")
535       and return;
536
537     my ( $dir, $file ) = ( $loc =~ m{(.*)/([^/]+)$} );
538     if ( -e "$dir/autorun/$file" ) {
539         &notice("Updating $dir/autorun/$file");
540         unlink "$dir/autorun/$file"
541           or &notice("Failed to remove old $file from autorun: $!");
542         symlink "../$file", "$dir/autorun/$file"
543           or &notice("Failed to create symlink in autorun directory: $!");
544     }
545
546     &notice("Download complete.  Reload twirssi with /script load $file");
547 }
548
549 sub load_friends {
550     my $fh   = shift;
551     my $page = 1;
552     my %new_friends;
553     eval {
554         while (1)
555         {
556             print $fh "Loading friends page $page...\n" if ( $fh and &debug );
557             my $friends = $twit->friends( { page => $page } );
558             last unless $friends;
559             $new_friends{ $_->{screen_name} } = time foreach @$friends;
560             $page++;
561             last if @$friends == 0 or $page == 10;
562         }
563     };
564
565     if ($@) {
566         &notice("Error during friends list update.  Aborted.");
567         return;
568     }
569
570     my ( $added, $removed ) = ( 0, 0 );
571     print $fh "Scanning for new friends...\n" if ( $fh and &debug );
572     foreach ( keys %new_friends ) {
573         next if exists $friends{$_};
574         $friends{$_} = time;
575         $added++;
576     }
577
578     print $fh "Scanning for removed friends...\n" if ( $fh and &debug );
579     foreach ( keys %friends ) {
580         next if exists $new_friends{$_};
581         delete $friends{$_};
582         $removed++;
583     }
584
585     return ( $added, $removed );
586 }
587
588 sub get_updates {
589     print scalar localtime, " - get_updates starting" if &debug;
590
591     $window =
592       Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
593     unless ($window) {
594         Irssi::active_win()
595           ->print( "Can't find a window named '"
596               . Irssi::settings_get_str('twitter_window')
597               . "'.  Create it or change the value of twitter_window" );
598     }
599     unless ($twit) {
600         &notice("Not logged in!  Use /twitter_login username pass!");
601         return;
602     }
603
604     my ( $fh, $filename ) = File::Temp::tempfile();
605     my $pid = fork();
606
607     if ($pid) {    # parent
608         Irssi::timeout_add_once( 5000, 'monitor_child', [ $filename, 0 ] );
609         Irssi::pidwait_add($pid);
610     } elsif ( defined $pid ) {    # child
611         close STDIN;
612         close STDOUT;
613         close STDERR;
614
615         my $new_poll = time;
616
617         my $error = 0;
618         $error += &do_updates( $fh, $user, $twit );
619         foreach ( keys %twits ) {
620             next if $_ eq $user;
621             $error += &do_updates( $fh, $_, $twits{$_} );
622         }
623
624         my ( $added, $removed ) = &load_friends($fh);
625         if ( $added + $removed ) {
626             print $fh "%R***%n Friends list updated: ",
627               join( ", ",
628                 sprintf( "%d added",   $added ),
629                 sprintf( "%d removed", $removed ) ),
630               "\n";
631         }
632         print $fh "__friends__\n";
633         foreach ( sort keys %friends ) {
634             print $fh "$_ $friends{$_}\n";
635         }
636
637         if ($error) {
638             print $fh "type:error Update encountered errors.  Aborted\n";
639             print $fh $last_poll;
640         } else {
641             print $fh $new_poll;
642         }
643         close $fh;
644         exit;
645     }
646     print scalar localtime, " - get_updates ends" if &debug;
647 }
648
649 sub do_updates {
650     my ( $fh, $username, $obj ) = @_;
651
652     print scalar localtime, " - Polling for updates for $username" if &debug;
653     my $tweets;
654     eval {
655         $tweets = $obj->friends_timeline(
656             { since => HTTP::Date::time2str($last_poll) } )
657           || [];
658     };
659
660     if ($@) {
661         print $fh "type:error Error during friends_timeline call.  Aborted.\n";
662         return 1;
663     }
664
665     foreach my $t ( reverse @$tweets ) {
666         my $text = decode_entities( $t->{text} );
667         $text =~ s/%/%%/g;
668         $text =~ s/(^|\W)\@([-\w]+)/$1%B\@$2%n/g;
669         my $reply = "tweet";
670         if (    Irssi::settings_get_bool("show_reply_context")
671             and $t->{in_reply_to_screen_name} ne $username
672             and $t->{in_reply_to_screen_name}
673             and not exists $friends{ $t->{in_reply_to_screen_name} } )
674         {
675             $nicks{ $t->{in_reply_to_screen_name} } = time;
676             my $context = $obj->show_status( $t->{in_reply_to_status_id} );
677             if ($context) {
678                 my $ctext = decode_entities( $context->{text} );
679                 $ctext =~ s/%/%%/g;
680                 $ctext =~ s/(^|\W)\@([-\w]+)/$1%B\@$2%n/g;
681                 printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
682                   $context->{id}, $username,
683                   $context->{user}{screen_name}, $ctext;
684                 $reply = "reply";
685             } else {
686                 print "Failed to get context from $t->{in_reply_to_screen_name}"
687                   if &debug;
688             }
689         }
690         next
691           if $t->{user}{screen_name} eq $username
692               and not Irssi::settings_get_bool("show_own_tweets");
693         printf $fh "id:%d account:%s nick:%s type:%s %s\n",
694           $t->{id}, $username, $t->{user}{screen_name}, $reply, $text;
695     }
696
697     print scalar localtime, " - Polling for replies" if &debug;
698     eval {
699         $tweets = $obj->replies( { since => HTTP::Date::time2str($last_poll) } )
700           || [];
701     };
702
703     if ($@) {
704         print $fh "type:error Error during replies call.  Aborted.\n";
705         return 1;
706     }
707
708     foreach my $t ( reverse @$tweets ) {
709         next
710           if exists $friends{ $t->{user}{screen_name} };
711
712         my $text = decode_entities( $t->{text} );
713         $text =~ s/%/%%/g;
714         $text =~ s/(^|\W)\@([-\w]+)/$1%B\@$2%n/g;
715         printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
716           $t->{id}, $username, $t->{user}{screen_name}, $text;
717     }
718
719     print scalar localtime, " - Polling for DMs" if &debug;
720     eval {
721         $tweets =
722           $obj->direct_messages( { since => HTTP::Date::time2str($last_poll) } )
723           || [];
724     };
725
726     if ($@) {
727         print $fh "type:error Error during direct_messages call.  Aborted.\n";
728         return 1;
729     }
730
731     foreach my $t ( reverse @$tweets ) {
732         my $text = decode_entities( $t->{text} );
733         $text =~ s/%/%%/g;
734         $text =~ s/(^|\W)\@([-\w]+)/$1%B\@$2%n/g;
735         printf $fh "id:%d account:%s nick:%s type:dm %s\n",
736           $t->{id}, $username, $t->{sender_screen_name}, $text;
737     }
738     print scalar localtime, " - Done" if &debug;
739
740     return 0;
741 }
742
743 sub monitor_child {
744     my ( $data, $attempt ) = @_;
745     my $filename = $data->[0];
746
747     print scalar localtime, " - checking child log at $filename" if &debug;
748     my $old_last_poll = $last_poll;
749     if ( open FILE, $filename ) {
750         my @lines;
751         while (<FILE>) {
752             chomp;
753             last if /^__friends__/;
754             my %meta;
755             foreach my $key (qw/id account nick type/) {
756                 s/^$key:(\S+)\s*//;
757                 $meta{$key} = $1;
758             }
759
760             next if exists $tweet_cache{ $meta{id} };
761             $tweet_cache{ $meta{id} } = time;
762             my $account = "";
763             if ( $meta{account} ne $user ) {
764                 $account = "$meta{account}: ";
765             }
766
767             my $marker = "";
768             if (    $meta{type} ne 'dm'
769                 and Irssi::settings_get_bool("twirssi_track_replies")
770                 and $meta{nick}
771                 and $meta{id} )
772             {
773                 $marker = ( $id_map{__indexes}{ $meta{nick} } + 1 ) % 100;
774                 $id_map{ lc $meta{nick} }[$marker] = $meta{id};
775                 $id_map{__indexes}{ $meta{nick} }  = $marker;
776                 $marker                            = ":$marker";
777             }
778
779             if ( $meta{type} eq 'tweet' ) {
780                 push @lines, "[$account%B\@$meta{nick}%n$marker] $_\n",;
781             } elsif ( $meta{type} eq 'reply' ) {
782                 push @lines, "[$account\\--> %B\@$meta{nick}%n$marker] $_\n",;
783             } elsif ( $meta{type} eq 'dm' ) {
784                 push @lines, "[$account%B\@$meta{nick}%n (%WDM%n)] $_\n",;
785             } elsif ( $meta{type} eq 'error' ) {
786                 push @lines, "error: $_\n" if &debug,;
787             } elsif ( $meta{type} eq 'debug' ) {
788                 push @lines, "debug: $_\n" if &debug,;
789             }
790         }
791
792         %friends = ();
793         while (<FILE>) {
794             if (/^\d+$/) {
795                 $last_poll = $_;
796                 last;
797             }
798             my ( $f, $t ) = split ' ', $_;
799             $nicks{$f} = $friends{$f} = $t;
800         }
801
802         if ( $last_poll != $old_last_poll ) {
803             print "new last_poll = $last_poll" if &debug;
804             foreach my $line (@lines) {
805                 chomp $line;
806                 $window->print( $line, MSGLEVEL_PUBLIC );
807                 foreach ( $line =~ /\@([-\w]+)/ ) {
808                     $nicks{$1} = time;
809                 }
810             }
811
812             close FILE;
813             unlink $filename
814               or warn "Failed to remove $filename: $!"
815               unless &debug;
816
817             # keep enough cached tweets, to make sure we don't show duplicates.
818             foreach ( keys %tweet_cache ) {
819                 next if $tweet_cache{$_} >= $old_last_poll;
820                 delete $tweet_cache{$_};
821             }
822
823             # save id_map hash
824             if ( keys %id_map
825                 and my $file =
826                 Irssi::settings_get_str("twirssi_replies_store") )
827             {
828                 if ( open JSON, ">$file" ) {
829                     print JSON JSON::Any->objToJson( \%id_map );
830                     close JSON;
831                 } else {
832                     &notice("Failed to write replies to $file: $!");
833                 }
834             }
835             return;
836         }
837     }
838
839     close FILE;
840
841     if ( $attempt < 12 ) {
842         Irssi::timeout_add_once( 5000, 'monitor_child',
843             [ $filename, $attempt + 1 ] );
844     } else {
845         &notice("Giving up on polling $filename");
846         unlink $filename unless &debug;
847     }
848 }
849
850 sub debug {
851     return Irssi::settings_get_bool("twirssi_debug");
852 }
853
854 sub notice {
855     $window->print( "%R***%n @_", MSGLEVEL_PUBLIC );
856 }
857
858 sub sig_complete {
859     my ( $complist, $window, $word, $linestart, $want_space ) = @_;
860
861     if (
862         $linestart =~ /^\/twitter_reply(?:_as)?\s*$/
863         or ( Irssi::settings_get_bool("twirssi_use_reply_aliases")
864             and $linestart =~ /^\/reply(?:_as)?\s*$/ )
865       )
866     {    # /twitter_reply gets a nick:num
867         @$complist = grep /^\Q$word/i, sort keys %{ $id_map{__indexes} };
868     }
869
870     # /tweet, /tweet_as, /dm, /dm_as - complete @nicks (and nicks as the first
871     # arg to dm)
872     if ( $linestart =~ /^\/(?:tweet|dm)/ ) {
873         my $prefix = $word =~ s/^@//;
874         $prefix = 0 if $linestart eq '/dm' or $linestart eq '/dm_as';
875         push @$complist, grep /^\Q$word/i,
876           sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
877         @$complist = map { "\@$_" } @$complist if $prefix;
878     }
879 }
880
881 Irssi::settings_add_str( "twirssi", "twitter_window",     "twitter" );
882 Irssi::settings_add_str( "twirssi", "bitlbee_server",     "bitlbee" );
883 Irssi::settings_add_str( "twirssi", "short_url_provider", "TinyURL" );
884 Irssi::settings_add_str( "twirssi", "twirssi_location",
885     ".irssi/scripts/twirssi.pl" );
886 Irssi::settings_add_str( "twirssi", "twitter_usernames", undef );
887 Irssi::settings_add_str( "twirssi", "twitter_passwords", undef );
888 Irssi::settings_add_str( "twirssi", "twirssi_replies_store",
889     ".irssi/scripts/twirssi.json" );
890 Irssi::settings_add_bool( "twirssi", "tweet_to_away",             0 );
891 Irssi::settings_add_bool( "twirssi", "show_reply_context",        0 );
892 Irssi::settings_add_bool( "twirssi", "show_own_tweets",           1 );
893 Irssi::settings_add_bool( "twirssi", "twirssi_debug",             0 );
894 Irssi::settings_add_bool( "twirssi", "twirssi_first_run",         1 );
895 Irssi::settings_add_bool( "twirssi", "twirssi_track_replies",     1 );
896 Irssi::settings_add_bool( "twirssi", "twirssi_use_reply_aliases", 0 );
897 $window = Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
898
899 if ($window) {
900     Irssi::command_bind( "dm",               "cmd_direct" );
901     Irssi::command_bind( "dm_as",            "cmd_direct_as" );
902     Irssi::command_bind( "tweet",            "cmd_tweet" );
903     Irssi::command_bind( "tweet_as",         "cmd_tweet_as" );
904     Irssi::command_bind( "twitter_reply",    "cmd_reply" );
905     Irssi::command_bind( "twitter_reply_as", "cmd_reply_as" );
906     Irssi::command_bind( "twitter_login",    "cmd_login" );
907     Irssi::command_bind( "twitter_logout",   "cmd_logout" );
908     Irssi::command_bind( "twitter_switch",   "cmd_switch" );
909     Irssi::command_bind( "twirssi_upgrade",  "cmd_upgrade" );
910     if ( Irssi::settings_get_bool("twirssi_use_reply_aliases") ) {
911         Irssi::command_bind( "reply",    "cmd_reply" );
912         Irssi::command_bind( "reply_as", "cmd_reply_as" );
913     }
914     Irssi::command_bind(
915         "twirssi_dump",
916         sub {
917             print "twits: ", join ", ",
918               map { "u: $_->{username}" } values %twits;
919             print "friends: ", join ", ", sort keys %friends;
920             print "nicks: ",   join ", ", sort keys %nicks;
921             print "id_map: ", Dumper \%{ $id_map{__indexes} };
922             print "last poll: $last_poll";
923         }
924     );
925     Irssi::command_bind(
926         "twirssi_version",
927         sub {
928             &notice(
929 "Twirssi v$VERSION (r$REV);  Net::Twitter v$Net::Twitter::VERSION. "
930                   . "See details at http://tinyurl.com/twirssi" );
931         }
932     );
933     Irssi::command_bind(
934         "twitter_friend",
935         &gen_cmd(
936             "/twitter_friend <username>",
937             "create_friend",
938             sub { &notice("Following $_[0]"); $nicks{ $_[0] } = time; }
939         )
940     );
941     Irssi::command_bind(
942         "twitter_unfriend",
943         &gen_cmd(
944             "/twitter_unfriend <username>",
945             "destroy_friend",
946             sub { &notice("Stopped following $_[0]"); delete $nicks{ $_[0] }; }
947         )
948     );
949     Irssi::command_bind( "twitter_updates", "get_updates" );
950     Irssi::signal_add_last( 'complete word' => \&sig_complete );
951
952     &notice("  %Y<%C(%B^%C)%N                   TWIRSSI v%R$VERSION%N (r$REV)");
953     &notice("   %C(_(\\%N           http://twirssi.com/ for full docs");
954     &notice(
955         "    %Y||%C `%N Log in with /twitter_login, send updates with /tweet");
956
957     my $file = Irssi::settings_get_str("twirssi_replies_store");
958     if ( $file and -r $file ) {
959         if ( open( JSON, $file ) ) {
960             local $/;
961             my $json = <JSON>;
962             close JSON;
963             eval {
964                 my $ref = JSON::Any->jsonToObj($json);
965                 %id_map = %$ref;
966                 my $num = keys %{ $id_map{__indexes} };
967                 &notice( sprintf "Loaded old replies from %d contact%s.",
968                     $num, ( $num == 1 ? "" : "s" ) );
969             };
970         } else {
971             &notice("Failed to load old replies from $file: $!");
972         }
973     }
974
975     if ( my $provider = Irssi::settings_get_str("short_url_provider") ) {
976         eval "use WWW::Shorten::$provider;";
977
978         if ($@) {
979             &notice(
980 "Failed to load WWW::Shorten::$provider - either clear short_url_provider or install the CPAN module"
981             );
982         }
983     }
984
985     if (    my $autouser = Irssi::settings_get_str("twitter_usernames")
986         and my $autopass = Irssi::settings_get_str("twitter_passwords") )
987     {
988         &cmd_login();
989     }
990
991 } else {
992     Irssi::active_win()
993       ->print( "Create a window named "
994           . Irssi::settings_get_str('twitter_window')
995           . " or change the value of twitter_window.  Then, reload twirssi." );
996 }
997