forked from oysttyer/oysttyer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
oysttyer.pl
executable file
·8652 lines (7930 loc) · 255 KB
/
oysttyer.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/perl -s
# TODO: Eventually we should use Getopt::Long and go back to #!/usr/bin/env perl
#########################################################################
#
# oysttyer v2.9 (c)2016- oysttyer organisation
# (c)2007-2012 cameron kaiser (and contributors).
# all rights reserved.
#
# https://oysttyer.github.io/
#
# distributed under the floodgap free software license
# http://www.floodgap.com/software/ffsl/
#
# After all, we're flesh and blood. -- Oingo Boingo
# If someone writes an app and no one uses it, does his code run? -- me
#
#########################################################################
require 5.005;
BEGIN {
# ONLY STUFF THAT MUST RUN BEFORE INITIALIZATION GOES HERE!
# THIS FUNCTION HAS GOTTEN TOO DAMN CLUTTERED!
# @INC = (); # wreck intentionally for testing
# dynamically changing PERL_SIGNALS doesn't work in Perl 5.14+ (bug
# 92246). we deal with this by forcing -signals_use_posix if the
# environment variable wasn't already set.
if ($] >= 5.014000 && $ENV{'PERL_SIGNALS'} ne 'unsafe') {
$signals_use_posix = 1;
} else {
$ENV{'PERL_SIGNALS'} = 'unsafe';
}
$command_line = $0; $0 = "oysttyer";
$oysttyer_VERSION = "2.9";
$oysttyer_PATCH_VERSION = 1;
$oysttyer_RC_NUMBER = 0; # non-zero for release candidate
# this is kludgy, yes.
$LANG = $ENV{'LANG'} || $ENV{'GDM_LANG'} || $ENV{'LC_CTYPE'} ||
$ENV{'ALL'};
$my_version_string = "${oysttyer_VERSION}.${oysttyer_PATCH_VERSION}";
(warn ("$my_version_string\n"), exit) if ($version);
$packet_length = 2048;
$space_pad = " " x $packet_length;
$background_is_ready = 0;
# for multi-module extension handling
$multi_module_mode = 0;
$multi_module_context = 0;
$muffle_server_messages = 0;
undef $master_store;
undef %push_stack;
$padded_patch_version = substr($oysttyer_PATCH_VERSION . " ", 0, 2);
%opts_boolean = map { $_ => 1 } qw(
ansi noansi verbose superverbose oysttyeristas noprompt
seven silent hold daemon script anonymous readline ssl
newline vcheck verify noratelimit notrack nonewrts notimeline
synch exception_is_maskable mentions simplestart
location readlinerepaint nocounter notifyquiet
signals_use_posix dostream nostreamreplies streamallreplies
nofilter showusername largeimages origimages doublespace extended
); %opts_sync = map { $_ => 1 } qw(
ansi pause dmpause oysttyeristas verbose superverbose
url rlurl dmurl newline wrap notimeline lists dmidurl
queryurl track colourprompt colourme notrack
colourdm colourreply colourwarn coloursearch colourlist idurl
notifies filter colourdefault backload searchhits dmsenturl
nostreamreplies mentions wtrendurl atrendurl filterusers
filterats filterrts filteratonly filterflags nofilter
); %opts_urls = map {$_ => 1} qw(
url dmurl uurl rurl wurl frurl rlurl update shorturl
apibase queryurl idurl delurl dmdelurl favsurl
favurl favdelurl followurl leaveurl
muteurl unmuteurl
dmupdate credurl blockurl blockdelurl friendsurl
modifyliurl adduliurl delliurl getliurl getlisurl getfliurl
creliurl delliurl deluliurl crefliurl delfliurl
getuliurl getufliurl dmsenturl rturl rtsbyurl dmidurl
statusliurl followliurl leaveliurl followersurl
oauthurl oauthauthurl oauthaccurl oauthbase wtrendurl
atrendurl frupdurl lookupidurl rtsofmeurl
); %opts_secret = map { $_ => 1} qw(
superverbose oysttyeristas
); %opts_comma_delimit = map { $_ => 1 } qw(
lists notifytype notifies filterflags filterrts filterats
filterusers filteratonly
); %opts_space_delimit = map { $_ => 1 } qw(
track
);
%opts_can_set = map { $_ => 1 } qw(
url pause dmurl dmpause superverbose ansi verbose
update uurl rurl wurl avatar oysttyeristas frurl track
rlurl noprompt shorturl newline wrap verify autosplit
notimeline queryurl colourprompt colourme
colourdm colourreply colourwarn coloursearch colourlist idurl
urlopen delurl notrack dmdelurl favsurl
favurl favdelurl slowpost notifies filter colourdefault
followurl leaveurl dmupdate mentions backload
lat long location searchhits blockurl blockdelurl woeid
nocounter linelength quotelinelength friendsurl followersurl lists
modifyliurl adduliurl delliurl getliurl getlisurl getfliurl
creliurl delliurl deluliurl crefliurl delfliurl atrendurl
getuliurl getufliurl dmsenturl rturl rtsbyurl wtrendurl
statusliurl followliurl leaveliurl dmidurl nostreamreplies
frupdurl filterusers filterats filterrts filterflags
filteratonly nofilter rtsofmeurl largeimages origimages extended
video_bitrate
); %opts_others = map { $_ => 1 } qw(
lynx curl seven silent maxhist noansi hold status
daemon timestamp twarg user anonymous script readline
leader ssl rc norc vcheck apibase notifytype exts
nonewrts synch runcommand authtype oauthkey oauthsecret
tokenkey tokensecret credurl keyf lockf readlinerepaint
simplestart exception_is_maskable oldperl notco
notify_tool_path oauthurl oauthauthurl oauthaccurl oauthbase
signals_use_posix dostream eventbuf replacement_newline
replacement_carriagereturn streamallreplies showusername
doublespace
); %valid = (%opts_can_set, %opts_others);
$rc = (defined($rc) && length($rc)) ? $rc : "";
unless ($norc) {
my $rcf =
($rc =~ m#^/#) ? $rc : "$ENV{'HOME'}/.oysttyerrc${rc}";
if (open(W, $rcf)) {
while(<W>) {
chomp;
next if (/^\s*$/ || /^#/);
s/^-//;
($key, $value) = split(/\=/, $_, 2);
if ($key eq 'rc') {
warn "** that's stupid, setting rc in an rc file\n";
} elsif ($key eq 'norc') {
warn "** that's dumb, using norc in an rc file\n";
} elsif (length $$key) {
; # carry on
} elsif ($valid{$key} && !length($$key)) {
$$key = $value;
} elsif ($key =~ /^extpref_/) {
$$key = $value;
} elsif (!$valid{$key}) {
warn "** setting $key not supported in this version\n";
}
}
close(W);
} elsif (length($rc)) {
die("couldn't access rc file $rcf: $!\n".
"to use defaults, use -norc or don't specify the -rc option.\n\n");
}
}
warn "** -twarg is deprecated\n" if (length($twarg));
$seven ||= 0;
$oldperl ||= 0;
$parent = $$;
$script = 1 if (length($runcommand));
$supreturnto = $verbose + 0;
$postbreak_time = 0;
$postbreak_count = 0;
# Want to keep original behaviour as well though
$newline ||= 0;
$replacement_newline ||= $seven ? ' [NL] ' : " \x{2424} ";
$replacement_carriagereturn ||= $seven ? ' [CR] ' : " \x{240D} ";
# our minimum official support is now 5.8.6.
if ($] < 5.008006 && !$oldperl) {
die(<<"EOF");
*** you are using a version of Perl in "extended" support: $] ***
the minimum tested version of Perl now required by oysttyer is 5.8.6.
Perl 5.005 thru 5.8.5 probably can still run oysttyer, but they are not
tested with it. if you want to suppress this warning, specify -oldperl on
the command line, or put oldperl=1 in your .oysttyerrc. bug patches will
still be accepted for older Perls; see the oysttyer home page for info.
for Perl 5.005, remember to also specify -seven.
EOF
}
# defaults that our extensions can override
$last_id = 0;
$last_dm = 0;
# a correct fix for -daemon would make this unlimited, but this
# is good enough for now.
$print_max ||= ($daemon) ? 999999 : 250; # shiver
$suspend_output = -1;
# try to find an OAuth keyfile if we haven't specified key+secret
# no worries if this fails; we could be Basic Auth, after all
$whine = (length($keyf)) ? 1 : 0;
$keyf ||= "$ENV{'HOME'}/.oysttyerkey";
$keyf = "$ENV{'HOME'}/.oysttyerkey${keyf}" if ($keyf !~ m#/#);
$attempted_keyf = $keyf;
if (!$oauthwizard && (
#!length($oauthkey) ||
#!length($oauthsecret) ||
!length($tokenkey) ||
!length($tokensecret) )
) {
my $keybuf = '';
if(open(W, $keyf)) {
while(<W>) {
chomp;
s/\s+//g;
$keybuf .= $_;
}
close(W);
my (@pairs) = split(/\&/, $keybuf);
foreach(@pairs) {
my (@pair) = split(/\=/, $_, 2);
$oauthkey = $pair[1]
if ($pair[0] eq 'ck') && !length($oauthkey);# && $pair[1] ne 'X');
$oauthsecret = $pair[1]
if ($pair[0] eq 'cs') && !length($oauthsecret);# && $pair[1] ne 'X');
$tokenkey = $pair[1]
if ($pair[0] eq 'at');
$tokensecret = $pair[1]
if ($pair[0] eq 'ats');
}
die("** tried to load OAuth tokens from $keyf\n".
" but it seems corrupt or incomplete. please see the documentation,\n".
" or delete the file so that we can try making your keyfile again.\n")
if ((!length($oauthkey) ||
!length($oauthsecret) ||
!length($tokenkey) ||
!length($tokensecret)));
} else {
die("** couldn't open keyfile $keyf: $!\n".
"if you want to run the OAuth wizard to create this file, add ".
"-oauthwizard\n")
if ($whine);
$keyf = ''; # i.e., we loaded nothing from a key file
}
}
# try to init Term::ReadLine if it was requested
# (shakes fist at @br3nda, it's all her fault)
%readline_completion = ();
if ($readline && !$silent && !$script) {
$ENV{"PERL_RL"} = "TTYtter" if (!length($ENV{'PERL_RL'}));
eval
'use Term::ReadLine; $termrl = new Term::ReadLine ("TTYtter", \*STDIN, \*STDOUT)'
|| die(
"$@\nthis perl doesn't have ReadLine. don't use -readline.\n");
$stdout = $termrl->OUT || \*STDOUT;
$stdin = $termrl->IN || \*STDIN;
$readline = '' if ($readline eq '1');
$readline =~ s/^"//; # for optimizer
$readline =~ s/"$//;
#$termrl->Attribs()->{'autohistory'} = undef; # not yet
(%readline_completion) = map {$_ => 1} split(/\s+/, $readline);
%original_readline = %readline_completion;
# readline repaint can't be tested here. we cache our
# result later.
} else {
$stdout = \*STDOUT;
$stdin = \*STDIN;
}
$wrapseq = 0;
$lastlinelength = -1;
print $stdout "$leader\n" if (length($leader));
# state information
$lasttwit = '';
$lastpostid = 0;
# stub namespace for multimodules and (eventually) state saving
undef %store;
$store = \%store;
$pack_magic = ($] < 5.006) ? '' : "U0";
$utf8_encode = sub { ; };
$utf8_decode = sub { ; };
unless ($seven) {
eval
'use utf8;binmode($stdin,":utf8");binmode($stdout,":utf8");return 1' ||
die("$@\nthis perl doesn't fully support UTF-8. use -seven.\n");
# this is for the prinput utf8 validator.
# adapted from http://mail.nl.linux.org/linux-utf8/2003-03/msg00087.html
# eventually this will be removed when 5.6.x support is removed,
# and Perl will do the UTF-8 validation for us.
$badutf8='[\x00-\x7f][\x80-\xbf]+|^[\x80-\xbf]+|'.
'[\xc0-\xdf][\x00-\x7f\xc0-\xff]|'.
'[\xc0-\xdf][\x80-\xbf]{2}|'.
'[\xe0-\xef][\x80-\xbf]{0,1}[\x00-\x7f\xc0-\xff]|'.
'[\xe0-\xef][\x80-\xbf]{3}|'.
'[\xf0-\xf7][\x80-\xbf]{0,2}[\x00-\x7f\xc0-\xff]|'.
'[\xf0-\xf7][\x80-\xbf]{4}|'.
'[\xf8-\xfb][\x80-\xbf]{0,3}[\x00-\x7f\xc0-\xff]|'.
'[\xf8-\xfb][\x80-\xbf]{5}|'.
'[\xfc-\xfd][\x80-\xbf]{0,4}[\x00-\x7f\xc0-\xff]|'.
'\xed[\xa0-\xbf][\x80-\xbf]|'.
'\xef\xbf[\xbe-\xbf]|'.
'[\xf0-\xf7][\x8f,\x9f,\xaf,\xbf]\xbf[\xbe-\xbf]|'.
'\xfe|\xff|'.
'[\xc0-\xc1][\x80-\xbf]|'.
'\xe0[\x80-\x9f][\x80-\xbf]|'.
'\xf0[\x80-\x8f][\x80-\xbf]{2}|'.
'\xf8[\x80-\x87][\x80-\xbf]{3}|'.
'\xfc[\x80-\x83][\x80-\xbf]{4}'; # gah!
eval <<'EOF';
$utf8_encode = sub { utf8::encode(shift); };
$utf8_decode = sub { utf8::decode(shift); };
EOF
}
$wraptime = sub { my $x = shift; return ($x, $x); };
if ($timestamp) {
my $fail = "-- can't use custom timestamps.\nspecify -timestamp by itself to use Twitter's without module.\n";
if (length($timestamp) > 1) { # pattern specified
eval 'use Date::Parse;return 1' ||
die("$@\nno Date::Parse $fail");
eval 'use Date::Format;return 1' ||
die("$@\nno Date::Format $fail");
$timestamp = "%Y-%m-%d %k:%M:%S"
if ($timestamp eq "default" ||
$timestamp eq "def");
$wraptime = sub {
my $time = str2time(shift);
my $stime = time2str($timestamp, $time);
return ($time, $stime);
};
}
}
}
END {
&killkid unless ($in_backticks || $in_buffer); # this is disgusting
}
#### COMMON STARTUP ####
# if we requested POSIX signals, or we NEED posix signals (5.14+), we
# must check if we have POSIX signals actually
if ($signals_use_posix) {
eval 'use POSIX';
# God help the system that doesn't have SIGTERM
$j = eval 'return POSIX::SIGTERM' ;
die(<<"EOF") if (!(0+$j));
*** death permeates me ***
your configuration requires using POSIX signalling (either Perl 5.14+ or
you specifically asked with -signals_use_posix). however, either you don't
have POSIX.pm, or it doesn't work.
oysttyer requires 'unsafe' Perl signals (which are of course for its
purposes perfectly safe). unfortunately, due to Perl bug 92246 5.14+ must
use POSIX.pm, or have the switch set before starting oysttyer. run one of
export PERL_SIGNALS=unsafe # sh, bash, ksh, etc.
setenv PERL_SIGNALS unsafe # csh, tcsh, etc.
and restart oysttyer, or use Perl 5.12 or earlier (without specifying
-signals_use_posix).
EOF
}
# do we have POSIX::Termios? (usually we do)
eval 'use POSIX; $termios = new POSIX::Termios;';
print $stdout "-- termios test: $termios\n" if ($verbose);
# check the TRLT version. versions < 1.3 won't work with 2.0.
if ($termrl && $termrl->ReadLine eq 'Term::ReadLine::TTYtter') {
eval '$trlv = $termrl->Version;';
die (<<"EOF") if (length($trlv) && 0+$trlv < 1.3);
*** death permeates me ***
you need to upgrade your Term::ReadLine::TTYtter to at least version 1.3
to use oysttyer 2.x, or bad things will happen such as signal mismatches,
unexpected quits, and dogs and cats living peacefully in the same house.
EOF
print $stdout "** t.co support needs Term::ReadLine:TTYtter 1.4+ (-notco to ignore)\n"
if (length($trlv) && !$notco && 0+$trlv < 1.4);
}
# try to get signal numbers for SIG* from POSIX. use internals if failed.
eval 'use POSIX; $SIGUSR1 = POSIX::SIGUSR1; $SIGUSR2 = POSIX::SIGUSR2; $SIGHUP = POSIX::SIGHUP; $SIGTERM = POSIX::SIGTERM';
# from <sys/signal.h>
$SIGHUP ||= 1;
$SIGTERM ||= 15;
$SIGUSR1 ||= 30;
$SIGUSR2 ||= 31;
# wrap warning
die(
"** dude, what the hell kind of terminal can't handle a 5 character line?\n")
if ($wrap > 1 && $wrap < 5);
print $stdout "** warning: prompts not wrapped for wrap < 70\n"
if ($wrap > 1 && $wrap < 70);
# reject stupid combinations
die("-largeimages and -origimages cannot be used together.\n")
if ($largeimages && $origimages);
die("you can't use automatic ratelimits with -noratelimit.\nuse -pause=#sec\n")
if ($noratelimit && $pause eq 'auto');
die("you can't use -synch with -script or -daemon.\n")
if ($synch && ($script || $daemon));
die("-script and -daemon cannot be used together.\n")
if ($script && $daemon);
# set up menu codes and caches
$is_background = 0;
$alphabet = "abcdefghijkLmnopqrstuvwxyz";
%store_hash = ();
$mini_split = 250; # i.e., 10 tweets for the mini-menu (/th)
# leaving 50 tweets for the foreground temporary menus
$tweet_counter = 0;
%dm_store_hash = ();
$dm_counter = 0;
%id_cache = ();
%filter_next = ();
# set up threading management
$in_reply_to = 0;
$expected_tweet_ref = undef;
# interpret -script at this level
if ($script) {
$noansi = $noprompt = 1;
$silent = ($verbose) ? 0 : 1;
$pause = $vcheck = $slowpost = $verify = 0;
}
### now instantiate the oysttyer dynamic API ###
### based off the defaults later in script. ####
# first we need to load any extensions specified by -exts.
if (length($exts) && $exts ne '0') {
$multi_module_mode = -1; # mark as loader stage
print "** attempting to load extensions\n" unless ($silent);
# unescape \,
$j=0; $xstring = "ESCAPED_STRING";
while($exts =~ /$xstring$j/) { $j++; }
$xstring .= $j;
$exts =~ s/\\,/$xstring/g;
foreach $file (split(/,/, $exts)) {
#TODO
# wildcards?
$file =~ s/$xstring/,/g;
print "** loading $file\n" unless ($silent);
die("** sorry, you cannot load the same extension twice.\n")
if ($master_store->{$file}->{'loaded'});
# prepare its working space in $store and load the module
$master_store->{$file} = { 'loaded' => 1 };
$store = \%{ $master_store->{$file} };
$EM_DONT_CARE = 0;
$EM_SCRIPT_ON = 1;
$EM_SCRIPT_OFF = -1;
$extension_mode = $EM_DONT_CARE;
die("** $file not found: $!\n") if (! -r "$file");
require $file; # and die if bad
die("** $file failed to load: $@\n") if ($@);
die("** consistency failure: reference failure on $file\n")
if (!$store->{'loaded'});
# check type of extension (interactive or non-interactive). if
# we are in the wrong mode, bail out.
if ($extension_mode) {
die(
"** this extension requires -script. this may conflict with other extensions\n".
" you are loading, which may have their own requirements.\n")
if ($extension_mode == $EM_SCRIPT_ON && !$script);
die(
"** this extension cannot work with -script. this may conflict with other\n".
" extensions you are loading, which may have their own requirements.\n")
if ($extension_mode == $EM_SCRIPT_OFF && $script);
}
# pick off all the subroutine references it makes for storage
# in an array to iterate and chain over later.
# these methods are multi-module safe
foreach $arry (qw(
handle exception tweettype conclude dmhandle dmconclude
heartbeat precommand prepost postpost addaction
eventhandle listhandle userhandle shutdown)) {
if (defined($$arry)) {
$aarry = "m_$arry";
push(@$aarry, [ $file, $$arry ]);
undef $$arry;
}
}
# these methods are NOT multi-module safe
# if a extension already hooked one of
# these and another extension tries to hook it, fatal error.
foreach $arry (qw(
getpassword prompt main autocompletion)) {
if (defined($$arry)) {
$sarry = "l_$arry";
if (defined($$sarry)) {
die(
"** double hook of unsafe method \"$arry\" -- you cannot use this extension\n".
" with the other extensions you are loading. see the documentation.\n");
}
$$sarry = $$arry;
undef $$arry;
}
}
}
# success! enable multi-module support in the oysttyer API and then
# dispatch calls through the multi-module system instead.
$multi_module_mode = 1; # mark as completed loader
$handle = \&multihandle;
$exception = \&multiexception;
$tweettype = \&multitweettype;
$conclude = \&multiconclude;
$dmhandle = \&multidmhandle;
$dmconclude = \&multidmconclude;
$heartbeat = \&multiheartbeat;
$precommand = \&multiprecommand;
$prepost = \&multiprepost;
$postpost = \&multipostpost;
$addaction = \&multiaddaction;
$shutdown = \&multishutdown;
$userhandle = \&multiuserhandle;
$listhandle = \&multilisthandle;
$eventhandle = \&multieventhandle;
} else {
# the old API single-end-point system
$multi_module_mode = 0; # not executing multi module endpoints
$handle = \&defaulthandle;
$exception = \&defaultexception;
$tweettype = \&defaulttweettype;
$conclude = \&defaultconclude;
$dmhandle = \&defaultdmhandle;
$dmconclude = \&defaultdmconclude;
$heartbeat = \&defaultheartbeat;
$precommand = \&defaultprecommand;
$prepost = \&defaultprepost;
$postpost = \&defaultpostpost;
$addaction = \&defaultaddaction;
$shutdown = \&defaultshutdown;
$userhandle = \&defaultuserhandle;
$listhandle = \&defaultlisthandle;
$eventhandle = \&defaulteventhandle;
}
# unsafe methods use the single-end-point
$prompt = $l_prompt || \&defaultprompt;
$main = $l_main || \&defaultmain;
$getpassword = $l_getpassword || \&defaultgetpassword;
# $autocompletion is special:
if ($termrl) {
$termrl->Attribs()->{'completion_function'} =
$l_autocompletion || \&defaultautocompletion;
}
# fetch_id is based off last_id, if an extension set it
$fetch_id = $last_id || 0;
# validate the notify method the user chose, if any.
# we can't do this in BEGIN, because it may not be instantiated yet,
# and we have to do it after loading modules because it might be in one.
@notifytypes = ();
if (length($notifytype) && $notifytype ne '0' &&
$notifytype ne '1' && !$status) {
# NOT $script! scripts have a use case for notifiers!
%dupenet = ();
foreach $nt (split(/\s*,\s*/, $notifytype)) {
$fnt="notifier_${nt}";
(warn("** duplicate notification $nt was ignored\n"), next)
if ($dupenet{$fnt});
eval 'return &$fnt(undef)' ||
die("** invalid notification framework $nt: $@\n");
$dupenet{$fnt}=1;
}
@notifytypes = keys %dupenet;
$notifytype = join(',', @notifytypes);
# warning if someone didn't tell us what notifies they wanted.
warn "-- warning: you specified -notifytype, but no -notifies\n"
if (!$silent && !length($notifies));
}
# set up track tags
if (length($tquery) && $tquery ne '0') {
my $xtquery = &tracktags_tqueryurlify($tquery);
die("** custom tquery is over $linelength length: $xtquery\n")
if (length($xtquery) >= $linelength);
@trackstrings = ($xtquery);
} else {
&tracktags_makearray;
}
# compile filterflags
&filterflags_compile;
# compile filters
exit(1) if (!&filter_compile);
$filterusers_sub = &filteruserlist_compile(undef, $filterusers);
$filterrts_sub = &filteruserlist_compile(undef, $filterrts);
$filteratonly_sub = &filteruserlist_compile(undef, $filteratonly);
exit(1) if (!&filterats_compile);
# compile lists
exit(1) if (!&list_compile);
# finally, compile notifies. we do this regardless of notifytype, so that
# an extension can look at it if it wants to.
¬ify_compile;
# check that we are using a sensible authtype, based on our guessed user agent
$authtype ||= "oauth";
die("** supported authtypes are basic or oauth only.\n")
if ($authtype ne 'basic' && $authtype ne 'oauth');
if ($termrl) {
$streamout = $stdout; # this is just simpler instead of dupping
warn(<<"EOF") if ($] < 5.006);
***********************************************************
** -readline may not function correctly on Perls < 5.6.0 **
***********************************************************
EOF
print $stdout "-- readline using ".$termrl->ReadLine."\n";
} else {
# dup $stdout for benefit of various other scripts
open(DUPSTDOUT, ">&STDOUT") ||
warn("** warning: could not dup $stdout: $!\n");
binmode(DUPSTDOUT, ":utf8") unless ($seven);
$streamout = \*DUPSTDOUT;
}
if ($silent) {
close($stdout);
open($stdout, ">>/dev/null"); # KLUUUUUUUDGE
}
# after this point, die() may cause problems
# initialize our route back out so background can talk to foreground
pipe(W, P) || die("pipe() error [or your Perl doesn't support it]: $!\n");
select(P); $|++;
# default command line options
$anonymous ||= 0;
$ssl ||= 1;
die("** -anonymous is no longer supported with Twitter (you must use -apibase also)\n")
if ($anonymous && !length($apibase));
undef $user if ($anonymous);
print $stdout "-- using SSL for default URLs.\n" if ($ssl);
$http_proto = ($ssl) ? 'https' : 'http';
$lat ||= undef;
$long ||= undef;
$location ||= 0;
$linelength ||= 280;
$quotelinelength ||= 256;
$tco_length ||= 23; # The number of characters that t.co links require
$dm_text_character_limit ||= 10000;
$oauthbase ||= $apibase || "${http_proto}://api.twitter.com";
# this needs to be AFTER oauthbase so that apibase can set oauthbase.
$apibase ||= "${http_proto}://api.twitter.com/1.1";
$nonewrts ||= 0;
# special case: if we explicitly refuse backload, don't load initially.
$backload = 30 if (!defined($backload)); # zero is valid!
$dont_refresh_first_time = 1 if (!$backload);
$searchhits ||= 20;
$url ||= "${apibase}/statuses/home_timeline.json";
$oauthurl ||= "${oauthbase}/oauth/request_token";
$oauthauthurl ||= "${oauthbase}/oauth/authorize";
$oauthaccurl ||= "${oauthbase}/oauth/access_token";
$credurl ||= "${apibase}/account/verify_credentials.json";
$update ||= "${apibase}/statuses/update.json";
$rurl ||= "${apibase}/statuses/mentions_timeline.json";
$uurl ||= "${apibase}/statuses/user_timeline.json";
$idurl ||= "${apibase}/statuses/show.json";
$delurl ||= "${apibase}/statuses/destroy/%I.json";
$rturl ||= "${apibase}/statuses/retweet";
$rtsbyurl ||= "${apibase}/statuses/retweets/%I.json";
$rtsofmeurl ||= "${apibase}/statuses/retweets_of_me.json";
$wurl ||= "${apibase}/users/show.json";
$frurl ||= "${apibase}/friendships/show.json";
$followurl ||= "${apibase}/friendships/create.json";
$leaveurl ||= "${apibase}/friendships/destroy.json";
$blockurl ||= "${apibase}/blocks/create.json";
$blockdelurl ||= "${apibase}/blocks/destroy.json";
$friendsurl ||= "${apibase}/friends/ids.json";
$followersurl ||= "${apibase}/followers/ids.json";
$frupdurl ||= "${apibase}/friendships/update.json";
$lookupidurl ||= "${apibase}/users/lookup.json";
$muteurl ||= "${apibase}/mutes/users/create.json";
$unmuteurl ||= "${apibase}/mutes/users/destroy.json";
$rlurl ||= "${apibase}/application/rate_limit_status.json";
$dmurl ||= "${apibase}/direct_messages.json";
$dmsenturl ||= "${apibase}/direct_messages/sent.json";
$dmupdate ||= "${apibase}/direct_messages/new.json";
$dmdelurl ||= "${apibase}/direct_messages/destroy.json";
$dmidurl ||= "${apibase}/direct_messages/show.json";
$favsurl ||= "${apibase}/favorites/list.json";
$favurl ||= "${apibase}/favorites/create.json";
$favdelurl ||= "${apibase}/favorites/destroy.json";
$getlisurl ||= "${apibase}/lists/list.json";
$creliurl ||= "${apibase}/lists/create.json";
$delliurl ||= "${apibase}/lists/destroy.json";
$modifyliurl ||= "${apibase}/lists/update.json";
$deluliurl ||= "${apibase}/lists/members/destroy_all.json";
$adduliurl ||= "${apibase}/lists/members/create_all.json";
$getuliurl ||= "${apibase}/lists/memberships.json";
$getufliurl ||= "${apibase}/lists/subscriptions.json";
$delfliurl ||= "${apibase}/lists/subscribers/destroy.json";
$crefliurl ||= "${apibase}/lists/subscribers/create.json";
$getfliurl ||= "${apibase}/lists/subscribers.json";
$getliurl ||= "${apibase}/lists/members.json";
$statusliurl ||= "${apibase}/lists/statuses.json";
$streamurl ||= "https://userstream.twitter.com/1.1/user.json";
$dostream ||= 0;
$eventbuf ||= 0;
$queryurl ||= "${apibase}/search/tweets.json";
# no more $trendurl in 2.1.
$wtrendurl ||= "${apibase}/trends/place.json";
$atrendurl ||= "${apibase}/trends/closest.json";
# pick ONE!
#$shorturl ||= "http://api.tr.im/v1/trim_simple?url=";
$shorturl ||= "https://is.gd/create.php?format=simple&url=";
# figure out the domain to stop shortener loops
&generate_shortdomain;
$pause = (($anonymous) ? 120 : "auto") if (!defined $pause);
# NOT ||= ... zero is a VALID value!
$superverbose ||= 0;
$avatar ||= "";
$urlopen ||= 'echo %U';
$hold ||= 0;
$holdhold ||= 0;
$daemon ||= 0;
$maxhist ||= 19;
undef $shadow_history;
$timestamp ||= 0;
$noprompt ||= 0;
$slowpost ||= 0;
$twarg ||= undef;
$verbose ||= $superverbose;
$dmpause = 4 if (!defined $dmpause); # NOT ||= ... zero is a VALID value!
$dmpause = 0 if ($anonymous);
$dmpause = 0 if ($pause eq '0');
$ansi = ($noansi) ? 0 :
(($ansi || $ENV{'TERM'} eq 'ansi' || $ENV{'TERM'} eq 'xterm-color')
? 1 : 0);
$showusername ||= 0;
$largeimages ||= 0;
$origimages ||= 0;
$doublespace ||= 0;
$extended ||= 0;
$video_bitrate ||= 'highest';
if ($extended) {
$tweet_mode = "extended";
$display_mode = "full_text";
} else {
$tweet_mode = "compatibility";
$display_mode = "text";
}
# synch overrides these options.
if ($synch) {
$pause = 0;
$dmpause = ($dmpause) ? 1 : 0;
}
$dmcount = $dmpause;
$lastshort = undef;
# ANSI sequences
$colourprompt ||= "CYAN";
$colourme ||= "YELLOW";
$colourdm ||= "GREEN";
$colourreply ||= "RED";
$colourwarn ||= "MAGENTA";
$coloursearch ||= "CYAN";
$colourlist ||= "OFF";
$colourdefault ||= "OFF";
$ESC = pack("C", 27);
$BEL = pack("C", 7);
&generate_ansi;
# to force unambiguous bareword interpretation
$true = 'true';
sub true { return 'true'; }
$false = 'false';
sub false { return 'false'; }
$null = undef;
sub null { return undef; }
select($stdout); $|++;
# figure out what our user agent should be
if ($lynx) {
if (length($lynx) > 1 && -x "/$lynx") {
$wend = $lynx;
print $stdout "Lynx forced to $wend\n";
} else {
$wend = &wherecheck("trying to find Lynx", "lynx",
"specify -curl to use curl instead, or just let oysttyer autodetect stuff.\n");
}
} else {
if (length($curl) > 1 && -x "/$curl") {
$wend = $curl;
print $stdout "cURL forced to $wend\n";
} else {
$wend = (($curl) ? &wherecheck("trying to find cURL", "curl",
"specify -lynx to use Lynx instead, or just let oysttyer autodetect stuff.\n")
: &wherecheck("trying to find cURL", "curl"));
if (!$curl && !length($wend)) {
$wend = &wherecheck("failed. trying to find Lynx",
"lynx",
"you must have either Lynx or cURL installed to use oysttyer.\n")
if (!length($wend));
$lynx = 1;
} else {
$curl = 1;
}
}
}
$baseagent = $wend;
# whoops, no Lynx here if we are not using Basic Auth
die(
"sorry, OAuth is not currently supported with Lynx.\n".
"you must use SSL cURL, or specify -authtype=basic.\n")
if ($lynx && $authtype ne 'basic' && !$anonymous);
# streaming API has multiple prereqs. not fatal; we just fall back on the
# REST API if not there.
unless($status) {
if (!$dostream || $authtype eq 'basic' || !$ssl || $script || $anonymous || $synch) {
$reason = (!$dostream) ? "(no -dostream)"
: ($script) ? "(-script)"
: (!$ssl) ? "(no SSL)"
: ($anonymous) ? "(-anonymous)"
: ($synch) ? "(-synch)"
: ($authtype eq 'basic') ? "(no OAuth)"
: "(it's funkatron's fault)";
print $stdout
"-- Streaming API disabled $reason (oysttyer will use REST API only)\n";
$dostream = 0;
} else {
print $stdout "-- Streaming API enabled\n";
# streams change mentions behaviour; we get them automatically.
# warn the user if the current settings are suboptimal.
if ($mentions) {
if ($nostreamreplies) {
print $stdout
"** warning: -mentions and -nostreamreplies are very inefficient together\n";
} else {
print $stdout
"** warning: -mentions not generally needed in Streaming mode\n";
}
}
}
} else { $dostream = 0; } # -status suppresses streaming
if (!$dostream && $streamallreplies) {
print $stdout
"** warning: -streamallreplies only works in Streaming mode\n";
}
# create and cache the logic for our selected user agent
if ($lynx) {
$simple_agent = "$baseagent -nostatus -source";
@wend = ('-nostatus');
@wind = (@wend, '-source'); # GET agent
@wend = (@wend, '-post_data'); # POST agent
# we don't need to have the request signed by Lynx right now;
# it doesn't know how to pass custom headers. so this is simpler.
$stringify_args = sub {
my $basecom = shift;
my $resource = shift;
my $data = shift;
my $dont_do_auth = shift;
my $k = join("\n", @_);
# if resource is an arrayref, then it's a GET with URL
# and args (mostly generated by &grabjson)
$resource = join('?', @{ $resource })
if (ref($resource) eq 'ARRAY');
die("wow, we have a bug: Lynx only works with Basic Auth\n")
if ($authtype ne 'basic' && !$dont_do_auth);
$k = "-auth=".$mytoken.':'.$mytokensecret."\n".$k
unless ($dont_do_auth);
$k .= "\n";
$basecom = "$basecom \"$resource\" -";
return ($basecom, $k, $data);
};
} else {
$simple_agent = "$baseagent -s -m 20";
@wend = ('-s', '-m', '20', '-A', "oysttyer/$oysttyer_VERSION",
'--http1.1', '-H', 'Expect:');
@wind = @wend;
$stringify_args = sub {
my $basecom = shift;
my $resource = shift;
my $data = shift;
my $dont_do_auth = shift;
my $p;
my $l = '';
foreach $p (@_) {
if ($p =~ /^-/) {
$l .= "\n" if (length($l));
$l .= "$p ";
next;
}
$l .= $p;
}
$l .= "\n";
# sign our request (Basic Auth or oAuth)
unless ($dont_do_auth) {
if ($authtype eq 'basic') {
$l .= "-u ".$mytoken.":".$mytokensecret."\n";
} else {
my $nonce;
my $timestamp;
my $sig;
my $verifier = '';
my $header;
my $ttoken = (length($mytoken) ?
(' oauth_token=\\"'.$mytoken.'\\",') :
'');
($timestamp, $nonce, $sig, $verifier) =
&signrequest($resource, $data);
$header = <<"EOF";
-H "Authorization: OAuth oauth_nonce=\\"$nonce\\", oauth_signature_method=\\"HMAC-SHA1\\", oauth_timestamp=\\"$timestamp\\", oauth_consumer_key=\\"$oauthkey\\", oauth_signature=\\"$sig\\",${ttoken}${verifier} oauth_version=\\"1.0\\""
EOF
print $stdout $header if ($superverbose);
$l .= $header;
}
}
# if resource is an arrayref, then it's a GET with URL
# and args (mostly generated by &grabjson)
$resource = join('?', @{ $resource })
if (ref($resource) eq 'ARRAY');
$l .= "url = \"$resource\"\n";
$l .= "data = \"$data\"\n" if length($data);
return ("$basecom -K -", $l, undef);
};
}
# update check
if ($vcheck && !length($status)) {
$vs = &updatecheck(0);
} else {
$vs =
"-- no version check performed (use /vcheck, or -vcheck to check on startup)\n"
unless ($script || $status);
}
print $stdout $vs; # and then again when client starts up
## make sure we have all the authentication pieces we need for the
## chosen method (authtoken handles this for Basic Auth;
## this is where we validate OAuth)
# if we use OAuth, then don't use any Basic Auth credentials we gave
# unless we specifically say -authtype=basic
if ($authtype eq 'oauth' && length($user)) {
print "** warning: -user is ignored when -authtype=oauth (default)\n";
$user = undef;
}
$whoami = (split(/\:/, $user, 2))[0] unless ($anonymous || !length($user));
# yes, this is plaintext. obfuscation would be ludicrously easy to crack,
# and there is no way to hide them effectively or fully in a Perl script.
# so be a good neighbour and leave this the fark alone, okay? stealing
# credentials is mean and inconvenient to users. this is blessed by
# arrangement with Twitter. don't be a d*ck. thanks for your cooperation.
$oauthkey = (!length($oauthkey) || $oauthkey eq 'X') ?