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