-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsmarthash-gui.py
475 lines (367 loc) · 19 KB
/
smarthash-gui.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
import importlib
import os
import threading
import time
from typing import List, Dict
import PySimpleGUI as sg
from termcolor import cprint
from baseplugin import ParamType, BasePlugin, HookCommandType, HookCommand, UIMode
from functions import PluginError, ServerError, ValidationError, folder_default
from smarthash import smarthash_version, SmartHash, MagicError
def collapsible(layout: List[List], key: str, visible: bool = True) -> sg.pin:
return sg.pin(sg.Column(layout, key=key, visible=visible))
class Args(object):
def __getitem__(self, key: str):
return getattr(self, key)
def __setitem__(self, key, val):
setattr(self, key, val)
def __contains__(self, item):
return hasattr(self, item)
class SmartHashGui(SmartHash):
MAIN_WIDTH = 80
def __init__(self):
self.load_config()
if 'Smarthash GUI' not in self.config:
self.config['Smarthash GUI'] = {'last path': ''}
plugin_filenames = SmartHash.plugin_find()
self.window = None
self.plugins = {}
self.curr_plugin = None
self.folder_browsers = []
self.curr_progress = 0
self.is_hashing = False
self.hooks = {}
self.args = None
for x in plugin_filenames:
self.plugins[x] = importlib.import_module("Plugins." + x).SmarthashPlugin()
if self.plugins[x].title in self.config:
self.plugins[x].set_config(self.config[self.plugins[x].title])
if not hasattr(self.plugins[x], 'handle'):
self.init_error("Could not import \"{0}\" plugin".format(x))
continue
if self.plugins[x].title not in self.config:
self.config[self.plugins[x].title] = {}
for hook in self.plugins[x].hooks:
if hook.element_name not in self.hooks:
self.hooks[hook.element_name] = []
self.hooks[hook.element_name].append(hook)
self.early_return = False
self.init_errors = []
window_title = 'smarthash v{0}'.format(smarthash_version)
window_initialization_text = "Loading plugins..." + " "*40
initialization_text = collapsible([[
sg.Text(window_initialization_text)
]], key='initialization_text')
last_plugin_matches = [x for x in list(self.plugins.values())
if 'selected plugin' in self.config['Smarthash GUI'] and
x.title == self.config['Smarthash GUI']['selected plugin']]
if last_plugin_matches:
self.select_plugin(last_plugin_matches[0])
else:
self.select_plugin(list(self.plugins.values())[0])
plugin_selection = [sg.Text("Select plugin: "),
sg.Combo([x.get_title() for x in self.plugins.values()],
key='plugin_selection',
default_value=self.curr_plugin.get_title(),
enable_events=True,
readonly=True,
size=(30, 1))]
initialization_error = collapsible([
[sg.MLine(" " * 100, key='initialization_error_ml', visible=False, size=(None, 5), text_color='red')]
], key='initialization_error')
progress_bar = collapsible([[
sg.ProgressBar(1, orientation='h', size=(SmartHashGui.MAIN_WIDTH - 34, 20), key='progress_bar'),
sg.Text("0.00%", size=(8, 1), key="progress_bar_percent")
]], key='progress_bar_wrapper', visible=False)
hash_result = collapsible([[
sg.Text(key='hash_result_txt', size=(60, 1))
]], key='hash_result', visible=False)
path_to_hash = self.config['Smarthash GUI']['last path'] \
if self.config['Smarthash GUI']['last path'] else folder_default
main = collapsible([
[sg.Text("Create a torrent from a folder")],
[
sg.Input(path_to_hash, key='path_to_hash', disabled=True, enable_events=True,
size=(SmartHashGui.MAIN_WIDTH, None)),
sg.FolderBrowse()
],
[
sg.Checkbox("Skip video rehash",
key='skip_video_rehash',
default=False,
enable_events=True)
],
plugin_selection,
self.generate_plugin_ui(),
[progress_bar],
[hash_result],
[sg.Button("Create", key='create_button', disabled=True)],
], key='main', visible=False)
self.layout = [
[initialization_text],
[initialization_error],
[main]
]
self.window = sg.Window(window_title, self.layout, icon='assets/icon.ico', finalize=True)
# execute hooks
for element, hooks in self.hooks.items():
for hook in hooks:
if type(self.window[element]) == sg.Combo:
value = self.window[element].DefaultValue
else:
value = self.window[element].DefaultText
# Don't execute hook for default values if set
if not hook.exec_on_default and self.window[element] == value:
continue
if hook.exec_on_init:
self.exec_hook_commands_async(hook, value)
# set the initial state of the create button
self.update_create_button(self.window.read(0)[1])
self.background_thread = threading.Thread(target=self.init)
self.background_thread.start()
self.run()
def generate_plugin_ui(self) -> List[sg.Element]:
plugin_ui = []
for plugin in self.plugins.values():
elements = []
for param in plugin.parameters:
if param.ui_mode not in [UIMode.GUI, UIMode.BOTH]:
continue
default_value = param.default_value
if plugin.title in self.config and param.name in self.config[plugin.title] and param.load_last_value:
default_value = self.config[plugin.title][param.name]
if param.param_type == ParamType.CHECKBOX and type(default_value) != bool:
default_value = default_value == "True"
key = "{0}_{1}".format(plugin.get_title(), param.name)
metadata = {'plugin': plugin.title, 'name': param.name, 'default_value': param.default_value}
if param.param_type == ParamType.TEXT:
elements.append([
collapsible([[
sg.Text(param.label, size=(10, 1)),
sg.Input(default_value,
key=key,
enable_events=True,
size=(SmartHashGui.MAIN_WIDTH - 12, None),
disabled=(param.disabled or param.display_only),
metadata=metadata)
]], visible=param.visible, key=key+'_wrapper')])
elif param.param_type == ParamType.PATH:
elements.append([
collapsible([[
sg.Text(param.label, size=(10, 1)),
sg.Input(default_value,
key=key,
enable_events=True,
readonly=True,
disabled=(param.disabled or param.display_only),
metadata=metadata),
sg.FolderBrowse()
]], visible=param.visible, key=key+'_wrapper')])
self.folder_browsers.append(key)
elif param.param_type == ParamType.SELECT:
elements.append([
collapsible([[
sg.Text(param.label, size=(10, 1)),
sg.Combo(param.options,
key=key,
default_value=default_value,
enable_events=True,
readonly=True,
size=(30, 1),
disabled=(param.disabled or param.display_only),
metadata=metadata)
]], visible=param.visible, key=key+'_wrapper')])
elif param.param_type == ParamType.CHECKBOX:
elements.append([
collapsible([[
sg.Checkbox(param.label,
key=key,
default=default_value,
enable_events=True,
disabled=(param.disabled or param.display_only),
metadata=metadata)
]], visible=param.visible, key=key+'_wrapper')])
elif param.param_type == ParamType.RADIO:
buttons = []
for option in param.options:
buttons.append(
sg.Radio(option,
key,
default=(option == param.default_value),
enable_events=True,
disabled=(param.disabled or param.display_only),
key=key+'_'+option)
)
elements.append([
collapsible([buttons], visible=param.visible, key=key+'_wrapper')])
visible = plugin.get_title() == self.curr_plugin.get_title()
plugin_ui.append(
collapsible(elements, visible=visible, key=plugin.get_title())
)
return plugin_ui
def select_plugin(self, plugin: BasePlugin) -> None:
for _, curr_plugin in self.plugins.items():
visible = curr_plugin == plugin
if self.window:
self.window[curr_plugin.get_title()].update(visible=visible)
if visible:
self.curr_plugin = plugin
self.config['Smarthash GUI']['selected plugin'] = curr_plugin.title
def init(self):
for plugin in self.plugins.values():
self.plugin_update(plugin)
if self.init_errors:
pass
self.window['initialization_text'].update(visible=False)
self.window['main'].update(visible=True)
def run(self):
while True: # The Event Loop
event, values = self.window.read()
if event == sg.WIN_CLOSED or event == 'Exit':
self.terminate()
break
# append a path separator to inputs
if event in self.folder_browsers \
and len(values[event]) and values[event][-1] != '/' and os.path.isdir(values[event]):
values[event] += '/'
self.window[event].update(values[event])
if event == "create_button":
self.args = Args()
self.args['path'] = values['path_to_hash']
self.args['skip_video_rehash'] = values['skip_video_rehash']
for param in self.curr_plugin.parameters:
if param.ui_mode not in [UIMode.GUI, UIMode.BOTH] or param.display_only:
continue
if param.param_type == ParamType.RADIO:
for option in param.options:
if values["{0}_{1}_{2}".format(self.curr_plugin.get_title(), param.name, option)]:
setattr(self.args, param.name, option)
else:
key = "{0}_{1}".format(self.curr_plugin.get_title(), param.name)
setattr(self.args, param.name, values[key])
self.background_thread = threading.Thread(target=self.hash_func,
kwargs={'path': values['path_to_hash']})
self.window['create_button'].update('Hashing...', disabled=True)
self.window['progress_bar'].update(0)
self.window['progress_bar_percent'].update("{:.1f}%".format(0))
self.window['progress_bar_wrapper'].update(visible=True)
self.background_thread.start()
if event == "plugin_selection":
for plugin in self.plugins.values():
if plugin.get_title() == values['plugin_selection']:
self.select_plugin(plugin)
self.config['Smarthash GUI']['selected plugin'] = plugin.title
if event == "path_to_hash":
self.config['Smarthash GUI']['last path'] = values[event]
# match the event with inputs to the current plugin, save to global config
if self.window[event].metadata and 'plugin' in self.window[event].metadata:
element_metadata = self.window[event].metadata
self.config[element_metadata['plugin']][element_metadata['name']] = str(values[event])
# execute hooks
if event in self.hooks:
for hook in self.hooks[event]:
threading.Thread(target=self.exec_hook_commands_async, args=(hook, values[event])).start()
self.update_create_button(values)
print(event)
self.window.close()
def exec_hook_commands_async(self, hook, value):
commands = hook.function(value)
for command in commands:
self.exec_hook_command(command)
# update the create button state, since hooks can unset required values
self.update_create_button(self.window.read(0)[1])
def exec_hook_command(self, command: HookCommand) -> None:
if command.command_type == HookCommandType.UPDATE:
self.window[command.element_name].update(command.value)
elif command.command_type == HookCommandType.VISIBLE:
self.window[command.element_name].update(visible=command.value)
elif command.command_type == HookCommandType.OPTIONS:
old_value = self.window[command.element_name].get()
new_value = old_value if old_value in command.value \
else self.window[command.element_name].metadata['default_value']
self.window[command.element_name].update(new_value, values=command.value)
elif command.command_type == HookCommandType.RESET_DEFAULT:
self.window[command.element_name].update(self.window[command.element_name].metadata['default_value'])
def update_create_button(self, values: Dict) -> None:
# reevaluate the create button's disabled status for all changes
create_disabled = False
if not os.path.isdir(values['path_to_hash']):
create_disabled = True
# Check plugin-specific logic for if the torrent can be created
if not self.curr_plugin.create_valid():
create_disabled = True
parameters = {x.name: x for x in self.curr_plugin.parameters if x.required}
for param in parameters.values():
# checkbox param types always have a value
if param.param_type == ParamType.CHECKBOX:
continue
if param.display_only or not param.visible:
continue
elif param.param_type == ParamType.RADIO:
selected = False
for option in param.options:
if values.get("{0}_{1}_{2}".format(self.curr_plugin.get_title(), param.name, option)):
selected = True
if not selected:
create_disabled = True
else:
value = values.get("{0}_{1}".format(self.curr_plugin.get_title(), param.name))
if not value or value == param.default_value:
create_disabled = True
if self.is_hashing:
create_disabled = True
self.window['create_button'].update(disabled=create_disabled)
def hash_func(self, path):
self.process_folder_wrapper(path)
def process_folder_wrapper(self, path: str):
self.is_hashing = True
self.window['hash_result'].update(visible=False)
try:
self.process_folder(path, self.curr_plugin)
self.window['hash_result_txt'].update('Success!', text_color='green3')
except ValidationError as e:
if e.errors and len(e.errors[0]) > 400:
e.errors[0] = "<error message is too long to display>"
self.window['hash_result_txt'].update(e.errors[0], text_color='red2')
except (MagicError, PluginError) as e:
self.window['hash_result_txt'].update(e.error, text_color='red2')
except ServerError as e:
self.window['hash_result_txt'].update(e.error, text_color='red2')
time.sleep(1)
self.process_folder_wrapper(path)
finally:
self.window['progress_bar_wrapper'].update(visible=False)
self.window['hash_result'].update(visible=True)
self.window['create_button'].update('Create', disabled=False)
self.is_hashing = False
def init_error(self, msg: str):
if self.init_errors and self.init_errors[-1][0] == msg:
self.init_errors[-1][1] += 1
else:
self.init_errors.append([msg, 1])
combined_msg = "\n".join([self.__flatten_error(x) for x in self.init_errors])
self.window['initialization_error_ml'].update(visible=True, value=combined_msg)
cprint(msg, 'red')
def hash_progress_callback(self, amount):
factor = 0.4 if 'video-screenshots' in self.curr_plugin.options else 0.5
self.curr_progress = amount * factor
self.window['progress_bar'].update(self.curr_progress)
self.window['progress_bar_percent'].update("{:.1f}%".format(self.curr_progress*100))
def pricker_progress_callback(self, num_bytes) -> None:
factor = 0.4 if 'video-screenshots' in self.curr_plugin.options else 0.5
self.curr_progress = factor + (num_bytes/self.total_media_size)* factor
self.window['progress_bar'].update(self.curr_progress)
self.window['progress_bar_percent'].update("{:.1f}%".format(self.curr_progress*100))
def image_extaction_progress_callback(self, x: int, total_images: int) -> None:
self.curr_progress = 0.8 + (x / total_images) * 0.2
self.window['progress_bar'].update(self.curr_progress)
self.window['progress_bar_percent'].update("{:.1f}%".format(self.curr_progress*100))
@staticmethod
def __flatten_error(err):
if err[1] == 1:
return err[0]
return "{0} [{1}]".format(err[0], err[1])
def clear_error(self):
self.window['initialization_error'].update(visible=False)
if __name__ == "__main__":
smarthash = SmartHashGui()