Пример #1
0
 def fapality(self, url):
     c = client.request(url)
     soup = BeautifulSoup(c,'html.parser')
     r = soup.find_all('source', id=re.compile("video_source_[0-9]"))
     names = []
     srcs  = []
     for i in r:
         name = i['title']
         names.append(kodi.giveColor(name,'white',True))
         src = i['src']
         srcs.append(src)
     selected = kodi.dialog.select('Select a Quality.',names)
     if selected < 0:
         kodi.notify(msg='No option selected.')
         kodi.idle()
         quit()
     else:
         url2 = srcs[selected]
         headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36',
         'Referer' : url}
         link = requests.get(url2,headers=headers, stream=True)
         xbmc.Player().play(link.url)
Пример #2
0
 def porndig(self,url):
     r = client.request(url)
     soup = BeautifulSoup(r,'html.parser')
     iframe = soup.find('div', class_={'video_wrapper'}).iframe['src']
     r = client.request(iframe)
     soup = BeautifulSoup(r,'html.parser')
     pattern = r'''['"]url['"]:.*?['"](.*?)['"].*?['"]label['"]:.*?['"](.*?)['"]'''
     c = re.findall(pattern,r,flags=re.DOTALL)
     names = []
     srcs  = []
     for url,quality in sorted(c, reverse=False):
         url = url.replace('\\','') + '|Referer='+iframe
         names.append(kodi.giveColor(quality,'white',True))
         srcs.append(url)
     selected = kodi.dialog.select('Select a link.',names)
     if selected < 0:
         kodi.notify(msg='No option selected.')
         kodi.idle()
         quit()
     else:
         url2 = srcs[selected]
         xbmc.Player().play(url2)
Пример #3
0
def special_listener():
    ''' Corner cases that needs to be listened to.
        This is run in a loop within monitor.py
    '''
    player = xbmc.Player()
    is_playing = player.isPlaying()
    count = int(window('jellyfin.external_count') or 0)

    if (not is_playing and
            xbmc.getCondVisibility('Window.IsVisible(DialogContextMenu.xml)')
            and xbmc.getInfoLabel('Control.GetLabel(1002)')
            == xbmc.getLocalizedString(12021)):

        control = int(xbmcgui.Window(10106).getFocusId())

        if control == 1002:  # Start from beginning

            LOG.info("Resume dialog: Start from beginning selected.")
            window('jellyfin.resume.bool', False)
        else:
            LOG.info("Resume dialog: Resume selected.")
            window('jellyfin.resume.bool', True)

    elif is_playing and not window('jellyfin.external_check'):
        time = player.getTime()

        if time > 1:  # Not external player.

            window('jellyfin.external_check', value="true")
            window('jellyfin.external_count', value="0")
        elif count == 120:

            LOG.info("External player detected.")
            window('jellyfin.external.bool', True)
            window('jellyfin.external_check.bool', True)
            window('jellyfin.external_count', value="0")

        elif time == 0:
            window('jellyfin.external_count', value=str(count + 1))
Пример #4
0
 def play_item(self, item, name, context):
     path = item.ManifestUrl
     resolved = True if path else False
     listitem = xbmcgui.ListItem()
     listitem.setContentLookup(False)
     listitem.setMimeType('application/dash+xml')
     # ideprecated inputstreamaddon property
     # https://forum.kodi.tv/showthread.php?tid=353560
     # https://github.com/xbmc/xbmc/pull/18020
     listitem.setProperty('inputstreamaddon', 'inputstream.adaptive')
     listitem.setProperty('inputstream', 'inputstream.adaptive')
     listitem.setProperty('inputstream.adaptive.manifest_type', 'mpd')
     listitem.setProperty('inputstream.adaptive.manifest_update_parameter', 'full')
     listitem.setProperty('inputstream.adaptive.max_bandwidth', self.plugin.max_bw)
     listitem.setProperty('inputstream.adaptive.license_type', 'com.widevine.alpha')
     listitem.setProperty('inputstream.adaptive.license_key', '{0}&{1}&_widevineChallenge=B{{SSM}}|||JBlicense'.format(item.LaUrl, item.LaUrlAuthParam))
     if context and resolved:
         listitem.setInfo('video', {'Title': name})
         xbmc.Player().play(path, listitem)
     else:
         listitem.setPath(path)
         xbmcplugin.setResolvedUrl(self.plugin.addon_handle, resolved, listitem)
Пример #5
0
    def play(self, quality=None):
        try:
            if sys.argv[3] == 'resume:true':
                self.properties.pop('ResumeTime', None)
                self.properties.pop('TotalTime', None)
        except:
            pass

        result = True
        if quality_player.parse(self, quality=quality) == False:
            result = False

        li = self.get_li()
        handle = _handle()

        if handle > 0:
            if not result:
                _failed_playback()
            else:
                xbmcplugin.setResolvedUrl(handle, True, li)
        elif result:
            xbmc.Player().play(self.path, li)
Пример #6
0
    def databaseUpdated(self, database):
        showDialogs = utils.getSettingBool(
            'notify_next_run'
        )  # if the user has selected to show dialogs for library operations
        # check if we should clean the library
        if (utils.getSettingBool('clean_libraries')):
            # check if should update while playing media
            if (not xbmc.Player().isPlaying()
                    or utils.getSettingBool("run_during_playback")):
                if (utils.getSettingInt("clean_timer") == 0):
                    # check if we should clean music, or video
                    aJob = CronSchedule()
                    aJob.name = utils.getString(30048)
                    aJob.timer_type = utils.__addon_id__
                    if ((utils.getSettingInt('library_to_clean') == 0
                         or utils.getSettingInt('library_to_clean') == 1)
                            and database == 'video'):
                        # create the clean job schedule
                        aJob.command = {
                            'method': 'VideoLibrary.Clean',
                            'params': {
                                'showdialogs': showDialogs
                            }
                        }
                    if ((utils.getSettingInt('library_to_clean') == 2
                         or utils.getSettingInt('library_to_clean') == 0)
                            and database == 'music'):
                        aJob.command = {
                            'method': 'AudioLibrary.Clean',
                            'params': {
                                'showdialogs': showDialogs
                            }
                        }

                    self.cleanLibrary(aJob)

        # writeLastRun will trigger notifications
        self.writeLastRun()
def getEpisodeInfo():
    episode = {}
    episode['tvshow'] = staticutils.normalizeString(
        xbmc.getInfoLabel('VideoPlayer.TVshowtitle'))  # Show
    episode['season'] = xbmc.getInfoLabel('VideoPlayer.Season')  # Season
    episode['episode'] = xbmc.getInfoLabel('VideoPlayer.Episode')  # Episode
    file_original_path = xbmc.Player().getPlayingFile()  # Full path

    # Check if season is "Special"
    if str(episode['episode']).lower().find('s') > -1:
        episode['season'] = 0
        episode['episode'] = int(str(episode['episode'])[-1:])

    elif file_original_path.find('rar://') > -1:
        file_original_path = os.path.dirname(file_original_path[6:])

    elif file_original_path.find('stack://') > -1:
        file_original_path = file_original_path.split(' , ')[0][8:]

    episode['filename'] = os.path.splitext(
        os.path.basename(file_original_path))[0]

    return episode
Пример #8
0
 def hqporner(self, url):
     #try:
         r = client.request(url)
         pattern = r"""iframe\s*width=['"]\d+['"]\s*height=['"]\d+['"]\s*src=['"]([^'"]+)"""
         url = re.findall(pattern,r)[0]
         url = url if url.startswith('http') else 'https:' + url
         r = client.request(url)
         pattern = r"""a\s+href=['"]([^'"]+mp4)['"].*?>(.*?)<"""
         urls = re.findall(pattern,r)
         names = []
         srcs  = []
         for links,qual in urls:
             if not 'http' in links: links='http:'+links
             names.append(kodi.giveColor(qual,'white',True))
             srcs.append(links)
         selected = kodi.dialog.select('Select a link.',names)
         if selected < 0:
             kodi.notify(msg='No option selected.')
             kodi.idle()
             quit()
         else:
             url2 = srcs[selected]
             xbmc.Player().play(url2)
def reset_thread(is_ia, old_settings):
    log.debug('Settings Reset Thread: STARTED')

    monitor = xbmc.Monitor()
    player = xbmc.Player()
    sleep_time = 100  #ms

    #wait upto 10 seconds for playback to start
    count = 0
    while not monitor.abortRequested():
        if player.isPlaying():
            break

        if count > 10 * (1000 / sleep_time):
            break

        count += 1
        xbmc.sleep(sleep_time)

    # wait until playback stops
    while not monitor.abortRequested():
        if not player.isPlaying():
            break

        xbmc.sleep(sleep_time)

    xbmc.sleep(2000)

    #cant set settings while they are being used in kodi 17
    if not player.isPlaying():
        if is_ia:
            inputstream.set_settings(old_settings)
        else:
            set_gui_settings(old_settings)

    log.debug('Settings Reset Thread: DONE')
    xbmc.executebuiltin('Skin.SetString(quality_reset_thread,)')
Пример #10
0
def shuffle_category(key):
    """Generate a shuffled playlist and start playing"""

    data = get_json('https://data.jw-api.org/mediator/v1/categories/' + global_lang + '/' + key + '?&detailed=1')
    data = data['category']
    all_media = data.get('media', [])
    for sc in data.get('subcategories', []):  # type: dict
        # Don't include things like Featured, because that would become duplicate
        if 'AllowShuffleInCategoryHeader' in sc.get('tags', []):
            all_media += sc.get('media', [])

    # Shuffle in place, we don't want to mess with Kodi's settings
    random.shuffle(all_media)

    pl = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
    pl.clear()

    for md in all_media:
        media = Media()
        media.parse_media(md, censor_hidden=False)
        if media.url and not media.hidden:
            pl.add(media.resolved_url, media.listitem())

    xbmc.Player().play(pl)
Пример #11
0
 def youporn(self, url):
     try:        
         headers = {'User-Agent' : 'User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko'}
         link = requests.get(url,headers=headers).text
         soup = BeautifulSoup(link, 'html.parser')
         r = soup.find('div', class_={'feature videoLike'})['data-videoid']
         apiurl = ('https://www.youporn.com/api/video/media_definitions/%s' % r)
         link = requests.get(apiurl,headers=headers).json()
         names = []
         srcs  = []
         for i in link:
             quality = i['quality']
             mediia = i['videoUrl']
             names.append(kodi.giveColor(quality,'white',True))
             srcs.append(mediia)
         selected = kodi.dialog.select('Select a link.',names)
         if selected < 0:
             kodi.notify(msg='No option selected.')
             kodi.idle()
             quit()
         else:
             url2 = srcs[selected]
             xbmc.Player().play(url2)
     except: pass
Пример #12
0
 def siska(self, url):
         c = client.request(url)
         
         pattern = r'''<iframe src=['"](.*?)['"]'''
         r = re.findall(pattern,c,flags=re.DOTALL)
         names = []
         srcs  = []
         found = 0
         for url in r:
             if not 'hqq.tv' in url:
                 if resolveurl.HostedMediaFile(url).valid_url():
                     found += 1
                     stream = ('Link %s' % found)
                     names.append(kodi.giveColor(stream,'white',True))
                     srcs.append(url)
         selected = kodi.dialog.select('Select a Quality.',names)
         if selected < 0:
             kodi.notify(msg='No option selected.')
             kodi.idle()
             quit()
         else:
             url2 = srcs[selected]
             u = resolveurl.HostedMediaFile(url2).resolve()
             xbmc.Player().play(u)
Пример #13
0
def special_listener():
    ''' Corner cases that needs to be listened to.
        This is run in a loop within monitor.py
    '''
    player = xbmc.Player()
    is_playing = player.isPlaying()
    count = int(window('jellyfin.external_count') or 0)

    if is_playing and not window('jellyfin.external_check'):
        time = player.getTime()

        if time > 1:  # Not external player.

            window('jellyfin.external_check', value="true")
            window('jellyfin.external_count', value="0")
        elif count == 120:

            LOG.info("External player detected.")
            window('jellyfin.external.bool', True)
            window('jellyfin.external_check.bool', True)
            window('jellyfin.external_count', value="0")

        elif time == 0:
            window('jellyfin.external_count', value=str(count + 1))
Пример #14
0
    def get(self, name, imdb, season, episode):
        try:
            if not control.setting('subtitles') == 'true': raise Exception()

            langDict = {
                'Afrikaans': 'afr',
                'Albanian': 'alb',
                'Arabic': 'ara',
                'Armenian': 'arm',
                'Basque': 'baq',
                'Bengali': 'ben',
                'Bosnian': 'bos',
                'Breton': 'bre',
                'Bulgarian': 'bul',
                'Burmese': 'bur',
                'Catalan': 'cat',
                'Chinese': 'chi',
                'Croatian': 'hrv',
                'Czech': 'cze',
                'Danish': 'dan',
                'Dutch': 'dut',
                'English': 'eng',
                'Esperanto': 'epo',
                'Estonian': 'est',
                'Finnish': 'fin',
                'French': 'fre',
                'Galician': 'glg',
                'Georgian': 'geo',
                'German': 'ger',
                'Greek': 'ell',
                'Hebrew': 'heb',
                'Hindi': 'hin',
                'Hungarian': 'hun',
                'Icelandic': 'ice',
                'Indonesian': 'ind',
                'Italian': 'ita',
                'Japanese': 'jpn',
                'Kazakh': 'kaz',
                'Khmer': 'khm',
                'Korean': 'kor',
                'Latvian': 'lav',
                'Lithuanian': 'lit',
                'Luxembourgish': 'ltz',
                'Macedonian': 'mac',
                'Malay': 'may',
                'Malayalam': 'mal',
                'Manipuri': 'mni',
                'Mongolian': 'mon',
                'Montenegrin': 'mne',
                'Norwegian': 'nor',
                'Occitan': 'oci',
                'Persian': 'per',
                'Polish': 'pol',
                'Portuguese': 'por,pob',
                'Portuguese(Brazil)': 'pob,por',
                'Romanian': 'rum',
                'Russian': 'rus',
                'Serbian': 'scc',
                'Sinhalese': 'sin',
                'Slovak': 'slo',
                'Slovenian': 'slv',
                'Spanish': 'spa',
                'Swahili': 'swa',
                'Swedish': 'swe',
                'Syriac': 'syr',
                'Tagalog': 'tgl',
                'Tamil': 'tam',
                'Telugu': 'tel',
                'Thai': 'tha',
                'Turkish': 'tur',
                'Ukrainian': 'ukr',
                'Urdu': 'urd'
            }

            codePageDict = {
                'ara': 'cp1256',
                'ar': 'cp1256',
                'ell': 'cp1253',
                'el': 'cp1253',
                'heb': 'cp1255',
                'he': 'cp1255',
                'tur': 'cp1254',
                'tr': 'cp1254',
                'rus': 'cp1251',
                'ru': 'cp1251'
            }

            quality = [
                'bluray', 'hdrip', 'brrip', 'bdrip', 'dvdrip', 'webrip', 'hdtv'
            ]

            langs = []
            try:
                try:
                    langs = langDict[control.setting(
                        'subtitles.lang.1')].split(',')
                except:
                    langs.append(langDict[control.setting('subtitles.lang.1')])
            except:
                pass
            try:
                try:
                    langs = langs + langDict[control.setting(
                        'subtitles.lang.2')].split(',')
                except:
                    langs.append(langDict[control.setting('subtitles.lang.2')])
            except:
                pass

            try:
                subLang = xbmc.Player().getSubtitles()
            except:
                subLang = ''
            if subLang == langs[0]: raise Exception()

            un = control.setting('os.user')
            pw = control.setting('os.pass')

            server = xmlrpc_client.Server(
                'http://api.opensubtitles.org/xml-rpc', verbose=0)
            token = server.LogIn(un, pw, 'en',
                                 'XBMC_Subtitles_Unofficial_v5.2.14')['token']

            sublanguageid = ','.join(langs)
            imdbid = re.sub('[^0-9]', '', imdb)

            if not (season == None or episode == None):
                result = server.SearchSubtitles(token, [{
                    'sublanguageid': sublanguageid,
                    'imdbid': imdbid,
                    'season': season,
                    'episode': episode
                }])['data']
                fmt = ['hdtv']
            else:
                result = server.SearchSubtitles(token, [{
                    'sublanguageid': sublanguageid,
                    'imdbid': imdbid
                }])['data']
                try:
                    vidPath = xbmc.Player().getPlayingFile()
                except:
                    vidPath = ''
                fmt = re.split('\.|\(|\)|\[|\]|\s|\-', vidPath)
                fmt = [i.lower() for i in fmt]
                fmt = [i for i in fmt if i in quality]

            filter = []
            result = [i for i in result if i['SubSumCD'] == '1']

            for lang in langs:
                filter += [
                    i for i in result if i['SubLanguageID'] == lang and any(
                        x in i['MovieReleaseName'].lower() for x in fmt)
                ]
                filter += [
                    i for i in result if i['SubLanguageID'] == lang and any(
                        x in i['MovieReleaseName'].lower() for x in quality)
                ]
                filter += [i for i in result if i['SubLanguageID'] == lang]

            try:
                lang = xbmc.convertLanguage(filter[0]['SubLanguageID'],
                                            xbmc.ISO_639_1)
            except:
                lang = filter[0]['SubLanguageID']

            subname = str(filter[0]['SubFileName'])

            content = [
                filter[0]['IDSubtitleFile'],
            ]
            content = server.DownloadSubtitles(token, content)
            content = base64.b64decode(content['data'][0]['data'])
            content = gzip.GzipFile(fileobj=six.BytesIO(content)).read()
            if six.PY3: content = six.ensure_text(content)

            subtitle = control.transPath('special://temp/')
            subtitle = os.path.join(subtitle, 'TemporarySubs.%s.srt' % lang)

            codepage = codePageDict.get(lang, '')
            if codepage and control.setting('subtitles.utf') == 'true':
                try:
                    content_encoded = codecs.decode(content, codepage)
                    content = codecs.encode(content_encoded, 'utf-8')
                except:
                    pass

            file = control.openFile(subtitle, 'w')
            file.write(str(content))
            file.close()

            xbmc.sleep(1000)
            xbmc.Player().setSubtitles(subtitle)

            if control.setting('subtitles.notify') == 'true':
                if xbmc.Player().isPlaying() and xbmc.Player().isPlayingVideo(
                ):
                    control.execute('Dialog.Close(all,true)')
                    xbmc.sleep(3000)
                    control.infoDialog(
                        subname,
                        heading='{} subtitles downloaded'.format(
                            str(lang).upper()),
                        time=6000)
        except:
            pass
Пример #15
0
image = xbmcgui.ControlImage

getCurrentDialogId = xbmcgui.getCurrentWindowDialogId()

getCurrentWinId = xbmcgui.getCurrentWindowId()

keyboard = xbmc.Keyboard

monitor = xbmc.Monitor()

execute = xbmc.executebuiltin

skin = xbmc.getSkinDir()

player = xbmc.Player()

playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)

resolve = xbmcplugin.setResolvedUrl

legalFilename = xbmc.makeLegalFilename if getKodiVersion() < 19 else xbmcvfs.makeLegalFilename

openFile = xbmcvfs.File

makeFile = xbmcvfs.mkdir

deleteFile = xbmcvfs.delete

deleteDir = xbmcvfs.rmdir
Пример #16
0
 def play(self):
     li = self.get_li()
     xbmc.Player().play(self.path, li)
Пример #17
0
    def play_playlist(self,
                      items,
                      clear=True,
                      seektime=None,
                      audio=None,
                      subtitle=None):
        ''' Play a list of items. Creates a new playlist. Add additional items as plugin listing.
        '''
        item = items['Items'][0]
        playlist = self.get_playlist(item)
        player = xbmc.Player()

        # xbmc.executebuiltin("Playlist.Clear") # Clear playlist to remove the previous item from playlist position no.2

        if clear:
            if player.isPlaying():
                player.stop()

            xbmc.executebuiltin('ActivateWindow(busydialognocancel)')
            index = 0
        else:
            index = max(playlist.getposition(), 0) + 1  # Can return -1

        listitem = xbmcgui.ListItem()
        LOG.info("[ playlist/%s ] %s", item['Id'], item['Name'])

        play = playutils.PlayUtils(item, False, self.server_id, self.server)
        source = play.select_source(play.get_sources())
        play.set_external_subs(source, listitem)

        item['PlaybackInfo']['AudioStreamIndex'] = audio or item[
            'PlaybackInfo']['AudioStreamIndex']
        item['PlaybackInfo']['SubtitleStreamIndex'] = subtitle or item[
            'PlaybackInfo'].get('SubtitleStreamIndex')

        self.set_listitem(item, listitem, None, True if seektime else False)
        listitem.setPath(item['PlaybackInfo']['Path'])
        playutils.set_properties(item, item['PlaybackInfo']['Method'],
                                 self.server_id)

        playlist.add(item['PlaybackInfo']['Path'], listitem, index)
        index += 1

        if clear:
            xbmc.executebuiltin('Dialog.Close(busydialognocancel)')
            player.play(playlist)

        server_address = item['PlaybackInfo']['ServerAddress']
        token = item['PlaybackInfo']['Token']

        for item in items['Items'][1:]:
            listitem = xbmcgui.ListItem()
            LOG.info("[ playlist/%s ] %s", item['Id'], item['Name'])

            self.set_listitem(item, listitem, None, False)
            path = '{}/Audio/{}/stream.mp3?static=true&api_key={}'.format(
                server_address, item['Id'], token)
            listitem.setPath(path)

            playlist.add(path, listitem, index)
            index += 1
Пример #18
0
def Notif(message):
    if not xbmc.Player().isPlaying():
        Dialog.notification(pluginname, message, sound=False)
def jsonrpc(action, arguments=None):
    """ put some JSON together for the JSON-RPC APIv6 """
    if arguments is None:
        arguments = {}

    if action.lower() == 'sendkey':
        request = json.dumps({
            'jsonrpc': '2.0',
            'method': 'Input.SendText',
            'params': {
                'text': arguments[0],
                'done': False
            }
        })
    elif action.lower() == 'ping':
        request = json.dumps({
            'jsonrpc': '2.0',
            'id': 1,
            'method': 'JSONRPC.Ping'
        })
    elif action.lower() == 'playmedia':
        full_url = arguments[0]
        resume = arguments[1]
        xbmc.Player().play(
            'plugin://plugin.video.composite_for_plex/?mode=5&force=' +
            resume + '&url=' + full_url)
        return True
    elif arguments:
        request = json.dumps({
            'id': 1,
            'jsonrpc': '2.0',
            'method': action,
            'params': arguments
        })
    else:
        request = json.dumps({'id': 1, 'jsonrpc': '2.0', 'method': action})

    LOG.debugplus('Sending request to Kodi without network stack: %s' %
                  request)
    result = parse_jsonrpc(xbmc.executeJSONRPC(request))

    if not result:
        try:
            web_server = AddonSettings().kodi_web_server()
        except RuntimeError:
            return result

        make_web_request = web_server['name'] and web_server[
            'password'] and web_server['port']

        if make_web_request:
            # xbmc.executeJSONRPC appears to fail on the login screen, but going
            # through the network stack works, so let's try the request again
            credentials = '%s:%s' % (web_server['name'],
                                     web_server['password'])
            if PY3:
                credentials = credentials.encode('utf-8')
                base64bytes = base64.encodebytes(credentials)
                base64string = base64bytes.decode('utf-8').replace('\n', '')
            else:
                base64string = base64.encodestring(credentials).replace(
                    '\n', '')  # pylint: disable=no-member
            headers = {
                'Content-Type': 'application/json',
                'Authorization': 'Basic ' + base64string,
            }
            request_manager = RequestManager()
            result = parse_jsonrpc(
                request_manager.post(
                    request_manager.uri('127.0.0.1', web_server['port']),
                    '/jsonrpc', request, headers))

    return result
Пример #20
0
import bjsonrpc
from bjsonrpc.handlers import BaseHandler

from kodi_six import xbmc, xbmcgui, xbmcvfs
from six.moves import urllib_request

from da_inc.addon import ADDON, ADDON_PATH
from da_inc.logger import log
from da_inc.config import JSONRPC_EXT_PORT, da_inc_HOST
from da_inc.osarch import PLATFORM
from da_inc.util import toUtf8, notify, getLocalizedString, getLocalizedLabel, getLocalizedText, system_information
from da_inc.overlay import OverlayText
from da_inc.dialog_select import DialogSelect
from da_inc.dialog_insert import DialogInsert

XBMC_PLAYER = xbmc.Player()

class da_incRPCServer(BaseHandler):
    public_methods_pattern = r'^[A-Za-z]\w+$'

    _objects = {}
    _failures = {}

    def Reset(self):
        for i in self._objects:
            try:
                self._objects[i].hide()
            except:
                pass
        log.info("Resetting RPC objects...")
        self._objects = {}
def isPlayingVideo():
    return xbmc.Player().isPlayingVideo()
Пример #22
0
def run(url_suffix="", retry=0):
    if '/restart/' in sys.argv[0]:
        restart_signal()
        return

    try:
        buffer_timeout = int(ADDON.getSetting("buffer_timeout"))
        if buffer_timeout < 60:
            buffer_timeout = 60
    except:
        buffer_timeout = 60
    buffer_timeout = buffer_timeout * 2

    try:
        preload_timeout = int(ADDON.getSetting("preload_timeout"))
        if preload_timeout < 1:
            preload_timeout = 1
    except:
        preload_timeout = 1

    socket.setdefaulttimeout(buffer_timeout)
    opener = urllib_request.build_opener(NoRedirectHandler())
    opener.addheaders = [('User-Agent', ADDON_ID)]
    urllib_request.install_opener(opener)

    # Pause currently playing Elementum file to avoid doubling requests
    try:
        if xbmc.Player().isPlaying() and ADDON_ID in xbmc.Player(
        ).getPlayingFile():
            xbmc.Player().pause()
    except:
        pass

    url = sys.argv[0].replace("plugin://%s" % ADDON_ID,
                              ELEMENTUMD_HOST + url_suffix) + sys.argv[2]
    query_add = ""

    if len(sys.argv) > 3:
        query_add = sys.argv[3].replace(":", "=")

    if query_add and "resume=" not in url:
        query_add = query_add.replace("resume=", "doresume=")
        if "?" in url:
            url += "&" + query_add
        else:
            url += "?" + query_add

    log.debug("Requesting %s from %s" % (url, repr(sys.argv)))

    try:
        data = _json(url)
    except PlayerException as e:
        redirect_url = e.__str__()
        log.debug("Launching player with %s" % (redirect_url))
        xbmcplugin.endOfDirectory(HANDLE, succeeded=True)
        xbmc.sleep(500)
        xbmc.executeJSONRPC(
            '{"jsonrpc":"2.0","method":"Player.Open","params":{"item":{"file":"%s"}},"id":"1"}'
            % (redirect_url))
        return
    except RedirectException as e:
        redirect_url = e.__str__()
        log.debug("Redirecting Kodi with %s" % (redirect_url))
        xbmcplugin.endOfDirectory(HANDLE, succeeded=True)
        xbmc.sleep(500)
        if "keyboard=1" in sys.argv[0]:
            xbmc.executebuiltin('Container.Update(%s,replace)' %
                                (redirect_url))
        else:
            xbmc.executebuiltin('Container.Update(%s)' % (redirect_url))
        return
    except urllib_error.URLError as e:
        # We can retry the request if connection is refused.
        # For example when plugin has not yet started but is requested by someone.
        if retry <= 2:
            time.sleep(preload_timeout)
            return run(retry=retry + 1)

        if isinstance(e.reason, IOError) or isinstance(
                e.reason, OSError) or 'Connection refused' in e.reason:
            notify(getLocalizedString(30116), time=7000)
        else:
            import traceback
            map(log.error, traceback.format_exc().split("\n"))
            notify(e.reason, time=7000)
        return
    except Exception as e:
        import traceback
        log.debug(traceback.print_exc())
        map(log.error, traceback.format_exc().split("\n"))
        try:
            msg = six.ensure_text(e.__str__(), errors='ignore')
        except:
            try:
                msg = six.ensure_binary(e.__str__(), errors='ignore')
            except:
                msg = repr(e)
        notify(getLocalizedLabel(msg), time=7000)
        return

    if not data:
        return

    if data["content_type"]:
        content_type = data["content_type"]
        if data["content_type"].startswith("menus"):
            content_type = data["content_type"].split("_")[1]

        xbmcplugin.addSortMethod(HANDLE, xbmcplugin.SORT_METHOD_UNSORTED)
        if content_type != "tvshows":
            xbmcplugin.addSortMethod(HANDLE,
                                     xbmcplugin.SORT_METHOD_LABEL_IGNORE_THE)
        else:
            xbmcplugin.addSortMethod(HANDLE,
                                     xbmcplugin.SORT_METHOD_TITLE_IGNORE_THE)
        xbmcplugin.addSortMethod(HANDLE, xbmcplugin.SORT_METHOD_DATE)
        xbmcplugin.addSortMethod(HANDLE, xbmcplugin.SORT_METHOD_GENRE)
        xbmcplugin.setContent(HANDLE, content_type)

    listitems = list(range(len(data["items"])))
    for i, item in enumerate(data["items"]):
        # Translate labels
        if "LOCALIZE" in item["label"]:
            if item["label"][0:8] == "LOCALIZE":
                item["label"] = getLocalizedLabel(item["label"])
            else:
                item["label"] = getLocalizedText(item["label"])
            if isinstance(item["label"], str):
                item["label"] = six.ensure_text(item["label"], 'utf-8')
        if "LOCALIZE" in item["label2"]:
            if item["label2"][0:8] == "LOCALIZE":
                item["label2"] = getLocalizedText(item["label2"])
            else:
                item["label2"] = getLocalizedText(item["label2"])
            if isinstance(item["label2"], str):
                item["label2"] = six.ensure_text(item["label2"], 'utf-8')

        if PLATFORM['kodi'] >= 19:
            listItem = xbmcgui.ListItem(label=item["label"],
                                        label2=item["label2"])
            listItem.setArt({'icon': item["icon"]})
            listItem.setArt({'thumb': item["thumbnail"]})
        else:
            listItem = xbmcgui.ListItem(label=item["label"],
                                        label2=item["label2"],
                                        iconImage=item["icon"],
                                        thumbnailImage=item["thumbnail"])

        try:
            if item.get("castmembers") and PLATFORM['kodi'] >= 17:
                listItem.setCast(item.get("castmembers"))
            if item.get("info"):
                item["info"] = normalizeLabels(item["info"])
                listItem.setInfo("video", item["info"])
            if item.get("stream_info"):
                for type_, values in item["stream_info"].items():
                    listItem.addStreamInfo(type_, values)
            if item.get("art"):
                if "fanarts" in item.get("art") and item.get("art")["fanarts"]:
                    try:
                        start = 0
                        fanart_list = []
                        for fa in item.get("art")["fanarts"]:
                            start += 1
                            item.get("art")["fanart{}".format(start)] = fa
                            fanart_list.append({'image': fa})

                        if PLATFORM['kodi'] >= 18:
                            listItem.setAvailableFanart(fanart_list)
                    except Exception as e:
                        log.warning(
                            "Could not initialize ListItem.Art (%s): %s" %
                            (repr(item.get("art")), repr(e)))
                        pass
                    del item.get("art")["fanarts"]

                listItem.setArt(item["art"])
            elif ADDON.getSetting('default_fanart') == 'true' and item[
                    "label"] != six.ensure_text(getLocalizedString(30218),
                                                'utf-8'):
                fanart = os.path.join(ADDON_PATH, "fanart.jpg")
                listItem.setArt({'fanart': fanart})
            if item.get("context_menu"):
                # Translate context menus
                for m, menu in enumerate(item["context_menu"]):
                    if menu[0][0:8] == "LOCALIZE":
                        menu[0] = getLocalizedLabel(menu[0])
                    if PLATFORM['kodi'] >= 19 and menu[1][0:5] == "XBMC.":
                        menu[1] = menu[1][5:]
                listItem.addContextMenuItems(item["context_menu"])
            listItem.setProperty("isPlayable", item["is_playable"] and "true"
                                 or "false")
            if item.get("properties"):
                for k, v in item["properties"].items():
                    listItem.setProperty(k, v)
        except Exception as e:
            log.warning("Could not initialize ListItem (%s): %s" %
                        (repr(item.get("info")), repr(e)))
        listitems[i] = (item["path"], listItem, not item["is_playable"])

    xbmcplugin.addDirectoryItems(HANDLE, listitems, totalItems=len(listitems))

    # Set ViewMode
    if data["content_type"]:
        viewMode = ADDON.getSetting("viewmode_%s" % data["content_type"])
        if viewMode:
            try:
                xbmc.executebuiltin('Container.SetViewMode(%s)' % viewMode)
            except Exception as e:
                log.warning("Unable to SetViewMode(%s): %s" %
                            (viewMode, repr(e)))

    xbmcplugin.endOfDirectory(HANDLE,
                              succeeded=True,
                              updateListing=False,
                              cacheToDisc=True)
Пример #23
0
# -*- coding: utf-8 -*-
# *  Credits:
# *
# *  original Audio Profiles code by Regss
# *  updates and additions through v1.4.1 by notoco and CtrlGy
# *  updates and additions since v1.4.2 by pkscout

from kodi_six import xbmc, xbmcgui
from resources.lib import notify
from resources.lib.addoninfo import *

KODIMONITOR = xbmc.Monitor()
KODIPLAYER = xbmc.Player()


class DIALOG:

    def start(self, xml_file, labels=None, textboxes=None, buttons=None, thelist=0, force_dialog=False):
        count = 0
        if ADDON.getSetting('player_show').lower() == 'true':
            delay = int(ADDON.getSetting('player_autoclose_delay'))
            autoclose = ADDON.getSetting('player_autoclose').lower()
        else:
            delay = 10
            autoclose = 'false'
        display = SHOW(xml_file, ADDON_PATH, labels=labels, textboxes=textboxes, buttons=buttons, thelist=thelist)
        display.show()
        while (KODIPLAYER.isPlaying() or force_dialog) and not KODIMONITOR.abortRequested():
            if force_dialog:
                notify.logDebug('the current returned value from display is: %s' % str(display.ret))
                if display.ret is not None:
Пример #24
0
def parse(item, quality=None, geolock=None):
    if quality is None:
        quality = get_quality()
        if quality == QUALITY_CUSTOM:
            quality = int(settings.getFloat('max_bandwidth') * 1000000)
    else:
        quality = int(quality)

    if quality in (QUALITY_DISABLED, QUALITY_SKIP):
        return

    url = item.path.split('|')[0]
    parse = urlparse(url.lower())

    if 'http' not in parse.scheme:
        return

    parser = None
    if item.inputstream and item.inputstream.check():
        is_ia = True
        if item.inputstream.manifest_type == 'mpd':
            parser = MPD()
        elif item.inputstream.manifest_type == 'hls':
            parser = M3U8()
    else:
        is_ia = False
        if parse.path.endswith('.m3u') or parse.path.endswith('.m3u8'):
            parser = M3U8()

    if not parser:
        return

    if item.use_proxy:
        url = gui.PROXY_PATH + url

    try:
        resp = Session().get(url,
                             headers=item.headers,
                             cookies=item.cookies,
                             attempts=1,
                             timeout=30)
    except Exception as e:
        log.exception(e)
        return False
    else:
        result = resp.ok

    if not result:
        error = require_country(geolock)
        if not error:
            error = _(_.QUALITY_PARSE_ERROR,
                      error=_(_.QUALITY_HTTP_ERROR, code=resp.status_code))

        gui.ok(error)
        return False

    try:
        parser.parse(resp.text, proxy_enabled=item.use_proxy)
        qualities = parser.qualities()
    except Exception as e:
        log.exception(e)
        gui.ok(_(_.QUALITY_PARSE_ERROR, error=e))
        return

    if len(qualities) < 2:
        log.debug('Only found {} quality, skipping quality select'.format(
            len(qualities)))
        return

    qualities = sorted(qualities, key=lambda s: s[0], reverse=True)

    if quality == QUALITY_ASK:
        quality = get_kodi_string('_slyguy_last_quality')
        addon = get_kodi_string('_slyguy_last_addon')
        playlist_pos = xbmc.PlayList(xbmc.PLAYLIST_VIDEO).getposition()

        if quality and addon == ADDON_ID and (playlist_pos > 0 or
                                              (xbmc.Player().isPlaying()
                                               and playlist_pos == -1)):
            quality = int(quality)
        else:
            quality = select_quality(qualities)

        set_kodi_string('_slyguy_last_quality', quality)
        set_kodi_string('_slyguy_last_addon', ADDON_ID)

        if quality == QUALITY_SKIP:
            return

    if quality == QUALITY_BEST:
        quality = qualities[0][0]
    elif quality == QUALITY_LOWEST:
        quality = qualities[-1][0]

    min_bandwidth, max_bandwidth, stream = parser.bandwidth_range(quality)
    if stream['adaption_set'] > 0 and item.use_proxy:
        item.headers['_proxy_adaption_set'] = str(stream['adaption_set'])

    set_settings(min_bandwidth, max_bandwidth, is_ia)
Пример #25
0
def PlayMonitor(mode=''):
    PLog('PlayMonitor:')
    PLAYLIST = get_playlist()

    OSD = xbmcgui.Dialog()

    mtitle = u"PLAYLIST-Tools"
    PLAYDELAY = 10  # Sek.
    open(PLAYLIST_ALIVE, 'w').close()  # Lebendsignal ein - Abgleich play_list
    xbmc.sleep(1000)  # Start-Info abwarten
    monitor = xbmc.Monitor()
    player = xbmc.Player()

    cnt = 1
    for item in PLAYLIST:
        PLog(item)
        seekTime = 0  # seek-Point Video
        item = py2_decode(item)
        if '###gesehen' in item:
            msg1 = "Titel %d schon gespielt" % cnt
            xbmcgui.Dialog().notification("PLAYLIST: ", msg1, ICON_PLAYLIST,
                                          2000)
            cnt = cnt + 1
            continue

        title, url, thumb, Plot, status = item.split('###')
        if "neu ab" in status:
            seekTime = re.search(u'neu ab (\d+) sec', status).group(
                1)  # Startpos aus Playlist übernehmen
        PLog("Nr.: %s | %s | ab %s sec" % (cnt, title[:80], seekTime))
        msg2 = "Titel %d von %d" % (cnt, len(PLAYLIST))
        xbmcgui.Dialog().notification("PLAYLIST: ", msg2, ICON_PLAYLIST, 2000)
        cnt = cnt + 1
        start_time = int(seekTime)

        # seek-Problem bei HLS-Streams - s. github.com/xbmc/xbmc/issues/18415
        # Exception-Behandl. für nicht verfügb. Videos:
        try:  #  playlist="true" = skip Startliste:
            play_time, video_dur = PlayVideo(url,
                                             title,
                                             thumb,
                                             Plot,
                                             playlist="true",
                                             seekTime=seekTime)
        except Exception as exception:
            PLog(str(exception))
            continue
        percent = 0
        # noch nichts abgespielt

        while not monitor.waitForAbort(2):
            # Notification ev. ergänzen: player.getTotalTime(),
            if player.isPlaying():
                try:
                    play_time = player.getTime()
                except:
                    pass
            else:
                percent = 0
                if play_time > 0 and video_dur > 0:
                    play_time = play_time + 2  # Ausgleich Pause
                    percent = 100 * (float(play_time) / float(video_dur))
                    percent = int(round(percent))
                break
            xbmc.sleep(1000)

        PLog("start_time %d, play_time %d, video_dur %d, percent %d" %\
         (start_time,play_time,video_dur,percent))
        del_val = SETTINGS.getSetting('pref_delete_viewed')  # default 75%
        del_val = re.search(u'(\d+)', del_val).group(1)
        del_val = int(del_val)
        if percent >= del_val:  # Prozentabgleich mit Setting
            item = item.replace("###neu", "###delete")
            PLog('mark_delete: ' + item[:80])
        else:
            pos = item.find("###neu")  # seekTime=play_time anhängen
            item = item[:pos] + "###neu ab %d sec" % play_time
            PLog('mark_gesehen: ' + item[:80])
        PLAYLIST[cnt - 2] = py2_encode(item)
        new_list = "\n".join(PLAYLIST)
        RSave(PLAYFILE, new_list)  # Lock erf. falls auf Share

        if cnt > len(PLAYLIST):
            break
        msg1 = u"nächster PLAYLIST-Titel: %d von %d" % (cnt, len(PLAYLIST))
        msg2 = u"startet automatisch in %d sec." % PLAYDELAY
        msg3 = u"STOP beendet die PLAYLIST"
        PLog(msg1)

        sec = PLAYDELAY
        title = "PLAYLIST:"
        icon = ICON_PLAYLIST
        bg_thread = Thread(target=CountDown,
                           args=(sec, title, icon))  # Notification-CountDown
        bg_thread.start()

        ret = MyDialog(msg1=msg1, msg2=msg2, msg3=msg3, ok=False, cancel='Weiter', \
         yes='STOP', heading=mtitle,autoclose=PLAYDELAY*1000)
        PLog("ret: %d" % ret)
        open(COUNT_STOP, 'w').close()
        if ret == 1:  # autoclose, cancel: 0
            break

    xbmcgui.Dialog().notification("PLAYLIST: ", "beendet", ICON_PLAYLIST, 2000)
    if os.path.exists(PLAYLIST_ALIVE):  # Lebendsignal aus
        os.remove(PLAYLIST_ALIVE)

    return
Пример #26
0
def _json(url):
    with closing(urllib_request.urlopen(url)) as response:
        if response.code >= 300 and response.code <= 307:
            # Pause currently playing Elementum file to avoid doubling requests
            try:
                if xbmc.Player().isPlaying() and ADDON_ID in xbmc.Player(
                ).getPlayingFile():
                    xbmc.Player().pause()
            except:
                pass

            _infoLabels = InfoLabels(getInfoLabels())

            item = xbmcgui.ListItem(path=response.geturl(),
                                    label=_infoLabels["label"],
                                    label2=_infoLabels["label2"],
                                    thumbnailImage=_infoLabels["thumbnail"])

            item.setArt({
                "thumb": _infoLabels["artthumb"],
                "poster": _infoLabels["artposter"],
                "tvshowposter": _infoLabels["arttvshowposter"],
                "banner": _infoLabels["artbanner"],
                "fanart": _infoLabels["artfanart"],
                "clearart": _infoLabels["artclearart"],
                "clearlogo": _infoLabels["artclearlogo"],
                "landscape": _infoLabels["artlandscape"],
                "icon": _infoLabels["articon"]
            })

            item.setInfo(type='Video', infoLabels=_infoLabels)
            xbmcplugin.setResolvedUrl(HANDLE, True, item)
            return

            # TODO: If somebody wants to try to fix the issue with having correct naming in Kodi player information.
            # Currently Kodi pushes file name, which is stored on the disk (inside of strm file).
            # And the problem is that we can't change it (or at least, I'm not aware of any ways to do it).
            # So I have tried to remove it and create a playlist, but that does not work with starting anything from a library.

            # try:
            #     log.debug("PLAYING: %s" % (xbmc.Player().getPlayingFile()))
            # except:
            #     log.debug("NOT PLAYING")

            # if "elementum" in response.geturl().lower() and "http" not in response.geturl().lower():
            #     log.debug("RESOLVED: %s" % response.geturl().lower())
            #     xbmcplugin.setResolvedUrl(HANDLE, True, item)
            # else:
            #     playlistId = xbmc.PLAYLIST_VIDEO
            #     if xbmc.PlayList(1).size() > 0:
            #         playlistId = 1
            #     elif xbmc.PlayList(0).size() > 0:
            #         playlistId = 0

            #     playlist = xbmc.PlayList(playlistId)
            #     playlist.clear()
            #     playlist.add(url=response.geturl(), listitem=item, index=0)
            #     log.debug("PLAYLIST: %s --- %d" % (response.geturl(), playlist.size()))
            #     xbmc.Player().play(playlist)

            # return

        payload = response.read()

        try:
            if payload:
                return json.loads(payload)
        except:
            raise Exception(payload)
Пример #27
0
 def Player_Open(self, item):
     return xbmc.Player().play(item)
Пример #28
0
def run(url_suffix=""):
    to = int(ADDON.getSetting("buffer_timeout"))
    if to < 60:
        to = 60
    to = to * 2

    socket.setdefaulttimeout(to)
    urllib_request.install_opener(
        urllib_request.build_opener(NoRedirectHandler()))

    # Pause currently playing Elementum file to avoid doubling requests
    try:
        if xbmc.Player().isPlaying() and ADDON_ID in xbmc.Player(
        ).getPlayingFile():
            xbmc.Player().pause()
    except:
        pass

    url = sys.argv[0].replace("plugin://%s" % ADDON_ID,
                              ELEMENTUMD_HOST + url_suffix) + sys.argv[2]
    query_add = ""

    if len(sys.argv) > 3:
        app = sys.argv[3].replace(":", "=")

        # Replacing resume=false with resume=true if item is launched from main window
        title = xbmc.getInfoLabel('ListItem.Title')
        label = xbmc.getInfoLabel('ListItem.Label')
        # if "resume" in app and not title and not label:
        #     app = app.replace("resume=false", "resume=true")
        # if "resume" not in app and not title and not label:
        if not title and not label:
            if app:
                app = app.replace("resume=false", "")
                app += "&"
            if app and "resume" not in app:
                app += "resume=true"
        query_add = app
    elif "play" in url or "links" in url:
        query_add = "resume=true"

    if query_add and "resume" not in url:
        query_add = query_add.replace("resume=", "doresume=")
        if "?" in url:
            url += "&" + query_add
        else:
            url += "?" + query_add

    log.debug("Requesting %s from %s" % (url, repr(sys.argv)))

    try:
        data = _json(url)
    except urllib_error.URLError as e:
        if isinstance(e.reason, IOError) or isinstance(
                e.reason, OSError) or 'Connection refused' in e.reason:
            notify(getLocalizedString(30116), time=7000)
        else:
            import traceback
            map(log.error, traceback.format_exc().split("\n"))
            notify(e.reason, time=7000)
        return
    except Exception as e:
        import traceback
        map(log.error, traceback.format_exc().split("\n"))
        try:
            msg = six.ensure_text(e.__str__(), errors='ignore')
        except:
            try:
                msg = six.ensure_binary(e.__str__(), errors='ignore')
            except:
                msg = repr(e)
        notify(getLocalizedLabel(msg), time=7000)
        return

    if not data:
        return

    if data["content_type"]:
        content_type = data["content_type"]
        if data["content_type"].startswith("menus"):
            content_type = data["content_type"].split("_")[1]

        xbmcplugin.addSortMethod(HANDLE, xbmcplugin.SORT_METHOD_UNSORTED)
        if content_type != "tvshows":
            xbmcplugin.addSortMethod(HANDLE,
                                     xbmcplugin.SORT_METHOD_LABEL_IGNORE_THE)
        else:
            xbmcplugin.addSortMethod(HANDLE,
                                     xbmcplugin.SORT_METHOD_TITLE_IGNORE_THE)
        xbmcplugin.addSortMethod(HANDLE, xbmcplugin.SORT_METHOD_DATE)
        xbmcplugin.addSortMethod(HANDLE, xbmcplugin.SORT_METHOD_GENRE)
        xbmcplugin.setContent(HANDLE, content_type)

    listitems = list(range(len(data["items"])))
    for i, item in enumerate(data["items"]):
        # Translate labels
        if item["label"][0:8] == "LOCALIZE":
            item["label"] = getLocalizedLabel(item["label"])
            if isinstance(item["label"], str):
                item["label"] = six.ensure_text(item["label"], 'utf-8')
        if item["label2"][0:8] == "LOCALIZE":
            item["label2"] = getLocalizedLabel(item["label2"])

        listItem = xbmcgui.ListItem(label=item["label"],
                                    label2=item["label2"],
                                    iconImage=item["icon"],
                                    thumbnailImage=item["thumbnail"])
        if item.get("info"):
            listItem.setInfo("video", item["info"])
        if item.get("stream_info"):
            for type_, values in item["stream_info"].items():
                listItem.addStreamInfo(type_, values)
        if item.get("art"):
            listItem.setArt(item["art"])
        elif ADDON.getSetting('default_fanart'
                              ) == 'true' and item["label"] != six.ensure_text(
                                  getLocalizedString(30218), 'utf-8'):
            fanart = os.path.join(ADDON_PATH, "fanart.png")
            listItem.setArt({'fanart': fanart})
        if item.get("context_menu"):
            # Translate context menus
            for m, menu in enumerate(item["context_menu"]):
                if menu[0][0:8] == "LOCALIZE":
                    menu[0] = getLocalizedLabel(menu[0])
            listItem.addContextMenuItems(item["context_menu"])
        listItem.setProperty("isPlayable", item["is_playable"] and "true"
                             or "false")
        if item.get("properties"):
            for k, v in item["properties"].items():
                listItem.setProperty(k, v)
        listitems[i] = (item["path"], listItem, not item["is_playable"])

    xbmcplugin.addDirectoryItems(HANDLE, listitems, totalItems=len(listitems))

    # Set ViewMode
    if data["content_type"]:
        viewMode = ADDON.getSetting("viewmode_%s" % data["content_type"])
        if viewMode:
            try:
                xbmc.executebuiltin('Container.SetViewMode(%s)' % viewMode)
            except Exception as e:
                log.warning("Unable to SetViewMode(%s): %s" %
                            (viewMode, repr(e)))

    xbmcplugin.endOfDirectory(HANDLE,
                              succeeded=True,
                              updateListing=False,
                              cacheToDisc=False)
Пример #29
0
        while not monitor.abortRequested():
            from datetime import datetime, timedelta
            today = datetime.today()
            freq = var.addon.getSetting('auto_update')
            time = var.addon.getSetting('update_time')
            time = '00:00' if time == '' else time
            last = getConfig('last_update', '1970-01-01')
            update_run = updateRunning()

            if freq == '0':
                break
            dt = last + ' ' + time[0:5]
            dtlast = strp(dt, '%Y-%m-%d %H:%M')
            freqdays = [0, 1, 2, 5, 7][int(freq)]
            lastidle = xbmc.getGlobalIdleTime()
            if xbmc.Player().isPlaying():
                startidle = lastidle
            if lastidle < startidle:
                startidle = 0
            idletime = lastidle - startidle
            if var.addon.getSetting('wait_idle') != 'true':
                idletime = idleupdate

            if dtlast + timedelta(days=freqdays) <= today and idletime >= idleupdate:
                if not update_run:
                    Log('Starting DBUpdate ({} / {})'.format(dtlast, today))
                    xbmc.executebuiltin('XBMC.RunPlugin(plugin://{}/?mode=appfeed&sitemode=updateAll)'.format(var.addon.getAddonInfo('id')))

            if monitor.waitForAbort(checkfreq):
                break
    Log('AmazonDB: Service End')
Пример #30
0
    Decode params from sys.argv[2].
    """
    return dict(urlparse.parse_qsl(urlparse.urlparse(sys.argv[2]).query))

params = get_params()
if params['action'] == 'search' or params['action'] == 'manualsearch':
    item = {}
    item['temp']               = False
    item['rar']                = False
    item['mansearch']          = False
    item['year']               = xbmc.getInfoLabel("VideoPlayer.Year")                           # Year
    item['season']             = str(xbmc.getInfoLabel("VideoPlayer.Season"))                    # Season
    item['episode']            = str(xbmc.getInfoLabel("VideoPlayer.Episode"))                   # Episode
    item['tvshow']             = xbmc.getInfoLabel("VideoPlayer.TVshowtitle")   # Show
    item['title']              = xbmc.getInfoLabel("VideoPlayer.OriginalTitle") # try to get original title
    item['file_original_path'] = urllib.unquote(xbmc.Player().getPlayingFile().decode('utf-8'))  # Full path of a playing file
    item['3let_language']      = []

    if 'searchstring' in params:
        item['mansearch'] = True
        item['mansearchstr'] = params['searchstring']

    for lang in urllib.unquote(params['languages']).decode('utf-8').split(","):
        item['3let_language'].append(xbmc.convertLanguage(lang,xbmc.ISO_639_2))

    if item['title'] == "":
        item['title']  = xbmc.getInfoLabel("VideoPlayer.Title")                       # no original title, get just Title
        if item['title'] == os.path.basename(xbmc.Player().getPlayingFile()):         # get movie title and year if is filename
            title, year = xbmc.getCleanMovieTitle(item['title'])
            item['title'] = title.replace('[','').replace(']','')
            item['year'] = year