Debian Codegraph @

gallery_dl/extractor/utils/jsurl.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2026 Mike Fährmann
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License version 2 as
7 # published by the Free Software Foundation.
8
9
10 def parse(data):
11 """Parse JSURL data
12
13 Nested lists and dicts are handled in a special way to deal
14 with the way Tsumino expects its parameters -> expand(...)
15
16 Example: ~(name~'John*20Doe~age~42~children~(~'Mary~'Bill))
17 Ref: https://github.com/Sage/jsurl
18 """
19 i = 0
20 imax = len(data)
21
22 def eat(expected):
23 nonlocal i
24
25 if data[i] != expected:
26 raise ValueError(
27 f"bad JSURL syntax: expected '{expected}', got {data[i]}")
28 i += 1
29
30 def decode():
31 nonlocal i
32
33 beg = i
34 result = ""
35
36 while i < imax:
37 ch = data[i]
38
39 if ch not in "~)*!":
40 i += 1
41
42 elif ch == "*":
43 if beg < i:
44 result += data[beg:i]
45 if data[i + 1] == "*":
46 result += chr(int(data[i+2:i+6], 16))
47 i += 6
48 else:
49 result += chr(int(data[i+1:i+3], 16))
50 i += 3
51 beg = i
52
53 elif ch == "!":
54 if beg < i:
55 result += data[beg:i]
56 result += "$"
57 i += 1
58 beg = i
59
60 else:
61 break
62
63 return result + data[beg:i]
64
65 def parse_one():
66 nonlocal i
67
68 eat('~')
69 result = ""
70 ch = data[i]
71
72 if ch == "(":
73 i += 1
74
75 if data[i] == "~":
76 result = []
77 if data[i+1] == ")":
78 i += 1
79 else:
80 result.append(parse_one())
81 while data[i] == "~":
82 result.append(parse_one())
83
84 else:
85 result = {}
86
87 if data[i] != ")":
88 while True:
89 key = decode()
90 value = parse_one()
91 for ekey, evalue in expand(key, value):
92 result[ekey] = evalue
93 if data[i] != "~":
94 break
95 i += 1
96 eat(")")
97
98 elif ch == "'":
99 i += 1
100 result = decode()
101
102 else:
103 beg = i
104 i += 1
105
106 while i < imax and data[i] not in "~)":
107 i += 1
108
109 sub = data[beg:i]
110 if ch in "0123456789-":
111 fval = float(sub)
112 ival = int(fval)
113 result = ival if ival == fval else fval
114 else:
115 if sub not in ("true", "false", "null"):
116 raise ValueError("bad value keyword: " + sub)
117 result = sub
118
119 return result
120
121 def expand(key, value):
122 if isinstance(value, list):
123 for index, cvalue in enumerate(value):
124 ckey = f"{key}[{index}]"
125 yield from expand(ckey, cvalue)
126 elif isinstance(value, dict):
127 for ckey, cvalue in value.items():
128 ckey = f"{key}[{ckey}]"
129 yield from expand(ckey, cvalue)
130 else:
131 yield key, value
132
133 return parse_one()