示例#1
0
 def builder():
     for count, item in enumerate(self.results, 1):
         try:
             listitem = self.make_listitem()
             quality = item.get('quality', 'SD')
             quality_icon = self.get_quality_iconPath(quality)
             extra_info = item.get('info')
             size_label = str(round(item.get(
                 'size', ''), 2)) + ' GB' if item.get('size') else 'NA'
             listitem.setProperty('venom.source_dict', jsdumps([item]))
             listitem.setProperty('venom.debrid',
                                  self.debrid_abv(item.get('debrid')))
             listitem.setProperty('venom.provider',
                                  item.get('provider').upper())
             listitem.setProperty('venom.source',
                                  item.get('source').upper())
             listitem.setProperty('venom.seeders',
                                  str(item.get('seeders')))
             listitem.setProperty('venom.hash', item.get('hash', 'N/A'))
             listitem.setProperty('venom.name', item.get('name'))
             listitem.setProperty('venom.quality', quality.upper())
             listitem.setProperty('venom.quality_icon', quality_icon)
             listitem.setProperty('venom.url', item.get('url'))
             listitem.setProperty('venom.extra_info', extra_info)
             listitem.setProperty('venom.size_label', size_label)
             listitem.setProperty('venom.count', '%02d.)' % count)
             yield listitem
         except:
             from resources.lib.modules import log_utils
             log_utils.error()
	def user_cloud_to_listItem(self, folder_id=None):
		sysaddon = sys.argv[0]
		syshandle = int(sys.argv[1])
		folder_str, deleteMenu = control.lang(40046).upper(), control.lang(40050)
		cloud_dict = self.user_cloud()['magnets']
		cloud_dict = [i for i in cloud_dict if i['statusCode'] == 4]
		for count, item in enumerate(cloud_dict, 1):
			try:
				cm = []
				folder_name = control.strip_non_ascii_and_unprintable(item['filename'])
				id = item['id']
				status_str = '[COLOR %s]%s[/COLOR]' % (control.getColor(control.setting('highlight.color')), item['status'].capitalize())
				label = '%02d | [B]%s[/B] | [B]%s[/B] | [I]%s [/I]' % (count, status_str, folder_str, folder_name)
				url = '%s?action=ad_BrowseUserCloud&source=%s' % (sysaddon, quote_plus(jsdumps(item)))

				cm.append((deleteMenu % 'Transfer', 'RunPlugin(%s?action=ad_DeleteTransfer&id=%s&name=%s)' %
					(sysaddon, id, folder_name)))
				item = control.item(label=label)
				item.addContextMenuItems(cm)
				item.setArt({'icon': ad_icon, 'poster': ad_icon, 'thumb': ad_icon, 'fanart': addonFanart, 'banner': ad_icon})
				item.setInfo(type='video', infoLabels='')
				video_streaminfo = {'codec': 'h264'}
				item.addStreamInfo('video', video_streaminfo)
				control.addItem(handle=syshandle, url=url, listitem=item, isFolder=True)
			except:
				log_utils.error()
		control.content(syshandle, 'files')
		control.directory(syshandle, cacheToDisc=True)
示例#3
0
	def play_source(self, title, year, season, episode, imdb, tmdb, tvdb, url, meta, debridPackCall=False):
		try:
			from sys import argv # some functions like ActivateWindow() throw invalid handle less this is imported here.
			if not url: raise Exception
			self.media_type = 'movie' if season is None or episode is None else 'episode'
			self.title, self.year = title, str(year)
			if self.media_type == 'movie':
				self.name, self.season, self.episode = '%s (%s)' % (title, self.year), None, None
			elif self.media_type == 'episode':
				self.name, self.season, self.episode = '%s S%02dE%02d' % (title, int(season), int(episode)), '%01d' % int(season), '%01d' % int(episode)
			self.imdb, self.tmdb, self.tvdb = imdb or '', tmdb or '', tvdb or ''
			self.ids = {'imdb': self.imdb, 'tmdb': self.tmdb, 'tvdb': self.tvdb}
## - compare meta received to database and use largest(eventually switch to a request to fetch missing db meta for item)
			self.imdb_user = control.setting('imdb.user').replace('ur', '')
			self.tmdb_key = control.setting('tmdb.api.key')
			if not self.tmdb_key: self.tmdb_key = '3320855e65a9758297fec4f7c9717698'
			self.tvdb_key = control.setting('tvdb.api.key')
			if self.media_type == 'episode': self.user = str(self.imdb_user) + str(self.tvdb_key)
			else: self.user = str(self.tmdb_key)
			self.lang = control.apiLanguage()['tvdb']
			meta1 = dict((k, v) for k, v in iter(meta.items()) if v is not None and v != '') if meta else None
			meta2 = metacache.fetch([{'imdb': self.imdb, 'tmdb': self.tmdb, 'tvdb': self.tvdb}], self.lang, self.user)[0]
			if meta2 != self.ids: meta2 = dict((k, v) for k, v in iter(meta2.items()) if v is not None and v != '')
			if meta1 is not None:
				try:
					if len(meta2) > len(meta1):
						meta2.update(meta1)
						meta = meta2
					else: meta = meta1
				except: log_utils.error()
			else: meta = meta2 if meta2 != self.ids else meta1
##################
			self.poster = meta.get('poster') if meta else ''
			self.fanart = meta.get('fanart') if meta else ''
			self.meta = meta
			poster, thumb, season_poster, fanart, banner, clearart, clearlogo, discart, meta = self.getMeta(meta)
			self.offset = Bookmarks().get(name=self.name, imdb=imdb, tmdb=tmdb, tvdb=tvdb, season=season, episode=episode, year=self.year, runtime=meta.get('duration') if meta else 0)

			if self.offset == '-1':
				log_utils.log('User requested playback cancel', level=log_utils.LOGDEBUG)
				control.notification(message=32328)
				return control.cancelPlayback()

			item = control.item(path=url)
			item.setUniqueIDs(self.ids)
			if self.media_type == 'episode':
				item.setArt({'tvshow.clearart': clearart, 'tvshow.clearlogo': clearlogo, 'tvshow.discart': discart, 'thumb': thumb, 'tvshow.poster': season_poster, 'season.poster': season_poster, 'tvshow.fanart': fanart})
			else:
				item.setArt({'clearart': clearart, 'clearlogo': clearlogo, 'discart': discart, 'thumb': thumb, 'poster': poster, 'fanart': fanart})
			if 'castandart' in meta: item.setCast(meta.get('castandart', ''))
			item.setInfo(type='video', infoLabels=control.metadataClean(meta))
			item.setProperty('IsPlayable', 'true')
			if debridPackCall: control.player.play(url, item) # seems this is only way browseDebrid pack files will play and have meta marked as watched
			else: control.resolve(int(argv[1]), True, item)
			homeWindow.setProperty('script.trakt.ids', jsdumps(self.ids))
			self.keepAlive()
			homeWindow.clearProperty('script.trakt.ids')
		except:
			log_utils.error()
			return control.cancelPlayback()
示例#4
0
 def builder():
     for count, item in enumerate(self.results, 1):
         try:
             listitem = self.make_listitem()
             listitem.setProperty('venom.tvshowtitle',
                                  item.get('tvshowtitle'))
             listitem.setProperty('venom.year', str(item.get('year')))
             listitem.setProperty('venom.isHidden',
                                  str(item.get('isHidden')))
             listitem.setProperty('venom.isSelected',
                                  str(item.get('isHidden')))
             listitem.setProperty('venom.imdb', item.get('imdb'))
             listitem.setProperty('venom.tmdb', str(item.get('tmdb')))
             listitem.setProperty('venom.tvdb', str(item.get('tvdb')))
             listitem.setProperty('venom.status', item.get('status'))
             listitem.setProperty(
                 'venom.watched_count', '(watched ' +
                 str(item.get('watched_count').get('watched')) +
                 ' of ' + str(item.get('watched_count').get('total')) +
                 ')')
             listitem.setProperty(
                 'venom.rating', str(round(float(item.get('rating')),
                                           1)))
             listitem.setProperty('venom.trailer', item.get('trailer'))
             listitem.setProperty('venom.studio', item.get('studio'))
             listitem.setProperty('venom.genre', item.get('genre', ''))
             # listitem.setProperty('venom.duration', str(item.get('duration'))) # not used
             listitem.setProperty('venom.mpaa',
                                  item.get('mpaa') or 'NA')
             listitem.setProperty('venom.plot', item.get('plot'))
             poster = item.get('season_poster', '') or item.get(
                 'poster', '') or item.get('poster2', '') or item.get(
                     'poster3', '')
             fanart = item.get('fanart', '') or item.get(
                 'fanart2', '') or item.get('fanart3', '')
             clearlogo = item.get('clearlogo', '')
             clearart = item.get('clearart', '')
             art = {
                 'poster': poster,
                 'tvshow.poster': poster,
                 'fanart': fanart,
                 'icon': item.get('icon') or poster,
                 'thumb': item.get('thumb', ''),
                 'banner': item.get('banner2', ''),
                 'clearlogo': clearlogo,
                 'tvshow.clearlogo': clearlogo,
                 'clearart': clearart,
                 'tvshow.clearart': clearart,
                 'landscape': item.get('landscape', '')
             }
             listitem.setProperty('venom.poster', poster)
             listitem.setProperty('venom.clearlogo', clearlogo)
             listitem.setProperty('venom.art', jsdumps(art))
             listitem.setProperty('venom.count', '%02d.)' % count)
             yield listitem
         except:
             from resources.lib.modules import log_utils
             log_utils.error()
示例#5
0
	def _post_request(self, url, postData):
		postData = jsdumps(postData)
		url = self.baseUrl + url
		response = requests.post(url, data=postData, headers=self.headers).text
		if 'Not Authorized' in response:
			self.renewToken()
			self.headers['Authorization'] = 'Bearer %s' % self.jwToken
			response = requests.post(url, data=postData, headers=self.headers).text
		response = jsloads(response)
		return response
        def builder():
            for count, item in enumerate(self.uncached, 1):
                try:
                    listitem = self.make_listitem()
                    quality = item.get('quality', 'SD')
                    quality_icon = self.get_quality_iconPath(quality)
                    extra_info = item.get('info')
                    try:
                        size_label = extra_info.split('|', 1)[0]
                        if any(value in size_label
                               for value in ['HEVC', '3D']):
                            size_label = ''
                    except:
                        size_label = ''

                    try:
                        f = ' / '.join([
                            '%s' % info.strip()
                            for info in extra_info.split('|')
                        ])
                    except:
                        f = ''
                    if 'name_info' in item:
                        t = getFileType(name_info=item.get('name_info'))
                    else:
                        t = getFileType(url=item.get('url'))
                    t = '%s /%s' % (f, t) if (f != '' and f != '0 '
                                              and f != ' ') else t
                    if t == '': t = getFileType(url=item.get('url'))
                    extra_info = t

                    listitem.setProperty('venom.source_dict', jsdumps([item]))
                    listitem.setProperty('venom.debrid',
                                         self.debrid_abv(item.get('debrid')))
                    listitem.setProperty('venom.provider',
                                         item.get('provider').upper())
                    listitem.setProperty('venom.source',
                                         item.get('source').upper())
                    listitem.setProperty('venom.seeders',
                                         str(item.get('seeders')))
                    listitem.setProperty('venom.hash', item.get('hash', 'N/A'))
                    listitem.setProperty('venom.name', item.get('name'))
                    listitem.setProperty('venom.quality', quality.upper())
                    listitem.setProperty('venom.quality_icon', quality_icon)
                    listitem.setProperty('venom.url', item.get('url'))
                    listitem.setProperty('venom.extra_info', extra_info)
                    if size_label:
                        listitem.setProperty('venom.size_label', size_label)
                    else:
                        listitem.setProperty('venom.size_label', 'NA')
                    listitem.setProperty('venom.count', '%02d.)' % count)
                    yield listitem
                except:
                    from resources.lib.modules import log_utils
                    log_utils.error()
示例#7
0
 def builder():
     for count, item in enumerate(self.results, 1):
         try:
             listitem = self.make_listitem()
             listitem.setProperty('dg.title', item.get('title'))
             if item.get('tvshowtitle'):
                 listitem.setProperty('dg.media_type', 'show')
             else:
                 listitem.setProperty('dg.media_type', 'movie')
             listitem.setProperty('dg.year', str(item.get('year')))
             listitem.setProperty('dg.isSelected', '')
             listitem.setProperty('dg.imdb', item.get('imdb'))
             listitem.setProperty('dg.tmdb', item.get('tmdb'))
             listitem.setProperty('dg.tvdb', item.get('tvdb'))
             listitem.setProperty('dg.trakt', item.get('trakt'))
             listitem.setProperty('dg.status', item.get('status'))
             listitem.setProperty(
                 'dg.rating', str(round(float(item.get('rating')), 1)))
             listitem.setProperty('dg.trailer', item.get('trailer'))
             listitem.setProperty('dg.studio', item.get('studio'))
             listitem.setProperty('dg.genre', item.get('genre', ''))
             listitem.setProperty('dg.duration',
                                  str(item.get('duration')))
             listitem.setProperty('dg.mpaa', item.get('mpaa') or 'NA')
             listitem.setProperty('dg.plot', item.get('plot'))
             poster = item.get('season_poster', '') or item.get(
                 'poster', '') or item.get('poster2', '') or item.get(
                     'poster3', '')
             fanart = item.get('fanart', '') or item.get(
                 'fanart2', '') or item.get('fanart3', '')
             clearlogo = item.get('clearlogo', '')
             clearart = item.get('clearart', '')
             art = {
                 'poster': poster,
                 'tvshow.poster': poster,
                 'fanart': fanart,
                 'icon': item.get('icon') or poster,
                 'thumb': item.get('thumb', ''),
                 'banner': item.get('banner2', ''),
                 'clearlogo': clearlogo,
                 'tvshow.clearlogo': clearlogo,
                 'clearart': clearart,
                 'tvshow.clearart': clearart,
                 'landscape': item.get('landscape', '')
             }
             listitem.setProperty('dg.poster', poster)
             listitem.setProperty('dg.clearlogo', clearlogo)
             listitem.setProperty('dg.art', jsdumps(art))
             listitem.setProperty('dg.count', '%02d.)' % count)
             yield listitem
         except:
             from resources.lib.modules import log_utils
             log_utils.error()
示例#8
0
    async def botsuggest(self, ctx, *, suggestion: str = None):
        author = ctx.message.author

        def check(m):
            return m.author == author and m.channel == author.dm_channel

        if suggestion is None:
            await ctx.send("Please check your DMs")
            await author.send("What is your bot suggestion?")
            try:
                msg = await self.bot.wait_for('message', check=check, timeout=30)
                suggestion = msg.content
                dateSubmitted = msg.created_at.strftime("%m/%d/%Y, %H:%M:%S") + " GMT"
                submitUser = f"{author.name}#{author.discriminator} : {author.id}"

                submitData = {
                    "User": submitUser,
                    "Suggestion": suggestion,
                    "TimeSubmitted": dateSubmitted
                }
                response = post(
                    config['botSuggestHook'], data=jsdumps(submitData),
                    headers={'Content-Type': 'application/json'}
                )
                await author.send("Suggestion Submitted!")
            except asyncio.TimeoutError:
                await ctx.send("Timeout reached. Suggestion cancelled!")
        else:
            dateSubmitted = ctx.message.created_at.strftime("%m/%d/%Y, %H:%M:%S") + " GMT"
            submitUser = f"{author.name}#{author.discriminator} : {author.id}"
            submitData = {
                "User": submitUser,
                "Suggestion": suggestion,
                "TimeSubmitted": dateSubmitted
            }
            response = post(
                config['botSuggestHook'], data=jsdumps(submitData),
                headers={'Content-Type': 'application/json'}
            )
            await ctx.send("Suggestion Submitted!")
	def user_transfers_to_listItem(self):
		sysaddon = sys.argv[0]
		syshandle = int(sys.argv[1])
		transfer_files = self.user_cloud()['magnets']
		if not transfer_files:
			control.notification(message='Request Failure-Empty Content')
			return
		folder_str, deleteMenu, restartMenu = control.lang(40046).upper(), control.lang(40050), control.lang(40008)
		for count, item in enumerate(transfer_files, 1):
			try:
				status_code = item['statusCode'] 
				if status_code in (0,1, 2, 3):
					active = True
					downloaded = item['downloaded']
					size = item['size']
					try: percent = str(round(float(downloaded) / size * 100, 1))
					except: percent = '0'
				else:
					active = False
				folder_name = control.strip_non_ascii_and_unprintable(item['filename'])
				id = item['id']
				status_str = '[COLOR %s]%s[/COLOR]' % (control.getColor(control.setting('highlight.color')), item['status'].capitalize())
				if active:
					label = '%02d | [B]%s[/B] - %s | [B]%s[/B]' % (count, status_str, str(percent) + '%', folder_name)
				else:
					label = '%02d | [B]%s[/B] | [B]%s[/B] | [I]%s [/I]' % (count, status_str, folder_str, folder_name)
				if status_code == 4:
					url = '%s?action=ad_BrowseUserCloud&source=%s' % (sysaddon, quote_plus(jsdumps(item)))
					isFolder = True
				else:
					url = ''
					isFolder = False
				cm = []
				cm.append((deleteMenu % 'Transfer', 'RunPlugin(%s?action=ad_DeleteTransfer&id=%s&name=%s)' %
					(sysaddon, id, folder_name)))
				if status_code in (6, 7, 9, 10):
					cm.append((restartMenu, 'RunPlugin(%s?action=ad_RestartTransfer&id=%s&name=%s)' %
						(sysaddon, id, folder_name)))
				item = control.item(label=label)
				item.addContextMenuItems(cm)
				item.setArt({'icon': ad_icon, 'poster': ad_icon, 'thumb': ad_icon, 'fanart': addonFanart, 'banner': ad_icon})
				item.setInfo(type='video', infoLabels='')
				video_streaminfo = {'codec': 'h264'}
				item.addStreamInfo('video', video_streaminfo)
				control.addItem(handle=syshandle, url=url, listitem=item, isFolder=isFolder)
			except:
				log_utils.error()
		control.content(syshandle, 'files')
		control.directory(syshandle, cacheToDisc=True)
示例#10
0
	def newToken(self, ignore_lock=False):
		url = self.baseUrl + "login"
		postdata = {"apikey": self.apiKey}
		postdata = jsdumps(postdata)
		headers = self.headers
		if 'Authorization' in headers:
			headers.pop('Authorization')
		response = jsloads(requests.post(url, data=postdata, headers=self.headers).text)
		self.jwToken = response['token']
		# tools.tvdb_refresh = self.jwToken
		control.setSetting('tvdb.jw', self.jwToken)
		self.headers['Authorization'] = self.jwToken
		log_utils.log('Refreshed TVDB Token', level=log_utils.LOGDEBUG)
		control.setSetting('tvdb.expiry', str(time() + (24 * (60 * 60))))
		return response
示例#11
0
def make_settings_dict(): # service runs upon a setting change
	try:
		root = ET.parse(settingsFile).getroot()
		settings_dict = {}
		for item in root:
			dict_item = {}
			setting_id = item.get('id')
			if getKodiVersion() >= 18: setting_value = item.text
			else: setting_value = item.get('value')
			if setting_value is None: setting_value = ''
			dict_item = {setting_id: setting_value}
			settings_dict.update(dict_item)
		homeWindow.setProperty('fenomscrapers_settings', jsdumps(settings_dict))
		return settings_dict
	except:
		return None
示例#12
0
def make_settings_dict():  # service runs upon a setting change
    try:
        root = ET.parse(settingsFile).getroot()
        settings_dict = {}
        for item in root:
            dict_item = {}
            setting_id = item.get('id')
            setting_value = item.text
            if setting_value is None: setting_value = ''
            dict_item = {setting_id: setting_value}
            settings_dict.update(dict_item)
        homeWindow.setProperty('venom_settings', jsdumps(settings_dict))
        refresh_playAction()
        refresh_libPath()
        return settings_dict
    except:
        return None
示例#13
0
def make_settings_dict():
    try:
        root = ET.parse(settingsFile).getroot()
        settings_dict = {}
        for item in root:
            dict_item = {}
            setting_id = item.get('id')
            if getKodiVersion() >= 18: setting_value = item.text
            else: setting_value = item.get('value')
            if setting_value is None: setting_value = ''
            dict_item = {setting_id: setting_value}
            settings_dict.update(dict_item)
        homeWindow.setProperty('venom_settings', jsdumps(settings_dict))
        # xbmc.log('settings_dict = %s' % settings_dict, 2)
        return settings_dict
    except:
        return None
示例#14
0
def fetch_api(url, githubToken, **cus_headers):
    headers = {
        'user-agent': 'zzlzhang',
        'Content-Type': 'application/json',
        'Authorization': "token {0:s}".format(githubToken),
    }
    for key, value in cus_headers.get('headers', {}).items():
        headers[key] = value

    postData = cus_headers.get('data', {})

    method_to_call = getattr(requests, cus_headers.get('method', 'get'))
    response = requests.post(url, headers=headers, data=jsdumps(
        postData)) if postData else method_to_call(url, headers=headers)

    if not response.ok:
        response.raise_for_status()
    return response.text
示例#15
0
    def checkpoint(self, last_modified, features, tweets):
        '''
        Saves current data to checkpoint.
        '''
        now = datetime.now(timezone.utc)
        curfile = path.join(self.checkpoint_dir,
                            '{}.json.gz'.format(now.strftime('%Y%m')))
        logging.debug('checkpointing buffer')
        mon_beg = int(datetime(now.year, now.month, 1).timestamp() * 1000)

        outobj = {'metadata' : { 'Last-Modified' : last_modified },\
                  'features' : list(clean_features(mon_beg,features)),\
                  'tweets'   : list(clean_tweets(mon_beg,tweets)) }
        with GzipFile(curfile, 'w') as fout:
            fout.write(jsdumps(outobj).encode('utf-8'))
        outobj = None

        min_time = int((now - self.buffer_tdelta).timestamp() * 1000)
        return last_modified, list(clean_features(min_time, features)), list(
            clean_tweets(min_time, tweets))
def injectMap(value, map_id=None, input_id=None, input_name=None,
    input_class='json', widget='initPointMap', edit_mode=False, **kwargs):
    """ Returns map tag elements I need """

    if None in (map_id, input_id, ):
        UUID = getUUID()
        if map_id is None:
            map_id = "map_%s" % UUID
        if input_id is None:
            input_id = "feature_source_%s" % UUID

    ValueTag = INPUT(
        _id = input_id,
        _name = input_name or "feature_source",
        _value = value,
        _class = input_class,
        _type = "hidden",
    )
    params = dict(_style = "width: 350px", _class = "smallmap")
    for k,v in kwargs.items():
        if k.startswith('_'):
            params[k] = v
    #params.update(dict([('_%s' % k, v) for k,v in kwargs.items()]))
    MapTag = DIV(_id = map_id, **params)

    ollib = SCRIPT(_src=URL(plugin_root, 'openlayers/lib/OpenLayers.js'))
    mylib = SCRIPT(_src=URL(plugin_root, 'widgets.js'))
    elements = dict(
        widgetname = widget,
        map_options = jsdumps(dict(div=map_id)),
        myinput = input_id,
        viewmode = 'false' if edit_mode else 'true'
    )
    callmapscript = SCRIPT(
        'jQuery( document ).ready( %(widgetname)s("%(myinput)s", %(map_options)s, %(viewmode)s) )' % elements,
        _type = "text/javascript",
    )
    return SPAN(ValueTag, MapTag, ollib, mylib, callmapscript)
示例#17
0
def getTrakt(url, post=None, extended=False):
    try:
        if not url.startswith(BASE_URL): url = urljoin(BASE_URL, url)
        if post: post = jsdumps(post)
        if not getTraktCredentialsInfo():
            result = client.request(url, post=post, headers=headers)
            return result

        headers['Authorization'] = 'Bearer %s' % control.setting('trakt.token')
        result = client.request(url,
                                post=post,
                                headers=headers,
                                output='extended',
                                error=True)
        # result = utils.byteify(result) # check if this is needed because client "as_bytes" should handle this
        try:
            code = str(
                result[1])  # result[1] is already a str from client module
        except:
            code = ''

        if code.startswith('5') or (
                result and isinstance(result, py_tools.string_types)
                and '<html' in result
        ) or not result:  # covers Maintenance html responses ["Bad Gateway", "We're sorry, but something went wrong (500)"])
            log_utils.log('Temporary Trakt Server Problems',
                          level=log_utils.LOGNOTICE)
            control.notification(title=32315, message=33676)
            return None
        elif result and code in ['423']:
            log_utils.log('Locked User Account - Contact Trakt Support: %s' %
                          str(result[0]),
                          level=log_utils.LOGWARNING)
            control.notification(title=32315, message=33675)
            return None
        elif result and code in ['404']:
            log_utils.log('Request Not Found: url=(%s): %s' %
                          (url, str(result[0])),
                          level=log_utils.LOGDEBUG)
            return None
        elif result and code in ['429']:
            if 'Retry-After' in result[2]:
                # API REQUESTS ARE BEING THROTTLED, INTRODUCE WAIT TIME (1000 calls every 5 minutes, doubt we'll ever hit that)
                throttleTime = result[2]['Retry-After']
                control.notification(
                    title=32315,
                    message='Trakt Throttling Applied, Sleeping for %s seconds'
                    % throttleTime)  # message ang code 33674
                control.sleep((int(throttleTime) + 1) * 1000)
                return getTrakt(url, post=post, extended=extended)
        elif result and code in ['401']:  # Re-Auth token
            log_utils.log('Re-Authenticating Trakt Token',
                          level=log_utils.LOGDEBUG)
            success = re_auth(headers)
            if success: return getTrakt(url, post=post, extended=extended)
        if result and code not in ['401', '405']:
            if extended: return result[0], result[2]
            else: return result[0]
    except:
        log_utils.error('getTrakt Error: ')
    return None
示例#18
0
def send(subject, message):
    if not type(message) is str: message = jsdumps(message)
    subject, message = map(b64enc, (subject, message))
    return bitmessage.sendMessage(toaddress, fromaddress, subject, message)
示例#19
0
 def onAction(self, action):
     try:
         action_id = action.getId(
         )  # change to just "action" as the ID is already returned in that.
         if action_id in self.info_actions:
             chosen_source = self.item_list[self.get_position(
                 self.window_id)]
             chosen_source = chosen_source.getProperty('venom.source_dict')
             syssource = quote_plus(chosen_source)
             self.execute_code(
                 'RunPlugin(plugin://plugin.video.venom/?action=sourceInfo&source=%s)'
                 % syssource)
         if action_id in self.selection_actions:
             focus_id = self.getFocusId()
             if focus_id == 2001:
                 return self.load_uncachedTorrents()
             chosen_source = self.item_list[self.get_position(
                 self.window_id)]
             source = chosen_source.getProperty('venom.source')
             if 'UNCACHED' in source:
                 debrid = chosen_source.getProperty('venom.debrid')
                 source_dict = chosen_source.getProperty(
                     'venom.source_dict')
                 link_type = 'pack' if 'package' in source_dict else 'single'
                 sysname = quote_plus(self.meta.get('title'))
                 if 'tvshowtitle' in self.meta and 'season' in self.meta and 'episode' in self.meta:
                     poster = self.meta.get(
                         'season_poster') or self.meta.get('poster')
                     sysname += quote_plus(' S%02dE%02d' % (int(
                         self.meta['season']), int(self.meta['episode'])))
                 elif 'year' in self.meta:
                     sysname += quote_plus(' (%s)' % self.meta['year'])
                 try:
                     new_sysname = quote_plus(
                         chosen_source.getProperty('venom.name'))
                 except:
                     new_sysname = sysname
                 self.execute_code(
                     'RunPlugin(plugin://plugin.video.venom/?action=cacheTorrent&caller=%s&type=%s&title=%s&items=%s&url=%s&source=%s&meta=%s)'
                     % (debrid, link_type, sysname,
                        quote_plus(jsdumps(self.results)),
                        quote_plus(chosen_source.getProperty('venom.url')),
                        quote_plus(source_dict),
                        quote_plus(jsdumps(self.meta))))
                 self.selected = (None, '')
             else:
                 self.selected = ('play_Item', chosen_source)
             return self.close()
         elif action_id in self.context_actions:
             from re import match as re_match
             chosen_source = self.item_list[self.get_position(
                 self.window_id)]
             source_dict = chosen_source.getProperty('venom.source_dict')
             cm_list = [('[B]Additional Link Info[/B]', 'sourceInfo')]
             if 'cached (pack)' in source_dict:
                 cm_list += [('[B]Browse Debrid Pack[/B]', 'showDebridPack')
                             ]
             source = chosen_source.getProperty('venom.source')
             if not 'UNCACHED' in source and self.dnlds_enabled:
                 cm_list += [('[B]Download[/B]', 'download')]
             if re_match(r'^CACHED.*TORRENT', source):
                 debrid = chosen_source.getProperty('venom.debrid')
                 cm_list += [('[B]Save to %s Cloud[/B]' % debrid,
                              'saveToCloud')]
             chosen_cm_item = dialog.contextmenu([i[0] for i in cm_list])
             if chosen_cm_item == -1: return
             cm_action = cm_list[chosen_cm_item][1]
             if cm_action == 'sourceInfo':
                 self.execute_code(
                     'RunPlugin(plugin://plugin.video.venom/?action=sourceInfo&source=%s)'
                     % quote_plus(source_dict))
             elif cm_action == 'showDebridPack':
                 debrid = chosen_source.getProperty('venom.debrid')
                 name = chosen_source.getProperty('venom.name')
                 hash = chosen_source.getProperty('venom.hash')
                 self.execute_code(
                     'RunPlugin(plugin://plugin.video.venom/?action=showDebridPack&caller=%s&name=%s&url=%s&source=%s)'
                     % (quote_plus(debrid), quote_plus(name),
                        quote_plus(chosen_source.getProperty('venom.url')),
                        quote_plus(hash)))
                 self.selected = (None, '')
             elif cm_action == 'download':
                 sysname = quote_plus(self.meta.get('title'))
                 poster = self.meta.get('poster', '')
                 if 'tvshowtitle' in self.meta and 'season' in self.meta and 'episode' in self.meta:
                     sysname = quote_plus(self.meta.get('tvshowtitle'))
                     poster = self.meta.get(
                         'season_poster') or self.meta.get('poster')
                     sysname += quote_plus(' S%02dE%02d' % (int(
                         self.meta['season']), int(self.meta['episode'])))
                 elif 'year' in self.meta:
                     sysname += quote_plus(' (%s)' % self.meta['year'])
                 try:
                     new_sysname = quote_plus(
                         chosen_source.getProperty('venom.name'))
                 except:
                     new_sysname = sysname
                 self.execute_code(
                     'RunPlugin(plugin://plugin.video.venom/?action=download&name=%s&image=%s&source=%s&caller=sources&title=%s)'
                     % (new_sysname, quote_plus(poster),
                        quote_plus(source_dict), sysname))
                 self.selected = (None, '')
             elif cm_action == 'saveToCloud':
                 magnet = chosen_source.getProperty('venom.url')
                 if debrid == 'AD':
                     from resources.lib.debrid import alldebrid
                     transfer_function = alldebrid.AllDebrid
                     debrid_icon = alldebrid.ad_icon
                 elif debrid == 'PM':
                     from resources.lib.debrid import premiumize
                     transfer_function = premiumize.Premiumize
                     debrid_icon = premiumize.pm_icon
                 elif debrid == 'RD':
                     from resources.lib.debrid import realdebrid
                     transfer_function = realdebrid.RealDebrid
                     debrid_icon = realdebrid.rd_icon
                 result = transfer_function().create_transfer(magnet)
                 if result:
                     notification(message='Sending MAGNET to the %s cloud' %
                                  debrid,
                                  icon=debrid_icon)
         elif action in self.closing_actions:
             self.selected = (None, '')
             self.close()
     except:
         from resources.lib.modules import log_utils
         log_utils.error()
示例#20
0
def re_auth(headers):
    try:
        oauth = urljoin(BASE_URL, '/oauth/token')
        opost = {
            'client_id': V2_API_KEY,
            'client_secret': CLIENT_SECRET,
            'redirect_uri': REDIRECT_URI,
            'grant_type': 'refresh_token',
            'refresh_token': control.setting('trakt.refresh')
        }
        result = client.request(oauth,
                                post=jsdumps(opost),
                                headers=headers,
                                error=True)
        # result = utils.byteify(result) # check if this is needed because client "as_bytes" should handle this
        try:
            code = str(result[1])
        except:
            code = ''

        if code.startswith('5') or (
                result and isinstance(result, py_tools.string_types)
                and '<html' in result
        ) or not result:  # covers Maintenance html responses ["Bad Gateway", "We're sorry, but something went wrong (500)"])
            log_utils.log('Temporary Trakt Server Problems',
                          level=log_utils.LOGNOTICE)
            control.notification(title=32315, message=33676)
            return False
        elif result and code in ['423']:
            log_utils.log('Locked User Account - Contact Trakt Support: %s' %
                          str(result[0]),
                          level=log_utils.LOGWARNING)
            control.notification(title=32315, message=33675)
            return False

        if result and code not in ['401', '405']:
            try:
                result = jsloads(
                    result
                )  # result = utils.json_loads_as_str(result) # which json method here?
            except:
                log_utils.error()
                return False
            if 'error' in result and result['error'] == 'invalid_grant':
                log_utils.log('Please Re-Authorize your Trakt Account: %s' %
                              result['error'],
                              __name__,
                              level=log_utils.LOGERROR)
                control.notification(title=32315, message=33677)
                return False

            token, refresh = result['access_token'], result['refresh_token']
            control.setSetting(id='trakt.token', value=token)
            control.setSetting(id='trakt.refresh', value=refresh)

            control.addon('script.module.myaccounts').setSetting(
                'trakt.token', token)
            control.addon('script.module.myaccounts').setSetting(
                'trakt.refresh', refresh)
            log_utils.log('Trakt Token Successfully Re-Authorized',
                          level=log_utils.LOGDEBUG)
            return True
        else:
            log_utils.log('Error while Re-Authorizing Trakt Token: %s' %
                          str(result[0]),
                          level=log_utils.LOGDEBUG)
            return False
    except:
        log_utils.error()
示例#21
0
	def tvshowDirectory(self, items, next=True):
		control.playlist.clear()
		if not items: # with reuselanguageinvoker on an empty directory must be loaded, do not use sys.exit()
			control.hide() ; control.notification(title=32002, message=33049)
		sysaddon, syshandle = argv[0], int(argv[1])
		is_widget = 'plugin' not in control.infoLabel('Container.PluginName')
		settingFanart = control.setting('fanart') == 'true'
		addonPoster, addonFanart, addonBanner = control.addonPoster(), control.addonFanart(), control.addonBanner()
		indicators = getTVShowIndicators(refresh=True)
		unwatchedEnabled = control.setting('tvshows.unwatched.enabled') == 'true'
		flatten = control.setting('flatten.tvshows') == 'true'
		if trakt.getTraktIndicatorsInfo():
			watchedMenu, unwatchedMenu = control.lang(32068), control.lang(32069)
		else:
			watchedMenu, unwatchedMenu = control.lang(32066), control.lang(32067)
		traktManagerMenu, queueMenu = control.lang(32070), control.lang(32065)
		showPlaylistMenu, clearPlaylistMenu = control.lang(35517), control.lang(35516)
		playRandom, addToLibrary = control.lang(32535), control.lang(32551)
		nextMenu = control.lang(32053)
		for i in items:
			try:
				imdb, tmdb, tvdb, year, trailer = i.get('imdb', ''), i.get('tmdb', ''), i.get('tvdb', ''), i.get('year', ''), i.get('trailer', '')
				title = i.get('tvshowtitle') or i.get('title')
				systitle = quote_plus(title)
				meta = dict((k, v) for k, v in iter(i.items()) if v is not None and v != '')
				meta.update({'code': imdb, 'imdbnumber': imdb, 'mediatype': 'tvshow', 'tag': [imdb, tmdb]}) # "tag" and "tagline" for movies only, but works in my skin mod so leave
				if unwatchedEnabled: trakt.seasonCount(imdb) # pre-cache season counts for the listed shows
				try: meta.update({'genre': cleangenre.lang(meta['genre'], self.lang)})
				except: pass
				try:
					if 'tvshowtitle' not in meta: meta.update({'tvshowtitle': title})
				except: pass
				poster = meta.get('poster3') or meta.get('poster2') or meta.get('poster') or addonPoster
				landscape = meta.get('landscape')
				fanart = ''
				if settingFanart: fanart = meta.get('fanart3') or meta.get('fanart2') or meta.get('fanart') or landscape or addonFanart
				thumb = meta.get('thumb') or poster or landscape
				icon = meta.get('icon') or poster
				banner = meta.get('banner3') or meta.get('banner2') or meta.get('banner') or addonBanner
				art = {}
				art.update({'poster': poster, 'tvshow.poster': poster, 'fanart': fanart, 'icon': icon, 'thumb': thumb, 'banner': banner, 'clearlogo': meta.get('clearlogo', ''),
						'tvshow.clearlogo': meta.get('clearlogo', ''), 'clearart': meta.get('clearart', ''), 'tvshow.clearart': meta.get('clearart', ''), 'landscape': landscape})
				for k in ('poster2', 'poster3', 'fanart2', 'fanart3', 'banner2', 'banner3', 'trailer'): meta.pop(k, None)
				meta.update({'poster': poster, 'fanart': fanart, 'banner': banner, 'thumb': thumb, 'icon': icon})
####-Context Menu and Overlays-####
				cm = []
				try:
					overlay = int(getTVShowOverlay(indicators, imdb, tvdb))
					watched = (overlay == 5)
					if self.traktCredentials:
						cm.append((traktManagerMenu, 'RunPlugin(%s?action=tools_traktManager&name=%s&imdb=%s&tvdb=%s&watched=%s)' % (sysaddon, systitle, imdb, tvdb, watched)))
					if watched:
						meta.update({'playcount': 1, 'overlay': 5})
						cm.append((unwatchedMenu, 'RunPlugin(%s?action=playcount_TVShow&name=%s&imdb=%s&tvdb=%s&query=4)' % (sysaddon, systitle, imdb, tvdb)))
					else:
						meta.update({'playcount': 0, 'overlay': 4})
						cm.append((watchedMenu, 'RunPlugin(%s?action=playcount_TVShow&name=%s&imdb=%s&tvdb=%s&query=5)' % (sysaddon, systitle, imdb, tvdb)))
				except: pass
				sysmeta, sysart = quote_plus(jsdumps(meta)), quote_plus(jsdumps(art))
				cm.append(('Find similar', 'ActivateWindow(10025,%s?action=tvshows&url=https://api.trakt.tv/shows/%s/related,return)' % (sysaddon, imdb)))
				cm.append((playRandom, 'RunPlugin(%s?action=play_Random&rtype=season&tvshowtitle=%s&year=%s&imdb=%s&tmdb=%s&tvdb=%s&art=%s)' % (sysaddon, systitle, year, imdb, tmdb, tvdb, sysart)))
				cm.append((queueMenu, 'RunPlugin(%s?action=playlist_QueueItem&name=%s)' % (sysaddon, systitle)))
				cm.append((showPlaylistMenu, 'RunPlugin(%s?action=playlist_Show)' % sysaddon))
				cm.append((clearPlaylistMenu, 'RunPlugin(%s?action=playlist_Clear)' % sysaddon))
				cm.append((addToLibrary, 'RunPlugin(%s?action=library_tvshowToLibrary&tvshowtitle=%s&year=%s&imdb=%s&tmdb=%s&tvdb=%s)' % (sysaddon, systitle, year, imdb, tmdb, tvdb)))
				cm.append(('[COLOR red]Venom Settings[/COLOR]', 'RunPlugin(%s?action=tools_openSettings)' % sysaddon))
####################################
				if flatten: url = '%s?action=episodes&tvshowtitle=%s&year=%s&imdb=%s&tmdb=%s&tvdb=%s&meta=%s' % (sysaddon, systitle, year, imdb, tmdb, tvdb, sysmeta)
				else: url = '%s?action=seasons&tvshowtitle=%s&year=%s&imdb=%s&tmdb=%s&tvdb=%s&art=%s' % (sysaddon, systitle, year, imdb, tmdb, tvdb, sysart)
				if trailer: meta.update({'trailer': trailer})
				else: meta.update({'trailer': '%s?action=play_Trailer&type=%s&name=%s&year=%s&imdb=%s' % (sysaddon, 'show', systitle, year, imdb)})
				item = control.item(label=title, offscreen=True)
				if 'castandart' in i: item.setCast(i['castandart'])
				item.setArt(art)
				if unwatchedEnabled:
					try: 
						count = getShowCount(indicators, imdb, tvdb) # this is threaded without .join() so not all results are immediately seen
						if count:
							item.setProperties({'WatchedEpisodes': str(count['watched']), 'UnWatchedEpisodes': str(count['unwatched'])})
							item.setProperties({'TotalSeasons': str(meta.get('total_seasons', '')), 'TotalEpisodes': str(count['total'])})
						else:
							item.setProperties({'WatchedEpisodes': '0', 'UnWatchedEpisodes': str(meta.get('total_aired_episodes', ''))}) # temp use TMDb's "total_aired_episodes" for threads not finished....next load counts will update with trakt data
							item.setProperties({'TotalSeasons': str(meta.get('total_seasons', '')), 'TotalEpisodes': str(meta.get('total_aired_episodes', ''))})
					except: pass
				item.setProperty('IsPlayable', 'false')
				item.setProperty('tmdb_id', str(tmdb))
				if is_widget: item.setProperty('isVenom_widget', 'true')
				item.setUniqueIDs({'imdb': imdb, 'tmdb': tmdb, 'tvdb': tvdb})
				item.setInfo(type='video', infoLabels=control.metadataClean(meta))
				item.addContextMenuItems(cm)
				control.addItem(handle=syshandle, url=url, listitem=item, isFolder=True)
			except:
				from resources.lib.modules import log_utils
				log_utils.error()
		if next:
			try:
				if not items: raise Exception()
				url = items[0]['next']
				if not url: raise Exception()
				url_params = dict(parse_qsl(urlsplit(url).query))
				if 'imdb.com' in url and 'start' in url_params:
					page = '  [I](%s)[/I]' % str(int(((int(url_params.get('start')) - 1) / int(self.page_limit)) + 1))
				else: page = '  [I](%s)[/I]' % url_params.get('page')
				nextMenu = '[COLOR skyblue]' + nextMenu + page + '[/COLOR]'
				u = urlparse(url).netloc.lower()
				if u in self.imdb_link or u in self.trakt_link:
					url = '%s?action=tvshowPage&url=%s' % (sysaddon, quote_plus(url))
				elif u in self.tmdb_link:
					url = '%s?action=tmdbTvshowPage&url=%s' % (sysaddon, quote_plus(url))
				elif u in self.tvmaze_link:
					url = '%s?action=tvmazeTvshowPage&url=%s' % (sysaddon, quote_plus(url))
				item = control.item(label=nextMenu, offscreen=True)
				icon = control.addonNext()
				item.setProperty('IsPlayable', 'false')
				item.setArt({'icon': icon, 'thumb': icon, 'poster': icon, 'banner': icon})
				item.setProperty ('SpecialSort', 'bottom')
				control.addItem(handle=syshandle, url=url, listitem=item, isFolder=True)
			except:
				from resources.lib.modules import log_utils
				log_utils.error()
		control.content(syshandle, 'tvshows')
		control.directory(syshandle, cacheToDisc=True)
		# control.sleep(500)
		views.setView('tvshows', {'skin.estuary': 55, 'skin.confluence': 500})
 def builder():
     for count, item in enumerate(self.results, 1):
         try:
             listitem = self.make_listitem()
             tvshowtitle = item.get('tvshowtitle')
             listitem.setProperty('venom.tvshowtitle', tvshowtitle)
             listitem.setProperty('venom.year', str(item.get('year')))
             zoneTo, formatInput = 'utc', '%Y-%m-%d'
             if 'T' in str(item.get('premiered', '')):
                 zoneTo, formatInput = 'local', '%Y-%m-%dT%H:%M:%S.000Z'
             new_date = tools.convert_time(stringTime=str(
                 item.get('premiered', '')),
                                           formatInput=formatInput,
                                           formatOutput='%m-%d-%Y',
                                           zoneFrom='utc',
                                           zoneTo=zoneTo)
             listitem.setProperty('venom.premiered', new_date)
             season = str(item.get('season'))
             listitem.setProperty('venom.season', season)
             episode = str(item.get('episode'))
             listitem.setProperty('venom.episode', episode)
             label = '%s  -  %sx%s' % (tvshowtitle, season,
                                       episode.zfill(2))
             listitem.setProperty('venom.label', label)
             labelProgress = str(round(float(item['progress']),
                                       1)) + '%'
             listitem.setProperty('venom.progress',
                                  '[' + labelProgress + ']')
             listitem.setProperty('venom.isSelected', '')
             listitem.setProperty('venom.imdb', item.get('imdb'))
             listitem.setProperty('venom.tvdb', item.get('tvdb'))
             listitem.setProperty(
                 'venom.rating', str(round(float(item.get('rating')),
                                           1)))
             listitem.setProperty('venom.trailer', item.get('trailer'))
             listitem.setProperty('venom.studio', item.get('studio'))
             listitem.setProperty('venom.genre',
                                  str(item.get('genre', '')))
             listitem.setProperty('venom.duration',
                                  str(item.get('duration')))
             listitem.setProperty('venom.mpaa',
                                  item.get('mpaa') or 'NA')
             listitem.setProperty('venom.plot', item.get('plot'))
             poster = item.get('season_poster', '') or item.get(
                 'poster', '') or item.get('poster2', '') or item.get(
                     'poster3', '')
             fanart = item.get('fanart', '') or item.get(
                 'fanart2', '') or item.get('fanart3', '')
             clearlogo = item.get('clearlogo', '')
             clearart = item.get('clearart', '')
             art = {
                 'poster': poster,
                 'tvshow.poster': poster,
                 'fanart': fanart,
                 'icon': item.get('icon') or poster,
                 'thumb': item.get('thumb', ''),
                 'banner': item.get('banner2', ''),
                 'clearlogo': clearlogo,
                 'tvshow.clearlogo': clearlogo,
                 'clearart': clearart,
                 'tvshow.clearart': clearart,
                 'landscape': item.get('landscape', '')
             }
             listitem.setProperty('venom.poster', poster)
             listitem.setProperty('venom.clearlogo', clearlogo)
             listitem.setProperty('venom.art', jsdumps(art))
             listitem.setProperty('venom.count', '%02d.)' % count)
             yield listitem
         except:
             from resources.lib.modules import log_utils
             log_utils.error()
    def onAction(self, action):
        try:
            action_id = action.getId(
            )  # change to just "action" as the ID is already returned in that.
            if action_id in self.info_actions:
                chosen_source = self.item_list[self.get_position(
                    self.window_id)]
                chosen_source = chosen_source.getProperty('venom.source_dict')
                syssource = quote_plus(chosen_source)
                self.execute_code(
                    'RunPlugin(plugin://plugin.video.venom/?action=sourceInfo&source=%s)'
                    % syssource)
            if action_id in self.selection_actions:
                chosen_source = self.item_list[self.get_position(
                    self.window_id)]
                source = chosen_source.getProperty('venom.source')
                if 'UNCACHED' in source:
                    debrid = chosen_source.getProperty('venom.debrid')
                    source_dict = chosen_source.getProperty(
                        'venom.source_dict')
                    link_type = 'pack' if 'package' in source_dict else 'single'
                    sysname = quote_plus(self.meta.get('title'))
                    if 'tvshowtitle' in self.meta and 'season' in self.meta and 'episode' in self.meta:
                        poster = self.meta.get(
                            'season_poster') or self.meta.get('poster')
                        sysname += quote_plus(' S%02dE%02d' % (int(
                            self.meta['season']), int(self.meta['episode'])))
                    elif 'year' in self.meta:
                        sysname += quote_plus(' (%s)' % self.meta['year'])
                    try:
                        new_sysname = quote_plus(
                            chosen_source.getProperty('venom.name'))
                    except:
                        new_sysname = sysname
                    self.execute_code(
                        'RunPlugin(plugin://plugin.video.venom/?action=cacheTorrent&caller=%s&type=%s&title=%s&items=%s&url=%s&source=%s&meta=%s)'
                        % (debrid, link_type, sysname,
                           quote_plus(jsdumps(self.uncached)),
                           quote_plus(chosen_source.getProperty('venom.url')),
                           quote_plus(source_dict),
                           quote_plus(jsdumps(self.meta))))
                    self.selected = (None, '')
                else:
                    self.selected = (None, '')
                return self.close()
            elif action_id in self.context_actions:
                chosen_source = self.item_list[self.get_position(
                    self.window_id)]
                source_dict = chosen_source.getProperty('venom.source_dict')
                cm_list = [('[B]Additional Link Info[/B]', 'sourceInfo')]

                source = chosen_source.getProperty('venom.source')
                if 'UNCACHED' in source:
                    debrid = chosen_source.getProperty('venom.debrid')
                    seeders = chosen_source.getProperty('venom.seeders')
                    cm_list += [('[B]Cache to %s Cloud (seeders=%s)[/B]' %
                                 (debrid, seeders), 'cacheToCloud')]

                chosen_cm_item = dialog.contextmenu([i[0] for i in cm_list])
                if chosen_cm_item == -1: return
                cm_action = cm_list[chosen_cm_item][1]

                if cm_action == 'sourceInfo':
                    self.execute_code(
                        'RunPlugin(plugin://plugin.video.venom/?action=sourceInfo&source=%s)'
                        % quote_plus(source_dict))

                if cm_action == 'cacheToCloud':
                    debrid = chosen_source.getProperty('venom.debrid')
                    source_dict = chosen_source.getProperty(
                        'venom.source_dict')
                    link_type = 'pack' if 'package' in source_dict else 'single'
                    sysname = quote_plus(self.meta.get('title'))
                    if 'tvshowtitle' in self.meta and 'season' in self.meta and 'episode' in self.meta:
                        poster = self.meta.get(
                            'season_poster') or self.meta.get('poster')
                        sysname += quote_plus(' S%02dE%02d' % (int(
                            self.meta['season']), int(self.meta['episode'])))
                    elif 'year' in self.meta:
                        sysname += quote_plus(' (%s)' % self.meta['year'])
                    try:
                        new_sysname = quote_plus(
                            chosen_source.getProperty('venom.name'))
                    except:
                        new_sysname = sysname
                    self.execute_code(
                        'RunPlugin(plugin://plugin.video.venom/?action=cacheTorrent&caller=%s&type=%s&title=%s&items=%s&url=%s&source=%s&meta=%s)'
                        % (debrid, link_type, sysname,
                           quote_plus(jsdumps(self.uncached)),
                           quote_plus(chosen_source.getProperty('venom.url')),
                           quote_plus(source_dict),
                           quote_plus(jsdumps(self.meta))))
            elif action in self.closing_actions:
                self.selected = (None, '')
                self.close()
        except:
            from resources.lib.modules import log_utils
            log_utils.error()
示例#24
0
                            # --key=value
                            k = i[2:r]
                            v = i[r + 1:]
                            config[k] = v
                        else:
                            # --key
                            k = i[2:]
                            config[k] = True
                    # -kv
                    elif i[1] != '-':
                        k = i[1]
                        v = i[2:]
                        config[k] = v
            else:
                # list
                li.append(i)
        except StopIteration:
            if li:
                if config:
                    return [config, li]
                return li
            if config:
                return config
        except ValueError:
            ('argv format error')
            exit(1)


from json import dumps as jsdumps
print(jsdumps(argvParse(), indent=1))
示例#25
0
def getTrakt(url,
             post=None,
             cache=True,
             check=False,
             timestamp=None,
             extended=False,
             direct=False,
             authentication=None):
    try:
        if not url.startswith(BASE_URL):
            url = urljoin(BASE_URL, url)

        if authentication:
            valid = True
            token = authentication['token']
            refresh = authentication['refresh']
        else:
            valid = getTraktCredentialsInfo()
            token = control.setting('trakt.token')
            refresh = control.setting('trakt.refresh')

        headers = {
            'Content-Type': 'application/json',
            'trakt-api-key': V2_API_KEY,
            'trakt-api-version': '2'
        }
        if post: post = jsdumps(post)
        if direct or not valid:
            result = client.request(url, post=post, headers=headers)
            return result

        headers['Authorization'] = 'Bearer %s' % token
        result = client.request(url,
                                post=post,
                                headers=headers,
                                output='extended',
                                error=True)
        if result and not (result[1] == '401' or result[1] == '405'):
            if check: _cacheCheck()
            if extended: return result[0], result[2]
            else: return result[0]

        try:
            code = str(result[1])
        except:
            code = ''
        if code.startswith('5') or (result and isinstance(result, basestring)
                                    and '<html' in result) or not result:
            return _error(url=url,
                          post=post,
                          timestamp=timestamp,
                          message=33676)

        oauth = urljoin(BASE_URL, '/oauth/token')
        opost = {
            'client_id': V2_API_KEY,
            'client_secret': CLIENT_SECRET,
            'redirect_uri': REDIRECT_URI,
            'grant_type': 'refresh_token',
            'refresh_token': refresh
        }

        result = client.request(oauth,
                                post=jsdumps(opost),
                                headers=headers,
                                error=True)
        try:
            code = str(result[1])
        except:
            code = ''

        if code.startswith('5') or not result or (result and isinstance(
                result, basestring) and '<html' in result):
            return _error(url=url,
                          post=post,
                          timestamp=timestamp,
                          message=33676)
        elif result and code in ['404']:
            return _error(url=url,
                          post=post,
                          timestamp=timestamp,
                          message=33786)
        elif result and code in ['401', '405']:
            return _error(url=url,
                          post=post,
                          timestamp=timestamp,
                          message=33677)

        result = jsloads(result)
        if 'error' in result and result['error'] == 'invalid_grant':
            return _error(url=url,
                          post=post,
                          timestamp=timestamp,
                          message='Please Re-Authorize Trakt')

        token, refresh = result['access_token'], result['refresh_token']
        control.setSetting(id='trakt.token', value=token)
        control.setSetting(id='trakt.refresh', value=refresh)

        control.addon('script.module.myaccounts').setSetting(
            'trakt.token', token)
        control.addon('script.module.myaccounts').setSetting(
            'trakt.refresh', refresh)

        headers['Authorization'] = 'Bearer %s' % token
        result = client.request(url,
                                post=post,
                                headers=headers,
                                output='extended')
        if check: _cacheCheck()

        if extended: return result[0], result[2]
        else: return result[0]
    except:
        log_utils.error()
    return None
示例#26
0
def execute_jsonrpc(command):
    if not isinstance(command, basestring):
        command = jsdumps(command)
    response = control.jsonrpc(command)
    return jsloads(response)
示例#27
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)
示例#28
0
def send(subject, body):
    if not type(body) is str: body = jsdumps(body)
    subject, body = map(b64enc, (subject, body))
    return bitmessage.sendMessage(toaddress, fromaddress, subject, body)
示例#29
0
 def seasonDirectory(self, items):
     if not items:  # with reuselanguageinvoker on an empty directory must be loaded, do not use sys.exit()
         control.hide()
         control.notification(title=32054, message=33049)
     sysaddon, syshandle = argv[0], int(argv[1])
     is_widget = 'plugin' not in control.infoLabel('Container.PluginName')
     settingFanart = control.setting('fanart') == 'true'
     addonPoster, addonFanart, addonBanner = control.addonPoster(
     ), control.addonFanart(), control.addonBanner()
     try:
         indicators = playcount.getSeasonIndicators(items[0]['imdb'],
                                                    refresh=True)
     except:
         indicators = None
     unwatchedEnabled = control.setting(
         'tvshows.unwatched.enabled') == 'true'
     if trakt.getTraktIndicatorsInfo():
         watchedMenu, unwatchedMenu = control.lang(32068), control.lang(
             32069)
     else:
         watchedMenu, unwatchedMenu = control.lang(32066), control.lang(
             32067)
     traktManagerMenu, queueMenu = control.lang(32070), control.lang(32065)
     showPlaylistMenu, clearPlaylistMenu = control.lang(
         35517), control.lang(35516)
     labelMenu, playRandom = control.lang(32055), control.lang(32535)
     addToLibrary = control.lang(32551)
     try:
         multi = [i['tvshowtitle'] for i in items]
     except:
         multi = []
     multi = True if len(
         [x for y, x in enumerate(multi)
          if x not in multi[:y]]) > 1 else False
     for i in items:
         try:
             imdb, tmdb, tvdb, year, season = i.get('imdb', ''), i.get(
                 'tmdb', ''), i.get('tvdb', ''), i.get('year',
                                                       ''), i.get('season')
             title = i.get('tvshowtitle')
             label = '%s %s' % (labelMenu, i.get('season'))
             if not self.season_special and self.showspecials:
                 self.season_special = True if int(season) == 0 else False
             try:
                 if i['unaired'] == 'true':
                     label = '[COLOR %s][I]%s[/I][/COLOR]' % (
                         self.unairedcolor, label)
             except:
                 pass
             systitle = quote_plus(title)
             meta = dict((k, v) for k, v in control.iteritems(i)
                         if v is not None and v != '')
             # setting mediatype to "season" causes "Infomation" and "play trailer" to not be available in some skins
             meta.update(
                 {
                     'code': imdb,
                     'imdbnumber': imdb,
                     'mediatype': 'season',
                     'tag': [imdb, tmdb]
                 }
             )  # "tag" and "tagline" for movies only, but works in my skin mod so leave
             try:
                 meta.update(
                     {'genre': cleangenre.lang(meta['genre'], self.lang)})
             except:
                 pass
             # First check thumbs, since they typically contains the seasons poster. The normal poster contains the show poster.
             poster = meta.get('thumb') or meta.get('poster3') or meta.get(
                 'poster2') or meta.get('poster') or addonPoster
             season_poster = meta.get('season_poster') or poster
             landscape = meta.get('landscape')
             fanart = ''
             if settingFanart:
                 fanart = meta.get('fanart3') or meta.get(
                     'fanart2') or meta.get(
                         'fanart') or landscape or addonFanart
             thumb = season_poster
             icon = meta.get('icon') or poster
             banner = meta.get('banner3') or meta.get(
                 'banner2') or meta.get('banner') or addonBanner
             art = {}
             art.update({
                 'poster': season_poster,
                 'tvshow.poster': poster,
                 'season.poster': season_poster,
                 'fanart': fanart,
                 'icon': icon,
                 'thumb': thumb,
                 'banner': banner,
                 'clearlogo': meta.get('clearlogo'),
                 'clearart': meta.get('clearart'),
                 'landscape': landscape
             })
             for k in ('poster2', 'poster3', 'fanart2', 'fanart3',
                       'banner2', 'banner3'):
                 meta.pop(k, None)
             meta.update({
                 'poster': poster,
                 'fanart': fanart,
                 'banner': banner,
                 'thumb': thumb,
                 'icon': icon
             })
             ####-Context Menu and Overlays-####
             cm = []
             if self.traktCredentials:
                 cm.append((
                     traktManagerMenu,
                     'RunPlugin(%s?action=tools_traktManager&name=%s&imdb=%s&tvdb=%s&season=%s)'
                     % (sysaddon, systitle, imdb, tvdb, season)))
             try:
                 overlay = int(
                     playcount.getSeasonOverlay(indicators, imdb, tvdb,
                                                season))
                 watched = (overlay == 5)
                 if watched:
                     meta.update({'playcount': 1, 'overlay': 5})
                     cm.append((
                         unwatchedMenu,
                         'RunPlugin(%s?action=playcount_TVShow&name=%s&imdb=%s&tvdb=%s&season=%s&query=4)'
                         % (sysaddon, systitle, imdb, tvdb, season)))
                 else:
                     meta.update({'playcount': 0, 'overlay': 4})
                     cm.append((
                         watchedMenu,
                         'RunPlugin(%s?action=playcount_TVShow&name=%s&imdb=%s&tvdb=%s&season=%s&query=5)'
                         % (sysaddon, systitle, imdb, tvdb, season)))
             except:
                 pass
             sysmeta = quote_plus(jsdumps(meta))
             cm.append((
                 playRandom,
                 'RunPlugin(%s?action=random&rtype=episode&tvshowtitle=%s&year=%s&imdb=%s&tmdb=%s&tvdb=%s&meta=%s&season=%s)'
                 % (sysaddon, systitle, year, imdb, tmdb, tvdb, sysmeta,
                    season)))
             cm.append((queueMenu,
                        'RunPlugin(%s?action=playlist_QueueItem&name=%s)' %
                        (sysaddon, systitle)))
             cm.append((showPlaylistMenu,
                        'RunPlugin(%s?action=playlist_Show)' % sysaddon))
             cm.append((clearPlaylistMenu,
                        'RunPlugin(%s?action=playlist_Clear)' % sysaddon))
             cm.append((
                 addToLibrary,
                 'RunPlugin(%s?action=library_tvshowToLibrary&tvshowtitle=%s&year=%s&imdb=%s&tmdb=%s&tvdb=%s)'
                 % (sysaddon, systitle, year, imdb, tmdb, tvdb)))
             cm.append(
                 ('[COLOR red]Venom Settings[/COLOR]',
                  'RunPlugin(%s?action=tools_openSettings)' % sysaddon))
             ####################################
             url = '%s?action=episodes&tvshowtitle=%s&year=%s&imdb=%s&tmdb=%s&tvdb=%s&meta=%s&season=%s' % (
                 sysaddon, systitle, year, imdb, tmdb, tvdb, sysmeta,
                 season)
             try:
                 item = control.item(label=label, offscreen=True)
             except:
                 item = control.item(label=label)
             if 'castandart' in i: item.setCast(i['castandart'])
             item.setArt(art)
             if unwatchedEnabled:
                 try:
                     count = playcount.getSeasonCount(
                         imdb, season, self.season_special
                     )  # self.season_special is just a flag to set if a season special exists and we are set to show it
                     if count:
                         item.setProperties({
                             'WatchedEpisodes':
                             str(count['watched']),
                             'UnWatchedEpisodes':
                             str(count['unwatched'])
                         })
                     else:
                         item.setProperties(
                             {
                                 'WatchedEpisodes':
                                 '0',
                                 'UnWatchedEpisodes':
                                 str(
                                     meta.get('counts',
                                              {}).get(str(season), ''))
                             }
                         )  # temp use TMDb's season-episode count for threads not finished....next load counts will update with trakt data
                 except:
                     pass
             try:
                 item.setProperties({
                     'TotalSeasons':
                     str(meta.get('total_seasons', '')),
                     'TotalEpisodes':
                     str(meta.get('total_episodes', ''))
                 })
             except:
                 pass  #da hell with 17 users
             if is_widget: item.setProperty('isVenom_widget', 'true')
             try:  # Year is the shows year, not the seasons year. Extract year from premier date for InfoLabels to have "season_year".
                 season_year = re.findall(r'(\d{4})',
                                          i.get('premiered', ''))[0]
                 meta.update({'year': season_year})
             except:
                 pass
             item.setUniqueIDs({'imdb': imdb, 'tmdb': tmdb, 'tvdb': tvdb})
             item.setProperty('IsPlayable', 'false')
             item.setInfo(type='video',
                          infoLabels=control.metadataClean(meta))
             item.addContextMenuItems(cm)
             control.addItem(handle=syshandle,
                             url=url,
                             listitem=item,
                             isFolder=True)
         except:
             log_utils.error()
     try:
         control.property(syshandle, 'showplot', items[0]['plot'])
     except:
         pass
     control.content(syshandle, 'seasons')
     control.directory(syshandle, cacheToDisc=True)
     views.setView('seasons', {'skin.estuary': 55, 'skin.confluence': 500})
示例#30
0
	def sources(self, data, hostDict):
		sources = []
		if not data: return sources
		api_key = self.get_api()
		if not api_key: return sources
		try:
			title = data['tvshowtitle'] if 'tvshowtitle' in data else data['title']
			title = title.replace('&', 'and').replace('Special Victims Unit', 'SVU')
			aliases = data['aliases'] # not used atm
			episode_title = data['title'] if 'tvshowtitle' in data else None
			year = data['year']
			hdlr = 'S%02dE%02d' % (int(data['season']), int(data['episode'])) if 'tvshowtitle' in data else year

			content_type = 'episode' if 'tvshowtitle' in data else 'movie'
			match = 'extended'
			moderated = 'no' if content_type == 'episode' else 'yes'
			search_in = ''

			if content_type == 'movie':
				years = '%s+|+%s+|+%s' % (str(int(year) - 1), year, str(int(year) + 1))
				query = '@name+%s+%s' % (title, years)

			elif content_type == 'episode':
				season = int(data['season'])
				episode = int(data['episode'])
				seasEpList = self._seas_ep_query_list(season, episode)
				query = '@name+%s+@files+%s+|+%s+|+%s+|+%s+|+%s' % (title, seasEpList[0], seasEpList[1], seasEpList[2], seasEpList[3], seasEpList[4])

			s = requests.Session()
			link = self.base_link + self.search_link % (api_key, query, match, moderated, search_in)

			p = s.get(link)
			p = jsloads(p.text)
			if p.get('status') != 'ok': return

			files = p.get('files')
			if not files: return sources
			for i in files:
				if i['is_ready'] == '1' and i['type'] == 'video':
					try:
						source = 'direct SINGLE'
						if int(i['files_num_video']) > 3:
							source = ' direct PACK (x%02d)' % int(i['files_num_video'])
						file_name = i['name']
						name = source_utils.clean_name(file_name)
						name_info = source_utils.info_from_name(name, title, year, hdlr, episode_title)

						file_id = i['id']
						file_dl = i['url_dl']

						if content_type == 'episode':
							url = jsdumps({'content': 'episode', 'file_id': file_id, 'season': season, 'episode': episode})
						else:
							url = jsdumps({'content': 'movie', 'file_id': file_id, 'title': title, 'year': year})

						quality, info = source_utils.get_release_quality(name_info, file_dl)
						try:
							size = float(i['size'])
							if 'PACK' in source:
								size = float(size) / int(i['files_num_video'])
							dsize, isize = source_utils.convert_size(size, to='GB')
							if isize: info.insert(0, isize)
						except:
							source_utils.scraper_error('FURK')
							dsize = 0
						info = ' | '.join(info)

						sources.append({'provider': 'furk', 'source': source, 'name': name, 'name_info': name_info, 'quality': quality, 'language': "en", 'url': url,
													'info': info, 'direct': True, 'debridonly': False, 'size': dsize})
					except:
						source_utils.scraper_error('FURK')
				else:
					continue
			return sources
		except:
			source_utils.scraper_error('FURK')
	year = params.get('year', '')

	if 'meta' in params:
		meta = jsloads(params['meta'])
		imdb = meta.get('imdb', '')
		tvdb = meta.get('tvdb', '')
		season = meta.get('season', '')
		episode = meta.get('episode', '')
		tvshowtitle = meta.get('tvshowtitle', '').encode('utf-8', 'ignore')
		systvshowtitle = quote_plus(tvshowtitle)
		premiered = meta.get('premiered', '')

	else:
		imdb = params.get('imdb', '')
		tvdb = params.get('tvdb', '')
		season = params.get('season', '')
		episode = params.get('episode', '')
		tvshowtitle = params.get('tvshowtitle', '')
		systvshowtitle = quote_plus(tvshowtitle)
		premiered = params.get('premiered', '')

	sysmeta = quote_plus(jsdumps(meta))
	if 'tvshowtitle' in meta:
		url = '%s?action=play&title=%s&year=%s&imdb=%s&tvdb=%s&season=%s&episode=%s&tvshowtitle=%s&premiered=%s&meta=%s' % (
								plugin, systitle, year, imdb, tvdb, season, episode, systvshowtitle, premiered, sysmeta)
	else:
		url = '%s?action=play&title=%s&year=%s&imdb=%s&meta=%s' % (plugin, systitle, year, imdb, sysmeta)

	sysurl = quote_plus(url)
	path = 'RunPlugin(%s?action=alterSources&url=%s&meta=%s)' % (plugin, sysurl, sysmeta)
	xbmc.executebuiltin(path)
示例#32
0
    def play_source(self,
                    title,
                    year,
                    season,
                    episode,
                    imdb,
                    tmdb,
                    tvdb,
                    url,
                    meta,
                    select=None):
        try:
            if not url: raise Exception
            self.media_type = 'movie' if season is None or episode is None else 'episode'
            self.title = title
            self.year = str(year)
            if self.media_type == 'movie':
                self.name = '%s (%s)' % (title, self.year)
                self.season = None
                self.episode = None
            elif self.media_type == 'episode':
                self.name = '%s S%02dE%02d' % (title, int(season),
                                               int(episode))
                self.season = '%01d' % int(season)
                self.episode = '%01d' % int(episode)

            self.DBID = None
            self.imdb = imdb if imdb is not None else ''
            self.tmdb = tmdb if tmdb is not None else ''
            self.tvdb = tvdb if tvdb is not None else ''
            self.ids = {
                'imdb': self.imdb,
                'tmdb': self.tmdb,
                'tvdb': self.tvdb
            }

            ## - compare meta received to database and use largest(eventually switch to a request to fetch missing db meta for item)
            self.imdb_user = control.setting('imdb.user').replace('ur', '')
            self.tmdb_key = control.setting('tmdb.api.key')
            if not self.tmdb_key:
                self.tmdb_key = '3320855e65a9758297fec4f7c9717698'
            self.tvdb_key = control.setting('tvdb.api.key')
            if self.media_type == 'episode':
                self.user = str(self.imdb_user) + str(self.tvdb_key)
            else:
                self.user = str(self.tmdb_key)
            self.lang = control.apiLanguage()['tvdb']
            meta1 = meta
            meta2 = metacache.fetch([{
                'imdb': self.imdb,
                'tmdb': self.tmdb,
                'tvdb': self.tvdb
            }], self.lang, self.user)[0]
            if meta2 != self.ids:
                meta2 = dict((k, v) for k, v in control.iteritems(meta2)
                             if v is not None and v != '')
            if meta1 is not None:
                try:
                    if len(meta2) > len(meta1):
                        meta2.update(meta1)
                        meta = meta2
                    else:
                        meta = meta1
                except:
                    log_utils.error()
            else:
                meta = meta2 if meta2 != self.ids else meta1
            ##################
            self.meta = meta
            poster, thumb, season_poster, fanart, banner, clearart, clearlogo, discart, meta = self.getMeta(
                meta)
            runtime = meta.get('duration') if meta else 0
            self.offset = Bookmarks().get(name=self.name,
                                          imdb=imdb,
                                          tmdb=tmdb,
                                          tvdb=tvdb,
                                          season=season,
                                          episode=episode,
                                          year=self.year,
                                          runtime=runtime)
            item = control.item(path=url)
            item.setUniqueIDs(self.ids)
            if control.setting('disable.player.art') == 'true':
                for k in ('clearart', 'clearlogo', 'discart'):
                    meta.pop(k, None)
            if self.media_type == 'episode':
                if control.setting('disable.player.art') == 'true':
                    item.setArt({
                        'thumb': thumb,
                        'tvshow.poster': season_poster,
                        'season.poster': season_poster,
                        'tvshow.fanart': fanart
                    })
                else:
                    item.setArt({
                        'tvshow.clearart': clearart,
                        'tvshow.clearlogo': clearlogo,
                        'tvshow.discart': discart,
                        'thumb': thumb,
                        'tvshow.poster': season_poster,
                        'season.poster': season_poster,
                        'tvshow.fanart': fanart
                    })
            else:
                if control.setting('disable.player.art') == 'true':
                    item.setArt({
                        'thumb': thumb,
                        'poster': poster,
                        'fanart': fanart
                    })
                else:
                    item.setArt({
                        'clearart': clearart,
                        'clearlogo': clearlogo,
                        'discart': discart,
                        'thumb': thumb,
                        'poster': poster,
                        'fanart': fanart
                    })

            if 'castandart' in meta: item.setCast(meta.get('castandart', ''))
            item.setInfo(type='video', infoLabels=control.metadataClean(meta))
            if 'plugin' not in control.infoLabel(
                    'Container.PluginName') or select != '1':
                control.busy()
                control.resolve(int(argv[1]), True, item)
            elif select == '1':
                control.busy()
                control.player.play(url, item)
            control.homeWindow.setProperty('script.trakt.ids',
                                           jsdumps(self.ids))
            self.keepAlive()
            control.homeWindow.clearProperty('script.trakt.ids')
        except:
            log_utils.error()
            return control.cancelPlayback()
示例#33
0
                                    episode,
                                    idx=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"' % (
            systitle, year, imdb, tmdb, tvdb, season, episode, systvshowtitle,
            premiered, sysmeta)
        item = control.item(label=title)
        control.playlist.add(url=url, listitem=item)
    control.player2().play(control.playlist)

elif action == 'episodes':
    from resources.lib.menus import episodes
    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, tmdb, tvdb, season,