-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
twicli.js
2245 lines (2217 loc) · 91.1 KB
/
twicli.js
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
// common
function $(id) { return document.getElementById(id); }
// 文字参照をデコード
function charRef(s) {
var ele = document.createElement("div");
ele.innerHTML = s;
return ele.firstChild.nodeValue;
}
// フォームをシリアライズ
function serializeForm(f, filter) {
var url = '';
for (var e = 0; e < f.elements.length; e++) {
var input = f.elements[e];
if (input.name && input.value && (!filter || input.name.indexOf(filter) >= 0))
url += (url == '' ? '?' : '&') + input.name + "=" + OAuth.percentEncode(input.value.replace(/\r?\n/g, "\r\n"));
}
return url;
}
// OAuth用formに引数を設定(Twitter APIのみ)
function setupOAuthArgs(args) {
var api_args = $("api_args");
api_args.innerHTML = "";
if (args) {
args = args.split("&");
for (var i = 0; i < args.length; i++) {
var v = args[i].split("=");
var el = document.createElement("input");
el.type = "hidden";
el.name = v[0];
el.value = decodeURIComponent(v[1]);
api_args.appendChild(el);
}
}
}
function setupOAuthURL(url, post, post_agent, multipart) {
var twapi2 = url.indexOf(twitterAPI2) == 0;
if (url.indexOf(twitterAPI) != 0 && !twapi2) return url;
var media_upload = url.indexOf('update_with_media.json') >= 0 && post;
var json_post = url.indexOf('?_body=') >= 0 && post;
if (media_upload || json_post) multipart = true;
var nosign = [];
url = url.split("?");
if (post && !(media_upload && post_agent) && url[1] && url[1].match(/(^|&)((?:status)=[^&]+)/) && RegExp.$2.indexOf('%2A') >= 0 || RegExp.$2.indexOf('*') >= 0) {
// "*"(%2A)はPOSTデータではURLEncodeされずに送信されOAuthエラーとなるため、URL内に含める(statusにのみ対応)
url[1] = url[1].replace(RegExp.$1+RegExp.$2, '');
url[0] += "?" + RegExp.$2.replace(/\*/g, '%2A');
}
setupOAuthArgs(url[1]);
if (multipart || json_post) {
var cs = document.request.childNodes;
for (var e = cs.length - 1; e >= 0; e--) {
if (cs[e].tagName == 'INPUT' && cs[e].name.indexOf('oauth') < 0 || cs[e] === $('api_args')) {
nosign.push(cs[e]);
cs[e].parentNode.removeChild(cs[e]);
}
}
document.request.enctype = 'multipart/form-data';
} else
document.request.enctype = 'application/x-www-form-urlencoded';
document.request.method = (post || post_agent) ? 'POST' : 'GET';
document.etc.URL.value = url[0];
consumer.signForm(document.request, document.etc);
url = document.etc.URL.value;
if (post_agent) {
var sid = ['','2'][((new Date).getTime()/1000/60/60/12|0)%2];
url = url.replace(twitterAPI, 'https://tweet-agent'+sid+'.appspot.com/1.1/');
} else if (twapi2) {
url = url.replace(twitterAPI2, 'https://thumbnail-url-t2yaxfegmq-uw.a.run.app/twitter-api/2/');
}
for (e = 0; e < nosign.length; e++)
document.request.appendChild(nosign[e]);
if (media_upload) {
var media = $("media");
media.parentNode.removeChild(media);
media.style.display = "none";
$("api_args").appendChild(media);
}
return url + (!post || multipart ? serializeForm(document.request, multipart && 'oauth') : '');
}
// クロスドメインJavaScript呼び出し(Twitter APIはOAuth認証)
function loadXDomainScript(url, ele) {
url = setupOAuthURL(url);
if (!url) return ele;
if (ele && ele.parentNode)
ele.parentNode.removeChild(ele);
ele = document.createElement("script");
ele.src = url;
ele.type = "text/javascript";
document.body.appendChild(ele);
return ele;
}
// クロスドメインJavaScript呼び出し(エラー処理+リトライ付き, Twitter APIはOAuth認証)
var xds = {
load: function(url, callback, onerror, retry, callback_key, post_agent) {
var url2 = setupOAuthURL(url +
(callback_key === false ? '' :
(url.indexOf('?')<0?'?':'&') + (callback_key?callback_key:'callback') + '=cb'),
false, post_agent);
if (!url2) return null;
loading(true);
var ifr = document.createElement("iframe");
ifr.style.display = "none";
document.body.appendChild(ifr);
var d = ifr.contentWindow.document;
var cnt = 0; // 二重onload防止
ifr[ifr.readyState/*IE*/ ? "onreadystatechange" : "onload"] = function() {
if (this.readyState && this.readyState != 'complete' || cnt++) return;
if (d.x) {
if (callback) callback.apply(this, d.x);
} else if (retry && retry > 1) {
if (url.indexOf(twitterAPI) == 0) {
updateRateLimit(function(limits){
if (url.substr(twitterAPI.length).match(/(.*?)\/(.*)\.json/)) {
var ep = '/'+RegExp.$1+'/'+RegExp.$2;
var resource = limits.resources[RegExp.$1];
ep = ep.replace(/\d+/,':id');
if (resource && resource[ep] && resource[ep].remaining <= 0) {
var d = resource[ep].reset - Math.floor((new Date).getTime()/1000);
return error(_('Too many requests: Twitter API $1 is rate limited; reset in $2', ep, Math.floor(d/60) + ":" + d2(Math.floor(d%60))));
}
}
loading(true); // retry待ち表示
setTimeout(function(){ xds.load(url, callback, onerror, retry-1);
loading(false);
}, 1000);
});
}
} else if (onerror)
onerror();
loading(false);
setTimeout(function(){ try { ifr.parentNode.removeChild(ifr); } catch(e) {} }, 0);
};
d.write('<scr'+'ipt src="array.js"></scr'+'ipt>' +
'<scr'+'ipt src="'+url2+'"></scr'+'ipt>');
d.close();
return ifr;
},
abort: function(ifr) {
if (ifr && ifr.parentNode) {
ifr.parentNode.removeChild(ifr);
loading(false);
}
},
load_default: function(url, callback, old, callback_key) {
this.abort(old);
return this.load(url, callback, twFail, 3, callback_key);
},
load_for_tab: function(url, callback, callback_key) { // タブ切替時に自動abort
var ifr_tab = this.ifr_tab;
var fr = [this.load(url,
function() { callback.apply(this,arguments); try { ifr_tab.remove(fr[0]); } catch(e) {} },
function() { twFail(); try { ifr_tab.remove(fr[0]); } catch(e) {} },
3, callback_key)];
this.ifr_tab.push(fr[0]);
},
abort_tab: function() {
for (var i = 0; i < this.ifr_tab.length; i++)
this.abort(this.ifr_tab[i])
this.ifr_tab = [];
},
ifr_tab: []
};
// CORSによるPOST (Agent経由)
function corsPost(url, done, err) {
loading(true);
var url_post = setupOAuthURL(url, true, true, true);
var form = new FormData();
var inputs = document.request.getElementsByTagName("INPUT");
for (var i = 0; i < inputs.length; i++)
if (inputs[i].type == 'file')
form.append(inputs[i].name, inputs[i].files[0]);
else if (inputs[i].name.indexOf('oauth_') != 0)
form.append(inputs[i].name, inputs[i].value);
var xhr = new XMLHttpRequest();
xhr.onload = function(){
if (xhr.readyState != 4) return;
loading(false);
if (xhr.status == 200)
done(JSON.parse(xhr.responseText));
else
done({'errors': [{message: xhr.responseText}]});
}
xhr.onerror = function(){ loading(false); err(); }
xhr.open('POST', url_post, true);
xhr.send(form);
}
// 動的にフレームを生成してPOSTを投げる(Twitter APIはOAuth認証)
var postQueue = [];
function enqueuePost(url, done, err, retry, force_post) {
if (post_via_agent && url.indexOf(twitterAPI) == 0)
if ((!$('media') || !$('media').value) && !force_post)
return xds.load(url, done, err, retry, null, true);
else
return corsPost(url, done, err);
postQueue.push(arguments);
if (postQueue.length > 1) // 複数リクエストを同時に投げないようキューイング
return;
postNext();
}
function postNext() {
if (postQueue.length)
postInIFrame.apply(this, postQueue[0]);
}
var postSeq = 0;
var postTimeout = 3000;
function postInIFrame(url, done, err, retry) {
loading(true);
var frm = url.indexOf(twitterAPI) == 0 ? document.request : document.post;
frm.action = setupOAuthURL(url, true);
frm.target = "pfr" + (++postSeq);
var pfr = document.createElement("iframe"); // formのtargetとなるiframeを生成
pfr.name = "pfr" + postSeq;
pfr.src = "about:blank";
pfr.style.display = "none";
var errTimer = false;
// 一定時間内に正常終了しなければエラーとみなす
// 通常5秒、エラー処理指定時はデフォルト3秒→10秒、ファイル送信時は更に+30秒)
errTimer = setTimeout(function(){
loading(false);
if (err) err(); else done();
setTimeout(function(){
pfr.parentNode && pfr.parentNode.removeChild(pfr);
postQueue.shift();
postNext();
}, 0);
}, (frm.enctype=='multipart/form-data'?30000:0) + (retry?10000:err?postTimeout:5000));
var cnt = 0;
var onload = pfr.onload = function(){
if (cnt++ == 0) {
setTimeout(function(){frm.submit();}, 0);
} else {
loading(false);
clearTimeout(errTimer);
done();
setTimeout(function(){
pfr.parentNode && pfr.parentNode.removeChild(pfr);
postQueue.shift();
postNext();
}, 0);
}
};
if ('\v'=='v') pfr.onreadystatechange = function(){ /* for IE */
if (this.readyState == "complete") {
pfr.contentWindow.name = pfr.name;
onload();
}
};
document.body.appendChild(pfr);
}
// 要素の位置を取得
function cumulativeOffset(ele) {
var top = 0, left = 0;
do {
top += ele.offsetTop || 0;
left += ele.offsetLeft || 0;
ele = ele.offsetParent;
} while (ele);
return [left, top];
}
// スクロール
if (navigator.userAgent.indexOf('iPhone') >= 0)
window.scrollBy = function(x,y) { scrollTo(x+window.pageXOffset,y+window.pageYOffset) };
var scroll_adjust = 0;
var scroll_duration;
var scroll_timer = null;
function getScrollY() { return window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop; }
function scrollToY(y, total, start) {
var cont = scroll_timer && !start;
if (scroll_timer) clearTimeout(scroll_timer);
scroll_timer = null;
var t = (new Date).getTime();
start = start || t;
total = total || y - getScrollY();
if (start == t) scroll_adjust = 0;
if (start == t) scroll_duration = Math.min(500, Math.abs(total));
y += scroll_adjust;
scroll_adjust = 0;
if (start+scroll_duration <= t || cont)
return scrollTo(0, y);
var pix = Math.ceil(total*(1-Math.cos((t-start)/scroll_duration*Math.PI))/2);
scrollTo(0, y-total+pix);
scroll_timer = setTimeout(function(){scrollToY(y, total, start)}, 20);
}
function scrollToDiv(d, top_margin) {
top_margin = (top_margin || 0) + $('control').clientHeight+1;
var top = cumulativeOffset(d)[1];
var h = d.offsetHeight;
var sc_top = document.body.scrollTop || document.documentElement.scrollTop;
var win_h = window.innerHeight || document.documentElement.clientHeight;
if (top < sc_top+top_margin) scrollToY(top-top_margin);
if (sc_top+win_h < top+h)
if (win_h >= h+top_margin) scrollToY(top+h-win_h);
else scrollToY(top-top_margin);
}
// DOM Storage (or Cookie)
var use_local_storage = true;
try {
window.sessionStorage; /* check DOM storage is accessible */
if (!window.localStorage) window.localStorage = window.globalStorage && window.globalStorage[location.hostname];
} catch(e) { use_local_storage = false; }
if (location.search.indexOf("cookie=1") >= 0) use_local_storage = false;
function readCookie(key) {
try {
if (use_local_storage && window.localStorage && window.localStorage["twicli_"+key])
return String(window.localStorage["twicli_"+key]);
} catch(e) { return null; }
key += "=";
var scookie = document.cookie + ";";
var start = scookie.indexOf(key);
if (start >= 0) {
var end = scookie.indexOf(";", start);
return unescape(scookie.substring(start + key.length, end));
}
return null;
}
function writeCookie(key, val, days) {
if (use_local_storage && window.localStorage)
try {
deleteCookie(key); // to avoid exception on iPad
window.localStorage["twicli_"+key] = val;
} catch(e) {
alert("DOM storage write error!\n" + e);
}
else {
var sday = new Date();
sday.setTime(sday.getTime() + (days * 1000 * 60 * 60 * 24));
document.cookie = key + "=" + escape(val) + ";expires=" + sday.toGMTString();
}
}
function deleteCookie(key) {
try { delete window.localStorage["twicli_"+key]; } catch(e) {}
var sday = new Date();
sday.setTime(sday.getTime() - 1);
document.cookie = key + "=;expires=" + sday.toGMTString();
}
function exportableKey(key) {
if (key.indexOf('twicli_') != 0) return false;
var blacklist = ['access','accounts','followers_ids','lists_users.'];
for (var i = 0; i < blacklist.length; i++)
if (key.indexOf('twicli_' + blacklist[i]) == 0) return false;
return true;
}
function serializeCookies() {
if (!use_local_storage || !window.localStorage) return null;
var ret = {};
for (var key in localStorage)
if (exportableKey(key))
ret[key] = localStorage[key];
return JSON.stringify(ret);
}
function deserializeCookies(json) {
var ret = JSON.parse(json);
for (var key in ret)
if (exportableKey(key))
localStorage[key] = ret[key] || "";
}
function uploadSettings() {
if (!confirm(_('Are you sure to upload your settings to the server? The settings are only downloadable from the current account. Authentication information is not included.'))) return;
var xhr = new XMLHttpRequest();
xhr.open('POST', 'save_settings.cgi', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200 && xhr.responseText == "OK\n")
alert(_('Your settings are uploaded successfully.'));
else
alert(_('Failed to upload settings. (Error $1)', xhr.status));
}
}
xhr.send('key=' + hex_sha1(access_token) + '&data=' + encodeURIComponent(serializeCookies()));
}
function downloadSettings() {
if (!confirm(_('Are you sure to download your settings from the server? Current settings are overwritten.'))) return;
var xhr = new XMLHttpRequest();
xhr.open('GET', 'settings/' + hex_sha1(access_token) + '?' + (new Date).getTime(), true);
xhr.responseType = 'text';
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
deserializeCookies(xhr.responseText);
alert(_('Your settings are downloaded. Please reload to enable them.'));
}
else
alert(_('Failed to download settings. (Error $1)', xhr.status));
}
}
xhr.send();
}
// 言語リソースをルックアップ
var browser_lang = navigator.browserLanguage || navigator.language || navigator.userLanguage || 'en';
var browser_lang0 = browser_lang.split('-')[0];
if (!langNames[browser_lang] && langNames[browser_lang0]) browser_lang = browser_lang0;
var user_lang = readCookie('user_lang') || browser_lang;
var lang;
for (lang = 0; lang < langList.length; lang++)
if (langList[lang] == user_lang) break;
function _(key) {
if (!langResources[key])
alert("no langResource\n\n"+key);
else
key = langResources[key][lang] || key;
var args = arguments;
return key.replace(/\$(\d+)/g, function(x,n){ return args[parseInt(n)] });
}
// version check
document.twicli_js_ver = 12;
if (!document.twicli_html_ver || document.twicli_html_ver < document.twicli_js_ver) {
if (location.href.indexOf('?') < 0) {
location.href = location.href + '?' + document.twicli_js_ver;
} else {
alert(_('An old HTML file is loaded. Please reload it. If the problem is not fixed, please try erasing caches.'));
}
}
// user-defined CSS
try {
$('theme_css').innerHTML = readCookie('theme_css') || "";
} catch(e) {
console.log("Failed to apply theme_css.");
}
var dark_mode = false;
try {
if (!readCookie('theme_name') && window.matchMedia("(prefers-color-scheme: dark)").matches) {
document.write('<style id="dark_mode">@import url(styles/dark.css);</style>');
dark_mode = true;
}
} catch(e) {
console.log("Error on dark-mode switch: " + e);
}
var user_style = readCookie('user_style') || "";
document.write('<style id="usercss">' + user_style + '</style>');
// twicli用変数
var twitterURL = 'https://twitter.com/';
var twitterAPI = 'https://api.twitter.com/1.1/';
var twitterAPI2 = 'https://api.twitter.com/2/';
var myname = null; // 自ユーザ名
var myid = null; // 自ユーザID
var last_user = null; // user TLに表示するユーザ名
var last_user_info = null; // user TLに表示するユーザ情報(TLから切替時のキャッシュ)
// 設定値
var currentCookieVer = 25;
var cookieVer = parseInt(readCookie('ver')) || 0;
var updateInterval = (cookieVer>18) && parseInt(readCookie('update_interval')) || 90;
var pluginstr = (cookieVer>6) && readCookie('tw_plugins') || ' regexp.js\nlists.js\nsearch.js\nfollowers.js\nshorten_url.js\nresolve_url.js';
if (cookieVer<8) pluginstr+="\ntranslate.js\nscroll.js";
if (cookieVer<9) pluginstr+="\nthumbnail.js";
//if (cookieVer<10) pluginstr=" worldcup-2010.js\n" + pluginstr.substr(1);
if (cookieVer<11) pluginstr = pluginstr.replace(/worldcup-2010\.js[\r\n]+/,'');
if (cookieVer<11) pluginstr+="\ngeomap.js";
if (cookieVer<12 && pluginstr.indexOf('tweet_url_reply.js')<0) pluginstr+="\ntweet_url_reply.js";
//if (cookieVer<13) pluginstr+="\nrelated_results.js";
if (cookieVer<14) pluginstr+="\nembedsrc.js";
if (cookieVer<15) pluginstr = pluginstr.replace(/search2\.js[\r\n]+/,'');
if (cookieVer<16) pluginstr+="\nmute.js";
if (cookieVer<17) pluginstr = pluginstr.replace(/outputz\.js[\r\n]+/,'');
if (cookieVer<17) pluginstr = pluginstr.replace(/related_results\.js[\r\n]+/,'');
if (cookieVer<18) if (pluginstr.indexOf('shortcutkey.js')<0) pluginstr+="\nshortcutkey.js";
if (cookieVer<18) if (pluginstr.indexOf('multi_account.js')<0) pluginstr+="\nmulti_account.js";
if (cookieVer<18) if (pluginstr.indexOf('notify.js')<0) pluginstr+="\nnotify.js";
if (cookieVer<21) if (pluginstr.indexOf('tweets_after_rt.js')<0) pluginstr+="\ntweets_after_rt.js";
//if (cookieVer<23) if (pluginstr.indexOf('ioc_flags.js')<0) pluginstr+="\nioc_flags.js";
if (cookieVer<24) pluginstr = pluginstr.replace(/ioc_flags\.js[\r\n]+/,'');
if (cookieVer<25) if (pluginstr.indexOf('move2https.js')<0) pluginstr+="\nmove2https.js";
pluginstr = pluginstr.substr(1);
var plugins = new Array;
var max_count = Math.min((cookieVer>3) && parseInt(readCookie('max_count')) || 50, 800);
var max_count_u = Math.min(parseInt(readCookie('max_count_u')) || 50, 800);
var nr_limit = Math.max(max_count*2.5, parseInt(readCookie('limit')) || 500); // 表示する発言数の上限
var no_since_id = parseInt(readCookie('no_since_id') || "0"); // since_idを使用しない
var no_counter = parseInt(readCookie('no_counter') || "0"); // 発言文字数カウンタを無効化
var no_resize_fst = parseInt(readCookie('no_resize_fst') || "0"); // フィールドの自動リサイズを無効化
var replies_in_tl = parseInt(readCookie('replies_in_tl') || "1"); // フォロー外からのReplyをTLに表示
var display_as_rt = parseInt(readCookie('display_as_rt') || "0"); // Retweetを"RT @〜: …"形式で表示
var reply_to_all = parseInt(readCookie('reply_to_all') || "1"); // 全員に返信
var footer = readCookie('footer') || ""; // フッタ文字列
var decr_enter = parseInt(readCookie('decr_enter') || "0"); // Shift/Ctrl+Enterで投稿
var confirm_close = parseInt(readCookie('confirm_close') || "1"); // Tabを閉じるとき確認
var confirm_delete = parseInt(readCookie('confirm_delete') || "1"); // ツイート削除時に確認
var confirm_rt = parseInt(readCookie('confirm_rt') || "1"); // Retweet時に確認
var confirm_too_long = parseInt(readCookie('confirm_too_long') || "1"); // 長いツイートをする前に確認
var no_geotag = parseInt(readCookie('no_geotag') || "0"); // GeoTaggingを無効化
var post_via_agent = cookieVer > 19 ? parseInt(readCookie('post_via_agent') || "1") : 1; // tweet-agent経由でツイート
var show_header_img = parseInt(readCookie('show_header_img') || "1"); // ヘッダ画像表示
var dnd_image_upload_supported = navigator.userAgent.indexOf('WebKit') >= 0 ||
navigator.userAgent.match(/Firefox\/(\d+)/) && RegExp.$1 >= 10;
var dnd_image_upload = cookieVer > 21 ? parseInt(readCookie('dnd_image_upload') ||
(dnd_image_upload_supported ? "1" : "0")) : dnd_image_upload_supported; // ドラッグ&ドロップで画像アップロード
// TL管理用
var cur_page = 1; // 現在表示中のページ
var nr_page = 0; // 次に取得するページ
var nr_page_re = 0; // 次に取得するページ(reply用)
var max_id;
var get_next_func = getOldTL; // 次ページ取得関数
var since_id = null; // TLの最終since_id
var since_id_reply = null; // Replyの最終since_id
var in_reply_to_user = null; // 発言の返信先ユーザ
var in_reply_to_status_id = null;// 発言の返信先id
// クロスドメイン通信関連
var seq = (new Date).getTime();
var users_log = [];
var update_ele = null;
var update_ele2 = null;
var reply_ele = null;
var reply_ele2 = null;
var direct_ele = null;
// UI関連
var user_picks = []; // [⇔]で表示するユーザ名
var popup_user = null; // ポップアップメニューが選択されたユーザ名
var popup_id = null; // ポップアップメニューが選択された発言ID
var popup_ele = null; // ポップアップメニューが選択された発言ノード
var fav_mode = 0; // Userタブで 1: fav表示中 2: following表示中 3: followers表示中
var rep_top = 0; // replyのオーバーレイ位置
var rep_trace_id = null; // replyのオーバーレイに追加する発言ID
var popup_top = 0; // ポップアップメニューの表示位置
var min_fst_height = 30; // 発言欄の最小の高さ
var selected_menu; // 選択中のタブ
var update_timer = null;
var update_reply_counter = 0;
var update_direct_counter = 0;
var last_post = null;
var last_in_reply_to_user = null;
var last_in_reply_to_status_id = null;
var in_reply_to_status_id_tw = null;
var last_direct_id = null;
var geo = null;
var geowatch = null;
var loading_cnt = 0;
var err_timeout = null;
var update_post_check = false;
var tweet_failed_notified = false;
var tw_limits = {};
var t_co_maxstr = "http://t.co/**********";
var api_resources = ['statuses','friendships','friends','followers','users','search','lists','favorites'];
var first_update = true;
var reset_timer = null;
var last_update_time = null;
var default_api_args = 'suppress_response_codes=true';
var default_api_args_tl = default_api_args + '&include_entities=true&tweet_mode=extended';
var user_cache = {};
var user_cache_by_screen_name = {};
var user_cache_fetch_list = [];
var user_fetch_callback = null;
function text(tw) {
return tw.extended_tweet && tw.extended_tweet.full_text || tw.full_text || tw.text;
}
function ent(tw, for_urls) {
return tw.extended_tweet && tw.extended_tweet.entities ||
!for_urls && tw.extended_entities || tw.entities;
}
// loading表示のコントロール
function loading(start) {
loading_cnt += start ? 1 : loading_cnt > 0 ? -1 : 0;
$('loading').style.display = loading_cnt > 0 ? "block" : "none";
}
//ログイン・自ユーザ名受信
var access_token = readCookie('access_token');
var access_secret = readCookie('access_secret');
if (!access_token || !access_secret) location.href = 'oauth/index.html';
//URL(?status=〜)から発言入力
if (location.search.match(/[?&]status=(.*?)(?:&|$)/)) {
writeCookie('twicli_onload', decodeURIComponent(RegExp.$1));
location.href = "twicli.html";
} else {
setTimeout(function(){
if ($("fst") && ($("fst").value = readCookie('twicli_onload') || '')) {
deleteCookie('twicli_onload');
}
}, 0);
}
function twAuth(a) {
if (a.errors && a.errors[0]) {
alert(a.errors[0].message);
if (a.errors[0].message == "Incorrect signature" || a.errors[0].message.indexOf("Could not authenticate") >= 0)
logout();
return;
}
if (!myname || !myid || myname != a.screen_name) {
myname = last_user = a.screen_name;
last_user_info = a;
myid = a.id_str || a.id;
writeCookie('access_user', myname+'|'+myid, 3652);
$("user").innerHTML = last_user;
update();
}
if (!no_geotag && a.geo_enabled && navigator.geolocation) {
$("option").innerHTML += '<div id="geotag"><a href="javascript:toggleGeoTag()"><img align="left" id="geotag-img" src="images/earth_off.png">'+_('GeoTagging')+' <span id="geotag-st">OFF</span></a><small id="geotag-info"></small></div>';
setFstHeight(min_fst_height, true);
}
callPlugins('auth');
}
function twAuthFallback() {
// verify_credentials API is unavailable?
xds.load(twitterAPI + "users/show.json?screen_name="+myname +
"&" + default_api_args, twAuth, function(){error("Authentication failed.");});
}
function auth() {
var name = readCookie('access_user');
if (!myname && name) {
name = name.split('|');
myname = last_user = name[0];
myid = name[1];
$("user").innerHTML = last_user;
update();
}
xds.load(twitterAPI + "account/verify_credentials.json?" +
default_api_args, twAuth, twAuthFallback, 1);
}
function logout(force) {
if (!force && !confirm(_('Are you sure to logout? You need to re-authenticate twicli at next launch.')))
return;
callPlugins('logout');
deleteCookie('access_token');
deleteCookie('access_secret');
deleteCookie('access_user');
location.href = 'oauth/index.html';
}
function error(str, err) {
if (err && err[0] && err[0].code == 93) {
if (confirm(_('Cannot access to direct messages. Please re-auth twicli for DM access.')))
logout(true);
return;
}
if (err && err.errors && err.errors[0])
str += _('Twitter API error') + ': ' + err.errors[0].message;
$("errorc").innerHTML = str;
$("error").style.display = "block";
if (err_timeout) clearTimeout(err_timeout);
err_timeout = error_animate(true);
}
function error_animate(show, t) {
t = t || new Date();
var dur = new Date() - t;
var opacity = Math.min(0.7, dur/300.0);
if (!show) opacity = Math.max(0, 0.7-opacity);
$("error").style.opacity = opacity;
if (show && opacity == 0.7)
err_timeout = setTimeout(function(){ error_animate(false); }, 5000);
else if (!show && opacity == 0)
$("error").style.display = "none";
else
err_timeout = setTimeout(function(){ error_animate(show, t); }, 30);
}
function clear_error() {
if ($("error").style.opacity == 0.7) {
clearTimeout(err_timeout);
err_timeout = setTimeout(function(){ error_animate(false); }, 0);
}
}
var notify_queue = [];
var notify_timer = null;
function notify(str) {
callPlugins('notify', str);
if (notify_timer) {
notify_queue.push(str);
return;
}
notify_show(str);
}
function notify_show(str) {
$("notifyc").innerHTML = str || notify_queue.shift() || '';
$("notify").style.display = "block";
setTimeout(function(){
var win_h = window.innerHeight || document.documentElement.clientHeight;
$("notify").style.top = win_h - $("notifyc").clientHeight + "px";
notify_timer = setTimeout(clear_notify, 5000);
}, 0);
}
function clear_notify() {
if (notify_timer) clearTimeout(notify_timer);
$("notify").style.top = "100%";
if (notify_queue.length)
notify_timer = setTimeout(notify_show, 500);
else
notify_timer = setTimeout(function(){
$("notify").style.display = "none";
notify_timer = null;
}, 500);
}
function twFail() {
error('<img style="vertical-align:middle" src="images/whale.png"> '+_('API error (Twitter may be over capacity?)'));
}
function sendMessage(user, text) {
callPlugins("sendMessage", user, text);
fetchUserCacheByScreenName(user, function() {
var user_id = user_cache_by_screen_name[user].id_str;
enqueuePost(twitterAPI + "direct_messages/events/new.json?_body={\"event\": " +
"{\"type\":\"message_create\",\"message_create\":{\"target\":{\"recipient_id\":" + user_id +
"},\"message_data\":{\"text\":\"" + encodeURIComponent(text) + "\"}}}}",
function(tw){ if (tw && tw.errors) error('', tw); resetFrm(); },
function(){ error(_('Twitter API error')); resetFrm(); },
false, true);
});
return false;
}
function isMessage() {
return document.frm.status.value.match(/^[dD]\s+(\w+)\s+([\w\W]+)/);
}
// enterキーで発言, "r"入力で再投稿, 空欄でTL更新
function press(e) {
if (e != 1 && (e.keyCode != 13 && e.keyCode != 10 ||
!decr_enter && (e.ctrlKey || e.shiftKey) || decr_enter && !(e.ctrlKey || e.shiftKey)) )
return true;
var st = document.frm.status;
if (st.value == '' && !($('media')&&$('media').value)) {
update();
return false;
}
if (parseInt($("counter").innerHTML,10) < 0)
if (confirm_too_long && !confirm(_("This tweet is too long.")))
return false;
var retry = 0;
if (st.value == "r" && last_post) {
retry = 1;
st.value = last_post;
in_reply_to_user = last_in_reply_to_user;
setReplyId(last_in_reply_to_status_id);
}
if (isMessage()) {
// DM送信
return sendMessage(RegExp.$1, RegExp.$2);
}
last_post = st.value;
last_in_reply_to_user = in_reply_to_user;
last_in_reply_to_status_id = in_reply_to_status_id;
if (st.value.substr(0,1) == ".")
setReplyId(false); // "."で始まる時はin_reply_to指定無し
callPlugins("post", st.value);
st.value += footer;
st.select();
var text = st.value;
var do_post = function(r){
var media = $('media')&&$('media').value;
enqueuePost(twitterAPI + 'statuses/update' + (media ? '_with_media' : '') + '.json?'+
default_api_args_tl +
'&status=' + OAuth.percentEncode(st.value) +
(geo && geo.coords ? "&display_coordinates=true&lat=" + geo.coords.latitude +
"&long=" + geo.coords.longitude : "") +
(in_reply_to_status_id ? "&in_reply_to_status_id=" + in_reply_to_status_id : ""),
function(tw){ if (tw && tw.errors) error('', tw); else resetFrm(); twShow([tw]); },
function(err){ if (err) return error('', err); if (media && post_via_agent) { resetFrm(); setTimeout(update, 1000); } else if (r && post_via_agent) do_post(false); },
retry);
};
do_post(true);
callPlugins("postQueued", text);
in_reply_to_user = null;
return false;
}
// GeoTag
function toggleGeoTag() {
if (!geowatch) {
geowatch = navigator.geolocation.watchPosition(function(g){
geo = g;
var maplink = typeof(display_map) == 'function';
$("geotag-info").innerHTML = " : " + (maplink ? '<a href="javascript:display_map([geo.coords.latitude, geo.coords.longitude, geo.coords.accuracy], $(\'geotag-info\'))">' : '') + g.coords.latitude + ", " + g.coords.longitude + " (" + g.coords.accuracy + "m)" + (maplink ? '</a>' : '');
setFstHeight(null, true);
});
$("geotag-img").src = "images/earth.png";
$("geotag-st").innerHTML = "ON";
$("geotag-info").innerHTML = " : -";
} else {
navigator.geolocation.clearWatch(geowatch);
geo = geowatch = null;
$("geotag-img").src = "images/earth_off.png";
$("geotag-st").innerHTML = "OFF";
$("geotag-info").innerHTML = "";
setFstHeight(null, true);
}
}
// フォームリサイズ
function setFstHeight(h, force) {
if (!h)
h = $("fst").value.length ? Math.max($("fst").scrollHeight+2,min_fst_height) : min_fst_height;
if (no_resize_fst && !force) return;
if (Math.abs(h - parseInt($("fst").style.height)) < 3 && !force) return;
var exh = (navigator.userAgent.indexOf("MSIE 8") >= 0 ? 1 : navigator.userAgent.indexOf("MSIE 9") >= 0 ? 1 : 0), opt = $("option").clientHeight;
$("fst").style.height = h + 'px';
$("option").style.top = h + 2 + exh*5 + 'px';
$("menu").style.top = $("counter-div").style.top = h+3+exh*5 + opt + 'px';
var mh = Math.max($("menu").clientHeight, $("menu2").clientHeight);
$("control").style.height = h+mh+2+exh*5 + opt + 'px';
$("tw").style.top = $("tw2").style.top = $("re").style.top = h+mh+3+exh*4 + opt + 'px';
}
if (navigator.userAgent.indexOf('iPhone') < 0)
window.onresize = function(){ setFstHeight(null, true); }
// 発言文字数カウンタ表示・更新
function updateCount() {
setFstHeight();
if (!no_counter) $("counter-div").style.display = "block";
// for calculate length with shorten URL.
var s = $("fst").value.replace(
/https?:\/\/[^/\s]*[\w!#$%&'()*+,./:;=?~-]*[\w#/+-]/g,
function(t) {return t_co_maxstr.replace(/^http/, t.substr(0, t.indexOf(':')))});
$("counter").innerHTML = Math.floor(isMessage() ? 10000 - charsInTweet(RegExp.$2) : 140 - charsInTweet(footer) - charsInTweet(s));
}
function charsInTweet(text) {
var chars = 0;
text.split('').forEach(function(c) {
var code = c.charCodeAt(0);
chars += ((code >= 0 && code <= 0x10ff) || (code >= 0xd800 && code <= 0xdfff)) ? 0.5 : 1;
});
return chars;
}
// フォームのフォーカス解除時の処理
function blurFst() {
if ($("fst").value == "") setReplyId(false);
}
// フォームの初期化
function resetFrm(arg) {
document.frm.reset();
$("api_args").innerHTML = "";
if ($("imgup")) $("option").removeChild($("imgup"));
setReplyId(false);
if ($("counter-div").style.display == "block") updateCount();
setFstHeight(min_fst_height, true);
callPlugins("resetFrm", arg);
}
// reply先の設定/解除
function setReplyId(id, tw_id) {
var t;
if (in_reply_to_status_id_tw && (t = $(in_reply_to_status_id_tw)))
removeClass(t, 'inrep');
else if (in_reply_to_status_id) for (var i = 0; i < 3; i++) {
t = $(['tw-','re-','tw2c-'][i]+in_reply_to_status_id);
if (t) removeClass(t, 'inrep');
}
in_reply_to_status_id = id;
in_reply_to_status_id_tw = tw_id;
if (tw_id)
addClass($(tw_id), 'inrep');
else if (id) for (i = 0; i < 3; i++) {
t = $(['tw-','re-','tw2c-'][i]+id);
if (t) addClass(t, 'inrep');
}
}
// reply先を設定
function replyTo(user, id, tw_id, direct) {
in_reply_to_user = user;
var head = (direct || selected_menu.id == "direct" ? "d " : "@") + user + " ";
var ele = $(tw_id);
if (!direct && selected_menu.id != "direct" && reply_to_all && ele) {
var tw = ele.tw.retweeted_status || ele.tw;
var users = text(tw).match(/@\w+/g);
if (users)
head = head + (users.uniq().join(" ")+" ").replace(head, '').replace('@'+myname+' ', '');
}
if (document.frm.status.value.toLowerCase().indexOf(head.toLowerCase()) !== 0) // 連続押しガード
document.frm.status.value = head + document.frm.status.value;
setReplyId(id, tw_id);
document.frm.status.select();
}
// reply先を表示
function dispReply(user, id, ele, cascade) {
user_picks.push(user);
var e = !cascade && (window.event || arguments.callee.caller.arguments[0]);
var shiftkey = e && (e.shiftKey || e.modifiers & 4);
var td = $((selected_menu.id == "TL" ? "tw" : selected_menu.id == "reply" ? "re" : "tw2c") + "-" + id);
if (td && td.style.display == "none") td = null;
var rd = $('reps-' + id);
// 通常 → 反転表示 (rdあり) or オーバーレイ表示
// shiftキー → 反転表示 (td優先) or オーバーレイ表示(td/rdなし)
var d = shiftkey ? td || rd : rd || td;
if (!shiftkey && !rd || shiftkey && !d || cascade) {
// オーバーレイ表示
var ele_top = cumulativeOffset(ele)[1] + 20;
if (ele.parentNode.parentNode.id == "reps" || ele.parentNode.parentNode.parentNode.id == "reps" || cascade)
rep_trace_id = id;
else
rep_top = ele_top;
d = d || $("tw-" + id) || $("re-" + id) || $("tw2c-" + id);
if (d && d.tw) {
dispReply2(d.tw);
return;
}
if (cascade) return;
reply_ele = xds.load_default(twitterAPI + 'statuses/show/'+id+'.json?' +
default_api_args_tl, dispReply2, reply_ele);
return;
}
// 反転表示
if (d.parentNode.id != 'reps')
closeRep();
scrollToDiv(d);
addClass(d, 'emp');
setTimeout(function(){ removeClass(d, 'emp'); }, 2000);
}
// reply先をoverlay表示
function dispReply2(tw) {
if (tw.errors) return error('', tw);
var id = tw.id_str || tw.id;
if ($('rep').style.display == 'block' && $('reps-'+id)) // already displayed
return;
var el = document.createElement("div");
el.id = 'reps-'+id;
el.innerHTML = makeHTML(tw, false, 'reps');
el.tw = tw;
callPlugins("newMessageElement", el, tw, 'reps');
if (!rep_trace_id || id != rep_trace_id) {
$('reps').innerHTML = '';
$('rep').style.top = rep_top + 'px';
} else
$('reps').appendChild(document.createElement('hr'));
$('reps').appendChild(el);
openRep();
scrollToDiv(el);
user_picks.push(tw.user.screen_name);
var in_reply_to = tw.in_reply_to_status_id_str || tw.in_reply_to_status_id;
if (in_reply_to) {
var d = $("tw-" + in_reply_to) || $("re-" + in_reply_to) || $("tw2c-" + in_reply_to);
if (d)
dispReply(tw.user.screen_name, in_reply_to, $('reps') /* この引数は使われない */, true);
}
}
// replyのoverlay表示を閉じる
function closeRep() {
callPlugins('closeRep');
var rep = $('rep');
rep.style.display = 'none';
removeClass(rep.getElementsByClassName('both')[0], 'hide');
$('reps').innerHTML = '';
rep_trace_id = null;
user_picks = [];
}
function openRep(hideBoth) {
var rep = $('rep'), both = rep.getElementsByClassName('both')[0];
if (hideBoth) addClass(both, 'hide');
rep.style.display = 'block';
}
function addClass(ele, className) {
var classList = ele.className.split(' ').filter(function(c) { return c !== ''; });
if (classList.some(function(c) { return c === className; })) return;
classList.push(className);
ele.className = classList.join(' ');
}
function removeClass(ele, className) {
ele.className = ele.className.split(' ').filter(function(c) {
return c !== '' && c !== className;
}).join(' ');
}
// quotedStatusをoverlay表示
function overlayQuoted(ele) {
ele = ele.parentNode.parentNode;
rep_top = cumulativeOffset(ele)[1];
var tw = ele.parentNode.parentNode.tw;
closeRep();
setTimeout(function(){ dispReply2((tw.retweeted_status || tw).quoted_status); }, 0);
return false;
}
// replyからユーザ間のタイムラインを取得
function pickup2() {
user_picks = user_picks.uniq();
if (user_picks.length < 2) return;
switchUser(user_picks.join());
}
// ポップアップメニューの初期化
function popup_init() {
var popup_id_list = ['popup_link_user', 'popup_link_status', 'popup_status_delete',
'popup_status_retweet', 'popup_status_quote', 'popup_status_href',
'upopup_user_block', 'upopup_user_unblock', 'upopup_user_spam'];
for (var x = 0; x < popup_id_list.length; x++)
$(popup_id_list[x]).innerHTML = _($(popup_id_list[x]).innerHTML);
}
// ポップアップメニューを表示
function popup_menu(user, id, ele) {
popup_user = user;
popup_id = id;
popup_ele = ele.parentNode.parentNode;
callPlugins("popup", $('popup'), user, id, ele);
$('popup_link_user').href = twitterURL + user;
$('popup_link_status').href = twitterURL + user + '/statuses/' + id;
$('popup_status_delete').style.display = (selected_menu.id == "direct" || popup_ele.tw.user.screen_name == myname ? "block" : "none");
$('popup_status_retweet').style.display = (selected_menu.id != "direct" ? "block" : "none");
$('popup_status_quote').style.display = (selected_menu.id != "direct" ? "block" : "none");
$('popup_status_href').style.display = (selected_menu.id != "direct" ? "block" : "none");
$('popup').style.display = "block";
var pos = cumulativeOffset(ele);
$('popup').style.left = pos[0] < $('popup').offsetWidth - ele.offsetWidth ? 0 : pos[0] - $('popup').offsetWidth + ele.offsetWidth + 'px';
popup_top = pos[1] + 20;
$('popup').style.top = popup_top + 'px';
$('popup_hide').style.height = Math.max(document.body.scrollHeight, $("tw").offsetHeight+$("control").offsetHeight) + 'px';