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