forked from stashapp/CommunityScripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
renamerOnUpdate.py
1370 lines (1214 loc) · 49.5 KB
/
renamerOnUpdate.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
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
import difflib
import json
import os
import re
import shutil
import sqlite3
import sys
import time
import traceback
from datetime import datetime
import requests
try:
import psutil # pip install psutil
MODULE_PSUTIL = True
except Exception:
MODULE_PSUTIL = False
try:
import unidecode # pip install Unidecode
MODULE_UNIDECODE = True
except Exception:
MODULE_UNIDECODE = False
try:
import renamerOnUpdate_config as config
except Exception:
import config
import log
DB_VERSION_FILE_REFACTOR = 32
DB_VERSION_SCENE_STUDIO_CODE = 38
DRY_RUN = config.dry_run
DRY_RUN_FILE = None
if config.log_file:
DRY_RUN_FILE = os.path.join(os.path.dirname(config.log_file), "renamerOnUpdate_dryrun.txt")
if DRY_RUN:
if DRY_RUN_FILE and not config.dry_run_append:
if os.path.exists(DRY_RUN_FILE):
os.remove(DRY_RUN_FILE)
log.LogInfo("Dry mode on")
START_TIME = time.time()
FRAGMENT = json.loads(sys.stdin.read())
FRAGMENT_SERVER = FRAGMENT["server_connection"]
PLUGIN_DIR = FRAGMENT_SERVER["PluginDir"]
PLUGIN_ARGS = FRAGMENT['args'].get("mode")
#log.LogDebug("{}".format(FRAGMENT))
def callGraphQL(query, variables=None):
# Session cookie for authentication
graphql_port = str(FRAGMENT_SERVER['Port'])
graphql_scheme = FRAGMENT_SERVER['Scheme']
graphql_cookies = {'session': FRAGMENT_SERVER['SessionCookie']['Value']}
graphql_headers = {
"Accept-Encoding": "gzip, deflate, br",
"Content-Type": "application/json",
"Accept": "application/json",
"Connection": "keep-alive",
"DNT": "1"
}
graphql_domain = FRAGMENT_SERVER['Host']
if graphql_domain == "0.0.0.0":
graphql_domain = "localhost"
# Stash GraphQL endpoint
graphql_url = f"{graphql_scheme}://{graphql_domain}:{graphql_port}/graphql"
json = {'query': query}
if variables is not None:
json['variables'] = variables
try:
response = requests.post(graphql_url, json=json, headers=graphql_headers, cookies=graphql_cookies, timeout=20)
except Exception as e:
exit_plugin(err=f"[FATAL] Error with the graphql request {e}")
if response.status_code == 200:
result = response.json()
if result.get("error"):
for error in result["error"]["errors"]:
raise Exception(f"GraphQL error: {error}")
return None
if result.get("data"):
return result.get("data")
elif response.status_code == 401:
exit_plugin(err="HTTP Error 401, Unauthorised.")
else:
raise ConnectionError(f"GraphQL query failed: {response.status_code} - {response.content}")
def graphql_getScene(scene_id):
query = """
query FindScene($id: ID!, $checksum: String) {
findScene(id: $id, checksum: $checksum) {
...SceneData
}
}
fragment SceneData on Scene {
id
oshash
checksum
title
date
rating
stash_ids {
endpoint
stash_id
}
organized""" + FILE_QUERY + """
studio {
id
name
parent_studio {
id
name
}
}
tags {
id
name
}
performers {
id
name
gender
favorite
rating
stash_ids{
endpoint
stash_id
}
}
movies {
movie {
name
date
}
scene_index
}
}
"""
variables = {
"id": scene_id
}
result = callGraphQL(query, variables)
return result.get('findScene')
# used for bulk
def graphql_findScene(perPage, direc="DESC") -> dict:
query = """
query FindScenes($filter: FindFilterType) {
findScenes(filter: $filter) {
count
scenes {
...SlimSceneData
}
}
}
fragment SlimSceneData on Scene {
id
oshash
checksum
title
date
rating
organized
stash_ids {
endpoint
stash_id
}
""" + FILE_QUERY + """
studio {
id
name
parent_studio {
id
name
}
}
tags {
id
name
}
performers {
id
name
gender
favorite
rating
stash_ids{
endpoint
stash_id
}
}
movies {
movie {
name
date
}
scene_index
}
}
"""
# ASC DESC
variables = {'filter': {"direction": direc, "page": 1, "per_page": perPage, "sort": "updated_at"}}
result = callGraphQL(query, variables)
return result.get("findScenes")
# used to find duplicate
def graphql_findScenebyPath(path, modifier) -> dict:
query = """
query FindScenes($filter: FindFilterType, $scene_filter: SceneFilterType) {
findScenes(filter: $filter, scene_filter: $scene_filter) {
count
scenes {
id
title
}
}
}
"""
# ASC DESC
variables = {
'filter': {
"direction": "ASC",
"page": 1,
"per_page": 40,
"sort": "updated_at"
},
"scene_filter": {
"path": {
"modifier": modifier,
"value": path
}
}
}
result = callGraphQL(query, variables)
return result.get("findScenes")
def graphql_getConfiguration():
query = """
query Configuration {
configuration {
general {
databasePath
}
}
}
"""
result = callGraphQL(query)
return result.get('configuration')
def graphql_getStudio(studio_id):
query = """
query FindStudio($id:ID!) {
findStudio(id: $id) {
id
name
parent_studio {
id
name
}
}
}
"""
variables = {
"id": studio_id
}
result = callGraphQL(query, variables)
return result.get("findStudio")
def graphql_removeScenesTag(id_scenes: list, id_tags: list):
query = """
mutation BulkSceneUpdate($input: BulkSceneUpdateInput!) {
bulkSceneUpdate(input: $input) {
id
}
}
"""
variables = {'input': {"ids": id_scenes, "tag_ids": {"ids": id_tags, "mode": "REMOVE"}}}
result = callGraphQL(query, variables)
return result
def graphql_getBuild():
query = """
{
systemStatus {
databaseSchema
}
}
"""
result = callGraphQL(query)
return result['systemStatus']['databaseSchema']
def find_diff_text(a: str, b: str):
addi = minus = stay = ""
minus_ = addi_ = 0
for _, s in enumerate(difflib.ndiff(a, b)):
if s[0] == ' ':
stay += s[-1]
minus += "*"
addi += "*"
elif s[0] == '-':
minus += s[-1]
minus_ += 1
elif s[0] == '+':
addi += s[-1]
addi_ += 1
if minus_ > 20 or addi_ > 20:
log.LogDebug(f"Diff Checker: +{addi_}; -{minus_};")
log.LogDebug(f"OLD: {a}")
log.LogDebug(f"NEW: {b}")
else:
log.LogDebug(f"Original: {a}\n- Charac: {minus}\n+ Charac: {addi}\n Result: {b}")
return
def has_handle(fpath, all_result=False):
lst = []
for proc in psutil.process_iter():
try:
for item in proc.open_files():
if fpath == item.path:
if all_result:
lst.append(proc)
else:
return proc
except Exception:
pass
return lst
def config_edit(name: str, state: bool):
found = 0
try:
with open(config.__file__, 'r', encoding='utf8') as file:
config_lines = file.readlines()
with open(config.__file__, 'w', encoding='utf8') as file_w:
for line in config_lines:
if len(line.split("=")) > 1:
if name == line.split("=")[0].strip():
file_w.write(f"{name} = {state}\n")
found += 1
continue
file_w.write(line)
except PermissionError as err:
log.LogError(f"You don't have the permission to edit config.py ({err})")
return found
def check_longpath(path: str):
# Trying to prevent error with long paths for Win10
# https://docs.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation?tabs=cmd
if len(path) > 240 and not IGNORE_PATH_LENGTH:
log.LogError(f"The path is too long ({len(path)} > 240). You can look at 'order_field'/'ignore_path_length' in config.")
return 1
def get_template_filename(scene: dict):
template = None
# Change by Studio
if scene.get("studio") and config.studio_templates:
template_found = False
current_studio = scene.get("studio")
if config.studio_templates.get(current_studio['name']):
template = config.studio_templates[current_studio['name']]
template_found = True
# by first Parent found
while current_studio.get("parent_studio") and not template_found:
if config.studio_templates.get(current_studio.get("parent_studio").get("name")):
template = config.studio_templates[current_studio['parent_studio']['name']]
template_found = True
current_studio = graphql_getStudio(current_studio.get("parent_studio")['id'])
# Change by Tag
tags = [x["name"] for x in scene["tags"]]
if scene.get("tags") and config.tag_templates:
for match, job in config.tag_templates.items():
if match in tags:
template = job
break
return template
def get_template_path(scene: dict):
template = {"destination": "", "option": [], "opt_details": {}}
# Change by Path
if config.p_path_templates:
for match, job in config.p_path_templates.items():
if match in scene["path"]:
template["destination"] = job
break
# Change by Studio
if scene.get("studio") and config.p_studio_templates:
if config.p_studio_templates.get(scene["studio"]["name"]):
template["destination"] = config.p_studio_templates[scene["studio"]["name"]]
# by Parent
if scene["studio"].get("parent_studio"):
if config.p_studio_templates.get(scene["studio"]["name"]):
template["destination"] = config.p_studio_templates[scene["studio"]["name"]]
# Change by Tag
tags = [x["name"] for x in scene["tags"]]
if scene.get("tags") and config.p_tag_templates:
for match, job in config.p_tag_templates.items():
if match in tags:
template["destination"] = job
break
if scene.get("tags") and config.p_tag_option:
for tag in scene["tags"]:
if config.p_tag_option.get(tag["name"]):
opt = config.p_tag_option[tag["name"]]
template["option"].extend(opt)
if "clean_tag" in opt:
if template["opt_details"].get("clean_tag"):
template["opt_details"]["clean_tag"].append(tag["id"])
else:
template["opt_details"] = {"clean_tag": [tag["id"]]}
if not scene['organized'] and PATH_NON_ORGANIZED:
template["destination"] = PATH_NON_ORGANIZED
return template
def sort_performer(lst_use: list, lst_app=[]):
for p in lst_use:
lst_use[p].sort()
for p in lst_use.values():
for n in p:
if n not in lst_app:
lst_app.append(n)
return lst_app
def sort_rating(d: dict):
new_d = {}
for i in sorted(d.keys(), reverse=True):
new_d[i] = d[i]
return new_d
def extract_info(scene: dict, template: None):
# Grabbing things from Stash
scene_information = {}
scene_information['current_path'] = str(scene['path'])
# note: contain the dot (.mp4)
scene_information['file_extension'] = os.path.splitext(scene_information['current_path'])[1]
# note: basename contains the extension
scene_information['current_filename'] = os.path.basename(scene_information['current_path'])
scene_information['current_directory'] = os.path.dirname(scene_information['current_path'])
scene_information['oshash'] = scene['oshash']
scene_information['checksum'] = scene.get("checksum")
scene_information['studio_code'] = scene.get("code")
if scene.get("stash_ids"):
#todo support other db that stashdb ?
scene_information['stashid_scene'] = scene['stash_ids'][0]["stash_id"]
if template.get("path"):
if "^*" in template["path"]["destination"]:
template["path"]["destination"] = template["path"]["destination"].replace("^*", scene_information['current_directory'])
scene_information['template_split'] = os.path.normpath(template["path"]["destination"]).split(os.sep)
scene_information['current_path_split'] = os.path.normpath(scene_information['current_path']).split(os.sep)
if FILENAME_ASTITLE and not scene.get("title"):
scene["title"] = scene_information['current_filename']
# Grab Title (without extension if present)
if scene.get("title"):
# Removing extension if present in title
scene_information['title'] = re.sub(fr"{scene_information['file_extension']}$", "", scene['title'])
if PREPOSITIONS_REMOVAL:
for word in PREPOSITIONS_LIST:
scene_information['title'] = re.sub(fr"^{word}[\s_-]", "", scene_information['title'])
# Grab Date
scene_information['date'] = scene.get("date")
if scene_information['date']:
date_scene = datetime.strptime(scene_information['date'], r"%Y-%m-%d")
scene_information['date_format'] = datetime.strftime(date_scene, config.date_format)
# Grab Duration
scene_information['duration'] = scene['file']['duration']
if config.duration_format:
scene_information['duration'] = time.strftime(config.duration_format, time.gmtime(scene_information['duration']))
else:
scene_information['duration'] = str(scene_information['duration'])
# Grab Rating
if scene.get("rating"):
scene_information['rating'] = RATING_FORMAT.format(scene['rating'])
# Grab Performer
scene_information['performer_path'] = None
if scene.get("performers"):
perf_list = []
perf_list_stashid = []
perf_rating = {"0": []}
perf_favorite = {"yes": [], "no": []}
for perf in scene['performers']:
if perf.get("gender"):
if perf['gender'] in PERFORMER_IGNOREGENDER:
continue
elif "UNDEFINED" in PERFORMER_IGNOREGENDER:
continue
# path related
if template.get("path"):
if "inverse_performer" in template["path"]["option"]:
perf["name"] = re.sub(r"([a-zA-Z]+)(\s)([a-zA-Z]+)", r"\3 \1", perf["name"])
perf_list.append(perf['name'])
if perf.get('rating'):
if perf_rating.get(str(perf['rating'])) is None:
perf_rating[str(perf['rating'])] = []
perf_rating[str(perf['rating'])].append(perf['name'])
else:
perf_rating["0"].append(perf['name'])
if perf.get('favorite'):
perf_favorite['yes'].append(perf['name'])
else:
perf_favorite['no'].append(perf['name'])
# if the path already contains the name we keep this one
if perf["name"] in scene_information['current_path_split'] and scene_information.get('performer_path') is None and PATH_KEEP_ALRPERF:
scene_information['performer_path'] = perf["name"]
log.LogDebug(f"[PATH] Keeping the current name of the performer '{perf['name']}'")
perf_rating = sort_rating(perf_rating)
# sort performer
if PERFORMER_SORT == "rating":
# sort alpha
perf_list = sort_performer(perf_rating)
elif PERFORMER_SORT == "favorite":
perf_list = sort_performer(perf_favorite)
elif PERFORMER_SORT == "mix":
perf_list = []
for p in perf_favorite:
perf_favorite[p].sort()
for p in perf_favorite.get("yes"):
perf_list.append(p)
perf_list = sort_performer(perf_rating, perf_list)
elif PERFORMER_SORT == "mixid":
perf_list = []
for p in perf_favorite.get("yes"):
perf_list.append(p)
for p in perf_rating.values():
for n in p:
if n not in perf_list:
perf_list.append(n)
elif PERFORMER_SORT == "name":
perf_list.sort()
if not scene_information['performer_path'] and perf_list:
scene_information['performer_path'] = perf_list[0]
if len(perf_list) > PERFORMER_LIMIT:
if not PERFORMER_LIMIT_KEEP:
log.LogInfo(f"More than {PERFORMER_LIMIT} performer(s). Ignoring $performer")
perf_list = []
else:
log.LogInfo(f"Limited the amount of performer to {PERFORMER_LIMIT}")
perf_list = perf_list[0: PERFORMER_LIMIT]
scene_information['performer'] = PERFORMER_SPLITCHAR.join(perf_list)
if perf_list:
for p in perf_list:
for perf in scene['performers']:
#todo support other db that stashdb ?
if p == perf['name'] and perf.get('stash_ids'):
perf_list_stashid.append(perf['stash_ids'][0]["stash_id"])
break
scene_information['stashid_performer'] = PERFORMER_SPLITCHAR.join(perf_list_stashid)
if not PATH_ONEPERFORMER:
scene_information['performer_path'] = PERFORMER_SPLITCHAR.join(perf_list)
elif PATH_NOPERFORMER_FOLDER:
scene_information['performer_path'] = "NoPerformer"
# Grab Studio name
if scene.get("studio"):
if SQUEEZE_STUDIO_NAMES:
scene_information['studio'] = scene['studio']['name'].replace(' ', '')
else:
scene_information['studio'] = scene['studio']['name']
scene_information['studio_family'] = scene_information['studio']
studio_hierarchy = [scene_information['studio']]
# Grab Parent name
if scene['studio'].get("parent_studio"):
if SQUEEZE_STUDIO_NAMES:
scene_information['parent_studio'] = scene['studio']['parent_studio']['name'].replace(' ', '')
else:
scene_information['parent_studio'] = scene['studio']['parent_studio']['name']
scene_information['studio_family'] = scene_information['parent_studio']
studio_p = scene['studio']
while studio_p.get("parent_studio"):
studio_p = graphql_getStudio(studio_p['parent_studio']['id'])
if studio_p:
if SQUEEZE_STUDIO_NAMES:
studio_hierarchy.append(studio_p['name'].replace(' ', ''))
else:
studio_hierarchy.append(studio_p['name'])
studio_hierarchy.reverse()
scene_information['studio_hierarchy'] = studio_hierarchy
# Grab Tags
if scene.get("tags"):
tag_list = []
for tag in scene['tags']:
# ignore tag in blacklist
if tag['name'] in TAGS_BLACKLIST:
continue
# check if there is a whilelist
if len(TAGS_WHITELIST) > 0:
if tag['name'] in TAGS_WHITELIST:
tag_list.append(tag['name'])
else:
tag_list.append(tag['name'])
scene_information['tags'] = TAGS_SPLITCHAR.join(tag_list)
# Grab Height (720p,1080p,4k...)
scene_information['bitrate'] = str(round(int(scene['file']['bitrate']) / 1000000, 2))
scene_information['resolution'] = 'SD'
scene_information['height'] = f"{scene['file']['height']}p"
if scene['file']['height'] >= 720:
scene_information['resolution'] = 'HD'
if scene['file']['height'] >= 2160:
scene_information['height'] = '4k'
scene_information['resolution'] = 'UHD'
if scene['file']['height'] >= 2880:
scene_information['height'] = '5k'
if scene['file']['height'] >= 3384:
scene_information['height'] = '6k'
if scene['file']['height'] >= 4320:
scene_information['height'] = '8k'
# For Phone ?
if scene['file']['height'] > scene['file']['width']:
scene_information['resolution'] = 'VERTICAL'
if scene.get("movies"):
scene_information["movie_title"] = scene["movies"][0]["movie"]["name"]
if scene["movies"][0]["movie"].get("date"):
scene_information["movie_year"] = scene["movies"][0]["movie"]["date"][0:4]
if scene["movies"][0].get("scene_index"):
scene_information["movie_index"] = scene["movies"][0]["scene_index"]
scene_information["movie_scene"] = f"scene {scene_information['movie_index']}"
# Grab Video and Audio codec
scene_information['video_codec'] = scene['file']['video_codec'].upper()
scene_information['audio_codec'] = scene['file']['audio_codec'].upper()
if scene_information.get("date"):
scene_information['year'] = scene_information['date'][0:4]
if FIELD_WHITESPACE_SEP:
for key, value in scene_information.items():
if key in ["current_path", "current_filename", "current_directory", "current_path_split", "template_split"]:
continue
if type(value) is str:
scene_information[key] = value.replace(" ", FIELD_WHITESPACE_SEP)
elif type(value) is list:
scene_information[key] = [x.replace(" ", FIELD_WHITESPACE_SEP) for x in value]
return scene_information
def replace_text(text: str):
for old, new in FILENAME_REPLACEWORDS.items():
if type(new) is str:
new = [new]
if len(new) > 1:
if new[1] == "regex":
tmp = re.sub(old, new[0], text)
if tmp != text:
log.LogDebug(f"Regex matched: {text} -> {tmp}")
else:
if new[1] == "word":
tmp = re.sub(fr'([\s_-])({old})([\s_-])', f'\\1{new[0]}\\3', text)
elif new[1] == "any":
tmp = text.replace(old, new[0])
if tmp != text:
log.LogDebug(f"'{old}' changed with '{new[0]}'")
else:
tmp = re.sub(fr'([\s_-])({old})([\s_-])', f'\\1{new[0]}\\3', text)
if tmp != text:
log.LogDebug(f"'{old}' changed with '{new[0]}'")
text = tmp
return tmp
def cleanup_text(text: str):
text = re.sub(r'\(\W*\)|\[\W*\]|{[^a-zA-Z0-9]*}', '', text)
text = re.sub(r'[{}]', '', text)
text = remove_consecutive_nonword(text)
return text.strip(" -_.")
def remove_consecutive_nonword(text: str):
for _ in range(0, 10):
m = re.findall(r'(\W+)\1+', text)
if m:
text = re.sub(r'(\W+)\1+', r'\1', text)
else:
break
return text
def field_replacer(text: str, scene_information:dict):
field_found = re.findall(r"\$\w+", text)
result = text
title = None
replaced_word = ""
if field_found:
field_found.sort(key=len, reverse=True)
for i in range(0, len(field_found)):
f = field_found[i].replace("$", "").strip("_")
# If $performer is before $title, prevent having duplicate text.
if f == "performer" and len(field_found) > i + 1 and scene_information.get('performer'):
if field_found[i+1] == "$title" and scene_information.get('title') and PREVENT_TITLE_PERF:
if re.search(f"^{scene_information['performer'].lower()}", scene_information['title'].lower()):
log.LogDebug("Ignoring the performer field because it's already in start of title")
result = result.replace("$performer", "")
continue
replaced_word = scene_information.get(f)
if not replaced_word:
replaced_word = ""
if FIELD_REPLACER.get(f"${f}"):
replaced_word = replaced_word.replace(FIELD_REPLACER[f"${f}"]["replace"], FIELD_REPLACER[f"${f}"]["with"])
if f == "title":
title = replaced_word.strip()
continue
if replaced_word == "":
result = result.replace(field_found[i], replaced_word)
else:
result = result.replace(f"${f}", replaced_word)
return result, title
def makeFilename(scene_information: dict, query: str) -> str:
new_filename = str(query)
r, t = field_replacer(new_filename, scene_information)
if FILENAME_REPLACEWORDS:
r = replace_text(r)
if not t:
r = r.replace("$title", "")
r = cleanup_text(r)
if t:
r = r.replace("$title", t)
# Replace spaces with splitchar
r = r.replace(' ', FILENAME_SPLITCHAR)
return r
def makePath(scene_information: dict, query: str) -> str:
new_filename = str(query)
new_filename = new_filename.replace("$performer", "$performer_path")
r, t = field_replacer(new_filename, scene_information)
if not t:
r = r.replace("$title", "")
r = cleanup_text(r)
if t:
r = r.replace("$title", t)
return r
def capitalizeWords(s: str):
# thanks to BCFC_1982 for it
return re.sub(r"[A-Za-z]+('[A-Za-z]+)?", lambda word: word.group(0).capitalize(), s)
def create_new_filename(scene_info: dict, template: str):
new_filename = makeFilename(scene_info, template) + DUPLICATE_SUFFIX[scene_info['file_index']] + scene_info['file_extension']
if FILENAME_LOWER:
new_filename = new_filename.lower()
if FILENAME_TITLECASE:
new_filename = capitalizeWords(new_filename)
# Remove illegal character for Windows
new_filename = re.sub('[\\/:"*?<>|]+', '', new_filename)
if FILENAME_REMOVECHARACTER:
new_filename = re.sub(f'[{FILENAME_REMOVECHARACTER}]+', '', new_filename)
# Trying to remove non standard character
if MODULE_UNIDECODE and UNICODE_USE:
new_filename = unidecode.unidecode(new_filename, errors='preserve')
else:
# Using typewriter for Apostrophe
new_filename = re.sub("[’‘”“]+", "'", new_filename)
return new_filename
def remove_consecutive(liste: list):
new_list = []
for i in range(0, len(liste)):
if i != 0 and liste[i] == liste[i - 1]:
continue
new_list.append(liste[i])
return new_list
def create_new_path(scene_info: dict, template: dict):
# Create the new path
# Split the template path
path_split = scene_info['template_split']
path_list = []
for part in path_split:
if ":" in part and path_split[0]:
path_list.append(part)
elif part == "$studio_hierarchy":
if not scene_info.get("studio_hierarchy"):
continue
for p in scene_info["studio_hierarchy"]:
path_list.append(re.sub('[\\/:"*?<>|]+', '', p).strip())
else:
path_list.append(re.sub('[\\/:"*?<>|]+', '', makePath(scene_info, part)).strip())
# Remove blank, empty string
path_split = [x for x in path_list if x]
# The first character was a seperator, so put it back.
if path_list[0] == "":
path_split.insert(0, "")
if PREVENT_CONSECUTIVE:
# remove consecutive (/FolderName/FolderName/video.mp4 -> FolderName/video.mp4
path_split = remove_consecutive(path_split)
if "^*" in template["path"]["destination"]:
if scene_info['current_directory'] != os.sep.join(path_split):
path_split.pop(len(scene_info['current_directory']))
path_edited = os.sep.join(path_split)
if FILENAME_REMOVECHARACTER:
path_edited = re.sub(f'[{FILENAME_REMOVECHARACTER}]+', '', path_edited)
# Using typewriter for Apostrophe
new_path = re.sub("[’‘”“]+", "'", path_edited)
return new_path
def connect_db(path: str):
try:
sqliteConnection = sqlite3.connect(path, timeout=10)
log.LogDebug("Python successfully connected to SQLite")
except sqlite3.Error as error:
log.LogError(f"FATAL SQLITE Error: {error}")
return None
return sqliteConnection
def checking_duplicate_db(scene_info: dict):
scenes = graphql_findScenebyPath(scene_info['final_path'], "EQUALS")
if scenes["count"] > 0:
log.LogError("Duplicate path detected")
for dupl_row in scenes["scenes"]:
log.LogWarning(f"Identical path: [{dupl_row['id']}]")
return 1
scenes = graphql_findScenebyPath(scene_info['new_filename'], "EQUALS")
if scenes["count"] > 0:
for dupl_row in scenes["scenes"]:
if dupl_row['id'] != scene_info['scene_id']:
log.LogWarning(f"Duplicate filename: [{dupl_row['id']}]")
def db_rename(stash_db: sqlite3.Connection, scene_info):
cursor = stash_db.cursor()
# Database rename
cursor.execute("UPDATE scenes SET path=? WHERE id=?;", [scene_info['final_path'], scene_info['scene_id']])
stash_db.commit()
# Close DB
cursor.close()
def db_rename_refactor(stash_db: sqlite3.Connection, scene_info):
cursor = stash_db.cursor()
# 2022-09-17T11:25:52+02:00
mod_time = datetime.now().astimezone().isoformat('T', 'seconds')
# get the next id that we should use if needed
cursor.execute("SELECT MAX(id) from folders")
new_id = cursor.fetchall()[0][0] + 1
# get the old folder id
cursor.execute("SELECT id FROM folders WHERE path=?", [scene_info['current_directory']])
old_folder_id = cursor.fetchall()[0][0]
# check if the folder of file is created in db
cursor.execute("SELECT id FROM folders WHERE path=?", [scene_info['new_directory']])
folder_id = cursor.fetchall()
if not folder_id:
dir = scene_info['new_directory']
# reduce the path to find a parent folder
for _ in range(1, len(scene_info['new_directory'].split(os.sep))):
dir = os.path.dirname(dir)
cursor.execute("SELECT id FROM folders WHERE path=?", [dir])
parent_id = cursor.fetchall()
if parent_id:
# create a new row with the new folder with the parent folder find above
cursor.execute(
"INSERT INTO 'main'.'folders'('id', 'path', 'parent_folder_id', 'mod_time', 'created_at', 'updated_at', 'zip_file_id') VALUES (?, ?, ?, ?, ?, ?, ?);",
[
new_id, scene_info['new_directory'], parent_id[0][0],
mod_time, mod_time, mod_time, None
])
stash_db.commit()
folder_id = new_id
break
else:
folder_id = folder_id[0][0]
if folder_id:
cursor.execute("SELECT file_id from scenes_files WHERE scene_id=?", [scene_info['scene_id']])
file_ids = cursor.fetchall()
file_id = None
for f in file_ids:
# it can have multiple file for a scene
cursor.execute("SELECT parent_folder_id from files WHERE id=?", [f[0]])
check_parent = cursor.fetchall()[0][0]
# if the parent id is the one found above section, we find our file.s
if check_parent == old_folder_id:
file_id = f[0]
break
if file_id:
#log.LogDebug(f"UPDATE files SET basename={scene_info['new_filename']}, parent_folder_id={folder_id}, updated_at={mod_time} WHERE id={file_id};")
cursor.execute("UPDATE files SET basename=?, parent_folder_id=?, updated_at=? WHERE id=?;", [scene_info['new_filename'], folder_id, mod_time, file_id])
cursor.close()
stash_db.commit()
else:
raise Exception("Failed to find file_id")
else:
cursor.close()
raise Exception(f"You need to setup a library with the new location ({scene_info['new_directory']}) and scan at least 1 file")
def file_rename(current_path: str, new_path: str, scene_info: dict):
# OS Rename
if not os.path.isfile(current_path):
log.LogWarning(f"[OS] File doesn't exist in your Disk/Drive ({current_path})")
return 1
# moving/renaming
new_dir = os.path.dirname(new_path)
current_dir = os.path.dirname(current_path)
if not os.path.exists(new_dir):
log.LogInfo(f"Creating folder because it don't exist ({new_dir})")
os.makedirs(new_dir)
try:
shutil.move(current_path, new_path)
except PermissionError as err:
if "[WinError 32]" in str(err) and MODULE_PSUTIL:
log.LogWarning("A process is using this file (Probably FFMPEG), trying to find it ...")
# Find which process accesses the file, it's ffmpeg for sure...
process_use = has_handle(current_path, PROCESS_ALLRESULT)
if process_use:
# Terminate the process then try again to rename
log.LogDebug(f"Process that uses this file: {process_use}")
if PROCESS_KILL:
p = psutil.Process(process_use.pid)
p.terminate()
p.wait(10)
# If process is not terminated, this will create an error again.
try:
shutil.move(current_path, new_path)
except Exception as err:
log.LogError(f"Something still prevents renaming the file. {err}")
return 1
else:
log.LogError("A process prevents renaming the file.")
return 1
else:
log.LogError(f"Something prevents renaming the file. {err}")
return 1
# checking if the move/rename work correctly
if os.path.isfile(new_path):
log.LogInfo(f"[OS] File Renamed! ({current_path} -> {new_path})")
if LOGFILE:
try:
with open(LOGFILE, 'a', encoding='utf-8') as f:
f.write(f"{scene_info['scene_id']}|{current_path}|{new_path}|{scene_info['oshash']}\n")
except Exception as err:
shutil.move(new_path, current_path)
log.LogError(f"Restoring the original path, error writing the logfile: {err}")
return 1
if REMOVE_EMPTY_FOLDER:
with os.scandir(current_dir) as it:
if not any(it):
log.LogInfo(f"Removing empty folder ({current_dir})")
try:
os.rmdir(current_dir)
except Exception as err:
log.logWarning(f"Fail to delete empty folder {current_dir} - {err}")
else: