Ejemplo n.º 1
0
    def seasonList(self, url):
        # Dirty implementation, but avoids rewritting everything from episodes.py.

        episodes = episodesx.Episodes(type=self.type)
        self.list = cache.get(episodes.trakt_list, 0, url, self.trakt_user)
        self.list = self.list[::-1]

        tvshows = tvshowsx.tvshows(type=self.type)
        tvshows.list = self.list
        tvshows.worker()
        self.list = tvshows.list

        # Remove duplicate season entries.
        try:
            result = []
            for i in self.list:
                found = False
                for j in result:
                    if i['imdb'] == j['imdb'] and i['season'] == j['season']:
                        found = True
                        break
                if not found:
                    result.append(i)
            self.list = result
        except:
            pass

        self.seasonDirectory(self.list)
Ejemplo n.º 2
0
def tvshowsUpdate(imdb, tvdb):
	try:
		if traktIndicators: return
		check_metahandler()
		from resources.lib.menus import episodes

		name = addonInfo('name')
		metaget = metahandlers.MetaData(tmdb_api_key, omdb_api_key, tvdb_api_key)
		metaget.get_meta('tvshow', name='', imdb_id=imdb)

		items = episodes.Episodes().get('', '0', imdb, '0', tvdb, create_directory=False)
		for i in range(len(items)):
			items[i]['season'] = int(items[i]['season'])
			items[i]['episode'] = int(items[i]['episode'])

		seasons = {}
		for i in items:
			if i['season'] not in seasons: seasons[i['season']] = []
			seasons[i['season']].append(i)

		countSeason = 0
		metaget.get_seasons('', imdb, seasons.keys()) # Must be called to initialize the database.

		for key, value in iter(seasons.items()):
			countEpisode = 0
			for i in value:
				countEpisode += int(metaget._get_watched_episode({'imdb_id': i['imdb'], 'season': i['season'], 'episode': i['episode'], 'premiered': ''}) == 5)
			countSeason += int(countEpisode == len(value))
			metaget.change_watched('season', '', imdb_id=imdb, season=key, watched = 5 if countEpisode == len(value) else 4)
		metaget.change_watched('tvshow', '', imdb_id=imdb, watched = 5 if countSeason == len(seasons.keys()) else 4)
	except:
		from resources.lib.modules import log_utils
		log_utils.error()
	containerRefresh()
Ejemplo n.º 3
0
def tvshowsUpdate(imdb, tvdb):
    try:
        if traktIndicators is True:
            return

        from metahandler import metahandlers
        from resources.lib.menus import episodes

        name = control.addonInfo('name')
        metaget = metahandlers.MetaData()
        metaget.get_meta('tvshow', name='', imdb_id=imdb)

        items = episodes.Episodes().get('', '0', imdb, tvdb, idx=False)

        for i in range(len(items)):
            items[i]['season'] = int(items[i]['season'])
            items[i]['episode'] = int(items[i]['episode'])

        seasons = {}

        for i in items:
            if i['season'] not in seasons:
                seasons[i['season']] = []
            seasons[i['season']].append(i)

        countSeason = 0

        metaget.get_seasons(
            '', imdb,
            seasons.keys())  # Must be called to initialize the database.

        for key, value in seasons.iteritems():
            countEpisode = 0

            for i in value:
                countEpisode += int(
                    metaget._get_watched_episode({
                        'imdb_id': i['imdb'],
                        'season': i['season'],
                        'episode': i['episode'],
                        'premiered': ''
                    }) == 7)

            countSeason += int(countEpisode == len(value))
            metaget.change_watched(
                'season',
                '',
                imdb_id=imdb,
                season=key,
                watched=7 if countEpisode == len(value) else 6)
        metaget.change_watched(
            'tvshow',
            '',
            imdb_id=imdb,
            watched=7 if countSeason == len(seasons.keys()) else 6)
    except:
        log_utils.error()

    control.refresh()
Ejemplo n.º 4
0
	def userlists(self):
		episodes = episodesx.Episodes(type = self.type)
		userlists = []

		try:
			if self.traktCredentials is False:
				raise Exception()
			activity = trakt.getActivity()
		except:
			pass

		try:
			if self.traktCredentials is False:
				raise Exception()
			self.list = []
			try:
				if activity > cache.timeout(episodes.trakt_user_list, self.traktlists_link, self.trakt_user):
					raise Exception()
				userlists += cache.get(episodes.trakt_user_list, 3, self.traktlists_link, self.trakt_user)
			except:
				userlists += cache.get(episodes.trakt_user_list, 0, self.traktlists_link, self.trakt_user)
		except:
			pass

		try:
			if self.traktCredentials is False:
				raise Exception()
			self.list = []
			try:
				if activity > cache.timeout(episodes.trakt_user_list, self.traktlikedlists_link, self.trakt_user): raise Exception()
				userlists += cache.get(episodes.trakt_user_list, 3, self.traktlikedlists_link, self.trakt_user)
			except:
				userlists += cache.get(episodes.trakt_user_list, 0, self.traktlikedlists_link, self.trakt_user)
		except:
			pass

		self.list = []

		# Filter the user's own lists that were
		for i in range(len(userlists)):
			contains = False
			adapted = userlists[i]['url'].replace('/me/', '/%s/' % self.trakt_user)
			for j in range(len(self.list)):
				if adapted == self.list[j]['url'].replace('/me/', '/%s/' % self.trakt_user):
					contains = True
					break
			if not contains:
				self.list.append(userlists[i])

		for i in range(0, len(self.list)): self.list[i].update({'image': 'traktlists.png', 'action': 'seasonsList'})

		# Watchlist
		if self.traktCredentials is True:
			self.list.insert(0, {'name': control.lang(32033).encode('utf-8'), 'url': self.traktwatchlist_link, 'image': 'traktwatch.png', 'action': 'seasons'})

		episodes.addDirectory(self.list, queue = True)
		return self.list
Ejemplo n.º 5
0
def tvshows(tvshowtitle, imdb, tvdb, season, watched):
	watched = int(watched)
	try:
		if traktIndicators is True:
			if watched == 7:
				trakt.watch(name=tvshowtitle, imdb = imdb, tvdb = tvdb, season = season, refresh = True)
			else:
				trakt.unwatch(name=tvshowtitle, imdb = imdb, tvdb = tvdb, season = season, refresh = True)
		else:
			from metahandler import metahandlers
			from resources.lib.menus import episodes

			name = control.addonInfo('name')
			dialog = control.progressDialogBG
			dialog.create(str(name), str(tvshowtitle))
			dialog.update(0, str(name), str(tvshowtitle))

			metaget = metahandlers.MetaData()
			metaget.get_meta('tvshow', name='', imdb_id=imdb)

			items = episodes.Episodes().get(tvshowtitle, '0', imdb, tvdb, idx = False)

			for i in range(len(items)):
				items[i]['season'] = int(items[i]['season'])
				items[i]['episode'] = int(items[i]['episode'])

			try:
				items = [i for i in items if int('%01d' % int(season)) == int('%01d' % i['season'])]
			except:
				pass

			items = [{'label': '%s S%02dE%02d' % (tvshowtitle, i['season'], i['episode']), 'season': int('%01d' % i['season']), 'episode': int('%01d' % i['episode'])} for i in items]

			count = len(items)

			for i in range(count):
				if xbmc.abortRequested is True:
					return sys.exit()
				dialog.update(int(100.0 / count * i), str(name), str(items[i]['label']))
				season, episode = items[i]['season'], items[i]['episode']
				metaget.get_episode_meta('', imdb_id = imdb, season = season, episode = episode)
				metaget.change_watched('episode', '', imdb_id = imdb, season = season, episode = episode, watched = watched)

			tvshowsUpdate(imdb = imdb, tvdb = tvdb)

			try:
				dialog.close()
			except:
				pass
	except:
		log_utils.error()
Ejemplo n.º 6
0
def tvshows(tvshowtitle, imdb, tvdb, season, watched):
	watched = int(watched)
	try:
		if traktIndicators:
			if watched == 5: trakt.watch(name=tvshowtitle, imdb=imdb, tvdb=tvdb, season=season, refresh=True)
			else: trakt.unwatch(name=tvshowtitle, imdb=imdb, tvdb=tvdb, season=season, refresh=True)
		else:
			check_metahandler()
			from resources.lib.menus import episodes
			from sys import exit as sysexit

			name = addonInfo('name')
			dialog = progressDialogBG
			dialog.create(str(name), str(tvshowtitle))
			dialog.update(0, str(name), str(tvshowtitle))

			metaget = metahandlers.MetaData(tmdb_api_key, omdb_api_key, tvdb_api_key)
			metaget.get_meta('tvshow', name='', imdb_id=imdb)

			items = episodes.Episodes().get(tvshowtitle, '0', imdb, tvdb, create_directory = False)
			for i in range(len(items)):
				items[i]['season'] = int(items[i]['season'])
				items[i]['episode'] = int(items[i]['episode'])
			try: items = [i for i in items if int('%01d' % int(season)) == int('%01d' % i['season'])]
			except: pass

			items = [{'label': '%s S%02dE%02d' % (tvshowtitle, i['season'], i['episode']), 'season': int('%01d' % i['season']), 'episode': int('%01d' % i['episode'])} for i in items]
			count = len(items)
			for i in range(count):
				if monitor.abortRequested(): return sysexit()
				dialog.update(int(100.0 / count * i), str(name), str(items[i]['label']))
				season, episode = items[i]['season'], items[i]['episode']
				metaget.get_episode_meta('', imdb_id=imdb, season=season, episode=episode)
				metaget.change_watched('episode', '', imdb_id=imdb, season=season, episode=episode, watched=watched)
			tvshowsUpdate(imdb=imdb, tvdb=tvdb)

			try: dialog.close()
			except: pass
			del dialog
	except:
		from resources.lib.modules import log_utils
		log_utils.error()
Ejemplo n.º 7
0
    # seasons.Seasons().get(tvshowtitle, year, imdb, tmdb, tvdb)

elif action == 'seasonsUserlists':
    from resources.lib.indexers import seasons
    seasons.Seasons().userlists()

elif action == 'seasonsList':
    from resources.lib.menus import seasons
    seasons.Seasons().seasonList(url)

####################################################
# EPISODES
####################################################
elif action == 'episodes':
    from resources.lib.menus import episodes
    episodes.Episodes().get(tvshowtitle, year, imdb, tvdb, season, episode)
    # episodes.Episodes().get(tvshowtitle, year, imdb, tmdb, tvdb, season, episode)

elif action == 'episodesPage':
    from resources.lib.menus import episodes
    episodes.Episodes().get(tvshowtitle, year, imdb, tvdb, season, episode)

elif action == 'tvWidget':
    from resources.lib.menus import episodes
    episodes.Episodes().widget()

elif action == 'calendar':
    from resources.lib.menus import episodes
    episodes.Episodes().calendar(url)

elif action == 'calendars':
Ejemplo n.º 8
0
def router(params):
    action = params.get('action')
    id = params.get('id')
    name = params.get('name')
    title = params.get('title')
    year = params.get('year')
    imdb = params.get('imdb')
    tmdb = params.get('tmdb')
    tvdb = params.get('tvdb')
    season = params.get('season')
    episode = params.get('episode')
    tvshowtitle = params.get('tvshowtitle')
    type = params.get('type')
    url = params.get('url')
    query = params.get('query')
    source = params.get('source')

    if action is None:
        from resources.lib.menus import navigator
        isUpdate = control.homeWindow.getProperty('venom.updated')
        if isUpdate == 'true':
            control.execute(
                'RunPlugin(plugin://plugin.video.venom/?action=tools_cleanSettings)'
            )
            control.homeWindow.clearProperty('venom.updated')
            from resources.lib.modules import changelog
            changelog.get()
        navigator.Navigator().root()

    ####################################################
    #---MOVIES
    ####################################################
    elif action == 'movieNavigator':
        from resources.lib.menus import navigator
        navigator.Navigator().movies()

    elif action == 'movieliteNavigator':
        from resources.lib.menus import navigator
        navigator.Navigator().movies(lite=True)

    elif action == 'mymovieNavigator':
        from resources.lib.menus import navigator
        navigator.Navigator().mymovies()

    elif action == 'mymovieliteNavigator':
        from resources.lib.menus import navigator
        navigator.Navigator().mymovies(lite=True)

    elif action == 'movies':
        from resources.lib.menus import movies
        movies.Movies().get(url)

    elif action == 'moviePage':
        from resources.lib.menus import movies
        movies.Movies().get(url)

    elif action == 'tmdbmovies':
        from resources.lib.menus import movies
        movies.Movies().getTMDb(url)

    elif action == 'tmdbmoviePage':
        from resources.lib.menus import movies
        movies.Movies().getTMDb(url)

    elif action == 'movieSearch':
        from resources.lib.menus import movies
        movies.Movies().search()

    elif action == 'movieSearchnew':
        from resources.lib.menus import movies
        movies.Movies().search_new()

    elif action == 'movieSearchterm':
        from resources.lib.menus import movies
        movies.Movies().search_term(name)

    elif action == 'moviePerson':
        from resources.lib.menus import movies
        movies.Movies().person()

    elif action == 'movieGenres':
        from resources.lib.menus import movies
        movies.Movies().genres()

    elif action == 'movieLanguages':
        from resources.lib.menus import movies
        movies.Movies().languages()

    elif action == 'movieCertificates':
        from resources.lib.menus import movies
        movies.Movies().certifications()

    elif action == 'movieYears':
        from resources.lib.menus import movies
        movies.Movies().years()

    elif action == 'moviePersons':
        from resources.lib.menus import movies
        movies.Movies().persons(url)

    elif action == 'moviesUnfinished':
        from resources.lib.menus import movies
        movies.Movies().unfinished(url)

    elif action == 'movieUserlists':
        from resources.lib.menus import movies
        movies.Movies().userlists()

    elif action == 'movies_traktUnfinishedManager':
        from resources.lib.menus import movies
        movies.Movies().unfinishedManager()

    ####################################################
    #---Collections
    ####################################################
    elif action and action.startswith('collections'):
        if action == 'collections_Navigator':
            from resources.lib.menus import collections
            collections.Collections().collections_Navigator()
        elif action == 'collections_Boxset':
            from resources.lib.menus import collections
            collections.Collections().collections_Boxset()
        elif action == 'collections_Kids':
            from resources.lib.menus import collections
            collections.Collections().collections_Kids()
        elif action == 'collections_BoxsetKids':
            from resources.lib.menus import collections
            collections.Collections().collections_BoxsetKids()
        elif action == 'collections_Superhero':
            from resources.lib.menus import collections
            collections.Collections().collections_Superhero()
        elif action == 'collections_MartialArts':
            from resources.lib.menus import collections
            collections.Collections().collections_martial_arts()
        elif action == 'collections_MartialArtsActors':
            from resources.lib.menus import collections
            collections.Collections().collections_martial_arts_actors()
        elif action == 'collections':
            from resources.lib.menus import collections
            collections.Collections().get(url)

    ####################################################
    #---Furk
    ####################################################
    elif action and action.startswith('furk'):
        if action == "furkNavigator":
            from resources.lib.menus import navigator
            navigator.Navigator().furk()
        elif action == "furkUserFiles":
            from resources.lib.menus import furk
            furk.Furk().user_files()
        elif action == "furkMetaSearch":
            from resources.lib.menus import furk
            furk.Furk().furk_meta_search(url)
        elif action == "furkSearch":
            from resources.lib.menus import furk
            furk.Furk().search()
        elif action == "furkSearchNew":
            from resources.lib.menus import furk
            furk.Furk().search_new()

    ####################################################
    # TV Shows
    ####################################################
    # if action and action.startswith('tv_'):
    elif action == 'tvNavigator':
        from resources.lib.menus import navigator
        navigator.Navigator().tvshows()

    elif action == 'tvliteNavigator':
        from resources.lib.menus import navigator
        navigator.Navigator().tvshows(lite=True)

    elif action == 'mytvNavigator':
        from resources.lib.menus import navigator
        navigator.Navigator().mytvshows()

    elif action == 'mytvliteNavigator':
        from resources.lib.menus import navigator
        navigator.Navigator().mytvshows(lite=True)

    elif action == 'tvshows':
        from resources.lib.menus import tvshows
        tvshows.TVshows().get(url)

    elif action == 'tvshowPage':
        from resources.lib.menus import tvshows
        tvshows.TVshows().get(url)

    elif action == 'tmdbTvshows':
        from resources.lib.menus import tvshows
        tvshows.TVshows().getTMDb(url)

    elif action == 'tmdbTvshowPage':
        from resources.lib.menus import tvshows
        tvshows.TVshows().getTMDb(url)

    elif action == 'tvmazeTvshows':
        from resources.lib.menus import tvshows
        tvshows.TVshows().getTVmaze(url)

    elif action == 'tvmazeTvshowPage':
        from resources.lib.menus import tvshows
        tvshows.TVshows().getTVmaze(url)

    elif action == 'tvSearch':
        from resources.lib.menus import tvshows
        tvshows.TVshows().search()

    elif action == 'tvSearchnew':
        from resources.lib.menus import tvshows
        tvshows.TVshows().search_new()

    elif action == 'tvSearchterm':
        from resources.lib.menus import tvshows
        tvshows.TVshows().search_term(name)

    elif action == 'tvPerson':
        from resources.lib.menus import tvshows
        tvshows.TVshows().person()

    elif action == 'tvGenres':
        from resources.lib.menus import tvshows
        tvshows.TVshows().genres()

    elif action == 'tvNetworks':
        from resources.lib.menus import tvshows
        tvshows.TVshows().networks()

    elif action == 'tvLanguages':
        from resources.lib.menus import tvshows
        tvshows.TVshows().languages()

    elif action == 'tvCertificates':
        from resources.lib.menus import tvshows
        tvshows.TVshows().certifications()

    elif action == 'tvPersons':
        from resources.lib.menus import tvshows
        tvshows.TVshows().persons(url)

    elif action == 'tvUserlists':
        from resources.lib.menus import tvshows
        tvshows.TVshows().userlists()

    elif action == 'tvOriginals':
        from resources.lib.menus import tvshows
        tvshows.TVshows().originals()

    elif action == 'shows_traktHiddenManager':
        from resources.lib.menus import tvshows
        tvshows.TVshows().traktHiddenManager()

    ####################################################
    #---SEASONS
    ####################################################
    elif action == 'seasons':
        from resources.lib.menus import seasons
        art = params.get('art')
        seasons.Seasons().get(tvshowtitle, year, imdb, tmdb, tvdb, art)

    ####################################################
    #---EPISODES
    ####################################################
    elif action == 'episodes':
        from resources.lib.menus import episodes
        meta = params.get('meta')
        episodes.Episodes().get(tvshowtitle, year, imdb, tmdb, tvdb, meta,
                                season, episode)

    elif action == 'calendar':
        from resources.lib.menus import episodes
        episodes.Episodes().calendar(url)

    elif action == 'upcomingProgress':
        from resources.lib.menus import episodes
        episodes.Episodes().upcoming_progress(url)

    elif action == 'calendars':
        from resources.lib.menus import episodes
        episodes.Episodes().calendars()

    elif action == 'episodesUnfinished':
        from resources.lib.menus import episodes
        episodes.Episodes().unfinished(url)

    elif action == 'episodesUserlists':
        from resources.lib.menus import episodes
        episodes.Episodes().userlists()

    elif action == 'episodes_traktUnfinishedManager':
        from resources.lib.menus import episodes
        episodes.Episodes().unfinishedManager()

    ####################################################
    #---Premium Services
    ####################################################
    elif action == 'premiumNavigator':
        from resources.lib.menus import navigator
        navigator.Navigator().premium_services()

    elif action and action.startswith('pm_'):
        if action == 'pm_ServiceNavigator':
            from resources.lib.menus import navigator
            navigator.Navigator().premiumize_service()
        elif action == 'pm_AccountInfo':
            from resources.lib.debrid import premiumize
            premiumize.Premiumize().account_info_to_dialog()
        # elif action == 'pm_Authorize':
        # from resources.lib.debrid import premiumize
        # premiumize.Premiumize().auth()
        elif action == 'pm_MyFiles':
            from resources.lib.debrid import premiumize
            premiumize.Premiumize().my_files_to_listItem(id, name)
        elif action == 'pm_Transfers':
            from resources.lib.debrid import premiumize
            premiumize.Premiumize().user_transfers_to_listItem()
        elif action == 'pm_Rename':
            from resources.lib.debrid import premiumize
            premiumize.Premiumize().rename(type, id, name)
        elif action == 'pm_Delete':
            from resources.lib.debrid import premiumize
            premiumize.Premiumize().delete(type, id, name)
        elif action == 'pm_DeleteTransfer':
            from resources.lib.debrid import premiumize
            premiumize.Premiumize().delete_transfer(id, name)
        elif action == 'pm_ClearFinishedTransfers':  # disabled for now till PM fixes
            from resources.lib.debrid import premiumize
            premiumize.Premiumize().clear_finished_transfers()

    elif action and action.startswith('rd_'):
        if action == 'rd_ServiceNavigator':
            from resources.lib.menus import navigator
            navigator.Navigator().realdebrid_service()
        elif action == 'rd_AccountInfo':
            from resources.lib.debrid import realdebrid
            realdebrid.RealDebrid().account_info_to_dialog()
        # elif action == 'rd_Authorize':
        # from resources.lib.debrid import realdebrid
        # realdebrid.RealDebrid().auth()
        elif action == 'rd_UserTorrentsToListItem':
            from resources.lib.debrid import realdebrid
            realdebrid.RealDebrid().user_torrents_to_listItem()
        elif action == 'rd_MyDownloads':
            from resources.lib.debrid import realdebrid
            realdebrid.RealDebrid().my_downloads_to_listItem(int(query))
        elif action == 'rd_BrowseUserTorrents':
            from resources.lib.debrid import realdebrid
            realdebrid.RealDebrid().browse_user_torrents(id)
        elif action == 'rd_DeleteUserTorrent':
            from resources.lib.debrid import realdebrid
            realdebrid.RealDebrid().delete_user_torrent(id, name)
        elif action == 'rd_DeleteDownload':
            from resources.lib.debrid import realdebrid
            realdebrid.RealDebrid().delete_download(id, name)

    elif action and action.startswith('ad_'):
        if action == 'ad_ServiceNavigator':
            from resources.lib.menus import navigator
            navigator.Navigator().alldebrid_service()
        elif action == 'ad_AccountInfo':
            from resources.lib.debrid import alldebrid
            alldebrid.AllDebrid().account_info_to_dialog()
        # elif action == 'ad_Authorize':
        # from resources.lib.debrid import alldebrid
        # alldebrid.AllDebrid().auth()
        elif action == 'ad_Transfers':
            from resources.lib.debrid import alldebrid
            alldebrid.AllDebrid().user_transfers_to_listItem()
        elif action == 'ad_CloudStorage':
            from resources.lib.debrid import alldebrid
            alldebrid.AllDebrid().user_cloud_to_listItem()
        elif action == 'ad_BrowseUserCloud':
            from resources.lib.debrid import alldebrid
            alldebrid.AllDebrid().browse_user_cloud(source)
        elif action == 'ad_DeleteTransfer':
            from resources.lib.debrid import alldebrid
            alldebrid.AllDebrid().delete_transfer(id, name, silent=False)
        elif action == 'ad_RestartTransfer':
            from resources.lib.debrid import alldebrid
            alldebrid.AllDebrid().restart_transfer(id, name, silent=False)

    ####################################################
    #---Anime
    ####################################################
    elif action and action.startswith('anime_'):
        if action == 'anime_Navigator':
            from resources.lib.menus import navigator
            navigator.Navigator().anime()
        elif action == 'anime_Movies':
            from resources.lib.menus import movies
            movies.Movies().get(url)
        elif action == 'anime_TVshows':
            from resources.lib.menus import tvshows
            tvshows.TVshows().get(url)

    ####################################################
    #---YouTube
    ####################################################
    elif action == 'youtube':
        from resources.lib.menus import youtube
        if id is None: youtube.yt_index().root(action)
        else: youtube.yt_index().get(action, id)

    elif action == 'sectionItem':
        pass  # Placeholder. This is a non-clickable menu item for notes, etc.

    ####################################################
    #---Download
    ####################################################
    elif action and action.startswith('download'):
        if action == 'downloadNavigator':
            from resources.lib.menus import navigator
            navigator.Navigator().downloads()
        elif action == 'download':
            caller = params.get('caller')
            image = params.get('image')
            if caller == 'sources':  # future, move to downloader module for pack support
                control.busy()
                try:
                    from json import loads as jsloads
                    from resources.lib.modules import sources
                    from resources.lib.modules import downloader
                    downloader.download(
                        name, image,
                        sources.Sources().sourcesResolve(jsloads(source)[0]),
                        title)
                except:
                    import traceback
                    traceback.print_exc()
            if caller == 'premiumize':
                control.busy()
                try:
                    from resources.lib.modules import downloader
                    from resources.lib.debrid import premiumize
                    downloader.download(
                        name, image,
                        premiumize.Premiumize().add_headers_to_url(
                            url.replace(' ', '%20')))
                except:
                    import traceback
                    traceback.print_exc()
            if caller == 'realdebrid':
                control.busy()
                try:
                    from resources.lib.modules import downloader
                    from resources.lib.debrid import realdebrid
                    if type == 'unrestrict':
                        downloader.download(
                            name, image,
                            realdebrid.RealDebrid().unrestrict_link(
                                url.replace(' ', '%20')))
                    else:
                        downloader.download(name, image,
                                            url.replace(' ', '%20'))
                except:
                    import traceback
                    traceback.print_exc()
            if caller == 'alldebrid':
                control.busy()
                try:
                    from resources.lib.modules import downloader
                    from resources.lib.debrid import alldebrid
                    downloader.download(
                        name, image,
                        alldebrid.AllDebrid().unrestrict_link(
                            url.replace(' ', '%20')))
                except:
                    import traceback
                    traceback.print_exc()

    ####################################################
    #---Tools
    ####################################################
    elif action and action.startswith('tools_'):
        if action == 'tools_ShowNews':
            from resources.lib.modules import newsinfo
            newsinfo.news()
        elif action == 'tools_ShowChangelog':
            from resources.lib.modules import changelog
            changelog.get()
        elif action == 'tools_ShowHelp':
            from resources.help import help
            help.get(name)
        elif action == 'tools_LanguageInvoker':
            from resources.lib.modules import language_invoker
            language_invoker.set_reuselanguageinvoker()
        elif action == 'tools_toolNavigator':
            from resources.lib.menus import navigator
            navigator.Navigator().tools()
        elif action == 'tools_traktToolsNavigator':
            from resources.lib.menus import navigator
            navigator.Navigator().traktTools()
        elif action == 'tools_searchNavigator':
            from resources.lib.menus import navigator
            navigator.Navigator().search()
        elif action == 'tools_viewsNavigator':
            from resources.lib.menus import navigator
            navigator.Navigator().views()
        elif action == 'tools_addView':
            from resources.lib.modules import views
            content = params.get('content')
            views.addView(content)
        elif action == 'tools_resetViewTypes':
            from resources.lib.modules import views
            views.clearViews()
        elif action == 'tools_cleanSettings':
            from resources.lib.modules import clean_settings
            clean_settings.clean_settings()
        elif action == 'tools_openMyAccount':
            from myaccounts import openMASettings
            from resources.lib.modules import my_accounts
            openMASettings(query)
            control.sleep(500)
            while control.condVisibility('Window.IsVisible(addonsettings)'
                                         ) or control.homeWindow.getProperty(
                                             'myaccounts.active') == 'true':
                control.sleep(500)
            control.sleep(100)
            my_accounts.syncMyAccounts()
            control.sleep(100)
            if params.get('opensettings') == 'true':
                control.openSettings(params.get('query2'),
                                     'plugin.video.venom')
        elif action == 'tools_syncMyAccount':
            from resources.lib.modules import my_accounts
            my_accounts.syncMyAccounts()
            if params.get('opensettings') == 'true':
                control.openSettings(query, 'plugin.video.venom')
        elif action == 'tools_traktAcctMyAccounts':
            control.execute(
                'RunScript(script.module.myaccounts, action=traktAcct)')
        elif action == 'tools_adAcctMyAccounts':
            control.execute(
                'RunScript(script.module.myaccounts, action=alldebridAcct)')
        elif action == 'tools_pmAcctMyAccounts':
            control.execute(
                'RunScript(script.module.myaccounts, action=premiumizeAcct)')
        elif action == 'tools_rdAcctMyAccounts':
            control.execute(
                'RunScript(script.module.myaccounts, action=realdebridAcct)')
        elif action == 'tools_openSettings':
            control.openSettings(query)
        elif action == 'tools_contextVenomSettings':
            control.openSettings('0.0', 'context.venom')
            control.trigger_widget_refresh()
        elif action == 'tools_fenomscrapersSettings':
            control.openSettings('0.0', 'script.module.fenomscrapers')
        elif action == 'tools_traktManager':
            from resources.lib.modules import trakt
            watched = (params.get('watched')
                       == 'True') if params.get('watched') else None
            unfinished = (params.get('unfinished')
                          == 'True') if params.get('unfinished') else False
            trakt.manager(name,
                          imdb,
                          tvdb,
                          season,
                          episode,
                          watched=watched,
                          unfinished=unfinished)
        elif action == 'tools_cachesyncMovies':
            from resources.lib.modules import trakt
            trakt.cachesyncMovies(int(params.get('timeout')))
        elif action == 'tools_cachesyncTVShows':
            from resources.lib.modules import trakt
            trakt.cachesyncTVShows(int(params.get('timeout')))
        elif action == 'tools_syncTraktProgress':
            from resources.lib.modules import trakt
            trakt.sync_progress()
        elif action == 'tools_syncTraktWatched':
            from resources.lib.modules import trakt
            trakt.sync_watched()

    ####################################################
    #---Play
    ####################################################
    elif action and action.startswith('play_'):
        if action == 'play_Item':
            from resources.lib.modules import sources
            premiered = params.get('premiered')
            meta = params.get('meta')
            select = params.get('select')
            rescrape = params.get('rescrape')
            sources.Sources().play(title, year, imdb, tmdb, tvdb, season,
                                   episode, tvshowtitle, premiered, meta,
                                   select, rescrape)

            # if episode and control.homeWindow.getProperty('venom.isplaying.playlist') != 'true':
            # if int(episode) != 1: control.playlist.clear()
            # import xbmc
            # enable_playnext = control.setting('enable.playnext') == 'true'
            # media_type = 'movie' if tvshowtitle is None else 'episode'
            # rescrape = params.get('rescrape')
            # select = params.get('select')
            # if control.homeWindow.getProperty('venom.isplaying.playlist') == 'true' or enable_playnext is False or media_type == 'movie' or rescrape or select == '0':
            # try:
            # if control.homeWindow.getProperty('venom.isplaying.playlist') == 'true':
            # xbmc.log('[ plugin.video.venom ] venom.isplaying.playlist = %s' % control.homeWindow.getProperty('venom.isplaying.playlist'), 1)
            # from resources.lib.modules import sources
            # premiered = params.get('premiered')
            # meta = params.get('meta')
            # xbmc.log('[ plugin.video.venom ] control.playlist.size() = %s' % control.playlist.size(), 1)
            # xbmc.log('[ plugin.video.venom ] control.playlist.getposition() = %s' % control.playlist.getposition(), 1)
            # xbmc.log('[ plugin.video.venom ] Calling....sources.Sources().play()', 1)
            # if int(control.playlist.getposition()) == -1 or (int(control.playlist.getposition()) == (control.playlist.size() - 1)):
            # control.homeWindow.clearProperty('venom.isplaying.playlist')
            # sources.Sources().play(title, year, imdb, tmdb, tvdb, season, episode, tvshowtitle, premiered, meta, select, rescrape)
            # except:
            # import traceback
            # traceback.print_exc()
            # else:
            # try:
            # xbmc.log('[ plugin.video.venom ] control.playlist.size() = %s' % control.playlist.size(), 1)
            # is_widget = 'plugin' not in control.infoLabel('Container.PluginName')
            # if is_widget:
            # control.playlist.clear()
            # control.cancelPlayback()

            # # control.playlist.clear()
            # # control.cancelPlayback()

            # if control.playlist.size() <= 1:
            # current_ep = episode
            # xbmc.log('[ plugin.video.venom ] current_ep = %s' % current_ep, 1)
            # from json import dumps as jsdumps
            # from resources.lib.menus import episodes
            # meta = params.get('meta')
            # items = episodes.Episodes().get(tvshowtitle, year, imdb, tmdb, tvdb, meta, season, episode, create_directory=False)
            # control.playlist.clear()
            # for i in items:
            # title = i['title']
            # systitle = quote_plus(title)
            # year = i['year']
            # imdb = i['imdb']
            # tmdb = i['tmdb']
            # tvdb = i['tvdb']
            # season = i['season']
            # episode = i['episode']
            # tvshowtitle = i['tvshowtitle']
            # systvshowtitle = quote_plus(tvshowtitle)
            # premiered = i['premiered']
            # sysmeta = quote_plus(jsdumps(i))
            # url = 'plugin://plugin.video.venom/?action=play_Item&title=%s&year=%s&imdb=%s&tmdb=%s&tvdb=%s&season=%s&episode=%s&tvshowtitle=%s&premiered=%s&meta=%s&select=1' % (
            # systitle, year, imdb, tmdb, tvdb, season, episode, systvshowtitle, premiered, sysmeta)
            # item = control.item(label=title, offscreen=True)
            # # item.setProperty('IsPlayable', 'true')
            # control.playlist.add(url=url, listitem=item)
            # control.homeWindow.setProperty('venom.isplaying.playlist', 'true')
            # playlist_urls = [control.playlist[i].getPath() for i in range(control.playlist.size())]
            # xbmc.log('[ plugin.video.venom ] control.playlist.size() = %s' % control.playlist.size(), 1)
            # xbmc.log('[ plugin.video.venom ] playlist_urls = %s' % playlist_urls, 1)
            # xbmc.log('[ plugin.video.venom ] Calling....control.player2().play(control.playlist)', 1)
            # control.player2().play(control.playlist)
            # return
            # except:
            # control.homeWindow.clearProperty('venom.isplaying.playlist')
            # import traceback
            # traceback.print_exc()

        elif action == "play_preScrapeNext":
            from resources.lib.modules.player import PlayNext
            PlayNext().prescrapeNext()

        elif action == "play_nextWindowXML":
            from resources.lib.modules.player import PlayNext
            play_next = PlayNext()
            play_next.display_xml()
            del play_next

        elif action == 'play_All':  # context menu works same as "Play from Here"
            control.player2().play(control.playlist)

        elif action == 'play_URL':
            caller = params.get('caller')
            if caller == 'realdebrid':
                from resources.lib.debrid import realdebrid
                if type == 'unrestrict':
                    control.player.play(
                        realdebrid.RealDebrid().unrestrict_link(
                            url.replace(' ', '%20')))
                else:
                    control.player.play(url.replace(' ', '%20'))
            elif caller == 'alldebrid':
                from resources.lib.debrid import alldebrid
                if type == 'unrestrict':
                    control.player.play(alldebrid.AllDebrid().unrestrict_link(
                        url.replace(' ', '%20')))
                else:
                    control.player.play(url.replace(' ', '%20'))
            else:
                control.player.play(url.replace(' ', '%20'))

        elif action == 'play_EpisodesList':  # global context option
            from json import dumps as jsdumps
            from resources.lib.menus import episodes
            meta = params.get('meta')
            items = episodes.Episodes().get(tvshowtitle,
                                            year,
                                            imdb,
                                            tmdb,
                                            tvdb,
                                            meta,
                                            season,
                                            episode,
                                            create_directory=False)
            control.playlist.clear()
            for i in items:
                title = i['title']
                systitle = quote_plus(title)
                year = i['year']
                imdb = i['imdb']
                tmdb = i['tmdb']
                tvdb = i['tvdb']
                season = i['season']
                episode = i['episode']
                tvshowtitle = i['tvshowtitle']
                systvshowtitle = quote_plus(tvshowtitle)
                premiered = i['premiered']
                sysmeta = quote_plus(jsdumps(i))
                url = 'plugin://plugin.video.venom/?action=play_Item&title=%s&year=%s&imdb=%s&tmdb=%s&tvdb=%s&season=%s&episode=%s&tvshowtitle=%s&premiered=%s&meta=%s&select=1' % (
                    systitle, year, imdb, tmdb, tvdb, season, episode,
                    systvshowtitle, premiered, sysmeta)
                item = control.item(label=title, offscreen=True)
                control.playlist.add(url=url, listitem=item)
            control.player2().play(control.playlist)

        elif action == 'play_Trailer':
            from resources.lib.modules import trailer
            windowedtrailer = params.get('windowedtrailer')
            windowedtrailer = int(windowedtrailer) if windowedtrailer in (
                "0", "1") else 0
            trailer.Trailer().play(type, name, year, url, imdb,
                                   windowedtrailer)

        elif action == 'play_Random':
            rtype = params.get('rtype')
            if rtype == 'movie':
                from resources.lib.menus import movies
                rlist = movies.Movies().get(url, create_directory=False)
                xbmc.log('movie rlist=%s' % rlist, 1)
                xbmc.log('url=%s' % url, 1)
                r = 'plugin://plugin.video.venom/?action=play_Item'
            elif rtype == 'episode':
                from resources.lib.menus import episodes
                meta = params.get('meta')
                rlist = episodes.Episodes().get(tvshowtitle,
                                                year,
                                                imdb,
                                                tmdb,
                                                tvdb,
                                                meta,
                                                season,
                                                create_directory=False)
                r = 'plugin://plugin.video.venom/?action=play_Item'
            elif rtype == 'season':
                from resources.lib.menus import seasons
                art = params.get('art')
                rlist = seasons.Seasons().get(tvshowtitle,
                                              year,
                                              imdb,
                                              tmdb,
                                              tvdb,
                                              art,
                                              create_directory=False)
                r = 'plugin://plugin.video.venom/?action=play_Random&rtype=episode'
            elif rtype == 'show':
                from resources.lib.menus import tvshows
                rlist = tvshows.TVshows().get(url, create_directory=False)
                r = 'plugin://plugin.video.venom/?action=play_Random&rtype=season'
            from random import randint
            from json import dumps as jsdumps
            try:
                rand = randint(1, len(rlist)) - 1
                for p in [
                        'title', 'year', 'imdb', 'tmdb', 'tvdb', 'season',
                        'episode', 'tvshowtitle', 'premiered', 'select'
                ]:
                    if rtype == "show" and p == "tvshowtitle":
                        try:
                            r += '&' + p + '=' + quote_plus(
                                rlist[rand]['title'])
                        except:
                            pass
                    else:
                        try:
                            r += '&' + p + '=' + quote_plus(str(
                                rlist[rand][p]))
                        except:
                            pass
                try:
                    r += '&meta=' + quote_plus(jsdumps(rlist[rand]))
                except:
                    r += '&meta=' + quote_plus("{}")
                if rtype == "movie":
                    try:
                        control.notification(
                            title=32536,
                            message='%s (%s)' %
                            (rlist[rand]['title'], rlist[rand]['year']))
                    except:
                        pass
                elif rtype == "episode":
                    try:
                        control.notification(title=32536,
                                             message='%s - %01dx%02d - %s' %
                                             (rlist[rand]['tvshowtitle'],
                                              int(rlist[rand]['season']),
                                              int(rlist[rand]['episode']),
                                              rlist[rand]['title']))
                    except:
                        pass
                control.execute('RunPlugin(%s)' % r)
            except:
                control.notification(message=32537)

    elif action == 'play':  # for support of old style .strm library files
        from resources.lib.modules import sources
        premiered = params.get('premiered')
        meta = params.get('meta')
        select = params.get('select')
        rescrape = params.get('rescrape')
        sources.Sources().play(title, year, imdb, tmdb, tvdb, season, episode,
                               tvshowtitle, premiered, meta, select, rescrape)

    ####################################################
    #---Playlist
    ####################################################
    elif action and action.startswith('playlist_'):
        if action == 'playlist_Manager':
            from resources.lib.modules import playlist
            art = params.get('art')
            meta = params.get('meta')
            playlist.playlistManager(name, url, meta, art)
        elif action == 'playlist_Show':
            from resources.lib.modules import playlist
            playlist.playlistShow()
        elif action == 'playlist_Clear':
            from resources.lib.modules import playlist
            playlist.playlistClear()
        elif action == 'playlist_QueueItem':
            control.queueItem()
            if name is None: control.notification(title=35515, message=35519)
            else: control.notification(title=name, message=35519)

    ####################################################
    #---Playcount
    ####################################################
    elif action and action.startswith('playcount_'):
        if action == 'playcount_Movie':
            from resources.lib.modules import playcount
            playcount.movies(name, imdb, query)
        elif action == 'playcount_Episode':
            from resources.lib.modules import playcount
            playcount.episodes(name, imdb, tvdb, season, episode, query)
        elif action == 'playcount_TVShow':
            from resources.lib.modules import playcount
            playcount.tvshows(name, imdb, tvdb, season, query)

    ####################################################
    #---Source Actions
    ####################################################
    elif action == 'alterSources':
        from resources.lib.modules import sources
        meta = params.get('meta')
        sources.Sources().alterSources(url, meta)

    elif action == 'showDebridPack':
        from resources.lib.modules.sources import Sources
        caller = params.get('caller')
        Sources().debridPackDialog(caller, name, url, source)

    elif action == 'sourceInfo':
        from resources.lib.modules.sources import Sources
        Sources().sourceInfo(source)

    elif action == 'cacheTorrent':
        caller = params.get('caller')
        pack = True if type == 'pack' else False
        if caller == 'RD':
            from resources.lib.debrid.realdebrid import RealDebrid as debrid_function
        elif caller == 'PM':
            from resources.lib.debrid.premiumize import Premiumize as debrid_function
        elif caller == 'AD':
            from resources.lib.debrid.alldebrid import AllDebrid as debrid_function
        success = debrid_function().add_uncached_torrent(url, pack=pack)
        if success:
            from resources.lib.modules import sources
            meta = params.get('meta')
            items = params.get('items')
            sources.Sources().playItem(title, items, source, meta)

    ####################################################
    #---Library Actions
    ####################################################
    elif action and action.startswith('library_'):
        if action == 'library_Navigator':
            from resources.lib.menus import navigator
            navigator.Navigator().library()
        elif action == 'library_movieToLibrary':
            from resources.lib.modules import library
            library.libmovies().add(name, title, year, imdb, tmdb)
        elif action == 'library_moviesToLibrary':
            from resources.lib.modules import library
            library.libmovies().range(url, name)
        elif action == 'library_moviesListToLibrary':
            from resources.lib.menus import movies
            movies.Movies().moviesListToLibrary(url)
        elif action == 'library_moviesToLibrarySilent':
            from resources.lib.modules import library
            library.libmovies().silent(url)
        elif action == 'library_tvshowToLibrary':
            from resources.lib.modules import library
            library.libtvshows().add(tvshowtitle, year, imdb, tmdb, tvdb)
        elif action == 'library_tvshowsToLibrary':
            from resources.lib.modules import library
            library.libtvshows().range(url, name)
        elif action == 'library_tvshowsListToLibrary':
            from resources.lib.menus import tvshows
            tvshows.TVshows().tvshowsListToLibrary(url)
        elif action == 'library_tvshowsToLibrarySilent':
            from resources.lib.modules import library
            library.libtvshows().silent(url)
        elif action == 'library_update':
            control.notification(message=32085)
            from resources.lib.modules import library
            library.libepisodes().update()
            library.libmovies().list_update()
            library.libtvshows().list_update()
            while True:
                if control.condVisibility('Library.IsScanningVideo'):
                    control.sleep(3000)
                    continue
                else:
                    break
            control.sleep(1000)
            control.notification(message=32086)
        elif action == 'library_clean':
            from resources.lib.modules import library
            library.lib_tools().clean()
        elif action == 'library_setup':
            from resources.lib.modules import library
            library.lib_tools().total_setup()
        elif action == 'library_service':
            from resources.lib.modules import library
            library.lib_tools().service()

    ####################################################
    #---Cache
    ####################################################
    elif action and action.startswith('cache_'):
        if action == 'cache_Navigator':
            from resources.lib.menus import navigator
            navigator.Navigator().cf()
        elif action == 'cache_clearAll':
            from resources.lib.menus import navigator
            navigator.Navigator().clearCacheAll()
        elif action == 'cache_clearSources':
            from resources.lib.menus import navigator
            navigator.Navigator().clearCacheProviders()
        elif action == 'cache_clearMeta':
            from resources.lib.menus import navigator
            navigator.Navigator().clearCacheMeta()
        elif action == 'cache_clearCache':
            from resources.lib.menus import navigator
            navigator.Navigator().clearCache()
        elif action == 'cache_clearSearch':
            from resources.lib.menus import navigator
            navigator.Navigator().clearCacheSearch()
        elif action == 'cache_clearSearchPhrase':
            from resources.lib.menus import navigator
            navigator.Navigator().clearCacheSearchPhrase(source, name)
        elif action == 'cache_clearBookmarks':
            from resources.lib.menus import navigator
            navigator.Navigator().clearBookmarks()
        elif action == 'cache_clearBookmark':
            from resources.lib.menus import navigator
            navigator.Navigator().clearBookmark(name, year)
        elif action == 'cache_clearKodiBookmark':  # context.venom action call only
            from resources.lib.database import cache
            cache.clear_local_bookmark(url)
Ejemplo n.º 9
0
#---SEASONS
####################################################
if action and action.startswith('seasons'):
	if action == 'seasons':
		from resources.lib.menus import seasons
		art = params.get('art')
		seasons.Seasons().get(tvshowtitle, year, imdb, tmdb, tvdb, art)

####################################################
#---EPISODES
####################################################
if action == 'playEpisodesList':
	from json import dumps as jsdumps
	from resources.lib.menus import episodes
	meta = params.get('meta')
	items = episodes.Episodes().get(tvshowtitle, year, imdb, tmdb, tvdb, meta, season, episode, create_directory=False)
	control.playlist.clear()
	for i in items:
		title = i['title']
		systitle = quote_plus(title)
		year = i['year']
		imdb = i['imdb']
		tmdb = i['tmdb']
		tvdb = i['tvdb']
		season = i['season']
		episode = i['episode']
		tvshowtitle = i['tvshowtitle']
		systvshowtitle = quote_plus(tvshowtitle)
		premiered = i['premiered']
		sysmeta = quote_plus(jsdumps(i))
		url = 'plugin://plugin.video.venom/?action=play&title=%s&year=%s&imdb=%s&tmdb=%s&tvdb=%s&season=%s&episode=%s&tvshowtitle=%s&premiered=%s&meta=%s&select="2"' % (
Ejemplo n.º 10
0
    def update(self, query=None, info='true'):
        if not query is None:
            control.idle()

        try:
            items = []
            season, episode = [], []
            show = [
                os.path.join(self.library_folder, i)
                for i in control.listDir(self.library_folder)[0]
            ]

            for s in show:
                try:
                    season += [
                        os.path.join(s, i) for i in control.listDir(s)[0]
                    ]
                except:
                    pass

            for s in season:
                try:
                    episode.append([
                        os.path.join(s, i) for i in control.listDir(s)[1]
                        if i.endswith('.strm')
                    ][-1])
                except:
                    pass

            for file in episode:
                try:
                    file = control.openFile(file)
                    read = file.read()
                    read = read.encode('utf-8')
                    file.close()

                    if not read.startswith(sys.argv[0]):
                        raise Exception()
                    params = dict(urlparse.parse_qsl(read.replace('?', '')))

                    try:
                        tvshowtitle = params['tvshowtitle']
                    except:
                        tvshowtitle = None

                    try:
                        tvshowtitle = params['show']
                    except:
                        pass

                    if tvshowtitle is None or tvshowtitle == '':
                        raise Exception()

                    year, imdb, tvdb = params['year'], params['imdb'], params[
                        'tvdb']
                    imdb = 'tt' + re.sub('[^0-9]', '', str(imdb))

                    try:
                        tmdb = params['tmdb']
                    except:
                        tmdb = '0'

                    items.append({
                        'tvshowtitle': tvshowtitle,
                        'year': year,
                        'imdb': imdb,
                        'tmdb': tmdb,
                        'tvdb': tvdb
                    })
                except:
                    pass

            items = [i for x, i in enumerate(items) if i not in items[x + 1:]]

            if len(items) == 0:
                raise Exception()
        except:
            import traceback
            traceback.print_exc()
            return

        try:
            lib = control.jsonrpc(
                '{"jsonrpc": "2.0", "method": "VideoLibrary.GetTVShows", "params": {"properties" : ["imdbnumber", "title", "year"]}, "id": 1}'
            )
            log_utils.log('lib = %s' % str(lib), __name__, log_utils.LOGDEBUG)
            lib = unicode(lib, 'utf-8', errors='ignore')
            log_utils.log('lib = %s' % str(lib), __name__, log_utils.LOGDEBUG)
            lib = json.loads(lib)['result']['tvshows']
        except:
            import traceback
            traceback.print_exc()
            return

        if info == 'true' and not control.condVisibility(
                'Window.IsVisible(infodialog)') and not control.condVisibility(
                    'Player.HasVideo'):
            control.notification(title='default',
                                 message=32553,
                                 icon='default',
                                 time=10000000,
                                 sound=notificationSound)
            self.infoDialog = True

        try:
            control.makeFile(control.dataPath)
            dbcon = database.connect(control.libcacheFile)
            dbcur = dbcon.cursor()
            dbcur.execute("CREATE TABLE IF NOT EXISTS tvshows ("
                          "id TEXT, "
                          "items TEXT, "
                          "UNIQUE(id)"
                          ");")
        except:
            import traceback
            traceback.print_exc()
            return

        try:
            from resources.lib.menus import episodes
        except:
            import traceback
            traceback.print_exc()
            return

        files_added = 0

        # __init__ doesn't get called from services so self.date never gets updated and new episodes are not added to the library
        self.datetime = (datetime.datetime.utcnow() -
                         datetime.timedelta(hours=5))

        if control.setting('library.importdelay') != 'true':
            self.date = self.datetime.strftime('%Y%m%d')
        else:
            self.date = (self.datetime -
                         datetime.timedelta(hours=24)).strftime('%Y%m%d')

        for item in items:
            it = None

            if xbmc.abortRequested is True:
                return sys.exit()

            try:
                dbcur.execute("SELECT * FROM tvshows WHERE id = '%s'" %
                              item['tvdb'])
                fetch = dbcur.fetchone()
                if fetch is not None:
                    it = eval(fetch[1].encode('utf-8'))
            except:
                import traceback
                traceback.print_exc()
                pass

            try:
                if it is not None:
                    raise Exception()

                it = episodes.Episodes().get(item['tvshowtitle'],
                                             item['year'],
                                             item['imdb'],
                                             item['tvdb'],
                                             idx=False)

                status = it[0]['status'].lower()

                it = [{
                    'title': i['title'],
                    'year': i['year'],
                    'imdb': i['imdb'],
                    'tvdb': i['tvdb'],
                    'season': i['season'],
                    'episode': i['episode'],
                    'tvshowtitle': i['tvshowtitle'],
                    'premiered': i['premiered']
                } for i in it]

                if status == 'continuing':
                    raise Exception()

                dbcur.execute("INSERT INTO tvshows Values (?, ?)",
                              (item['tvdb'], repr(it)))
                dbcur.connection.commit()
                dbcon.close()
            except:
                import traceback
                traceback.print_exc()
                pass

            try:
                id = [item['imdb'], item['tvdb']]

                if item['tmdb'] != '0':
                    id += [item['tmdb']]

                ep = [
                    x['title'].encode('utf-8') for x in lib
                    if str(x['imdbnumber']) in id or (
                        x['title'].encode('utf-8') == item['tvshowtitle']
                        and str(x['year']) == item['year'])
                ][0]
                ep = control.jsonrpc(
                    '{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": {"filter":{"and": [{"field": "tvshow", "operator": "is", "value": "%s"}]}, "properties": ["season", "episode"]}, "id": 1}'
                    % ep)
                ep = unicode(ep, 'utf-8', errors='ignore')
                ep = json.loads(ep).get('result', {}).get('episodes', {})
                ep = [{
                    'season': int(i['season']),
                    'episode': int(i['episode'])
                } for i in ep]
                ep = sorted(ep, key=lambda x: (x['season'], x['episode']))[-1]

                num = [
                    x for x, y in enumerate(it)
                    if str(y['season']) == str(ep['season'])
                    and str(y['episode']) == str(ep['episode'])
                ][-1]

                it = [y for x, y in enumerate(it) if x > num]

                if len(it) == 0:
                    continue
            except:
                import traceback
                traceback.print_exc()
                continue

            for i in it:
                try:
                    if xbmc.abortRequested is True:
                        return sys.exit()

                    premiered = i.get('premiered', '0')
                    if (premiered != '0'
                            and int(re.sub('[^0-9]', '', str(premiered))) >
                            int(self.date)) or (premiered == '0'
                                                and not self.include_unknown):
                        continue

                    libtvshows().strmFile(i)
                    files_added += 1
                except:
                    import traceback
                    traceback.print_exc()
                    pass

        if self.infoDialog is True:
            control.notification(title='default',
                                 message=32554,
                                 icon='default',
                                 time=1,
                                 sound=notificationSound)

        if self.library_setting == 'true' and not control.condVisibility(
                'Library.IsScanningVideo') and files_added > 0:
            control.execute('UpdateLibrary(video)')
Ejemplo n.º 11
0
    def add(self, tvshowtitle, year, imdb, tvdb, range=False):
        if not control.condVisibility('Window.IsVisible(infodialog)') and not control.condVisibility('Player.HasVideo')\
          and self.silentDialog is False:
            control.notification(title='default',
                                 message=32552,
                                 icon='default',
                                 time=10000000,
                                 sound=notificationSound)
            self.infoDialog = True

        from resources.lib.menus import episodes
        items = episodes.Episodes().get(tvshowtitle,
                                        year,
                                        imdb,
                                        tvdb,
                                        idx=False)
        try:
            items = [{
                'title': i['title'],
                'year': i['year'],
                'imdb': i['imdb'],
                'tvdb': i['tvdb'],
                'season': i['season'],
                'episode': i['episode'],
                'tvshowtitle': i['tvshowtitle'],
                'premiered': i['premiered']
            } for i in items]
        except:
            items = []

        try:
            if not self.dupe_setting == 'true': raise Exception()
            if items == []: raise Exception()
            id = [items[0]['imdb'], items[0]['tvdb']]
            lib = control.jsonrpc(
                '{"jsonrpc": "2.0", "method": "VideoLibrary.GetTVShows", "params": {"properties" : ["imdbnumber", "title", "year"]}, "id": 1}'
            )
            lib = unicode(lib, 'utf-8', errors='ignore')
            lib = json.loads(lib)['result']['tvshows']
            lib = [
                i['title'].encode('utf-8') for i in lib
                if str(i['imdbnumber']) in id or (
                    i['title'].encode('utf-8') == items[0]['tvshowtitle']
                    and str(i['year']) == items[0]['year'])
            ][0]
            lib = control.jsonrpc(
                '{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": {"filter":{"and": [{"field": "tvshow", "operator": "is", "value": "%s"}]}, "properties": ["season", "episode"]}, "id": 1}'
                % lib)
            lib = unicode(lib, 'utf-8', errors='ignore')
            lib = json.loads(lib)['result']['episodes']
            lib = [
                'S%02dE%02d' % (int(i['season']), int(i['episode']))
                for i in lib
            ]
            items = [
                i for i in items if not 'S%02dE%02d' %
                (int(i['season']), int(i['episode'])) in lib
            ]
        except:
            pass
        files_added = 0

        for i in items:
            try:
                if xbmc.abortRequested is True:
                    return sys.exit()
                if self.check_setting == 'true':
                    if i['episode'] == '1':
                        self.block = True
                        src = lib_tools.check_sources(i['title'], i['year'],
                                                      i['imdb'], i['tvdb'],
                                                      i['season'],
                                                      i['episode'],
                                                      i['tvshowtitle'],
                                                      i['premiered'])
                        if src:
                            self.block = False
                    if self.block is True:
                        raise Exception()

                premiered = i.get('premiered', '0')
                if (premiered != '0'
                        and int(re.sub('[^0-9]', '', str(premiered))) > int(
                            self.date)) or (premiered == '0'
                                            and not self.include_unknown):
                    continue
                self.strmFile(i)
                files_added += 1
            except:
                pass

        if range is True:
            return

        if self.infoDialog is True:
            control.notification(title='default',
                                 message=32554,
                                 icon='default',
                                 time=1,
                                 sound=notificationSound)

        if self.library_setting == 'true' and not control.condVisibility(
                'Library.IsScanningVideo') and files_added > 0:
            control.execute('UpdateLibrary(video)')
Ejemplo n.º 12
0
	def add(self, tvshowtitle, year, imdb, tvdb, range=False):
		contains = lib_tools.ckKodiSources()
		if general_notification:
			if not control.condVisibility('Window.IsVisible(infodialog)') and not control.condVisibility('Player.HasVideo'):
				control.notification(title = tvshowtitle, message = 32552, icon = 'default', time = 1000, sound =notificationSound )

		try:
			from resources.lib.menus import episodes
			items = episodes.Episodes().get(tvshowtitle, year, imdb, tvdb, idx=False)
		except:
			log_utils.error()
			return

		status = items[0]['status'].lower()

		try:
			items = [{'title': i['title'], 'year': i['year'], 'imdb': i['imdb'], 'tvdb': i['tvdb'], 'season': i['season'], 'episode': i['episode'], 'tvshowtitle': i['tvshowtitle'], 'premiered': i['premiered']} for i in items]
		except:
			items = []

		if items == []:
			return

		try:
			if self.dupe_chk != 'true':
				raise Exception()

			id = [items[0]['imdb'], items[0]['tvdb']]
			# lib = control.jsonrpc('{"jsonrpc": "2.0", "method": "VideoLibrary.GetTVShows", "params": {"properties" : ["imdbnumber", "title", "year"]}, "id": 1}')
			lib = control.jsonrpc('{"jsonrpc": "2.0", "method": "VideoLibrary.GetTVShows", "params": {"filter":{"or": [{"field": "year", "operator": "is", "value": "%s"}, {"field": "year", "operator": "is", "value": "%s"}, {"field": "year", "operator": "is", "value": "%s"}]}, "properties": ["imdbnumber", "title", "year"]}, "id": 1}' % (year, str(int(year)+1), str(int(year)-1)))
			lib = unicode(lib, 'utf-8', errors='ignore')
			lib = json.loads(lib)['result']['tvshows']
			lib = [i['title'].encode('utf-8') for i in lib if str(i['imdbnumber']) in id or (i['title'].encode('utf-8') == items[0]['tvshowtitle'] and str(i['year']) == items[0]['year'])][0]

			lib = control.jsonrpc('{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": {"filter":{"and": [{"field": "tvshow", "operator": "is", "value": "%s"}]}, "properties": ["season", "episode"]}, "id": 1}' % lib)
			lib = unicode(lib, 'utf-8', errors='ignore')
			lib = json.loads(lib)['result']['episodes']
			lib = ['S%02dE%02d' % (int(i['season']), int(i['episode'])) for i in lib]
			items = [i for i in items if not 'S%02dE%02d' % (int(i['season']), int(i['episode'])) in lib]
		except:
			lib = []
			pass

		files_added = 0
		for i in items:
			if lib != []:
				continue

			try:
				if xbmc.abortRequested is True:
					return sys.exit()

				if self.check_setting == 'true':
					if i['episode'] == '1':
						self.block = True
						src = lib_tools.check_sources(i['title'], i['year'], i['imdb'], i['tvdb'], i['season'], i['episode'], i['tvshowtitle'], i['premiered'])
						if src:
							self.block = False
					if self.block is True:
						continue

				# Show Season Special(Season0).
				if str(i.get('season')) == '0' and control.setting('tv.specials') == 'false':
					continue

				premiered = i.get('premiered', '0')

				# Show Unaired or Unknown items.
				if premiered == '0' and self.include_unknown == 'false':
					continue
				elif status == 'ended':
					pass
				elif int(re.sub('[^0-9]', '', str(premiered))) > int(re.sub('[^0-9]', '', str(self.date))):
					unaired = 'true'
					if self.showunaired != 'true':
						continue

				self.strmFile(i)
				files_added += 1
			except:
				log_utils.error()
				pass

		if files_added == 0:
			control.notification(title = tvshowtitle, message = 32652, icon = 'default', time = 1000, sound = notificationSound)

		if range is True:
			return files_added

		if self.library_update == 'true' and not control.condVisibility('Library.IsScanningVideo') and files_added > 0:
			if contains:
				if general_notification:
					control.notification(title = tvshowtitle, message = 32554, icon = 'default', time = 1000, sound = notificationSound)
				control.execute('UpdateLibrary(video)')
			elif general_notification:
				control.notification(title = tvshowtitle, message = 'strm file written but library cannot be updated', icon = 'default', time = 2000, sound = notificationSound)