forked from bstrdsmkr/1Channel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice.py
210 lines (185 loc) · 8.47 KB
/
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
import os
# workaround for bug in Python imports
import datetime
# noinspection PyUnresolvedReferences
import _strptime
# noinspection PyUnresolvedReferences
import time
import xbmc
import xbmcgui
import xbmcaddon
ADDON = xbmcaddon.Addon(id='plugin.video.1channel')
try:
DB_NAME = ADDON.getSetting('db_name')
DB_USER = ADDON.getSetting('db_user')
DB_PASS = ADDON.getSetting('db_pass')
DB_ADDRESS = ADDON.getSetting('db_address')
if ADDON.getSetting('use_remote_db') == 'true' and \
DB_ADDRESS is not None and \
DB_USER is not None and \
DB_PASS is not None and \
DB_NAME is not None:
import mysql.connector as database
xbmc.log('1Channel: Service: Loading MySQL as DB engine')
DB = 'mysql'
else:
xbmc.log('1Channel: Service: MySQL not enabled or not setup correctly')
raise ValueError('MySQL not enabled or not setup correctly')
except:
try:
from sqlite3 import dbapi2 as database
xbmc.log('1Channel: Service: Loading sqlite3 as DB engine')
except:
from pysqlite2 import dbapi2 as database
xbmc.log('1Channel: Service: Loading pysqlite2 as DB engine')
DB = 'sqlite'
db_dir = os.path.join(xbmc.translatePath("special://database"), 'onechannelcache.db')
def format_time(seconds):
minutes, seconds = divmod(seconds, 60)
if minutes > 60:
hours, minutes = divmod(minutes, 60)
return "%02d:%02d:%02d" % (hours, minutes, seconds)
else:
return "%02d:%02d" % (minutes, seconds)
def ChangeWatched(imdb_id, video_type, name, season, episode, year='', watched=''):
from metahandler import metahandlers
metaget = metahandlers.MetaData(False)
metaget.change_watched(video_type, name, imdb_id, season=season, episode=episode, year=year, watched=watched)
class Service(xbmc.Player):
def __init__(self, *args, **kwargs):
xbmc.Player.__init__(self, *args, **kwargs)
self.reset()
self.last_run = 0
hours_list = [2, 5, 10, 15, 24]
selection = int(ADDON.getSetting('subscription-interval'))
self.hours = hours_list[selection]
self.DB = ''
xbmc.log('1Channel: Service starting...')
def reset(self):
xbmc.log('1Channel: Service: Resetting...')
win = xbmcgui.Window(10000)
win.clearProperty('1ch.playing.title')
win.clearProperty('1ch.playing.year')
win.clearProperty('1ch.playing.imdb')
win.clearProperty('1ch.playing.season')
win.clearProperty('1ch.playing.episode')
self._totalTime = 999999
self._lastPos = 0
self._sought = False
self.tracking = False
self.imdbnum = ''
self.video_type = ''
self.title = ''
self.season = ''
self.episode = ''
self.year = ''
def check(self):
win = xbmcgui.Window(10000)
if win.getProperty('1ch.playing.title'):
return True
else:
return False
def onPlayBackStarted(self):
xbmc.log('1Channel: Service: Playback started')
self.tracking = self.check()
if self.tracking:
xbmc.log('1Channel: Service: tracking progress...')
win = xbmcgui.Window(10000)
self.title = win.getProperty('1ch.playing.title')
self.imdb = win.getProperty('1ch.playing.imdb')
self.season = win.getProperty('1ch.playing.season')
self.year = win.getProperty('1ch.playing.year')
self.episode = win.getProperty('1ch.playing.episode')
if self.season or self.episode:
self.video_type = 'tvshow'
else:
self.video_type = 'movie'
self._totalTime = self.getTotalTime()
sql = 'SELECT bookmark FROM bookmarks WHERE video_type=? AND title=? AND season=? AND episode=? AND year=?'
if DB == 'mysql':
sql = sql.replace('?', '%s')
db = database.connect(DB_NAME, DB_USER, DB_PASS, DB_ADDRESS, buffered=True)
else:
db = database.connect(db_dir)
cur = db.cursor()
cur.execute(sql, (self.video_type, unicode(self.title, 'utf-8'), self.season, self.episode, self.year))
bookmark = cur.fetchone()
db.close()
if bookmark:
bookmark = float(bookmark[0])
if not (self._sought and (bookmark - 30 > 0)):
question = 'Resume %s from %s?' % (self.title, format_time(bookmark))
resume = xbmcgui.Dialog()
resume = resume.yesno(self.title, '', question, '', 'Start from beginning', 'Resume')
if resume: self.seekTime(bookmark)
self._sought = True
def onPlayBackStopped(self):
xbmc.log('1Channel: Playback Stopped')
if self.tracking:
playedTime = int(self._lastPos)
watched_values = [.7, .8, .9]
min_watched_percent = watched_values[int(ADDON.getSetting('watched-percent'))]
percent = int((playedTime / self._totalTime) * 100)
pTime = format_time(playedTime)
tTime = format_time(self._totalTime)
xbmc.log('1Channel: Service: %s played of %s total = %s%%' % (pTime, tTime, percent))
if playedTime == 0 and self._totalTime == 999999:
raise RuntimeError('XBMC silently failed to start playback')
elif ((playedTime / self._totalTime) > min_watched_percent) and (
self.video_type == 'movie' or (self.season and self.episode)):
xbmc.log('1Channel: Service: Threshold met. Marking item as watched')
if self.video_type == 'movie':
videotype = 'movie'
else:
videotype = 'episode'
ChangeWatched(self.imdb, videotype, self.title, self.season, self.episode, self.year, watched=7)
sql = 'DELETE FROM bookmarks WHERE video_type=? AND title=? AND season=? AND episode=? AND year=?'
if DB == 'mysql':
sql = sql.replace('?', '%s')
db = database.connect(DB_NAME, DB_USER, DB_PASS, DB_ADDRESS, buffered=True)
else:
db = database.connect(db_dir)
cur = db.cursor()
cur.execute(sql, (self.video_type, unicode(self.title, 'utf-8'), self.season, self.episode, self.year))
db.commit()
db.close()
else:
xbmc.log('1Channel: Service: Threshold not met. Saving bookmark')
sql = 'REPLACE INTO bookmarks (video_type, title, season, episode, year, bookmark) VALUES(?,?,?,?,?,?)'
if DB == 'mysql':
sql = sql.replace('?', '%s')
db = database.connect(DB_NAME, DB_USER, DB_PASS, DB_ADDRESS, buffered=True)
else:
sql = 'INSERT or ' + sql
db = database.connect(db_dir)
cur = db.cursor()
cur.execute(sql, (self.video_type, unicode(self.title, 'utf-8'), self.season,
self.episode, self.year, playedTime))
db.commit()
db.close()
self.reset()
def onPlayBackEnded(self):
xbmc.log('1Channel: Playback completed')
self.onPlayBackStopped()
monitor = Service()
while not xbmc.abortRequested:
if ADDON.getSetting('auto-update-subscriptions') == 'true':
now = datetime.datetime.now()
last_run = ADDON.getSetting('last_run')
last_run = datetime.datetime.strptime(last_run, "%Y-%m-%d %H:%M:%S.%f")
elapsed = now - last_run
threshold = datetime.timedelta(hours=monitor.hours)
if elapsed > threshold:
is_scanning = xbmc.getCondVisibility('Library.IsScanningVideo')
if not (monitor.isPlaying() or is_scanning):
xbmc.log('1Channel: Service: Updating subscriptions')
builtin = 'RunPlugin(plugin://plugin.video.1channel/?mode=UpdateSubscriptions)'
xbmc.executebuiltin(builtin)
ADDON.setSetting('last_run', now.strftime("%Y-%m-%d %H:%M:%S.%f"))
else:
xbmc.log('1Channel: Service: Busy... Postponing subscription update')
while monitor.tracking and monitor.isPlayingVideo():
monitor._lastPos = monitor.getTime()
xbmc.sleep(1000)
xbmc.sleep(1000)
xbmc.log('1Channel: Service: shutting down...')