2375ba9b0504299f51079c357904c6b5d900155b
[twirssi-net-twitter-lite.git] / twirssi.pl
1 use strict;
2 use Irssi;
3 use Irssi::Irc;
4 use HTTP::Date;
5 use HTML::Entities;
6 use File::Temp;
7 use LWP::Simple;
8 use Data::Dumper;
9 $Data::Dumper::Indent = 1;
10
11 use vars qw($VERSION %IRSSI);
12
13 $VERSION = "2.2.1beta";
14 my ($REV) = '$Rev: 607 $' =~ /(\d+)/;
15 %IRSSI = (
16     authors     => 'Dan Boger',
17     contact     => 'zigdon@gmail.com',
18     name        => 'twirssi',
19     description => 'Send twitter updates using /tweet.  '
20       . 'Can optionally set your bitlbee /away message to same',
21     license => 'GNU GPL v2',
22     url     => 'http://twirssi.com',
23     changed => '$Date: 2009-04-09 21:22:55 -0700 (Thu, 09 Apr 2009) $',
24 );
25
26 my $window;
27 my $twit;
28 my %twits;
29 my $user;
30 my $defservice;
31 my $poll;
32 my $last_poll;
33 my %nicks;
34 my %friends;
35 my %tweet_cache;
36 my %id_map;
37 my $failwhale            = 0;
38 my %irssi_to_mirc_colors = (
39     '%k' => '01',
40     '%r' => '05',
41     '%g' => '03',
42     '%y' => '07',
43     '%b' => '02',
44     '%m' => '06',
45     '%c' => '10',
46     '%w' => '15',
47     '%K' => '14',
48     '%R' => '04',
49     '%G' => '09',
50     '%Y' => '08',
51     '%B' => '12',
52     '%M' => '13',
53     '%C' => '11',
54     '%W' => '00',
55 );
56
57 sub cmd_direct {
58     my ( $data, $server, $win ) = @_;
59
60     return unless &logged_in($twit);
61
62     my ( $target, $text ) = split ' ', $data, 2;
63     unless ( $target and $text ) {
64         &notice("Usage: /dm <nick> <message>");
65         return;
66     }
67
68     &cmd_direct_as( "$user $data", $server, $win );
69 }
70
71 sub cmd_direct_as {
72     my ( $data, $server, $win ) = @_;
73
74     return unless &logged_in($twit);
75
76     my ( $username, $target, $text ) = split ' ', $data, 3;
77     unless ( $username and $target and $text ) {
78         &notice("Usage: /dm_as <username> <nick> <message>");
79         return;
80     }
81
82     return unless $username = &valid_username($username);
83
84     eval {
85         if ( $twits{$username}
86             ->new_direct_message( { user => $target, text => $text } ) )
87         {
88             &notice("DM sent to $target");
89             $nicks{$target} = time;
90         } else {
91             my $error;
92             eval {
93                 $error = JSON::Any->jsonToObj( $twits{$username}->get_error() );
94                 $error = $error->{error};
95             };
96             die $error if $error;
97             &notice("DM to $target failed");
98         }
99     };
100
101     if ($@) {
102         &notice("DM caused an error: $@");
103         return;
104     }
105 }
106
107 sub cmd_retweet {
108     my ( $data, $server, $win ) = @_;
109
110     return unless &logged_in($twit);
111
112     $data =~ s/^\s+|\s+$//;
113     unless ($data) {
114         &notice("Usage: /retweet <nick[:num]> [comment]");
115         return;
116     }
117
118     my ( $id, $data ) = split ' ', $data, 2;
119
120     &cmd_retweet_as( "$user $id $data", $server, $win );
121 }
122
123 sub cmd_retweet_as {
124     my ( $data, $server, $win ) = @_;
125
126     unless ( Irssi::settings_get_bool("twirssi_track_replies") ) {
127         &notice("twirssi_track_replies is required in order to reteet.");
128         return;
129     }
130
131     return unless &logged_in($twit);
132
133     $data =~ s/^\s+|\s+$//;
134     my ( $username, $id, $data ) = split ' ', $data, 3;
135
136     unless ($username) {
137         &notice("Usage: /retweet_as <username> <nick[:num]> [comment]");
138         return;
139     }
140
141     return unless $username = &valid_username($username);
142
143     my $nick;
144     $id =~ s/[^\w\d\-:]+//g;
145     ( $nick, $id ) = split /:/, $id;
146     unless ( exists $id_map{ lc $nick } ) {
147         &notice("Can't find a tweet from $nick to retweet!");
148         return;
149     }
150
151     $id = $id_map{__indexes}{$nick} unless $id;
152     unless ( $id_map{ lc $nick }[$id] ) {
153         &notice("Can't find a tweet numbered $id from $nick to retweet!");
154         return;
155     }
156
157     unless ( $id_map{__tweets}{ lc $nick }[$id] ) {
158         &notice("The text of this tweet isn't saved, sorry!");
159         return;
160     }
161
162 # Irssi::settings_add_str( "twirssi", "twirssi_retweet_format", 'RT $n: $t ${-- $c$}' );
163     my $text = Irssi::settings_get_str("twirssi_retweet_format");
164     $text =~ s/\$n/\@$nick/g;
165     if ($data) {
166         $text =~ s/\${|\$}//g;
167         $text =~ s/\$c/$data/;
168     } else {
169         $text =~ s/\${.*?\$}//;
170     }
171     $text =~ s/\$t/$id_map{__tweets}{ lc $nick }[$id]/;
172
173     $data = &shorten($text);
174
175     return if &too_long($data);
176
177     my $success = 1;
178     eval {
179         unless (
180             $twits{$username}->update(
181                 {
182                     status                => $data,
183                     in_reply_to_status_id => $id_map{ lc $nick }[$id]
184                 }
185             )
186           )
187         {
188             &notice("Update failed");
189             $success = 0;
190         }
191     };
192     return unless $success;
193
194     if ($@) {
195         &notice("Update caused an error: $@.  Aborted");
196         return;
197     }
198
199     foreach ( $data =~ /@([-\w]+)/ ) {
200         $nicks{$1} = time;
201     }
202
203     &notice("Retweet sent");
204 }
205
206 sub cmd_tweet {
207     my ( $data, $server, $win ) = @_;
208
209     return unless &logged_in($twit);
210
211     $data =~ s/^\s+|\s+$//;
212     unless ($data) {
213         &notice("Usage: /tweet <update>");
214         return;
215     }
216
217     &cmd_tweet_as( "$user\@$defservice $data", $server, $win );
218 }
219
220 sub cmd_tweet_as {
221     my ( $data, $server, $win ) = @_;
222
223     return unless &logged_in($twit);
224
225     $data =~ s/^\s+|\s+$//;
226     $data =~ s/\s\s+/ /g;
227     my ( $username, $data ) = split ' ', $data, 2;
228
229     unless ( $username and $data ) {
230         &notice("Usage: /tweet_as <username> <update>");
231         return;
232     }
233
234     return unless $username = &valid_username($username);
235
236     $data = &shorten($data);
237
238     return if &too_long($data);
239
240     my $success = 1;
241     eval {
242         unless ( $twits{$username}->update($data) )
243         {
244             &notice("Update failed");
245             $success = 0;
246         }
247     };
248     return unless $success;
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 cmd_reply {
265     my ( $data, $server, $win ) = @_;
266
267     return unless &logged_in($twit);
268
269     $data =~ s/^\s+|\s+$//;
270     unless ($data) {
271         &notice("Usage: /reply <nick[:num]> <update>");
272         return;
273     }
274
275     my ( $id, $data ) = split ' ', $data, 2;
276     unless ( $id and $data ) {
277         &notice("Usage: /reply <nick[:num]> <update>");
278         return;
279     }
280
281     &cmd_reply_as( "$user $id $data", $server, $win );
282 }
283
284 sub cmd_reply_as {
285     my ( $data, $server, $win ) = @_;
286
287     unless ( Irssi::settings_get_bool("twirssi_track_replies") ) {
288         &notice("twirssi_track_replies is required in order to reply to "
289               . "specific tweets.  Either enable it, or just use /tweet "
290               . "\@username <text>." );
291         return;
292     }
293
294     return unless &logged_in($twit);
295
296     $data =~ s/^\s+|\s+$//;
297     my ( $username, $id, $data ) = split ' ', $data, 3;
298
299     unless ( $username and $data ) {
300         &notice("Usage: /reply_as <username> <nick[:num]> <update>");
301         return;
302     }
303
304     return unless $username = &valid_username($username);
305
306     my $nick;
307     $id =~ s/[^\w\d\-:]+//g;
308     ( $nick, $id ) = split /:/, $id;
309     unless ( exists $id_map{ lc $nick } ) {
310         &notice("Can't find a tweet from $nick to reply to!");
311         return;
312     }
313
314     $id = $id_map{__indexes}{$nick} unless $id;
315     unless ( $id_map{ lc $nick }[$id] ) {
316         &notice("Can't find a tweet numbered $id from $nick to reply to!");
317         return;
318     }
319
320     if ( Irssi::settings_get_bool("twirssi_replies_autonick") ) {
321
322         # remove any @nick at the beginning of the reply, as we'll add it anyway
323         $data =~ s/^\s*\@?$nick\s*//;
324         $data = "\@$nick " . $data;
325     }
326
327     $data = &shorten($data);
328
329     return if &too_long($data);
330
331     my $success = 1;
332     eval {
333         unless (
334             $twits{$username}->update(
335                 {
336                     status                => $data,
337                     in_reply_to_status_id => $id_map{ lc $nick }[$id]
338                 }
339             )
340           )
341         {
342             &notice("Update failed");
343             $success = 0;
344         }
345     };
346     return unless $success;
347
348     if ($@) {
349         &notice("Update caused an error: $@.  Aborted");
350         return;
351     }
352
353     foreach ( $data =~ /@([-\w]+)/ ) {
354         $nicks{$1} = time;
355     }
356
357     my $away = &update_away($data);
358
359     &notice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
360 }
361
362 sub gen_cmd {
363     my ( $usage_str, $api_name, $post_ref ) = @_;
364
365     return sub {
366         my ( $data, $server, $win ) = @_;
367
368         return unless &logged_in($twit);
369
370         $data =~ s/^\s+|\s+$//;
371         unless ($data) {
372             &notice("Usage: $usage_str");
373             return;
374         }
375
376         my $success = 1;
377         eval {
378             unless ( $twit->$api_name($data) )
379             {
380                 &notice("$api_name failed");
381                 $success = 0;
382             }
383         };
384         return unless $success;
385
386         if ($@) {
387             &notice("$api_name caused an error.  Aborted.");
388             return;
389         }
390
391         &$post_ref($data) if $post_ref;
392       }
393 }
394
395 sub cmd_switch {
396     my ( $data, $server, $win ) = @_;
397
398     $data =~ s/^\s+|\s+$//g;
399     $data = &normalize_username($data);
400     if ( exists $twits{$data} ) {
401         &notice("Switching to $data");
402         $twit = $twits{$data};
403         if ( $data =~ /(.*)\@(.*)/ ) {
404             $user       = $1;
405             $defservice = $2;
406         } else {
407             &notice("Couldn't figure out what service '$data' is on");
408         }
409     } else {
410         &notice("Unknown user $data");
411     }
412 }
413
414 sub cmd_logout {
415     my ( $data, $server, $win ) = @_;
416
417     $data =~ s/^\s+|\s+$//g;
418     $data = $user unless $data;
419     return unless $data = &valid_username($data);
420
421     &notice("Logging out $data...");
422     $twits{$data}->end_session();
423     delete $twits{$data};
424     undef $twit;
425     if ( keys %twits ) {
426         &cmd_switch( ( keys %twits )[0], $server, $win );
427     } else {
428         Irssi::timeout_remove($poll) if $poll;
429         undef $poll;
430     }
431 }
432
433 sub cmd_login {
434     my ( $data, $server, $win ) = @_;
435     my $pass;
436     if ($data) {
437         ( $user, $pass ) = split ' ', $data, 2;
438     } elsif ( my $autouser = Irssi::settings_get_str("twitter_usernames")
439         and my $autopass = Irssi::settings_get_str("twitter_passwords") )
440     {
441         my @user = split /\s*,\s*/, $autouser;
442         my @pass = split /\s*,\s*/, $autopass;
443
444         # if a password ends with a '\', it was meant to escape the comma, and
445         # it should be concatinated with the next one
446         my @unescaped;
447         while (@pass) {
448             my $p = shift @pass;
449             while ( $p =~ /\\$/ and @pass ) {
450                 $p .= "," . shift @pass;
451             }
452             push @unescaped, $p;
453         }
454
455         if ( @user != @unescaped ) {
456             &notice("Number of usernames doesn't match "
457                   . "the number of passwords - auto-login failed" );
458         } else {
459             my ( $u, $p );
460             while ( @user and @unescaped ) {
461                 $u = shift @user;
462                 $p = shift @unescaped;
463                 &cmd_login("$u $p");
464             }
465             return;
466         }
467     } else {
468         &notice("/twitter_login requires either a username and password "
469               . "or twitter_usernames and twitter_passwords to be set." );
470         return;
471     }
472
473     %friends = %nicks = ();
474
475     my $service;
476     if ( $user =~ /^(.*)@(twitter|identica)$/ ) {
477         ( $user, $service ) = ( $1, $2 );
478     } else {
479         $service = Irssi::settings_get_str("twirssi_default_service");
480     }
481     $defservice = $service = ucfirst lc $service;
482
483     eval "use Net::$service";
484     if ($@) {
485         &notice(
486             "Failed to load Net::$service when trying to log in as $user: $@");
487         return;
488     }
489
490     $twit = "Net::$service"->new(
491         username => $user,
492         password => $pass,
493         source   => "twirssi"
494     );
495
496     unless ( $twit->verify_credentials() ) {
497         &notice("Login as $user\@$service failed");
498         $twit = undef;
499         if ( keys %twits ) {
500             &cmd_switch( ( keys %twits )[0], $server, $win );
501         }
502         return;
503     }
504
505     if ($twit) {
506         my $rate_limit = $twit->rate_limit_status();
507         if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
508             &notice(
509                 "Rate limit exceeded, try again after $rate_limit->{reset_time}"
510             );
511             $twit = undef;
512             return;
513         }
514
515         $twits{"$user\@$service"} = $twit;
516         Irssi::timeout_remove($poll) if $poll;
517         $poll = Irssi::timeout_add( &get_poll_time * 1000, \&get_updates, "" );
518         &notice("Logged in as $user\@$service, loading friends list...");
519         &load_friends();
520         &notice( "loaded friends: ", scalar keys %friends );
521         if ( Irssi::settings_get_bool("twirssi_first_run") ) {
522             Irssi::settings_set_bool( "twirssi_first_run", 0 );
523             unless ( exists $friends{twirssi} ) {
524                 &notice("Welcome to twirssi!"
525                       . "  Perhaps you should add \@twirssi to your friends list,"
526                       . " so you can be notified when a new version is release?"
527                       . "  Just type /twitter_friend twirssi." );
528             }
529         }
530         %nicks = %friends;
531         $nicks{$user} = 0;
532         return 1;
533     } else {
534         &notice("Login failed");
535     }
536 }
537
538 sub cmd_add_search {
539     my ( $data, $server, $win ) = @_;
540
541     unless ( $twit and $twit->can('search') ) {
542         &notice("ERROR: Your version of Net::Twitter ($Net::Twitter::VERSION) "
543               . "doesn't support searches." );
544         return;
545     }
546
547     $data =~ s/^\s+|\s+$//;
548     $data = lc $data;
549
550     unless ($data) {
551         &notice("Usage: /twitter_subscribe <topic>");
552         return;
553     }
554
555     if ( exists $id_map{__searches}{$user}{$data} ) {
556         &notice("Already had a subscription for '$data'");
557         return;
558     }
559
560     $id_map{__searches}{$user}{$data} = 1;
561     &notice("Added subscription for '$data'");
562 }
563
564 sub cmd_del_search {
565     my ( $data, $server, $win ) = @_;
566
567     unless ( $twit and $twit->can('search') ) {
568         &notice("ERROR: Your version of Net::Twitter ($Net::Twitter::VERSION) "
569               . "doesn't support searches." );
570         return;
571     }
572     $data =~ s/^\s+|\s+$//;
573     $data = lc $data;
574
575     unless ($data) {
576         &notice("Usage: /twitter_unsubscribe <topic>");
577         return;
578     }
579
580     unless ( exists $id_map{__searches}{$user}{$data} ) {
581         &notice("No subscription found for '$data'");
582         return;
583     }
584
585     delete $id_map{__searches}{$user}{$data};
586     &notice("Removed subscription for '$data'");
587 }
588
589 sub cmd_list_search {
590     my ( $data, $server, $win ) = @_;
591
592     my $found = 0;
593     foreach my $suser ( sort keys %{ $id_map{__searches} } ) {
594         my $topics;
595         foreach my $topic ( sort keys %{ $id_map{__searches}{$suser} } ) {
596             $topics = $topics ? "$topics, $topic" : $topic;
597         }
598         if ($topics) {
599             $found = 1;
600             &notice("Search subscriptions for \@$suser: $topics");
601         }
602     }
603
604     unless ($found) {
605         &notice("No search subscriptions set up");
606     }
607 }
608
609 sub cmd_upgrade {
610     my ( $data, $server, $win ) = @_;
611
612     my $loc = Irssi::settings_get_str("twirssi_location");
613     unless ( -w $loc ) {
614         &notice(
615 "$loc isn't writable, can't upgrade.  Perhaps you need to /set twirssi_location?"
616         );
617         return;
618     }
619
620     my $md5;
621     unless ( $data or Irssi::settings_get_bool("twirssi_upgrade_beta") ) {
622         eval { use Digest::MD5; };
623
624         if ($@) {
625             &notice(
626 "Failed to load Digest::MD5.  Try '/twirssi_upgrade nomd5' to skip MD5 verification"
627             );
628             return;
629         }
630
631         $md5 = get("http://twirssi.com/md5sum");
632         chomp $md5;
633         $md5 =~ s/ .*//;
634         unless ($md5) {
635             &notice("Failed to download md5sum from peeron!  Aborting.");
636             return;
637         }
638
639         unless ( open( CUR, $loc ) ) {
640             &notice(
641 "Failed to read $loc.  Check that /set twirssi_location is set to the correct location."
642             );
643             return;
644         }
645
646         my $cur_md5 = Digest::MD5::md5_hex(<CUR>);
647         close CUR;
648
649         if ( $cur_md5 eq $md5 ) {
650             &notice("Current twirssi seems to be up to date.");
651             return;
652         }
653     }
654
655     my $URL =
656       Irssi::settings_get_bool("twirssi_upgrade_beta")
657       ? "http://github.com/zigdon/twirssi/raw/master/twirssi.pl"
658       : "http://twirssi.com/twirssi.pl";
659     &notice("Downloading twirssi from $URL");
660     LWP::Simple::getstore( $URL, "$loc.upgrade" );
661
662     unless ( $data or Irssi::settings_get_bool("twirssi_upgrade_beta") ) {
663         unless ( open( NEW, "$loc.upgrade" ) ) {
664             &notice(
665 "Failed to read $loc.upgrade.  Check that /set twirssi_location is set to the correct location."
666             );
667             return;
668         }
669
670         my $new_md5 = Digest::MD5::md5_hex(<NEW>);
671         close NEW;
672
673         if ( $new_md5 ne $md5 ) {
674             &notice("MD5 verification failed. expected $md5, got $new_md5");
675             return;
676         }
677     }
678
679     rename $loc, "$loc.backup"
680       or &notice("Failed to back up $loc: $!.  Aborting")
681       and return;
682     rename "$loc.upgrade", $loc
683       or &notice("Failed to rename $loc.upgrade: $!.  Aborting")
684       and return;
685
686     my ( $dir, $file ) = ( $loc =~ m{(.*)/([^/]+)$} );
687     if ( -e "$dir/autorun/$file" ) {
688         &notice("Updating $dir/autorun/$file");
689         unlink "$dir/autorun/$file"
690           or &notice("Failed to remove old $file from autorun: $!");
691         symlink "../$file", "$dir/autorun/$file"
692           or &notice("Failed to create symlink in autorun directory: $!");
693     }
694
695     &notice("Download complete.  Reload twirssi with /script load $file");
696 }
697
698 sub load_friends {
699     my $fh   = shift;
700     my $page = 1;
701     my %new_friends;
702     eval {
703         while (1)
704         {
705             print $fh "type:debug Loading friends page $page...\n"
706               if ( $fh and &debug );
707             my $friends = $twit->friends( { page => $page } );
708             last unless $friends;
709             $new_friends{ $_->{screen_name} } = time foreach @$friends;
710             $page++;
711             last if @$friends == 0 or $page == 10;
712         }
713     };
714
715     if ($@) {
716         print $fh "type:debug Error during friends list update.  Aborted.\n";
717         return;
718     }
719
720     my ( $added, $removed ) = ( 0, 0 );
721     print $fh "type:debug Scanning for new friends...\n" if ( $fh and &debug );
722     foreach ( keys %new_friends ) {
723         next if exists $friends{$_};
724         $friends{$_} = time;
725         $added++;
726     }
727
728     print $fh "type:debug Scanning for removed friends...\n"
729       if ( $fh and &debug );
730     foreach ( keys %friends ) {
731         next if exists $new_friends{$_};
732         delete $friends{$_};
733         $removed++;
734     }
735
736     return ( $added, $removed );
737 }
738
739 sub get_updates {
740     print scalar localtime, " - get_updates starting" if &debug;
741
742     $window =
743       Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
744     unless ($window) {
745         Irssi::active_win()
746           ->print( "Can't find a window named '"
747               . Irssi::settings_get_str('twitter_window')
748               . "'.  Create it or change the value of twitter_window" );
749     }
750
751     return unless &logged_in($twit);
752
753     my ( $fh, $filename ) = File::Temp::tempfile();
754     binmode( $fh, ":utf8" );
755     my $pid = fork();
756
757     if ($pid) {    # parent
758         Irssi::timeout_add_once( 5000, 'monitor_child', [ $filename, 0 ] );
759         Irssi::pidwait_add($pid);
760     } elsif ( defined $pid ) {    # child
761         close STDIN;
762         close STDOUT;
763         close STDERR;
764
765         my $new_poll = time;
766
767         my $error = 0;
768         my %context_cache;
769         foreach ( keys %twits ) {
770             $error++ unless &do_updates( $fh, $_, $twits{$_}, \%context_cache );
771         }
772
773         my ( $added, $removed ) = &load_friends($fh);
774         if ( $added + $removed ) {
775             print $fh "type:debug %R***%n Friends list updated: ",
776               join( ", ",
777                 sprintf( "%d added",   $added ),
778                 sprintf( "%d removed", $removed ) ),
779               "\n";
780         }
781         print $fh "__friends__\n";
782         foreach ( sort keys %friends ) {
783             print $fh "$_ $friends{$_}\n";
784         }
785
786         if ($error) {
787             print $fh "type:debug Update encountered errors.  Aborted\n";
788             print $fh "-- $last_poll";
789         } else {
790             print $fh "-- $new_poll";
791         }
792         close $fh;
793         exit;
794     }
795     print scalar localtime, " - get_updates ends" if &debug;
796 }
797
798 sub do_updates {
799     my ( $fh, $username, $obj, $cache ) = @_;
800
801     my $rate_limit = $obj->rate_limit_status();
802     if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
803         &notice("Rate limit exceeded for $username");
804         return undef;
805     }
806
807     print scalar localtime, " - Polling for updates for $username" if &debug;
808     my $tweets;
809     my $new_poll_id = 0;
810     eval {
811         if ( $id_map{__last_id}{$username}{timeline} )
812         {
813             $tweets = $obj->friends_timeline(
814                 { since_id => $id_map{__last_id}{$username}{timeline} } );
815         } else {
816             $tweets = $obj->friends_timeline();
817         }
818     };
819
820     if ($@) {
821         print $fh "type:debug Error during friends_timeline call: Aborted.\n";
822         print $fh "type:debug : $_\n" foreach split /\n/, Dumper($@);
823         return undef;
824     }
825
826     unless ( ref $tweets ) {
827         if ( $obj->can("get_error") ) {
828             my $error = "Unknown error";
829             eval { $error = JSON::Any->jsonToObj( $obj->get_error() ) };
830             unless ($@) { $error = $obj->get_error() }
831             print $fh
832               "type:debug API Error during friends_timeline call: Aborted\n";
833             print $fh "type:debug : $_\n" foreach split /\n/, Dumper($error);
834
835         } else {
836             print $fh
837               "type:debug API Error during friends_timeline call. Aborted.\n";
838         }
839         return undef;
840     }
841
842     foreach my $t ( reverse @$tweets ) {
843         my $text = decode_entities( $t->{text} );
844         $text = &hilight($text);
845         my $reply = "tweet";
846         if (    Irssi::settings_get_bool("show_reply_context")
847             and $t->{in_reply_to_screen_name} ne $username
848             and $t->{in_reply_to_screen_name}
849             and not exists $friends{ $t->{in_reply_to_screen_name} } )
850         {
851             $nicks{ $t->{in_reply_to_screen_name} } = time;
852             my $context;
853             unless ( $cache->{ $t->{in_reply_to_status_id} } ) {
854                 eval {
855                     $cache->{ $t->{in_reply_to_status_id} } =
856                       $obj->show_status( $t->{in_reply_to_status_id} );
857                 };
858
859             }
860             $context = $cache->{ $t->{in_reply_to_status_id} };
861
862             if ($context) {
863                 my $ctext = decode_entities( $context->{text} );
864                 $ctext = &hilight($ctext);
865                 if ( $context->{truncated} and ref($obj) ne 'Net::Identica' ) {
866                     $ctext .=
867                         " -- http://twitter.com/$context->{user}{screen_name}"
868                       . "/status/$context->{id}";
869                 }
870                 printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
871                   $context->{id}, $username,
872                   $context->{user}{screen_name}, $ctext;
873                 $reply = "reply";
874             }
875         }
876         next
877           if $t->{user}{screen_name} eq $username
878               and not Irssi::settings_get_bool("show_own_tweets");
879         if ( $t->{truncated} and ref($obj) ne 'Net::Identica' ) {
880             $text .= " -- http://twitter.com/$t->{user}{screen_name}"
881               . "/status/$t->{id}";
882         }
883         printf $fh "id:%d account:%s nick:%s type:%s %s\n",
884           $t->{id}, $username, $t->{user}{screen_name}, $reply, $text;
885         $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
886     }
887     printf $fh "id:%d account:%s type:last_id timeline\n",
888       $new_poll_id, $username;
889
890     print scalar localtime, " - Polling for replies" if &debug;
891     $new_poll_id = 0;
892     eval {
893         if ( $id_map{__last_id}{$username}{reply} )
894         {
895             $tweets = $obj->replies(
896                 { since_id => $id_map{__last_id}{$username}{reply} } )
897               || [];
898         } else {
899             $tweets = $obj->replies() || [];
900         }
901     };
902
903     if ($@) {
904         print $fh "type:debug Error during replies call.  Aborted.\n";
905         return undef;
906     }
907
908     foreach my $t ( reverse @$tweets ) {
909         next
910           if exists $friends{ $t->{user}{screen_name} };
911
912         my $text = decode_entities( $t->{text} );
913         $text = &hilight($text);
914         if ( $t->{truncated} ) {
915             $text .= " -- http://twitter.com/$t->{user}{screen_name}"
916               . "/status/$t->{id}";
917         }
918         printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
919           $t->{id}, $username, $t->{user}{screen_name}, $text;
920         $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
921     }
922     printf $fh "id:%d account:%s type:last_id reply\n", $new_poll_id, $username;
923
924     print scalar localtime, " - Polling for DMs" if &debug;
925     $new_poll_id = 0;
926     eval {
927         if ( $id_map{__last_id}{$username}{dm} )
928         {
929             $tweets = $obj->direct_messages(
930                 { since_id => $id_map{__last_id}{$username}{dm} } )
931               || [];
932         } else {
933             $tweets = $obj->direct_messages() || [];
934         }
935     };
936
937     if ($@) {
938         print $fh "type:debug Error during direct_messages call.  Aborted.\n";
939         return undef;
940     }
941
942     foreach my $t ( reverse @$tweets ) {
943         my $text = decode_entities( $t->{text} );
944         $text = &hilight($text);
945         printf $fh "id:%d account:%s nick:%s type:dm %s\n",
946           $t->{id}, $username, $t->{sender_screen_name}, $text;
947         $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
948     }
949     printf $fh "id:%d account:%s type:last_id dm\n", $new_poll_id, $username;
950
951     print scalar localtime, " - Polling for subscriptions" if &debug;
952     if ( $obj->can('search') and $id_map{__searches}{$username} ) {
953         my $search;
954         foreach my $topic ( sort keys %{ $id_map{__searches}{$username} } ) {
955             print $fh "type:debug searching for $topic since ",
956               "$id_map{__searches}{$username}{$topic}\n";
957             eval {
958                 $search = $obj->search(
959                     {
960                         q        => $topic,
961                         since_id => $id_map{__searches}{$username}{$topic}
962                     }
963                 );
964             };
965
966             if ($@) {
967                 print $fh
968                   "type:debug Error during search($topic) call.  Aborted.\n";
969                 return undef;
970             }
971
972             unless ( $search->{max_id} ) {
973                 print $fh "type:debug Invalid search results when searching",
974                   " for $topic. Aborted.\n";
975                 return undef;
976             }
977
978             $id_map{__searches}{$username}{$topic} = $search->{max_id};
979             printf $fh "id:%d account:%s type:searchid topic:%s\n",
980               $search->{max_id}, $username, $topic;
981
982             foreach my $t ( reverse @{ $search->{results} } ) {
983                 my $text = decode_entities( $t->{text} );
984                 $text = &hilight($text);
985                 printf $fh "id:%d account:%s nick:%s type:search topic:%s %s\n",
986                   $t->{id}, $username, $t->{from_user}, $topic, $text;
987                 $new_poll_id = $t->{id}
988                   if not $new_poll_id
989                       or $t->{id} < $new_poll_id;
990             }
991         }
992     }
993
994     print scalar localtime, " - Done" if &debug;
995
996     return 1;
997 }
998
999 sub monitor_child {
1000     my ($data)   = @_;
1001     my $filename = $data->[0];
1002     my $attempt  = $data->[1];
1003
1004     print scalar localtime, " - checking child log at $filename ($attempt)"
1005       if &debug;
1006     my ($new_last_poll);
1007
1008     # first time we run we don't want to print out *everything*, so we just
1009     # pretend
1010     my $suppress = 0;
1011     $suppress = 1 unless keys %tweet_cache;
1012
1013     if ( open FILE, $filename ) {
1014         my @lines;
1015         my %new_cache;
1016         while (<FILE>) {
1017             chomp;
1018             last if /^__friends__/;
1019             my $hilight = 0;
1020             my %meta;
1021
1022             foreach my $key (qw/id account nick type topic/) {
1023                 if (s/^$key:(\S+)\s*//) {
1024                     $meta{$key} = $1;
1025                 }
1026             }
1027
1028             if ( not $meta{type} or $meta{type} !~ /searchid|last_id/ ) {
1029                 if ( exists $meta{id} and exists $new_cache{ $meta{id} } ) {
1030                     next;
1031                 }
1032
1033                 $new_cache{ $meta{id} } = time;
1034
1035                 if ( exists $meta{id} and exists $tweet_cache{ $meta{id} } ) {
1036                     next;
1037                 }
1038             }
1039
1040             my $account = "";
1041             $meta{account} =~ s/\@(\w+)$//;
1042             $meta{service} = $1;
1043             if (
1044                 lc $meta{service} eq
1045                 lc Irssi::settings_get_str("twirssi_default_service") )
1046             {
1047                 $account = "$meta{account}: "
1048                   if lc "$meta{account}\@$meta{service}" ne lc
1049                       "$user\@$defservice";
1050             } else {
1051                 $account = "$meta{account}\@$meta{service}: ";
1052             }
1053
1054             my $marker = "";
1055             if (    $meta{type} ne 'dm'
1056                 and Irssi::settings_get_bool("twirssi_track_replies")
1057                 and $meta{nick}
1058                 and $meta{id} )
1059             {
1060                 $marker = ( $id_map{__indexes}{ $meta{nick} } + 1 ) % 100;
1061                 $id_map{ lc $meta{nick} }[$marker]           = $meta{id};
1062                 $id_map{__indexes}{ $meta{nick} }            = $marker;
1063                 $id_map{__tweets}{ lc $meta{nick} }[$marker] = $_;
1064                 $marker                                      = ":$marker";
1065             }
1066
1067             my $hilight_color =
1068               $irssi_to_mirc_colors{ Irssi::settings_get_str("hilight_color") };
1069             my $nick =
1070               '@' . substr( $meta{account}, 0, index( $meta{account}, "@" ) );
1071             if ( $_ =~ /\Q$nick\E(?:\W|$)/i
1072                 and Irssi::settings_get_bool("twirssi_hilights") )
1073             {
1074                 $meta{nick} = "\cC$hilight_color$meta{nick}\cO";
1075                 $hilight = MSGLEVEL_HILIGHT;
1076             }
1077
1078             if ( $meta{type} =~ /tweet|reply/ ) {
1079                 push @lines,
1080                   [
1081                     ( MSGLEVEL_PUBLIC | $hilight ),
1082                     $meta{type}, $account, $meta{nick}, $marker, $_
1083                   ];
1084             } elsif ( $meta{type} eq 'search' ) {
1085                 push @lines,
1086                   [
1087                     ( MSGLEVEL_PUBLIC | $hilight ),
1088                     $meta{type}, $account, $meta{topic},
1089                     $meta{nick}, $marker,  $_
1090                   ];
1091                 if (
1092                     exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
1093                     and $meta{id} >
1094                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
1095                 {
1096                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
1097                       $meta{id};
1098                 }
1099             } elsif ( $meta{type} eq 'dm' ) {
1100                 push @lines,
1101                   [
1102                     ( MSGLEVEL_MSGS | $hilight ),
1103                     $meta{type}, $account, $meta{nick}, $_
1104                   ];
1105             } elsif ( $meta{type} eq 'searchid' ) {
1106                 print "Search '$meta{topic}' returned id $meta{id}" if &debug;
1107                 if (
1108                     exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
1109                     and $meta{id} >=
1110                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
1111                 {
1112                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
1113                       $meta{id};
1114                 } elsif (&debug) {
1115                     print "Search '$meta{topic}' returned invalid id $meta{id}";
1116                 }
1117             } elsif ( $meta{type} eq 'last_id' ) {
1118                 $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} =
1119                   $meta{id}
1120                   if $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} <
1121                       $meta{id};
1122             } elsif ( $meta{type} eq 'error' ) {
1123                 push @lines, [ MSGLEVEL_MSGS, $_ ];
1124             } elsif ( $meta{type} eq 'debug' ) {
1125                 print "$_" if &debug,;
1126             } else {
1127                 print "Unknown line type $meta{type}: $_" if &debug,;
1128             }
1129         }
1130
1131         %friends = ();
1132         while (<FILE>) {
1133             if (/^-- (\d+)$/) {
1134                 ($new_last_poll) = ($1);
1135                 last;
1136             }
1137             my ( $f, $t ) = split ' ', $_;
1138             $nicks{$f} = $friends{$f} = $t;
1139         }
1140
1141         if ($new_last_poll) {
1142             print "new last_poll    = $new_last_poll" if &debug;
1143             print "new last_poll_id = ", Dumper( $id_map{__last_id} ) if &debug;
1144             if ($suppress) {
1145                 print "First call, not printing updates" if &debug;
1146             } else {
1147                 foreach my $line (@lines) {
1148                     $window->printformat(
1149                         $line->[0],
1150                         "twirssi_" . $line->[1],
1151                         @$line[ 2 .. $#$line ]
1152                     );
1153                 }
1154             }
1155
1156             close FILE;
1157             unlink $filename
1158               or warn "Failed to remove $filename: $!"
1159               unless &debug;
1160
1161             # commit the pending cache lines to the actual cache, now that
1162             # we've printed our output
1163             %tweet_cache = ( %tweet_cache, %new_cache );
1164
1165             # keep enough cached tweets, to make sure we don't show duplicates.
1166             foreach ( keys %tweet_cache ) {
1167                 next if $tweet_cache{$_} >= $last_poll - 3600;
1168                 delete $tweet_cache{$_};
1169             }
1170             $last_poll = $new_last_poll;
1171
1172             # save id_map hash
1173             if ( keys %id_map
1174                 and my $file =
1175                 Irssi::settings_get_str("twirssi_replies_store") )
1176             {
1177                 if ( open JSON, ">$file" ) {
1178                     print JSON JSON::Any->objToJson( \%id_map );
1179                     close JSON;
1180                 } else {
1181                     &ccrap("Failed to write replies to $file: $!");
1182                 }
1183             }
1184             $failwhale = 0;
1185             return;
1186         }
1187     }
1188
1189     close FILE;
1190
1191     if ( $attempt < 24 ) {
1192         Irssi::timeout_add_once( 5000, 'monitor_child',
1193             [ $filename, $attempt + 1 ] );
1194     } else {
1195         print "Giving up on polling $filename" if &debug;
1196         unlink $filename unless &debug;
1197
1198         return unless Irssi::settings_get_bool("twirssi_notify_timeouts");
1199
1200         my $since;
1201         my @time = localtime($last_poll);
1202         if ( time - $last_poll < 24 * 60 * 60 ) {
1203             $since = sprintf( "%d:%02d", @time[ 2, 1 ] );
1204         } else {
1205             $since = scalar localtime($last_poll);
1206         }
1207
1208         if ( not $failwhale and time - $last_poll > 60 * 60 ) {
1209             foreach my $whale (
1210                 q{     v  v        v},
1211                 q{     |  |  v     |  v},
1212                 q{     | .-, |     |  |},
1213                 q{  .--./ /  |  _.---.| },
1214                 q{   '-. (__..-"       \\},
1215                 q{      \\          a    |},
1216                 q{       ',.__.   ,__.-'/},
1217                 q{         '--/_.'----'`}
1218               )
1219             {
1220                 &ccrap($whale);
1221             }
1222             $failwhale = 1;
1223         }
1224         &ccrap("Haven't been able to get updated tweets since $since");
1225     }
1226 }
1227
1228 sub debug {
1229     return Irssi::settings_get_bool("twirssi_debug");
1230 }
1231
1232 sub notice {
1233     $window->print( "%R***%n @_", MSGLEVEL_PUBLIC );
1234 }
1235
1236 sub ccrap {
1237     $window->print( "%R***%n @_", MSGLEVEL_CLIENTCRAP );
1238 }
1239
1240 sub update_away {
1241     my $data = shift;
1242
1243     if (    Irssi::settings_get_bool("tweet_to_away")
1244         and $data !~ /\@\w/
1245         and $data !~ /^[dD] / )
1246     {
1247         my $server =
1248           Irssi::server_find_tag( Irssi::settings_get_str("bitlbee_server") );
1249         if ($server) {
1250             $server->send_raw("away :$data");
1251             return 1;
1252         } else {
1253             &ccrap( "Can't find bitlbee server.",
1254                 "Update bitlbee_server or disable tweet_to_away" );
1255             return 0;
1256         }
1257     }
1258
1259     return 0;
1260 }
1261
1262 sub too_long {
1263     my $data    = shift;
1264     my $noalert = shift;
1265
1266     if ( length $data > 140 ) {
1267         &notice( "Tweet too long (" . length($data) . " characters) - aborted" )
1268           unless $noalert;
1269         return 1;
1270     }
1271
1272     return 0;
1273 }
1274
1275 sub valid_username {
1276     my $username = shift;
1277
1278     $username = &normalize_username($username);
1279
1280     unless ( exists $twits{$username} ) {
1281         &notice("Unknown username $username");
1282         return undef;
1283     }
1284
1285     return $username;
1286 }
1287
1288 sub logged_in {
1289     my $obj = shift;
1290     unless ($obj) {
1291         &notice("Not logged in!  Use /twitter_login username pass!");
1292         return 0;
1293     }
1294
1295     return 1;
1296 }
1297
1298 sub sig_complete {
1299     my ( $complist, $window, $word, $linestart, $want_space ) = @_;
1300
1301     if (
1302         $linestart =~ /^\/(?:retweet|twitter_reply)(?:_as)?\s*$/
1303         or ( Irssi::settings_get_bool("twirssi_use_reply_aliases")
1304             and $linestart =~ /^\/reply(?:_as)?\s*$/ )
1305       )
1306     {    # /twitter_reply gets a nick:num
1307         $word =~ s/^@//;
1308         @$complist = map { "$_:$id_map{__indexes}{$_}" }
1309           sort { $nicks{$b} <=> $nicks{$a} }
1310           grep /^\Q$word/i,
1311           keys %{ $id_map{__indexes} };
1312     }
1313
1314     # /tweet, /tweet_as, /dm, /dm_as - complete @nicks (and nicks as the first
1315     # arg to dm)
1316     if ( $linestart =~ /^\/(?:tweet|dm)/ ) {
1317         my $prefix = $word =~ s/^@//;
1318         $prefix = 0 if $linestart eq '/dm' or $linestart eq '/dm_as';
1319         push @$complist, grep /^\Q$word/i,
1320           sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1321         @$complist = map { "\@$_" } @$complist if $prefix;
1322     }
1323 }
1324
1325 sub event_send_text {
1326     my ( $line, $server, $win ) = @_;
1327     my $awin = Irssi::active_win();
1328
1329     # if the window where we got our text was the twitter window, and the user
1330     # wants to be lazy, tweet away!
1331     if ( ( $awin->get_active_name() eq $window->{name} )
1332         and Irssi::settings_get_bool("tweet_window_input") )
1333     {
1334         &cmd_tweet( $line, $server, $win );
1335     }
1336 }
1337
1338 sub get_poll_time {
1339     my $poll = Irssi::settings_get_int("twitter_poll_interval");
1340     return $poll if $poll >= 60;
1341     return 60;
1342 }
1343
1344 sub hilight {
1345     my $text = shift;
1346
1347     if ( Irssi::settings_get_str("twirssi_nick_color") ) {
1348         my $c = Irssi::settings_get_str("twirssi_nick_color");
1349         $c = $irssi_to_mirc_colors{$c};
1350         $text =~ s/(^|\W)\@([-\w]+)/$1\cC$c\@$2\cO/g if $c;
1351     }
1352     if ( Irssi::settings_get_str("twirssi_topic_color") ) {
1353         my $c = Irssi::settings_get_str("twirssi_topic_color");
1354         $c = $irssi_to_mirc_colors{$c};
1355         $text =~ s/(^|\W)\#([-\w]+)/$1\cC$c\#$2\cO/g if $c;
1356     }
1357     $text =~ s/[\n\r]/ /g;
1358
1359     return $text;
1360 }
1361
1362 sub shorten {
1363     my $data = shift;
1364
1365     my $provider = Irssi::settings_get_str("short_url_provider");
1366     if (
1367         (
1368             Irssi::settings_get_bool("twirssi_always_shorten")
1369             or &too_long( $data, 1 )
1370         )
1371         and $provider
1372       )
1373     {
1374         my @args;
1375         if ( $provider eq 'Bitly' ) {
1376             @args[ 1, 2 ] = split ',',
1377               Irssi::settings_get_str("short_url_args"), 2;
1378             unless ( @args == 3 ) {
1379                 &ccrap(
1380                     "WWW::Shorten::Bitly requires a username and API key.",
1381                     "Set short_url_args to username,API_key or change your",
1382                     "short_url_provider."
1383                 );
1384                 return $data;
1385             }
1386         }
1387
1388         foreach my $url ( $data =~ /(https?:\/\/\S+[\w\/])/g ) {
1389             eval {
1390                 $args[0] = $url;
1391                 my $short = makeashorterlink(@args);
1392                 if ($short) {
1393                     $data =~ s/\Q$url/$short/g;
1394                 } else {
1395                     &notice("Failed to shorten $url!");
1396                 }
1397             };
1398         }
1399     }
1400
1401     return $data;
1402 }
1403
1404 sub normalize_username {
1405     my $user = shift;
1406
1407     my ( $username, $service ) = split /\@/, $user, 2;
1408     if ($service) {
1409         $service = ucfirst lc $service;
1410     } else {
1411         $service =
1412           ucfirst lc Irssi::settings_get_str("twirssi_default_service");
1413         unless ( exists $twits{"$username\@$service"} ) {
1414             $service = undef;
1415             foreach my $t ( sort keys %twits ) {
1416                 next unless $t =~ /^\Q$username\E\@(Twitter|Identica)/;
1417                 $service = $1;
1418                 last;
1419             }
1420
1421             unless ($service) {
1422                 &notice("Can't find a logged in user '$user'");
1423             }
1424         }
1425     }
1426
1427     return "$username\@$service";
1428 }
1429
1430 Irssi::signal_add( "send text", "event_send_text" );
1431
1432 Irssi::theme_register(
1433     [
1434         'twirssi_tweet',  '[$0%B@$1%n$2] $3',
1435         'twirssi_search', '[$0%r$1%n:%B@$2%n$3] $4',
1436         'twirssi_reply',  '[$0\--> %B@$1%n$2] $3',
1437         'twirssi_dm',     '[$0%r@$1%n (%WDM%n)] $2',
1438         'twirssi_error',  'ERROR: $0',
1439     ]
1440 );
1441
1442 Irssi::settings_add_int( "twirssi", "twitter_poll_interval", 300 );
1443 Irssi::settings_add_str( "twirssi", "twitter_window",          "twitter" );
1444 Irssi::settings_add_str( "twirssi", "bitlbee_server",          "bitlbee" );
1445 Irssi::settings_add_str( "twirssi", "short_url_provider",      "TinyURL" );
1446 Irssi::settings_add_str( "twirssi", "short_url_args",          undef );
1447 Irssi::settings_add_str( "twirssi", "twitter_usernames",       undef );
1448 Irssi::settings_add_str( "twirssi", "twitter_passwords",       undef );
1449 Irssi::settings_add_str( "twirssi", "twirssi_default_service", "Twitter" );
1450 Irssi::settings_add_str( "twirssi", "twirssi_nick_color",      "%B" );
1451 Irssi::settings_add_str( "twirssi", "twirssi_topic_color",     "%r" );
1452 Irssi::settings_add_str( "twirssi", "twirssi_retweet_format",
1453     'RT $n: "$t" ${-- $c$}' );
1454 Irssi::settings_add_str( "twirssi", "twirssi_location",
1455     ".irssi/scripts/twirssi.pl" );
1456 Irssi::settings_add_str( "twirssi", "twirssi_replies_store",
1457     ".irssi/scripts/twirssi.json" );
1458 Irssi::settings_add_bool( "twirssi", "twirssi_upgrade_beta",      0 );
1459 Irssi::settings_add_bool( "twirssi", "tweet_to_away",             0 );
1460 Irssi::settings_add_bool( "twirssi", "show_reply_context",        0 );
1461 Irssi::settings_add_bool( "twirssi", "show_own_tweets",           1 );
1462 Irssi::settings_add_bool( "twirssi", "twirssi_debug",             0 );
1463 Irssi::settings_add_bool( "twirssi", "twirssi_first_run",         1 );
1464 Irssi::settings_add_bool( "twirssi", "twirssi_track_replies",     1 );
1465 Irssi::settings_add_bool( "twirssi", "twirssi_replies_autonick",  1 );
1466 Irssi::settings_add_bool( "twirssi", "twirssi_use_reply_aliases", 0 );
1467 Irssi::settings_add_bool( "twirssi", "twirssi_notify_timeouts",   1 );
1468 Irssi::settings_add_bool( "twirssi", "twirssi_hilights",          1 );
1469 Irssi::settings_add_bool( "twirssi", "twirssi_always_shorten",    0 );
1470 Irssi::settings_add_bool( "twirssi", "tweet_window_input",        0 );
1471
1472 $last_poll = time - &get_poll_time;
1473 $window = Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
1474 if ( !$window ) {
1475     Irssi::active_win()
1476       ->print( "Couldn't find a window named '"
1477           . Irssi::settings_get_str('twitter_window')
1478           . "', trying to create it." );
1479     $window =
1480       Irssi::Windowitem::window_create(
1481         Irssi::settings_get_str('twitter_window'), 1 );
1482     $window->set_name( Irssi::settings_get_str('twitter_window') );
1483 }
1484
1485 if ($window) {
1486     Irssi::command_bind( "dm",                         "cmd_direct" );
1487     Irssi::command_bind( "dm_as",                      "cmd_direct_as" );
1488     Irssi::command_bind( "tweet",                      "cmd_tweet" );
1489     Irssi::command_bind( "tweet_as",                   "cmd_tweet_as" );
1490     Irssi::command_bind( "retweet",                    "cmd_retweet" );
1491     Irssi::command_bind( "retweet_as",                 "cmd_retweet_as" );
1492     Irssi::command_bind( "twitter_reply",              "cmd_reply" );
1493     Irssi::command_bind( "twitter_reply_as",           "cmd_reply_as" );
1494     Irssi::command_bind( "twitter_login",              "cmd_login" );
1495     Irssi::command_bind( "twitter_logout",             "cmd_logout" );
1496     Irssi::command_bind( "twitter_switch",             "cmd_switch" );
1497     Irssi::command_bind( "twitter_subscribe",          "cmd_add_search" );
1498     Irssi::command_bind( "twitter_unsubscribe",        "cmd_del_search" );
1499     Irssi::command_bind( "twitter_list_subscriptions", "cmd_list_search" );
1500     Irssi::command_bind( "twirssi_upgrade",            "cmd_upgrade" );
1501     Irssi::command_bind( "twitter_updates",            "get_updates" );
1502     if ( Irssi::settings_get_bool("twirssi_use_reply_aliases") ) {
1503         Irssi::command_bind( "reply",    "cmd_reply" );
1504         Irssi::command_bind( "reply_as", "cmd_reply_as" );
1505     }
1506     Irssi::command_bind(
1507         "twirssi_dump",
1508         sub {
1509             print "twits: ", join ", ",
1510               map { "u: $_->{username}\@" . ref($_) } values %twits;
1511             print "selected: $user\@$defservice";
1512             print "friends: ", join ", ", sort keys %friends;
1513             print "nicks: ",   join ", ", sort keys %nicks;
1514             print "searches: ", Dumper \%{ $id_map{__searches} };
1515             print "last poll: $last_poll";
1516             if ( open DUMP, ">/tmp/twirssi.cache.txt" ) {
1517                 print DUMP Dumper \%tweet_cache;
1518                 close DUMP;
1519                 print "cache written out to /tmp/twirssi.cache.txt";
1520             }
1521         }
1522     );
1523     Irssi::command_bind(
1524         "twirssi_version",
1525         sub {
1526             &notice("Twirssi v$VERSION (r$REV); "
1527                   . "Net::Twitter v$Net::Twitter::VERSION. "
1528                   . "JSON in use: "
1529                   . JSON::Any::handler()
1530                   . ".  See details at http://twirssi.com/" );
1531         }
1532     );
1533     Irssi::command_bind(
1534         "twitter_friend",
1535         &gen_cmd(
1536             "/twitter_friend <username>",
1537             "create_friend",
1538             sub { &notice("Following $_[0]"); $nicks{ $_[0] } = time; }
1539         )
1540     );
1541     Irssi::command_bind(
1542         "twitter_unfriend",
1543         &gen_cmd(
1544             "/twitter_unfriend <username>",
1545             "destroy_friend",
1546             sub { &notice("Stopped following $_[0]"); delete $nicks{ $_[0] }; }
1547         )
1548     );
1549     Irssi::command_bind(
1550         "twitter_device_updates",
1551         &gen_cmd(
1552             "/twitter_device_updates none|im|sms",
1553             "update_delivery_device",
1554             sub { &notice("Device updated to $_[0]"); }
1555         )
1556     );
1557     Irssi::signal_add_last( 'complete word' => \&sig_complete );
1558
1559     &notice("  %Y<%C(%B^%C)%N                   TWIRSSI v%R$VERSION%N (r$REV)");
1560     &notice("   %C(_(\\%N           http://twirssi.com/ for full docs");
1561     &notice(
1562         "    %Y||%C `%N Log in with /twitter_login, send updates with /tweet");
1563
1564     my $file = Irssi::settings_get_str("twirssi_replies_store");
1565     if ( $file and -r $file ) {
1566         if ( open( JSON, $file ) ) {
1567             local $/;
1568             my $json = <JSON>;
1569             close JSON;
1570             eval {
1571                 my $ref = JSON::Any->jsonToObj($json);
1572                 %id_map = %$ref;
1573                 my $num = keys %{ $id_map{__indexes} };
1574                 &notice( sprintf "Loaded old replies from %d contact%s.",
1575                     $num, ( $num == 1 ? "" : "s" ) );
1576                 &cmd_list_search;
1577             };
1578         } else {
1579             &notice("Failed to load old replies from $file: $!");
1580         }
1581     }
1582
1583     if ( my $provider = Irssi::settings_get_str("short_url_provider") ) {
1584         &notice("Loading WWW::Shorten::$provider...");
1585         eval "use WWW::Shorten::$provider;";
1586
1587         if ($@) {
1588             &notice(
1589                 "Failed to load WWW::Shorten::$provider - either clear",
1590                 "short_url_provider or install the CPAN module"
1591             );
1592         }
1593     }
1594
1595     if (    my $autouser = Irssi::settings_get_str("twitter_usernames")
1596         and my $autopass = Irssi::settings_get_str("twitter_passwords") )
1597     {
1598         &cmd_login();
1599         &get_updates;
1600     }
1601
1602 } else {
1603     Irssi::active_win()
1604       ->print( "Create a window named "
1605           . Irssi::settings_get_str('twitter_window')
1606           . " or change the value of twitter_window.  Then, reload twirssi." );
1607 }
1608
1609 # vim: set sts=4 expandtab: