-
Notifications
You must be signed in to change notification settings - Fork 3
/
Executor.py
159 lines (129 loc) · 5.47 KB
/
Executor.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
import requests
from getch import getch
from pathlib import Path
import utils
import re
from utils import lenInBytes
import sys
from datetime import date
class Executor:
def __init__(self, setting):
self.setting = setting
day = date.today().strftime("%Y%m%d")
self.renameRecords = open(
f"renameHistory_{day}.txt", "a", encoding="utf-8") # TODO: filename to config
def HandleFiles(self, info, bangou, fileNames):
print(
f"===== 2/3: handle bangou {utils.yellowStr(bangou)}")
self.HandleBangou(info, fileNames[bangou][0])
if len(fileNames[bangou]) > 1: # need to rename files with index
for index, fileName in enumerate(fileNames[bangou]):
self.HandleFile(info, fileName, index)
else:
self.HandleFile(info, fileNames[bangou][0])
def HandleBangou(self, info, path): # only save one copy of album and thumb
if self.setting.saveAlbum:
self.SaveAlbum(info, path)
if self.setting.saveThumb:
self.SaveThumb(info, path)
def HandleFile(self, info, path, index=-1):
print(
f"===== 3/3: handle file {utils.yellowStr(str(path))}")
self.Rename(info, path, index)
# optional TODO: fill video meta description in video file
# TODO: option: new folder for all video file, for the same actor, for the same tag # create link
def getValidWindowsFileName(self, fileName):
"""
https://docs.microsoft.com/zh-tw/windows/win32/fileio/naming-a-file?redirectedfrom=MSDN
"""
return re.sub(r"[><:\"/\\\|\?*]", "_", fileName)
def Rename(self, info, path, index):
newFileName = self.setting.fileNameFormat
for key in info:
infokey = "{" + key + "}"
infovalue = info[key]
if type(infovalue) is list:
infovalue = ""
for element in info[key]:
infovalue = infovalue + "[" + element + "]"
newFileName = newFileName.replace(infokey, infovalue)
if "win" in sys.platform:
newFileName = self.getValidWindowsFileName(newFileName)
# handle multiple files with the same bangou
numberStr = ("_" + str(index+1)) if (index != -1) else ""
# handle file name too long error
if lenInBytes(newFileName) + lenInBytes(numberStr) + lenInBytes(path.suffix) > self.setting.maxFileLength:
print(utils.blueBackStr(f"File name too long: {newFileName}"))
maxFileLength = self.setting.maxFileLength - \
lenInBytes(path.suffix) - lenInBytes(numberStr)
while lenInBytes(newFileName) > maxFileLength:
newFileName = newFileName[0:-1]
print(
f"After truncate file name: {utils.blueBackStr(newFileName)}")
newName = newFileName + numberStr + path.suffix
if path.name == newName:
print(
f"File {utils.grayBackStr(str(path))} no need to rename")
return
self.DoRename(path, newName)
def DoRename(self, path, newName):
newPath = path.parents[0] / newName
print(f"Rename {utils.blueBackStr(str(path))}\n" +
f"To {utils.greenBackStr(str(newPath))}")
if self.setting.dryRun:
return
if self.setting.renameCheck:
print(utils.blueBackStr(f"Do you want to execute rename?(Y/n)"))
response = getch()
print(response)
if response.lower() == "n":
print("User cancel rename")
return
try:
self.renameRecords.write(f"{path} -> {newPath}\n")
self.renameRecords.flush()
path.rename(newPath)
except Exception as e:
print(
utils.redBackStr(f"Rename [{str(path)}] to [{str(newPath)}] failed"))
print(e)
def SaveAlbum(self, info, path):
if not info["album"]:
print("Album link not found")
return
albumFileName = info["bangou"] + ".jpg"
albumPath = Path(path.parents[0] / albumFileName)
if albumPath.exists():
print(
f"Album {utils.blueBackStr(str(albumPath))} already exists")
return
self.DoSaveAlbum(info["album"], albumPath)
def DoSaveAlbum(self, fileURL, albumPath):
print(
f"Save album {utils.greenBackStr(str(albumPath))}")
if self.setting.dryRun:
return
with open(albumPath, 'wb') as albumFile:
fileObject = requests.get(fileURL)
albumFile.write(fileObject.content)
def SaveThumb(self, info, path):
if not info["thumbs"]:
print("Thumbnail link not found")
return
for index, thumb in enumerate(info["thumbs"]):
fileName = info["bangou"] + "_thumb" + \
str(index).zfill(2) + ".jpg"
filePath = Path(path.parents[0] / fileName)
if filePath.exists():
print(
f"Thumbnail {utils.blueBackStr(str(filePath))} already exists")
continue
self.DoSaveThumb(thumb, filePath)
def DoSaveThumb(self, fileURL, filePath):
print(
f"Save thumbnail {utils.greenBackStr(str(filePath))}")
if self.setting.dryRun:
return
with open(filePath, 'wb') as thumbFile:
fileObject = requests.get(fileURL)
thumbFile.write(fileObject.content)