r614 - Fix searches, thanks to @Olatho finding a bug. Note that existing searches...
[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.2beta";
14 my ($REV) = '$Rev: 614 $' =~ /(\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-20 20:24:00 -0700 (Mon, 20 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\@$defservice"}{$data} ) {
556         &notice("Already had a subscription for '$data'");
557         return;
558     }
559
560     $id_map{__searches}{"$user\@$defservice"}{$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\@$defservice"}{$data} ) {
581         &notice("No subscription found for '$data'");
582         return;
583     }
584
585     delete $id_map{__searches}{"$user\@$defservice"}{$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( { count => 100 } );
814         } else {
815             $tweets = $obj->friends_timeline();
816         }
817     };
818
819     if ($@) {
820         print $fh "type:debug Error during friends_timeline call: Aborted.\n";
821         print $fh "type:debug : $_\n" foreach split /\n/, Dumper($@);
822         return undef;
823     }
824
825     unless ( ref $tweets ) {
826         if ( $obj->can("get_error") ) {
827             my $error = "Unknown error";
828             eval { $error = JSON::Any->jsonToObj( $obj->get_error() ) };
829             unless ($@) { $error = $obj->get_error() }
830             print $fh
831               "type:debug API Error during friends_timeline call: Aborted\n";
832             print $fh "type:debug : $_\n" foreach split /\n/, Dumper($error);
833
834         } else {
835             print $fh
836               "type:debug API Error during friends_timeline call. Aborted.\n";
837         }
838         return undef;
839     }
840
841     foreach my $t ( reverse @$tweets ) {
842         my $text = decode_entities( $t->{text} );
843         $text = &hilight($text);
844         my $reply = "tweet";
845         if (    Irssi::settings_get_bool("show_reply_context")
846             and $t->{in_reply_to_screen_name} ne $username
847             and $t->{in_reply_to_screen_name}
848             and not exists $friends{ $t->{in_reply_to_screen_name} } )
849         {
850             $nicks{ $t->{in_reply_to_screen_name} } = time;
851             my $context;
852             unless ( $cache->{ $t->{in_reply_to_status_id} } ) {
853                 eval {
854                     $cache->{ $t->{in_reply_to_status_id} } =
855                       $obj->show_status( $t->{in_reply_to_status_id} );
856                 };
857
858             }
859             $context = $cache->{ $t->{in_reply_to_status_id} };
860
861             if ($context) {
862                 my $ctext = decode_entities( $context->{text} );
863                 $ctext = &hilight($ctext);
864                 if ( $context->{truncated} and ref($obj) ne 'Net::Identica' ) {
865                     $ctext .=
866                         " -- http://twitter.com/$context->{user}{screen_name}"
867                       . "/status/$context->{id}";
868                 }
869                 printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
870                   $context->{id}, $username,
871                   $context->{user}{screen_name}, $ctext;
872                 $reply = "reply";
873             }
874         }
875         next
876           if $t->{user}{screen_name} eq $username
877               and not Irssi::settings_get_bool("show_own_tweets");
878         if ( $t->{truncated} and ref($obj) ne 'Net::Identica' ) {
879             $text .= " -- http://twitter.com/$t->{user}{screen_name}"
880               . "/status/$t->{id}";
881         }
882         printf $fh "id:%d account:%s nick:%s type:%s %s\n",
883           $t->{id}, $username, $t->{user}{screen_name}, $reply, $text;
884         $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
885     }
886     printf $fh "id:%d account:%s type:last_id timeline\n",
887       $new_poll_id, $username;
888
889     print scalar localtime, " - Polling for replies" if &debug;
890     $new_poll_id = 0;
891     eval {
892         if ( $id_map{__last_id}{$username}{reply} )
893         {
894             $tweets = $obj->replies(
895                 { since_id => $id_map{__last_id}{$username}{reply} } )
896               || [];
897         } else {
898             $tweets = $obj->replies() || [];
899         }
900     };
901
902     if ($@) {
903         print $fh "type:debug Error during replies call.  Aborted.\n";
904         return undef;
905     }
906
907     foreach my $t ( reverse @$tweets ) {
908         next
909           if exists $friends{ $t->{user}{screen_name} };
910
911         my $text = decode_entities( $t->{text} );
912         $text = &hilight($text);
913         if ( $t->{truncated} ) {
914             $text .= " -- http://twitter.com/$t->{user}{screen_name}"
915               . "/status/$t->{id}";
916         }
917         printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
918           $t->{id}, $username, $t->{user}{screen_name}, $text;
919         $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
920     }
921     printf $fh "id:%d account:%s type:last_id reply\n", $new_poll_id, $username;
922
923     print scalar localtime, " - Polling for DMs" if &debug;
924     $new_poll_id = 0;
925     eval {
926         if ( $id_map{__last_id}{$username}{dm} )
927         {
928             $tweets = $obj->direct_messages(
929                 { since_id => $id_map{__last_id}{$username}{dm} } )
930               || [];
931         } else {
932             $tweets = $obj->direct_messages() || [];
933         }
934     };
935
936     if ($@) {
937         print $fh "type:debug Error during direct_messages call.  Aborted.\n";
938         return undef;
939     }
940
941     foreach my $t ( reverse @$tweets ) {
942         my $text = decode_entities( $t->{text} );
943         $text = &hilight($text);
944         printf $fh "id:%d account:%s nick:%s type:dm %s\n",
945           $t->{id}, $username, $t->{sender_screen_name}, $text;
946         $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
947     }
948     printf $fh "id:%d account:%s type:last_id dm\n", $new_poll_id, $username;
949
950     print scalar localtime, " - Polling for subscriptions" if &debug;
951     if ( $obj->can('search') and $id_map{__searches}{$username} ) {
952         my $search;
953         foreach my $topic ( sort keys %{ $id_map{__searches}{$username} } ) {
954             print $fh "type:debug searching for $topic since ",
955               "$id_map{__searches}{$username}{$topic}\n";
956             eval {
957                 $search = $obj->search(
958                     {
959                         q        => $topic,
960                         since_id => $id_map{__searches}{$username}{$topic}
961                     }
962                 );
963             };
964
965             if ($@) {
966                 print $fh
967                   "type:debug Error during search($topic) call.  Aborted.\n";
968                 return undef;
969             }
970
971             unless ( $search->{max_id} ) {
972                 print $fh "type:debug Invalid search results when searching",
973                   " for $topic. Aborted.\n";
974                 return undef;
975             }
976
977             $id_map{__searches}{$username}{$topic} = $search->{max_id};
978             printf $fh "id:%d account:%s type:searchid topic:%s\n",
979               $search->{max_id}, $username, $topic;
980
981             foreach my $t ( reverse @{ $search->{results} } ) {
982                 my $text = decode_entities( $t->{text} );
983                 $text = &hilight($text);
984                 printf $fh "id:%d account:%s nick:%s type:search topic:%s %s\n",
985                   $t->{id}, $username, $t->{from_user}, $topic, $text;
986                 $new_poll_id = $t->{id}
987                   if not $new_poll_id
988                       or $t->{id} < $new_poll_id;
989             }
990         }
991     }
992
993     print scalar localtime, " - Done" if &debug;
994
995     return 1;
996 }
997
998 sub monitor_child {
999     my ($data)   = @_;
1000     my $filename = $data->[0];
1001     my $attempt  = $data->[1];
1002
1003     print scalar localtime, " - checking child log at $filename ($attempt)"
1004       if &debug;
1005     my ($new_last_poll);
1006
1007     # first time we run we don't want to print out *everything*, so we just
1008     # pretend
1009     my $suppress = 0;
1010     $suppress = 1 unless keys %tweet_cache;
1011
1012     if ( open FILE, $filename ) {
1013         my @lines;
1014         my %new_cache;
1015         while (<FILE>) {
1016             chomp;
1017             last if /^__friends__/;
1018             my $hilight = 0;
1019             my %meta;
1020
1021             foreach my $key (qw/id account nick type topic/) {
1022                 if (s/^$key:(\S+)\s*//) {
1023                     $meta{$key} = $1;
1024                 }
1025             }
1026
1027             if ( not $meta{type} or $meta{type} !~ /searchid|last_id/ ) {
1028                 if ( exists $meta{id} and exists $new_cache{ $meta{id} } ) {
1029                     next;
1030                 }
1031
1032                 $new_cache{ $meta{id} } = time;
1033
1034                 if ( exists $meta{id} and exists $tweet_cache{ $meta{id} } ) {
1035                     next;
1036                 }
1037             }
1038
1039             my $account = "";
1040             $meta{account} =~ s/\@(\w+)$//;
1041             $meta{service} = $1;
1042             if (
1043                 lc $meta{service} eq
1044                 lc Irssi::settings_get_str("twirssi_default_service") )
1045             {
1046                 $account = "$meta{account}: "
1047                   if lc "$meta{account}\@$meta{service}" ne lc
1048                       "$user\@$defservice";
1049             } else {
1050                 $account = "$meta{account}\@$meta{service}: ";
1051             }
1052
1053             my $marker = "";
1054             if (    $meta{type} ne 'dm'
1055                 and Irssi::settings_get_bool("twirssi_track_replies")
1056                 and $meta{nick}
1057                 and $meta{id} )
1058             {
1059                 $marker = ( $id_map{__indexes}{ $meta{nick} } + 1 ) % 100;
1060                 $id_map{ lc $meta{nick} }[$marker]           = $meta{id};
1061                 $id_map{__indexes}{ $meta{nick} }            = $marker;
1062                 $id_map{__tweets}{ lc $meta{nick} }[$marker] = $_;
1063                 $marker                                      = ":$marker";
1064             }
1065
1066             my $hilight_color =
1067               $irssi_to_mirc_colors{ Irssi::settings_get_str("hilight_color") };
1068             my $nick =
1069               '@' . substr( $meta{account}, 0, index( $meta{account}, "@" ) );
1070             if ( $_ =~ /\Q$nick\E(?:\W|$)/i
1071                 and Irssi::settings_get_bool("twirssi_hilights") )
1072             {
1073                 $meta{nick} = "\cC$hilight_color$meta{nick}\cO";
1074                 $hilight = MSGLEVEL_HILIGHT;
1075             }
1076
1077             if ( $meta{type} =~ /tweet|reply/ ) {
1078                 push @lines,
1079                   [
1080                     ( MSGLEVEL_PUBLIC | $hilight ),
1081                     $meta{type}, $account, $meta{nick}, $marker, $_
1082                   ];
1083             } elsif ( $meta{type} eq 'search' ) {
1084                 push @lines,
1085                   [
1086                     ( MSGLEVEL_PUBLIC | $hilight ),
1087                     $meta{type}, $account, $meta{topic},
1088                     $meta{nick}, $marker,  $_
1089                   ];
1090                 if (
1091                     exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
1092                     and $meta{id} >
1093                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
1094                 {
1095                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
1096                       $meta{id};
1097                 }
1098             } elsif ( $meta{type} eq 'dm' ) {
1099                 push @lines,
1100                   [
1101                     ( MSGLEVEL_MSGS | $hilight ),
1102                     $meta{type}, $account, $meta{nick}, $_
1103                   ];
1104             } elsif ( $meta{type} eq 'searchid' ) {
1105                 print "Search '$meta{topic}' returned id $meta{id}" if &debug;
1106                 if (
1107                     exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
1108                     and $meta{id} >=
1109                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
1110                 {
1111                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
1112                       $meta{id};
1113                 } elsif (&debug) {
1114                     print "Search '$meta{topic}' returned invalid id $meta{id}";
1115                 }
1116             } elsif ( $meta{type} eq 'last_id' ) {
1117                 $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} =
1118                   $meta{id}
1119                   if $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} <
1120                       $meta{id};
1121             } elsif ( $meta{type} eq 'error' ) {
1122                 push @lines, [ MSGLEVEL_MSGS, $_ ];
1123             } elsif ( $meta{type} eq 'debug' ) {
1124                 print "$_" if &debug,;
1125             } else {
1126                 print "Unknown line type $meta{type}: $_" if &debug,;
1127             }
1128         }
1129
1130         %friends = ();
1131         while (<FILE>) {
1132             if (/^-- (\d+)$/) {
1133                 ($new_last_poll) = ($1);
1134                 last;
1135             }
1136             my ( $f, $t ) = split ' ', $_;
1137             $nicks{$f} = $friends{$f} = $t;
1138         }
1139
1140         if ($new_last_poll) {
1141             print "new last_poll    = $new_last_poll" if &debug;
1142             print "new last_poll_id = ", Dumper( $id_map{__last_id} ) if &debug;
1143             if ($suppress) {
1144                 print "First call, not printing updates" if &debug;
1145             } else {
1146                 foreach my $line (@lines) {
1147                     $window->printformat(
1148                         $line->[0],
1149                         "twirssi_" . $line->[1],
1150                         @$line[ 2 .. $#$line ]
1151                     );
1152                 }
1153             }
1154
1155             close FILE;
1156             unlink $filename
1157               or warn "Failed to remove $filename: $!"
1158               unless &debug;
1159
1160             # commit the pending cache lines to the actual cache, now that
1161             # we've printed our output
1162             %tweet_cache = ( %tweet_cache, %new_cache );
1163
1164             # keep enough cached tweets, to make sure we don't show duplicates.
1165             foreach ( keys %tweet_cache ) {
1166                 next if $tweet_cache{$_} >= $last_poll - 3600;
1167                 delete $tweet_cache{$_};
1168             }
1169             $last_poll = $new_last_poll;
1170
1171             # save id_map hash
1172             if ( keys %id_map
1173                 and my $file =
1174                 Irssi::settings_get_str("twirssi_replies_store") )
1175             {
1176                 if ( open JSON, ">$file" ) {
1177                     print JSON JSON::Any->objToJson( \%id_map );
1178                     close JSON;
1179                 } else {
1180                     &ccrap("Failed to write replies to $file: $!");
1181                 }
1182             }
1183             $failwhale = 0;
1184             return;
1185         }
1186     }
1187
1188     close FILE;
1189
1190     if ( $attempt < 24 ) {
1191         Irssi::timeout_add_once( 5000, 'monitor_child',
1192             [ $filename, $attempt + 1 ] );
1193     } else {
1194         print "Giving up on polling $filename" if &debug;
1195         unlink $filename unless &debug;
1196
1197         return unless Irssi::settings_get_bool("twirssi_notify_timeouts");
1198
1199         my $since;
1200         my @time = localtime($last_poll);
1201         if ( time - $last_poll < 24 * 60 * 60 ) {
1202             $since = sprintf( "%d:%02d", @time[ 2, 1 ] );
1203         } else {
1204             $since = scalar localtime($last_poll);
1205         }
1206
1207         if ( not $failwhale and time - $last_poll > 60 * 60 ) {
1208             foreach my $whale (
1209                 q{     v  v        v},
1210                 q{     |  |  v     |  v},
1211                 q{     | .-, |     |  |},
1212                 q{  .--./ /  |  _.---.| },
1213                 q{   '-. (__..-"       \\},
1214                 q{      \\          a    |},
1215                 q{       ',.__.   ,__.-'/},
1216                 q{         '--/_.'----'`}
1217               )
1218             {
1219                 &ccrap($whale);
1220             }
1221             $failwhale = 1;
1222         }
1223         &ccrap("Haven't been able to get updated tweets since $since");
1224     }
1225 }
1226
1227 sub debug {
1228     return Irssi::settings_get_bool("twirssi_debug");
1229 }
1230
1231 sub notice {
1232     $window->print( "%R***%n @_", MSGLEVEL_PUBLIC );
1233 }
1234
1235 sub ccrap {
1236     $window->print( "%R***%n @_", MSGLEVEL_CLIENTCRAP );
1237 }
1238
1239 sub update_away {
1240     my $data = shift;
1241
1242     if (    Irssi::settings_get_bool("tweet_to_away")
1243         and $data !~ /\@\w/
1244         and $data !~ /^[dD] / )
1245     {
1246         my $server =
1247           Irssi::server_find_tag( Irssi::settings_get_str("bitlbee_server") );
1248         if ($server) {
1249             $server->send_raw("away :$data");
1250             return 1;
1251         } else {
1252             &ccrap( "Can't find bitlbee server.",
1253                 "Update bitlbee_server or disable tweet_to_away" );
1254             return 0;
1255         }
1256     }
1257
1258     return 0;
1259 }
1260
1261 sub too_long {
1262     my $data    = shift;
1263     my $noalert = shift;
1264
1265     if ( length $data > 140 ) {
1266         &notice( "Tweet too long (" . length($data) . " characters) - aborted" )
1267           unless $noalert;
1268         return 1;
1269     }
1270
1271     return 0;
1272 }
1273
1274 sub valid_username {
1275     my $username = shift;
1276
1277     $username = &normalize_username($username);
1278
1279     unless ( exists $twits{$username} ) {
1280         &notice("Unknown username $username");
1281         return undef;
1282     }
1283
1284     return $username;
1285 }
1286
1287 sub logged_in {
1288     my $obj = shift;
1289     unless ($obj) {
1290         &notice("Not logged in!  Use /twitter_login username pass!");
1291         return 0;
1292     }
1293
1294     return 1;
1295 }
1296
1297 sub sig_complete {
1298     my ( $complist, $window, $word, $linestart, $want_space ) = @_;
1299
1300     if (
1301         $linestart =~ /^\/(?:retweet|twitter_reply)(?:_as)?\s*$/
1302         or ( Irssi::settings_get_bool("twirssi_use_reply_aliases")
1303             and $linestart =~ /^\/reply(?:_as)?\s*$/ )
1304       )
1305     {    # /twitter_reply gets a nick:num
1306         $word =~ s/^@//;
1307         @$complist = map { "$_:$id_map{__indexes}{$_}" }
1308           sort { $nicks{$b} <=> $nicks{$a} }
1309           grep /^\Q$word/i,
1310           keys %{ $id_map{__indexes} };
1311     }
1312
1313     if ( $linestart =~ /^\/twitter_unfriend\s*$/ )
1314     {    # /twitter_unfriend gets a nick
1315         $word =~ s/^@//;
1316         push @$complist, grep /^\Q$word/i,
1317           sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1318     }
1319
1320     # /tweet, /tweet_as, /dm, /dm_as - complete @nicks (and nicks as the first
1321     # arg to dm)
1322     if ( $linestart =~ /^\/(?:tweet|dm)/ ) {
1323         my $prefix = $word =~ s/^@//;
1324         $prefix = 0 if $linestart eq '/dm' or $linestart eq '/dm_as';
1325         push @$complist, grep /^\Q$word/i,
1326           sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1327         @$complist = map { "\@$_" } @$complist if $prefix;
1328     }
1329 }
1330
1331 sub event_send_text {
1332     my ( $line, $server, $win ) = @_;
1333     my $awin = Irssi::active_win();
1334
1335     # if the window where we got our text was the twitter window, and the user
1336     # wants to be lazy, tweet away!
1337     if ( ( $awin->get_active_name() eq $window->{name} )
1338         and Irssi::settings_get_bool("tweet_window_input") )
1339     {
1340         &cmd_tweet( $line, $server, $win );
1341     }
1342 }
1343
1344 sub get_poll_time {
1345     my $poll = Irssi::settings_get_int("twitter_poll_interval");
1346     return $poll if $poll >= 60;
1347     return 60;
1348 }
1349
1350 sub hilight {
1351     my $text = shift;
1352
1353     if ( Irssi::settings_get_str("twirssi_nick_color") ) {
1354         my $c = Irssi::settings_get_str("twirssi_nick_color");
1355         $c = $irssi_to_mirc_colors{$c};
1356         $text =~ s/(^|\W)\@([-\w]+)/$1\cC$c\@$2\cO/g if $c;
1357     }
1358     if ( Irssi::settings_get_str("twirssi_topic_color") ) {
1359         my $c = Irssi::settings_get_str("twirssi_topic_color");
1360         $c = $irssi_to_mirc_colors{$c};
1361         $text =~ s/(^|\W)\#([-\w]+)/$1\cC$c\#$2\cO/g if $c;
1362     }
1363     $text =~ s/[\n\r]/ /g;
1364
1365     return $text;
1366 }
1367
1368 sub shorten {
1369     my $data = shift;
1370
1371     my $provider = Irssi::settings_get_str("short_url_provider");
1372     if (
1373         (
1374             Irssi::settings_get_bool("twirssi_always_shorten")
1375             or &too_long( $data, 1 )
1376         )
1377         and $provider
1378       )
1379     {
1380         my @args;
1381         if ( $provider eq 'Bitly' ) {
1382             @args[ 1, 2 ] = split ',',
1383               Irssi::settings_get_str("short_url_args"), 2;
1384             unless ( @args == 3 ) {
1385                 &ccrap(
1386                     "WWW::Shorten::Bitly requires a username and API key.",
1387                     "Set short_url_args to username,API_key or change your",
1388                     "short_url_provider."
1389                 );
1390                 return $data;
1391             }
1392         }
1393
1394         foreach my $url ( $data =~ /(https?:\/\/\S+[\w\/])/g ) {
1395             eval {
1396                 $args[0] = $url;
1397                 my $short = makeashorterlink(@args);
1398                 if ($short) {
1399                     $data =~ s/\Q$url/$short/g;
1400                 } else {
1401                     &notice("Failed to shorten $url!");
1402                 }
1403             };
1404         }
1405     }
1406
1407     return $data;
1408 }
1409
1410 sub normalize_username {
1411     my $user = shift;
1412
1413     my ( $username, $service ) = split /\@/, $user, 2;
1414     if ($service) {
1415         $service = ucfirst lc $service;
1416     } else {
1417         $service =
1418           ucfirst lc Irssi::settings_get_str("twirssi_default_service");
1419         unless ( exists $twits{"$username\@$service"} ) {
1420             $service = undef;
1421             foreach my $t ( sort keys %twits ) {
1422                 next unless $t =~ /^\Q$username\E\@(Twitter|Identica)/;
1423                 $service = $1;
1424                 last;
1425             }
1426
1427             unless ($service) {
1428                 &notice("Can't find a logged in user '$user'");
1429             }
1430         }
1431     }
1432
1433     return "$username\@$service";
1434 }
1435
1436 Irssi::signal_add( "send text", "event_send_text" );
1437
1438 Irssi::theme_register(
1439     [
1440         'twirssi_tweet',  '[$0%B@$1%n$2] $3',
1441         'twirssi_search', '[$0%r$1%n:%B@$2%n$3] $4',
1442         'twirssi_reply',  '[$0\--> %B@$1%n$2] $3',
1443         'twirssi_dm',     '[$0%r@$1%n (%WDM%n)] $2',
1444         'twirssi_error',  'ERROR: $0',
1445     ]
1446 );
1447
1448 Irssi::settings_add_int( "twirssi", "twitter_poll_interval", 300 );
1449 Irssi::settings_add_str( "twirssi", "twitter_window",          "twitter" );
1450 Irssi::settings_add_str( "twirssi", "bitlbee_server",          "bitlbee" );
1451 Irssi::settings_add_str( "twirssi", "short_url_provider",      "TinyURL" );
1452 Irssi::settings_add_str( "twirssi", "short_url_args",          undef );
1453 Irssi::settings_add_str( "twirssi", "twitter_usernames",       undef );
1454 Irssi::settings_add_str( "twirssi", "twitter_passwords",       undef );
1455 Irssi::settings_add_str( "twirssi", "twirssi_default_service", "Twitter" );
1456 Irssi::settings_add_str( "twirssi", "twirssi_nick_color",      "%B" );
1457 Irssi::settings_add_str( "twirssi", "twirssi_topic_color",     "%r" );
1458 Irssi::settings_add_str( "twirssi", "twirssi_retweet_format",
1459     'RT $n: "$t" ${-- $c$}' );
1460 Irssi::settings_add_str( "twirssi", "twirssi_location",
1461     ".irssi/scripts/twirssi.pl" );
1462 Irssi::settings_add_str( "twirssi", "twirssi_replies_store",
1463     ".irssi/scripts/twirssi.json" );
1464 Irssi::settings_add_bool( "twirssi", "twirssi_upgrade_beta",      0 );
1465 Irssi::settings_add_bool( "twirssi", "tweet_to_away",             0 );
1466 Irssi::settings_add_bool( "twirssi", "show_reply_context",        0 );
1467 Irssi::settings_add_bool( "twirssi", "show_own_tweets",           1 );
1468 Irssi::settings_add_bool( "twirssi", "twirssi_debug",             0 );
1469 Irssi::settings_add_bool( "twirssi", "twirssi_first_run",         1 );
1470 Irssi::settings_add_bool( "twirssi", "twirssi_track_replies",     1 );
1471 Irssi::settings_add_bool( "twirssi", "twirssi_replies_autonick",  1 );
1472 Irssi::settings_add_bool( "twirssi", "twirssi_use_reply_aliases", 0 );
1473 Irssi::settings_add_bool( "twirssi", "twirssi_notify_timeouts",   1 );
1474 Irssi::settings_add_bool( "twirssi", "twirssi_hilights",          1 );
1475 Irssi::settings_add_bool( "twirssi", "twirssi_always_shorten",    0 );
1476 Irssi::settings_add_bool( "twirssi", "tweet_window_input",        0 );
1477
1478 $last_poll = time - &get_poll_time;
1479 $window = Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
1480 if ( !$window ) {
1481     Irssi::active_win()
1482       ->print( "Couldn't find a window named '"
1483           . Irssi::settings_get_str('twitter_window')
1484           . "', trying to create it." );
1485     $window =
1486       Irssi::Windowitem::window_create(
1487         Irssi::settings_get_str('twitter_window'), 1 );
1488     $window->set_name( Irssi::settings_get_str('twitter_window') );
1489 }
1490
1491 if ($window) {
1492     Irssi::command_bind( "dm",                         "cmd_direct" );
1493     Irssi::command_bind( "dm_as",                      "cmd_direct_as" );
1494     Irssi::command_bind( "tweet",                      "cmd_tweet" );
1495     Irssi::command_bind( "tweet_as",                   "cmd_tweet_as" );
1496     Irssi::command_bind( "retweet",                    "cmd_retweet" );
1497     Irssi::command_bind( "retweet_as",                 "cmd_retweet_as" );
1498     Irssi::command_bind( "twitter_reply",              "cmd_reply" );
1499     Irssi::command_bind( "twitter_reply_as",           "cmd_reply_as" );
1500     Irssi::command_bind( "twitter_login",              "cmd_login" );
1501     Irssi::command_bind( "twitter_logout",             "cmd_logout" );
1502     Irssi::command_bind( "twitter_switch",             "cmd_switch" );
1503     Irssi::command_bind( "twitter_subscribe",          "cmd_add_search" );
1504     Irssi::command_bind( "twitter_unsubscribe",        "cmd_del_search" );
1505     Irssi::command_bind( "twitter_list_subscriptions", "cmd_list_search" );
1506     Irssi::command_bind( "twirssi_upgrade",            "cmd_upgrade" );
1507     Irssi::command_bind( "twitter_updates",            "get_updates" );
1508     if ( Irssi::settings_get_bool("twirssi_use_reply_aliases") ) {
1509         Irssi::command_bind( "reply",    "cmd_reply" );
1510         Irssi::command_bind( "reply_as", "cmd_reply_as" );
1511     }
1512     Irssi::command_bind(
1513         "twirssi_dump",
1514         sub {
1515             print "twits: ", join ", ",
1516               map { "u: $_->{username}\@" . ref($_) } values %twits;
1517             print "selected: $user\@$defservice";
1518             print "friends: ", join ", ", sort keys %friends;
1519             print "nicks: ",   join ", ", sort keys %nicks;
1520             print "searches: ", Dumper \%{ $id_map{__searches} };
1521             print "last poll: $last_poll";
1522             if ( open DUMP, ">/tmp/twirssi.cache.txt" ) {
1523                 print DUMP Dumper \%tweet_cache;
1524                 close DUMP;
1525                 print "cache written out to /tmp/twirssi.cache.txt";
1526             }
1527         }
1528     );
1529     Irssi::command_bind(
1530         "twirssi_version",
1531         sub {
1532             &notice("Twirssi v$VERSION (r$REV); "
1533                   . "Net::Twitter v$Net::Twitter::VERSION. "
1534                   . "JSON in use: "
1535                   . JSON::Any::handler()
1536                   . ".  See details at http://twirssi.com/" );
1537         }
1538     );
1539     Irssi::command_bind(
1540         "twitter_friend",
1541         &gen_cmd(
1542             "/twitter_friend <username>",
1543             "create_friend",
1544             sub { &notice("Following $_[0]"); $nicks{ $_[0] } = time; }
1545         )
1546     );
1547     Irssi::command_bind(
1548         "twitter_unfriend",
1549         &gen_cmd(
1550             "/twitter_unfriend <username>",
1551             "destroy_friend",
1552             sub { &notice("Stopped following $_[0]"); delete $nicks{ $_[0] }; }
1553         )
1554     );
1555     Irssi::command_bind(
1556         "twitter_device_updates",
1557         &gen_cmd(
1558             "/twitter_device_updates none|im|sms",
1559             "update_delivery_device",
1560             sub { &notice("Device updated to $_[0]"); }
1561         )
1562     );
1563     Irssi::signal_add_last( 'complete word' => \&sig_complete );
1564
1565     &notice("  %Y<%C(%B^%C)%N                   TWIRSSI v%R$VERSION%N (r$REV)");
1566     &notice("   %C(_(\\%N           http://twirssi.com/ for full docs");
1567     &notice(
1568         "    %Y||%C `%N Log in with /twitter_login, send updates with /tweet");
1569
1570     my $file = Irssi::settings_get_str("twirssi_replies_store");
1571     if ( $file and -r $file ) {
1572         if ( open( JSON, $file ) ) {
1573             local $/;
1574             my $json = <JSON>;
1575             close JSON;
1576             eval {
1577                 my $ref = JSON::Any->jsonToObj($json);
1578                 %id_map = %$ref;
1579                 my $num = keys %{ $id_map{__indexes} };
1580                 &notice( sprintf "Loaded old replies from %d contact%s.",
1581                     $num, ( $num == 1 ? "" : "s" ) );
1582                 &cmd_list_search;
1583             };
1584         } else {
1585             &notice("Failed to load old replies from $file: $!");
1586         }
1587     }
1588
1589     if ( my $provider = Irssi::settings_get_str("short_url_provider") ) {
1590         &notice("Loading WWW::Shorten::$provider...");
1591         eval "use WWW::Shorten::$provider;";
1592
1593         if ($@) {
1594             &notice(
1595                 "Failed to load WWW::Shorten::$provider - either clear",
1596                 "short_url_provider or install the CPAN module"
1597             );
1598         }
1599     }
1600
1601     if (    my $autouser = Irssi::settings_get_str("twitter_usernames")
1602         and my $autopass = Irssi::settings_get_str("twitter_passwords") )
1603     {
1604         &cmd_login();
1605         &get_updates;
1606     }
1607
1608 } else {
1609     Irssi::active_win()
1610       ->print( "Create a window named "
1611           . Irssi::settings_get_str('twitter_window')
1612           . " or change the value of twitter_window.  Then, reload twirssi." );
1613 }
1614
1615 # vim: set sts=4 expandtab: