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