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