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