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