/
library_service.py
448 lines (371 loc) · 19 KB
/
library_service.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
# -*- coding: utf-8 -*-
#-------------------------------------------------------------
# Service for updating new episodes on library series
# ------------------------------------------------------------
import datetime
import imp
import math
import re
import threading
from core import config, scrapertools
from core import filetools
from core import jsontools
from core import library
from platformcode import logger
from core.item import Item
from platformcode import platformtools
def convert_old_to_v4():
logger.info()
path_series_xml = filetools.join(config.get_data_path(), "series.xml")
path_series_json = filetools.join(config.get_data_path(), "series.json")
series_insertadas = 0
series_fallidas = 0
version = 'v?'
# Rename and create Series directory
import time
new_name = str(time.time())
path_series_old = filetools.join(library.LIBRARY_PATH, "SERIES_OLD_" + new_name)
if filetools.rename(library.TVSHOWS_PATH, "SERIES_OLD_" + new_name):
if not filetools.mkdir(library.TVSHOWS_PATH):
logger.error("ERROR, impossibile creare la directory SERIES")
return False
else:
logger.error("ERROR,impossibile rinominare la directory SERIES")
return False
path_cine_old = filetools.join(library.LIBRARY_PATH, "CINE_OLD_" + new_name)
if filetools.rename(library.MOVIES_PATH, "CINE_OLD_" + new_name):
if not filetools.mkdir(library.MOVIES_PATH):
logger.error("ERROR, impossibile creare la directory CINE")
return False
else:
logger.error("ERROR, impossibile rinominare la directory CINE")
return False
# Convert library from v1 to v4 (xml)
if filetools.exists(path_series_xml):
try:
data = filetools.read(path_series_xml)
for line in data.splitlines():
try:
aux = line.rstrip('\n').split(",")
tvshow = aux[0].strip()
url = aux[1].strip()
channel = aux[2].strip()
serie = Item(contentSerieName=tvshow, url=url, channel=channel, action="episodios",
title=tvshow, active=True)
patron = "^(.+)[\s]\((\d{4})\)$"
matches = re.compile(patron, re.DOTALL).findall(serie.contentSerieName)
if matches:
serie.infoLabels['title'] = matches[0][0]
serie.infoLabels['year'] = matches[0][1]
else:
serie.infoLabels['title'] = tvshow
insertados, sobreescritos, fallidos = library.save_library_tvshow(serie, list())
if fallidos == 0:
series_insertadas += 1
platformtools.dialog_notification("Serie aggiornata", serie.infoLabels['title'])
else:
series_fallidas += 1
except:
series_fallidas += 1
filetools.rename(path_series_xml, "series.xml.old")
version = 'v4'
except EnvironmentError:
logger.error("ERROR al leer el archivo: %s" % path_series_xml)
return False
# Convert library from v2 to v4 (json)
if filetools.exists(path_series_json):
try:
data = jsontools.load_json(filetools.read(path_series_json))
for tvshow in data:
for channel in data[tvshow]["channels"]:
try:
serie = Item(contentSerieName=data[tvshow]["channels"][channel]["tvshow"],
url=data[tvshow]["channels"][channel]["url"], channel=channel, action="episodios",
title=data[tvshow]["name"], active=True)
if not tvshow.startswith("t_"):
serie.infoLabels["tmdb_id"] = tvshow
insertados, sobreescritos, fallidos = library.save_library_tvshow(serie, list())
if fallidos == 0:
series_insertadas += 1
platformtools.dialog_notification("Serie aggiornata", serie.infoLabels['title'])
else:
series_fallidas += 1
except:
series_fallidas += 1
filetools.rename(path_series_json, "series.json.old")
version = 'v4'
except EnvironmentError:
logger.error("ERROR al leer el archivo: %s" % path_series_json)
return False
# Convert library from v2 to v4
if version != 'v4':
# Get old Series recursively
for raiz, subcarpetas, ficheros in filetools.walk(path_series_old):
for f in ficheros:
if f == "tvshow.json":
try:
serie = Item().fromjson(filetools.read(filetools.join(raiz, f)))
insertados, sobreescritos, fallidos = library.save_library_tvshow(serie, list())
if fallidos == 0:
series_insertadas += 1
platformtools.dialog_notification("Serie aggiornata", serie.infoLabels['title'])
else:
series_fallidas += 1
except:
series_fallidas += 1
movies_insertadas = 0
movies_fallidas = 0
for raiz, subcarpetas, ficheros in filetools.walk(path_cine_old):
for f in ficheros:
if f.endswith(".strm.json"):
try:
movie = Item().fromjson(filetools.read(filetools.join(raiz, f)))
insertados, sobreescritos, fallidos = library.save_library_movie(movie)
if fallidos == 0:
movies_insertadas += 1
platformtools.dialog_notification("Film aggiornato", movie.infoLabels['title'])
else:
movies_fallidas += 1
except:
movies_fallidas += 1
config.set_setting("library_version", 'v4')
platformtools.dialog_notification("Libreria aggiornata con il nuovo formato",
"%s serie convertite e %s serie scaricate. Continuare per"
"ottenere le info sugli episodi" %
(series_insertadas, series_fallidas), time=12000)
# Cleanup library of empty records
if config.is_xbmc():
from platformcode import xbmc_library
xbmc_library.clean()
return True
def update(path, p_dialog, i, t, serie, overwrite):
logger.info("Actualizando " + path)
insertados_total = 0
# logger.debug("%s: %s" %(serie.contentSerieName,str(list_canales) ))
for channel, url in serie.library_urls.items():
serie.channel = channel
serie.url = url
heading = 'Aggiornamento della libreria...'
p_dialog.update(int(math.ceil((i + 1) * t)), heading, "%s: %s" % (serie.contentSerieName,
serie.channel.capitalize()))
try:
pathchannels = filetools.join(config.get_runtime_path(), "channels", serie.channel + '.py')
logger.info("Caricando il canale: " + pathchannels + " " +
serie.channel)
if serie.library_filter_show:
serie.show = serie.library_filter_show.get(channel, serie.contentSerieName)
obj = imp.load_source(serie.channel, pathchannels)
itemlist = obj.episodios(serie)
try:
if int(overwrite) == 3:
# Overwrite all files (tvshow.nfo, 1x01.nfo, 1x01 [canal].json, 1x01.strm, etc...)
insertados, sobreescritos, fallidos = library.save_library_tvshow(serie, itemlist)
else:
insertados, sobreescritos, fallidos = library.save_library_episodes(path, itemlist, serie,
silent=True,
overwrite=overwrite)
insertados_total += insertados
except Exception as ex:
logger.error("Errore nei capitoli delle serie")
template = "An exception of type %s occured. Arguments:\n%r"
message = template % (type(ex).__name__, ex.args)
logger.error(message)
except Exception as ex:
logger.error("Errore nel prendere gli episodi di: %s" % serie.show)
template = "An exception of type %s occured. Arguments:\n%r"
message = template % (type(ex).__name__, ex.args)
logger.error(message)
return insertados_total > 0
def check_for_update(overwrite=True):
logger.info("Aggiornamento series...")
p_dialog = None
serie_actualizada = False
update_when_finished = False
hoy = datetime.date.today()
try:
if config.get_setting("updatelibrary", "biblioteca") != 0 or overwrite:
config.set_setting("updatelibrary_last_check", hoy.strftime('%Y-%m-%d'), "biblioteca")
heading = 'Aggiornamento della libreria...'
p_dialog = platformtools.dialog_progress_bg('streamondemand', heading)
p_dialog.update(0, '')
import glob
show_list = glob.glob(filetools.join(library.TVSHOWS_PATH, u'/*/tvshow.nfo'))
if show_list:
t = float(100) / len(show_list)
for i, tvshow_file in enumerate(show_list):
head_nfo, serie = library.read_nfo(tvshow_file)
path = filetools.dirname(tvshow_file)
logger.info("serie=" + serie.contentSerieName)
p_dialog.update(int(math.ceil((i + 1) * t)), heading, serie.contentSerieName)
interval = int(serie.active) # Can be bool type
if not serie.active:
# Unload if the Serie is not active
continue
# Update next
update_next = serie.update_next
if update_next:
y, m, d = update_next.split('-')
update_next = datetime.date(int(y), int(m), int(d))
else:
update_next = hoy
update_last = serie.update_last
if update_last:
y, m, d = update_last.split('-')
update_last = datetime.date(int(y), int(m), int(d))
else:
update_last = hoy
# if the Serie is active ...
if overwrite or config.get_setting("updatetvshows_interval", "biblioteca") == 0:
# ... force autonomus update
serie_actualizada = update(path, p_dialog, i, t, serie, overwrite)
elif interval == 1 and update_next <= hoy:
# ...weekly update
serie_actualizada = update(path, p_dialog, i, t, serie, overwrite)
if not serie_actualizada and update_last <= hoy - datetime.timedelta(days=7):
# raise the interval
interval = 7
update_next = hoy + datetime.timedelta(days=interval)
elif interval == 7 and update_next <= hoy:
# ...14days update
serie_actualizada = update(path, p_dialog, i, t, serie, overwrite)
if not serie_actualizada:
if update_last <= hoy - datetime.timedelta(days=14):
# raise the interval
interval = 30
update_next += datetime.timedelta(days=interval)
elif interval == 30 and update_next <= hoy:
# ...monthly update
serie_actualizada = update(path, p_dialog, i, t, serie, overwrite)
if not serie_actualizada:
update_next += datetime.timedelta(days=interval)
if interval != int(serie.active) or update_next.strftime('%Y-%m-%d') != serie.update_next:
serie.active = interval
serie.update_next = update_next.strftime('%Y-%m-%d')
serie.channel = "biblioteca"
serie.action = "get_temporadas"
filetools.write(tvshow_file, head_nfo + serie.tojson())
if serie_actualizada:
if config.get_setting("search_new_content", "biblioteca") == 0:
# Update Kodi library: Search contents in the Serie directory
if config.is_xbmc():
from platformcode import xbmc_library
xbmc_library.update(folder=filetools.basename(path))
else:
update_when_finished = True
if config.get_setting("search_new_content", "biblioteca") == 1 and update_when_finished:
# Update Kodi library: Search contents for every Serie
if config.is_xbmc():
from platformcode import xbmc_library
xbmc_library.update()
p_dialog.close()
else:
logger.info("Libreria non aggiornata, opzione disattiva nella configurazione di streamondemand")
except Exception as ex:
logger.error("Si è verificato un errore nell'aggiornamento")
template = "An exception of type %s occured. Arguments:\n%r"
message = template % (type(ex).__name__, ex.args)
logger.error(message)
if p_dialog:
p_dialog.close()
def start(thread=True):
if thread:
t = threading.Thread(target=start, args=[False])
t.setDaemon(True)
t.start()
else:
import xbmc
updatelibrary_wait = [0, 10000, 20000, 30000, 60000]
wait = updatelibrary_wait[int(config.get_setting("updatelibrary_wait", "biblioteca"))]
if wait > 0:
xbmc.sleep(wait)
# Compare the library and update it if necessary
if config.get_setting("library_version") != 'v4':
platformtools.dialog_ok(config.PLUGIN_NAME.capitalize(), "Aggiornamento della libreria al nuovo formato",
"Selezionare correttamente il nome della serie, se non sicuro seleziona 'Annulla'.")
if not convert_old_to_v4():
platformtools.dialog_ok(config.PLUGIN_NAME.capitalize(),
"ERROR, nella conversione al nuovo formato")
else:
# Option 2 "Once per day"
if not config.get_setting("updatelibrary", "biblioteca") == 2:
check_for_update(overwrite=False)
else:
if not config.get_setting("updatelibrary", "biblioteca") == 2:
check_for_update(overwrite=False)
# Cycling update
while True:
monitor_update()
xbmc.sleep(3600 * 1000)
def monitor_update():
update_setting = config.get_setting("updatelibrary", "biblioteca")
if update_setting == 2 or update_setting == 3:
hoy = datetime.date.today()
last_check = config.get_setting("updatelibrary_last_check", "biblioteca")
if last_check:
y, m, d = last_check.split('-')
last_check = datetime.date(int(y), int(m), int(d))
else:
last_check = hoy - datetime.timedelta(days=1)
update_start = config.get_setting("everyday_delay", "biblioteca") * 4
if last_check < hoy and datetime.datetime.now().hour >= int(update_start):
logger.info("Inizio update programmato: %s" % datetime.datetime.now())
check_for_update(overwrite=False)
if __name__ == "__main__":
if scrapertools.wait_for_internet(retry=10):
'''
disable update channel/server
if config.get_setting("check_for_channel_updates") == "true":
# -- Update channels from repository streamondemand ------
try:
from core import update_channels
except:
logger.info("streamondemand.library_service Error in update_channels")
# ----------------------------------------------------------------------
# -- Update servertools and servers from repository streamondemand ------
try:
from core import update_servers
except:
logger.info("streamondemand.library_service Error in update_servers")
# ----------------------------------------------------------------------
'''
# Start from the beginning
import xbmc
# adult mode:
# Change from False to True to the system 0: Never, 1:Always, 2:Only on Kodi restart
# if == 2 inactive.
if config.get_setting("adult_mode") == False or config.get_setting("adult_mode") == 2:
config.set_setting("adult_mode", 0)
elif config.get_setting("adult_mode") == True:
config.set_setting("adult_mode", 1)
updatelibrary_wait = [0, 10000, 20000, 30000, 60000]
wait = updatelibrary_wait[int(config.get_setting("updatelibrary_wait", "biblioteca"))]
if wait > 0:
xbmc.sleep(wait)
# Compare the library and update it if necessary
if config.get_setting("library_version") != 'v4':
platformtools.dialog_ok(config.PLUGIN_NAME.capitalize(), "Aggiornamento della libreria al nuovo formato",
"Seleziona il nome corretto di serie o film, se non sicuro seleziona 'Cancel'.")
if not convert_old_to_v4():
platformtools.dialog_ok(config.PLUGIN_NAME.capitalize(),
"ERROR, al actualizar la biblioteca al nuevo formato")
else:
# Option 2 "Once per day"
if not config.get_setting("updatelibrary", "biblioteca") == 2:
check_for_update(overwrite=False)
else:
if not config.get_setting("updatelibrary", "biblioteca") == 2:
check_for_update(overwrite=False)
# Cycle execution
if config.get_platform(True)['num_version'] >= 14:
monitor = xbmc.Monitor() # For Kodi >= 14
else:
monitor = None # For Kodi < 14
if monitor:
while not monitor.abortRequested():
monitor_update()
if monitor.waitForAbort(3600 * 1000):
break
else:
while not xbmc.abortRequested:
monitor_update()
xbmc.sleep(3600 * 1000)