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