Пример #1
0
    def rename(path, newpath):
        log("FileAccess: rename " + path + " to " + newpath)

        try:
            if xbmcvfs.rename(path, newpath):
                return True
        except Exception as e: 
            log("FileAccess: rename, Failed! %s"%(e), xbmc.LOGERROR)

        if path[0:6].lower() == 'smb://' or newpath[0:6].lower() == 'smb://':
            if os.name.lower() == 'nt':
                log("FileAccess: Modifying name")
                if path[0:6].lower() == 'smb://':
                    path = '\\\\' + path[6:]

                if newpath[0:6].lower() == 'smb://':
                    newpath = '\\\\' + newpath[6:]

        try:
            log("FileAccess: os.rename")
            os.rename(xbmcvfs.translatePath(path), xbmcvfs.translatePath(newpath))
            return True
        except Exception as e: 
            log("FileAccess: rename, Failed! %s"%(e), xbmc.LOGERROR)

        try:
            log("FileAccess: shutil.move")
            shutil.move(xbmcvfs.translatePath(path), xbmcvfs.translatePath(newpath))
            return True
        except Exception as e: 
            log("FileAccess: rename, Failed! %s"%(e), xbmc.LOGERROR)

        log("FileAccess: OSError")
        raise OSError()
Пример #2
0
    def _makedirs(path):
        if len(path) == 0:
            return False

        if(xbmcvfs.exists(path)):
            return True

        success = xbmcvfs.mkdir(path)
        if success == False:
            if path == os.path.dirname(xbmcvfs.translatePath(path)):
                return False

            if FileAccess._makedirs(os.path.dirname(xbmcvfs.translatePath(path))):
                return xbmcvfs.mkdir(path)
        return xbmcvfs.exists(path)
Пример #3
0
    def writeLastRun(self):
        runFile = xbmcvfs.File(
            xbmcvfs.translatePath(utils.data_dir() + "last_run.txt"), 'w')
        runFile.write(str(self.last_run))
        runFile.close()

        self.showNotify(True)
Пример #4
0
def searchHistoryPush(title):
    addonUserDataFolder = xbmcvfs.translatePath(
        "special://profile/addon_data/plugin.video.orftvthek")
    json_file = os.path.join(addonUserDataFolder, 'searchhistory.json')
    title = unqoute_url(title)
    title = title.replace("+", " ").strip()
    # check if file exists
    if os.path.exists(json_file):
        # check if file already has an entry
        if os.path.getsize(json_file) > 0:
            # append value to JSON File
            data = getJsonFile(json_file)
            data.append(title)
            saveJsonFile(data, json_file)
        # found empty file - writing first record
        else:
            data = []
            data.append(title)
            saveJsonFile(data, json_file)
    # create json file
    else:
        if not os.path.exists(addonUserDataFolder):
            os.makedirs(addonUserDataFolder)
        data = []
        data.append(title)
        saveJsonFile(data, json_file)
Пример #5
0
def showNotification(title, message):
    xbmcgui.Dialog().notification(getString(30000),
                                  message,
                                  time=5000,
                                  icon=xbmcvfs.translatePath(
                                      __Addon.getAddonInfo('path') +
                                      "/resources/media/icon.png"),
                                  sound=False)
Пример #6
0
    def readLastRun(self):
        if (self.last_run == 0):
            # read it in from the settings
            if (xbmcvfs.exists(
                    xbmcvfs.translatePath(utils.data_dir() + "last_run.txt"))):

                runFile = xbmcvfs.File(
                    xbmcvfs.translatePath(utils.data_dir() + "last_run.txt"))

                try:
                    # there may be an issue with this file, we'll get it the next time through
                    self.last_run = float(runFile.read())
                except ValueError:
                    self.last_run = 0

                runFile.close()
            else:
                self.last_run = 0
Пример #7
0
def searchHistoryGet():
    addonUserDataFolder = xbmcvfs.translatePath(
        "special://profile/addon_data/plugin.video.orftvthek")
    json_file = os.path.join(addonUserDataFolder, 'searchhistory.json')
    if os.path.exists(json_file):
        if os.path.getsize(json_file) > 0:
            data = getJsonFile(json_file)
            return data
    return []
Пример #8
0
def translate_path(path):
    '''
    Use new library location for translate path starting in Kodi 19
    '''
    version = kodi_version()

    if version > 18:
        return xbmcvfs.translatePath(path)
    else:
        return xbmc.translatePath(path)
    def get_media_url(self, host, media_id):
        video = None
        web_url = self.get_url(host, media_id)

        if xbmc.getCondVisibility(
                'System.HasAddon(plugin.googledrive)') and self.get_setting(
                    'use_gdrive') == "true":
            addon = xbmcaddon.Addon('plugin.googledrive')
            if six.PY3:
                db = xbmcvfs.translatePath(
                    addon.getAddonInfo('profile')) + 'accounts.db'
            else:
                db = xbmc.translatePath(
                    addon.getAddonInfo('profile')) + 'accounts.db'
            conn = sqlite3.connect(db)
            c = conn.cursor()
            c.execute("SELECT key FROM store;")
            driveid = c.fetchone()[0]
            conn.close()

            doc_id = re.search(r'[-\w]{25,}', web_url)
            if doc_id:
                common.kodi.notify(header=None,
                                   msg='Resolving with Google Drive',
                                   duration=3000)
                video = 'plugin://plugin.googledrive/?action=play&content_type=video&driveid={0}&item_id={1}'.format(
                    driveid, doc_id.group(0))

        if not video:
            response, video_urls = self._parse_google(web_url)
            if video_urls:
                video_urls.sort(key=self.__key, reverse=True)
                video = helpers.pick_source(video_urls)

            if response is not None:
                res_headers = response.get_headers(as_dict=True)
                if 'Set-Cookie' in res_headers:
                    self.headers['Cookie'] = res_headers['Set-Cookie']

        if not video:
            if any(url_match in web_url for url_match in self.url_matches):
                video = self._parse_redirect(web_url, hdrs=self.headers)
            elif 'googlevideo.' in web_url:
                video = web_url + helpers.append_headers(self.headers)
        elif 'plugin://' not in video:
            if any(url_match in video for url_match in self.url_matches):
                video = self._parse_redirect(video, hdrs=self.headers)

        if video:
            if 'plugin://' in video:  # google plus embedded videos may result in this
                return video
            else:
                return video + helpers.append_headers(self.headers)

        raise ResolverError('File not found')
Пример #10
0
def showNotification(message,
                     time_ms=3000,
                     icon_path=None,
                     header=ADDON.getAddonInfo('name')):
    try:
        icon_path = icon_path or xbmcvfs.translatePath(
            ADDON.getAddonInfo('icon'))
        xbmc.executebuiltin('Notification({0},{1},{2},{3})'.format(
            header, message, time_ms, icon_path))
    except RuntimeError:  # Happens when disabling the addon
        LOG(message)
Пример #11
0
def checkBlacklist(title):
    addonUserDataFolder = xbmcvfs.translatePath(
        "special://profile/addon_data/plugin.video.orftvthek")
    bl_json_file = os.path.join(addonUserDataFolder, 'blacklist.json')
    if os.path.exists(bl_json_file):
        if os.path.getsize(bl_json_file) > 0:
            data = getJsonFile(bl_json_file)
            tmp = data
            for item in tmp:
                if py2_decode(item) == py2_decode(title):
                    return True
    return False
Пример #12
0
def removeBlacklist(title):
    addonUserDataFolder = xbmcvfs.translatePath(
        "special://profile/addon_data/plugin.video.orftvthek")
    bl_json_file = os.path.join(addonUserDataFolder, 'blacklist.json')
    if os.path.exists(bl_json_file):
        if os.path.getsize(bl_json_file) > 0:
            data = getJsonFile(bl_json_file)
            tmp = data
            for item in tmp:
                if item.encode('UTF-8') == title:
                    tmp.remove(item)
            saveJsonFile(tmp, bl_json_file)
Пример #13
0
def printBlacklist(banner, backdrop, translation, pluginhandle):
    addonUserDataFolder = xbmcvfs.translatePath(
        "special://profile/addon_data/plugin.video.orftvthek")
    bl_json_file = os.path.join(addonUserDataFolder, 'blacklist.json')
    if os.path.exists(bl_json_file):
        if os.path.getsize(bl_json_file) > 0:
            data = getJsonFile(bl_json_file)
            for item in data:
                item = item.encode('UTF-8')
                description = translation(30040).encode('UTF-8') % item
                parameters = {'link': item, 'mode': 'unblacklistShow'}
                url = build_kodi_url(parameters)
                createListItem(item, banner, description, None, None, None,
                               url, False, False, backdrop, pluginhandle)
Пример #14
0
class ADOBE:
    REGGIE_FQDN = 'http://api.auth.adobe.com'
    SP_FQDN = 'http://sp.auth.adobe.com'
    app_id = ''
    app_version = ''
    device_id = ''
    device_type = ''
    device_user = ''
    headers = {
        'Accept':
        '*/*',
        'Content-type':
        'application/x-www-form-urlencoded',
        'Accept-Language':
        'en-US',
        'User-Agent':
        'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
        'Chrome/43.0.2357.81 Safari/537.36',
        'Connection':
        'Keep-Alive',
        'Pragma':
        'no-cache'
    }
    mvpd_id = ''
    private_key = ''
    public_key = ''
    reg_code = ''
    registration_url = ''
    requestor_id = ''
    resource_id = ''
    if sys.version_info[0] > 2:
        sso_path = xbmcvfs.translatePath(
            xbmcaddon.Addon().getAddonInfo('profile'))
    else:
        sso_path = xbmc.translatePath(
            xbmcaddon.Addon().getAddonInfo('profile'))
    local_string = xbmcaddon.Addon(
        'script.module.adobepass').getLocalizedString
    verify = False

    def __init__(self, service_vars):
        # service_vars is a dictionary type variable (key: value)
        self.device_id = self.get_device_id()

        # Mandatory Parameters
        self.requestor_id = service_vars['requestor_id']
        self.public_key = service_vars['public_key']
        self.private_key = service_vars['private_key']
        self.registration_url = service_vars['registration_url']
        self.resource_id = service_vars['resource_id']

        # Optional Parameters
        if 'app_id' in service_vars: self.app_id = service_vars['app_id']
        if 'app_version' in service_vars:
            self.app_version = service_vars['app_version']
        if 'device_type' in service_vars:
            self.device_type = service_vars['device_type']
        if 'device_user' in service_vars:
            self.device_user = service_vars['device_user']
        if 'mvpd_id' in service_vars: self.mvpd_id = service_vars['mvpd_id']

    def get_device_id(self):
        file_name = os.path.join(self.sso_path, 'device.id')
        if not os.path.isfile(file_name):
            if not os.path.exists(self.sso_path):
                os.makedirs(self.sso_path)
            new_device_id = str(uuid.uuid1())
            device_file = open(file_name, 'w')
            device_file.write(new_device_id)
            device_file.close()

        file_name = os.path.join(self.sso_path, 'device.id')
        device_file = open(file_name, 'r')
        device_id = device_file.readline()
        device_file.close()

        return device_id

    def create_authorization(self, request_method, request_uri):
        nonce = str(uuid.uuid4())
        epoch_time = str(int(time.time() * 1000))
        authorization = "%s requestor_id=%s, nonce=%s, signature_method=HMAC-SHA1, request_time=%s, request_uri=%s" % \
                        (request_method, self.requestor_id, nonce, epoch_time, request_uri)
        signature = hmac.new(codecs.encode(self.private_key),
                             codecs.encode(authorization), hashlib.sha1)
        signature = codecs.decode(base64.b64encode(signature.digest()))
        authorization += ", public_key=" + self.public_key + ", signature=" + signature

        return authorization

    def register_device(self):
        """
        <REGGIE_FQDN>/reggie/v1/{requestorId}/regcode
        Returns randomly generated registration Code and login Page URI
        """
        reggie_url = '/reggie/v1/' + self.requestor_id + '/regcode'
        self.headers['Authorization'] = self.create_authorization(
            'POST', reggie_url)

        url = self.REGGIE_FQDN + reggie_url

        payload = 'registrationURL='
        if self.registration_url != '':
            payload += self.registration_url
        else:
            payload += self.SP_FQDN + '/adobe-services'

        payload += '&ttl=3600'
        payload += '&deviceId=' + self.device_id
        payload += '&format=json'
        if self.app_id != '': payload += '&appId=' + self.app_id
        if self.app_version != '': payload += '&appVersion=' + self.app_version
        if self.device_type != '': payload += '&deviceType=' + self.device_type
        if self.mvpd_id != '': payload += '&mvpd=' + self.mvpd_id

        r = requests.post(url,
                          headers=self.headers,
                          cookies=self.load_cookies(),
                          data=payload,
                          verify=self.verify)
        self.reg_code = str(r.json()['code'])

        msg = self.local_string(
            30010
        ) + '[B][COLOR yellow]' + self.registration_url + '[/COLOR][/B][CR]'
        msg += self.local_string(30011) + '[CR]'
        msg += self.local_string(
            30012
        ) + '[B][COLOR yellow]' + self.reg_code + '[/COLOR][/B]' + self.local_string(
            30013)

        dialog = xbmcgui.Dialog()
        dialog.ok(self.local_string(30009), msg)

    def pre_auth(self):
        """
        <SP_FQDN>/api/v1/preauthorize
        Retrieves the list of preauthorized resource
        """
        pre_auth_url = '/api/v1/preauthorize'
        self.headers['Authorization'] = self.create_authorization(
            'GET', pre_auth_url)

        url = self.REGGIE_FQDN + preauth_url
        url += '?deviceId=' + self.device_id
        url += '&requestor=' + self.requestor_id
        url += '&resource=' + self.resource_id
        url += '&format=json'

        requests.get(url,
                     headers=self.headers,
                     cookies=self.load_cookies(),
                     verify=self.verify)

    def authorize(self):
        """
        <SP_FQDN>/api/v1/authorize
        Obtains authorization response

        200 - Success
        403 - No Success
        """
        auth_url = '/api/v1/authorize'
        self.headers['Authorization'] = self.create_authorization(
            'GET', auth_url)

        url = self.REGGIE_FQDN + auth_url
        url += '?deviceId=' + self.device_id
        url += '&requestor=' + self.requestor_id
        url += '&resource=' + self.resource_id
        url += '&format=json'

        r = requests.get(url,
                         headers=self.headers,
                         cookies=self.load_cookies(),
                         verify=self.verify)
        self.save_cookies(r.cookies)

        if not r.ok:
            title = self.local_string(30014)
            if 'message' in r.json() and 'details' in r.json():
                title = r.json()['message']
                msg = r.json()['details']
            elif 'message' in r.json():
                msg = r.json()['message']
            else:
                msg = r.text
            dialog = xbmcgui.Dialog()
            dialog.ok(title, msg)
            return False
        else:
            return True

    def logout(self):
        """
        <SP_FQDN>/api/v1/logout
        Remove AuthN and AuthZ tokens from storage
        """
        auth_url = '/api/v1/logout'
        self.headers['Authorization'] = self.create_authorization(
            'DELETE', auth_url)

        url = self.REGGIE_FQDN + auth_url
        url += '?deviceId=' + self.device_id
        url += '&requestor=' + self.requestor_id
        url += '&format=json'

        r = requests.delete(url,
                            headers=self.headers,
                            cookies=self.load_cookies(),
                            verify=self.verify)

        if r.status_code == 204:
            dialog = xbmcgui.Dialog()
            dialog.notification(self.local_string(30015),
                                self.local_string(30016), '', 3000, False)

    def media_token(self):
        """
        <SP_FQDN>/api/v1/mediatoken
        Obtains Short Media Token
        """
        token_url = '/api/v1/mediatoken'
        self.headers['Authorization'] = self.create_authorization(
            'GET', token_url)

        url = self.REGGIE_FQDN + token_url
        url += '?deviceId=' + self.device_id
        url += '&requestor=' + self.requestor_id
        url += '&resource=' + self.resource_id
        url += '&format=json'

        r = requests.get(url,
                         headers=self.headers,
                         cookies=self.load_cookies(),
                         verify=self.verify)
        self.save_cookies(r.cookies)

        if r.ok:
            return r.json()['serializedToken']
        else:
            if 'details' in r.json():
                msg = r.json()['details']
            else:
                msg = r.text

            dialog = xbmcgui.Dialog()
            dialog.ok(self.local_string(30017), msg)
            return ''

    def get_authn(self):
        """
        <SP_FQDN>/api/v1/tokens/authn
        Returns the AuthN token if found

        200 - Success
        404 - Not Found
        410 - Expired
        """
        authn_url = '/api/v1/tokens/authn'
        self.headers['Authorization'] = self.create_authorization(
            'GET', authn_url)

        url = self.SP_FQDN + authn_url
        url += '?deviceId=' + self.device_id
        url += '&requestor=' + self.requestor_id
        url += '&resource=' + self.resource_id
        url += '&format=json'

        r = requests.get(url,
                         headers=self.headers,
                         cookies=self.load_cookies(),
                         verify=self.verify)
        self.save_cookies(r.cookies)

        auth_info = ''
        if 'mvpd' in r.json():
            auth_info = 'Provider: ' + json_source['mvpd']
        if 'expires' in r.json():
            auth_info += ' expires on ' + json_source['expires']

        return auth_info

    def check_authn(self):
        """
        <SP_FQDN>/api/v1/checkauthn
        Indicates whether the device has an unexpired AuthN token.

        200 - Success
        403 - No Success
        """
        authn_url = '/api/v1/checkauthn'
        self.headers['Authorization'] = self.create_authorization(
            'GET', authn_url)

        url = self.SP_FQDN + authn_url
        url += '?deviceId=' + self.device_id
        url += '&format=json'

        r = requests.get(url,
                         headers=self.headers,
                         cookies=self.load_cookies(),
                         verify=self.verify)
        self.save_cookies(r.cookies)

        if r.ok:
            return True
        else:
            return False

    def get_authz(self):
        """
        <SP_FQDN>/api/v1/tokens/authz
        Returns the AuthZ token if found

        200 - Success
        412 - No AuthN
        404 - No AuthZ
        410 - AuthZ Expired
        """
        authz_url = '/api/v1/tokens/authz'
        self.headers['Authorization'] = self.create_authorization(
            'GET', authz_url)

        url = self.SP_FQDN + authz_url
        url += '?deviceId=' + self.device_id
        url += '&requestor=' + self.requestor_id
        url += '&resource=' + self.resource_id
        url += '&format=json'

        r = requests.get(url,
                         headers=self.headers,
                         cookies=self.load_cookies(),
                         verify=self.verify)
        self.save_cookies(r.cookies)

        if not r.ok:
            title = self.local_string(30019) + str(r.status_code)
            if 'message' in r.json():
                title = r.json()['message']
            if 'details' in r.json():
                msg = r.json()['details']
            else:
                msg = r.text

            dialog = xbmcgui.Dialog()
            dialog.ok(title, msg)
            return ''

    def save_cookies(self, cookiejar):
        cookie_file = os.path.join(self.sso_path, 'cookies.lwp')
        cj = cookielib.LWPCookieJar()
        try:
            cj.load(cookie_file, ignore_discard=True)
        except:
            pass
        for c in cookiejar:
            args = dict(vars(c).items())
            args['rest'] = args['_rest']
            del args['_rest']
            c = cookielib.Cookie(**args)
            cj.set_cookie(c)
        cj.save(cookie_file, ignore_discard=True)

    def load_cookies(self):
        cookie_file = os.path.join(self.sso_path, 'cookies.lwp')
        cj = cookielib.LWPCookieJar()
        try:
            cj.load(cookie_file, ignore_discard=True)
        except:
            pass

        return cj
Пример #15
0

"""
import re
from six.moves import urllib_parse
import six
import sys
import xbmcaddon
try:
    from kodi_six import xbmcvfs, xbmcgui
except:
    import xbmcvfs
    import xbmcgui    
# insert at 1, 0 is the script path (or '' in REPL)
try:
    home = xbmcvfs.translatePath(xbmcaddon.Addon('plugin.video.OneX.Matrix').getAddonInfo('path').decode('utf-8'))
except:
    home = xbmcvfs.translatePath(xbmcaddon.Addon('plugin.video.OneX.Matrix').getAddonInfo('path'))
sys.path.insert(1, home+'/lib')
from resolveurl import common
from resolveurl.hmf import HostedMediaFile
from resolveurl.resolver import ResolveUrl
from resolveurl.plugins.__resolve_generic__ import ResolveGeneric
from resolveurl.plugins import *  # NOQA

common.logger.log_debug('Initializing ResolveURL version: %s' % common.addon_version)
MAX_SETTINGS = 75

PLUGIN_DIRS = []
host_cache = {}
Пример #16
0
    from urllib.parse import urlparse, parse_qs, quote, unquote, quote_plus, unquote_plus, urlencode  #python 3
except ImportError:
    from urlparse import urlparse, parse_qs  #python 2
    from urllib import quote, unquote, quote_plus, unquote_plus, urlencode
from kodi_six import xbmc, xbmcvfs, xbmcgui, xbmcplugin, xbmcaddon

plugin = sys.argv[0]
handle = int(sys.argv[1])
addon = xbmcaddon.Addon()
addonname = addon.getAddonInfo('name')
icon = addon.getAddonInfo('icon')
stream = 'https://5d2c98775bafe.streamlock.net:443/8090/8090/playlist.m3u8'
info = 'Canal Ricos, Perus, São Paulo\n\nWhatsapp: (11) 98870-0735'

if six.PY3:
    profile = xbmcvfs.translatePath(addon.getAddonInfo('profile'))
    home = xbmcvfs.translatePath(addon.getAddonInfo('path'))
else:
    profile = xbmc.translatePath(addon.getAddonInfo('profile')).decode('utf-8')
    home = xbmc.translatePath(addon.getAddonInfo('path')).decode('utf-8')

fanart_default = os.path.join(home, 'fanart.png')


def get_url(params):
    url = '%s?%s' % (plugin, urlencode(params))
    return url


def item(params, folder=True):
    url = get_url(params)
Пример #17
0
dateshort_format = xbmc.getRegion('dateshort')
time_format = xbmc.getRegion('time').replace('%H%H', '%H')
format = "%s %s" % (dateshort_format, time_format.replace(':%S', ''))
#log((date,dateshort_format,time_format,format))
start_time = datetime.datetime.fromtimestamp(
    time.mktime(time.strptime(date, format)))
timezone = tzlocal.get_localzone()
start_time = timezone.localize(start_time)
utc = pytz.timezone('utc')
start_time = start_time.astimezone(utc)
start_time = start_time.replace(tzinfo=None)

#log((channel, start_time))

conn = sqlite3.connect(xbmcvfs.translatePath(
    'special://profile/addon_data/plugin.video.iptv.recorder/xmltv.db'),
                       detect_types=sqlite3.PARSE_DECLTYPES
                       | sqlite3.PARSE_COLNAMES)
cursor = conn.cursor()
try:
    #log(channel)
    channel_id = cursor.execute('SELECT tvg_id FROM streams WHERE name=?',
                                (channel, )).fetchone()[0]
    if not channel_id:
        channel_id = cursor.execute(
            'SELECT tvg_id FROM streams WHERE tvg_name=?',
            (channel, )).fetchone()[0]
    #log(channel_id)
    if channel_id:
        program_id = cursor.execute(
            'SELECT uid FROM programmes WHERE channelid=? AND start=?',
Пример #18
0
def check_data_dir():
    if (not xbmcvfs.exists(xbmcvfs.translatePath(data_dir()))):
        xbmcvfs.mkdir(xbmcvfs.translatePath(data_dir()))
Пример #19
0
 def makedirs(directory):
     try:
         os.makedirs(xbmcvfs.translatePath(directory))
         return True
     except:
         return FileAccess._makedirs(directory)
Пример #20
0
 def exists(filename):
     try:
         return xbmcvfs.exists(filename)
     except UnicodeDecodeError:
         return os.path.exists(xbmcvfs.translatePath(filename))
     return False
Пример #21
0
from .kodijsonrpc import rpc
from kodi_six import xbmc
from kodi_six import xbmcgui
from kodi_six import xbmcaddon
from kodi_six import xbmcvfs

from plexnet import signalsmixin
import six

DEBUG = True
_SHUTDOWN = False

ADDON = xbmcaddon.Addon()

PROFILE = xbmcvfs.translatePath(ADDON.getAddonInfo('profile'))

SETTINGS_LOCK = threading.Lock()

_splitver = xbmc.getInfoLabel('System.BuildVersion').split()[0].split(".")
KODI_VERSION_MAJOR, KODI_VERSION_MINOR = int(_splitver[0].split("-")[0]), int(
    _splitver[1].split("-")[0])


class UtilityMonitor(xbmc.Monitor, signalsmixin.SignalsMixin):
    def __init__(self, *args, **kwargs):
        xbmc.Monitor.__init__(self, *args, **kwargs)
        signalsmixin.SignalsMixin.__init__(self)

    def watchStatusChanged(self):
        self.trigger('changed.watchstatus')
Пример #22
0
try:
    from kodi_six.xbmcvfs import translatePath
except (ImportError, AttributeError):
    from kodi_six.xbmc import translatePath

try:
    from typing import Text, Dict, Callable, Generator  # pylint: disable=unused-import
except ImportError:
    pass

ADDON = Addon()
ADDON_ID = ADDON.getAddonInfo('id')
ADDON_NAME = ADDON.getAddonInfo('name')
ADDON_VERSION = ADDON.getAddonInfo('version')
ADDON_PROFILE_DIR = translatePath(ADDON.getAddonInfo('profile'))
ADDON_DIR = translatePath(ADDON.getAddonInfo('path'))
ADDON_ICON = translatePath(ADDON.getAddonInfo('icon'))

if not os.path.exists(ADDON_PROFILE_DIR):
    os.mkdir(ADDON_PROFILE_DIR)


class logger(object):  # pylint: disable=invalid-name
    # pylint: disable=missing-docstring
    FORMAT = '{id} [v.{version}] - {filename}:{lineno} - {message}'

    @classmethod
    def _write_message(cls, message, level=xbmc.LOGDEBUG):
        # type: (Text, int) -> None
        curr_frame = inspect.currentframe()
Пример #23
0
def translate_path(path):
    return xbmcvfs.translatePath(path) if six.PY3 else xbmc.translatePath(path)
Пример #24
0
import calendar
import codecs
from datetime import datetime, timedelta
from kodi_six import xbmc, xbmcplugin, xbmcgui, xbmcaddon, xbmcvfs

if sys.version_info[0] > 2:
    import http
    cookielib = http.cookiejar
    urllib = urllib.parse
else:
    import cookielib

# KODI ADDON GLOBALS
ADDON_HANDLE = int(sys.argv[1])
if sys.version_info[0] > 2:
    ADDON_PATH_PROFILE = xbmcvfs.translatePath(
        xbmcaddon.Addon().getAddonInfo('profile'))
else:
    ADDON_PATH_PROFILE = xbmc.translatePath(
        xbmcaddon.Addon().getAddonInfo('profile'))
LOCAL_STRING = xbmcaddon.Addon().getLocalizedString
ROOTDIR = xbmcaddon.Addon().getAddonInfo('path')
ICON = os.path.join(ROOTDIR, "icon.png")
FANART = os.path.join(ROOTDIR, "fanart.jpg")
ROOT_URL = 'http://stream.nbcsports.com/data/mobile'
CONFIG_URL = 'https://stream.nbcsports.com/data/mobile/apps/NBCSports/configuration-vjs.json'

# Main settings
settings = xbmcaddon.Addon()
FREE_ONLY = str(settings.getSetting("free_only"))
KODI_VERSION = float(
    re.findall(r'\d{2}\.\d{1}', xbmc.getInfoLabel("System.BuildVersion"))[0])
Пример #25
0
# coding: utf-8

from __future__ import unicode_literals

import os

from kodi_six import xbmcaddon

try:
    from kodi_six.xbmcvfs import translatePath
except (ImportError, AttributeError):
    from kodi_six.xbmc import translatePath

__all__ = ['ADDON_ID', 'addon', 'path', 'profile', 'icon', 'get_ui_string']

ADDON_ID = 'service.subtitles.rvm.addic7ed'
addon = xbmcaddon.Addon(ADDON_ID)
path = translatePath(addon.getAddonInfo('path'))
profile = translatePath(addon.getAddonInfo('profile'))
icon = os.path.join(path, 'icon.png')


def get_ui_string(string_id):
    """
    Get language string by ID

    :param string_id: UI string ID
    :return: UI string
    """
    return addon.getLocalizedString(string_id)
Пример #26
0
class CustomPathFile:
    jsonFile = xbmcvfs.translatePath(utils.data_dir() + "custom_paths.json")
    paths = None
    contentType = 'video'  # all by default

    def __init__(self, contentType):
        self.paths = []
        self.contentType = contentType

        # try and read in the custom file
        self._readFile()

    def getSchedules(self, showDialogs=True):
        schedules = []

        # create schedules from the path information
        for aPath in self.paths:
            if (self.contentType == aPath['content']):
                schedules.append(self._createSchedule(aPath, showDialogs))

        return schedules

    def addPath(self, path):
        path['id'] = self._getNextId()
        self.paths.append(path)

        # save the file
        self._writeFile()

    def deletePath(self, aKey):
        # find the given key
        index = -1
        for i in range(0, len(self.paths)):
            if (self.paths[i]['id'] == aKey):
                index = i

        # if found, delete it
        if (i != -1):
            del self.paths[index]

        # save the file
        self._writeFile()

    def getPaths(self):
        result = []

        for aPath in self.paths:
            # if type matches the one we want
            if (self.contentType == 'all'
                    or self.contentType == aPath['content']):
                result.append(aPath)

        return result

    def _getNextId(self):
        result = 0

        if (len(self.paths) > 0):
            # sort ids, get highest one
            maxId = sorted(self.paths, reverse=True, key=lambda k: k['id'])
            result = maxId[0]['id']

        return result + 1

    def _writeFile(self):
        # sort the ids
        self.paths = sorted(self.paths, reverse=True, key=lambda k: k['id'])

        # create the custom file
        aFile = xbmcvfs.File(self.jsonFile, 'w')
        aFile.write(json.dumps(self.paths))
        aFile.close()

    def _readFile(self):

        if (xbmcvfs.exists(self.jsonFile)):

            # read in the custom file
            aFile = xbmcvfs.File(self.jsonFile)

            # load paths in the format {path:path,expression:expression,content:type}
            tempPaths = json.loads(aFile.read())

            # update values in path
            for aPath in tempPaths:

                # old files are only video, update
                if ('content' not in aPath):
                    aPath['content'] = 'video'

                if ('id' not in aPath):
                    aPath['id'] = self._getNextId()

                self.paths.append(aPath)

            aFile.close()
        else:
            # write a blank file
            self._writeFile()

    def _createSchedule(self, aPath, showDialogs):

        aSchedule = CronSchedule()
        aSchedule.name = aPath['path']

        # command depends on content type
        if (aPath['content'] == 'video'):
            aSchedule.command = {
                'method': 'VideoLibrary.Scan',
                'params': {
                    'directory': aPath['path'],
                    'showdialogs': showDialogs
                }
            }
        else:
            aSchedule.command = {
                'method': 'AudioLibrary.Scan',
                'params': {
                    'directory': aPath['path'],
                    'showdialogs': showDialogs
                }
            }

        aSchedule.expression = aPath['expression']

        return aSchedule