-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathStashNfoExporter.py
370 lines (325 loc) · 14.8 KB
/
StashNfoExporter.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
from genericpath import exists
from json import loads
import requests
import config
import log
import lxml.etree as etree
import datetime
import os
import time
import sqlite3
import json
import sys
HEADERS = {
'Content-Type': 'application/json',
'ApiKey': f'{config.api_key}',
'Accept': 'application/json',
'Connection': 'keep-alive',
'DNT': '1',
}
json_input = json.loads(sys.stdin.read())
# log.info(json_input)
def make_graphql_request(query):
try:
json_query = {"query": query}
response = requests.post(config.graphql_url, json=json_query, headers=HEADERS)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
log.error(f"Error making GraphQL request: {e}")
return None
def write_nfo(root, file_path):
xml_string = etree.tostring(root, pretty_print=True, xml_declaration=True,encoding="utf-8")
file = open(file_path, 'wb')
try:
file.write(xml_string)
finally:
file.close()
log.info(f"Added {file_path}")
def process_scene(scene):
root = etree.Element("movie")
# Title
title_element = etree.SubElement(root, "title")
title_element.text = scene['title']
# Original Title
original_title_element = etree.SubElement(root, "originaltitle")
original_title_element.text = scene['title']
# # Sort Title
# sort_title_element = etree.SubElement(root, "sorttitle")
# sort_title_element.text = scene['title']
# Unique ID
unique_id_element = etree.SubElement(root, "uniqueid")
unique_id_element.set("default", "true")
unique_id_element.text = str(scene['id'])
# Stash IDs
for stash_id in scene['stash_ids']:
stash_id_element = etree.SubElement(root, "uniqueid", type="stashdb")
stash_id_element.text = str(stash_id['stash_id'])
# MPAA Rating
mpaa_element = etree.SubElement(root, "mpaa")
mpaa_element.text = "XXX"
# Play Count
playcount_element = etree.SubElement(root, "playcount")
playcount_element.text = str(scene['play_count'])
# Date Added
dateadded_element = etree.SubElement(root, "dateadded")
dateadded_element.text = str(scene['created_at'])
# Premiered Date
premiered_element = etree.SubElement(root, "premiered")
premiered_element.text = scene['date']
# Year
if scene['date'] is not None:
year_element = etree.SubElement(root, "year")
year_element.text = str(datetime.datetime.strptime(str(scene['date']),"%Y-%m-%d").year)
# User Rating
#userrating_element = etree.SubElement(root, "userrating")
#userrating_element.text = str(scene['rating100'])
# Plot
plot_element = etree.SubElement(root, "plot")
plot_element.text = str(scene['details'])
# Outline
outline_element = etree.SubElement(root, "outline")
outline_element.text = str(scene['details'])
# Studio
studio_element = etree.SubElement(root, "studio")
if scene['studio'] is None:
studio_element.text = ""
else:
studio_element.text = scene['studio']['name']
# Director
director_element = etree.SubElement(root, "director")
director_element.text = scene['director']
# Studio Thumbnail (Logo)
thumb_studio_element = etree.SubElement(root, "thumb", attrib={"aspect": "clearlogo"})
if scene['studio'] is None:
thumb_studio_element.text = ""
else:
thumb_studio_element.text = scene['studio']['image_path']
# Landscape Thumbnail
thumb_landscape_element = etree.SubElement(root, "thumb", attrib={"aspect": "landscape"})
thumb_landscape_element.text = scene['paths']['screenshot']
# Vertical Thumbnail
thumb_poster_element = etree.SubElement(root, "thumb", attrib={"aspect": "poster"})
thumb_poster_element.text = scene['paths']['screenshot']
# Fanart Thumbnail
fanart_element = etree.SubElement(root, "fanart")
fanart_thumb_element = etree.SubElement(fanart_element, "thumb")
fanart_thumb_element.text = scene['paths']['screenshot']
# Actors
for actor in scene['performers']:
actor_element = etree.SubElement(root, "actor")
actor_name_element = etree.SubElement(actor_element, "name")
actor_name_element.text = actor['name']
image_element = etree.SubElement(actor_element, "thumb")
image_element.text = actor['image_path']
# Tag
for tag in scene['tags']:
tag_element = etree.SubElement(root, "tag")
tag_element.text = tag['name']
# Set
set_element = etree.SubElement(root, "set")
set_name_element = etree.SubElement(set_element, "name")
if scene['studio'] is None:
set_name_element.text = "No Studio"
else:
set_name_element.text = scene['studio']['name']
# File Information
for file_info in scene['files']:
fileinfo_element = etree.SubElement(root, "fileinfo")
streamdetails_element = etree.SubElement(fileinfo_element, "streamdetails")
# Video
video_element = etree.SubElement(streamdetails_element, "video")
video_codec_element = etree.SubElement(video_element, "codec")
video_codec_element.text = file_info['video_codec']
aspect_element = etree.SubElement(video_element, "aspect")
aspect_element.text = str(round(file_info['width'] / file_info['height'], 2))
width_element = etree.SubElement(video_element, "width")
width_element.text = str(file_info['width'])
height_element = etree.SubElement(video_element, "height")
height_element.text = str(file_info['height'])
duration_element = etree.SubElement(video_element, "durationinseconds")
duration_element.text = str(file_info['duration'])
# Audio
audio_element = etree.SubElement(streamdetails_element, "audio")
audio_codec_element = etree.SubElement(audio_element, "codec")
audio_codec_element.text = file_info['audio_codec']
return root
query = """
{
allScenes {
id
title
details
director
date
rating100
organized
play_count
created_at
updated_at
files {
path
video_codec
width
height
duration
audio_codec
}
paths {
screenshot
}
studio {
name
id
url
image_path
}
tags {
name
}
performers {
name
gender
image_path
url
}
stash_ids {
stash_id
}
}
}
"""
if "mode" in json_input["args"]:
if json_input['args']['mode'] == 'processNFO':
log.info("Starting Process Info")
START_TIME = time.time()
conn = sqlite3.connect('updates_data.db')
cursor = conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS scenes (
id INTEGER PRIMARY KEY,
title TEXT,
last_updated_at TEXT
)''')
conn.commit()
cursor.execute("SELECT id, last_updated_at FROM scenes")
rows = cursor.fetchall()
last_updated_dict = {row[0]: row[1] for row in rows}
r = make_graphql_request(query)
if r is not None:
if config.generate_nfo_for_files in ['Organized', 'Unorganized', 'All']:
organizedScenes = [scene for scene in r.get('data', {}).get('allScenes', [])
if (config.generate_nfo_for_files == 'Organized' and scene['organized']) or
(config.generate_nfo_for_files == 'Unorganized' and not scene['organized']) or
(config.generate_nfo_for_files == 'All')]
for scene in organizedScenes:
file_path = scene['files'][0]['path']
file_name = os.path.basename(file_path)
file_name_without_ext = os.path.splitext(file_name)[0]
file_base_dir = os.path.dirname(file_path)
nfo_file_name = f'{file_name_without_ext}.nfo'
# For testing only save path is my local nfo_test folder !
nfo_file_path = os.path.join(file_base_dir, nfo_file_name)
if int(scene['id']) in last_updated_dict and scene['updated_at'] == last_updated_dict[int(scene['id'])] and os.path.exists(nfo_file_path):
continue
else:
print("Changes Detected Adding to Database" +scene['title'] )
cursor.execute('''INSERT OR REPLACE INTO scenes (id, title, last_updated_at)
VALUES (?, ?, ?)''', (scene['id'], scene['title'], scene['updated_at']))
conn.commit()
last_updated_dict[scene['id']] = scene['updated_at']
for scene in organizedScenes:
file_path = scene['files'][0]['path']
file_name = os.path.basename(file_path)
file_name_without_ext = os.path.splitext(file_name)[0]
file_base_dir = os.path.dirname(file_path)
nfo_file_name = f'{file_name_without_ext}.nfo'
# For testing only save path is my local nfo_test folder !
nfo_file_path = os.path.join(file_base_dir, nfo_file_name)
if int(scene['id']) in last_updated_dict and scene['updated_at'] == last_updated_dict[int(scene['id'])] and os.path.exists(nfo_file_path):
continue
else:
print("Changes Detected" ,scene['title'] )
root = process_scene(scene)
file_path = scene['files'][0]['path']
file_name = os.path.basename(file_path)
file_name_without_ext = os.path.splitext(file_name)[0]
file_base_dir = os.path.dirname(file_path)
nfo_file_name = f'{file_name_without_ext}.nfo'
# For testing only save path is my local nfo_test folder !
# For Custom Path you can change base dir
nfo_file_path = os.path.join(file_base_dir, nfo_file_name)
write_nfo(root, nfo_file_path)
log.debug("Execution time: {}s".format(round(time.time() - START_TIME, 5)))
else:
log.error("Please Check config -> make_graphql_request")
else:
log.error("No response from GraphQL server")
if json_input['args']['mode'] == 'cleanupNFO':
log.info("Starting Cleanup Process")
START_TIME = time.time()
if os.path.exists('updates_data.db'):
os.remove('updates_data.db')
log.info("Deleted old database creating new !")
conn = sqlite3.connect('updates_data.db')
cursor = conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS scenes (
id INTEGER PRIMARY KEY,
title TEXT,
last_updated_at TEXT
)''')
conn.commit()
cursor.execute("SELECT id, last_updated_at FROM scenes")
rows = cursor.fetchall()
last_updated_dict = {row[0]: row[1] for row in rows}
r = make_graphql_request(query)
if r is not None:
if config.generate_nfo_for_files in ['Organized', 'Unorganized', 'All']:
organizedScenes = [scene for scene in r.get('data', {}).get('allScenes', [])
if (config.generate_nfo_for_files == 'Organized' and scene['organized']) or
(config.generate_nfo_for_files == 'Unorganized' and not scene['organized']) or
(config.generate_nfo_for_files == 'All')]
for scene in organizedScenes:
file_path = scene['files'][0]['path']
file_name = os.path.basename(file_path)
file_name_without_ext = os.path.splitext(file_name)[0]
file_base_dir = os.path.dirname(file_path)
nfo_file_name = f'{file_name_without_ext}.nfo'
# For testing only save path is my local nfo_test folder !
nfo_file_path = os.path.join(file_base_dir, nfo_file_name)
if int(scene['id']) in last_updated_dict and scene['updated_at'] == last_updated_dict[int(scene['id'])] and os.path.exists(nfo_file_path):
continue
else:
print("Changes Detected Adding to Database" +scene['title'] )
cursor.execute('''INSERT OR REPLACE INTO scenes (id, title, last_updated_at)
VALUES (?, ?, ?)''', (scene['id'], scene['title'], scene['updated_at']))
conn.commit()
last_updated_dict[scene['id']] = scene['updated_at']
for scene in organizedScenes:
file_path = scene['files'][0]['path']
file_name = os.path.basename(file_path)
file_name_without_ext = os.path.splitext(file_name)[0]
file_base_dir = os.path.dirname(file_path)
nfo_file_name = f'{file_name_without_ext}.nfo'
# For testing only save path is my local nfo_test folder !
nfo_file_path = os.path.join(file_base_dir, nfo_file_name)
if int(scene['id']) in last_updated_dict and scene['updated_at'] == last_updated_dict[int(scene['id'])] and os.path.exists(nfo_file_path):
continue
else:
print("Changes Detected" ,scene['title'] )
root = process_scene(scene)
file_path = scene['files'][0]['path']
file_name = os.path.basename(file_path)
file_name_without_ext = os.path.splitext(file_name)[0]
file_base_dir = os.path.dirname(file_path)
nfo_file_name = f'{file_name_without_ext}.nfo'
# For testing only save path is my local nfo_test folder !
# For Custom Path you can change base dir
nfo_file_path = os.path.join(file_base_dir, nfo_file_name)
write_nfo(root, nfo_file_path)
log.debug("Execution time: {}s".format(round(time.time() - START_TIME, 5)))
else:
log.error("Please Check config -> make_graphql_request")
else:
log.error("No response from GraphQL server")
else:
log.error("Create NFO First before cleanup")