Exemple #1
0
def resolve_url(url, name=None, iconimage=None, pattern=None):

    xbmc.executebuiltin("ActivateWindow(busydialog)")

    try:
        url, site = url.split('|SPLIT|')
    except:
        site = 'Unknown'
        log_utils.log('Error getting site information from :: %s' % (url),
                      log_utils.LOGERROR)

    if '|CHAT|' in url:
        url, site, name = url.split('|CHAT|')
    if '- [' in name:
        name = name.split('- [')[0]

    u = adultresolver.resolve(url, addon_id=kodi.get_id())

    if u == 'offline':
        xbmc.executebuiltin("Dialog.Close(busydialog)")
        kodi.notify(msg='This performer is offline.',
                    duration=5000,
                    sound=True)
        quit()
    if u:
        play(u, name, iconimage, url, site)
        time.sleep(5)
    else:
        xbmc.executebuiltin("Dialog.Close(busydialog)")
        log_utils.log('Failed to get any playable link for :: %s' % (url),
                      log_utils.LOGERROR)
        kodi.notify(msg='Failed to get any playable link.',
                    duration=7500,
                    sound=True)
        quit()
Exemple #2
0
def do_scheduled_task(task, isPlaying):
    global last_check
    now = datetime.datetime.now()
    if kodi.get_setting('auto-%s' % task) == 'true':
        if last_check < now - datetime.timedelta(minutes=1):
            # log_utils.log('Check Triggered: Last: %s Now: %s' % (last_check, now), log_utils.LOGDEBUG)
            next_run = get_next_run(task)
            last_check = now
        else:
            # hack next_run to be in the future
            next_run = now + datetime.timedelta(seconds=1)

        # log_utils.log("Update Status on [%s]: Currently: %s Will Run: %s Last Check: %s" % (task, now, next_run, last_check), xbmc.LOGDEBUG)
        if now >= next_run:
            is_scanning = xbmc.getCondVisibility('Library.IsScanningVideo')
            if not is_scanning:
                during_playback = kodi.get_setting('%s-during-playback' % (task)) == 'true'
                if during_playback or not isPlaying:
                    log_utils.log('Service: Running Scheduled Task: [%s]' % (task))
                    builtin = 'RunPlugin(plugin://%s/?mode=%s)' % (kodi.get_id(), task)
                    xbmc.executebuiltin(builtin)
                    db_connection.set_setting('%s-last_run' % task, now.strftime("%Y-%m-%d %H:%M:%S.%f"))
                else:
                    log_utils.log('Service: Playing... Busy... Postponing [%s]' % (task), log_utils.LOGDEBUG)
            else:
                log_utils.log('Service: Scanning... Busy... Postponing [%s]' % (task), log_utils.LOGDEBUG)
Exemple #3
0
def do_startup_task(task):
    run_on_startup = kodi.get_setting('auto-%s' % task) == 'true' and kodi.get_setting('%s-during-startup' % task) == 'true'
    if run_on_startup and not xbmc.abortRequested:
        log_utils.log('Service: Running startup task [%s]' % (task))
        now = datetime.datetime.now()
        xbmc.executebuiltin('RunPlugin(plugin://%s/?mode=%s)' % (kodi.get_id(), task))
        db_connection.set_setting('%s-last_run' % (task), now.strftime("%Y-%m-%d %H:%M:%S.%f"))
Exemple #4
0
 def onPlayBackStopped(self):
     logger.log('Service: Playback Stopped', log_utils.LOGNOTICE)
     if self.tracked:
         # clear the playlist if SALTS was playing and only one item in playlist to
         # use playlist to determine playback method in get_sources
         pl = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
         plugin_url = 'plugin://%s/' % (kodi.get_id())
         if pl.size() == 1 and pl[0].getfilename().lower().startswith(plugin_url):
             logger.log('Service: Clearing Single Item SALTS Playlist', log_utils.LOGDEBUG)
             pl.clear()
             
         playedTime = float(self._lastPos)
         try: percent_played = int((playedTime / self._totalTime) * 100)
         except: percent_played = 0  # guard div by zero
         pTime = utils.format_time(playedTime)
         tTime = utils.format_time(self._totalTime)
         logger.log('Service: Played %s of %s total = %s%%' % (pTime, tTime, percent_played), log_utils.LOGDEBUG)
         if playedTime == 0 and self._totalTime == 999999:
             logger.log('Kodi silently failed to start playback', log_utils.LOGWARNING)
         elif playedTime >= 5:
             if percent_played <= 98:
                 logger.log('Service: Setting bookmark on |%s|%s|%s| to %s seconds' % (self.trakt_id, self.season, self.episode, playedTime), log_utils.LOGDEBUG)
                 self.db_connection.set_bookmark(self.trakt_id, playedTime, self.season, self.episode)
                 
             if percent_played >= 75 and self._from_library:
                 if kodi.has_addon('script.trakt'):
                     run = 'RunScript(script.trakt, action=sync, silent=True)'
                     xbmc.executebuiltin(run)
         self.reset()
Exemple #5
0
def show_next_up(last_label, sf_begin):
    token = kodi.get_setting('trakt_oauth_token')
    if token and xbmc.getInfoLabel('Container.PluginName') == kodi.get_id() and xbmc.getInfoLabel('Container.Content') == 'tvshows':
        if xbmc.getInfoLabel('ListItem.label') != last_label:
            sf_begin = time.time()

        last_label = xbmc.getInfoLabel('ListItem.label')
        if sf_begin and (time.time() - sf_begin) >= int(kodi.get_setting('next_up_delay')):
            liz_url = xbmc.getInfoLabel('ListItem.FileNameAndPath')
            queries = kodi.parse_query(liz_url[liz_url.find('?'):])
            if 'trakt_id' in queries:
                try: list_size = int(kodi.get_setting('list_size'))
                except: list_size = 30
                try: trakt_timeout = int(kodi.get_setting('trakt_timeout'))
                except: trakt_timeout = 20
                trakt_api = Trakt_API(token, kodi.get_setting('use_https') == 'true', list_size, trakt_timeout, kodi.get_setting('trakt_offline') == 'true')
                progress = trakt_api.get_show_progress(queries['trakt_id'], full=True)
                if 'next_episode' in progress and progress['next_episode']:
                    if progress['completed'] or kodi.get_setting('next_unwatched') == 'true':
                        next_episode = progress['next_episode']
                        date = utils2.make_day(utils2.make_air_date(next_episode['first_aired']))
                        if kodi.get_setting('next_time') != '0':
                            date_time = '%s@%s' % (date, utils2.make_time(utils.iso_2_utc(next_episode['first_aired']), 'next_time'))
                        else:
                            date_time = date
                        msg = '[[COLOR deeppink]%s[/COLOR]] - %sx%s' % (date_time, next_episode['season'], next_episode['number'])
                        if next_episode['title']: msg += ' - %s' % (next_episode['title'])
                        duration = int(kodi.get_setting('next_up_duration')) * 1000
                        kodi.notify(header=i18n('next_episode'), msg=msg, duration=duration)
            sf_begin = 0
    else:
        last_label = ''
    
    return last_label, sf_begin
Exemple #6
0
def show_next_up(last_label, sf_begin):
    token = kodi.get_setting('trakt_oauth_token')
    if token and xbmc.getInfoLabel('Container.PluginName') == kodi.get_id() and xbmc.getInfoLabel('Container.Content') == 'tvshows':
        if xbmc.getInfoLabel('ListItem.label') != last_label:
            sf_begin = time.time()

        last_label = xbmc.getInfoLabel('ListItem.label')
        if sf_begin and (time.time() - sf_begin) >= int(kodi.get_setting('next_up_delay')):
            liz_url = xbmc.getInfoLabel('ListItem.FileNameAndPath')
            queries = kodi.parse_query(liz_url[liz_url.find('?'):])
            if 'trakt_id' in queries:
                try: list_size = int(kodi.get_setting('list_size'))
                except: list_size = 30
                try: trakt_timeout = int(kodi.get_setting('trakt_timeout'))
                except: trakt_timeout = 20
                trakt_api = Trakt_API(token, kodi.get_setting('use_https') == 'true', list_size, trakt_timeout, kodi.get_setting('trakt_offline') == 'true')
                progress = trakt_api.get_show_progress(queries['trakt_id'], full=True)
                if 'next_episode' in progress and progress['next_episode']:
                    if progress['completed'] or kodi.get_setting('next_unwatched') == 'true':
                        next_episode = progress['next_episode']
                        date = utils2.make_day(utils2.make_air_date(next_episode['first_aired']))
                        if kodi.get_setting('next_time') != '0':
                            date_time = '%s@%s' % (date, utils2.make_time(utils.iso_2_utc(next_episode['first_aired']), 'next_time'))
                        else:
                            date_time = date
                        msg = '[[COLOR deeppink]%s[/COLOR]] - %sx%s' % (date_time, next_episode['season'], next_episode['number'])
                        if next_episode['title']: msg += ' - %s' % (next_episode['title'])
                        duration = int(kodi.get_setting('next_up_duration')) * 1000
                        kodi.notify(header=i18n('next_episode'), msg=msg, duration=duration)
            sf_begin = 0
    else:
        last_label = ''
    
    return last_label, sf_begin
Exemple #7
0
 def onPlayBackStopped(self):
     logger.log('Service: Playback Stopped', log_utils.LOGNOTICE)
     if self.tracked:
         # clear the playlist if transistortv was playing and only one item in playlist to
         # use playlist to determine playback method in get_sources
         pl = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
         plugin_url = 'plugin://%s/' % (kodi.get_id())
         if pl.size() == 1 and pl[0].getfilename().lower().startswith(plugin_url):
             logger.log('Service: Clearing Single Item Stream All The Sources Playlist', log_utils.LOGDEBUG)
             pl.clear()
             
         playedTime = float(self._lastPos)
         try: percent_played = int((playedTime / self._totalTime) * 100)
         except: percent_played = 0  # guard div by zero
         pTime = utils.format_time(playedTime)
         tTime = utils.format_time(self._totalTime)
         logger.log('Service: Played %s of %s total = %s%%' % (pTime, tTime, percent_played), log_utils.LOGDEBUG)
         if playedTime == 0 and self._totalTime == 999999:
             logger.log('Kodi silently failed to start playback', log_utils.LOGWARNING)
         elif playedTime >= 5:
             if percent_played <= 98:
                 logger.log('Service: Setting bookmark on |%s|%s|%s| to %s seconds' % (self.trakt_id, self.season, self.episode, playedTime), log_utils.LOGDEBUG)
                 self.db_connection.set_bookmark(self.trakt_id, playedTime, self.season, self.episode)
                 
             if percent_played >= 75 and self._from_library:
                 if kodi.has_addon('script.trakt'):
                     run = 'RunScript(script.trakt, action=sync, silent=True)'
                     xbmc.executebuiltin(run)
         self.reset()
Exemple #8
0
def do_scheduled_task(task, isPlaying):
    global last_check
    now = datetime.datetime.now()
    if kodi.get_setting("auto-%s" % task) == "true":
        if last_check < now - datetime.timedelta(minutes=1):
            # log_utils.log('Check Triggered: Last: %s Now: %s' % (last_check, now), log_utils.LOGDEBUG)
            next_run = get_next_run(task)
            last_check = now
        else:
            # hack next_run to be in the future
            next_run = now + datetime.timedelta(seconds=1)

        # log_utils.log("Update Status on [%s]: Currently: %s Will Run: %s Last Check: %s" % (task, now, next_run, last_check), xbmc.LOGDEBUG)
        if now >= next_run:
            is_scanning = xbmc.getCondVisibility("Library.IsScanningVideo")
            if not is_scanning:
                during_playback = kodi.get_setting("%s-during-playback" % (task)) == "true"
                if during_playback or not isPlaying:
                    log_utils.log("Service: Running Scheduled Task: [%s]" % (task))
                    builtin = "RunPlugin(plugin://%s/?mode=%s)" % (kodi.get_id(), task)
                    xbmc.executebuiltin(builtin)
                    db_connection.set_setting("%s-last_run" % task, now.strftime("%Y-%m-%d %H:%M:%S.%f"))
                else:
                    log_utils.log("Service: Playing... Busy... Postponing [%s]" % (task), log_utils.LOGDEBUG)
            else:
                log_utils.log("Service: Scanning... Busy... Postponing [%s]" % (task), log_utils.LOGDEBUG)
def run(REPO, STATE):
    ISSUES_FOR_REPO_URL = 'http://api.github.com/repos/%s/issues?state=%s' % (REPO, STATE)

    def write_issues(response):
        "output a list of issues to csv"
        if not r.status_code == 200:
            raise Exception(r.status_code)
        for issue in r.json():
            username = issue.get("user", {}).get('login', {})
            if issue['labels']:
                labels = issue['labels']
                for label in labels:
                    #if label['name'] == "Client Requested":
                    csvout.writerow(['\n<item>\n<id>'+str(issue['number'])+'</id>\n<username>'+username+'</username>\n<label>'+label['name']+'</label>\n<title>'+issue['title'].encode('utf-8')+'</title>\n<body>'+issue['body'].encode('utf-8')+'</body>\n<created>'+issue['created_at']+'</created>\n</item>\n'])
            else:
                csvout.writerow(['\n<item>\n<id>'+str(issue['number'])+'</id>\n<username>'+username+'</username>\n<label>No Label</label>\n<title>'+issue['title'].encode('utf-8')+'</title>\n<body>'+issue['body'].encode('utf-8')+'</body>\n<created>'+issue['created_at']+'</created>\n</item>\n'])

    r = requests.get(ISSUES_FOR_REPO_URL, verify=False)
    csvfile = xbmc.translatePath(os.path.join(kodi.datafolder, '%s-issues-%s.csv' % (kodi.get_id(),STATE)))
    csvout = csv.writer(open(csvfile, 'wb'))
    write_issues(r)

    #more pages? examine the 'link' header returned
    if 'link' in r.headers:
        pages = dict(
            [(rel[6:-1], url[url.index('<')+1:-1]) for url, rel in
                [link.split(';') for link in
                    r.headers['link'].split(',')]])
        while 'last' in pages and 'next' in pages:
            r = requests.get(pages['next'])
            write_issues(r)
            if pages['next'] == pages['last']:
                break
def githubSelect(name):
    import githubissues
    githubissues.run('xibalba10/plugin.video.xxx-o-dus', '%s' % name)
    file = xbmc.translatePath(os.path.join(kodi.datafolder, '%s-issues-%s.csv' % (kodi.get_id(),name)))
    
    global msg_text
    
    with open(file,mode='r')as f: txt = f.read()
    items = re.findall('<item>(.+?)</item>', txt, re.DOTALL)
    if len(items) < 1:
        msg_text = kodi.giveColor('No %s issues with XXX-O-DUS at this time.' % name.title(),'deeppink',True)
    else:
        msg_text = kodi.giveColor('%s Issues with XXX-O-DUS\n' % name.title(),'deeppink',True) + kodi.giveColor('Report Issues @ https://github.com/xibalba10/plugin.video.xxx-o-dus/issues','white',True) + '\n---------------------------------\n\n'
        for item in items:
            id = re.findall('<id>([^<]+)', item)[0]
            user = re.findall('<username>([^<]+)', item)[0]
            label = re.findall('<label>([^<]+)', item)[0]
            title = re.findall('<title>([^<]+)', item)[0]
            body = re.findall('<body>([^<]+)', item)[0]
            created = re.findall('<created>([^<]+)', item)[0]
            date,time = created.split('T')
            msg_text += '[B]ID: %s | Label: %s \nBy: %s on %s at %s[/B] \n\nTitle: %s \nMessage %s \n\n---------------------------------\n\n' \
                         % (id, \
                            kodi.githubLabel(label), \
                            user, \
                            date, \
                            time.replace('Z',''), \
                            title, \
                            body)
Exemple #11
0
def do_startup_task(task):
    run_on_startup = (
        kodi.get_setting("auto-%s" % task) == "true" and kodi.get_setting("%s-during-startup" % task) == "true"
    )
    if run_on_startup and not xbmc.abortRequested:
        log_utils.log("Service: Running startup task [%s]" % (task))
        now = datetime.datetime.now()
        xbmc.executebuiltin("RunPlugin(plugin://%s/?mode=%s)" % (kodi.get_id(), task))
        db_connection.set_setting("%s-last_run" % (task), now.strftime("%Y-%m-%d %H:%M:%S.%f"))
Exemple #12
0
def from_playlist():
    pl = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
    if pl.size() > 0:
        li = pl[pl.getposition()]
        plugin_url = 'plugin://%s/' % (kodi.get_id())
        if li.getfilename().lower().startswith(plugin_url):
            log_utils.log('Playing SALTS item from playlist |%s|%s|%s|' % (pl.getposition(), li.getfilename(), plugin_url), log_utils.LOGDEBUG)
            return True
    
    return False
Exemple #13
0
def from_playlist():
    pl = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
    if pl.size() > 0:
        li = pl[pl.getposition()]
        plugin_url = 'plugin://%s/' % (kodi.get_id())
        if li.getfilename().lower().startswith(plugin_url):
            log_utils.log('Playing SALTS item from playlist |%s|%s|%s|' % (pl.getposition(), li.getfilename(), plugin_url), log_utils.LOGDEBUG)
            return True
    
    return False
Exemple #14
0
def main(argv=None):
    if sys.argv: argv = sys.argv
    queries = kodi.parse_query(sys.argv[2])
    log_utils.log('Version: |%s| Queries: |%s|' % (kodi.get_version(), queries))
    log_utils.log('Args: |%s|' % (argv))

    # don't process params that don't match our url exactly. (e.g. plugin://plugin.video.1channel/extrafanart)
    plugin_url = 'plugin://%s/' % (kodi.get_id())
    if argv[0] != plugin_url:
        return

    mode = queries.get('mode', None)
    url_dispatcher.dispatch(mode, queries)
def is_salts():
    plugin_name = xbmc.getInfoLabel('Container.PluginName')
    logger.log('Is_Salts Test (1): |%s|' % (plugin_name))
    if plugin_name == kodi.get_id():
        return True
    elif not plugin_name:
        path = xbmc.getInfoLabel('ListItem.FileNameAndPath')
        if not path:
            path = xbmc.getInfoLabel('ListItem.Path')
        
        logger.log('Is_Salts Test (2): |%s|' % (path))
        if path:
            try:
                lines = xbmcvfs.File(path).read()
                logger.log('Is_Salts Test (3): |%s|%s|' % (lines, kodi.get_id()))
                if lines:
                    return lines.startswith('plugin://%s' % (kodi.get_id()))
            except:
                return True
        return True
    else:
        return False
Exemple #16
0
def main(argv=None):
    if sys.argv: argv = sys.argv
    queries = kodi.parse_query(sys.argv[2])
    logger.log('Version: |%s| Queries: |%s|' % (kodi.get_version(), queries))
    logger.log('Args: |%s|' % (argv))

    # don't process params that don't match our url exactly. (e.g. plugin://plugin.video.1channel/extrafanart)
    plugin_url = 'plugin://%s/' % (kodi.get_id())
    if argv[0] != plugin_url:
        return

    mode = queries.get('mode', None)
    url_dispatcher.dispatch(mode, queries)
Exemple #17
0
def is_salts():
    plugin_name = xbmc.getInfoLabel('Container.PluginName')
    logger.log('Is_Salts Test (1): |%s|' % (plugin_name))
    if plugin_name == kodi.get_id():
        return True
    elif not plugin_name:
        path = xbmc.getInfoLabel('ListItem.FileNameAndPath')
        if not path:
            path = xbmc.getInfoLabel('ListItem.Path')
        
        logger.log('Is_Salts Test (2): |%s|' % (path))
        if path:
            try:
                lines = xbmcvfs.File(path).read()
                logger.log('Is_Salts Test (3): |%s|%s|' % (lines, kodi.get_id()))
                if lines:
                    return lines.startswith('plugin://%s' % (kodi.get_id()))
            except:
                return True
        return True
    else:
        return False
Exemple #18
0
def run(REPO, STATE):
    ISSUES_FOR_REPO_URL = 'http://api.github.com/repos/%s/issues?state=%s' % (
        REPO, STATE)

    def write_issues(response):
        "output a list of issues to csv"
        if not r.status_code == 200:
            raise Exception(r.status_code)
        for issue in r.json():
            username = issue.get("user", {}).get('login', {})
            if issue['labels']:
                labels = issue['labels']
                for label in labels:
                    #if label['name'] == "Client Requested":
                    csvout.writerow([
                        '\n<item>\n<id>' + str(issue['number']) +
                        '</id>\n<username>' + username +
                        '</username>\n<label>' + label['name'] +
                        '</label>\n<title>' + issue['title'].encode('utf-8') +
                        '</title>\n<body>' + issue['body'].encode('utf-8') +
                        '</body>\n<created>' + issue['created_at'] +
                        '</created>\n</item>\n'
                    ])
            else:
                csvout.writerow([
                    '\n<item>\n<id>' + str(issue['number']) +
                    '</id>\n<username>' + username +
                    '</username>\n<label>No Label</label>\n<title>' +
                    issue['title'].encode('utf-8') + '</title>\n<body>' +
                    issue['body'].encode('utf-8') + '</body>\n<created>' +
                    issue['created_at'] + '</created>\n</item>\n'
                ])

    r = requests.get(ISSUES_FOR_REPO_URL, verify=False)
    csvfile = xbmc.translatePath(
        os.path.join(kodi.datafolder,
                     '%s-issues-%s.csv' % (kodi.get_id(), STATE)))
    csvout = csv.writer(open(csvfile, 'wb'))
    write_issues(r)

    #more pages? examine the 'link' header returned
    if 'link' in r.headers:
        pages = dict([
            (rel[6:-1], url[url.index('<') + 1:-1]) for url, rel in
            [link.split(';') for link in r.headers['link'].split(',')]
        ])
        while 'last' in pages and 'next' in pages:
            r = requests.get(pages['next'])
            write_issues(r)
            if pages['next'] == pages['last']:
                break
Exemple #19
0
def disable_global_cx(was_on):
    if kodi.has_addon('plugin.program.super.favourites'):
        active_plugin = xbmc.getInfoLabel('Container.PluginName')
        sf = xbmcaddon.Addon('plugin.program.super.favourites')
        if active_plugin == kodi.get_id():
            if sf.getSetting('CONTEXT') == 'true':
                logger.log('Disabling Global CX while Stream All The Sources is active', log_utils.LOGDEBUG)
                was_on = True
                sf.setSetting('CONTEXT', 'false')
        elif was_on:
            logger.log('Re-enabling Global CX while Stream All The Sources is not active', log_utils.LOGDEBUG)
            sf.setSetting('CONTEXT', 'true')
            was_on = False
    
    return was_on
Exemple #20
0
def disable_global_cx(was_on):
    if kodi.has_addon('plugin.program.super.favourites'):
        active_plugin = xbmc.getInfoLabel('Container.PluginName')
        sf = xbmcaddon.Addon('plugin.program.super.favourites')
        if active_plugin == kodi.get_id():
            if sf.getSetting('CONTEXT') == 'true':
                logger.log('Disabling Global CX while SALTS is active', log_utils.LOGDEBUG)
                was_on = True
                sf.setSetting('CONTEXT', 'false')
        elif was_on:
            logger.log('Re-enabling Global CX while SALTS is not active', log_utils.LOGDEBUG)
            sf.setSetting('CONTEXT', 'true')
            was_on = False
    
    return was_on
def main(argv=None):
    if sys.argv: argv = sys.argv
    queries = kodi.parse_query(sys.argv[2])
    log_utils.log('Version: |%s| Queries: |%s|' % (kodi.get_version(), queries), log_utils.LOGNOTICE)
    log_utils.log('Args: |%s|' % (argv), log_utils.LOGNOTICE)

    # don't process params that don't match our url exactly. (e.g. plugin://plugin.video.1channel/extrafanart)
    plugin_url = 'plugin://%s/' % (kodi.get_id())
    if argv[0] != plugin_url:
        return

    try:
        mode = queries.get('mode', None)
        url_dispatcher.dispatch(mode, queries)
    except (TransientTraktError, TraktError, TraktAuthError) as e:
        log_utils.log(str(e), log_utils.LOGERROR)
        kodi.notify(msg=str(e), duration=5000)
Exemple #22
0
def main(argv=None):
    if sys.argv: argv = sys.argv
    queries = kodi.parse_query(sys.argv[2])
    logger.log('Version: |%s| Queries: |%s|' % (kodi.get_version(), queries),
               log_utils.LOGNOTICE)
    logger.log('Args: |%s|' % (argv), log_utils.LOGNOTICE)

    # don't process params that don't match our url exactly. (e.g. plugin://plugin.video.1channel/extrafanart)
    plugin_url = 'plugin://%s/' % (kodi.get_id())
    if argv[0] != plugin_url:
        return

    try:
        mode = queries.get('mode', None)
        url_dispatcher.dispatch(mode, queries)
    except (TransientTraktError, TraktError, TraktAuthError) as e:
        logger.log(str(e), log_utils.LOGERROR)
        kodi.notify(msg=str(e), duration=5000)
Exemple #23
0
def find_link(url, name, iconimage, downloadableLink=False):

    xbmc.executebuiltin("ActivateWindow(busydialog)")

    if '|SPLIT|' in url: url = url.split('|SPLIT|')[0]
    if 'site=' in url: url = url.split('site=')[0]
    if '|User-Agent' in url: url = url.split('|User-Agent')[0]

    c = client.request(url, output='headers')

    checks = ['video','mpegurl']
    
    try:
        if any(f for f in checks if f in c['Content-Type']): downloadableLink = True
    except:
        xbmc.executebuiltin("Dialog.Close(busydialog)")
        kodi.notify(msg='Error downloading video.')
        quit()

    name = kodi.stripColor(name)
    if '] -' in name: name = name.split('] -')[1]
    if downloadableLink:
        dest = getDest()
        dest = os.path.join(dest, '%s.mp4' % urllib.quote_plus(name))
        download(url,name,iconimage,dest)
    else:
        u = adultresolver.resolve(url, addon_id=kodi.get_id())
        if (not isinstance(u, str)): u = player.multilinkselector(u)
        if u == 'quit': 
            xbmc.executebuiltin("Dialog.Close(busydialog)")
            quit()
        if u: 
            dest = getDest()
            dest = os.path.join(dest, '%s.tmp_mp4' % urllib.quote_plus(name))
            download(u,name,iconimage,dest)
        else:
            xbmc.executebuiltin("Dialog.Close(busydialog)")
            kodi.notify('No Downloadable Link Found.')
            quit()
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""
import functools
import log_utils
import time
import cPickle as pickle
import hashlib
import os
import shutil
import kodi

cache_path = kodi.translate_path(
    os.path.join('special://temp/%s/cache' % kodi.get_id()))
try:
    if not os.path.exists(cache_path):
        os.makedirs(cache_path)
except Exception as e:
    log_utils.log('Failed to create cache: %s: %s' % (cache_path, e),
                  log_utils.LOGWARNING)

cache_enabled = kodi.get_setting('use_cache') == 'true'


def reset_cache():
    try:
        shutil.rmtree(cache_path)
        return True
    except Exception as e:
Exemple #25
0
import db_utils
from url_dispatcher import URL_Dispatcher


def __enum(**enums):
    return type('Enum', (), enums)


DATABASE_VERSION = 1
DATABASE_FILE = kodi.translate_path('special://database/{0!s}{1!s}.db'.format(
    kodi.get_name(), str(DATABASE_VERSION)))
DATABASE = db_utils.SQLite(DATABASE_FILE)
DISPATCHER = URL_Dispatcher()

ADDON_DATA_DIR = kodi.translate_path('special://profile/addon_data/%s/' %
                                     kodi.get_id())
THUMBNAILS_DIR = kodi.translate_path('special://thumbnails/')
RESOLVER_DIRS = [
    kodi.translate_path(
        'special://home/addons/{0!s}/resources/lib/addon_lib/resolvers/'.
        format(kodi.get_id())),
    kodi.translate_path(
        'special://home/addons/script.module.urlresolver.xxx/resources/plugins/'
    )
]

COOKIE_FILE = kodi.translate_path('special://temp/%s/cookies.lwp' %
                                  kodi.get_id())

MODES = __enum(MAIN='main',
               PLAY='play',
    def get_list(self,
                 mode,
                 type,
                 url,
                 title_pattern,
                 url_pattern,
                 icon_pattern=None,
                 site=None,
                 d_p1=None,
                 d_p2=None,
                 d_p3=None,
                 parse=None,
                 cache_time=None,
                 searched=False,
                 stopend=False,
                 isVideo=False,
                 isDownloadable=False):

        if cache_time: r = cache.get(client.request, cache_time, url)
        else: r = client.request(url)

        if 're|' in d_p3:
            d_p3 = d_p3.replace('re|', '')
            r = dom_parser2.parse_dom(r, d_p1, {d_p2: re.compile('%s' % d_p3)})
        else:
            r = dom_parser2.parse_dom(r, d_p1, {d_p2: d_p3})

        if r:

            dirlst = []

            for i in r:
                name = re.findall(r'%s' % title_pattern, i.content)[0]
                name = kodi.sortX(i[1].encode('utf-8'))
                url = re.findall(r'%s' % url_pattern, i.content)[0]
                if icon_pattern:
                    iconimage = re.findall(r'%s' % icon_pattern, i.content)[0]
                elif site:
                    iconimage = xbmc.translatePath(
                        os.path.join(
                            'special://home/addons/script.xxxodus.artwork',
                            'resources/art/%s/icon.png' % site))
                else:
                    iconimage = xbmc.translatePath(
                        os.path.join('special://home/addons/' + kodi.get_id(),
                                     'icon.png'))
                fanarts = xbmc.translatePath(
                    os.path.join(
                        'special://home/addons/script.xxxodus.artwork',
                        'resources/art/%s/fanart.jpg' % site))
                if parse:
                    link, tag = parse.split('|SPLIT|')
                    if tag == 'url':
                        url = urlparse.urljoin(link, url)
                    elif tag == 'icon':
                        iconimage = urlparse.urljoin(link, iconimage)
                    else:
                        url = urlparse.urljoin(link, url)
                        iconimage = urlparse.urljoin(link, iconimage)
                if site: url += '|SPLIT|' + site
                if type == 'dir':
                    dirlst.append({
                        'name': kodi.giveColor(name, 'white'),
                        'url': url,
                        'mode': mode,
                        'icon': iconimage,
                        'fanart': fanarts,
                        'description': name,
                        'folder': True
                    })
                else:
                    dirlst.append({
                        'name': kodi.giveColor(name, 'white'),
                        'url': url,
                        'mode': mode,
                        'icon': iconimage,
                        'fanart': fanarts,
                        'description': name,
                        'folder': False
                    })

            if dirlst:
                if stopend:
                    buildDirectory(dirlst,
                                   stopend=True,
                                   isVideo=isVideo,
                                   isDownloadable=isDownloadable)
                else:
                    buildDirectory(dirlst,
                                   isVideo=isVideo,
                                   isDownloadable=isDownloadable)
Exemple #27
0
def githubIssues():

    choice = xbmcgui.Dialog().yesno(
        "[COLOR red]Please select an option[/COLOR]",
        "Would you like to view open issues or closed issues?",
        yeslabel='Closed',
        nolabel='Open')

    import githubissues
    if choice == 0: name = 'open'
    elif choice == 1: name = 'closed'
    else: quit()
    githubissues.run('Colossal1/plugin.video.ourmatch', '%s' % name)
    file = xbmc.translatePath(
        os.path.join(kodi.datafolder,
                     '%s-issues-%s.csv' % (kodi.get_id(), name)))

    with open(file, mode='r') as f:
        txt = f.read()
    items = re.findall('<item>(.+?)</item>', txt, re.DOTALL)
    if (not items) or (len(items) < 1):
        msg_text = kodi.giveColor(
            'No %s issues with Our Match at this time.' % name.title(), 'blue',
            True)
    else:
        msg_text = kodi.giveColor(
            '%s Issues with Our Match\n' % name.title(), 'blue', True
        ) + kodi.giveColor(
            'Report Issues @ https://github.com/Colossal1/plugin.video.ourmatch/issues',
            'white', True) + '\n---------------------------------\n\n'
        for item in items:
            try:
                id = re.findall('<id>([^<]+)', item)[0]
            except:
                id = 'Unknown'
            try:
                user = re.findall('<username>([^<]+)', item)[0]
            except:
                user = '******'
            try:
                label = re.findall('<label>([^<]+)', item)[0]
            except:
                label = 'Unknown'
            try:
                title = re.findall('<title>([^<]+)', item)[0]
            except:
                title = 'Unknown'
            try:
                body = re.findall('<body>([^<]+)', item)[0]
            except:
                body = 'Unknown'
            try:
                created = re.findall('<created>([^<]+)', item)[0]
                date, time = created.split('T')
            except:
                date = 'Unknown'
                time = 'Unknwon'
            msg_text += '[B]ID: %s | Label: %s \nBy: %s on %s at %s[/B] \n\nTitle: %s \nMessage %s \n\n---------------------------------\n\n' \
                         % (id, \
                            kodi.githubLabel(label), \
                            user, \
                            date, \
                            time.replace('Z',''), \
                            title, \
                            body)
    textboxGit('OurMatch Issues', msg_text)
Exemple #28
0
    elif view_mode == SEASONS:
        _log("set_view content is seasons")
        xbmcplugin.setContent(int(sys.argv[1]), "seasons")
    elif view_mode == EPISODES:
        _log("set_view content is episodes")
        xbmcplugin.setContent(int(sys.argv[1]), "episodes")
    skin_name = xbmc.getSkinDir()  # Reads skin name
    _log("set_view skin_name='" + skin_name + "'")
    try:
        if view_code == 0:
            _log("set_view view mode is " + view_mode)
            view_codes = ALL_VIEW_CODES.get(view_mode)
            view_code = view_codes.get(skin_name)
            _log("set_view view code for " + view_mode + " in " + skin_name +
                 " is " + str(view_code))
            xbmc.executebuiltin("Container.SetViewMode(" + str(view_code) +
                                ")")
        else:
            _log("set_view view code forced to " + str(view_code))
            xbmc.executebuiltin("Container.SetViewMode(" + str(view_code) +
                                ")")
    except:
        _log("Unable to find view code for view mode " + str(view_mode) +
             " and skin " + skin_name)


import kodi
addon_id = kodi.get_id()
__settings__ = xbmcaddon.Addon(id=addon_id)
__language__ = __settings__.getLocalizedString
Exemple #29
0
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""
import functools
import log_utils
import time
import cPickle as pickle
import hashlib
import os
import shutil
import kodi

cache_path = kodi.translate_path('special://temp/%s/cache/' % kodi.get_id())
try:
    if not os.path.exists(cache_path):
        os.makedirs(cache_path)
except Exception as e:
    log_utils.log('Failed to create cache: %s: %s' % (cache_path, e), log_utils.LOGWARNING)

cache_enabled = kodi.get_setting('use_cache') == 'true'


def make_cache_path():
    try:
        if not os.path.exists(cache_path):
            os.makedirs(cache_path)
    except Exception as e:
        log_utils.log('Failed to create cache: %s: %s' % (cache_path, e), log_utils.LOGWARNING)
import os
import re
import sys
import urllib
import urllib2
import urlparse
from resources.lib.modules import utils
import xxxtext

import kodi
import pyxbmct.addonwindow as pyxbmct

#############################################################
#################### SET ADDON ID ###########################
_self_          = xbmcaddon.Addon(id=kodi.get_id())

#############################################################
#################### SET ADDON THEME IMAGES #################
ART = xbmc.translatePath(os.path.join('special://home/addons/script.xxxodus.artwork', 'resources/pyxbmct/issues'))

Background_Image    = os.path.join(ART, 'bg.png')
Button  = os.path.join(ART, 'close.png')
ButtonF = os.path.join(ART, 'closef.png')
Open    = os.path.join(ART, 'numbers/not-selected/open/%s.png')
Open_Selected   = os.path.join(ART, 'numbers/selected/open/%s.png')
Closed  = os.path.join(ART, 'numbers/not-selected/closed/%s.png')
Closed_Seleted  = os.path.join(ART, 'numbers/selected/closed/%s.png')

def githubSelect(name):
    import githubissues
Exemple #31
0
def selector(option_list,title="Select one"):
    _log("selector title='"+title+"', options="+repr(option_list))
    dia=xbmcgui.Dialog(); selection=dia.select(title,option_list)
    return selection
def set_view(view_mode, view_code=0):
    _log("set_view view_mode='"+view_mode+"', view_code="+str(view_code))
    # Set the content for extended library views if needed
    if view_mode==MOVIES: _log("set_view content is movies"); xbmcplugin.setContent( int(sys.argv[1]) ,"movies" )
    elif view_mode==TV_SHOWS: _log("set_view content is tvshows"); xbmcplugin.setContent( int(sys.argv[1]) ,"tvshows" )
    elif view_mode==SEASONS: _log("set_view content is seasons"); xbmcplugin.setContent( int(sys.argv[1]) ,"seasons" )
    elif view_mode==EPISODES: _log("set_view content is episodes"); xbmcplugin.setContent( int(sys.argv[1]) ,"episodes" )
    skin_name=xbmc.getSkinDir() # Reads skin name
    _log("set_view skin_name='"+skin_name+"'")
    try:
        if view_code==0:
            _log("set_view view mode is "+view_mode)
            view_codes=ALL_VIEW_CODES.get(view_mode)
            view_code=view_codes.get(skin_name)
            _log("set_view view code for "+view_mode+" in "+skin_name+" is "+str(view_code))
            xbmc.executebuiltin("Container.SetViewMode("+str(view_code)+")")
        else:
            _log("set_view view code forced to "+str(view_code))
            xbmc.executebuiltin("Container.SetViewMode("+str(view_code)+")")
    except:
        _log("Unable to find view code for view mode "+str(view_mode)+" and skin "+skin_name)


import kodi
addon_id = kodi.get_id()
__settings__=xbmcaddon.Addon(id=addon_id); __language__=__settings__.getLocalizedString
Exemple #32
0
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""
import functools
import log_utils
import time
import cPickle as pickle
import hashlib
import os
import shutil
import kodi

cache_path = kodi.translate_path('special://temp/%s/cache/' % kodi.get_id())
try:
    if not os.path.exists(cache_path):
        os.makedirs(cache_path)
except Exception as e:
    log_utils.log('Failed to create cache: %s: %s' % (cache_path, e),
                  log_utils.LOGWARNING)

cache_enabled = kodi.get_setting('use_cache') == 'true'


def make_cache_path():
    try:
        if not os.path.exists(cache_path):
            os.makedirs(cache_path)
    except Exception as e:
Exemple #33
0
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
    
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.
    
    You should have received a copy of the GNU General Public License
    along with this program. If not, see <http://www.gnu.org/licenses/>.
"""

import kodi
from url_dispatcher import URL_Dispatcher


def __enum(**enums):
    return type('Enum', (), enums)


DISPATCHER = URL_Dispatcher()

MODES = __enum(MAIN='main', PLAY='play', OPEN='open')

DIRECTORIES = __enum(
    DATA=kodi.translate_path('special://profile/addon_data/%s/' %
                             kodi.get_id()))

ICONS = __enum(ADDON=kodi.translate_path(
    'special://home/addons/{0!s}/icon.png'.format(kodi.get_id())))