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