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