forked from Zanzibar82/plugin.video.streamondemand-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
library_service.py
213 lines (167 loc) · 9.27 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
# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# streamondemand 5
# Copyright 2015 tvalacarta@gmail.com
# http://www.mimediacenter.info/foro/viewforum.php?f=36
#
# Distributed under the terms of GNU General Public License v3 (GPLv3)
# http://www.gnu.org/licenses/gpl-3.0.html
# ------------------------------------------------------------
# This file is part of streamondemand 5.
#
# streamondemand 5 is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# streamondemand 5 is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with streamondemand 5. If not, see <http://www.gnu.org/licenses/>.
# ------------------------------------------------------------
# Service for updating new episodes on library series
# ------------------------------------------------------------
import imp
import math
import re
from core import config
from core import filetools
from core import jsontools
from core import logger
from core import scrapertools
from core.item import Item
from platformcode import library
from platformcode import platformtools
def create_tvshows_from_xml():
logger.info("streamondemand.platformcode.library_service create_tvshows_from_xml")
fname = filetools.join(config.get_data_path(), library.TVSHOW_FILE_OLD)
if filetools.exists(fname):
platformtools.dialog_ok("Biblioteca: Se va a actualizar al nuevo formato",
"Seleccione el nombre correcto de cada serie, si no está seguro pulse 'Cancelar'.",
"Hay nuevas opciones en 'Biblioteca' y en la 'configuración' del addon.")
filetools.rename(library.TVSHOWS_PATH, "SERIES_OLD")
if not filetools.exists(library.TVSHOWS_PATH):
filetools.mkdir(library.TVSHOWS_PATH)
if filetools.exists(library.TVSHOWS_PATH):
try:
data = filetools.read(fname)
for line in data.splitlines():
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
library.save_library_tvshow(serie, list())
filetools.rename(fname, "series.xml.old")
# Por ultimo limpia la libreria, por que las rutas anteriores ya no existen
library.clean()
except EnvironmentError:
logger.info("ERROR al leer el archivo: {0}".format(fname))
else:
logger.info("ERROR, no se ha podido crear la nueva carpeta de SERIES")
else:
logger.info("ERROR, no se ha podido renombrar la antigua carpeta de SERIES")
return True
return False
def create_tvshows_from_json(_actualizado):
logger.info("streamondemand.platformcode.library_service create_tvshows_from_json")
fname = filetools.join(config.get_data_path(), library.TVSHOW_FILE)
if filetools.exists(fname):
if not _actualizado:
platformtools.dialog_ok("Biblioteca: Actualizando formato",
"Espere por favor mientras se completa el proceso")
try:
data = jsontools.loads(filetools.read(fname))
for tvshow in data:
for channel in data[tvshow]["channels"]:
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
library.save_library_tvshow(serie, list())
filetools.rename(fname, "series.json.old")
except EnvironmentError:
logger.info("ERROR al leer el archivo: {0}".format(fname))
def main():
if scrapertools.wait_for_internet(retry=10):
# -- 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")
# ----------------------------------------------------------------------
logger.info("streamondemand.library_service Actualizando series...")
p_dialog = None
try:
if config.get_setting("updatelibrary") == "true":
heading = 'Aggiornamento biblioteca....'
p_dialog = platformtools.dialog_progress_bg('streamondemand', heading)
p_dialog.update(0, '')
show_list = []
for path, folders, files in filetools.walk(library.TVSHOWS_PATH):
show_list.extend([filetools.join(path, f) for f in files if f == "tvshow.json"])
# fix float porque la division se hace mal en python 2.x
t = float(100) / len(show_list)
for i, tvshow_file in enumerate(show_list):
serie = Item().fromjson(filetools.read(tvshow_file))
path = filetools.dirname(tvshow_file)
logger.info("streamondemand.library_service serie=" + serie.contentSerieName)
logger.info("streamondemand.library_service Actualizando " + path)
logger.info("streamondemand.library_service url " + serie.url)
show_name = serie.contentTitle
if show_name == "":
show_name = serie.show
p_dialog.update(int(math.ceil((i + 1) * t)), heading, show_name)
# si la serie esta activa se actualiza
if serie.active:
try:
pathchannels = filetools.join(config.get_runtime_path(), "channels", serie.channel + '.py')
logger.info("streamondemand.library_service Cargando canal: " + pathchannels + " " +
serie.channel)
obj = imp.load_source(serie.channel, pathchannels)
itemlist = obj.episodios(serie)
try:
library.save_library_episodes(path, itemlist, serie, True)
except Exception as ex:
logger.info("streamondemand.library_service Error al guardar los capitulos de la serie")
template = "An exception of type {0} occured. Arguments:\n{1!r}"
message = template.format(type(ex).__name__, ex.args)
logger.info(message)
except Exception as ex:
logger.error("Error al obtener los episodios de: {0}".
format(serie.show))
template = "An exception of type {0} occured. Arguments:\n{1!r}"
message = template.format(type(ex).__name__, ex.args)
logger.info(message)
p_dialog.close()
else:
logger.info("No actualiza la biblioteca, está desactivado en la configuración de streamondemand")
except Exception as ex:
logger.info("streamondemand.library_service Se ha producido un error al actualizar las series")
template = "An exception of type {0} occured. Arguments:\n{1!r}"
message = template.format(type(ex).__name__, ex.args)
logger.info(message)
if p_dialog:
p_dialog.close()
if __name__ == "__main__":
actualizado = create_tvshows_from_xml()
create_tvshows_from_json(actualizado)
main()