forked from stashapp/CommunityScripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
kodi-helper.py
335 lines (275 loc) · 9.26 KB
/
kodi-helper.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
import argparse
import os
import requests
import math
import re
import json
import config
BATCH_SIZE = 100
def parseArgs():
parser = argparse.ArgumentParser(description="Generate nfo and strm files for Kodi integration.")
parser.add_argument("mode", metavar="MODE", choices=["generate-nfo", "generate-strm"], help="generate-nfo or generate-strm")
parser.add_argument("--inline", action="store_true", help="Generate nfo files along side video files")
parser.add_argument("--outdir", metavar="<output directory>", help="Generate files in <outdir>")
parser.add_argument("--preserve-path", action="store_true", help="Include source file directory structure in output directory (with --outdir only)")
parser.add_argument("--truncate-prefix", type=str, metavar="<path prefix>", help="Remove prefix from output directory (with --preserve-path only)")
parser.add_argument("--use-source-filenames", action="store_true", help="Use source filenames for strm files instead of stash id")
parser.add_argument("--overwrite", action="store_true", help="Overwrite nfo/strm files if already present")
parser.add_argument("--filter", metavar="<filter string>", help="JSON graphql string to filter scenes with")
parser.add_argument("--genre", metavar="<genre>", help="Genre to assign. May be included multiple times", action="append")
return parser.parse_args()
# raw plugins may accept the plugin input from stdin, or they can elect
# to ignore it entirely. In this case it optionally reads from the
# command-line parameters.
def main():
args = parseArgs()
if args.mode == "generate-nfo":
generateNFOFiles(args)
elif args.mode == "generate-strm":
generateSTRMFiles(args)
def generateNFOFiles(args):
if not args.inline and args.outdir == "":
print("--outdir or --inline must be set\n")
return
filter = args.filter or ""
if filter != "":
filter = json.loads(filter)
else:
filter = {}
total = getCount(filter)
pages = math.ceil(total / BATCH_SIZE)
i = 1
while i <= pages:
print("Processing page {} of {}".format(i, pages))
scenes = getScenes(i, filter)
for scene in scenes:
# don't regenerate if file already exists and not overwriting
output = getOutputNFOFile(scene["path"], args)
if not args.overwrite and os.path.exists(output):
continue
nfo = generateNFO(scene, args)
writeFile(output, nfo, True)
i += 1
def generateSTRMFiles(args):
if args.outdir == "":
print("--outdir must be set\n")
return
filter = args.filter or ""
if filter != "":
filter = json.loads(filter)
else:
filter = {}
total = getCount(filter)
pages = math.ceil(total / BATCH_SIZE)
i = 1
while i <= pages:
print("Processing page {} of {}".format(i, pages))
scenes = getScenes(i, filter)
for scene in scenes:
name = ""
outdir = getOutputDir(scene["path"], args)
if args.use_source_filenames:
name = basename(os.path.splitext(scene["path"])[0])
else:
name = scene["id"]
name = os.path.join(outdir, name)
# don't regenerate if file already exists and not overwriting
strmOut = name + ".strm"
if args.overwrite or not os.path.exists(strmOut):
data = generateSTRM(scene)
writeFile(strmOut, data, False)
output = name + ".nfo"
if args.overwrite or not os.path.exists(output):
nfo = generateNFO(scene, args)
writeFile(output, nfo, True)
i += 1
def basename(f):
f = os.path.normpath(f)
return os.path.basename(f)
def getOutputSTRMFile(sceneID, args):
return os.path.join(args.outdir, "{}.strm".format(sceneID))
def getOutputDir(sourceFile, args):
ret = args.outdir
if args.preserve_path:
if args.truncate_prefix != None:
toRemove = args.truncate_prefix
if sourceFile.startswith(toRemove):
sourceFile = sourceFile[len(toRemove):]
sourceFile = os.path.normpath(sourceFile)
ret = os.path.join(args.outdir, os.path.dirname(sourceFile))
return ret
def getOutputNFOFile(sourceFile, args):
if args.inline:
# just replace the extension
return os.path.splitext(sourceFile)[0]+".nfo"
outdir = getOutputDir(sourceFile, args)
ret = os.path.join(outdir, basename(sourceFile))
return os.path.splitext(ret)[0]+".nfo"
def getCount(sceneFilter):
query = """
query findScenes($filter: FindFilterType!, $scene_filter: SceneFilterType!) {
findScenes(filter: $filter, scene_filter: $scene_filter) {
count
}
}
"""
variables = {
'filter': {
'per_page': 0,
},
'scene_filter': sceneFilter
}
result = __callGraphQL(query, variables)
return result["findScenes"]["count"]
def getScenes(page, sceneFilter):
query = """
query findScenes($filter: FindFilterType!, $scene_filter: SceneFilterType!) {
findScenes(filter: $filter, scene_filter: $scene_filter) {
scenes {
id
title
path
rating
details
date
oshash
paths {
screenshot
stream
}
studio {
name
image_path
}
performers {
name
image_path
}
tags {
name
}
movies {
movie {
name
}
}
}
}
}
"""
variables = {
'filter': {
'per_page': BATCH_SIZE,
'page': page,
},
'scene_filter': sceneFilter
}
result = __callGraphQL(query, variables)
return result["findScenes"]["scenes"]
def addAPIKey(url):
if config.api_key:
return url + "&apikey=" + config.api_key
return url
def getSceneTitle(scene):
if scene["title"] != None and scene["title"] != "":
return scene["title"]
return basename(scene["path"])
def generateSTRM(scene):
return scene["paths"]["stream"]
def generateNFO(scene, args):
ret = """
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<movie>
<title>{title}</title>
<userrating>{rating}</userrating>
<plot>{details}</plot>
<uniqueid type="stash">{id}</uniqueid>
{tags}
<premiered>{date}</premiered>
<studio>{studio}</studio>
{performers}
{thumbs}
{fanart}
{genres}
</movie>
"""
tags = ""
for t in scene["tags"]:
tags = tags + """
<tag>{}</tag>""".format(t["name"])
rating = ""
if scene["rating"] != None:
rating = scene["rating"]
date = ""
if scene["date"] != None:
date = scene["date"]
studio = ""
logo = ""
if scene["studio"] != None:
studio = scene["studio"]["name"]
logo = scene["studio"]["image_path"]
if not logo.endswith("?default=true"):
logo = addAPIKey(logo)
else:
logo = ""
performers = ""
i = 0
for p in scene["performers"]:
thumb = addAPIKey(p["image_path"])
performers = performers + """
<actor>
<name>{}</name>
<role></role>
<order>{}</order>
<thumb>{}</thumb>
</actor>""".format(p["name"], i, thumb)
i += 1
thumbs = [
"""<thumb aspect="poster">{}</thumb>""".format(addAPIKey(scene["paths"]["screenshot"]))
]
fanart = [
"""<thumb>{}</thumb>""".format(addAPIKey(scene["paths"]["screenshot"]))
]
if logo != "":
thumbs.append("""<thumb aspect="clearlogo">{}</thumb>""".format(logo))
fanart.append("""<thumb>{}</thumb>""".format(logo))
fanart = """<fanart>{}</fanart>""".format("\n".join(fanart))
genres = []
if args.genre != None:
for g in args.genre:
genres.append("<genre>{}</genre>".format(g))
ret = ret.format(title = getSceneTitle(scene), rating = rating, id = scene["id"], tags = tags, date = date, studio = studio, performers = performers, details = scene["details"] or "", thumbs = "\n".join(thumbs), fanart = fanart, genres = "\n".join(genres))
return ret
def writeFile(fn, data, useUTF):
encoding = None
if useUTF:
encoding = "utf-8-sig"
os.makedirs(os.path.dirname(fn), exist_ok=True)
f = open(fn, "w", encoding=encoding)
f.write(data)
f.close()
def __callGraphQL(query, variables = None):
headers = {
"Accept-Encoding": "gzip, deflate, br",
"Content-Type": "application/json",
"Accept": "application/json",
"Connection": "keep-alive",
"DNT": "1",
"ApiKey": config.api_key
}
json = {}
json['query'] = query
if variables != None:
json['variables'] = variables
# handle cookies
response = requests.post(config.server_url, json=json, headers=headers)
if response.status_code == 200:
result = response.json()
if result.get("error", None):
for error in result["error"]["errors"]:
raise Exception("GraphQL error: {}".format(error))
if result.get("data", None):
return result.get("data")
else:
raise Exception("GraphQL query failed:{} - {}. Query: {}. Variables: {}".format(response.status_code, response.content, query, variables))
main()