1.7.2 - r348 - Fix lots of printing issues. Fix endless polling for lost files....
[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.2";
15 my ($REV) = '$Rev: 348 $' =~ /(\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 11:09:34 -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 "type:debug Loading friends page $page...\n"
557               if ( $fh and &debug );
558             my $friends = $twit->friends( { page => $page } );
559             last unless $friends;
560             $new_friends{ $_->{screen_name} } = time foreach @$friends;
561             $page++;
562             last if @$friends == 0 or $page == 10;
563         }
564     };
565
566     if ($@) {
567         print $fh "type:error Error during friends list update.  Aborted.\n";
568         return;
569     }
570
571     my ( $added, $removed ) = ( 0, 0 );
572     print $fh "type:debug Scanning for new friends...\n" if ( $fh and &debug );
573     foreach ( keys %new_friends ) {
574         next if exists $friends{$_};
575         $friends{$_} = time;
576         $added++;
577     }
578
579     print $fh "type:debug Scanning for removed friends...\n"
580       if ( $fh and &debug );
581     foreach ( keys %friends ) {
582         next if exists $new_friends{$_};
583         delete $friends{$_};
584         $removed++;
585     }
586
587     return ( $added, $removed );
588 }
589
590 sub get_updates {
591     print scalar localtime, " - get_updates starting" if &debug;
592
593     $window =
594       Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
595     unless ($window) {
596         Irssi::active_win()
597           ->print( "Can't find a window named '"
598               . Irssi::settings_get_str('twitter_window')
599               . "'.  Create it or change the value of twitter_window" );
600     }
601     unless ($twit) {
602         &notice("Not logged in!  Use /twitter_login username pass!");
603         return;
604     }
605
606     my ( $fh, $filename ) = File::Temp::tempfile();
607     my $pid = fork();
608
609     if ($pid) {    # parent
610         Irssi::timeout_add_once( 5000, 'monitor_child', [ $filename, 0 ] );
611         Irssi::pidwait_add($pid);
612     } elsif ( defined $pid ) {    # child
613         close STDIN;
614         close STDOUT;
615         close STDERR;
616
617         my $new_poll = time;
618
619         my $error = 0;
620         $error += &do_updates( $fh, $user, $twit );
621         foreach ( keys %twits ) {
622             next if $_ eq $user;
623             $error += &do_updates( $fh, $_, $twits{$_} );
624         }
625
626         my ( $added, $removed ) = &load_friends($fh);
627         if ( $added + $removed ) {
628             print $fh "type:debug %R***%n Friends list updated: ",
629               join( ", ",
630                 sprintf( "%d added",   $added ),
631                 sprintf( "%d removed", $removed ) ),
632               "\n";
633         }
634         print $fh "__friends__\n";
635         foreach ( sort keys %friends ) {
636             print $fh "$_ $friends{$_}\n";
637         }
638
639         if ($error) {
640             print $fh "type:error Update encountered errors.  Aborted\n";
641             print $fh $last_poll;
642         } else {
643             print $fh $new_poll;
644         }
645         close $fh;
646         exit;
647     }
648     print scalar localtime, " - get_updates ends" if &debug;
649 }
650
651 sub do_updates {
652     my ( $fh, $username, $obj ) = @_;
653
654     print scalar localtime, " - Polling for updates for $username" if &debug;
655     my $tweets;
656     eval {
657         $tweets = $obj->friends_timeline(
658             { since => HTTP::Date::time2str($last_poll) } );
659     };
660
661     if ($@) {
662         print $fh "type:error Error during friends_timeline call.  Aborted.\n";
663         return 1;
664     }
665
666     unless ( ref $tweets ) {
667         if ( $obj->can("get_error") ) {
668             print $fh "type:error API Error during friends_timeline call: ",
669               JSON::Any->jsonToObj( $obj->get_error() ), "  Aborted.\n";
670         } else {
671             print $fh
672               "type:error API Error during friends_timeline call. Aborted.\n";
673         }
674         return 1;
675     }
676
677     foreach my $t ( reverse @$tweets ) {
678         my $text = decode_entities( $t->{text} );
679         $text =~ s/%/%%/g;
680         $text =~ s/(^|\W)\@([-\w]+)/$1%B\@$2%n/g;
681         my $reply = "tweet";
682         if (    Irssi::settings_get_bool("show_reply_context")
683             and $t->{in_reply_to_screen_name} ne $username
684             and $t->{in_reply_to_screen_name}
685             and not exists $friends{ $t->{in_reply_to_screen_name} } )
686         {
687             $nicks{ $t->{in_reply_to_screen_name} } = time;
688             my $context = $obj->show_status( $t->{in_reply_to_status_id} );
689             if ($context) {
690                 my $ctext = decode_entities( $context->{text} );
691                 $ctext =~ s/%/%%/g;
692                 $ctext =~ s/(^|\W)\@([-\w]+)/$1%B\@$2%n/g;
693                 printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
694                   $context->{id}, $username,
695                   $context->{user}{screen_name}, $ctext;
696                 $reply = "reply";
697             } else {
698                 print "Failed to get context from $t->{in_reply_to_screen_name}"
699                   if &debug;
700             }
701         }
702         next
703           if $t->{user}{screen_name} eq $username
704               and not Irssi::settings_get_bool("show_own_tweets");
705         printf $fh "id:%d account:%s nick:%s type:%s %s\n",
706           $t->{id}, $username, $t->{user}{screen_name}, $reply, $text;
707     }
708
709     print scalar localtime, " - Polling for replies" if &debug;
710     eval {
711         $tweets = $obj->replies( { since => HTTP::Date::time2str($last_poll) } )
712           || [];
713     };
714
715     if ($@) {
716         print $fh "type:error Error during replies call.  Aborted.\n";
717         return 1;
718     }
719
720     foreach my $t ( reverse @$tweets ) {
721         next
722           if exists $friends{ $t->{user}{screen_name} };
723
724         my $text = decode_entities( $t->{text} );
725         $text =~ s/%/%%/g;
726         $text =~ s/(^|\W)\@([-\w]+)/$1%B\@$2%n/g;
727         printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
728           $t->{id}, $username, $t->{user}{screen_name}, $text;
729     }
730
731     print scalar localtime, " - Polling for DMs" if &debug;
732     eval {
733         $tweets =
734           $obj->direct_messages( { since => HTTP::Date::time2str($last_poll) } )
735           || [];
736     };
737
738     if ($@) {
739         print $fh "type:error Error during direct_messages call.  Aborted.\n";
740         return 1;
741     }
742
743     foreach my $t ( reverse @$tweets ) {
744         my $text = decode_entities( $t->{text} );
745         $text =~ s/%/%%/g;
746         $text =~ s/(^|\W)\@([-\w]+)/$1%B\@$2%n/g;
747         printf $fh "id:%d account:%s nick:%s type:dm %s\n",
748           $t->{id}, $username, $t->{sender_screen_name}, $text;
749     }
750     print scalar localtime, " - Done" if &debug;
751
752     return 0;
753 }
754
755 sub monitor_child {
756     my ($data)   = @_;
757     my $filename = $data->[0];
758     my $attempt  = $data->[1];
759
760     print scalar localtime, " - checking child log at $filename ($attempt)"
761       if &debug;
762     my $new_last_poll;
763     if ( open FILE, $filename ) {
764         my @lines;
765         while (<FILE>) {
766             chomp;
767             last if /^__friends__/;
768             my %meta;
769             foreach my $key (qw/id account nick type/) {
770                 s/^$key:(\S+)\s*//;
771                 $meta{$key} = $1;
772             }
773
774             next if exists $meta{id} and exists $tweet_cache{ $meta{id} };
775             $tweet_cache{ $meta{id} } = time;
776             my $account = "";
777             if ( $meta{account} ne $user ) {
778                 $account = "$meta{account}: ";
779             }
780
781             my $marker = "";
782             if (    $meta{type} ne 'dm'
783                 and Irssi::settings_get_bool("twirssi_track_replies")
784                 and $meta{nick}
785                 and $meta{id} )
786             {
787                 $marker = ( $id_map{__indexes}{ $meta{nick} } + 1 ) % 100;
788                 $id_map{ lc $meta{nick} }[$marker] = $meta{id};
789                 $id_map{__indexes}{ $meta{nick} }  = $marker;
790                 $marker                            = ":$marker";
791             }
792
793             if ( $meta{type} eq 'tweet' ) {
794                 push @lines, "[$account%B\@$meta{nick}%n$marker] $_\n",;
795             } elsif ( $meta{type} eq 'reply' ) {
796                 push @lines, "[$account\\--> %B\@$meta{nick}%n$marker] $_\n",;
797             } elsif ( $meta{type} eq 'dm' ) {
798                 push @lines, "[$account%B\@$meta{nick}%n (%WDM%n)] $_\n",;
799             } elsif ( $meta{type} eq 'error' ) {
800                 push @lines, "ERROR: $_\n";
801             } elsif ( $meta{type} eq 'debug' ) {
802                 print "$_" if &debug,;
803             } else {
804                 print "Unknown line type $meta{type}: $_" if &debug,;
805             }
806         }
807
808         %friends = ();
809         while (<FILE>) {
810             if (/^\d+$/) {
811                 $new_last_poll = $_;
812                 last;
813             }
814             my ( $f, $t ) = split ' ', $_;
815             $nicks{$f} = $friends{$f} = $t;
816         }
817
818         if ($new_last_poll) {
819             print "new last_poll = $new_last_poll" if &debug;
820             foreach my $line (@lines) {
821                 chomp $line;
822                 $window->print( $line, MSGLEVEL_PUBLIC );
823                 foreach ( $line =~ /\@([-\w]+)/ ) {
824                     $nicks{$1} = time;
825                 }
826             }
827
828             close FILE;
829             unlink $filename
830               or warn "Failed to remove $filename: $!"
831               unless &debug;
832
833             # keep enough cached tweets, to make sure we don't show duplicates.
834             foreach ( keys %tweet_cache ) {
835                 next if $tweet_cache{$_} >= $last_poll;
836                 delete $tweet_cache{$_};
837             }
838             $last_poll = $new_last_poll;
839
840             # save id_map hash
841             if ( keys %id_map
842                 and my $file =
843                 Irssi::settings_get_str("twirssi_replies_store") )
844             {
845                 if ( open JSON, ">$file" ) {
846                     print JSON JSON::Any->objToJson( \%id_map );
847                     close JSON;
848                 } else {
849                     &notice("Failed to write replies to $file: $!");
850                 }
851             }
852             return;
853         }
854     }
855
856     close FILE;
857
858     if ( $attempt < 12 ) {
859         Irssi::timeout_add_once( 5000, 'monitor_child',
860             [ $filename, $attempt + 1 ] );
861     } else {
862         &notice("Giving up on polling $filename");
863         unlink $filename unless &debug;
864     }
865 }
866
867 sub debug {
868     return Irssi::settings_get_bool("twirssi_debug");
869 }
870
871 sub notice {
872     $window->print( "%R***%n @_", MSGLEVEL_PUBLIC );
873 }
874
875 sub sig_complete {
876     my ( $complist, $window, $word, $linestart, $want_space ) = @_;
877
878     # /twitter_reply gets a nick:num
879     if ( $linestart =~ /^\/twitter_reply(?:_as)?\s*$/ ) {
880         @$complist = grep /^\Q$word/i, sort keys %{ $id_map{__indexes} };
881     }
882
883     # /tweet, /tweet_as, /dm, /dm_as - complete @nicks (and nicks as the first
884     # arg to dm)
885     if ( $linestart =~ /^\/(?:tweet|dm)/ ) {
886         my $prefix = $word =~ s/^@//;
887         $prefix = 0 if $linestart eq '/dm' or $linestart eq '/dm_as';
888         push @$complist, grep /^\Q$word/i,
889           sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
890         @$complist = map { "\@$_" } @$complist if $prefix;
891     }
892 }
893
894 Irssi::settings_add_str( "twirssi", "twitter_window",     "twitter" );
895 Irssi::settings_add_str( "twirssi", "bitlbee_server",     "bitlbee" );
896 Irssi::settings_add_str( "twirssi", "short_url_provider", "TinyURL" );
897 Irssi::settings_add_str( "twirssi", "twirssi_location",
898     ".irssi/scripts/twirssi.pl" );
899 Irssi::settings_add_str( "twirssi", "twitter_usernames", undef );
900 Irssi::settings_add_str( "twirssi", "twitter_passwords", undef );
901 Irssi::settings_add_str( "twirssi", "twirssi_replies_store",
902     ".irssi/scripts/twirssi.json" );
903 Irssi::settings_add_bool( "twirssi", "tweet_to_away",         0 );
904 Irssi::settings_add_bool( "twirssi", "show_reply_context",    0 );
905 Irssi::settings_add_bool( "twirssi", "show_own_tweets",       1 );
906 Irssi::settings_add_bool( "twirssi", "twirssi_debug",         0 );
907 Irssi::settings_add_bool( "twirssi", "twirssi_first_run",     1 );
908 Irssi::settings_add_bool( "twirssi", "twirssi_track_replies", 1 );
909 $window = Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
910
911 if ($window) {
912     Irssi::command_bind( "dm",               "cmd_direct" );
913     Irssi::command_bind( "dm_as",            "cmd_direct_as" );
914     Irssi::command_bind( "tweet",            "cmd_tweet" );
915     Irssi::command_bind( "tweet_as",         "cmd_tweet_as" );
916     Irssi::command_bind( "twitter_reply",    "cmd_reply" );
917     Irssi::command_bind( "twitter_reply_as", "cmd_reply_as" );
918     Irssi::command_bind( "twitter_login",    "cmd_login" );
919     Irssi::command_bind( "twitter_logout",   "cmd_logout" );
920     Irssi::command_bind( "twitter_switch",   "cmd_switch" );
921     Irssi::command_bind( "twirssi_upgrade",  "cmd_upgrade" );
922     Irssi::command_bind(
923         "twirssi_dump",
924         sub {
925             print "twits: ", join ", ",
926               map { "u: $_->{username}" } values %twits;
927             print "friends: ", join ", ", sort keys %friends;
928             print "nicks: ",   join ", ", sort keys %nicks;
929             print "id_map: ", Dumper \%{ $id_map{__indexes} };
930             print "last poll: $last_poll";
931         }
932     );
933     Irssi::command_bind(
934         "twirssi_version",
935         sub {
936             &notice(
937 "Twirssi v$VERSION (r$REV);  Net::Twitter v$Net::Twitter::VERSION. "
938                   . "See details at http://tinyurl.com/twirssi" );
939         }
940     );
941     Irssi::command_bind(
942         "twitter_friend",
943         &gen_cmd(
944             "/twitter_friend <username>",
945             "create_friend",
946             sub { &notice("Following $_[0]"); $nicks{ $_[0] } = time; }
947         )
948     );
949     Irssi::command_bind(
950         "twitter_unfriend",
951         &gen_cmd(
952             "/twitter_unfriend <username>",
953             "destroy_friend",
954             sub { &notice("Stopped following $_[0]"); delete $nicks{ $_[0] }; }
955         )
956     );
957     Irssi::command_bind( "twitter_updates", "get_updates" );
958     Irssi::signal_add_last( 'complete word' => \&sig_complete );
959
960     &notice("  %Y<%C(%B^%C)%N                   TWIRSSI v%R$VERSION%N (r$REV)");
961     &notice("   %C(_(\\%N           http://twirssi.com/ for full docs");
962     &notice(
963         "    %Y||%C `%N Log in with /twitter_login, send updates with /tweet");
964
965     my $file = Irssi::settings_get_str("twirssi_replies_store");
966     if ( $file and -r $file ) {
967         if ( open( JSON, $file ) ) {
968             local $/;
969             my $json = <JSON>;
970             close JSON;
971             eval {
972                 my $ref = JSON::Any->jsonToObj($json);
973                 %id_map = %$ref;
974                 my $num = keys %{ $id_map{__indexes} };
975                 &notice( sprintf "Loaded old replies from %d contact%s.",
976                     $num, ( $num == 1 ? "" : "s" ) );
977             };
978         } else {
979             &notice("Failed to load old replies from $file: $!");
980         }
981     }
982
983     if ( my $provider = Irssi::settings_get_str("short_url_provider") ) {
984         eval "use WWW::Shorten::$provider;";
985
986         if ($@) {
987             &notice(
988 "Failed to load WWW::Shorten::$provider - either clear short_url_provider or install the CPAN module"
989             );
990         }
991     }
992
993     if (    my $autouser = Irssi::settings_get_str("twitter_usernames")
994         and my $autopass = Irssi::settings_get_str("twitter_passwords") )
995     {
996         &cmd_login();
997     }
998
999 } else {
1000     Irssi::active_win()
1001       ->print( "Create a window named "
1002           . Irssi::settings_get_str('twitter_window')
1003           . " or change the value of twitter_window.  Then, reload twirssi." );
1004 }
1005