-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
257 lines (202 loc) · 7.65 KB
/
main.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
import re
import requests
import os
import sys
import shutil
import platform
if platform.system() == 'Windows':
import ctypes
from PIL import Image
import win32api
import win32con
from ctypes import POINTER, Structure, c_wchar, c_int, sizeof, byref
from ctypes.wintypes import BYTE, WORD, DWORD, LPWSTR, LPSTR
elif platform.system() == 'Darwin':
import Cocoa
from PIL import Image
# 自定义区域
TMDb_API_Key = '' # TMDb 的 API Key
ext_list = [".mkv", ".mp4"] # 脚本扫描的文件扩展名
# 自定义区域结束
TMDb_API_URL = 'https://api.themoviedb.org/3'
def getMetadata(fileName):
'''
Get metadata from file name.
'''
print('获取元数据...')
res = re.sub(r'\[.*?\]|\(.*?\)', '', fileName) # 删除 [] 内容
res = re.sub(r'[^\x00-\x7f]', '', res) # 删除中文
year = False
if re.search(r"\d{4}\.", res):
year = re.findall(r"\d{4}\.", res)[-1][:-1] # 获取年份
res = res[:res.rfind(re.findall(r"\d{4}\.", res)[-1])] # 删除年份后内容
res = res.replace('.', ' ') # 删除 . 符号
res = ' '.join(res.split()) # 删除多余空格
if res:
return res, year
else:
return False
def SearchonTMDb(title, year):
'''
Get movie id from TMDb.
'''
print('搜索电影信息...')
TMDbSearchURL = TMDb_API_URL+'/search/movie'
TMDbSearchData = {
'api_key': TMDb_API_Key,
'query': title,
'year': year
}
TMDbSearchRes = requests.get(
url=TMDbSearchURL, params=TMDbSearchData).json()
if TMDbSearchRes['total_results']:
TMDbMovieID = TMDbSearchRes['results'][0]['id']
return str(TMDbMovieID)
else:
return False
def DetailsonTMDb(TMDbMovieID):
'''
Get the primary information about a movie from TMDb via movie id.
'''
TMDbDetailsURL = TMDb_API_URL+'/movie/'+TMDbMovieID
TMDbDetailsData = {
'api_key': TMDb_API_Key,
'language': 'zh-CN'
}
TMDbDetailsRes = requests.get(
url=TMDbDetailsURL, params=TMDbDetailsData).json()
title_zh_CN = TMDbDetailsRes['title'].replace(': ', ':')
original_title = TMDbDetailsRes['original_title'].replace(': ', ':')
original_language = TMDbDetailsRes['original_language']
return title_zh_CN, original_title, original_language
def getPosterImage(TMDbMovieID, original_language):
'''
Get poster image from TMDb.
'''
print('下载电影封面...')
TMDbImageURL = TMDb_API_URL+'/movie/'+TMDbMovieID+'/images'
TMDbImageData = {
'api_key': TMDb_API_Key,
'language': original_language
}
try:
TMDbImageRes = requests.get(TMDbImageURL, params=TMDbImageData).json()
posterPath = TMDbImageRes['posters'][0]['file_path']
except IndexError:
TMDbImageData = {
'api_key': TMDb_API_Key,
}
TMDbImageRes = requests.get(TMDbImageURL, params=TMDbImageData).json()
posterPath = TMDbImageRes['posters'][0]['file_path']
TMDbImageBaseURL = 'https://image.tmdb.org/t/p/w300'
posterURL = TMDbImageBaseURL+posterPath
posterImage = requests.get(posterURL)
return posterImage.content
def changeFloderIconWin(folderPath, posterLocalPath):
img = Image.open(posterLocalPath)
x, y = img.size
x = int(256/y*x)
img = img.resize((x, 256), Image.ANTIALIAS)
img_new = Image.new('RGBA', (256, 256), (0, 0, 0, 0))
img_new.paste(img, (int((256 - x) / 2), 0))
img_new.save(folderPath+'favicon.ico', "ico", quality=100)
iconPath = 'favicon.ico'
'''
此处修改文件夹图标的方法来自于 https://stackoverflow.com/questions/4662759/how-to-change-folder-icons-with-python-on-windows
'''
# HICON = c_int
LPTSTR = LPWSTR
# TCHAR = c_wchar
# MAX_PATH = 260
FCSM_ICONFILE = 0x00000010
FCS_FORCEWRITE = 0x00000002
# SHGFI_ICONLOCATION = 0x000001000
class GUID(Structure):
_fields_ = [
('Data1', DWORD),
('Data2', WORD),
('Data3', WORD),
('Data4', BYTE * 8)]
class SHFOLDERCUSTOMSETTINGS(Structure):
_fields_ = [
('dwSize', DWORD),
('dwMask', DWORD),
('pvid', POINTER(GUID)),
('pszWebViewTemplate', LPTSTR),
('cchWebViewTemplate', DWORD),
('pszWebViewTemplateVersion', LPTSTR),
('pszInfoTip', LPTSTR),
('cchInfoTip', DWORD),
('pclsid', POINTER(GUID)),
('dwFlags', DWORD),
('pszIconFile', LPTSTR),
('cchIconFile', DWORD),
('iIconIndex', c_int),
('pszLogo', LPTSTR),
('cchLogo', DWORD)]
shell32 = ctypes.windll.shell32
fcs = SHFOLDERCUSTOMSETTINGS()
fcs.dwSize = sizeof(fcs)
fcs.dwMask = FCSM_ICONFILE
fcs.pszIconFile = iconPath
fcs.cchIconFile = 0
shell32.SHGetSetFolderCustomSettings(
byref(fcs), folderPath, FCS_FORCEWRITE)
win32api.SetFileAttributes(
folderPath+'favicon.ico', win32con.FILE_ATTRIBUTE_HIDDEN)
os.remove(posterLocalPath)
def changeFloderIconMac(folderPath, posterLocalPath):
img = Image.open(posterLocalPath)
x, y = img.size
x = int(256/y*x)
img = img.resize((x, 256), Image.ANTIALIAS)
img_new = Image.new('RGBA', (256, 256), (0, 0, 0, 0))
img_new.paste(img, (int((256 - x) / 2), 0))
img_new.save(folderPath+'favicon.png', "png", quality=100)
Cocoa.NSWorkspace.sharedWorkspace().setIcon_forFile_options_(Cocoa.NSImage.alloc().initWithContentsOfFile_(
folderPath+'favicon.png'), folderPath, 0) or sys.exit("Unable to set file icon")
if __name__ == "__main__":
os.chdir(sys.path[0])
dirs = os.listdir('.')
for originalFileName in dirs:
skipFlag = False
if os.path.splitext(originalFileName)[1].lower() in ext_list:
print('当前文件:'+originalFileName)
fileNameWithoutExt = os.path.splitext(originalFileName)[0]
titleFromFile, year = getMetadata(fileNameWithoutExt)
while True:
if titleFromFile:
TMDbMovieID = SearchonTMDb(titleFromFile, year)
if TMDbMovieID:
break
else:
titleFromFile = input(
originalFileName+' 无搜索结果,请手动输入电影名(直接回车跳过该文件):')
else:
titleFromFile = input(
originalFileName+' 元数据获取失败,请手动输入电影名(直接回车跳过该文件):')
if titleFromFile:
continue
else:
skipFlag = True
break
if skipFlag:
continue
title_zh_CN, original_title, original_language = DetailsonTMDb(
TMDbMovieID)
if title_zh_CN == original_title:
folderPath = sys.path[0]+'/'+original_title+'/'
else:
folderPath = sys.path[0]+'/'+title_zh_CN+' '+original_title+'/'
if not os.path.exists(folderPath):
os.mkdir(folderPath)
shutil.move(originalFileName, folderPath)
posterLocalPath = folderPath+title_zh_CN+'.jpg'
posterImage = getPosterImage(TMDbMovieID, original_language)
file = open(posterLocalPath, 'wb')
file.write(posterImage)
file.close()
if platform.system() == 'Windows':
changeFloderIconWin(folderPath, posterLocalPath)
elif platform.system() == 'Darwin':
changeFloderIconMac(folderPath, posterLocalPath)