-
Notifications
You must be signed in to change notification settings - Fork 119
/
vkopt.js
executable file
·12407 lines (11651 loc) · 562 KB
/
vkopt.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
// ==UserScript==
// @name VKOpt 3.x
// @author KiberInfinity( /id13391307 )
// @namespace http://vkopt.net/
// @description Vkontakte Optimizer 3.x
// @include *vkontakte.ru*
// @include *vk.com*
// ==/UserScript==
//
// (c) All Rights Reserved. VkOpt.
//
/* VERSION INFO */
var vVersion = 307;
var vBuild = 181018;
var vVersionRev = 1;
var vPostfix = '';
if (!window.vkopt) window.vkopt={};
var vkopt_defaults = {
config: {
scroll_to_next: false,
ad_block: true,
skip_away: true,
compact_audio: false,
audio_full_title: false,
disable_border_radius: false,
audio_dl: true,
audio_wait_hover: true,
vid_dl: true,
audio_size_info: false,
audio_clean_titles: false,
audio_album_info: true,
//size_info_on_ctrl: true,
scrobbler: true,
im_dialogs_right: false,
dont_cut_bracket: false,
postpone_custom_interval: true,
pv_comm_move_down: false,
calc_age: true,
audio_pos: false,
old_unread_msg: false,
old_unread_msg_bg: 'c5d9e7',
im_recent_emoji: false,
ru_vk_logo: false,
//hide_big_like: false,
hide_left_set: false,
hide_recommendations: false,
show_full_user_info: false,
switch_kbd_lay: true,
show_online_status: false,
show_common_group: false,
common_group_color: '90ee90',
dislikes_enabled: false,
dislike_icon_index: 1,
//disabled:
im_store_h: false,
//Extra:
vkopt_guide: true, // показываем, где находится кнопка настроек, до тех пор, пока в настройки всё же не зайдут
photo_replacer: true,
audio_more_acts: true, // доп. менюшка для каждой аудиозаписи
vk_audio_icon_dots: false, // иконка аудио "действия/скачать" в виде трех точек
//audio_dl_acts_2_btns: false, // разделить на аудио кнопки скачивания и меню доп.действий
audio_force_flash: false, // принудительно использовать Flash для аудио-плеера
im_hide_dialogs: false, // Новый стиль диалогов. Полотно переписки на всю ширину, список диалогов скрывается при клике по истории, показ списка - клик по заголовку переписки
attach_media_by_id: true, // при вставке айди медиа в поле поиска из диалога прикрепления, в диалог подгружается медиа-файл с этим айди
datepicker_inj: true, // активна ли инъекция в конструктор DatePicker'а
zodiak_ophiuchus:false, // 13ый знак зодиака, Змееносец, между 30 ноября и 17 декабря
photo_search_copy: true,
ph_download_with_name: false,
stealth_addons: true, // прикидываемся перед ТП, что у нас не стоит расширение для скачивания.
im_block_typing: false,
im_block_mark_read: false,
gim_block_typing: false,
gim_block_mark_read: false,
accept_more_cats: true,
lastfm_enable_scrobbling: false,
lastfm_token: '',
lastfm_username: 'NO_AUTH',
lastfm_session_key: '',
//Consts:
SAVE_MSG_HISTORY_PATTERN: "%username% (%date%):\r\n%message%\r\n%attachments%\r\n\r\n",
SAVE_MSG_HISTORY_DATE_FORMAT: "HH:MM:ss dd/mm/yyyy",
AUDIO_INFO_LOAD_THREADS_COUNT: 5,
AUTO_LIST_DRAW_ROWS_INJ: true, // На случай, если инъекция будет убивать редер автоподгружаемых списков
MAX_CACHE_AUDIO_SIZE_ITEMS: 10000 // максимальное количество запомненных размеров аудио в локальном хранилище
},
popular: [
'dislikes_enabled',
'scroll_to_next',
'pv_comm_move_down',
'disable_border_radius'
],
disabled_modules: [
/*
"res",
"settings",
"lang",
"owners",
"away",
"photoview",
"photos",
"audio",
"scrobbler",
"audio_info",
"audioplayer",
"videoview",
"messages",
"attacher",
"face",
"profile",
"groups",
"wall",
"friends",
"support",
"test_module",
"turn_blocks",
"vk_dislike"
*/
]
};
var vkopt_core = {
disallow_location: /\/m\.vk\.com|login\.vk\.com|oauth\.vk\.com|al_index\.php|frame\.php|widget_.+php|notifier\.php|audio\?act=done_add/i,
dom_ready: function(fn, ctx){
var ready, timer;
var onChange = function (e) {
if (!window.IDL || !window.VK_LANGS) return; // Ждём vk_lib.js и vklang.js
if (document.getElementById('footer') || document.getElementById('footer_wrap')) {
fireDOMReady();
} else if (e && e.type == "DOMContentLoaded") {
fireDOMReady();
} else if (e && e.type == "load") {
fireDOMReady();
} else if (document.readyState) {
if ((/loaded|complete/).test(document.readyState)) {
fireDOMReady();
} else if (!!document.documentElement.doScroll) {
try {
ready || document.documentElement.doScroll('left');
} catch (e) {
return;
}
fireDOMReady();
}
}
};
var fireDOMReady = function () {
if (!ready) {
ready = true;
fn.call(ctx || window);
if (document.removeEventListener)
document.removeEventListener("DOMContentLoaded", onChange, false);
document.onreadystatechange = null;
window.onload = null;
clearInterval(timer);
timer = null;
}
};
if (document.addEventListener)
document.addEventListener("DOMContentLoaded", onChange, false);
document.onreadystatechange = onChange;
timer = setInterval(onChange, 5);
window.onload = onChange;
},
init: function(){
if (vkopt_core.disallow_location.test(document.location.href)) return;
//TODO: тут ещё бы дождаться подгрузки vk_lib.js
vkopt_core.dom_ready(function(){
// if (!isNewVk()) return;
if (!window.StaticFiles){
console.log('avoid vkopt init');
} else {
console.log('init vkopt 3.x');
vkopt_core.run();
}
});
},
run: function(){
// Под новый дизайн чуть другие функции работы с локализацией.
vkopt.lang.override(); // TODO: убрать этот костыль при удалении скриптов для старого дизайна
vkopt.settings.init_defaults();
for (var key in StaticFiles)
if (StaticFiles[key].t == 'js' && StaticFiles[key].l)
vk_glue.inj_to_file(key);
vkopt_core.plugins.on_init();
vk_glue.nav_handler();
window.vkopt_core_ready = true;
vkCheckUpdates();
},
timeout: function(fn, t){
return window['set'+'Timeout'](fn,t);
},
mod_str_as_node: function(str, func, params){
if (!str || str.tagName)
return str;
var is_table = str.substr(0,3)=='<tr';
var div = vkCe(is_table?'table':'div');
div.innerHTML = str;
func(div,params);
var txt = div.innerHTML;
if (is_table && txt.substr(0,7) == "<tbody>")
txt = txt.substr(7,txt.length-15);
return txt;
//TODO: call to plugins
},
setLoc: function(new_location){ // использовать вместо nav.setLoc для избежания рекурсии, обход реакции на смену URL'а
nav.setLoc(new_location,'vkopt');
},
plugins: {
delayed_run: function(plug_id){ //функция для пуска отдельного плагина, который не был подключен до основного запуска вкопта
// сначала прописываем в vkopt_defaults.config данные о значениях опций по умолчанию
var options_list = vkopt_core.plugins.call_method(plug_id, 'onSettings');
vkopt.settings.update_defaults(options_list);
// добавляем стили модуля в страницу
var css = vkopt_core.plugins.get_css(plug_id);
if (css != '')
vkopt.set_css(css, 'vkopt_'+plug_id+'_styles');
vkopt_core.plugins.call_method(plug_id, 'onInit');
vkopt_core.plugins.call_modules('onModuleDelayedInit', plug_id); // сообщаем всем модулям о подключении опоздавшего
for (var key in StaticFiles)
if (StaticFiles[key].t == 'js')
vkopt_core.plugins.call_method(plug_id, 'onLibFiles', key);
vkopt_core.plugins.call_method(plug_id, 'onLocation', nav.objLoc, cur.module);
vkopt_core.plugins.call_method(plug_id, 'processNode', null, {source:'delayed_run'});
},
call_method: function(){ // (plug_id, method, arg1, arg2 ...)
var args = Array.prototype.slice.call(arguments);
var plug_id = args.shift();
var method = args.shift();
//Предотвращаем вызов обработчиков у отключенных модулей
if (vkopt_defaults.disabled_modules.indexOf(plug_id) > -1)
return;
var field = vkopt[plug_id][method];
if (field) // TODO: && isModuleEnabled(plug_id)
return isFunction(field) ? field.apply(this, args) : field;
},
call_modules: function(){ // (method, arg1, arg2 ...)
var args = Array.prototype.slice.call(arguments);
var results = {};
for (var plug_id in vkopt){
var res = vkopt_core.plugins.call_method.apply({plugin_id:plug_id}, [plug_id].concat(args));
if (res != undefined) results[plug_id] = res;
}
return results;
},
on_init:function(){
vkopt_core.plugins.add_css();
vkopt_core.plugins.call_modules('onInit');
vkopt_core.plugins.process_node(ge('page_body'));
},
add_css:function(){
var code = '';
if (!vkopt.settings.get('style_per_module')){
for (var plug_id in vkopt)
code += vkopt_core.plugins.get_css(plug_id);
vkaddcss(code);
} else {
for (var plug_id in vkopt){
code = vkopt_core.plugins.get_css(plug_id);
code && vkopt.set_css(code,'vkopt_module_'+plug_id);
}
}
},
get_css:function(plug_id){
var css = vkopt[plug_id].css;
if (!css) return '';
return (Object.prototype.toString.call(css) === '[object Function]')?css():css;
},
on_js_file: function(file){
//console.log('on *.js: '+file);
vkopt_core.plugins.call_modules('onLibFiles', file);
},
on_location: function(){
//console.log('on nav: ', cur.module, ' obj: ', JSON.stringify(nav.objLoc));
vkopt_core.plugins.call_modules('onLocation', nav.objLoc, cur.module);
},
on_ajax_post: function(url, query, options){
var res = vkopt_core.plugins.call_modules('onRequestQuery', url, query, options);
if (url === 'al_im.php' && query.act === 'a_send') {
res = extend(res, vkopt_core.plugins.call_modules('onImSend', query));
}
for (var i in res)
if (res[i] === false)
return false;
return true;
},
process_response: function(answer, url, q){
// answer - массив, элементы которого в последствии становятся аргументами вызываемых колбеков. можно править его элементы
var _rx = /^\s*<(div|table|input|a)/i;
for (var i=0; i < answer.length; i++){
if (typeof answer[i]=='string' && _rx.test(answer[i]) ){
answer[i] = vkopt_core.mod_str_as_node(answer[i], vkopt_core.plugins.process_node, {source:'process_response', url:url, q:q});
}
else if (isArray(answer[i])){
var sub = answer[i];
for (var j = 0; j < sub.length; j++)
if (typeof sub[j]=='string' && _rx.test(sub[j]) ){
sub[j] = vkopt_core.mod_str_as_node(sub[j], vkopt_core.plugins.process_node, {source:'process_response', url:url, q:q});
}
}
}
// для случаев, когда тело html'а передано не отдельным аргументом, а внутри какого-то JSON'а:
if (url === '/al_im.php' && q.act == 'a_start' && answer[0] && answer[0].history){ // открытие диалога
answer[0].history = vkopt_core.mod_str_as_node(answer[0].history, vkopt_core.plugins.process_node, {source:'process_response_im_a_start', url:url, q:q});
}
vkopt_core.plugins.call_modules('onResponseAnswer', answer,url,q);
},
process_node: function(node, params){
node = node || ge('content');
var nodes=node.getElementsByTagName('a');
for (var i=0;i<nodes.length;i++)
vkopt_core.plugins.process_links(nodes[i],params);
//if (params && params.source = 'process_response' )
vkopt_core.plugins.call_modules('processNode', node, params);
},
process_links:function(link_el, params){
vkopt_core.plugins.call_modules('processLinks', link_el, params);
},
on_cmd: function(data){ // listen messages for communicate between tabs
vkopt_core.plugins.call_modules('onCmd', data);
},
eltt_first_show: function(ett){
vkopt_core.plugins.call_modules('onElementTooltipFirstTimeShow', ett, ett._opts);
},
/*
inline_dd_create: function(el, opts){
vkopt_core.plugins.call_modules('onInlineDropdownCreate', el, opts);
},
*/
datepicker_create: function(){
vkopt_core.plugins.call_modules('onDatepickerCreate', Array.prototype.slice.call(arguments));
}
}
};
var vk_glue = {
inj_handler: function(files){ // call from stManager.add(files, callback, async) -> vk_glue.inj_handler(files)
return function(no_pending){
if (no_pending)
console.log('no need inject?', files);
if (!isArray(files)) files = [files];
for (var i in files){
if (files[i].indexOf('.js') != -1)
vk_glue.inj_to_file(files[i]);
}
}
},
inj_to_file: function(file_name){
switch (file_name){
case 'common.js':
case 'common_web.js':
case 'cmodules/web/common_web.js':
vk_glue.inj.common(); break;
case 'auto_list.js': vk_glue.inj.auto_list(); break;
case 'ui_controls.js': vk_glue.inj.ui_controls(); break;
case 'datepicker.js': vk_glue.inj.datepicker(); break;
case 'notifier.js': vk_glue.inj.notifier(); break;
}
vkopt_core.plugins.on_js_file(file_name);
},
inj: {
common: function(){
// перехватываем момент подключения скриптов:
//Inj.BeforeR("stManager.add",/__stm._waiters.push\(\[([^,]+)/,"__stm._waiters.push([$1, vk_glue.inj_handler(#ARG0#)]);");
Inj.End("stManager.add",function(files, callback, asyn){
var f, wait = [];
if (!isArray(files))
files = [files];
for (var i in files){
f = files[i];
if (!f) continue;
if (f.indexOf('?') != -1)
f = f.split('?')[0];
if (!StaticFiles[f].l)
wait.push(f);
}
if (wait.length)
__stm._waiters.push([wait, vk_glue.inj_handler(files)]);
});
// следующая строка не факт что нужна (а может оптимизированней будет, если её убрать), т.к она срабатывает только если у нас нет списка ожидания,
// т.е скрипты были ранее уже подгружены на страницу, и инъекции вероятно остались на месте.
//Inj.BeforeR("stManager.add",/(if\s*\(![a-zA-z_]+.length\))/,"$1{vk_glue.inj_handler(#ARG0#)(true);}"); //"_matched_{vk_glue.inj...
// перехват события об аякс загрузке новой страницы / смене URL'а
Inj.End('nav.setLoc',function(){
if (arguments[1]!="vkopt")
setTimeout(vk_glue.nav_handler,2);
});
// Ловим момент, когда через extend меняют информацию о текущем модуле страницы
Inj.End('extend', function(obj, obj2){
if (obj && obj2 && window.cur && obj == cur && obj2.module)
setTimeout(vk_glue.nav_handler,2);
})
// Перехватываем результат ajax-запросов с возможностью модификации перед колбеком
Inj.Start('ajax._post',
// ARG0 - url; ARG1 - query object; ARG2 - options
function(url, query, options){
// Mod callback:
var ctx = this;
if (ctx.__ARG2__){
var onDoneOrig = ctx.__ARG2__.onDone;
ctx.__ARG2__.onDone = function(){
var argarr = Array.prototype.slice.call(arguments);
vk_glue.response_handler(argarr, ctx.__ARG0__, ctx.__ARG1__);
onDoneOrig && onDoneOrig.apply(window, argarr);
}
}
// End of callback mod
}
);
// айфремовая загрузка выглядит так - загрузили каркас с частью данных, дальше по ходу загрузки айфреймовой страницы выполняются куски заполнения элементов карскаса.
// эти кучки тоже надо перехватывать.
Inj.Start('ajax.framegot',function(cont, html, js, params){
if (this.args && this.args[1])
this.args[1]=vk_glue.process_on_framegot(this.args[1]);
});
// Можем модифицировать поля запроса перед отсылкой ajax-запроса, либо заблокировать его
Inj.Start('ajax.post',function(url, query, options){
if (vk_glue.process_on_post(url, query, options) === false)
this.prevent = true;
});
// цепляемся к возвращению обработанного шаблона из getTemplate
Inj.End('getTemplate',function(tplName, state){
// если исходная функция что-то вернула
if (this.result){
// возвращаем модифицированный ответ
this.return_result = vk_glue.tpl_hook(this.result, tplName, state)
this.prevent_all = true;
}
})
/*
Inj.Start('renderFlash','vkOnRenderFlashVars(vars);');
*/
// перехват тултипов при создании их контента. например для перехвата создания меню "Ещё" перед его показом в просмотрщике фото
Inj.Start('ElementTooltip.prototype.show', function(){
var handle = function(){
vkopt_core.plugins.eltt_first_show(this);
}
var obj = this.this_obj;
if (obj._opts){
if (obj._opts.onFirstTimeShow){
var orig = obj._opts.onFirstTimeShow;
obj._opts.onFirstTimeShow = function(){
var args = Array.prototype.slice.call(arguments);
handle.apply(obj, args);
orig.apply(obj, args);
}
} else {
obj._opts.onFirstTimeShow = handle;
}
}
});
},
notifier: function(){
Notifier.addRecvClbk('vkcmd', 0, function(data){
vkopt_core.plugins.on_cmd(data);
}, true);
},
auto_list: function(){
if (vkopt_defaults.config.AUTO_LIST_DRAW_ROWS_INJ){
Inj.End('AutoList.prototype._drawRows',function(t){
var s = this.this_obj;
var N = 0;
each(t, function(i, o) {
if ("string" == typeof o) // копипаст фильтра из _drawRows
N++; // считаем количество элементов, которые должны были быть вставлены
});
var new_rows = domChildren(s._containerEl).slice(-N); // получаем список из N последних вставленных элементов
for (var i = 0; i < new_rows.length; i++)
vkopt_core.plugins.process_node(new_rows[i]);
})
}
// Inj.Replace('AutoList.prototype._drawRows',/\.appendChild\(([A-Za-z_0-9]+)\)/,'$&; vkopt_core.plugins.process_node($1);');
// Inj.End('AutoList.prototype._drawRows', '; vkopt_core.plugins.process_node(this._containerEl);'); // Другой вариант. Меньше шансов того, что отвалится, но тут выходит повторная обработка ранее выведенного.
},
ui_controls: function(){
/*
var orig = InlineDropdown; // бекап
Inj.Start('InlineDropdown','vkopt_core.plugins.inline_dd_create(#ARG0#, #ARG1#);'); // Инжект в конструктор не работает с текущим враппером функций из обновленного Inj
for (var method in orig.prototype) //восстанавливаем методы из бекапа
InlineDropdown.prototype[method] = orig.prototype[method];
*/
},
datepicker: function(){
if (!vkopt.settings.get('datepicker_inj'))
return;
// передаём в наш перехватчик id элемента в котором указана дата.
if (!window.vkorigDatepicker || (window.Datepicker && Datepicker.toString().indexOf('onDatepickerCreate') == -1)){
window.vkorigDatepicker = window.Datepicker;
window.Datepicker = function(el, options){
// moved from vkopt.wall.onLibFiles mod. Attach to this by event onDatepickerCreate
var args = Array.prototype.slice.call(arguments);
vkopt_core.plugins.datepicker_create.apply(this, args);
vkorigDatepicker.apply(this, args);
}
}
}
},
nav_handler: function(){ //TODO: debounce?
// тут какие-то системные действия движка до передаче события в плагины
// ...
vkopt_core.plugins.on_location();
},
process_on_framegot: function(html){
return vkopt_core.mod_str_as_node(html, vkopt_core.plugins.process_node);
},
process_on_post: function(url, query, options){
return vkopt_core.plugins.on_ajax_post(url, query, options);
},
response_handler: function(answer,url,q){
// try{
vkopt_core.plugins.process_response(answer, url, q);
// catch(e){
// vkopt_core.ping_stat({type: 'fail', source: 'response_handler', url: url, q: q ? q.act : ''})
// }
},
tpl_hook: function(html, tpl_name, state){
// Сообщаем модулям, что нужно как элемент обработать содержимое возвращаемое функцией getTemplate
return vkopt_core.mod_str_as_node(html, vkopt_core.plugins.process_node, {source:"getTemplate", tpl_name: tpl_name, state: state})
}
};
/*
(function(){
window.vkopt = (window.vkopt || {});
var m = {
id: 'vkopt_any_plugin',
// <core>
onInit: function(){}, // выполняется один раз после загрузки стрницы
onLibFiles: function(file_name){}, // место для инъекций = срабатывает при подключении нового js-файла движком контакта.
onLocation: function(nav_obj,cur_module_name){}, // вызывается при переходе между страницами
onRequestQuery: function(url, query, options){} // вызывается перед выполнением ajax.post метода. Если функция вернёт false, то запрос выполнен не будет.
onResponseAnswer: function(answer,url,params){}, // answer - массив, изменять только его элементы
onCmd: function(command_obj){}, // слушает сообщения отосланные из других вкладок вк через vkopt.cmd(command_obj)
processNode: function(node, params){} // обработка элемента
processLinks: function(link, params){}, // обработка ссылки
onModuleDelayedInit: function(plugin_id){}, // реакция на подключение модуля, опоздавшего к загрузке страницы.
onElementTooltipFirstTimeShow: function(ett, ett_options), // реакция на первый показ ElementTooltip, при создании его контента. На момент вызова в элементе ett._ttel уже есть контент. По ett._opts.id можно определить к чему тултип относится.
// UNAVAILABLE! onInlineDropdownCreate: function(el, options), // реакция на создание контрола InlineDropdown. Можно использовать для добавления своих пунктов в options.items для меню элемента el
onDatepickerCreate: function(args){}, // вызывается при создании селектора даты new Datepicker(), args - массив аргументов переданных в конструктор
// <settings>
onSettings: function(){} || {} // возвращаем объект с перечисленными по категориям настройками этого модуля
onOptionChanged: function(option_id, val, option_data){}, // реакция на изменение опции
firstRun: function(){} // вызывается при первом запуске (не найдены ранее прописанные настройки vkopt'a),
// P.S. вкопт из хранилища расширения восстанавливает только данные из своего конфига, если они были сохранены,
// тогда это первым запуском не считается, но в локальном хранилище могут отсутствовать данные от других модулей,
// хранящих инфу не через vkopt.settings.get | vkopt.settings.set
// <im>
onImSend: function(query){} // вызывается перед отправкой личного сообщения. Если функция вернёт false, то сообщение не отправится.
onImReceive: <not implemented yet>
// <audio>
onAudioRowItems: function(audioEl, audioObject, audio){} // добавление кастомных кнопок-иконок (actions) и пунктов в доп. действия (more) для аудио
// результатом вызова функции должен быть объект вида {actions:[item1, item2, ...], more:[item1, item2, ...]}
// а каждый добавляемый пункт имеет вид массива с элементами:
// itemN = [
// id, // id кнопки, добавляется к имени CSS-класса
// function(audioEl, audioObject, audio), // обработчик нажатия на кнопку
// html, // внутреннее содержимое кнопки, для конопок-иконок обычно пустая строка
// attrs, // строка с дополнительными атрибутами
// tagName // если требуется, чтоб тегом кнопки был не "div", а другой, то указывать тут.
// ]
// <photos>
onPhotoAlbumItems: function(aid, oid){} // добавление пунктов в меню действий с альбомом
// результатом вызова функции должен быть массив с объектами, которые могут содержать поля:
// {
// href: ссылка
// item_class: доп. CSS-класс,
// onclick: строка или функция обработчик,
// attrs: доп. HTML атрибуты тега пункта,
// text: название пункта
// }
// aid может быть как числовым, так и вида "tag", "photos", "00", "000"
// <groups>
onGroupActionItems: function(oid, gid){} // добавление пунктов в меню действий на главной странице группы
// результатом вызова функции должен быть массив с объектами, которые могут содержать поля:
// {
// href: ссылка
// item_class: доп. CSS-класс,
// onclick: строка или функция обработчик,
// attrs: доп. HTML атрибуты тега пункта,
// text: название пункта
// }
};
window.vkopt[m.id] = m;
if (window.vkopt_core_ready) vkopt_core.plugins.delayed_run(m.id); // запускает модуль, если мы опоздали к загрузке страницы, провоцирует вызов события onModuleDelayedInit
})();
*/
// vkopt.zipjs library
(function(obj) {
/*
Zip.js
Copyright (c) 2013 Gildas Lormeau. All rights reserved.
Please read copyright notice, list of conditions and the disclaimer https://raw.githubusercontent.com/gildas-lormeau/zip.js/master/WebContent/zip.js
*/
"use strict";
var ERR_WRITE = "Error while writing zip file.";
var ERR_READ_DATA = "Error while reading file data.";
var ERR_DUPLICATED_NAME = "File already exists.";
var CHUNK_SIZE = 512 * 1024;
var appendABViewSupported;
try {
appendABViewSupported = new Blob([ new DataView(new ArrayBuffer(0)) ]).size === 0;
} catch (e) {
}
function Crc32() {
this.crc = -1;
}
Crc32.prototype.append = function append(data) {
var crc = this.crc | 0, table = this.table;
for (var offset = 0, len = data.length | 0; offset < len; offset++)
crc = (crc >>> 8) ^ table[(crc ^ data[offset]) & 0xFF];
this.crc = crc;
};
Crc32.prototype.get = function get() {
return ~this.crc;
};
Crc32.prototype.table = (function() {
var i, j, t, table = []; // Uint32Array is actually slower than []
for (i = 0; i < 256; i++) {
t = i;
for (j = 0; j < 8; j++)
if (t & 1)
t = (t >>> 1) ^ 0xEDB88320;
else
t = t >>> 1;
table[i] = t;
}
return table;
})();
// "no-op" codec
function NOOP() {}
NOOP.prototype.append = function append(bytes, onprogress) {
return bytes;
};
NOOP.prototype.flush = function flush() {};
function getDataHelper(byteLength, bytes) {
var dataBuffer, dataArray;
dataBuffer = new ArrayBuffer(byteLength);
dataArray = new Uint8Array(dataBuffer);
if (bytes)
dataArray.set(bytes, 0);
return {
buffer : dataBuffer,
array : dataArray,
view : new DataView(dataBuffer)
};
}
function blobSlice(blob, index, length) {
if (index < 0 || length < 0 || index + length > blob.size)
throw new RangeError('offset:' + index + ', length:' + length + ', size:' + blob.size);
if (blob.slice)
return blob.slice(index, index + length);
else if (blob.webkitSlice)
return blob.webkitSlice(index, index + length);
else if (blob.mozSlice)
return blob.mozSlice(index, index + length);
else if (blob.msSlice)
return blob.msSlice(index, index + length);
}
// Readers
function Reader() {
}
function BlobReader(blob) {
var that = this;
function init(callback) {
that.size = blob.size;
callback();
}
function readUint8Array(index, length, callback, onerror) {
var reader = new FileReader();
reader.onload = function(e) {
callback(new Uint8Array(e.target.result));
};
reader.onerror = onerror;
try {
reader.readAsArrayBuffer(blobSlice(blob, index, length));
} catch (e) {
onerror(e);
}
}
that.size = 0;
that.init = init;
that.readUint8Array = readUint8Array;
}
BlobReader.prototype = new Reader();
BlobReader.prototype.constructor = BlobReader;
// Writers
function Writer() {
}
Writer.prototype.getData = function(callback) {
callback(this.data);
};
function BlobWriter(contentType) {
var blob, that = this;
function init(callback) {
blob = new Blob([], {
type : contentType
});
callback();
}
function writeUint8Array(array, callback) {
blob = new Blob([ blob, appendABViewSupported ? array : array.buffer ], {
type : contentType
});
callback();
}
function getData(callback) {
callback(blob);
}
that.init = init;
that.writeUint8Array = writeUint8Array;
that.getData = getData;
}
BlobWriter.prototype = new Writer();
BlobWriter.prototype.constructor = BlobWriter;
function FileWriter(fileEntry, contentType) {
var writer, that = this;
function init(callback, onerror) {
fileEntry.createWriter(function(fileWriter) {
writer = fileWriter;
callback();
}, onerror);
}
function writeUint8Array(array, callback, onerror) {
var blob = new Blob([ appendABViewSupported ? array : array.buffer ], {
type : contentType
});
writer.onwrite = function() {
writer.onwrite = null;
callback();
};
writer.onerror = onerror;
writer.write(blob);
}
function getData(callback) {
fileEntry.file(callback);
}
that.init = init;
that.writeUint8Array = writeUint8Array;
that.getData = getData;
}
FileWriter.prototype = new Writer();
FileWriter.prototype.constructor = FileWriter;
function MutableFileWriter(fileHandle, contentType) {
var lockedFile, that = this;
function init(callback) {
//lockedFile = fileHandle.open('readwrite');
callback();
}
function writeUint8Array(array, callback) {
var blob = new Blob([ appendABViewSupported ? array : array.buffer ], {
type : contentType
});
var lockedFile = fileHandle.open('readwrite');
var writing = lockedFile.append(blob)
writing.onsuccess = function(){
callback();
}
writing.onerror = function(){
console.log('Something goes wrong in the writing process: ' + this.error);
}
}
function getData(callback) {
fileHandle.getFile().onsuccess = function () {
callback(this.result);
}
}
that.init = init;
that.writeUint8Array = writeUint8Array;
that.getData = getData;
}
MutableFileWriter.prototype = new Writer();
MutableFileWriter.prototype.constructor = MutableFileWriter;
function launchProcess(process, reader, writer, offset, size, crcType, onprogress, onend, onreaderror, onwriteerror) {
var chunkIndex = 0, index, outputSize = 0,
crcInput = crcType === 'input',
crcOutput = crcType === 'output',
crc = new Crc32();
function step() {
var outputData;
index = chunkIndex * CHUNK_SIZE;
if (index < size)
reader.readUint8Array(offset + index, Math.min(CHUNK_SIZE, size - index), function(inputData) {
var outputData;
try {
outputData = process.append(inputData, function(loaded) {
if (onprogress)
onprogress(index + loaded, size);
});
} catch (e) {
onreaderror(e);
return;
}
if (outputData) {
outputSize += outputData.length;
writer.writeUint8Array(outputData, function() {
chunkIndex++;
setTimeout(step, 1);
}, onwriteerror);
if (crcOutput)
crc.append(outputData);
} else {
chunkIndex++;
setTimeout(step, 1);
}
if (crcInput)
crc.append(inputData);
if (onprogress)
onprogress(index, size);
}, onreaderror);
else {
try {
outputData = process.flush();
} catch (e) {
onreaderror(e);
return;
}
if (outputData) {
if (crcOutput)
crc.append(outputData);
outputSize += outputData.length;
writer.writeUint8Array(outputData, function() {
onend(outputSize, crc.get());
}, onwriteerror);
} else
onend(outputSize, crc.get());
}
}
step();
}
function copy(worker, sn, reader, writer, offset, size, computeCrc32, onend, onprogress, onreaderror, onwriteerror) {
var crcType = 'input';
launchProcess(new NOOP(), reader, writer, offset, size, crcType, onprogress, onend, onreaderror, onwriteerror);
}
// ZipWriter
function encodeUTF8(string) {
return unescape(encodeURIComponent(string));
}
function getBytes(str) {
var i, array = [];
for (i = 0; i < str.length; i++)
array.push(str.charCodeAt(i));
return array;
}
function createZipWriter(writer, callback, onerror) {
var files = {}, filenames = [], datalength = 0;
var deflateSN = 0;
function onwriteerror(err) {
onerror(err || ERR_WRITE);
}
function onreaderror(err) {
onerror(err || ERR_READ_DATA);
}
var zipWriter = {
add : function(name, reader, onend, onprogress, options) {
var header, filename, date;
var worker = this._worker;
function writeHeader(callback) {
var data;
date = options.lastModDate || new Date();
header = getDataHelper(26);
files[name] = {
headerArray : header.array,
directory : options.directory,
filename : filename,
offset : datalength,
comment : getBytes(encodeUTF8(options.comment || ""))
};
header.view.setUint32(0, 0x14000808);
if (options.version)
header.view.setUint8(0, options.version);
header.view.setUint16(6, (((date.getHours() << 6) | date.getMinutes()) << 5) | date.getSeconds() / 2, true);
header.view.setUint16(8, ((((date.getFullYear() - 1980) << 4) | (date.getMonth() + 1)) << 5) | date.getDate(), true);
header.view.setUint16(22, filename.length, true);
data = getDataHelper(30 + filename.length);
data.view.setUint32(0, 0x504b0304);
data.array.set(header.array, 4);
data.array.set(filename, 30);
datalength += data.array.length;
writer.writeUint8Array(data.array, callback, onwriteerror);
}
function writeFooter(compressedLength, crc32) {
var footer = getDataHelper(16);
datalength += compressedLength || 0;
footer.view.setUint32(0, 0x504b0708);
if (typeof crc32 != "undefined") {
header.view.setUint32(10, crc32, true);
footer.view.setUint32(4, crc32, true);
}
if (reader) {
footer.view.setUint32(8, compressedLength, true);
header.view.setUint32(14, compressedLength, true);
footer.view.setUint32(12, reader.size, true);
header.view.setUint32(18, reader.size, true);
}
writer.writeUint8Array(footer.array, function() {
datalength += 16;
onend();
}, onwriteerror);
}
function writeFile() {
options = options || {};
name = name.trim();
if (options.directory && name.charAt(name.length - 1) != "/")
name += "/";
if (files.hasOwnProperty(name)) {
onerror(ERR_DUPLICATED_NAME);
return;
}
filename = getBytes(encodeUTF8(name));
filenames.push(name);
writeHeader(function() {
if (reader)
copy(worker, deflateSN++, reader, writer, 0, reader.size, true, writeFooter, onprogress, onreaderror, onwriteerror);
else
writeFooter();
}, onwriteerror);
}
if (reader)
reader.init(writeFile, onreaderror);
else
writeFile();
},
close : function(callback) {
if (this._worker) {
this._worker.terminate();
this._worker = null;
}
var data, length = 0, index = 0, indexFilename, file;
for (indexFilename = 0; indexFilename < filenames.length; indexFilename++) {
file = files[filenames[indexFilename]];
length += 46 + file.filename.length + file.comment.length;
}
data = getDataHelper(length + 22);
for (indexFilename = 0; indexFilename < filenames.length; indexFilename++) {