forked from vadyur/script.media.aggregator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
kodidb.py
355 lines (287 loc) · 9.63 KB
/
kodidb.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
import log
import filesystem, os, time
import xml.etree.ElementTree as ET
test_reader = None
class AdvancedSettingsReader(object):
dict = {}
def LOG(self, s):
log.debug('[AdvancedSettingsReader]: ' + s)
def __init__(self):
self.use_mysql = False
self.dict.clear()
root = []
try:
import xbmc
path = xbmc.translatePath('special://profile/advancedsettings.xml').decode('utf-8')
self.LOG(path)
if filesystem.exists(path):
self.load(path)
except:
pass
def load(self, path):
try:
with filesystem.fopen(path, 'r') as f:
content = f.read()
#log.debug(content)
root = ET.fromstring(content)
except IOError as e:
self.LOG("I/O error({0}): {1}".format(e.errno, e.strerror))
return
except BaseException as e:
self.LOG("error: " + str(e))
return
for section in root:
if section.tag == 'videodatabase':
for child in section:
if child.tag in ['type', 'host', 'port', 'user', 'pass', 'name']:
self.dict[child.tag] = child.text
log.debug(child.text)
self.LOG('<videodatabase> found')
return
self.LOG('<videodatabase> not found')
def __getitem__(self, key):
return self.dict.get(key, None)
DB_VERSIONS = {
'10': '37',
'11': '60',
'12': '75',
'13': '78',
'14': '90',
'15': '93',
'16': '99',
'17': '107'
}
BASE_PATH = 'special://database'
class VideoDatabase(object):
@staticmethod
def find_last_version(name, path=BASE_PATH):
import re, xbmcvfs
try:
dirs, files = xbmcvfs.listdir(path)
matched_files = [f for f in files if bool(re.match(name, f, re.I))] #f.startswith(name)]
versions = [int(os.path.splitext(f[len(name):])[0]) for f in matched_files]
if not versions:
return 0
return max(versions)
except BaseException as e:
log.debug(e, log.lineno())
return 0
@staticmethod
def get_db_version(name=None):
try:
import xbmc
major = xbmc.getInfoLabel("System.BuildVersion").split(".")[0]
ver = DB_VERSIONS.get(major)
if ver:
return ver
return VideoDatabase.find_last_version(name, 'special://home/dbversions')
except ImportError:
return DB_VERSIONS['17']
def __init__(self):
try:
reader = test_reader if test_reader else AdvancedSettingsReader()
self.DB_NAME = reader['name'] if reader['name'] is not None else 'MyVideos'
self.DB_NAME += self.get_db_version(self.DB_NAME)
log.debug('kodidb: DB name is ' + self.DB_NAME )
self.DB_USER = reader['user']
self.DB_PASS = reader['pass']
self.DB_ADDRESS = reader['host']
self.DB_PORT=reader['port']
if reader['type'] == 'mysql' and \
self.DB_ADDRESS is not None and \
self.DB_USER is not None and \
self.DB_PASS is not None and \
self.DB_NAME is not None:
log.debug('kodidb: Service: Loading MySQL as DB engine')
self.DB = 'mysql'
else:
log.debug('kodidb: Service: MySQL not enabled or not setup correctly')
raise ValueError('MySQL not enabled or not setup correctly')
except:
self.DB = 'sqlite'
import xbmc
self.db_dir = os.path.join(xbmc.translatePath(BASE_PATH), 'MyVideos%s.db' % VideoDatabase.find_last_version('MyVideos'))
def create_connection(self):
if self.DB == 'mysql':
import mysql.connector
return mysql.connector.connect( database=self.DB_NAME,
user=self.DB_USER,
password=self.DB_PASS,
host=self.DB_ADDRESS,
port=self.DB_PORT,
buffered=True)
else:
from sqlite3 import dbapi2 as db_sqlite
return db_sqlite.connect(self.db_dir)
def sql_request(self, req):
if self.DB == 'mysql':
return req.replace('?', '%s')
else:
return req.replace('%s', '?')
def request(fn):
def wrapper(self, *args, **kwargs):
self.db = self.videoDB.create_connection()
try:
sql = fn(self, *args, **kwargs)
cur = self.db.cursor()
cur.execute(sql)
result = cur.fetchall()
self.db.commit()
#result = []
#for item in res:
# result.append(item)
return result
finally:
self.db.close()
return wrapper
class KodiDB(object):
def debug(self, msg, line=0):
if isinstance(msg, unicode):
msg = msg.encode('utf-8')
#line = inspect.currentframe().f_back.f_back.f_lineno
log.debug('[KodiDB:%d] %s' % (line, msg))
def __init__(self, strmName, strmPath, pluginUrl):
self.debug('strmName: ' + strmName, log.lineno())
self.debug('strmPath: ' + strmPath, log.lineno())
self.debug('pluginUrl: ' + pluginUrl, log.lineno())
self.timeOffset = 0
self.strmName = strmName
self.strmPath = strmPath
self.pluginUrl = pluginUrl
self.videoDB = VideoDatabase()
def PlayerPreProccessing(self):
import xbmc
xbmc.sleep(1000)
self.db = self.videoDB.create_connection()
try:
self.debug('PlayerPreProccessing: ', log.lineno())
strmItem = self.getFileItem(self.strmName, self.strmPath)
if not strmItem is None:
self.debug('\tstrmItem = ' + str(strmItem), log.lineno())
bookmarkItem = self.getBookmarkItem(strmItem['idFile'])
self.debug('\tbookmarkItem = ' + str(bookmarkItem), log.lineno())
self.timeOffset = bookmarkItem['timeInSeconds'] if bookmarkItem != None else 0
self.debug('\ttimeOffset: ' + str(self.timeOffset / 60) , log.lineno())
else:
self.debug('\tstrmItem is None', log.lineno())
finally:
self.db.close()
def PlayerPostProccessing(self):
self.db = self.videoDB.create_connection()
try:
self.debug('PlayerPostProccessing: ', log.lineno())
for cnt in range(3):
pluginItem = self.getFileItem(self.pluginUrl)
self.debug('\tpluginItem = ' + str(pluginItem), log.lineno())
if pluginItem:
break
self.debug('Try again #' + str(cnt + 2))
time.sleep(2)
strmItem = self.getFileItem(self.strmName, self.strmPath)
self.debug('\tstrmItem = ' + str(strmItem), log.lineno())
self.CopyWatchedStatus(pluginItem, strmItem)
self.ChangeBookmarkId(pluginItem, strmItem)
finally:
self.db.close()
def CopyWatchedStatus(self, pluginItem, strmItem ):
if pluginItem is None or strmItem is None:
return
if pluginItem['playCount'] is None or strmItem['idFile'] is None:
return
cur = self.db.cursor()
sql = 'UPDATE files'
sql += ' SET playCount=' + str(pluginItem['playCount'])
sql += ' WHERE idFile = ' + str(strmItem['idFile'])
self.debug('CopyWatchedStatus: ' + sql, log.lineno())
cur.execute(sql)
self.db.commit()
def ChangeBookmarkId(self, pluginItem, strmItem ):
if pluginItem is None or strmItem is None:
return
if strmItem['idFile'] is None or pluginItem['idFile'] is None:
return
cur = self.db.cursor()
#delete previous
sql = "DELETE FROM bookmark WHERE idFile=" + str(strmItem['idFile'])
self.debug('ChangeBookmarkId: ' + sql, log.lineno())
cur.execute(sql)
self.db.commit()
#set new
sql = 'UPDATE bookmark SET idFile=' + str(strmItem['idFile'])
sql += ' WHERE idFile = ' + str(pluginItem['idFile'])
self.debug('ChangeBookmarkId: ' + sql, log.lineno())
cur.execute(sql)
self.db.commit()
def getBookmarkItem(self, idFile):
cur = self.db.cursor()
sql = "SELECT idBookmark, idFile, timeInSeconds, totalTimeInSeconds " + \
"FROM bookmark WHERE idFile = " + str(idFile)
cur.execute(sql)
bookmarks = cur.fetchall()
for item in bookmarks:
self.debug('Bookmark: ' + item.__repr__(), log.lineno())
return { 'idBookmark': item[0], 'idFile': item[1], 'timeInSeconds': item[2], 'totalTimeInSeconds': item[3] }
return None
def getFileItem(self, strFilename, strPath = None):
cur = self.db.cursor()
sql = "SELECT idFile, idPath, strFilename, playCount, lastPlayed " + \
"FROM files WHERE strFilename" + \
"='" + strFilename.replace("'", "''") + "'" #.split('&nfo=')[0] + "%'"
self.debug(sql, log.lineno())
cur.execute(sql)
files = cur.fetchall()
if len(files) == 0:
self.debug('getFileItem: len(files) == 0', log.lineno())
return None
if strPath is None:
for item in files:
self.debug('File: ' + item.__repr__(), log.lineno())
return { 'idFile': item[0], 'idPath': item[1], 'strFilename': item[2], 'playCount': item[3], 'lastPlayed': item[4] }
else:
sql = 'SELECT idPath, strPath FROM path WHERE idPath IN ( '
ids = []
for item in files:
ids.append( str( item[1]))
sql += ', '.join(ids) + ' )'
self.debug(sql, log.lineno())
cur.execute(sql)
paths = cur.fetchall()
for path in paths:
#pattern = path[1].replace('\\', '/').replace('[', '\\[').replace(']', '\\]')
if path[1].replace('\\', '/').endswith(strPath + '/') or path[1].replace('/', '\\').endswith(strPath + '\\'):
for item in files:
if path[0] == item[1]:
self.debug('File: ' + item.__repr__(), log.lineno())
return { 'idFile': item[0], 'idPath': item[1], 'strFilename': item[2], 'playCount': item[3], 'lastPlayed': item[4] }
self.debug('return None', log.lineno())
return None
def getPathId(self, strPath):
cur = self.db.cursor()
sql = "SELECT idPath, strPath FROM path " + \
"WHERE strPath LIKE '%" + strPath.encode('utf-8').replace("'", "''") + "%'"
self.debug(sql, log.lineno())
cur.execute(sql)
return cur.fetchall()
def getFileDataById(self, fileId):
return
class MoreRequests(object):
def __init__(self):
self.videoDB = VideoDatabase()
@request
def get_movies_by_imdb(self, imdb):
""" return movie data by imdb """
sql = """select idMovie, idFile, c00, c22, uniqueid_value, c16, premiered
from movie_view
where uniqueid_value='{}'""".format(imdb)
#self.debug(sql, log.lineno())
return sql
@request
def get_movie_duplicates(self):
sql = """select idMovie, idFile, c00, c22, uniqueid_value, COUNT(uniqueid_value)
from movie_view
where uniqueid_value like 'tt%'
GROUP BY
uniqueid_value
HAVING
COUNT(uniqueid_value) > 1"""
return sql