/
toolbox.py
573 lines (469 loc) · 23 KB
/
toolbox.py
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
import logging
import json
import bson
import re
import tkinter as tk
import tkinter.font as tkfont
from tkinter import ttk
from tkinter import filedialog
from tkinter import messagebox
import os
from os import system
from os.path import abspath
from collections import OrderedDict
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s')
logging.info('Program started')
# https://stackoverflow.com/a/16375233
class TextLineNumbers(tk.Canvas):
def __init__(self, *args, **kwargs):
tk.Canvas.__init__(self, *args, **kwargs)
self.textwidget = None
def attach(self, text_widget):
self.textwidget = text_widget
def redraw(self, *args):
'''redraw line numbers'''
self.delete("all")
i = self.textwidget.index("@0,0")
while True :
dline= self.textwidget.dlineinfo(i)
if dline is None: break
y = dline[1]
linenum = str(i).split(".")[0]
self.create_text(2,y,anchor="nw", text=linenum)
i = self.textwidget.index("%s+1line" % i)
class CustomText(tk.Text):
def __init__(self, *args, **kwargs):
tk.Text.__init__(self, *args, **kwargs)
# create a proxy for the underlying widget
self._orig = self._w + "_orig"
self.tk.call("rename", self._w, self._orig)
self.tk.createcommand(self._w, self._proxy)
def _proxy(self, *args):
# let the actual widget perform the requested action
cmd = (self._orig,) + args
try:
result = self.tk.call(cmd)
except Exception:
return None
# generate an event if something was added or deleted,
# or the cursor position changed
if (args[0] in ("insert", "replace", "delete") or
args[0:3] == ("mark", "set", "insert") or
args[0:2] == ("xview", "moveto") or
args[0:2] == ("xview", "scroll") or
args[0:2] == ("yview", "moveto") or
args[0:2] == ("yview", "scroll")
):
self.event_generate("<<Change>>", when="tail")
# return what the actual widget returned
return result
class TextExtra(tk.Frame):
def __init__(self, *args, **kwargs):
tk.Frame.__init__(self, *args, **kwargs)
self.text = CustomText(self, wrap='none', font=('verdana', '7'))
self.vsb = tk.Scrollbar(self, orient="vertical", command=self.text.yview)
self.hsb = tk.Scrollbar(self, orient="horizontal", command=self.text.xview)
self.text.configure(yscrollcommand=self.vsb.set, xscrollcommand=self.hsb.set)
self.text.tag_configure("bigfont", font=("Helvetica", "24", "bold"))
self.linenumbers = TextLineNumbers(self, width=20)
self.linenumbers.attach(self.text)
self.vsb.pack(side="right", fill="y")
self.hsb.pack(side='bottom', fill='x')
self.linenumbers.pack(side="left", fill="y")
self.text.pack(side="right", fill="both", expand=True)
self.text.bind("<<Change>>", self._on_change)
self.text.bind("<Configure>", self._on_change)
def _on_change(self, event):
self.linenumbers.redraw()
def delete(self, *args, **kwargs):
self.text.delete(*args, **kwargs)
def get(self, *args, **kwargs):
return self.text.get(*args, **kwargs)
def see(self, *args, **kwargs):
self.text.see(*args, **kwargs)
self._on_change(event="<<Change>>")
def insert(self, *args, **kwargs):
self.text.insert(*args, **kwargs)
def configure(self, *args, **kwargs):
self.text.configure(*args, **kwargs)
def cget(self, *args, **kwargs):
return self.text.cget(*args, **kwargs)
class JsonFile:
def __init__(self, path):
self.file_path = path
self.json_original_text = None
self.json_text = None
self.host = None
self.hostname = None
self.scheme = None
self.json_object = None
self.tests_available = list()
self.status = ''
self._tests_all = [
'manga_list_complete', 'manga_search_complete', 'manga_complete', 'chapter_complete',
'anime_list_complete', 'anime_search_complete', 'anime_complete', 'episodes_complete'
]
self._load_file(path)
self._load_json()
self._parse_tests()
if self.status != 'invalid':
self._parse_host()
self._convert_links()
self._parse_search_link()
def _parse_search_link(self):
tmp_json_object = json.loads(self.json_text, object_pairs_hook=OrderedDict)
try:
self.search_link = tmp_json_object['anime_search_complete']['search_link']
logging.debug('search_link ' + self.search_link)
except KeyError:
try:
self.search_link = tmp_json_object['manga_search_complete']['search_link']
logging.debug('search_link ' + self.search_link)
except KeyError:
logging.warning('search_link not found')
def _clean_all(self):
self.json_text = None
self.host = None
self.hostname = None
self.scheme = None
self.json_object = None
self.tests_available = list()
def _parse_host(self):
self.host = self.json_object['host'].strip('/')
self.scheme = self.host.split('//')[0]
self.hostname = self.host.split('//')[1]
def _parse_tests(self):
if self.status != 'invalid':
for item in self._tests_all:
if item in self.json_object.keys():
self.tests_available.append(item)
logging.debug('Available tests: ' + str(self.tests_available))
else:
tmp = self._tests_all.copy()
tmp.remove('anime_search_complete')
tmp.remove('manga_search_complete')
self.tests_available = tmp
logging.warning('Tests parsing skipped, using tests_all: ' + str(self.tests_available))
def _load_file(self, path):
with open(path, 'r', encoding='utf8') as f:
self.json_text = f.read()
self.json_original_text = self.json_text
logging.info('Loading file ' + path)
def _load_json(self):
try:
self.json_object = json.loads(self.json_text, object_pairs_hook=OrderedDict)
self.status = 'valid'
except json.JSONDecodeError:
logging.warning("Got decode error, trying to fix json...")
self.status = 'mangled'
self._clean_json_string()
try:
self.json_object = json.loads(self.json_text, object_pairs_hook=OrderedDict)
logging.warning("Json fixed and loaded")
except json.JSONDecodeError:
logging.error("Invalid JSON")
self.status = 'invalid'
def _convert_links(self):
self.json_text = self.json_text.replace('$scheme$', self.scheme)
self.json_text = self.json_text.replace('$hostname$', self.hostname)
self.json_text = self.json_text.replace(r'%%host%%', self.host)
def _clean_json_string(self):
"""
Clears json from trailing commas
https://stackoverflow.com/a/23705538
It will mangle inputs like '{"foo": ",}"}'
"""
self.json_text = re.sub(",[ \t\r\n]+}", "}", self.json_text)
self.json_text = re.sub(",[ \t\r\n]+\]", "]", self.json_text)
class App:
def __init__(self):
self.root = tk.Tk()
self.temp_file_path = None
self.json_file = None
self.test_query = {
"manga_list_complete": 'java -jar NigmaX-2.1.jar --console test "{parser_path}" [{test_method}]',
"manga_search_complete": 'java -jar NigmaX-2.1.jar --console test "{parser_path}" [{test_method}] "{search_link}" "{query}"',
"manga_complete": 'java -jar NigmaX-2.1.jar --console test "{parser_path}" [{test_method}] "{query}"',
"chapter_complete": 'java -jar NigmaX-2.1.jar --console test "{parser_path}" [{test_method}] "{query}"',
"anime_search_complete": 'java -jar NigmaX-2.1.jar --console test "{parser_path}" [{test_method}] "{search_link}" "{query}"',
"anime_list_complete": 'java -jar NigmaX-2.1.jar --console test "{parser_path}" [{test_method}]',
"anime_complete": 'java -jar NigmaX-2.1.jar --console test "{parser_path}" [{test_method}] "{query}"',
"episodes_complete": 'java -jar NigmaX-2.1.jar --console test "{parser_path}" [{test_method}] "{query}" "{query}" "{query}"',
}
self.tests_available = ['Select parser. Tests will appear here']
self.create_main_window()
self.root.mainloop()
def create_main_window(self):
self.root.geometry("400x600")
self.root.resizable(False, False)
self.root.title("RadianceX Toolbox")
self.notebook = ttk.Notebook(self.root)
self.notebook.pack(padx=2, pady=2, fill='both', expand='true')
self.create_tab1()
self.create_tab2()
self.create_tab3()
def create_tab1(self):
self.tab1 = ttk.Frame(self.notebook)
self.parser_path = tk.StringVar()
self.radio_button_value = tk.IntVar()
# tab1 > header > entry
self.header = tk.Frame(self.tab1)
self.header.pack(fill='x', pady=5)
self.entry_path = tk.Entry(self.header, highlightbackground="#bebebe", highlightthickness=1,
textvariable=self.parser_path)
self.entry_path.pack(side='left', fill='x', padx=5, expand=True, ipady=1)
# tab1 > header > button
self.btn_select = ttk.Button(self.header, text="select", command=self.__btn_select_click)
self.btn_select.pack(side='right', padx=5)
# tab1 > label_json_status
self.label_json_status = tk.Label(self.tab1, text='json status')
self.label_json_status.pack(anchor='w', padx=5)
# tab1 > tests_frame
self.tests_frame = tk.LabelFrame(self.tab1, text="tests", padx=5, pady=5)
self.tests_frame.pack(padx=5, pady=5, fill='both')
self.update_tests_available_frame()
# tab1 > entry
self.entry_query = tk.Entry(self.tab1, highlightbackground="#bebebe", highlightthickness=1)
self.entry_query.pack(padx=5, pady=5, fill='x')
# tab1 > button
self.btn_run = ttk.Button(self.tab1, text='RUN', command=self.__btn_run_click)
self.btn_run.pack(padx=5, pady=5, fill='x')
self.notebook.add(self.tab1, text="Tests")
def create_tab2(self):
self.tab2 = ttk.Frame(self.notebook)
self.label_validate_result_text = tk.StringVar()
# tab2 > header
header = tk.Frame(self.tab2)
header.pack(fill='x')
# tab2 > header > text_box
self.text_box = TextExtra(header, highlightbackground="#bebebe")
font = tkfont.Font(font=self.text_box.cget('font'))
tab_width = font.measure(' ' * 4)
self.text_box.configure(tabs=(tab_width,))
self.text_box.pack(padx=5, pady=5)
# tab2 > validate_buttons_frame
validate_buttons_frame = tk.Frame(self.tab2)
validate_buttons_frame.pack(padx=5, fill='x')
# tab2 > validate_buttons_frame > btn_validate
self.btn_validate = ttk.Button(validate_buttons_frame, text='validate json', command=self.__btn_validate_click)
self.btn_validate.pack(side='left', padx=5, pady=5)
# tab2 > validate_buttons_frame > btn_clear
self.btn_clear = ttk.Button(validate_buttons_frame, text='clear', width=0, command=self.__btn_clear_click)
self.btn_clear.pack(side='left', padx=5, pady=5)
# tab2 > labelframe_validate_result
self.labelframe_validate_result = tk.LabelFrame(self.tab2, text="Results")
self.labelframe_validate_result.pack(padx=5, fill='x')
self.label_validate_result = tk.Message(self.labelframe_validate_result, width=380, textvariable=self.label_validate_result_text, foreground='green', font=('consolas', '9'))
self.label_validate_result.pack(fill='x', padx=5, pady=5)
self.notebook.add(self.tab2, text="JSON validator")
def create_tab3(self):
self.tab3 = tk.Frame(self.notebook)
style = ttk.Style()
style.configure('W.TButton', font=('calibri', 20))
# tab3 > btn_convert_json2bson
self.btn_convert_json2bson = ttk.Button(self.tab3, text="Convert JSON to BSON", style='W.TButton', command=self.__btn_convert_json2bson_click)
self.btn_convert_json2bson.pack(fill='x')
# tab3 > btn_convert_bson2json
self.btn_convert_bson2json = ttk.Button(self.tab3, text="Convert BSON to JSON", style='W.TButton', command=self.__btn_convert_bson2json_click)
self.btn_convert_bson2json.pack(fill='x')
# tab3 > btn_convert_links_static2dynamic
self.btn_convert_links_static2dynamic = ttk.Button(self.tab3, text="Convert static links to dynamic", style='W.TButton', command=self.__btn_convert_links_static2dynamic_click)
self.btn_convert_links_static2dynamic.pack(fill='x')
self.notebook.add(self.tab3, text="Converter")
def __btn_convert_bson2json_click(self):
logging.debug("__btn_convert_bson2json_click call")
inp_file_path = filedialog.askopenfilename(initialdir="./", title="Select file", filetypes=(("b files", "*.b"), ("bson files", "*.bson"), ("all files", "*.*")))
logging.debug("inp_file_path: " + inp_file_path)
if inp_file_path:
default_name = inp_file_path.split('/')[-1].split('.')[0]
out_file_path = filedialog.asksaveasfilename(initialdir="./", initialfile=f"{default_name}.json", title="Save as", filetypes=(("json files","*.json"), ("all files", "*.*")))
if out_file_path:
try:
convert_bson2json(inp_file_path, out_file_path)
except json.decoder.JSONDecodeError as e:
logging.warning("error due encoding json: " + str(e))
messagebox.showerror('Error', e)
except Exception as e:
logging.error("unknown exception: " + str(e))
messagebox.showerror('Error', e)
def __btn_convert_json2bson_click(self):
logging.debug("__btn_convert_json2bson_click call")
# if file not selected at Tests tab, ask path to file
if self.json_file:
inp_file_path = self.json_file.file_path
else:
inp_file_path = filedialog.askopenfilename(initialdir="./", title="Select file", filetypes=(("json files", "*.json"), ("all files", "*.*")))
logging.debug("inp_file_path: " + inp_file_path)
if inp_file_path:
default_name = inp_file_path.split('/')[-1].split('.')[0]
out_file_path = filedialog.asksaveasfilename(initialdir="./", initialfile=f"{default_name}.b", title="Save as", filetypes=(("b files","*.b"), ("all files", "*.*")))
logging.debug("out_file_path: " + out_file_path)
if out_file_path:
try:
convert_json2bson(inp_file_path, out_file_path)
except json.decoder.JSONDecodeError as e:
logging.warning("error due decoding json: " + str(e))
messagebox.showerror('Error', e)
except Exception as e:
logging.error("unknown exception: " + str(e))
messagebox.showerror('Error', e)
def __btn_convert_links_static2dynamic_click(self):
logging.debug("__btn_convert_links_static2dynamic_click call")
inp_file_path = filedialog.askopenfilename(initialdir="./", title="Select file", filetypes=(("json files", "*.json"), ("all files", "*.*")))
logging.debug("inp_file_path: " + inp_file_path)
if inp_file_path:
default_name = inp_file_path.split('/')[-1].split('.')[0]
out_file_path = filedialog.asksaveasfilename(initialdir="./", initialfile=f"{default_name}_converted.json", title="Save as", filetypes=(("json files","*.json"), ("all files", "*.*")))
if out_file_path:
try:
convert_links_static2dynamic(inp_file_path, out_file_path)
except Exception as e:
logging.error("unknown exception: " + str(e))
messagebox.showerror('Error', e)
def __btn_run_click(self):
logging.debug("__btn_run_click call")
if self.json_file:
method = self.tests_available[self.radio_button_value.get()]
test_query = self.test_query.get(method)
if self.temp_file_path is None:
parser_path = self.parser_path.get()
else:
parser_path = self.temp_file_path
query = self.entry_query.get()
test_query = test_query.format(
parser_path=parser_path,
test_method=method,
query=query,
search_link=self.json_file.search_link)
logging.debug("RUN " + test_query)
system("start cmd /k {command}".format(command=test_query))
def __btn_select_click(self):
logging.debug("__btn_select_click call")
path = filedialog.askopenfilename(initialdir="./", title="Select file", filetypes=(("json files","*.json"), ("all files", "*.*")))
if path:
self.parser_path.set(path)
logging.debug(f"SET Path: {path}")
self.path_selected()
def __btn_validate_click(self):
logging.debug("__btn_validate_click call")
try:
tmp = json.loads(self.text_box.get('1.0', 'end-1c'))
except json.JSONDecodeError as err:
self.label_validate_result.configure(foreground='red')
self.text_box.see(f'{err.lineno}.{err.colno}')
logging.warning(err)
# https://stackoverflow.com/a/35150895
start, stop = max(0, err.pos - 20), err.pos + 20
snippet = err.doc[start:stop]
snippet = snippet.replace('\n', '')
snippet = snippet.replace('\t', ' ')
snippet = snippet[0:41]
snippet = '...' + snippet + '...'
exact = '-' * (err.pos-start) + '^'
self.label_validate_result_text.set(f'{err}\n\n{snippet}\n{exact}')
else:
self.label_validate_result_text.set('valid json')
self.label_validate_result.configure(foreground='green')
def __btn_clear_click(self):
logging.debug("__btn_clear_click call")
self.text_box.delete('1.0', tk.END)
self.text_box.update()
def use_temp_file(self):
with open('temp.json', 'w', encoding='utf8') as temp:
temp.write(self.json_file.json_text)
self.temp_file_path = abspath(r'.\temp.json')
def update_tests_available_frame(self):
logging.debug("update_tests_available_frame call")
for child in self.tests_frame.winfo_children():
child.pack_forget()
child.destroy()
for i, test_method in enumerate(self.tests_available, 0):
ttk.Radiobutton(self.tests_frame, text=test_method, variable=self.radio_button_value, value=i).pack(anchor='w')
def path_selected(self):
self.json_file = JsonFile(self.parser_path.get())
self.tests_available.clear()
self.tests_available = self.json_file.tests_available
self.update_tests_available_frame()
if self.json_file.status == 'invalid':
self.use_temp_file()
self.update_label_json_status()
self.__btn_clear_click()
self.text_box.insert('1.0', self.json_file.json_original_text)
self.__btn_validate_click()
def update_label_json_status(self):
logging.debug("update_label_json_status call")
if self.json_file.status == 'valid':
self.label_json_status.configure(text='valid json', fg='green')
elif self.json_file.status == 'invalid':
self.label_json_status.configure(text='invalid json', fg='red')
elif self.json_file.status == 'mangled':
self.label_json_status.configure(text='mangled json', fg='orange')
def __del__(self):
logging.info('Program finished')
def log_function_call(func):
def wrapper(*args, **kwargs):
logging.debug(f"{func.__name__} call, args: {args}, kwargs: {kwargs}")
return func(*args, **kwargs)
return wrapper
def convert_links(obj: dict, host=None):
"""
Converts static links to dynamic
https://aniplay.tv -> $scheme$//$hostname$ or %%host%%
:param obj: json object(dictionary) that will be converted
:param host: custom site link e.g. https://aniplay.tv otherwise host will be parsed
:return: new converted object
"""
def converter(object_, ignore_nodes_, host_, in_replace_section_=False):
for key, value in object_.items():
if key == 'replace': # we are in replace section
if isinstance(value, dict): # if value is dictionary
converter(value, ignore_nodes_, host_, in_replace_section_=True)
elif isinstance(value, list): # if value is list
for item in value:
if isinstance(item, dict): # check that `item` is dictionary
converter(item, ignore_nodes_, host_, in_replace_section_=True)
elif isinstance(value, dict): # if value is another block of information
converter(value, ignore_nodes_, host_)
elif isinstance(value, list) and (key not in ignore_nodes_): # if value is list
for item in value:
if isinstance(item, dict): # check that `item` is dictionary
converter(item, ignore_nodes_, host_)
elif isinstance(value, str) and (key not in ignore_nodes_): # if value is string
if not in_replace_section_:
value = value.replace(host_, "$scheme$//$hostname$")
object_[key] = value
else:
value = value.replace(host_, r'%%host%%')
object_[key] = value
_obj = obj.copy()
_ignore_nodes = ('host', 'public_link')
_host = host or obj.get('host').strip('/')
converter(_obj, _ignore_nodes, _host)
return _obj
@log_function_call
def convert_json2bson(inp_fp, out_fp):
# load json
with open(inp_fp, 'rb') as f:
json_obj = json.load(f, object_pairs_hook=OrderedDict)
# convert and write bson
with open(out_fp, 'wb') as f:
f.write(bson.dumps(json_obj))
@log_function_call
def convert_bson2json(inp_fp, out_fp):
# load bson
with open(inp_fp, 'rb') as f:
inp_file = bson.loads(f.read())
# convert and write json
with open(out_fp, 'w', encoding='utf8') as f:
f.write(json.dumps(inp_file, indent=4, ensure_ascii=False))
@log_function_call
def convert_links_static2dynamic(inp_fp, out_fp):
with open(inp_fp, 'rb') as f:
inp_file = json.load(f, object_pairs_hook=OrderedDict)
inp_file = convert_links(inp_file)
with open(out_fp, 'w', encoding='utf8') as f:
f.write(json.dumps(inp_file, indent=4, ensure_ascii=False))
def main():
app = App()
if __name__ == '__main__':
main()