Advertisement
Guest User

Untitled

a guest
Jul 30th, 2012
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 31.04 KB | None | 0 0
  1. from time import strptime, mktime
  2. from operator import itemgetter
  3. import itertools
  4. import sys, itertools
  5. if sys.version_info < (2, 7):
  6. import simplejson
  7. else:
  8. import json as simplejson
  9. import xbmc, xbmcgui, xbmcaddon
  10. # http://mail.python.org/pipermail/python-list/2009-June/596197.html
  11. import _strptime
  12. from threading import Thread
  13.  
  14. __addon__ = xbmcaddon.Addon()
  15. __addonversion__ = __addon__.getAddonInfo('version')
  16. __addonid__ = __addon__.getAddonInfo('id')
  17. __cwd__ = __addon__.getAddonInfo('path')
  18.  
  19. def log(txt):
  20. message = 'script.watchlist: %s' % txt
  21. xbmc.log(msg=message, level=xbmc.LOGDEBUG)
  22.  
  23. class Main:
  24. def __init__( self ):
  25. self._parse_argv()
  26. self._init_vars()
  27. # check how we were executed
  28. if self.ALBUMID:
  29. self._play_album( self.ALBUMID )
  30. else:
  31. # clear our property, if another instance is already running it should stop now
  32. self.WINDOW.clearProperty('WatchList_Running')
  33. self._fetch_info()
  34. # give a possible other instance some time to notice the empty property
  35. xbmc.sleep(2000)
  36. self.WINDOW.setProperty('WatchList_Running', 'True')
  37. self._daemon()
  38.  
  39. def _parse_argv( self ):
  40. try:
  41. params = dict( arg.split( "=" ) for arg in sys.argv[ 1 ].split( "&" ) )
  42. except:
  43. params = {}
  44. self.MOVIES = params.get( "movies", "" )
  45. self.EPISODES = params.get( "episodes", "" )
  46. self.ALBUMS = params.get( "albums", "" )
  47. self.LIMIT = params.get( "limit", "25" )
  48. self.ALBUMID = params.get( "albumid", "" )
  49.  
  50. def _init_vars( self ):
  51. self.WINDOW = xbmcgui.Window( 10000 )
  52. self.Player = MyPlayer( action = self._update, movies = ( self.MOVIES == 'true' ), episodes = ( self.EPISODES == 'true' ), albums = ( self.ALBUMS == 'true' ) )
  53.  
  54. def _fetch_info( self ):
  55. if self.MOVIES == 'true':
  56. self._fetch_movies()
  57. if self.EPISODES == 'true':
  58. self._fetch_tvshows()
  59. self._fetch_episodes()
  60. if self.ALBUMS == 'true':
  61. self._fetch_songs()
  62. self._fetch_albums()
  63. if self.MOVIES == 'true':
  64. self._clear_movie_properties()
  65. self._set_movie_properties()
  66. if self.EPISODES == 'true':
  67. self._clear_episode_properties()
  68. self._set_episode_properties()
  69. if self.ALBUMS == 'true':
  70. self._clear_album_properties()
  71. self._set_album_properties()
  72.  
  73. def _fetch_movies( self ):
  74. self.movies = []
  75. self.movieList = []
  76. json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetMovies", "params": {"properties": ["title", "resume", "genre", "studio", "tagline", "runtime", "fanart", "thumbnail", "file", "plot", "plotoutline", "year", "lastplayed", "rating"]}, "id": 1}')
  77. json_query = unicode(json_query, 'utf-8', errors='ignore')
  78. json_response = simplejson.loads(json_query)
  79. if json_response.has_key('result') and json_response['result'].has_key('movies'):
  80. for item in json_response['result']['movies']:
  81. self.movieList.append(item)
  82. if item['resume']['position'] > 0:
  83. # this item has a resume point
  84. title = item['title']
  85. year = str(item['year'])
  86. genre = item['genre']
  87. studio = item['studio']
  88. plot = item['plot']
  89. plotoutline = item['plotoutline']
  90. tagline = item['tagline']
  91. runtime = item['runtime']
  92. fanart = item['fanart']
  93. thumbnail = item['thumbnail']
  94. path = item['file']
  95. rating = str(round(float(item['rating']),1))
  96. if item.has_key('resume'):
  97. # catch exceptions where the lastplayed isn't returned by json-rpc (bug?)
  98. lastplayed = item['lastplayed']
  99. else:
  100. lastplayed = ''
  101. if lastplayed == '':
  102. # catch exceptions where the item has been partially played, but playdate wasn't stored in the db
  103. lastplayed = '0'
  104. else:
  105. datetime = strptime(lastplayed, "%Y-%m-%d %H:%M:%S")
  106. lastplayed = str(mktime(datetime))
  107. self.movies.append([lastplayed, title, year, genre, studio, plot, plotoutline, tagline, runtime, fanart, thumbnail, path, rating])
  108. self.movies.sort(reverse=True)
  109. log("movie list: %s items" % len(self.movies))
  110.  
  111. def _fetch_tvshows( self ):
  112. self.tvshows = []
  113. # fetch all episodes in one query
  114. json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": {"properties": ["title", "playcount", "plot", "season", "episode", "showtitle", "thumbnail", "file", "lastplayed", "rating"], "sort": {"method": "episode"} }, "id": 1}' )
  115. json_query = unicode(json_query, 'utf-8', errors='ignore')
  116. json_response = simplejson.loads(json_query)
  117. if json_response.has_key('result') and json_response['result'].has_key('episodes'):
  118. json_response = json_response['result']['episodes']
  119. # our list is sorted by episode number, secondary we sort by tvshow title (itertools.groupy needs contiguous items) and split it into seperate lists for each tvshow
  120. episodes = [list(group) for key,group in itertools.groupby(sorted(json_response, key=itemgetter('showtitle')), key=itemgetter('showtitle'))]
  121. # fetch all tvshows, sorted by title
  122. json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetTVShows", "params": {"properties": ["title", "studio", "thumbnail", "fanart"], "sort": {"method": "title"}}, "id": 1}')
  123. json_query = unicode(json_query, 'utf-8', errors='ignore')
  124. json_response = simplejson.loads(json_query)
  125. if json_response.has_key('result') and json_response['result'].has_key('tvshows'):
  126. for count, tvshow in enumerate(json_response['result']['tvshows']):
  127. item = [tvshow['tvshowid'], tvshow['thumbnail'], tvshow['studio'], tvshow['title'], tvshow['fanart'], []]
  128. for episodelist in episodes:
  129. if episodelist[0]['showtitle'] == item[3]:
  130. item[5] = episodelist
  131. break
  132. self.tvshows.append(item)
  133. log("tv show list: %s items" % len(self.tvshows))
  134.  
  135. def _fetch_seasonthumb( self, tvshowid, seasonnumber ):
  136. json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetSeasons", "params": {"properties": ["season", "thumbnail"], "tvshowid":%s }, "id": 1}' % tvshowid)
  137. json_query = unicode(json_query, 'utf-8', errors='ignore')
  138. json_response = simplejson.loads(json_query)
  139. if json_response.has_key('result') and json_response['result'].has_key('seasons'):
  140. for item in json_response['result']['seasons']:
  141. season = "%.2d" % float(item['season'])
  142. if season == seasonnumber:
  143. thumbnail = item['thumbnail']
  144. return thumbnail
  145.  
  146. def _fetch_episodes( self ):
  147. self.episodes = []
  148. for tvshow in self.tvshows:
  149. lastplayed = ""
  150. episode_sorter = lambda item: (int(item['season']), int(item['episode']))
  151. for key, group in itertools.groupby(sorted(tvshow[5], key=episode_sorter), episode_sorter):
  152. playcount = 0
  153. for item in sorted(group, key=lambda x: (x['lastplayed'], x['episodeid'])):
  154. # sort first by lastplayed, so we're certain to always get the latest played item upon final iteration of the loop. Then sort by episodeid, mainly for the case where lastplayed is empty for all items, and we want the latest episodeid to be the one chosen (higher episodeid equals being added later to xbmc)
  155. playcount += int(item['playcount'])
  156. if playcount != 0:
  157. # this episode has been watched, record play date (we need it for sorting the final list) and continue to next episode
  158. lastplayed = item['lastplayed']
  159. if lastplayed == '':
  160. # catch exceptions where the episode has been played, but playdate wasn't stored in the db
  161. lastplayed = '0'
  162. else:
  163. datetime = strptime(lastplayed, "%Y-%m-%d %H:%M:%S")
  164. lastplayed = str(mktime(datetime))
  165. continue
  166. else:
  167. # this is the first unwatched episode, check if the episode is partially watched
  168. playdate = item['lastplayed']
  169. if (lastplayed == "") and (playdate == ""):
  170. # it's a tv show with 0 watched episodes, continue to the next tv show
  171. break
  172. else:
  173. # this is the episode we need
  174. title = item['title']
  175. episode = "%.2d" % float(item['episode'])
  176. path = item['file']
  177. plot = item['plot']
  178. season = "%.2d" % float(item['season'])
  179. thumbnail = item['thumbnail']
  180. showtitle = item['showtitle']
  181. rating = str(round(float(item['rating']),1))
  182. episodeno = "s%se%s" % ( season, episode, )
  183. print('Watchlist debug: %s - %s: %s'%(showtitle, title, episodeno))
  184. print(playdate)
  185. if not playdate == '':
  186. # if the episode is partially watched, use it's playdate for sorting
  187. datetime = strptime(playdate, "%Y-%m-%d %H:%M:%S")
  188. lastplayed = str(mktime(datetime))
  189. resumable = "True"
  190. else:
  191. resumable = "False"
  192. tvshowid = tvshow[0]
  193. showthumb = tvshow[1]
  194. studio = tvshow[2]
  195. fanart = tvshow[4]
  196. seasonthumb = ''
  197. self.episodes.append([lastplayed, title, episode, season, plot, showtitle, path, thumbnail, fanart, episodeno, studio, showthumb, seasonthumb, resumable, rating, playcount, tvshowid])
  198. # we have found our episode, collected all data, so continue to next tv show
  199. break
  200. self.episodes.sort(reverse=True)
  201. # only fetch seasonthumbs for items that will actually show up in the skin
  202. for count, episode in enumerate( self.episodes ):
  203. count += 1
  204. tvshowid = episode[16]
  205. season = episode[3]
  206. episode[12] = self._fetch_seasonthumb(tvshowid, season)
  207. if count == int(self.LIMIT):
  208. # stop here if our list contains more items
  209. break
  210. log("episode list: %s items" % len(self.episodes))
  211.  
  212. def _fetch_songs( self ):
  213. self.albumsids = {}
  214. previousid = ''
  215. json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "AudioLibrary.GetSongs", "params": {"properties": ["playcount", "albumid"], "sort": { "method": "album" } }, "id": 1}')
  216. json_query = unicode(json_query, 'utf-8', errors='ignore')
  217. json_response = simplejson.loads(json_query)
  218. if json_response.has_key('result') and (json_response['result'] != None) and (json_response['result'].has_key('songs')):
  219. for item in json_response['result']['songs']:
  220. albumid = item['albumid']
  221. if albumid != '':
  222. # ignore single tracks that do not belong to an album
  223. if albumid != previousid:
  224. # new album
  225. albumplaycount = 0
  226. playcount = item['playcount']
  227. albumplaycount = albumplaycount + playcount
  228. previousid = albumid
  229. else:
  230. # song from the same album
  231. playcount = item['playcount']
  232. albumplaycount = albumplaycount + playcount
  233. if playcount != 0:
  234. # don't add unplayed items
  235. self.albumsids.update({albumid: albumplaycount})
  236. self.albumsids = sorted(self.albumsids.items(), key=itemgetter(1))
  237. self.albumsids.reverse()
  238. log("album list: %s items" % len(self.albumsids))
  239.  
  240. def _fetch_albums( self ):
  241. self.albums = []
  242. for count, albumid in enumerate( self.albumsids ):
  243. count += 1
  244. json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "AudioLibrary.GetAlbumDetails", "params": {"properties": ["title", "description", "albumlabel", "artist", "genre", "year", "thumbnail", "fanart", "rating"], "albumid":%s }, "id": 1}' % albumid[0])
  245. json_query = unicode(json_query, 'utf-8', errors='ignore')
  246. json_response = simplejson.loads(json_query)
  247. if json_response.has_key('result') and json_response['result'].has_key('albumdetails'):
  248. item = json_response['result']['albumdetails']
  249. description = item['description']
  250. album = item['title']
  251. albumlabel = item['albumlabel']
  252. artist = item['artist']
  253. genre = item['genre']
  254. year = str(item['year'])
  255. thumbnail = item['thumbnail']
  256. fanart = item['fanart']
  257. rating = str(item['rating'])
  258. if rating == '48':
  259. rating = ''
  260. path = 'XBMC.RunScript(' + __addonid__ + ',albumid=' + str(albumid[0]) + ')'
  261. self.albums.append((album, artist, genre, year, albumlabel, description, rating, thumbnail, fanart, path))
  262. if count == int(self.LIMIT):
  263. # stop here if our list contains more items
  264. break
  265.  
  266. def _play_album( self, ID ):
  267. json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "AudioLibrary.GetSongs", "params": {"properties": ["file", "fanart"], "albumid":%s }, "id": 1}' % ID)
  268. json_query = unicode(json_query, 'utf-8', errors='ignore')
  269. json_response = simplejson.loads(json_query)
  270. # create a playlist
  271. playlist = xbmc.PlayList(0)
  272. # clear the playlist
  273. playlist.clear()
  274. if json_response.has_key('result') and json_response['result'].has_key('songs'):
  275. for item in json_response['result']['songs']:
  276. song = item['file']
  277. fanart = item['fanart']
  278. # create playlist item
  279. listitem = xbmcgui.ListItem()
  280. # add fanart image to the playlist item
  281. listitem.setProperty( "fanart_image", fanart )
  282. # add item to the playlist
  283. playlist.add( url=song, listitem=listitem )
  284. # play the playlist
  285. xbmc.Player().play( playlist )
  286.  
  287. def _daemon( self ):
  288. # keep running until xbmc exits or another instance is started
  289. while (not xbmc.abortRequested) and self.WINDOW.getProperty('WatchList_Running') == 'True':
  290. xbmc.sleep(1000)
  291. if xbmc.abortRequested:
  292. log('script stopped: xbmc quit')
  293. else:
  294. log('script stopped: new script instance started')
  295.  
  296. def _clear_movie_properties( self ):
  297. for count in range( int(self.LIMIT) ):
  298. count += 1
  299. self.WINDOW.clearProperty( "WatchList_Movie.%d.Label" % ( count ) )
  300.  
  301. def _clear_episode_properties( self ):
  302. for count in range( int(self.LIMIT) ):
  303. count += 1
  304. self.WINDOW.clearProperty( "WatchList_Episode.%d.Label" % ( count ) )
  305.  
  306. def _clear_album_properties( self ):
  307. for count in range( int(self.LIMIT) ):
  308. count += 1
  309. self.WINDOW.clearProperty( "WatchList_Album.%d.Label" % ( count ) )
  310.  
  311. def _set_movie_properties( self ):
  312. for count, movie in enumerate( self.movies ):
  313. count += 1
  314. self.WINDOW.setProperty( "WatchList_Movie.%d.Label" % ( count ), movie[1] )
  315. self.WINDOW.setProperty( "WatchList_Movie.%d.Year" % ( count ), movie[2] )
  316. self.WINDOW.setProperty( "WatchList_Movie.%d.Genre" % ( count ), movie[3] )
  317. self.WINDOW.setProperty( "WatchList_Movie.%d.Studio" % ( count ), movie[4] )
  318. self.WINDOW.setProperty( "WatchList_Movie.%d.Plot" % ( count ), movie[5] )
  319. self.WINDOW.setProperty( "WatchList_Movie.%d.PlotOutline" % ( count ), movie[6] )
  320. self.WINDOW.setProperty( "WatchList_Movie.%d.Tagline" % ( count ), movie[7] )
  321. self.WINDOW.setProperty( "WatchList_Movie.%d.Runtime" % ( count ), movie[8] )
  322. self.WINDOW.setProperty( "WatchList_Movie.%d.Fanart" % ( count ), movie[9] )
  323. self.WINDOW.setProperty( "WatchList_Movie.%d.Thumb" % ( count ), movie[10] )
  324. self.WINDOW.setProperty( "WatchList_Movie.%d.Path" % ( count ), movie[11] )
  325. self.WINDOW.setProperty( "WatchList_Movie.%d.Rating" % ( count ), movie[12] )
  326. if count == int(self.LIMIT):
  327. # stop here if our list contains more items
  328. break
  329.  
  330. def _set_episode_properties( self ):
  331. for count, episode in enumerate( self.episodes ):
  332. count += 1
  333. self.WINDOW.setProperty( "WatchList_Episode.%d.Label" % ( count ), episode[1] )
  334. self.WINDOW.setProperty( "WatchList_Episode.%d.Episode" % ( count ), episode[2] )
  335. self.WINDOW.setProperty( "WatchList_Episode.%d.Season" % ( count ), episode[3] )
  336. self.WINDOW.setProperty( "WatchList_Episode.%d.Plot" % ( count ), episode[4] )
  337. self.WINDOW.setProperty( "WatchList_Episode.%d.TVShowTitle" % ( count ), episode[5] )
  338. self.WINDOW.setProperty( "WatchList_Episode.%d.Path" % ( count ), episode[6] )
  339. self.WINDOW.setProperty( "WatchList_Episode.%d.Thumb" % ( count ), episode[7] )
  340. self.WINDOW.setProperty( "WatchList_Episode.%d.Fanart" % ( count ), episode[8] )
  341. self.WINDOW.setProperty( "WatchList_Episode.%d.EpisodeNo" % ( count ), episode[9] )
  342. self.WINDOW.setProperty( "WatchList_Episode.%d.Studio" % ( count ), episode[10] )
  343. self.WINDOW.setProperty( "WatchList_Episode.%d.TvshowThumb" % ( count ), episode[11] )
  344. self.WINDOW.setProperty( "WatchList_Episode.%d.SeasonThumb" % ( count ), episode[12] )
  345. self.WINDOW.setProperty( "WatchList_Episode.%d.IsResumable" % ( count ), episode[13] )
  346. self.WINDOW.setProperty( "WatchList_Episode.%d.Rating" % ( count ), episode[14] )
  347. if count == int(self.LIMIT):
  348. # stop here if our list contains more items
  349. break
  350.  
  351. def _set_album_properties( self ):
  352. for count, album in enumerate( self.albums ):
  353. count += 1
  354. self.WINDOW.setProperty( "WatchList_Album.%d.Label" % ( count ), album[0] )
  355. self.WINDOW.setProperty( "WatchList_Album.%d.Artist" % ( count ), album[1] )
  356. self.WINDOW.setProperty( "WatchList_Album.%d.Genre" % ( count ), album[2] )
  357. self.WINDOW.setProperty( "WatchList_Album.%d.Year" % ( count ), album[3] )
  358. self.WINDOW.setProperty( "WatchList_Album.%d.Album_Label" % ( count ), album[4] )
  359. self.WINDOW.setProperty( "WatchList_Album.%d.Album_Description" % ( count ), album[5] )
  360. self.WINDOW.setProperty( "WatchList_Album.%d.Rating" % ( count ), album[6] )
  361. self.WINDOW.setProperty( "WatchList_Album.%d.Thumb" % ( count ), album[7] )
  362. self.WINDOW.setProperty( "WatchList_Album.%d.Fanart" % ( count ), album[8] )
  363. self.WINDOW.setProperty( "WatchList_Album.%d.Path" % ( count ), album[9] )
  364. if count == int(self.LIMIT):
  365. # stop here if our list contains more items
  366. break
  367.  
  368. def _update( self, type, item, ended ):
  369. if type == 'movie':
  370. found = False
  371. # Delete movie from watch list movies
  372. for count, movie in enumerate( self.movies ):
  373. if movie[11] == item[11]:
  374. item[9] = movie[9]
  375. item[10] = movie[10]
  376. del self.movies[count]
  377. found = True
  378. break
  379. # If movie has a resume point, add it at the beginning
  380. if not ended:
  381. if found:
  382. self.movies.insert( 0, item )
  383. else:
  384. for m in self.movieList:
  385. if m['file'] == item[11]:
  386. item[9] = m['fanart']
  387. item[10] = m['thumbnail']
  388. self.movies.insert( 0, item )
  389. break
  390. self._clear_movie_properties()
  391. self._set_movie_properties()
  392. elif type == 'episode':
  393. # Only update if it was a new, unwatched episode
  394. if item[15] == 0:
  395. for tvshow in self.tvshows:
  396. # If tv show names match, set missing values
  397. if tvshow[3] == item[5]:
  398. fanart = tvshow[4]
  399. item[8] = fanart
  400. item[10] = tvshow[2]
  401. item[11] = tvshow[1]
  402. tvshowid = tvshow[0]
  403. item[16] = tvshowid
  404. # Delete episode from watch list episodes
  405. new = True
  406. for count, episode in enumerate( self.episodes ):
  407. if episode[5] == item[5]:
  408. # record our seasonthumb here since we need it later on
  409. seasonthumb = episode[12]
  410. item[12] = seasonthumb
  411. item[7] = episode[7]
  412. del self.episodes[count]
  413. new = False
  414. break
  415. # If the show is marked as watched, check for a new episode to add
  416. # else add the episode at the beginning of the list
  417. if ended:
  418. update = False
  419. insert = False
  420. for ep in tvshow[5]:
  421. seasonnumber = "%.2d" % float(ep['season'])
  422. episodenumber = "%.2d" % float(ep['episode'])
  423. if ( episodenumber != item[2] or seasonnumber != item[3] ) and ep['playcount'] == 0:
  424. if seasonnumber != item[3]:
  425. # our new episode is from the next season, so fetch seasonthumb
  426. seasonthumb = self._fetch_seasonthumb(tvshowid, seasonnumber)
  427. self.episodes.insert( 0, [ep['lastplayed'], ep['title'], episodenumber, seasonnumber, ep['plot'], ep['showtitle'], ep['file'], ep['thumbnail'], fanart, "s%se%s" % ( seasonnumber, episodenumber, ), tvshow[2], tvshow[1], seasonthumb, "True", str(round(float(ep['rating']),1)), ep['playcount']] )
  428. insert = True
  429. if update:
  430. break
  431. elif episodenumber == item[2] and seasonnumber == item[3]:
  432. ep['playcount'] = 1
  433. update = True
  434. if insert:
  435. break
  436. else:
  437. # If the episode wasn't in the watch list before, set season and episode thumb
  438. if new:
  439. for ep in tvshow[5]:
  440. seasonnumber = "%.2d" % float(ep['season'])
  441. episodenumber = "%.2d" % float(ep['episode'])
  442. if episodenumber == item[2] and seasonnumber == item[3]:
  443. item[7] = ep['thumbnail']
  444. item[12] = self._fetch_seasonthumb(tvshowid, seasonnumber)
  445. break
  446. self.episodes.insert( 0, item )
  447. break
  448. self._clear_episode_properties()
  449. self._set_episode_properties()
  450. elif type == 'album':
  451. xbmc.sleep(1000)
  452. self._fetch_songs()
  453. self._fetch_albums()
  454. self._clear_album_properties()
  455. self._set_album_properties()
  456.  
  457. class MyPlayer(xbmc.Player):
  458. def __init__( self, *args, **kwargs ):
  459. xbmc.Player.__init__( self )
  460. self.action = kwargs[ "action" ]
  461. self.movies = kwargs[ "movies" ]
  462. self.episodes = kwargs[ "episodes" ]
  463. self.albums = kwargs[ "albums" ]
  464. self.substrings = [ '-trailer', 'http://' ]
  465. self.timer = ""
  466. self.initValues()
  467.  
  468. def onPlayBackStarted( self ):
  469. # Set values based on the file content
  470. if ( self.isPlayingAudio() ):
  471. self.setValues( 'album' )
  472. else:
  473. # Stop timer thread on start
  474. self.stopTimer()
  475. # Update if an item was played (player is playing a playlist)
  476. if len(self.item) > 0:
  477. if self.type == 'movie' and self.movies:
  478. self.action( 'movie', self.item, ( self.time < 3*60 or self.totalTime * 0.9 <= self.time ) )
  479. if self.type == 'episode' and self.episodes:
  480. self.action( 'episode', self.item, ( self.totalTime * 0.9 <= self.time ) )
  481. self.initValues()
  482. # Start timer thread
  483. self.timer = Thread(target=self.startTimer)
  484. self.timer.start()
  485. if xbmc.getCondVisibility( 'VideoPlayer.Content(movies)' ):
  486. filename = ''
  487. isMovie = True
  488. try:
  489. filename = self.getPlayingFile()
  490. except:
  491. pass
  492. if filename != '':
  493. for string in self.substrings:
  494. if string in filename:
  495. isMovie = False
  496. break
  497. if isMovie:
  498. self.setValues( 'movie' )
  499. elif xbmc.getCondVisibility( 'VideoPlayer.Content(episodes)' ):
  500. # Check for tv show title and season to make sure it's really an episode
  501. if xbmc.getInfoLabel('VideoPlayer.Season') != "" and xbmc.getInfoLabel('VideoPlayer.TVShowTitle') != "":
  502. self.setValues( 'episode' )
  503.  
  504. def onPlayBackEnded( self ):
  505. self.stopTimer()
  506. if self.type == 'album' and self.albums:
  507. self.action( 'album', self.item, True )
  508. if self.type == 'movie' and self.movies:
  509. self.action( 'movie', self.item, True )
  510. if self.type == 'episode' and self.episodes:
  511. self.action( 'episode', self.item, True )
  512. self.initValues()
  513.  
  514. def onPlayBackStopped( self ):
  515. self.stopTimer()
  516. if self.type == 'album' and self.albums:
  517. self.action( 'album', self.item, True )
  518. if self.type == 'movie' and self.movies:
  519. self.action( 'movie', self.item, ( self.time < 3*60 or self.totalTime * 0.9 <= self.time ) )
  520. if self.type == 'episode' and self.episodes:
  521. self.action( 'episode', self.item, ( self.totalTime * 0.9 <= self.time ) )
  522. self.initValues()
  523.  
  524. def setValues( self, type ):
  525. self.type = type
  526. self.totalTime = 0
  527. try:
  528. self.totalTime = self.getTotalTime()
  529. except:
  530. pass
  531. if type == 'movie':
  532. title = xbmc.getInfoLabel('VideoPlayer.Title')
  533. year = xbmc.getInfoLabel('VideoPlayer.Year')
  534. genre = xbmc.getInfoLabel('VideoPlayer.Genre')
  535. studio = xbmc.getInfoLabel('VideoPlayer.Studio')
  536. plot = xbmc.getInfoLabel('VideoPlayer.Plot')
  537. plotoutline = xbmc.getInfoLabel('VideoPlayer.PlotOutline')
  538. tagline = xbmc.getInfoLabel('VideoPlayer.TagLine')
  539. runtime = xbmc.getInfoLabel('VideoPlayer.Duration')
  540. path = xbmc.getInfoLabel('Player.Filenameandpath')
  541. rating = str(xbmc.getInfoLabel('VideoPlayer.Rating'))
  542. self.item = ["", title, year, genre, studio, plot, plotoutline, tagline, runtime, "", "", path, rating]
  543. elif type == 'episode':
  544. title = xbmc.getInfoLabel('VideoPlayer.Title')
  545. episode = "%.2d" % float(xbmc.getInfoLabel('VideoPlayer.Episode'))
  546. path = xbmc.getInfoLabel('Player.Filenameandpath')
  547. plot = xbmc.getInfoLabel('VideoPlayer.Plot')
  548. season = "%.2d" % float(xbmc.getInfoLabel('VideoPlayer.Season'))
  549. showtitle = xbmc.getInfoLabel('VideoPlayer.TVShowTitle')
  550. rating = str(xbmc.getInfoLabel('VideoPlayer.Rating'))
  551. episodeno = "s%se%s" % ( season, episode, )
  552. studio = xbmc.getInfoLabel('VideoPlayer.Studio')
  553. playcount = xbmc.getInfoLabel('VideoPlayer.PlayCount')
  554. if playcount != "":
  555. playcount = int(playcount)
  556. else:
  557. playcount = 0
  558. self.item = ["", title, episode, season, plot, showtitle, path, "", "", episodeno, "", "", "", "True", rating, playcount, ""]
  559. elif type == 'album':
  560. pass
  561.  
  562. def initValues( self ):
  563. self.item = []
  564. self.type = ""
  565. self.time = 0
  566. self.totaltime = 0
  567.  
  568. def startTimer( self ):
  569. runtime = 0
  570. self.shutdown = False
  571. setTime = False
  572. while( self.isPlaying() and self.shutdown == False ):
  573. try:
  574. runtime = self.getTime()
  575. setTime = True
  576. except:
  577. setTime = False
  578. if (runtime <= 2):
  579. xbmc.sleep(5000)
  580. else:
  581. xbmc.sleep(1000)
  582. if setTime:
  583. self.time = runtime
  584.  
  585. def stopTimer( self ):
  586. if self.timer != "":
  587. self.shutdown = True
  588. xbmc.sleep(100)
  589. if self.timer.isAlive():
  590. self.timer.join()
  591.  
  592. if ( __name__ == "__main__" ):
  593. log('script version %s started' % __addonversion__)
  594. Main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement