eb878bf205db717e4a49b7abeec4bbb4c712e11e
[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.6beta";
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         $twit = undef;
517         if ( keys %twits ) {
518             &cmd_switch( ( keys %twits )[0], $server, $win );
519         }
520         return;
521     }
522
523     if ($twit) {
524         my $rate_limit = $twit->rate_limit_status();
525         if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
526             &notice(
527                 "Rate limit exceeded, try again after $rate_limit->{reset_time}"
528             );
529             $twit = undef;
530             return;
531         }
532
533         $twits{"$user\@$service"} = $twit;
534         Irssi::timeout_remove($poll) if $poll;
535         $poll = Irssi::timeout_add( &get_poll_time * 1000, \&get_updates, "" );
536         &notice("Logged in as $user\@$service, loading friends list...");
537         &load_friends();
538         &notice( "loaded friends: ", scalar keys %friends );
539         if ( Irssi::settings_get_bool("twirssi_first_run") ) {
540             Irssi::settings_set_bool( "twirssi_first_run", 0 );
541             unless ( exists $friends{twirssi} ) {
542                 &notice("Welcome to twirssi!"
543                       . "  Perhaps you should add \@twirssi to your friends list,"
544                       . " so you can be notified when a new version is release?"
545                       . "  Just type /twitter_follow twirssi." );
546             }
547         }
548         %nicks = %friends;
549         $nicks{$user} = 0;
550         return 1;
551     } else {
552         &notice("Login failed");
553     }
554 }
555
556 sub cmd_add_search {
557     my ( $data, $server, $win ) = @_;
558
559     unless ( $twit and $twit->can('search') ) {
560         &notice("ERROR: Your version of Net::Twitter ($Net::Twitter::VERSION) "
561               . "doesn't support searches." );
562         return;
563     }
564
565     $data =~ s/^\s+|\s+$//;
566     $data = lc $data;
567
568     unless ($data) {
569         &notice("Usage: /twitter_subscribe <topic>");
570         return;
571     }
572
573     if ( exists $id_map{__searches}{"$user\@$defservice"}{$data} ) {
574         &notice("Already had a subscription for '$data'");
575         return;
576     }
577
578     $id_map{__searches}{"$user\@$defservice"}{$data} = 1;
579     &notice("Added subscription for '$data'");
580 }
581
582 sub cmd_del_search {
583     my ( $data, $server, $win ) = @_;
584
585     unless ( $twit and $twit->can('search') ) {
586         &notice("ERROR: Your version of Net::Twitter ($Net::Twitter::VERSION) "
587               . "doesn't support searches." );
588         return;
589     }
590     $data =~ s/^\s+|\s+$//;
591     $data = lc $data;
592
593     unless ($data) {
594         &notice("Usage: /twitter_unsubscribe <topic>");
595         return;
596     }
597
598     unless ( exists $id_map{__searches}{"$user\@$defservice"}{$data} ) {
599         &notice("No subscription found for '$data'");
600         return;
601     }
602
603     delete $id_map{__searches}{"$user\@$defservice"}{$data};
604     &notice("Removed subscription for '$data'");
605 }
606
607 sub cmd_list_search {
608     my ( $data, $server, $win ) = @_;
609
610     my $found = 0;
611     foreach my $suser ( sort keys %{ $id_map{__searches} } ) {
612         my $topics;
613         foreach my $topic ( sort keys %{ $id_map{__searches}{$suser} } ) {
614             $topics = $topics ? "$topics, $topic" : $topic;
615         }
616         if ($topics) {
617             $found = 1;
618             &notice("Search subscriptions for \@$suser: $topics");
619         }
620     }
621
622     unless ($found) {
623         &notice("No search subscriptions set up");
624     }
625 }
626
627 sub cmd_upgrade {
628     my ( $data, $server, $win ) = @_;
629
630     my $loc = Irssi::settings_get_str("twirssi_location");
631     unless ( -w $loc ) {
632         &notice(
633 "$loc isn't writable, can't upgrade.  Perhaps you need to /set twirssi_location?"
634         );
635         return;
636     }
637
638     my $md5;
639     unless ( $data or Irssi::settings_get_bool("twirssi_upgrade_beta") ) {
640         eval { use Digest::MD5; };
641
642         if ($@) {
643             &notice(
644 "Failed to load Digest::MD5.  Try '/twirssi_upgrade nomd5' to skip MD5 verification"
645             );
646             return;
647         }
648
649         $md5 = get("http://twirssi.com/md5sum");
650         chomp $md5;
651         $md5 =~ s/ .*//;
652         unless ($md5) {
653             &notice("Failed to download md5sum from peeron!  Aborting.");
654             return;
655         }
656
657         unless ( open( CUR, $loc ) ) {
658             &notice(
659 "Failed to read $loc.  Check that /set twirssi_location is set to the correct location."
660             );
661             return;
662         }
663
664         my $cur_md5 = Digest::MD5::md5_hex(<CUR>);
665         close CUR;
666
667         if ( $cur_md5 eq $md5 ) {
668             &notice("Current twirssi seems to be up to date.");
669             return;
670         }
671     }
672
673     my $URL =
674       Irssi::settings_get_bool("twirssi_upgrade_beta")
675       ? "http://github.com/zigdon/twirssi/raw/master/twirssi.pl"
676       : "http://twirssi.com/twirssi.pl";
677     &notice("Downloading twirssi from $URL");
678     LWP::Simple::getstore( $URL, "$loc.upgrade" );
679
680     unless ( -s "$loc.upgrade" ) {
681         &notice("Failed to save $loc.upgrade."
682               . "  Check that /set twirssi_location is set to the correct location."
683         );
684         return;
685     }
686
687     unless ( $data or Irssi::settings_get_bool("twirssi_upgrade_beta") ) {
688         unless ( open( NEW, "$loc.upgrade" ) ) {
689             &notice("Failed to read $loc.upgrade."
690                   . "  Check that /set twirssi_location is set to the correct location."
691             );
692             return;
693         }
694
695         my $new_md5 = Digest::MD5::md5_hex(<NEW>);
696         close NEW;
697
698         if ( $new_md5 ne $md5 ) {
699             &notice("MD5 verification failed. expected $md5, got $new_md5");
700             return;
701         }
702     }
703
704     rename $loc, "$loc.backup"
705       or &notice("Failed to back up $loc: $!.  Aborting")
706       and return;
707     rename "$loc.upgrade", $loc
708       or &notice("Failed to rename $loc.upgrade: $!.  Aborting")
709       and return;
710
711     my ( $dir, $file ) = ( $loc =~ m{(.*)/([^/]+)$} );
712     if ( -e "$dir/autorun/$file" ) {
713         &notice("Updating $dir/autorun/$file");
714         unlink "$dir/autorun/$file"
715           or &notice("Failed to remove old $file from autorun: $!");
716         symlink "../$file", "$dir/autorun/$file"
717           or &notice("Failed to create symlink in autorun directory: $!");
718     }
719
720     &notice("Download complete.  Reload twirssi with /script load $file");
721 }
722
723 sub load_friends {
724     my $fh   = shift;
725     my $page = 1;
726     my %new_friends;
727     eval {
728         while (1)
729         {
730             print $fh "type:debug Loading friends page $page...\n"
731               if ( $fh and &debug );
732             my $friends = $twit->friends( { page => $page } );
733             last unless $friends;
734             $new_friends{ $_->{screen_name} } = time foreach @$friends;
735             $page++;
736             last if @$friends == 0 or $page == 10;
737         }
738     };
739
740     if ($@) {
741         print $fh "type:debug Error during friends list update.  Aborted.\n";
742         return;
743     }
744
745     my ( $added, $removed ) = ( 0, 0 );
746     print $fh "type:debug Scanning for new friends...\n" if ( $fh and &debug );
747     foreach ( keys %new_friends ) {
748         next if exists $friends{$_};
749         $friends{$_} = time;
750         $added++;
751     }
752
753     print $fh "type:debug Scanning for removed friends...\n"
754       if ( $fh and &debug );
755     foreach ( keys %friends ) {
756         next if exists $new_friends{$_};
757         delete $friends{$_};
758         $removed++;
759     }
760
761     return ( $added, $removed );
762 }
763
764 sub get_updates {
765     print scalar localtime, " - get_updates starting" if &debug;
766
767     $window =
768       Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
769     unless ($window) {
770         Irssi::active_win()
771           ->print( "Can't find a window named '"
772               . Irssi::settings_get_str('twitter_window')
773               . "'.  Create it or change the value of twitter_window" );
774     }
775
776     return unless &logged_in($twit);
777
778     my ( $fh, $filename ) = File::Temp::tempfile();
779     binmode( $fh, ":utf8" );
780     $child_pid = fork();
781
782     if ($child_pid) {    # parent
783         Irssi::timeout_add_once( 5000, 'monitor_child',
784             [ "$filename.done", 0 ] );
785         Irssi::pidwait_add($child_pid);
786     } elsif ( defined $child_pid ) {    # child
787         close STDIN;
788         close STDOUT;
789         close STDERR;
790
791         my $new_poll = time;
792
793         my $error = 0;
794         my %context_cache;
795         foreach ( keys %twits ) {
796             $error++ unless &do_updates( $fh, $_, $twits{$_}, \%context_cache );
797         }
798
799         print $fh "__friends__\n";
800         if (
801             time - $last_friends_poll >
802             Irssi::settings_get_int('twitter_friends_poll') )
803         {
804             print $fh "__updated ", time, "\n";
805             my ( $added, $removed ) = &load_friends($fh);
806             if ( $added + $removed ) {
807                 print $fh "type:debug %R***%n Friends list updated: ",
808                   join( ", ",
809                     sprintf( "%d added",   $added ),
810                     sprintf( "%d removed", $removed ) ),
811                   "\n";
812             }
813         }
814
815         foreach ( sort keys %friends ) {
816             print $fh "$_ $friends{$_}\n";
817         }
818
819         if ($error) {
820             print $fh "type:debug Update encountered errors.  Aborted\n";
821             print $fh "-- $last_poll";
822         } else {
823             print $fh "-- $new_poll";
824         }
825         close $fh;
826         rename $filename, "$filename.done";
827         exit;
828     } else {
829         &ccrap("Failed to fork for updating: $!");
830     }
831     print scalar localtime, " - get_updates ends" if &debug;
832 }
833
834 sub do_updates {
835     my ( $fh, $username, $obj, $cache ) = @_;
836
837     my $rate_limit = $obj->rate_limit_status();
838     if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
839         &notice("Rate limit exceeded for $username");
840         return undef;
841     }
842
843     print scalar localtime, " - Polling for updates for $username" if &debug;
844     my $tweets;
845     my $new_poll_id = 0;
846     eval {
847         if ( $id_map{__last_id}{$username}{timeline} )
848         {
849             $tweets = $obj->friends_timeline( { count => 100 } );
850         } else {
851             $tweets = $obj->friends_timeline();
852         }
853     };
854
855     if ($@) {
856         print $fh "type:debug Error during friends_timeline call: Aborted.\n";
857         print $fh "type:debug : $_\n" foreach split /\n/, Dumper($@);
858         return undef;
859     }
860
861     unless ( ref $tweets ) {
862         if ( $obj->can("get_error") ) {
863             my $error = "Unknown error";
864             eval { $error = JSON::Any->jsonToObj( $obj->get_error() ) };
865             unless ($@) { $error = $obj->get_error() }
866             print $fh
867               "type:debug API Error during friends_timeline call: Aborted\n";
868             print $fh "type:debug : $_\n" foreach split /\n/, Dumper($error);
869
870         } else {
871             print $fh
872               "type:debug API Error during friends_timeline call. Aborted.\n";
873         }
874         return undef;
875     }
876
877     foreach my $t ( reverse @$tweets ) {
878         my $text = decode_entities( $t->{text} );
879         $text =~ s/[\n\r]/ /g;
880         my $reply = "tweet";
881         if (    Irssi::settings_get_bool("show_reply_context")
882             and $t->{in_reply_to_screen_name} ne $username
883             and $t->{in_reply_to_screen_name}
884             and not exists $friends{ $t->{in_reply_to_screen_name} } )
885         {
886             $nicks{ $t->{in_reply_to_screen_name} } = time;
887             my $context;
888             unless ( $cache->{ $t->{in_reply_to_status_id} } ) {
889                 eval {
890                     $cache->{ $t->{in_reply_to_status_id} } =
891                       $obj->show_status( $t->{in_reply_to_status_id} );
892                 };
893
894             }
895             $context = $cache->{ $t->{in_reply_to_status_id} };
896
897             if ($context) {
898                 my $ctext = decode_entities( $context->{text} );
899                 $ctext =~ s/[\n\r]/ /g;
900                 if ( $context->{truncated} and ref($obj) ne 'Net::Identica' ) {
901                     $ctext .=
902                         " -- http://twitter.com/$context->{user}{screen_name}"
903                       . "/status/$context->{id}";
904                 }
905                 printf $fh "id:%u account:%s nick:%s type:tweet %s\n",
906                   $context->{id}, $username,
907                   $context->{user}{screen_name}, $ctext;
908                 $reply = "reply";
909             }
910         }
911         next
912           if $t->{user}{screen_name} eq $username
913               and not Irssi::settings_get_bool("show_own_tweets");
914         if ( $t->{truncated} and ref($obj) ne 'Net::Identica' ) {
915             $text .= " -- http://twitter.com/$t->{user}{screen_name}"
916               . "/status/$t->{id}";
917         }
918         printf $fh "id:%u account:%s nick:%s type:%s %s\n",
919           $t->{id}, $username, $t->{user}{screen_name}, $reply, $text;
920         $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
921     }
922     printf $fh "id:%u account:%s type:last_id timeline\n",
923       $new_poll_id, $username;
924
925     print scalar localtime, " - Polling for replies since ",
926       $id_map{__last_id}{$username}{reply}
927       if &debug;
928     $new_poll_id = 0;
929     eval {
930         if ( $id_map{__last_id}{$username}{reply} )
931         {
932             $tweets = $obj->replies(
933                 { since_id => $id_map{__last_id}{$username}{reply} } )
934               || [];
935         } else {
936             $tweets = $obj->replies() || [];
937         }
938     };
939
940     if ($@) {
941         print $fh "type:debug Error during replies call.  Aborted.\n";
942         return undef;
943     }
944
945     foreach my $t ( reverse @$tweets ) {
946         next
947           if exists $friends{ $t->{user}{screen_name} };
948
949         my $text = decode_entities( $t->{text} );
950         $text =~ s/[\n\r]/ /g;
951         if ( $t->{truncated} ) {
952             $text .= " -- http://twitter.com/$t->{user}{screen_name}"
953               . "/status/$t->{id}";
954         }
955         printf $fh "id:%u account:%s nick:%s type:tweet %s\n",
956           $t->{id}, $username, $t->{user}{screen_name}, $text;
957         $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
958     }
959     printf $fh "id:%u account:%s type:last_id reply\n", $new_poll_id, $username;
960
961     print scalar localtime, " - Polling for DMs" if &debug;
962     $new_poll_id = 0;
963     eval {
964         if ( $id_map{__last_id}{$username}{dm} )
965         {
966             $tweets = $obj->direct_messages(
967                 { since_id => $id_map{__last_id}{$username}{dm} } )
968               || [];
969         } else {
970             $tweets = $obj->direct_messages() || [];
971         }
972     };
973
974     if ($@) {
975         print $fh "type:debug Error during direct_messages call.  Aborted.\n";
976         return undef;
977     }
978
979     foreach my $t ( reverse @$tweets ) {
980         my $text = decode_entities( $t->{text} );
981         $text =~ s/[\n\r]/ /g;
982         printf $fh "id:%u account:%s nick:%s type:dm %s\n",
983           $t->{id}, $username, $t->{sender_screen_name}, $text;
984         $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
985     }
986     printf $fh "id:%u account:%s type:last_id dm\n", $new_poll_id, $username;
987
988     print scalar localtime, " - Polling for subscriptions" if &debug;
989     if ( $obj->can('search') and $id_map{__searches}{$username} ) {
990         my $search;
991         foreach my $topic ( sort keys %{ $id_map{__searches}{$username} } ) {
992             print $fh "type:debug searching for $topic since ",
993               "$id_map{__searches}{$username}{$topic}\n";
994             eval {
995                 $search = $obj->search(
996                     {
997                         q        => $topic,
998                         since_id => $id_map{__searches}{$username}{$topic}
999                     }
1000                 );
1001             };
1002
1003             if ($@) {
1004                 print $fh
1005                   "type:debug Error during search($topic) call.  Aborted.\n";
1006                 return undef;
1007             }
1008
1009             unless ( $search->{max_id} ) {
1010                 print $fh "type:debug Invalid search results when searching",
1011                   " for $topic. Aborted.\n";
1012                 return undef;
1013             }
1014
1015             $id_map{__searches}{$username}{$topic} = $search->{max_id};
1016             printf $fh "id:%u account:%s type:searchid topic:%s\n",
1017               $search->{max_id}, $username, $topic;
1018
1019             foreach my $t ( reverse @{ $search->{results} } ) {
1020                 my $text = decode_entities( $t->{text} );
1021                 $text =~ s/[\n\r]/ /g;
1022                 printf $fh "id:%u account:%s nick:%s type:search topic:%s %s\n",
1023                   $t->{id}, $username, $t->{from_user}, $topic, $text;
1024                 $new_poll_id = $t->{id}
1025                   if not $new_poll_id
1026                       or $t->{id} < $new_poll_id;
1027             }
1028         }
1029     }
1030
1031     print scalar localtime, " - Done" if &debug;
1032
1033     return 1;
1034 }
1035
1036 sub monitor_child {
1037     my ($data)   = @_;
1038     my $filename = $data->[0];
1039     my $attempt  = $data->[1];
1040
1041     print scalar localtime, " - checking child log at $filename ($attempt)"
1042       if &debug;
1043     my ($new_last_poll);
1044
1045     # first time we run we don't want to print out *everything*, so we just
1046     # pretend
1047
1048     if ( open FILE, $filename ) {
1049         binmode FILE, ":utf8";
1050         my @lines;
1051         my %new_cache;
1052         while (<FILE>) {
1053             last if /^__friends__/;
1054             unless (/\n$/) {    # skip partial lines
1055                                 # print "Skipping partial line: $_" if &debug;
1056                 next;
1057             }
1058             chomp;
1059             my $hilight = 0;
1060             my %meta;
1061
1062             foreach my $key (qw/id account nick type topic/) {
1063                 if (s/^$key:(\S+)\s*//) {
1064                     $meta{$key} = $1;
1065                 }
1066             }
1067
1068             if ( not $meta{type} or $meta{type} !~ /searchid|last_id/ ) {
1069                 if ( exists $meta{id} and exists $new_cache{ $meta{id} } ) {
1070                     next;
1071                 }
1072
1073                 $new_cache{ $meta{id} } = time;
1074
1075                 if ( exists $meta{id} and exists $tweet_cache{ $meta{id} } ) {
1076                     next;
1077                 }
1078             }
1079
1080             my $account = "";
1081             $meta{account} =~ s/\@(\w+)$//;
1082             $meta{service} = $1;
1083             if (
1084                 lc $meta{service} eq
1085                 lc Irssi::settings_get_str("twirssi_default_service") )
1086             {
1087                 $account = "$meta{account}: "
1088                   if lc "$meta{account}\@$meta{service}" ne lc
1089                       "$user\@$defservice";
1090             } else {
1091                 $account = "$meta{account}\@$meta{service}: ";
1092             }
1093
1094             my $marker = "";
1095             if (    $meta{type} ne 'dm'
1096                 and Irssi::settings_get_bool("twirssi_track_replies")
1097                 and $meta{nick}
1098                 and $meta{id} )
1099             {
1100                 $marker = ( $id_map{__indexes}{ $meta{nick} } + 1 ) % 100;
1101                 $id_map{ lc $meta{nick} }[$marker]           = $meta{id};
1102                 $id_map{__indexes}{ $meta{nick} }            = $marker;
1103                 $id_map{__tweets}{ lc $meta{nick} }[$marker] = $_;
1104                 $marker                                      = ":$marker";
1105             }
1106
1107             my $hilight_color =
1108               $irssi_to_mirc_colors{ Irssi::settings_get_str("hilight_color") };
1109             my $nick = "\@$meta{account}";
1110             if ( $_ =~ /\Q$nick\E(?:\W|$)/i
1111                 and Irssi::settings_get_bool("twirssi_hilights") )
1112             {
1113                 $meta{nick} = "\cC$hilight_color$meta{nick}\cO";
1114                 $hilight = MSGLEVEL_HILIGHT;
1115             }
1116
1117             if ( $meta{type} =~ /tweet|reply/ ) {
1118                 push @lines,
1119                   [
1120                     ( MSGLEVEL_PUBLIC | $hilight ),
1121                     $meta{type}, $account, $meta{nick}, $marker, $_
1122                   ];
1123             } elsif ( $meta{type} eq 'search' ) {
1124                 push @lines,
1125                   [
1126                     ( MSGLEVEL_PUBLIC | $hilight ),
1127                     $meta{type}, $account, $meta{topic},
1128                     $meta{nick}, $marker,  $_
1129                   ];
1130                 if (
1131                     exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
1132                     and $meta{id} >
1133                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
1134                 {
1135                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
1136                       $meta{id};
1137                 }
1138             } elsif ( $meta{type} eq 'dm' ) {
1139                 push @lines,
1140                   [
1141                     ( MSGLEVEL_MSGS | $hilight ),
1142                     $meta{type}, $account, $meta{nick}, $_
1143                   ];
1144             } elsif ( $meta{type} eq 'searchid' ) {
1145                 print "Search '$meta{topic}' returned id $meta{id}" if &debug;
1146                 if (
1147                     not
1148                     exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
1149                     or $meta{id} >=
1150                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
1151                 {
1152                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
1153                       $meta{id};
1154                 } elsif (&debug) {
1155                     print "Search '$meta{topic}' returned invalid id $meta{id}";
1156                 }
1157             } elsif ( $meta{type} eq 'last_id' ) {
1158                 $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} =
1159                   $meta{id}
1160                   if $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} <
1161                       $meta{id};
1162             } elsif ( $meta{type} eq 'error' ) {
1163                 push @lines, [ MSGLEVEL_MSGS, $_ ];
1164             } elsif ( $meta{type} eq 'debug' ) {
1165                 print "$_" if &debug,;
1166             } else {
1167                 print "Unknown line type $meta{type}: $_" if &debug,;
1168             }
1169         }
1170
1171         %friends = ();
1172         while (<FILE>) {
1173             if (/^__updated (\d+)$/) {
1174                 $last_friends_poll = $1;
1175                 print "Friend list updated" if &debug;
1176                 next;
1177             }
1178
1179             if (/^-- (\d+)$/) {
1180                 $new_last_poll = $1;
1181                 if ( $new_last_poll >= $last_poll ) {
1182                     last;
1183                 } else {
1184                     print "Impossible!  ",
1185                       "new_last_poll=$new_last_poll < last_poll=$last_poll!"
1186                       if &debug;
1187                     undef $new_last_poll;
1188                     next;
1189                 }
1190             }
1191             my ( $f, $t ) = split ' ', $_;
1192             $nicks{$f} = $friends{$f} = $t;
1193         }
1194
1195         if ($new_last_poll) {
1196             print "new last_poll    = $new_last_poll" if &debug;
1197             print "new last_poll_id = ", Dumper( $id_map{__last_id} ) if &debug;
1198             if ($first_call) {
1199                 print "First call, not printing updates" if &debug;
1200             } else {
1201                 foreach my $line (@lines) {
1202                     $window->printformat(
1203                         $line->[0],
1204                         "twirssi_" . $line->[1],
1205                         @$line[ 2 .. $#$line - 1 ],
1206                         &hilight( $line->[-1] )
1207                     );
1208                 }
1209             }
1210
1211             close FILE;
1212             unlink $filename
1213               or warn "Failed to remove $filename: $!"
1214               unless &debug;
1215
1216             # commit the pending cache lines to the actual cache, now that
1217             # we've printed our output
1218             %tweet_cache = ( %tweet_cache, %new_cache );
1219
1220             # keep enough cached tweets, to make sure we don't show duplicates.
1221             foreach ( keys %tweet_cache ) {
1222                 next if $tweet_cache{$_} >= $last_poll - 3600;
1223                 delete $tweet_cache{$_};
1224             }
1225             $last_poll = $new_last_poll;
1226             
1227             # make sure the pid is removed from the waitpid list
1228             Irssi::pidwait_remove($child_pid);
1229
1230             # save id_map hash
1231             if ( keys %id_map
1232                 and my $file =
1233                 Irssi::settings_get_str("twirssi_replies_store") )
1234             {
1235                 if ( open JSON, ">$file" ) {
1236                     print JSON JSON::Any->objToJson( \%id_map );
1237                     close JSON;
1238                 } else {
1239                     &ccrap("Failed to write replies to $file: $!");
1240                 }
1241             }
1242             $failwhale  = 0;
1243             $first_call = 0;
1244             return;
1245         }
1246     }
1247
1248     close FILE;
1249
1250     if ( $attempt < 24 ) {
1251         Irssi::timeout_add_once( 5000, 'monitor_child',
1252             [ $filename, $attempt + 1 ] );
1253     } else {
1254         print "Giving up on polling $filename" if &debug;
1255         unlink $filename unless &debug;
1256
1257         return unless Irssi::settings_get_bool("twirssi_notify_timeouts");
1258
1259         my $since;
1260         my @time = localtime($last_poll);
1261         if ( time - $last_poll < 24 * 60 * 60 ) {
1262             $since = sprintf( "%d:%02d", @time[ 2, 1 ] );
1263         } else {
1264             $since = scalar localtime($last_poll);
1265         }
1266
1267         if ( not $failwhale and time - $last_poll > 60 * 60 ) {
1268             foreach my $whale (
1269                 q{     v  v        v},
1270                 q{     |  |  v     |  v},
1271                 q{     | .-, |     |  |},
1272                 q{  .--./ /  |  _.---.| },
1273                 q{   '-. (__..-"       \\},
1274                 q{      \\          a    |},
1275                 q{       ',.__.   ,__.-'/},
1276                 q{         '--/_.'----'`}
1277               )
1278             {
1279                 &ccrap($whale);
1280             }
1281             $failwhale = 1;
1282         }
1283
1284         if ( time - $last_poll < 600 ) {
1285             &ccrap("Haven't been able to get updated tweets since $since");
1286         }
1287     }
1288 }
1289
1290 sub debug {
1291     return Irssi::settings_get_bool("twirssi_debug");
1292 }
1293
1294 sub notice {
1295     $window->print( "%R***%n @_", MSGLEVEL_PUBLIC );
1296 }
1297
1298 sub ccrap {
1299     $window->print( "%R***%n @_", MSGLEVEL_CLIENTCRAP );
1300 }
1301
1302 sub update_away {
1303     my $data = shift;
1304
1305     if (    Irssi::settings_get_bool("tweet_to_away")
1306         and $data !~ /\@\w/
1307         and $data !~ /^[dD] / )
1308     {
1309         my $server =
1310           Irssi::server_find_tag( Irssi::settings_get_str("bitlbee_server") );
1311         if ($server) {
1312             $server->send_raw("away :$data");
1313             return 1;
1314         } else {
1315             &ccrap( "Can't find bitlbee server.",
1316                 "Update bitlbee_server or disable tweet_to_away" );
1317             return 0;
1318         }
1319     }
1320
1321     return 0;
1322 }
1323
1324 sub too_long {
1325     my $data    = shift;
1326     my $noalert = shift;
1327
1328     if ( length $data > 140 ) {
1329         &notice( "Tweet too long (" . length($data) . " characters) - aborted" )
1330           unless $noalert;
1331         return 1;
1332     }
1333
1334     return 0;
1335 }
1336
1337 sub valid_username {
1338     my $username = shift;
1339
1340     $username = &normalize_username($username);
1341
1342     unless ( exists $twits{$username} ) {
1343         &notice("Unknown username $username");
1344         return undef;
1345     }
1346
1347     return $username;
1348 }
1349
1350 sub logged_in {
1351     my $obj = shift;
1352     unless ($obj) {
1353         &notice("Not logged in!  Use /twitter_login username pass!");
1354         return 0;
1355     }
1356
1357     return 1;
1358 }
1359
1360 sub sig_complete {
1361     my ( $complist, $window, $word, $linestart, $want_space ) = @_;
1362
1363     if (
1364         $linestart =~ /^\/(?:retweet|twitter_reply)(?:_as)?\s*$/
1365         or ( Irssi::settings_get_bool("twirssi_use_reply_aliases")
1366             and $linestart =~ /^\/reply(?:_as)?\s*$/ )
1367       )
1368     {    # /twitter_reply gets a nick:num
1369         $word =~ s/^@//;
1370         @$complist = map { "$_:$id_map{__indexes}{$_}" }
1371           sort { $nicks{$b} <=> $nicks{$a} }
1372           grep /^\Q$word/i,
1373           keys %{ $id_map{__indexes} };
1374     }
1375
1376     if ( $linestart =~ /^\/twitter_unfriend\s*$/ )
1377     {    # /twitter_unfriend gets a nick
1378         $word =~ s/^@//;
1379         push @$complist, grep /^\Q$word/i,
1380           sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1381     }
1382
1383     # /tweet, /tweet_as, /dm, /dm_as - complete @nicks (and nicks as the first
1384     # arg to dm)
1385     if ( $linestart =~ /^\/(?:tweet|dm)/ ) {
1386         my $prefix = $word =~ s/^@//;
1387         $prefix = 0 if $linestart eq '/dm' or $linestart eq '/dm_as';
1388         push @$complist, grep /^\Q$word/i,
1389           sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1390         @$complist = map { "\@$_" } @$complist if $prefix;
1391     }
1392 }
1393
1394 sub event_send_text {
1395     my ( $line, $server, $win ) = @_;
1396     my $awin = Irssi::active_win();
1397
1398     # if the window where we got our text was the twitter window, and the user
1399     # wants to be lazy, tweet away!
1400     if ( ( $awin->get_active_name() eq $window->{name} )
1401         and Irssi::settings_get_bool("tweet_window_input") )
1402     {
1403         &cmd_tweet( $line, $server, $win );
1404     }
1405 }
1406
1407 sub get_poll_time {
1408     my $poll = Irssi::settings_get_int("twitter_poll_interval");
1409     return $poll if $poll >= 60;
1410     return 60;
1411 }
1412
1413 sub hilight {
1414     my $text = shift;
1415
1416     if ( Irssi::settings_get_str("twirssi_nick_color") ) {
1417         my $c = Irssi::settings_get_str("twirssi_nick_color");
1418         $c = $irssi_to_mirc_colors{$c};
1419         $text =~ s/(^|\W)\@([-\w]+)/$1\cC$c\@$2\cO/g if $c;
1420     }
1421     if ( Irssi::settings_get_str("twirssi_topic_color") ) {
1422         my $c = Irssi::settings_get_str("twirssi_topic_color");
1423         $c = $irssi_to_mirc_colors{$c};
1424         $text =~ s/(^|\W)(\#|\!)([-\w]+)/$1\cC$c$2$3\cO/g if $c;
1425     }
1426     $text =~ s/[\n\r]/ /g;
1427
1428     return $text;
1429 }
1430
1431 sub shorten {
1432     my $data = shift;
1433
1434     my $provider = Irssi::settings_get_str("short_url_provider");
1435     if (
1436         (
1437             Irssi::settings_get_bool("twirssi_always_shorten")
1438             or &too_long( $data, 1 )
1439         )
1440         and $provider
1441       )
1442     {
1443         my @args;
1444         if ( $provider eq 'Bitly' ) {
1445             @args[ 1, 2 ] = split ',',
1446               Irssi::settings_get_str("short_url_args"), 2;
1447             unless ( @args == 3 ) {
1448                 &ccrap(
1449                     "WWW::Shorten::Bitly requires a username and API key.",
1450                     "Set short_url_args to username,API_key or change your",
1451                     "short_url_provider."
1452                 );
1453                 return $data;
1454             }
1455         }
1456
1457         foreach my $url ( $data =~ /(https?:\/\/\S+[\w\/])/g ) {
1458             eval {
1459                 $args[0] = $url;
1460                 my $short = makeashorterlink(@args);
1461                 if ($short) {
1462                     $data =~ s/\Q$url/$short/g;
1463                 } else {
1464                     &notice("Failed to shorten $url!");
1465                 }
1466             };
1467         }
1468     }
1469
1470     return decode "utf8", $data;
1471 }
1472
1473 sub normalize_username {
1474     my $user = shift;
1475
1476     my ( $username, $service ) = split /\@/, $user, 2;
1477     if ($service) {
1478         $service = ucfirst lc $service;
1479     } else {
1480         $service =
1481           ucfirst lc Irssi::settings_get_str("twirssi_default_service");
1482         unless ( exists $twits{"$username\@$service"} ) {
1483             $service = undef;
1484             foreach my $t ( sort keys %twits ) {
1485                 next unless $t =~ /^\Q$username\E\@(Twitter|Identica)/;
1486                 $service = $1;
1487                 last;
1488             }
1489
1490             unless ($service) {
1491                 &notice("Can't find a logged in user '$user'");
1492             }
1493         }
1494     }
1495
1496     return "$username\@$service";
1497 }
1498
1499 Irssi::signal_add( "send text", "event_send_text" );
1500
1501 Irssi::theme_register(
1502     [
1503         'twirssi_tweet',  '[$0%B@$1%n$2] $3',
1504         'twirssi_search', '[$0%r$1%n:%B@$2%n$3] $4',
1505         'twirssi_reply',  '[$0\--> %B@$1%n$2] $3',
1506         'twirssi_dm',     '[$0%r@$1%n (%WDM%n)] $2',
1507         'twirssi_error',  'ERROR: $0',
1508     ]
1509 );
1510
1511 Irssi::settings_add_int( "twirssi", "twitter_poll_interval", 300 );
1512 Irssi::settings_add_str( "twirssi", "twitter_window",          "twitter" );
1513 Irssi::settings_add_str( "twirssi", "bitlbee_server",          "bitlbee" );
1514 Irssi::settings_add_str( "twirssi", "short_url_provider",      "TinyURL" );
1515 Irssi::settings_add_str( "twirssi", "short_url_args",          undef );
1516 Irssi::settings_add_str( "twirssi", "twitter_usernames",       undef );
1517 Irssi::settings_add_str( "twirssi", "twitter_passwords",       undef );
1518 Irssi::settings_add_str( "twirssi", "twirssi_default_service", "Twitter" );
1519 Irssi::settings_add_str( "twirssi", "twirssi_nick_color",      "%B" );
1520 Irssi::settings_add_str( "twirssi", "twirssi_topic_color",     "%r" );
1521 Irssi::settings_add_str( "twirssi", "twirssi_retweet_format",
1522     'RT $n: "$t" ${-- $c$}' );
1523 Irssi::settings_add_str( "twirssi", "twirssi_location",
1524     ".irssi/scripts/twirssi.pl" );
1525 Irssi::settings_add_str( "twirssi", "twirssi_replies_store",
1526     ".irssi/scripts/twirssi.json" );
1527
1528 Irssi::settings_add_int( "twirssi", "twitter_friends_poll", 600 );
1529 Irssi::settings_add_int( "twirssi", "twitter_timeout",      30 );
1530
1531 Irssi::settings_add_bool( "twirssi", "twirssi_upgrade_beta",      0 );
1532 Irssi::settings_add_bool( "twirssi", "tweet_to_away",             0 );
1533 Irssi::settings_add_bool( "twirssi", "show_reply_context",        0 );
1534 Irssi::settings_add_bool( "twirssi", "show_own_tweets",           1 );
1535 Irssi::settings_add_bool( "twirssi", "twirssi_debug",             0 );
1536 Irssi::settings_add_bool( "twirssi", "twirssi_first_run",         1 );
1537 Irssi::settings_add_bool( "twirssi", "twirssi_track_replies",     1 );
1538 Irssi::settings_add_bool( "twirssi", "twirssi_replies_autonick",  1 );
1539 Irssi::settings_add_bool( "twirssi", "twirssi_use_reply_aliases", 0 );
1540 Irssi::settings_add_bool( "twirssi", "twirssi_notify_timeouts",   1 );
1541 Irssi::settings_add_bool( "twirssi", "twirssi_hilights",          1 );
1542 Irssi::settings_add_bool( "twirssi", "twirssi_always_shorten",    0 );
1543 Irssi::settings_add_bool( "twirssi", "tweet_window_input",        0 );
1544 Irssi::settings_add_bool( "twirssi", "twirssi_avoid_ssl",         0 );
1545
1546 $last_poll = time - &get_poll_time;
1547 $window = Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
1548 if ( !$window ) {
1549     Irssi::active_win()
1550       ->print( "Couldn't find a window named '"
1551           . Irssi::settings_get_str('twitter_window')
1552           . "', trying to create it." );
1553     $window =
1554       Irssi::Windowitem::window_create(
1555         Irssi::settings_get_str('twitter_window'), 1 );
1556     $window->set_name( Irssi::settings_get_str('twitter_window') );
1557 }
1558
1559 if ($window) {
1560     Irssi::command_bind( "dm",                         "cmd_direct" );
1561     Irssi::command_bind( "dm_as",                      "cmd_direct_as" );
1562     Irssi::command_bind( "tweet",                      "cmd_tweet" );
1563     Irssi::command_bind( "tweet_as",                   "cmd_tweet_as" );
1564     Irssi::command_bind( "retweet",                    "cmd_retweet" );
1565     Irssi::command_bind( "retweet_as",                 "cmd_retweet_as" );
1566     Irssi::command_bind( "twitter_reply",              "cmd_reply" );
1567     Irssi::command_bind( "twitter_reply_as",           "cmd_reply_as" );
1568     Irssi::command_bind( "twitter_login",              "cmd_login" );
1569     Irssi::command_bind( "twitter_logout",             "cmd_logout" );
1570     Irssi::command_bind( "twitter_switch",             "cmd_switch" );
1571     Irssi::command_bind( "twitter_subscribe",          "cmd_add_search" );
1572     Irssi::command_bind( "twitter_unsubscribe",        "cmd_del_search" );
1573     Irssi::command_bind( "twitter_list_subscriptions", "cmd_list_search" );
1574     Irssi::command_bind( "twirssi_upgrade",            "cmd_upgrade" );
1575     Irssi::command_bind( "twitter_updates",            "get_updates" );
1576     Irssi::command_bind( "bitlbee_away",               "update_away" );
1577     if ( Irssi::settings_get_bool("twirssi_use_reply_aliases") ) {
1578         Irssi::command_bind( "reply",    "cmd_reply" );
1579         Irssi::command_bind( "reply_as", "cmd_reply_as" );
1580     }
1581     Irssi::command_bind(
1582         "twirssi_dump",
1583         sub {
1584             print "twits: ", join ", ",
1585               map { "u: $_->{username}\@" . ref($_) } values %twits;
1586             print "selected: $user\@$defservice";
1587             print "friends: ", join ", ", sort keys %friends;
1588             print "nicks: ",   join ", ", sort keys %nicks;
1589             print "searches: ", Dumper \%{ $id_map{__searches} };
1590             print "last poll: $last_poll";
1591             if ( open DUMP, ">/tmp/twirssi.cache.txt" ) {
1592                 print DUMP Dumper \%tweet_cache;
1593                 close DUMP;
1594                 print "cache written out to /tmp/twirssi.cache.txt";
1595             }
1596         }
1597     );
1598     Irssi::command_bind(
1599         "twirssi_version",
1600         sub {
1601             &notice(
1602                 "Twirssi v$VERSION (r$REV); "
1603                   . (
1604                     $Net::Twitter::VERSION
1605                     ? "Net::Twitter v$Net::Twitter::VERSION. "
1606                     : ""
1607                   )
1608                   . (
1609                     $Net::Identica::VERSION
1610                     ? "Net::Identica v$Net::Identica::VERSION. "
1611                     : ""
1612                   )
1613                   . "JSON in use: "
1614                   . JSON::Any::handler()
1615                   . ".  See details at http://twirssi.com/"
1616             );
1617         }
1618     );
1619     Irssi::command_bind(
1620         "twitter_follow",
1621         &gen_cmd(
1622             "/twitter_follow <username>",
1623             "create_friend",
1624             sub { &notice("Following $_[0]"); $nicks{ $_[0] } = time; }
1625         )
1626     );
1627     Irssi::command_bind(
1628         "twitter_unfollow",
1629         &gen_cmd(
1630             "/twitter_unfriend <username>",
1631             "destroy_friend",
1632             sub { &notice("Stopped following $_[0]"); delete $nicks{ $_[0] }; }
1633         )
1634     );
1635     Irssi::command_bind(
1636         "twitter_device_updates",
1637         &gen_cmd(
1638             "/twitter_device_updates none|im|sms",
1639             "update_delivery_device",
1640             sub { &notice("Device updated to $_[0]"); }
1641         )
1642     );
1643     Irssi::command_bind(
1644         "twitter_block",
1645         &gen_cmd(
1646             "/twitter_block <username>",
1647             "create_block",
1648             sub { &notice("Blocked $_[0]"); }
1649         )
1650     );
1651     Irssi::command_bind(
1652         "twitter_unblock",
1653         &gen_cmd(
1654             "/twitter_unblock <username>",
1655             "destroy_block",
1656             sub { &notice("Unblock $_[0]"); }
1657         )
1658     );
1659     Irssi::signal_add_last( 'complete word' => \&sig_complete );
1660
1661     &notice("  %Y<%C(%B^%C)%N                   TWIRSSI v%R$VERSION%N (r$REV)");
1662     &notice("   %C(_(\\%N           http://twirssi.com/ for full docs");
1663     &notice(
1664         "    %Y||%C `%N Log in with /twitter_login, send updates with /tweet");
1665
1666     my $file = Irssi::settings_get_str("twirssi_replies_store");
1667     if ( $file and -r $file ) {
1668         if ( open( JSON, $file ) ) {
1669             local $/;
1670             my $json = <JSON>;
1671             close JSON;
1672             eval {
1673                 my $ref = JSON::Any->jsonToObj($json);
1674                 %id_map = %$ref;
1675                 my $num = keys %{ $id_map{__indexes} };
1676                 &notice( sprintf "Loaded old replies from %d contact%s.",
1677                     $num, ( $num == 1 ? "" : "s" ) );
1678                 &cmd_list_search;
1679             };
1680         } else {
1681             &notice("Failed to load old replies from $file: $!");
1682         }
1683     }
1684
1685     if ( my $provider = Irssi::settings_get_str("short_url_provider") ) {
1686         &notice("Loading WWW::Shorten::$provider...");
1687         eval "use WWW::Shorten::$provider;";
1688
1689         if ($@) {
1690             &notice(
1691                 "Failed to load WWW::Shorten::$provider - either clear",
1692                 "short_url_provider or install the CPAN module"
1693             );
1694         }
1695     }
1696
1697     if (    my $autouser = Irssi::settings_get_str("twitter_usernames")
1698         and my $autopass = Irssi::settings_get_str("twitter_passwords") )
1699     {
1700         &cmd_login();
1701         &get_updates;
1702     }
1703
1704 } else {
1705     Irssi::active_win()
1706       ->print( "Create a window named "
1707           . Irssi::settings_get_str('twitter_window')
1708           . " or change the value of twitter_window.  Then, reload twirssi." );
1709 }
1710
1711 # vim: set sts=4 expandtab: