forked from trakt/script.trakt
-
Notifications
You must be signed in to change notification settings - Fork 1
/
notification_service.py
280 lines (230 loc) · 9.36 KB
/
notification_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
# -*- coding: utf-8 -*-
""" Handles notifications from XBMC via its own thread and forwards them on to the scrobbler """
import sys
import xbmc
import xbmcaddon
import xbmcgui
if sys.version_info < (2, 7):
import simplejson as json
else:
import json
import globals
from traktapi import traktAPI
from utilities import Debug, checkScrobblingExclusion, xbmcJsonRequest
from scrobbler import Scrobbler
from movie_sync import SyncMovies
from episode_sync import SyncEpisodes
from sync_exec import do_sync
class NotificationService:
_scrobbler = None
def __init__(self):
self.run()
def _dispatch(self, data):
Debug("[Notification] Dispatch: %s" % data)
xbmc.sleep(500)
# check if scrobbler thread is still alive
if not self._scrobbler.isAlive():
if self.Player._playing and not self._scrobbler.pinging:
# make sure pinging is set
self._scrobbler.pinging = True
Debug("[Notification] Scrobler thread died, restarting.")
self._scrobbler.start()
action = data["action"]
if action == "started":
del data["action"]
p = {"item": data}
self._scrobbler.playbackStarted(p)
elif action == "ended" or action == "stopped":
self._scrobbler.playbackEnded()
elif action == "paused":
self._scrobbler.playbackPaused()
elif action == "resumed":
self._scrobbler.playbackResumed()
elif action == "seek" or action == "seekchapter":
self._scrobbler.playbackSeek()
elif action == "databaseUpdated":
if do_sync('movies'):
movies = SyncMovies(show_progress=False, api=globals.traktapi)
movies.Run()
if do_sync('episodes'):
episodes = SyncEpisodes(show_progress=False, api=globals.traktapi)
episodes.Run()
elif action == "scanStarted":
pass
elif action == "settingsChanged":
Debug("[Notification] Settings changed, reloading.")
globals.traktapi.updateSettings()
else:
Debug("[Notification] '%s' unknown dispatch action!" % action)
def run(self):
Debug("[Notification] Starting")
# setup event driven classes
self.Player = traktPlayer(action = self._dispatch)
self.Monitor = traktMonitor(action = self._dispatch)
# init traktapi class
globals.traktapi = traktAPI()
# initalize scrobbler class
self._scrobbler = Scrobbler(globals.traktapi)
# start loop for events
while (not xbmc.abortRequested):
xbmc.sleep(500)
# we aborted
if xbmc.abortRequested:
Debug("[Notification] abortRequested received, shutting down.")
# delete player/monitor
del self.Player
del self.Monitor
# join scrobbler, to wait for termination
Debug("[Notification] Joining scrobbler thread to wait for exit.")
self._scrobbler.join()
class traktMonitor(xbmc.Monitor):
def __init__(self, *args, **kwargs):
xbmc.Monitor.__init__(self)
self.action = kwargs["action"]
Debug("[traktMonitor] Initalized")
# called when database gets updated and return video or music to indicate which DB has been changed
def onDatabaseUpdated(self, database):
if database == "video":
Debug("[traktMonitor] onDatabaseUpdated(database: %s)" % database)
data = {"action": "databaseUpdated"}
self.action(data)
# called when database update starts and return video or music to indicate which DB is being updated
def onDatabaseScanStarted(self, database):
if database == "video":
Debug("[traktMonitor] onDatabaseScanStarted(database: %s)" % database)
data = {"action": "scanStarted"}
self.action(data)
def onSettingsChanged(self):
data = {"action": "settingsChanged"}
self.action(data)
class traktPlayer(xbmc.Player):
_playing = False
def __init__(self, *args, **kwargs):
xbmc.Player.__init__(self)
self.action = kwargs["action"]
Debug("[traktPlayer] Initalized")
# called when xbmc starts playing a file
def onPlayBackStarted(self):
xbmc.sleep(1000)
self.type = None
self.id = None
# only do anything if we're playing a video
if self.isPlayingVideo():
# get item data from json rpc
result = xbmcJsonRequest({"jsonrpc": "2.0", "method": "Player.GetItem", "params": {"playerid": 1}, "id": 1})
Debug("[traktPlayer] onPlayBackStarted() - %s" % result)
# check for exclusion
_filename = self.getPlayingFile()
if checkScrobblingExclusion(_filename):
Debug("[traktPlayer] onPlayBackStarted() - '%s' is in exclusion settings, ignoring." % _filename)
return
self.type = result["item"]["type"]
data = {"action": "started"}
# check type of item
if self.type == "unknown":
# do a deeper check to see if we have enough data to perform scrobbles
Debug("[traktPlayer] onPlayBackStarted() - Started playing a non-library file, checking available data.")
season = xbmc.getInfoLabel("VideoPlayer.Season")
episode = xbmc.getInfoLabel("VideoPlayer.Episode")
showtitle = xbmc.getInfoLabel("VideoPlayer.TVShowTitle")
year = xbmc.getInfoLabel("VideoPlayer.Year")
if season and episode and showtitle:
# we have season, episode and show title, can scrobble this as an episode
self.type = "episode"
data["type"] = "episode"
data["season"] = int(season)
data["episode"] = int(episode)
data["showtitle"] = showtitle
data["title"] = xbmc.getInfoLabel("VideoPlayer.Title")
Debug("[traktPlayer] onPlayBackStarted() - Playing a non-library 'episode' - %s - S%02dE%02d - %s." % (data["title"], data["season"], data["episode"]))
elif year and not season and not showtitle:
# we have a year and no season/showtitle info, enough for a movie
self.type = "movie"
data["type"] = "movie"
data["year"] = int(year)
data["title"] = xbmc.getInfoLabel("VideoPlayer.Title")
Debug("[traktPlayer] onPlayBackStarted() - Playing a non-library 'movie' - %s (%d)." % (data["title"], data["year"]))
else:
Debug("[traktPlayer] onPlayBackStarted() - Non-library file, not enough data for scrobbling, skipping.")
return
elif self.type == "episode" or self.type == "movie":
# get library id
self.id = result["item"]["id"]
data["id"] = self.id
data["type"] = self.type
if self.type == "episode":
Debug("[traktPlayer] onPlayBackStarted() - Doing multi-part episode check.")
result = xbmcJsonRequest({"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodeDetails", "params": {"episodeid": self.id, "properties": ["tvshowid", "season","episode"]}, "id": 1})
if result:
Debug("[traktPlayer] onPlayBackStarted() - %s" % result)
tvshowid = int(result["episodedetails"]["tvshowid"])
season = int(result["episodedetails"]["season"])
episode = int(result["episodedetails"]["episode"])
episode_index = episode - 1
result = xbmcJsonRequest({"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": {"tvshowid": tvshowid, "season": season, "properties": ["episode", "file"], "sort": {"method": "episode"}}, "id": 1})
if result:
Debug("[traktPlayer] onPlayBackStarted() - %s" % result)
# make sure episodes array exists in results
if result.has_key("episodes"):
multi = []
for i in range(episode_index, result["limits"]["total"]):
if result["episodes"][i]["file"] == result["episodes"][episode_index]["file"]:
multi.append(result["episodes"][i]["episodeid"])
else:
break
if len(multi) > 1:
data["multi_episode_data"] = multi
data["multi_episode_count"] = len(multi)
Debug("[traktPlayer] onPlayBackStarted() - This episode is part of a multi-part episode.")
else:
Debug("[traktPlayer] onPlayBackStarted() - Video type '%s' unrecognized, skipping." % self.type)
return
self._playing = True
# send dispatch
self.action(data)
# called when xbmc stops playing a file
def onPlayBackEnded(self):
if self._playing:
Debug("[traktPlayer] onPlayBackEnded() - %s" % self.isPlayingVideo())
self._playing = False
data = {"action": "ended"}
self.action(data)
# called when user stops xbmc playing a file
def onPlayBackStopped(self):
if self._playing:
Debug("[traktPlayer] onPlayBackStopped() - %s" % self.isPlayingVideo())
self._playing = False
data = {"action": "stopped"}
self.action(data)
# called when user pauses a playing file
def onPlayBackPaused(self):
if self._playing:
Debug("[traktPlayer] onPlayBackPaused() - %s" % self.isPlayingVideo())
data = {"action": "paused"}
self.action(data)
# called when user resumes a paused file
def onPlayBackResumed(self):
if self._playing:
Debug("[traktPlayer] onPlayBackResumed() - %s" % self.isPlayingVideo())
data = {"action": "resumed"}
self.action(data)
# called when user queues the next item
def onQueueNextItem(self):
if self._playing:
Debug("[traktPlayer] onQueueNextItem() - %s" % self.isPlayingVideo())
# called when players speed changes. (eg. user FF/RW)
def onPlayBackSpeedChanged(self, speed):
if self._playing:
Debug("[traktPlayer] onPlayBackSpeedChanged(speed: %s) - %s" % (str(speed), self.isPlayingVideo()))
# called when user seeks to a time
def onPlayBackSeek(self, time, offset):
if self._playing:
Debug("[traktPlayer] onPlayBackSeek(time: %s, offset: %s) - %s" % (str(time), str(offset), self.isPlayingVideo()))
data = {"action": "seek"}
self.action(data)
# called when user performs a chapter seek
def onPlayBackSeekChapter(self, chapter):
if self._playing:
Debug("[traktPlayer] onPlayBackSeekChapter(chapter: %s) - %s" % (str(chapter), self.isPlayingVideo()))
data = {"action": "seekchapter"}
self.action(data)