6358591b9b6e4bfeffbea0b8e266a22239b61cde
[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: 354 $' =~ /(\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:46:04 -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/(^|\W)\@([-\w]+)/$1\cC12\@$2\cC/g;
619         $text =~ s/[\n\r]/ /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/(^|\W)\@([-\w]+)/$1\cC12\@$2\cC/g;
635                 $ctext =~ s/[\n\r]/ /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/(^|\W)\@([-\w]+)/$1\cC12\@$2\cC/g;
672         $text =~ s/[\n\r]/ /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/(^|\W)\@([-\w]+)/$1\cC12\@$2\cC/g;
692         $text =~ s/[\n\r]/ /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                 $window->printformat(MSGLEVEL_PUBLIC, 'twirssi_tweet',
742                   $account, $meta{nick}, $marker, $_);
743             } elsif ( $meta{type} eq 'reply' ) {
744                 $window->printformat(MSGLEVEL_PUBLIC, 'twirssi_reply',
745                   $account, $meta{nick}, $marker, $_);
746             } elsif ( $meta{type} eq 'dm' ) {
747                 $window->printformat(MSGLEVEL_PUBLIC, 'twirssi_dm',
748                   $account, $meta{nick}, $_);
749             } elsif ( $meta{type} eq 'error' ) {
750                 $window->print("ERROR: $_", MSGLEVEL_PUBLIC);
751             } elsif ( $meta{type} eq 'debug' ) {
752                 print "$_" if &debug,;
753             } else {
754                 print "Unknown line type $meta{type}: $_" if &debug,;
755             }
756         }
757
758         %friends = ();
759         while (<FILE>) {
760             if (/^\d+$/) {
761                 $new_last_poll = $_;
762                 last;
763             }
764             my ( $f, $t ) = split ' ', $_;
765             $nicks{$f} = $friends{$f} = $t;
766         }
767
768         if ($new_last_poll) {
769             print "new last_poll = $new_last_poll" if &debug;
770
771             close FILE;
772             unlink $filename
773               or warn "Failed to remove $filename: $!"
774               unless &debug;
775
776             # keep enough cached tweets, to make sure we don't show duplicates.
777             foreach ( keys %tweet_cache ) {
778                 next if $tweet_cache{$_} >= $last_poll;
779                 delete $tweet_cache{$_};
780             }
781             $last_poll = $new_last_poll;
782
783             # save id_map hash
784             if ( keys %id_map
785                 and my $file =
786                 Irssi::settings_get_str("twirssi_replies_store") )
787             {
788                 if ( open JSON, ">$file" ) {
789                     print JSON JSON::Any->objToJson( \%id_map );
790                     close JSON;
791                 } else {
792                     &notice("Failed to write replies to $file: $!");
793                 }
794             }
795             return;
796         }
797     }
798
799     close FILE;
800
801     if ( $attempt < 12 ) {
802         Irssi::timeout_add_once( 5000, 'monitor_child',
803             [ $filename, $attempt + 1 ] );
804     } else {
805         &notice("Giving up on polling $filename");
806         unlink $filename unless &debug;
807     }
808 }
809
810 sub debug {
811     return Irssi::settings_get_bool("twirssi_debug");
812 }
813
814 sub notice {
815     $window->print( "%R***%n @_", MSGLEVEL_PUBLIC );
816 }
817
818 sub update_away {
819     my $data = shift;
820
821     if (    Irssi::settings_get_bool("tweet_to_away")
822         and $data !~ /\@\w/
823         and $data !~ /^[dD] / )
824     {
825         my $server =
826           Irssi::server_find_tag( Irssi::settings_get_str("bitlbee_server") );
827         if ($server) {
828             $server->send_raw("away :$data");
829             return 1;
830         } else {
831             &notice( "Can't find bitlbee server.",
832                 "Update bitlbee_server or disable tweet_to_away" );
833             return 0;
834         }
835     }
836
837     return 0;
838 }
839
840 sub too_long {
841     my $data = shift;
842
843     if ( length $data > 140 ) {
844         &notice(
845             "Tweet too long (" . length($data) . " characters) - aborted" );
846         return 1;
847     }
848
849     return 0;
850 }
851
852 sub valid_username {
853     my $username = shift;
854
855     unless ( exists $twits{$username} ) {
856         &notice("Unknown username $username");
857         return 0;
858     }
859
860     return 1;
861 }
862
863 sub logged_in {
864     my $obj = shift;
865     unless ($obj) {
866         &notice("Not logged in!  Use /twitter_login username pass!");
867         return 0;
868     }
869
870     return 1;
871 }
872
873 sub sig_complete {
874     my ( $complist, $window, $word, $linestart, $want_space ) = @_;
875
876     if (
877         $linestart =~ /^\/twitter_reply(?:_as)?\s*$/
878         or ( Irssi::settings_get_bool("twirssi_use_reply_aliases")
879             and $linestart =~ /^\/reply(?:_as)?\s*$/ )
880       )
881     {    # /twitter_reply gets a nick:num
882         @$complist = grep /^\Q$word/i, sort keys %{ $id_map{__indexes} };
883     }
884
885     # /tweet, /tweet_as, /dm, /dm_as - complete @nicks (and nicks as the first
886     # arg to dm)
887     if ( $linestart =~ /^\/(?:tweet|dm)/ ) {
888         my $prefix = $word =~ s/^@//;
889         $prefix = 0 if $linestart eq '/dm' or $linestart eq '/dm_as';
890         push @$complist, grep /^\Q$word/i,
891           sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
892         @$complist = map { "\@$_" } @$complist if $prefix;
893     }
894 }
895
896 sub event_send_text {
897     my ( $line, $server, $win ) = @_;
898     my $awin = Irssi::active_win();
899
900     # if the window where we got our text was the twitter window, and the user
901     # wants to be lazy, tweet away!
902     if ( ($awin->get_active_name() eq $window->{name})
903          and Irssi::settings_get_bool("tweet_window_input") ) {
904         &cmd_tweet($line, $server, $win);
905     }
906 }
907
908 Irssi::signal_add( "send text", "event_send_text" );
909
910 Irssi::theme_register([
911     'twirssi_tweet', '[$0%B@$1%n$2] $3',
912     'twirssi_reply', '[$0\--> %B@$1%n$2] $3',
913     'twirssi_dm',    '[$0%B@$1%n (%WDM%n)] $2',
914 ]);
915
916 Irssi::settings_add_str( "twirssi", "twitter_window",     "twitter" );
917 Irssi::settings_add_str( "twirssi", "bitlbee_server",     "bitlbee" );
918 Irssi::settings_add_str( "twirssi", "short_url_provider", "TinyURL" );
919 Irssi::settings_add_str( "twirssi", "twirssi_location",
920     ".irssi/scripts/twirssi.pl" );
921 Irssi::settings_add_str( "twirssi", "twitter_usernames", undef );
922 Irssi::settings_add_str( "twirssi", "twitter_passwords", undef );
923 Irssi::settings_add_str( "twirssi", "twirssi_replies_store",
924     ".irssi/scripts/twirssi.json" );
925 Irssi::settings_add_bool( "twirssi", "tweet_to_away",             0 );
926 Irssi::settings_add_bool( "twirssi", "show_reply_context",        0 );
927 Irssi::settings_add_bool( "twirssi", "show_own_tweets",           1 );
928 Irssi::settings_add_bool( "twirssi", "twirssi_debug",             0 );
929 Irssi::settings_add_bool( "twirssi", "twirssi_first_run",         1 );
930 Irssi::settings_add_bool( "twirssi", "twirssi_track_replies",     1 );
931 Irssi::settings_add_bool( "twirssi", "twirssi_use_reply_aliases", 0 );
932 Irssi::settings_add_bool( "twirssi", "tweet_window_input",        0 );
933 $window = Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
934
935 if ($window) {
936     Irssi::command_bind( "dm",               "cmd_direct" );
937     Irssi::command_bind( "dm_as",            "cmd_direct_as" );
938     Irssi::command_bind( "tweet",            "cmd_tweet" );
939     Irssi::command_bind( "tweet_as",         "cmd_tweet_as" );
940     Irssi::command_bind( "twitter_reply",    "cmd_reply" );
941     Irssi::command_bind( "twitter_reply_as", "cmd_reply_as" );
942     Irssi::command_bind( "twitter_login",    "cmd_login" );
943     Irssi::command_bind( "twitter_logout",   "cmd_logout" );
944     Irssi::command_bind( "twitter_switch",   "cmd_switch" );
945     Irssi::command_bind( "twirssi_upgrade",  "cmd_upgrade" );
946     if ( Irssi::settings_get_bool("twirssi_use_reply_aliases") ) {
947         Irssi::command_bind( "reply",    "cmd_reply" );
948         Irssi::command_bind( "reply_as", "cmd_reply_as" );
949     }
950     Irssi::command_bind(
951         "twirssi_dump",
952         sub {
953             print "twits: ", join ", ",
954               map { "u: $_->{username}" } values %twits;
955             print "friends: ", join ", ", sort keys %friends;
956             print "nicks: ",   join ", ", sort keys %nicks;
957             print "id_map: ", Dumper \%{ $id_map{__indexes} };
958             print "last poll: $last_poll";
959         }
960     );
961     Irssi::command_bind(
962         "twirssi_version",
963         sub {
964             &notice("Twirssi v$VERSION (r$REV); "
965                   . "Net::Twitter v$Net::Twitter::VERSION. "
966                   . "JSON in use: "
967                   . JSON::Any::handler()
968                   . ".  See details at http://twirssi.com/" );
969         }
970     );
971     Irssi::command_bind(
972         "twitter_friend",
973         &gen_cmd(
974             "/twitter_friend <username>",
975             "create_friend",
976             sub { &notice("Following $_[0]"); $nicks{ $_[0] } = time; }
977         )
978     );
979     Irssi::command_bind(
980         "twitter_unfriend",
981         &gen_cmd(
982             "/twitter_unfriend <username>",
983             "destroy_friend",
984             sub { &notice("Stopped following $_[0]"); delete $nicks{ $_[0] }; }
985         )
986     );
987     Irssi::command_bind( "twitter_updates", "get_updates" );
988     Irssi::signal_add_last( 'complete word' => \&sig_complete );
989
990     &notice("  %Y<%C(%B^%C)%N                   TWIRSSI v%R$VERSION%N (r$REV)");
991     &notice("   %C(_(\\%N           http://twirssi.com/ for full docs");
992     &notice(
993         "    %Y||%C `%N Log in with /twitter_login, send updates with /tweet");
994
995     my $file = Irssi::settings_get_str("twirssi_replies_store");
996     if ( $file and -r $file ) {
997         if ( open( JSON, $file ) ) {
998             local $/;
999             my $json = <JSON>;
1000             close JSON;
1001             eval {
1002                 my $ref = JSON::Any->jsonToObj($json);
1003                 %id_map = %$ref;
1004                 my $num = keys %{ $id_map{__indexes} };
1005                 &notice( sprintf "Loaded old replies from %d contact%s.",
1006                     $num, ( $num == 1 ? "" : "s" ) );
1007             };
1008         } else {
1009             &notice("Failed to load old replies from $file: $!");
1010         }
1011     }
1012
1013     if ( my $provider = Irssi::settings_get_str("short_url_provider") ) {
1014         eval "use WWW::Shorten::$provider;";
1015
1016         if ($@) {
1017             &notice(
1018 "Failed to load WWW::Shorten::$provider - either clear short_url_provider or install the CPAN module"
1019             );
1020         }
1021     }
1022
1023     if (    my $autouser = Irssi::settings_get_str("twitter_usernames")
1024         and my $autopass = Irssi::settings_get_str("twitter_passwords") )
1025     {
1026         &cmd_login();
1027     }
1028
1029 } else {
1030     Irssi::active_win()
1031       ->print( "Create a window named "
1032           . Irssi::settings_get_str('twitter_window')
1033           . " or change the value of twitter_window.  Then, reload twirssi." );
1034 }
1035