Repository navigation
Expand file tree
/
Copy pathspider.py
More file actions
1046 lines (965 loc) · 48.8 KB
/
Copy pathspider.py
File metadata and controls
1046 lines (965 loc) · 48.8 KB
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
"""TV Python 功能範例;配置與接口說明見 CatVodSpider/docs/development.md。"""
import json
import re
import tempfile
import time
from io import BytesIO
from pathlib import Path
from urllib.parse import quote, unquote, urlsplit
from base.spider import Spider as BaseSpider
PAGE_SIZE = 4
SEARCH_ALL_KEYWORD = "示範"
REQUEST_TIMEOUT_MS = 15000
VIDEO_SUFFIXES = (".m3u8", ".mpd", ".mp4", ".mkv", ".flv", ".mp3", ".m4a", ".aac")
CACHE_KEY = "python_spider_demo_message"
CACHE_VALUE = {"value": "範例資料", "items": [1, True, None]}
WASM_BYTES = bytes.fromhex("0061736d0100000001070160027f7f017f030201000707010361646400000a09010700200020016a0b")
COOKIE_NAME_PATTERN = re.compile(r"^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$")
# 真實爬蟲可把這個 tuple 換成 API 或 HTML 解析結果,其餘介面保持不變。
CATALOG = (
{
"id": "demo-01", "name": "星光探險隊", "genre": "動畫", "area": "台灣",
"year": "2026", "director": "林導演", "actors": ("小安", "小晴"),
"remark": "更新至 3 集", "episodes": ("第 1 集", "第 2 集", "第 3 集"),
"content": "一群朋友追尋失落星圖的原創示範故事。",
},
{
"id": "demo-02", "name": "城市觀察日記", "genre": "紀錄", "area": "日本",
"year": "2026", "director": "周導演", "actors": ("阿杰", "小美"),
"remark": "全 2 集", "episodes": ("上集", "下集"),
"content": "從日常交通與市場觀察城市生活。",
},
{
"id": "demo-03", "name": "料理研究室", "genre": "綜藝", "area": "韓國",
"year": "2025", "director": "陳導演", "actors": ("小晴", "大宇"),
"remark": "更新至 4 集", "episodes": ("第 1 集", "第 2 集", "第 3 集", "第 4 集"),
"content": "用常見食材完成四道家常料理。",
},
{
"id": "demo-04", "name": "午後推理社", "genre": "戲劇", "area": "台灣",
"year": "2025", "director": "李導演", "actors": ("阿杰", "若葉"),
"remark": "全 3 集", "episodes": ("線索", "追蹤", "答案"),
"content": "三位社員從校園小事練習推理。",
},
{
"id": "demo-05", "name": "海邊小旅行", "genre": "紀錄", "area": "台灣",
"year": "2024", "director": "周導演", "actors": ("大宇",),
"remark": "正片", "episodes": ("正片",),
"content": "沿著海岸記錄自然景色與地方文化。",
},
{
"id": "demo-06", "name": "節奏練習生", "genre": "綜藝", "area": "日本",
"year": "2024", "director": "陳導演", "actors": ("小美", "若葉"),
"remark": "全 2 集", "episodes": ("預賽", "決賽"),
"content": "表演者以節奏合作完成舞台任務。",
},
{
"id": "demo-07", "name": "紙飛機計畫", "genre": "動畫", "area": "日本",
"year": "2023", "director": "林導演", "actors": ("若葉", "小安"),
"remark": "全 3 集", "episodes": ("起飛", "風向", "返航"),
"content": "紙飛機乘著不同風向展開旅程。",
},
{
"id": "demo-08", "name": "轉角咖啡店", "genre": "戲劇", "area": "韓國",
"year": "2023", "director": "李導演", "actors": ("大宇", "小晴"),
"remark": "全 2 集", "episodes": ("相遇", "再會"),
"content": "一間咖啡店串起幾段溫暖的日常。",
},
{
"id": "demo-09", "name": "機器人運動會", "genre": "動畫", "area": "韓國",
"year": "2022", "director": "林導演", "actors": ("阿杰", "小美"),
"remark": "全 4 集", "episodes": ("開幕", "接力", "決勝", "閉幕"),
"content": "小型機器人組隊參加創意競賽。",
},
{
"id": "demo-10", "name": "深夜電台", "genre": "戲劇", "area": "台灣",
"year": "2022", "director": "李導演", "actors": ("小安", "大宇"),
"remark": "正片", "episodes": ("正片",),
"content": "主持人透過來電聽見城市裡的故事。",
},
{
"id": "demo-11", "name": "週末任務隊", "genre": "綜藝", "area": "韓國",
"year": "2021", "director": "陳導演", "actors": ("若葉", "小晴"),
"remark": "全 3 集", "episodes": ("任務一", "任務二", "任務三"),
"content": "成員分組完成城市探索任務。",
},
{
"id": "demo-12", "name": "山林的一天", "genre": "紀錄", "area": "日本",
"year": "2021", "director": "周導演", "actors": ("小美",),
"remark": "正片", "episodes": ("正片",),
"content": "以一天的時間觀察山林生態。",
},
)
def _filter_rows():
"""每次建立新物件,避免呼叫端若修改選取狀態時污染後續結果。"""
return [
{
"key": "sort", "name": "排序", "init": "latest",
"value": [
{"n": "最新", "v": "latest"},
{"n": "最早", "v": "oldest"},
{"n": "名稱", "v": "name"},
],
},
{
"key": "genre", "name": "類型", "init": "all",
"value": [{"n": "全部", "v": "all"}] + [
{"n": name, "v": name} for name in ("動畫", "戲劇", "綜藝", "紀錄")
],
},
{
"key": "area", "name": "地區", "init": "all",
"value": [{"n": "全部", "v": "all"}] + [
{"n": name, "v": name} for name in ("台灣", "日本", "韓國")
],
},
{
"key": "year", "name": "年份", "init": "all",
"value": [{"n": "全部", "v": "all"}] + [
{"n": year, "v": year} for year in ("2026", "2025", "2024", "2023", "2022", "2021")
],
},
]
class Spider(BaseSpider):
def init(self, extend=""):
if not isinstance(extend, str):
raise ValueError("Site.ext 必須是 JSON 物件")
try:
options = json.loads(extend) if extend else {}
except json.JSONDecodeError:
raise ValueError("Site.ext 必須是 JSON 物件") from None
if not isinstance(options, dict):
raise ValueError("Site.ext 必須是 JSON 物件")
if options.get("request_options") is not None and not isinstance(options["request_options"], dict):
raise ValueError("request_options 必須是物件")
self.options = options
self.socket = None
self.socket_state = {"state": "未連線", "text": 0, "binary": 0}
self.cache_key = CACHE_KEY
self.image_base = str(options.get("image_base") or "").rstrip("/")
self.web_url = str(options.get("web_url") or "https://example.com/")
self.request_url = str(options.get("request_url") or self.web_url)
self.cookie_name = str(options.get("cookie_name") or "").strip()
if self.cookie_name and not COOKIE_NAME_PATTERN.fullmatch(self.cookie_name):
raise ValueError("cookie_name 格式無效")
self._absolute_url(self.web_url, "web_url")
self._absolute_url(self.request_url, "request_url")
def homeContent(self, filter):
result = {
"class": [
{"type_id": "vod_portrait", "type_name": "VOD 直式"},
{"type_id": "vod_landscape", "type_name": "VOD 橫式"},
{"type_id": "vod_oval", "type_name": "VOD 圓形"},
{"type_id": "vod_list", "type_name": "VOD 列表"},
{"type_id": "class_landscape", "type_name": "分類橫式", "land": 1, "ratio": 1.78},
{"type_id": "class_oval", "type_name": "分類圓形", "circle": 1, "ratio": 1.0},
{"type_id": "folders", "type_name": "資料夾", "type_flag": "1"},
{"type_id": "actions", "type_name": "互動功能", "type_flag": "1"},
]
}
if filter:
result["filters"] = {
type_id: _filter_rows()
for type_id in (
"vod_portrait", "vod_landscape", "vod_oval", "vod_list",
"class_landscape", "class_oval",
)
}
return result
def homeVideoContent(self):
# 第一筆 VOD 的 style 決定整個首頁區塊,因此每筆都保持相同橫式樣式。
items = [self._card(item, "landscape") for item in CATALOG[:PAGE_SIZE]]
return {"list": items}
def categoryContent(self, tid, pg, filter, extend):
extend = extend if isinstance(extend, dict) else {}
if tid == "actions":
items = self._action_cards()
elif tid == "folders":
items = self._folder_cards()
elif tid.startswith("folder/genre/"):
genre = unquote(tid.removeprefix("folder/genre/"))
items = [self._card(item, "list") for item in CATALOG if item["genre"] == genre]
elif tid.startswith("folder/area/"):
area = unquote(tid.removeprefix("folder/area/"))
items = [self._card(item, "list") for item in CATALOG if item["area"] == area]
elif tid.startswith("actor/"):
actor = unquote(tid.removeprefix("actor/"))
items = [self._card(item, "list") for item in CATALOG if actor in item["actors"]]
elif tid.startswith("director/"):
director = unquote(tid.removeprefix("director/"))
items = [self._card(item, "list") for item in CATALOG if item["director"] == director]
elif tid in (
"vod_portrait", "vod_landscape", "vod_oval", "vod_list",
"class_landscape", "class_oval",
):
records = self._filtered_records(extend)
card_style = {
"vod_portrait": "portrait",
"vod_landscape": "landscape",
"vod_oval": "oval",
"vod_list": "list",
}.get(tid)
picture_style = {
"class_landscape": "landscape",
"class_oval": "oval",
}.get(tid, card_style)
# class_* 不放 VOD.style,讓 Class.land / Class.circle 決定整個分類頁樣式。
items = [self._card(item, card_style, picture_style) for item in records]
else:
items = []
return self.page(items, pg, PAGE_SIZE)
def searchContent(self, key, quick, pg="1"):
query = str(key or "").strip().casefold()
if not query:
return self.page([], pg, PAGE_SIZE)
matches = []
for item in CATALOG:
fields = (
SEARCH_ALL_KEYWORD, item["name"], item["genre"], item["area"],
item["year"], item["director"], *item["actors"],
)
if any(query in str(value).casefold() for value in fields):
matches.append(self._card(item, "list"))
return self.page(matches, pg, PAGE_SIZE)
def detailContent(self, ids):
items = []
for video_id in ids:
record = self._record(str(video_id).removeprefix("vod/"))
if record is None:
return {"list": [], "msg": "找不到此範例影片"}
items.append(self._detail_vod(record))
return {"list": items}
def _detail_vod(self, record):
flags = ["主要線"]
urls = [self._episode_line(record, "main")]
if str(self.options.get("backup_media_url") or "").strip():
flags.append("備用線")
urls.append(self._episode_line(record, "backup"))
if str(self.options.get("media_url") or "").split("?", 1)[0].lower().endswith(".m3u8"):
flags.append("代理線")
urls.append(self._episode_line(record, "proxy"))
item = self._card(record, "portrait")
item.update({
"type_name": record["genre"],
"vod_year": record["year"],
"vod_area": record["area"],
"vod_director": self._clickable("director", record["director"]),
"vod_actor": "、".join(self._clickable("actor", name) for name in record["actors"]),
"vod_content": record["content"],
"vod_play_from": "$$$".join(flags),
"vod_play_url": "$$$".join(urls),
})
return item
def playerContent(self, flag, id, vipFlags):
parts = str(id or "").split("/")
if len(parts) != 4 or parts[0] != "play" or parts[3] not in ("main", "backup", "proxy"):
return {"parse": 0, "msg": "無效的範例播放 ID"}
record = self._record(parts[1])
try:
episode_index = int(parts[2])
except ValueError:
episode_index = -1
if record is None or not 1 <= episode_index <= len(record["episodes"]):
return {"parse": 0, "msg": "找不到此範例集數"}
source = parts[3]
option_key = "backup_media_url" if source == "backup" else "media_url"
url = str(self.options.get(option_key) or "").strip()
qualities = self._qualities(self.options["media_urls"]) if source == "main" and "media_urls" in self.options else None
if qualities:
url = qualities["values"][qualities["position"]]["v"]
sniff_url = str(self.options.get("sniff_url") or "").strip() if source == "main" else ""
header_key = "backup_media_headers" if source == "backup" else "media_headers"
headers = self._string_map(self.options.get(header_key), header_key)
if not url and sniff_url:
self._absolute_url(sniff_url, "sniff_url")
return {"parse": 1, "jx": 0, "url": sniff_url, "header": headers, "list": [self._detail_vod(record)]}
if not url:
return {"parse": 0, "msg": "請先設定 ext.%s 再測試播放" % option_key}
self._absolute_url(url, option_key)
result = {
"parse": 0,
"jx": 0,
"url": self.proxyUrl({"demo": "playlist"}) if source == "proxy" else qualities or url,
"header": headers,
"list": [self._detail_vod(record)],
"artwork": self._picture(record, "landscape"),
"desc": "%s・%s" % (record["name"], record["episodes"][episode_index - 1]),
}
if "skips" in self.options:
result["skips"] = self._skips(self.options["skips"])
if self.options.get("timeshift") is not None:
result["timeshift"] = self.options["timeshift"]
media_format = str(self.options.get("media_format") or "").strip()
if media_format:
result["format"] = media_format
subtitles = self._subtitles(self.options.get("subtitles"))
if subtitles:
result["subs"] = subtitles
danmaku = self._danmaku(self.options.get("danmaku"))
if danmaku:
result["danmaku"] = danmaku
if self.options.get("live_danmaku") is True:
result["danmaku"] = [{"name": "即時彈幕", "url": self.danmakuUrl("demo")}]
drm = self._drm(self.options.get("drm"))
if drm:
result["drm"] = drm
if "start_position_ms" in self.options:
position = self.options["start_position_ms"]
if isinstance(position, int) and not isinstance(position, bool) and position >= 0:
result["position"] = position
else:
raise ValueError("start_position_ms 必須是大於或等於 0 的整數")
return result
def action(self, action):
if action == "wasm":
return self._wasm_action()
if action in ("ttl_cache", "ttl_text", "ttl_peek", "ttl_clear", "ttl_clear_all", "ttl_persist", "ttl_background",
"cache_write", "cache_read", "cache_delete"):
return self._cache_action(action)
if action in ("json", "session", "parallel", "parallel_map", "binary", "request_sync", "stream_read", "proxy_stream", "proxy_body"):
return self._network_action(action)
if action == "script":
value = self.js.eval("({value: value + 1, digest: md5X(text)})", {
"globals": {"value": 41, "text": "demo"}, "timeout": 1000
})
return {"msg": "腳本執行結果:" + json.dumps(value, ensure_ascii=False)}
if action == "download":
with tempfile.TemporaryDirectory() as directory:
target = Path(directory) / "demo.bin"
self.net.download(self.request_url, target)
return {"msg": "下載完成:%s bytes" % target.stat().st_size}
if action == "web_view":
return {"web": {"url": self._absolute_url(self.options.get("game_url") or self.web_url, "game_url"), "mode": "view"}}
if action == "proxy":
value = self.net.json(self.proxyUrl({"demo": "json"}))
return {"msg": "本機 proxy:" + value["name"]}
if action == "native_toast":
from java import jclass
jclass("com.github.catvod.Runtime").toast("Python 執行中的提示")
return {}
if action == "runtime":
return self._check_runtime()
if action == "sleep":
self.net.sleep(250)
return {"msg": "等待完成(250 毫秒)"}
if action == "toast":
return {"msg": "這是 Python action 回傳、由 App 顯示的 Toast"}
if action == "dialog":
return self._show_form()
if action == "dialog_steps":
return self._show_steps()
if action == "qrcode":
return self._show_qrcode()
if action == "site_key":
return {"msg": "目前 Site key:" + str(getattr(self, "siteKey", ""))}
if action == "web":
web = {"url": self.web_url}
if self.options.get("web_cookie"):
web["cookie"] = self.options["web_cookie"]
elif self.cookie_name:
web["cookie"] = [{"keys": [self.cookie_name]}]
return {"web": web}
if action == "cookie":
if not self.cookie_name:
return {"msg": "請先在 ext 設定 cookie_name"}
if self._cookie_value(self._cookies(), self.cookie_name):
return {"msg": "指定的 WebView Cookie 已存在;有效性仍須由站點 API 確認"}
return {"msg": "尚未取得指定的 WebView Cookie"}
if action == "cookie_clear":
if not self.cookie_name:
return {"msg": "請先在 ext 設定 cookie_name"}
try:
cleared = self._clear_cookie()
return {"msg": "已清除指定的 WebView Cookie" if cleared else "WebView Cookie 清除失敗"}
except Exception as error:
return {"msg": "WebView Cookie 清除失敗:" + type(error).__name__}
if action == "request":
return self._request()
if action == "socket-stop":
if self.socket is not None:
self.socket.close()
self.socket = None
return {"msg": "WebSocket 已停止"}
if action == "socket-state":
return {"msg": json.dumps(self.socket_state, ensure_ascii=False)}
if action == "socket-start":
return self._connect_socket()
if action == "websocket":
return self._exchange_socket()
return {"msg": "不支援此操作"}
def _cache_action(self, action):
if action == "ttl_cache":
value = self.net.cached("demo:ttl", {"ttl": 60000}, lambda: {"value": "範例資料"})
return {"msg": "TTL 快取:" + value["value"]}
if action == "ttl_text":
text = self.net.cachedText("demo:ttl", {"ttl": 60000}, lambda: {"value": "範例資料"})
return {"msg": "JSON 快取文字:" + text}
if action == "ttl_peek":
value = self.net.peek("demo:ttl")
return {"msg": "目前沒有 TTL 快取" if value is None else "已有 TTL 快取:" + value["value"]}
if action == "ttl_clear":
self.net.clearCache("demo:ttl")
return {"msg": "已清除 TTL 快取"}
if action == "ttl_clear_all":
self.net.clearCache()
return {"msg": "已清除目前站點的全部 TTL 快取"}
if action == "ttl_persist":
value = self.net.cached("demo:persist", {"ttl": 60000, "stale": False, "persist": True}, self._cache_value)
return {"msg": "持久化快取:" + str(value["updated"])}
if action == "ttl_background":
value = self.net.peek("demo:background")
self.net.refresh("demo:background", {"ttl": 1000, "stale": False, "persist": True}, self._refresh_cache)
return {"msg": "背景更新已安排;目前值:" + (str(value["updated"]) if value else "尚未載入")}
if action == "cache_write":
self.local.set(self.cache_key, CACHE_VALUE)
return {"msg": "已寫入 Python Local"}
if action == "cache_read":
value = self.local.get(self.cache_key)
return {"msg": json.dumps(value, ensure_ascii=False, separators=(",", ":")) if value is not None else "Python Local 尚無資料"}
if action == "cache_delete":
self.local.delete(self.cache_key)
return {"msg": "已刪除 Python Local 資料"}
raise ValueError(action)
def _show_form(self):
result = self.dialog({
"title": "表單範例", "message": "先帶入範例,再修改或確認;返回可取消。", "cancelable": True,
"inputs": [
{"name": "text", "label": "內容", "helperText": "可輸入多行文字,換行會保留", "type": "textarea", "enabled": False, "required": True, "maxLength": 80},
{"name": "choice", "label": "選項", "type": "select", "required": True,
"options": [{"value": "first", "label": "選項一"}, {"value": "second", "label": "選項二"}]},
{"name": "choices", "label": "多選", "type": "multiselect", "required": True, "maxItems": 2,
"options": [{"value": "first", "label": "選項一"}, {"value": "second", "label": "選項二"}, {"value": "third", "label": "選項三"}]},
],
"buttons": [
{"id": "fill", "label": "帶入範例", "close": False, "validate": []},
{"id": "confirm", "label": "確認", "enabled": False},
{"id": "error", "label": "錯誤提示", "close": False, "validate": []},
],
}, self._on_dialog)
return {} if result is None else {"msg": "已確認表單;輸入內容不會記錄或保存"}
def _on_dialog(self, event):
self.net.sleep(250)
if event["button"] == "fill":
return {
"values": {"text": "範例內容", "choice": "first", "choices": ["first", "second"]},
"inputs": [{"name": "text", "enabled": True}],
"buttons": [{"id": "confirm", "enabled": True}],
}
if event["button"] == "error":
return {"errors": {"text": "這是欄位錯誤提示示範"}}
return {"close": True}
def _show_qrcode(self):
version = 1
initial = "https://example.com/?v=1"
def on_action(event):
nonlocal version
if event["button"] != "refresh":
return None
self.net.sleep(250)
version += 1
content = "https://example.com/?v=" + str(version)
return {"qrcode": content, "message": content}
self.dialog({
"title": "QR Code 範例", "message": initial, "qrcode": initial, "copyable": True,
"buttons": [{"id": "refresh", "label": "更新", "close": False}, {"id": "close", "label": "關閉"}],
}, on_action)
return {}
def _show_steps(self):
index = 0
images = ['data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGAAAAAwCAIAAABhdOiYAAAAbklEQVR4nO3QwQkAIAwEQUuzdDvTDgQJRtE59hsIU1qtmlSOf3B5gAABAvQlUF8ZIECAAAHKFUm7BQQIECBAgAABAgToKaDIAAECBAjQZqC0W0CAAAECBAgQIECAAAECBAgQIAECBAjQLQECFGsAofuPsjrQFugAAAAASUVORK5CYII=', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGAAAAAwCAIAAABhdOiYAAAAeUlEQVR4nO3VwQ2AIBBFQUqyJEu1M+lAs5Cs4M7Pu5LAXGjHeemh9vkNFg8QIECAagDdEwMECBAgQLlAaWcBAQIECBAgQIAAAfoVUGiZIoAAAQIEyC8GCBAgQIAAAQIECNDYI0PLFAEECBCgkkCbBggQIECAFg7QSx0xt+dr9Gzw2wAAAABJRU5ErkJggg==']
def on_action(event):
nonlocal index
if event["button"] != "refresh":
return None
index = 1 - index
return {"image": images[index]}
first = self.dialog({
"title": "第一步", "message": "可更新示意圖片,輸入內容後繼續。", "image": images[index],
"inputs": [{"name": "text", "label": "內容", "helperText": "確認後進入下一步", "required": True}],
"buttons": [{"id": "next", "label": "下一步"}, {"id": "refresh", "label": "更新圖片", "close": False, "validate": []}],
}, on_action)
if first is None:
return {}
second = self.dialog({"title": "第二步", "message": first["values"]["text"], "copyable": True})
return {} if second is None else {"msg": "已完成兩步對話框;輸入內容不會記錄或保存"}
def liveContent(self, url=""):
urls = [self._absolute_url(self.options[key], key) + "$" + name
for key, name in (("media_url", "主要線"), ("backup_media_url", "備用線")) if self.options.get(key)]
return [{"name": "範例直播", "channel": [{"name": "示範頻道", "urls": urls}]}] if urls else []
def proxy(self, params):
kind = params.get("demo")
headers = {"X-Demo": "1"}
if kind == "json":
return [200, "application/json; charset=utf-8", '{"name":"demo","ok":true}', headers]
if kind == "stream":
response = self.net.stream(self.request_url, {"timeout": REQUEST_TIMEOUT_MS, "callTimeout": REQUEST_TIMEOUT_MS})
return [response["code"], response["contentType"], response["stream"], response["headers"]]
if kind == "body":
response = self.net.stream(self._stream_body())
return [200, response["contentType"], response["stream"], headers]
if kind == "playlist" and self.options.get("media_url"):
url = self._absolute_url(self.options["media_url"], "media_url")
return [200, "application/vnd.apple.mpegurl", "#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=1280000\n" + url + "\n", headers]
return [404, "text/plain; charset=utf-8", "未知的範例 proxy", headers]
@staticmethod
def _cache_value():
return {"updated": int(time.time() * 1000), "items": [1, True, None]}
def _refresh_cache(self):
self.net.sleep(250)
return self._cache_value()
def _stream_body(self):
for _ in range(2):
with self.net.openStream(self.request_url, {"timeout": REQUEST_TIMEOUT_MS, "callTimeout": REQUEST_TIMEOUT_MS}) as reader:
self._check_response({"code": reader.code})
while True:
chunk = reader.read()
if chunk is None:
break
yield chunk
def _count_stream_bytes(self, url):
with self.net.openStream(url, {"timeout": REQUEST_TIMEOUT_MS, "callTimeout": REQUEST_TIMEOUT_MS}) as reader:
self._check_response({"code": reader.code})
length = 0
while True:
chunk = reader.read()
if chunk is None:
return length
length += len(chunk)
def _request(self):
try:
response = self.net.req(self.request_url, self._request_options(True))
if response.get("error"):
return {"msg": "HTTP 請求失敗:" + str(response["error"])}
return {"msg": "HTTP %s,回應 %s bytes,已啟用 WebView Cookie" % (
response["code"], len(response["content"].encode("utf-8") if isinstance(response["content"], str) else response["content"]))}
except Exception as error:
return {"msg": "HTTP 請求失敗:" + type(error).__name__}
def _exchange_socket(self):
if not self.options.get("ws_url"):
return {"msg": "請先在 ext 設定 ws_url"}
try:
data = self.options.get("ws_data")
response = self.net.ws(self.options["ws_url"], {
"data": "" if data is None else data,
"headers": self._string_map(self.options.get("ws_headers"), "ws_headers"),
"timeout": REQUEST_TIMEOUT_MS,
})
if response.get("error"):
return {"msg": "WebSocket 交換失敗:" + str(response["error"])}
return {"msg": "WebSocket %s,回應 %s bytes" % (
response["code"], len(response["content"].encode("utf-8")))}
except Exception as error:
return {"msg": "WebSocket 交換失敗:" + type(error).__name__}
@staticmethod
def _wasm_action():
import pywasm
module = pywasm.binary.Module.from_reader(BytesIO(WASM_BYTES))
runtime = pywasm.Runtime(module)
result = runtime.exec("add", [20, 22])
if result != 42:
raise ValueError("WASM add 回傳值不符")
return {"msg": "WASM:add(20, 22) = %s" % result}
def _check_runtime(self):
try:
from java import jclass
crypto = jclass("com.github.catvod.utils.Crypto")
plain = crypto.aes("GCM", False, "0388dace60b6a392f328c2b971b2fe78ab6e47d42cec13bdf53a67b21257bddf", False,
"00000000000000000000000000000000", "000000000000000000000000", True)
passed = crypto.sha256("abc") == "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" and plain == "AAAAAAAAAAAAAAAAAAAAAA=="
return {"msg": "App 與加密 bridge 測試通過" if passed else "App 或加密 bridge 測試失敗"}
except Exception as error:
return {"msg": "App 或加密 bridge 測試失敗:" + type(error).__name__}
def _request_options(self, cookie):
headers = self._string_map(self.options.get("request_headers"), "request_headers")
if cookie and not any(key.lower() == "user-agent" for key in headers):
user_agent = str(self.net.getUserAgent() or "")
if user_agent:
headers["User-Agent"] = user_agent
return {
"method": str(self.options.get("request_method") or "GET"),
"headers": headers,
"timeout": REQUEST_TIMEOUT_MS,
"callTimeout": REQUEST_TIMEOUT_MS,
"cookie": cookie,
**(self.options.get("request_options") or {}),
}
def _network_action(self, action):
try:
if action == "json":
url = self._absolute_url(self.options.get("json_url"), "json_url")
value = self.net.json(url, {"timeout": REQUEST_TIMEOUT_MS})
return {"msg": "JSON 請求成功:" + type(value).__name__}
if action in ("stream_read", "proxy_stream", "proxy_body"):
url = self.request_url if action == "stream_read" else self.proxyUrl({"demo": "body" if action == "proxy_body" else "stream"})
return {"msg": "串流讀取完成:%s bytes" % self._count_stream_bytes(url)}
if action == "parallel":
values = self.net.batch([{ "url": self.request_url, "options": {"timeout": REQUEST_TIMEOUT_MS}} for _ in range(3)])
for value in values:
self._check_response(value)
return {"msg": "並行完成 3 次請求"}
if action == "parallel_map":
urls = [self.request_url, self._absolute_url(self.options.get("json_url"), "json_url")]
values = self.net.map(urls, self._request_summary, 2)
return {"msg": "並行映射完成:" + json.dumps(values, ensure_ascii=False)}
if action == "session":
with self.net.session() as flow:
if not flow.setCookie(self.request_url, "demo_session=1; Path=/"):
raise ValueError("Session Cookie 寫入失敗")
self._check_response(flow.req(self.request_url, {"timeout": REQUEST_TIMEOUT_MS}))
exists = "demo_session=1" in flow.getCookie(self.request_url)
return {"msg": "隔離 Session 請求完成,Cookie " + ("存在" if exists else "不存在")}
settings = self._request_options(False)
if action == "binary":
settings["buffer"] = 3
value = self.net.req(self.request_url, settings)
self._check_response(value)
return {"msg": "HTTP %s,回應長度 %s" % (value["code"], len(value["content"]))}
except Exception as error:
return {"msg": "網路示範失敗:" + str(error)}
def _request_summary(self, url, index):
value = self.net.req(url, {"timeout": REQUEST_TIMEOUT_MS})
self._check_response(value)
return {"index": index, "code": value["code"]}
@staticmethod
def _check_response(value):
if value.get("error"):
raise ValueError(value["error"])
if not 200 <= value["code"] < 300:
raise ValueError("HTTP %s" % value["code"])
@staticmethod
def _qualities(value):
if not isinstance(value, dict) or not isinstance(value.get("values"), list) or not value["values"]:
raise ValueError("media_urls 必須包含非空的 values 陣列")
values = [{"n": str(item["n"]), "v": Spider._absolute_url(item["v"], "media_urls.v")} for item in value["values"]]
position = value.get("position", 0)
if isinstance(position, bool) or not isinstance(position, int) or not 0 <= position < len(values):
raise ValueError("media_urls.position 必須是有效畫質索引")
return {"values": values, "position": position}
@staticmethod
def _skips(value):
if not isinstance(value, list):
raise ValueError("skips 必須是陣列")
for item in value:
if not isinstance(item, dict) or item.get("type") not in ("opening", "middle", "ending"):
raise ValueError("skips.type 格式錯誤")
start, end = item.get("start"), item.get("end")
if isinstance(start, bool) or not isinstance(start, int) or start < 0:
raise ValueError("skips.start 必須是非負整數毫秒")
if end is None and item["type"] == "ending" and start > 0:
continue
if isinstance(end, bool) or not isinstance(end, int) or end <= start:
raise ValueError("skips.end 必須晚於 start")
return [item.copy() for item in value]
def manualVideoCheck(self):
return True
def isVideoFormat(self, url):
try:
parsed = urlsplit(str(url or ""))
parsed.port
path = parsed.path.lower()
return parsed.scheme in ("http", "https") and bool(parsed.netloc) and path.endswith(VIDEO_SUFFIXES) and "/ad/" not in path
except ValueError:
return False
def danmaku(self, id, emit):
if not self.options.get("ws_url"):
raise ValueError("請先在 ext 設定 ws_url")
ready = False
stopped = False
def receive(socket, event):
nonlocal ready, stopped
if stopped:
return
if event["type"] == "message" and not event["binary"]:
if not ready:
emit({"state": "ready"})
ready = True
emit({"text": event["content"], "color": 0x66ccff, "size": 25, "type": 1, "colors": [0x66ccff, 0xcc99ff]})
elif event["type"] == "retry":
ready = False
emit({"state": "retrying", "msg": "彈幕連線中斷,等待恢復"})
elif event["type"] in ("error", "close"):
stopped = True
emit({"state": "error", "msg": str(event.get("error") or "彈幕連線已關閉")[:512]})
def stop():
nonlocal stopped
stopped = True
connection.cancel()
connection = self.net.connect(self.options["ws_url"], {
"headers": self._string_map(self.options.get("ws_headers"), "ws_headers"),
"data": self.options.get("ws_data"),
"timeout": REQUEST_TIMEOUT_MS,
"ping": 30000,
"idle": self.options.get("ws_idle", 0),
"reconnect": True,
}, receive)
return stop
def destroy(self):
if self.socket is not None:
self.socket.cancel()
self.socket = None
self.options = {}
def _connect_socket(self):
if not self.options.get("ws_url"):
return {"msg": "請先在 ext 設定 ws_url"}
if self.socket is not None:
self.socket.cancel()
state = {"state": "連線中", "text": 0, "binary": 0, "retries": 0}
self.socket_state = state
settings = {
"headers": self._string_map(self.options.get("ws_headers"), "ws_headers"),
"timeout": REQUEST_TIMEOUT_MS,
"ping": 30000,
"idle": self.options.get("ws_idle", 0),
"reconnect": True,
}
if "ws_data" in self.options:
settings["data"] = self.options["ws_data"]
self.socket = self.net.connect(self.options["ws_url"], settings,
lambda socket, event: self._socket_event(socket, event, state))
return {"msg": "WebSocket 已開始連線"}
@staticmethod
def _socket_event(socket, event, state):
if event["type"] == "open":
state["state"] = "已連線"
socket.send(bytes([0, 127, 128, 255]))
elif event["type"] == "message":
state["binary" if event["binary"] else "text"] += 1
elif event["type"] == "error":
state["error"] = event["error"]
elif event["type"] == "retry":
state["state"] = "重新連線中"
state["retries"] += 1
state["retryCode"] = event["code"]
elif event["type"] == "close":
state["state"] = "已關閉"
@staticmethod
def _absolute_url(value, name):
try:
target = urlsplit(str(value))
if target.scheme not in ("http", "https") or not target.hostname:
raise ValueError
target.port
return str(value)
except (TypeError, ValueError):
raise ValueError("%s 必須是完整 HTTP(S) 網址" % name) from None
def _filtered_records(self, extend):
genre = str(extend.get("genre") or "all")
area = str(extend.get("area") or "all")
year = str(extend.get("year") or "all")
records = [
item for item in CATALOG
if genre in ("all", item["genre"])
and area in ("all", item["area"])
and year in ("all", item["year"])
]
sort = str(extend.get("sort") or "latest")
if sort == "name":
records.sort(key=lambda item: item["name"])
elif sort == "oldest":
records.sort(key=lambda item: (item["year"], item["id"]))
else:
records.sort(key=lambda item: (item["year"], item["id"]), reverse=True)
return records
@staticmethod
def _record(ident):
return next((item for item in CATALOG if item["id"] == ident), None)
def _card(self, record, style_name=None, picture_style=None):
item = {
"vod_id": "vod/" + record["id"],
"vod_name": record["name"],
"vod_pic": self._picture(record, picture_style or style_name or "portrait"),
"vod_remarks": record["remark"],
"vod_year": record["year"],
}
styles = {
"portrait": {"type": "rect", "ratio": 0.75},
"landscape": {"type": "rect", "ratio": 1.78},
"oval": {"type": "oval", "ratio": 1.0},
"list": {"type": "list"},
}
if style_name in styles:
item["style"] = styles[style_name].copy()
return item
def _picture(self, record, style_name):
if not self.image_base:
return ""
width, height = {
"landscape": (800, 450),
"oval": (600, 600),
}.get(style_name, (600, 800))
return "%s/%s/%s/%s" % (self.image_base, quote(record["id"], safe=""), width, height)
def _folder_cards(self):
items = []
for genre in ("動畫", "戲劇", "綜藝", "紀錄"):
items.append(self._folder_card("folder/genre/" + quote(genre, safe=""), genre + "資料夾", "依類型開啟"))
for area in ("台灣", "日本", "韓國"):
items.append(self._folder_card("folder/area/" + quote(area, safe=""), area + "資料夾", "依地區開啟"))
return items
@staticmethod
def _folder_card(ident, name, remark):
return {
"vod_id": ident,
"vod_name": name,
"vod_remarks": remark,
"vod_tag": "folder",
"style": {"type": "list"},
}
@staticmethod
def _action_cards():
return [
{
"vod_id": "action/" + action,
"vod_name": name,
"vod_remarks": remark,
"action": action,
"style": {"type": "list"},
}
for action, name, remark in (
("web_view", "開啟獨立內容", "mode=view,返回依網頁歷史"),
("native_toast", "執行中 Toast", "呼叫 App 的 Runtime.toast"),
("json", "JSON 請求", "驗證 HTTP 狀態與 JSON"),
("request_sync", "同步 HTTP", "同步取得狀態、標頭與正文"),
("request", "HTTP + Cookie", "帶入 WebView Cookie,取得狀態與長度"),
("binary", "二進位回應", "buffer=3,直接取得 bytes"),
("cookie", "檢查 Cookie", "查看指定 Cookie 是否存在"),
("cookie_clear", "清除 Cookie", "寫入過期 Cookie 並確認結果"),
("session", "隔離 Session", "使用獨立 Cookie,用完關閉"),
("parallel", "批次請求", "並行取得 3 份回應"),
("parallel_map", "並行映射", "限制並行數,依序回傳解析結果"),
("script", "執行 JavaScript", "隔離執行,傳入變數與逾時"),
("download", "下載檔案", "下載至暫存檔,用完移除"),
("stream_read", "分塊讀取", "每塊最多 64 KiB,用完關閉"),
("proxy_stream", "串流代理", "由本機 proxy 轉送 request_url"),
("proxy_body", "串流輸出", "依序讀取兩次 request_url,輸出至同一 proxy"),
("websocket", "WebSocket 交換", "取得首個完整訊息後關閉"),
("socket-start", "WebSocket 連線", "持續收訊並發送二進位範例"),
("socket-state", "WebSocket 狀態", "查看文字與二進位訊息數"),
("socket-stop", "停止 WebSocket", "關閉連線並釋放資源"),
("sleep", "可取消等待", "等待 250 毫秒,取消即停止"),
("ttl_cache", "TTL 快取", "有效期內重用,過期背景更新"),
("ttl_text", "JSON 快取文字", "cachedText 取得原文,共用 TTL"),
("ttl_peek", "讀取已有快取", "只讀已有值,保留原有效期"),
("ttl_background", "背景更新快取", "peek 讀舊值,refresh 背景更新"),
("ttl_persist", "持久化快取", "重新載入爬蟲後仍可讀取"),
("ttl_clear", "清除 TTL 快取", "清除範例 key 並取消載入"),
("ttl_clear_all", "清除全部 TTL", "清除目前站點的 TTL 快取"),
("cache_write", "寫入 Local", "保存 JSON 物件、陣列與純量"),
("cache_read", "讀取 Local", "讀取範例值"),
("cache_delete", "刪除 Local", "刪除範例值"),
("wasm", "執行 WASM", "編譯內嵌模組並呼叫 add(20, 22)"),
("proxy", "本機 proxy", "透過 App HTTP server 呼叫此爬蟲"),
("runtime", "測試 App 與加密 bridge", "驗證 SHA-256 與 AES-GCM"),
("toast", "顯示 Toast", "action 回傳 msg,由 App 顯示"),
("dialog", "自訂 Dialog", "同一視窗驗證輸入、非同步回呼與欄位錯誤提示"),
("dialog_steps", "連續 Dialog", "圖片更新、欄位說明與兩步對話框"),
("qrcode", "顯示 QR Code", "同一視窗更新 QR Code 並複製說明文字"),
("site_key", "顯示 Site key", "由 App 在 init 前注入的 siteKey"),
("web", "開啟網頁", "action 回傳 web,由 App 開啟"),
)
]
@staticmethod
def _clickable(kind, name):
return BaseSpider.link(name, {"id": "%s/%s" % (kind, quote(name, safe="")), "name": name, "type_flag": "1"})
@staticmethod
def _safe_label(value):
return str(value or "").replace("$", "$").replace("#", "#").strip()
def _episode_line(self, record, source):
return "#".join(
"%s$play/%s/%s/%s" % (self._safe_label(name), record["id"], index, source)
for index, name in enumerate(record["episodes"], start=1)
)
@staticmethod
def _string_map(value, name):
if value in (None, ""):
return {}
if not isinstance(value, dict):
raise ValueError(name + " 必須是 JSON 物件")
result = {}
for key, item in value.items():
if item is not None:
result[str(key)] = str(item)
return result
@classmethod
def _subtitles(cls, value):
if value in (None, ""):
return []
if not isinstance(value, list):
raise ValueError("subtitles 必須是 JSON 陣列")
result = []
for index, item in enumerate(value):
if not isinstance(item, dict):
raise ValueError("subtitles[%s] 必須是 JSON 物件" % index)
url = str(item.get("url") or "").strip()
if not url:
continue
cls._absolute_url(url, "subtitles[%s].url" % index)
result.append({
"name": str(item.get("name") or "字幕 %s" % (index + 1)),
"url": url,
"lang": str(item.get("lang") or ""),
"format": str(item.get("format") or ""),
})
if "flag" in item:
if isinstance(item["flag"], bool) or not isinstance(item["flag"], int):
raise ValueError("subtitles.flag 必須是整數")
result[-1]["flag"] = item["flag"]
return result
@classmethod
def _danmaku(cls, value):
if value in (None, ""):
return []
if isinstance(value, str):
cls._absolute_url(value, "danmaku")
return [{"name": "彈幕", "url": value}]
if not isinstance(value, list):
raise ValueError("danmaku 必須是網址字串或 JSON 陣列")
result = []
for index, item in enumerate(value):
if isinstance(item, str):
name, url = "彈幕 %s" % (index + 1), item
elif isinstance(item, dict):
name = str(item.get("name") or "彈幕 %s" % (index + 1))
url = str(item.get("url") or "")
else: