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