Пример #1
0
def download(name, image, url):

    from resources.lib.modules import control

    if url == None:
        return control.infoDialog(control.lang(30501).encode('utf-8'))

    try: headers = dict(urlparse.parse_qsl(url.rsplit('|', 1)[1]))
    except: headers = dict('')

    url = url.split('|')[0]

    content = re.compile('(.+?)\sS(\d*)E\d*$').findall(name)
    transname = name.translate(None, '\/:*?"<>|').strip('.')
    levels =['../../../..', '../../..', '../..', '..']

    if len(content) == 0:
        dest = control.setting('movie.download.path')
        dest = control.transPath(dest)
        for level in levels:
            try: control.makeFile(os.path.abspath(os.path.join(dest, level)))
            except: pass
        control.makeFile(dest)
        dest = os.path.join(dest, transname)
        control.makeFile(dest)
    else:
        dest = control.setting('tv.download.path')
        dest = control.transPath(dest)
        for level in levels:
            try: control.makeFile(os.path.abspath(os.path.join(dest, level)))
            except: pass
        control.makeFile(dest)
        transtvshowtitle = content[0][0].translate(None, '\/:*?"<>|').strip('.')
        dest = os.path.join(dest, transtvshowtitle)
        control.makeFile(dest)
        dest = os.path.join(dest, 'Season %01d' % int(content[0][1]))
        control.makeFile(dest)

    ext = os.path.splitext(urlparse.urlparse(url).path)[1][1:]
    if not ext in ['mp4', 'mkv', 'flv', 'avi', 'mpg']: ext = 'mp4'
    dest = os.path.join(dest, transname + '.' + ext)

    sysheaders = urllib.quote_plus(json.dumps(headers))

    sysurl = urllib.quote_plus(url)

    systitle = urllib.quote_plus(name)

    sysimage = urllib.quote_plus(image)

    sysdest = urllib.quote_plus(dest)

    script = inspect.getfile(inspect.currentframe())
    cmd = 'RunScript(%s, %s, %s, %s, %s, %s)' % (script, sysurl, sysdest, systitle, sysimage, sysheaders)

    xbmc.executebuiltin(cmd)
Пример #2
0
    def __init__(self):
        self.library_folder = os.path.join(control.transPath(control.setting('library.movie')), '')

        self.check_setting = control.setting('library.check_movie') or 'false'
        self.library_setting = control.setting('library.update') or 'true'
        self.dupe_setting = control.setting('library.check') or 'true'
        self.silentDialog = False
        self.infoDialog = False
Пример #3
0
    def __init__(self):
        self.library_folder = os.path.join(control.transPath(control.setting("tv_library")), "")

        self.library_setting = control.setting("update_library") or "true"
        self.property = "%s_service_property" % control.addonInfo("name").lower()

        self.datetime = datetime.datetime.utcnow() - datetime.timedelta(hours=5)
        self.date = (self.datetime - datetime.timedelta(hours=24)).strftime("%Y%m%d")

        self.infoDialog = False
Пример #4
0
    def __init__(self):
        self.library_folder = os.path.join(control.transPath(control.setting('library.tv')),'')

        self.library_setting = control.setting('library.update') or 'true'
        self.include_unknown = control.setting('library.include_unknown') or 'true'
        self.property = '%s_service_property' % control.addonInfo('name').lower()

        self.datetime = (datetime.datetime.utcnow() - datetime.timedelta(hours = 5))
        self.date = (self.datetime - datetime.timedelta(hours = 24)).strftime('%Y%m%d')

        self.infoDialog = False
Пример #5
0
    def __init__(self):
        self.library_folder = os.path.join(control.transPath(control.setting("tv_library")), "")

        self.version = control.version()

        self.check_setting = control.setting("check_episode_link") or "false"
        self.library_setting = control.setting("update_library") or "true"
        self.dupe_setting = control.setting("check_library") or "true"

        self.datetime = datetime.datetime.utcnow() - datetime.timedelta(hours=5)
        self.date = (self.datetime - datetime.timedelta(hours=24)).strftime("%Y%m%d")

        self.infoDialog = False
        self.block = False
    def __init__(self):
        self.library_folder = os.path.join(control.transPath(control.setting('library.tv')),'')

        self.version = control.version()

        self.check_setting = control.setting('library.check_episode') or 'false'
        self.include_unknown = control.setting('library.include_unknown') or 'true'
        self.library_setting = control.setting('library.update') or 'true'
        self.dupe_setting = control.setting('library.check') or 'true'

        self.datetime = (datetime.datetime.utcnow() - datetime.timedelta(hours = 5))
        self.date = (self.datetime - datetime.timedelta(hours = 24)).strftime('%Y%m%d')

        self.infoDialog = False
        self.block = False
Пример #7
0
    def __init__(self):
        self.library_folder = os.path.join(control.transPath(control.setting('library.tv')),'')

        self.version = control.version()

        self.check_setting = control.setting('library.check_episode') or 'false'
        self.include_unknown = control.setting('library.include_unknown') or 'true'
        self.library_setting = control.setting('library.update') or 'true'
        self.dupe_setting = control.setting('library.check') or 'true'

        self.datetime = (datetime.datetime.utcnow() - datetime.timedelta(hours = 5))
        self.date = (self.datetime - datetime.timedelta(hours = 24)).strftime('%Y%m%d')

        self.infoDialog = False
        self.block = False
Пример #8
0
def restoreFolder():
    names = []
    links = []
    zipFolder = control.setting('restore.path')
    if zipFolder == '' or zipFolder == None:
        control.infoDialog('Please Setup a Zip Files Location first')
        control.openSettings(query='2.0')
        return
    for zipFile in os.listdir(zipFolder):
        if zipFile.endswith(".zip"):
            url = control.transPath(os.path.join(zipFolder, zipFile))
            names.append(zipFile)
            links.append(url)
    select = control.selectDialog(names)
    if select != -1: restore(links[select])
Пример #9
0
    def __init__(self):
        self.library_folder = os.path.join(control.transPath(control.setting('library.tv')),'')

        self.library_setting = control.setting('library.update') or 'true'
        self.include_unknown = control.setting('library.include_unknown') or 'true'
        self.include_special = control.setting('library.include_special')
        self.property = '%s_service_property' % control.addonInfo('name').lower()

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

        self.infoDialog = False
Пример #10
0
def clearViews():
    try:
        skin = control.skin
        control.hide()
        yes = control.yesnoDialog(control.lang(32056), '', '')
        if not yes:
            return
        control.makeFile(control.dataPath)
        dbcon = database.connect(control.viewsFile)
        dbcur = dbcon.cursor()
        for t in ['views']:
            try:
                dbcur.execute("DROP TABLE IF EXISTS %s" % t)
                dbcur.execute("VACUUM")
                dbcur.execute("CREATE TABLE IF NOT EXISTS views ("
                              "skin TEXT, "
                              "view_type TEXT, "
                              "view_id TEXT, "
                              "UNIQUE(skin, view_type)"
                              ");")
                dbcur.connection.commit()
                dbcon.close()
            except:
                log_utils.error()
                pass
        try:
            kodiDB = control.transPath('special://home/userdata/Database')
            kodiViewsDB = control.joinPath(kodiDB, 'ViewModes6.db')
            dbcon = database.connect(kodiViewsDB)
            dbcur = dbcon.cursor()
            dbcur.execute(
                "DELETE FROM view WHERE path LIKE 'plugin://plugin.video.venom/%'"
            )
            dbcur.connection.commit()
            dbcon.close()
        except:
            log_utils.error()
            pass
        skinName = control.addon(skin).getAddonInfo('name')
        skinIcon = control.addon(skin).getAddonInfo('icon')
        control.notification(
            title=skinName,
            message='View Types Successfully Cleared!',
            icon=skinIcon,
            sound=(control.setting('notification.sound') == 'true'))
    except:
        log_utils.error()
        pass
Пример #11
0
def backup(mode='full'):
    KODIV = control.get_Kodi_Version()
    backupdir = control.setting('download.path')
    if backupdir == '' or backupdir == None:
        control.infoDialog('Please Setup a Path for Downlads first')
        control.openSettings(query='1.3')
        return
    if mode == 'full':
        defaultName = "kodi_backup"
        BACKUPDATA = HOME
        FIX_SPECIAL()
    elif mode == 'userdata':
        defaultName = "kodi_userdata"
        BACKUPDATA = USERDATA
    else:
        return
    if os.path.exists(BACKUPDATA):
        if not backupdir == '':
            name = control.get_keyboard(default=defaultName,
                                        heading='Name your Backup')
            today = datetime.now().strftime('%Y%m%d%H%M')
            today = re.sub('[^0-9]', '', str(today))
            zipDATE = "_%s.zip" % today
            name = re.sub(' ', '_', name) + zipDATE
            backup_zip = control.transPath(os.path.join(backupdir, name))
            exclude_database = [
                'Textures13.db', '.DS_Store', 'advancedsettings.xml',
                'Thumbs.db', '.gitignore'
            ]
            try:
                maintenance.clearCache(mode='silent')
                #maintenance.deleteThumbnails(mode='silent')
                #maintenance.purgePackages(mode='silent')
            except:
                pass
            exclude_dirs = [
                '.git', '.idea', 'packages', 'backupdir', 'cache', 'system',
                'Thumbnails', 'peripheral_data', 'temp', 'My_Builds',
                'keymaps', 'cdm'
            ]
            CreateZip(BACKUPDATA, backup_zip, 'Creating Backup',
                      'Backing up files', exclude_dirs, exclude_database)
            dialog.ok(AddonTitle, 'Backup complete', '', '')
        else:
            dialog.ok(
                AddonTitle,
                'No backup location found. Please setup your Backup location',
                '', '')
Пример #12
0
    def __init__(self):
        self.library_folder = os.path.join(
            control.transPath(control.setting('tv_library')), '')

        self.library_setting = control.setting('update_library') or 'true'
        self.include_unknown = control.setting(
            'library.include_unknown') or 'true'
        self.property = '%s_service_property' % control.addonInfo(
            'name').lower()

        self.datetime = (datetime.datetime.utcnow() -
                         datetime.timedelta(hours=5))
        self.date = (self.datetime -
                     datetime.timedelta(hours=24)).strftime('%Y%m%d')

        self.infoDialog = False
Пример #13
0
    def download(self, name, url):
        if url == None: return
        dest = control.setting('download.path')
        if dest == '' or dest == None:
            control.infoDialog('Download Location is Empty...')
        self.stopped = False

        image = control.icon

        try:
            headers = dict(urlparse.parse_qsl(url.rsplit('|', 1)[1]))
        except:
            headers = dict('')

        content = re.compile('(.+?)\sS(\d*)E\d*$').findall(name)
        transname = name.translate(None, '\/:*?"<>|').strip('.')
        transname = os.path.splitext(transname)[0]

        dest = control.transPath(dest)
        control.makeFile(dest)
        dest = os.path.join(dest, transname)
        control.makeFile(dest)

        dest = os.path.join(dest, name)

        sysheaders = urllib.quote_plus(json.dumps(headers))

        sysurl = urllib.quote_plus(url)

        systitle = urllib.quote_plus(name)

        sysimage = urllib.quote_plus(image)

        sysdest = urllib.quote_plus(dest)

        #script = inspect.getfile(inspect.currentframe())

        try:
            self.doDownload(url, dest, transname, image, headers)
            if self.stopped == True:
                control.infoDialog(transname, 'Download Stopped...')
            else:
                control.infoDialog(transname, 'Download Completed...')

        except Exception as e:
            control.infoDialog('Unable to Download...')
            print("PREMIUMIZER DOWNLOADER ERROR:", str(e))
Пример #14
0
	def __init__(self):
		self.library_folder = os.path.join(control.transPath(control.setting('library.tv')),'')

		self.check_setting = control.setting('library.check_episode') or 'false'
		self.library_update = control.setting('library.update') or 'true'
		self.dupe_chk = control.setting('library.check') or 'true'

		self.include_unknown = control.setting('library.include_unknown') or 'true'
		self.showunaired = control.setting('showunaired') or 'true'

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

		self.block = False
Пример #15
0
    def __init__(self):
        self.library_folder = os.path.join(
            control.transPath(control.setting("library.tv")), ""
        )

        self.version = control.version()

        self.check_setting = control.setting("library.check_episode") or "false"
        self.include_unknown = control.setting("library.include_unknown") or "true"
        self.library_setting = control.setting("library.update") or "true"
        self.dupe_setting = control.setting("library.check") or "true"

        self.datetime = datetime.datetime.utcnow() - datetime.timedelta(hours=5)
        self.date = (self.datetime - datetime.timedelta(hours=24)).strftime("%Y%m%d")

        self.infoDialog = False
        self.block = False
Пример #16
0
def installAPK(name, url):
    if url == None: return
    dest = control.setting('download.path')
    if dest == '' or dest == None:
        control.infoDialog('Download Location is Empty...')

    image = control.icon

    try:
        headers = dict(urlparse.parse_qsl(url.rsplit('|', 1)[1]))
    except:
        headers = dict('')

    content = re.compile('(.+?)\sS(\d*)E\d*$').findall(name)
    transname = name.translate(None, '\/:*?"<>|')

    dest = control.transPath(dest)
    control.makeFile(dest)
    dest = os.path.join(dest, transname)

    sysheaders = urllib.quote_plus(json.dumps(headers))

    sysurl = urllib.quote_plus(url)

    systitle = urllib.quote_plus(name)

    sysimage = urllib.quote_plus(image)

    sysdest = urllib.quote_plus(dest)

    script = inspect.getfile(inspect.currentframe())

    dp = xbmcgui.DialogProgress()
    dp.create(name, "Please Wait...")
    try:
        r = downloadzip.download(url, dest, dp)
        if r == '0': control.infoDialog('Download Interrupted...')
        else: control.infoDialog('Download Completed...')
    except:
        control.infoDialog('Unable to Download...')

    apkfile = dest
    xbmc.executebuiltin(
        'StartAndroidActivity("","android.intent.action.VIEW","application/vnd.android.package-archive","file:'
        + apkfile + '")')
Пример #17
0
def add_source(source_name,
               source_path,
               source_content,
               source_thumbnail,
               type='video'):
    xml_file = control.transPath('special://profile/sources.xml')
    # if not os.path.exists(xml_file):
    if not control.existsPath(xml_file):
        with open(xml_file, 'w') as f:
            f.write('''
<sources>
	<programs>
		<default pathversion="1"/>
	</programs>
	<video>
		<default pathversion="1"/>
	</video>
	<music>
		<default pathversion="1"/>
	</music>
	<pictures>
		<default pathversion="1"/>
	</pictures>
	<files>
		<default pathversion="1"/>
	</files>
	<games>
		<default pathversion="1"/>
	</games>
</sources>
''')
    existing_source = _get_source_attr(xml_file,
                                       source_name,
                                       'path',
                                       type=type)
    if existing_source and existing_source != source_path and source_content != '':
        _remove_source_content(existing_source)
    if _add_source_xml(
            xml_file, source_name, source_path, source_thumbnail,
            type=type) and source_content != '':
        _remove_source_content(
            source_path
        )  # Added to also rid any remains because manual delete sources and kodi leaves behind a record in MyVideos*.db
        _set_source_content(source_content)
Пример #18
0
def buildInstaller(url):
    destination = dialog.browse(type=0,
                                heading='Select Download Directory',
                                shares='files',
                                useThumbs=True,
                                treatAsFolder=True,
                                enableMultiple=False)
    if destination:
        dest = control.transPath(os.path.join(destination, 'custom_build.zip'))
        downloader(url, dest)
        time.sleep(2)
        dp.create("Installing Build", "In Progress...", '', 'Please Wait')
        dp.update(0, "", "Extracting Zip Please Wait")
        ExtractZip(dest, HOME, dp)
        time.sleep(2)
        dp.close()
        dialog.ok(AddonTitle, 'Installation Complete...',
                  'Your interface will now be reset', 'Click ok to Start...')
        control.execute('LoadProfile(Master user)')
Пример #19
0
def get_cache_version():
    versionFile = control.joinPath(control.dataPath, 'cache.v')
    try:
        if not control.existsPath(versionFile):
            f = open(versionFile, 'w')
            f.close()
    except:
        log_utils.log(
            'Venom Addon Data Path Does not Exist. Creating Folder....',
            __name__, log_utils.LOGDEBUG)
        ad_folder = control.transPath(
            'special://profile/addon_data/plugin.video.venom')
        control.makeDirs(ad_folder)
    try:
        with open(versionFile, 'r') as fh:
            oldVersion = fh.read()
    except:
        oldVersion = '0'
    return oldVersion
Пример #20
0
def clearViews():
    try:
        skin = control.skin
        control.hide()
        if not control.yesnoDialog(control.lang(32056), '', ''): return
        control.makeFile(control.dataPath)
        dbcon = db.connect(control.viewsFile)
        dbcur = dbcon.cursor()
        try:
            dbcur.execute('''DROP TABLE IF EXISTS views''')
            dbcur.execute('''VACUUM''')
            dbcur.execute(
                '''CREATE TABLE IF NOT EXISTS views (skin TEXT, view_type TEXT, view_id TEXT, UNIQUE(skin, view_type));'''
            )
            dbcur.connection.commit()
        except:
            from resources.lib.modules import log_utils
            log_utils.error()
        finally:
            dbcur.close()
            dbcon.close()
        try:
            kodiDB = control.transPath('special://home/userdata/Database')
            kodiViewsDB = control.joinPath(kodiDB, 'ViewModes6.db')
            dbcon = db.connect(kodiViewsDB)
            dbcur = dbcon.cursor()
            dbcur.execute(
                '''DELETE FROM view WHERE path LIKE "plugin://plugin.video.dg/%"'''
            )
            dbcur.connection.commit()
        except:
            from resources.lib.modules import log_utils
            log_utils.error()
        finally:
            dbcur.close()
            dbcon.close()
        skinName = control.addon(skin).getAddonInfo('name')
        skinIcon = control.addon(skin).getAddonInfo('icon')
        control.notification(title=skinName, message=32087, icon=skinIcon)
    except:
        from resources.lib.modules import log_utils
        log_utils.error()
Пример #21
0
 def run(self):
     if control.getKodiVersion() < 18:
         return
     try:
         import xml.etree.ElementTree as ET
         addon_dir = control.transPath(
             control.addon('plugin.video.venom').getAddonInfo('path'))
         addon_xml = control.joinPath(addon_dir, 'addon.xml')
         tree = ET.parse(addon_xml)
         root = tree.getroot()
         current_addon_setting = control.addon(
             'plugin.video.venom').getSetting('reuse.languageinvoker')
         if current_addon_setting == '':
             return
         try:
             current_xml_setting = [
                 str(i.text) for i in root.iter('reuselanguageinvoker')
             ][0]
         except:
             return
         if current_xml_setting == current_addon_setting:
             return
         if not control.yesnoDialog(
                 '[B]Reuse Language Invoker[/B] SETTING/XML mismatch.\nRestore correct status(RECOMMENDED)?',
                 '', ''):
             return
         for item in root.iter('reuselanguageinvoker'):
             item.text = current_addon_setting
             hash_start = control.gen_file_hash(addon_xml)
             tree.write(addon_xml)
             hash_end = control.gen_file_hash(addon_xml)
             if hash_start != hash_end:
                 control.okDialog(
                     'Kodi must close and be restarted for the change to take effect.'
                 )
             else:
                 control.okDialog('Venom', 'Error setting correct value.')
         return
     except:
         log_utils.error()
         pass
Пример #22
0
def Delete_Packages(url):
    print '############################################################       DELETING PACKAGES             ###############################################################'
    packages_cache_path = control.transPath(
        os.path.join('special://home/addons/packages', ''))
    try:
        for root, dirs, files in os.walk(packages_cache_path):
            file_count = 0
            file_count += len(files)
            if file_count > 0:
                if yesnoDialog("Delete Package Cache Files",
                               str(file_count) + " files found",
                               "Do you want to delete them?",
                               yeslabel='YES',
                               nolabel='NO'):
                    for f in files:
                        os.unlink(os.path.join(root, f))
                    for d in dirs:
                        shutil.rmtree(os.path.join(root, d))
                    OkDialog(AddonTitle, "Complete")
    except:
        OkDialog(AddonTitle, "Sorry we were not able to remove Package Files")
Пример #23
0
def downloadAPK(name, url):
    if url == None: return
    dest = control.setting('download.path')
    if dest == '' or dest == None:
        control.infoDialog('Download Location is Empty...')

    image = control.icon

    try:
        headers = dict(urlparse.parse_qsl(url.rsplit('|', 1)[1]))
    except:
        headers = dict('')

    content = re.compile('(.+?)\sS(\d*)E\d*$').findall(name)
    transname = name.translate(None, '\/:*?"<>|')

    dest = control.transPath(dest)
    control.makeFile(dest)
    dest = os.path.join(dest, transname)

    sysheaders = urllib.quote_plus(json.dumps(headers))

    sysurl = urllib.quote_plus(url)

    systitle = urllib.quote_plus(name)

    sysimage = urllib.quote_plus(image)

    sysdest = urllib.quote_plus(dest)

    script = inspect.getfile(inspect.currentframe())

    dp = xbmcgui.DialogProgress()
    dp.create(name, "Please Wait...")
    try:
        downloadzip.download(url, dest, dp)
        control.infoDialog('Download Completed...')
    except:
        control.infoDialog('Unable to Download...')
Пример #24
0
def get():

        import xbmc,xbmcgui,xbmcaddon,xbmcvfs,os
        addonInfo = xbmcaddon.Addon().getAddonInfo
        addonPath = control.transPath(addonInfo('path'))
		changelogfile = os.path.join(addonPath, 'changelog.txt')
		r = open(changelogfile)
		text = r.read()

		id = 10147
		xbmc.executebuiltin('ActivateWindow(%d)' % id)
		xbmc.sleep(500)
		win = xbmcgui.Window(id)
		retry = 50
		while (retry > 0):
			try:
				xbmc.sleep(10)
				retry -= 1
				win.getControl(1).setLabel('Kpolyamass Version: %s' %(xbmcaddon.Addon().getAddonInfo('version')))
				win.getControl(5).setText(text)
				return
			except:
				pass
Пример #25
0
    def service(self):
        try:
            lib_tools.create_folder(
                os.path.join(
                    control.transPath(control.setting('library.movie')), ''))
            lib_tools.create_folder(
                os.path.join(control.transPath(control.setting('library.tv')),
                             ''))
        except:
            pass

        try:
            control.makeFile(control.dataPath)
            dbcon = database.connect(control.libcacheFile)
            dbcur = dbcon.cursor()
            dbcur.execute("CREATE TABLE IF NOT EXISTS service ("
                          "setting TEXT, "
                          "value TEXT, "
                          "UNIQUE(setting)"
                          ");")
            dbcur.execute("SELECT * FROM service WHERE setting = 'last_run'")
            fetch = dbcur.fetchone()
            if fetch == None:
                serviceProperty = "1970-01-01 23:59:00.000000"
                dbcur.execute("INSERT INTO service Values (?, ?)",
                              ('last_run', serviceProperty))
                dbcon.commit()
            else:
                serviceProperty = str(fetch[1])
            dbcon.close()
        except:
            try:
                return dbcon.close()
            except:
                return

        try:
            control.window.setProperty(self.property, serviceProperty)
        except:
            return

        while not xbmc.abortRequested:
            try:
                serviceProperty = control.window.getProperty(self.property)

                t1 = datetime.timedelta(hours=6)
                t2 = datetime.datetime.strptime(serviceProperty,
                                                '%Y-%m-%d %H:%M:%S.%f')
                t3 = datetime.datetime.now()

                check = abs(t3 - t2) > t1
                if check == False: raise Exception()

                if (control.player.isPlaying()
                        or control.condVisibility('Library.IsScanningVideo')):
                    raise Exception()

                serviceProperty = datetime.datetime.now().strftime(
                    '%Y-%m-%d %H:%M:%S.%f')

                control.window.setProperty(self.property, serviceProperty)

                try:
                    dbcon = database.connect(control.libcacheFile)
                    dbcur = dbcon.cursor()
                    dbcur.execute("CREATE TABLE IF NOT EXISTS service ("
                                  "setting TEXT, "
                                  "value TEXT, "
                                  "UNIQUE(setting)"
                                  ");")
                    dbcur.execute(
                        "DELETE FROM service WHERE setting = 'last_run'")
                    dbcur.execute("INSERT INTO service Values (?, ?)",
                                  ('last_run', serviceProperty))
                    dbcon.commit()
                    dbcon.close()
                except:
                    try:
                        dbcon.close()
                    except:
                        pass

                if not control.setting('library.service.update') == 'true':
                    raise Exception()
                info = control.setting(
                    'library.service.notification') or 'true'
                self.update(info=info)
            except:
                pass

            control.sleep(10000)
Пример #26
0
 def get(self, name, imdb, season, episode):
     import gzip, codecs
     try:
         from cStringIO import StringIO
     except ImportError:
         from io import BytesIO as StringIO
     import xmlrpclib, re, base64
     try:
         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()
         server = xmlrpclib.Server('https://api.opensubtitles.org/xml-rpc',
                                   verbose=0)
         token = server.LogIn('', '', 'en', 'XBMC_Subtitles_v1')
         token = token['token']
         sublanguageid = ','.join(langs)
         imdbid = re.sub(r'[^0-9]', '', imdb)
         if not (season is None or episode is 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(r'\.|\(|\)|\[|\]|\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']
         content = [
             filter[0]['IDSubtitleFile'],
         ]
         content = server.DownloadSubtitles(token, content)
         content = base64.b64decode(content['data'][0]['data'])
         content = gzip.GzipFile(fileobj=StringIO(content)).read()
         subtitle = control.transPath('special://temp/')
         subtitle = control.joinPath(subtitle,
                                     'TemporarySubs.%s.srt' % lang)
         codepage = codePageDict.get(lang, '')
         if codepage and control.setting('subtitles.utf') == 'true':
             try:
                 content_encoded = codecs.decode(
                     content, codepage)  # check for kodi 19?
                 content = codecs.encode(content_encoded,
                                         'utf-8')  # check for kodi 19?
             except:
                 pass
         file = control.openFile(subtitle, 'w')
         file.write(str(content))
         file.close()
         xbmc.sleep(1000)
         xbmc.Player().setSubtitles(subtitle)
     except:
         log_utils.error()
Пример #27
0
def download(name, image, url, meta_name=None):
    # def download(name, image, url, meta_name=None, selected_source): # future for re-write, pack file support
    if not url: return control.hide()
    try:
        file_format = control.setting('downloads.file.format')
        try:
            headers = dict(parse_qsl(url.rsplit('|', 1)[1]))
        except:
            headers = dict('')
        url = url.split('|')[0]
        try:
            transname = name.translate(None, '\/:*?"<>|').strip('.')
        except:
            transname = name.translate(name.maketrans(
                '', '', '\/:*?"<>|')).strip(
                    '.')  # maketrans() is in string module for py2
        ext_list = ('.3gp', '.divx', '.xvid', '.m4v', '.mp4', '.mpeg', '.mpg',
                    '.m2ts', '.mov', '.mkv', '.flv', '.avi', '.wmv', '.webm')
        for i in ext_list:
            transname = transname.rstrip(i)
        if meta_name:
            try:
                content = re.search(r'(.+?)\sS(\d*)E\d*$', meta_name).groups()
            except:
                content = ()
            if file_format == '0':
                try:
                    transname = meta_name.translate(None,
                                                    '\/:*?"<>|').strip('.')
                except:
                    transname = meta_name.translate(
                        meta_name.maketrans('', '', '\/:*?"<>|')).strip('.')
        else:
            try:
                content = re.search(
                    r'(.+?)(?:|\.| - |-|.-.|\s)(?:S|s|\s|\.)(\d{1,2})(?!\d)(?:|\.| - |-|.-.|x|\s)(?:E|e|\s|.)([0-2]{1}[0-9]{1})(?!\w)',
                    name.replace('\'', '')).groups()
            except:
                content = ()
        levels = ['../../../..', '../../..', '../..', '..']
        if len(content) == 0:
            dest = control.transPath(control.setting('movie.download.path'))
            for level in levels:
                try:
                    control.makeFile(os.path.abspath(os.path.join(dest,
                                                                  level)))
                except:
                    pass
            control.makeFile(dest)
            if meta_name:
                try:
                    dest = os.path.join(
                        dest,
                        meta_name.translate(None, '\/:*?"<>|').strip('.'))
                except:
                    dest = os.path.join(
                        dest,
                        meta_name.translate(
                            meta_name.maketrans('', '',
                                                '\/:*?"<>|')).strip('.'))
            else:
                try:
                    movie_info = re.search(
                        r'(.+?)(?:\.{0,1}-{0,1}\.{0,1}|\s*)(?:|\(|\[|\.)((?:19|20)(?:[0-9]{2}))',
                        name.replace('\'', '')).groups()
                except:
                    movie_info = ()
                if len(movie_info) != 0:
                    movietitle = titlecase(
                        re.sub(r'[^A-Za-z0-9\s]+', ' ', movie_info[0]))
                    dest = os.path.join(
                        dest, movietitle + ' (' + movie_info[1] + ')')
                    if file_format == '0':
                        transname = movietitle + ' (' + movie_info[1] + ')'
                else:
                    dest = os.path.join(dest, transname)
            control.makeFile(dest)
        else:
            dest = control.transPath(control.setting('tv.download.path'))
            for level in levels:
                try:
                    control.makeFile(os.path.abspath(os.path.join(dest,
                                                                  level)))
                except:
                    pass
            control.makeFile(dest)
            try:
                transtvshowtitle = content[0].translate(
                    None, '\/:*?"<>|').strip('.').replace('.', ' ')
            except:
                transtvshowtitle = content[0].translate(content[0].maketrans(
                    '', '', '\/:*?"<>|')).strip('.').replace('.', ' ')
            if not meta_name:
                transtvshowtitle = titlecase(
                    re.sub(r'[^A-Za-z0-9\s-]+', ' ', transtvshowtitle))
            dest = os.path.join(dest, transtvshowtitle)
            control.makeFile(dest)
            dest = os.path.join(dest, 'Season %01d' % int(content[1]))
            control.makeFile(dest)
            if file_format == '0' and not meta_name:
                transname = transtvshowtitle + ' S%sE%s' % (content[1],
                                                            content[2])
        ext = os.path.splitext(urlparse(url).path)[1][1:]
        if not ext in ('3gp', 'divx', 'xvid', 'm4v', 'mp4', 'mpeg', 'mpg',
                       'm2ts', 'mov', 'mkv', 'flv', 'avi', 'wmv', 'webm'):
            ext = 'mp4'
        dest = os.path.join(dest, transname + '.' + ext)
        doDownload(url, dest, name, image, headers)
    except:
        log_utils.error()
Пример #28
0
    def service(self):
        try:
            lib_tools.create_folder(os.path.join(control.transPath(control.setting('library.movie')), ''))
            lib_tools.create_folder(os.path.join(control.transPath(control.setting('library.tv')), ''))
        except:
            pass
        
        try:
            control.makeFile(control.dataPath)
            dbcon = database.connect(control.libcacheFile)
            dbcur = dbcon.cursor()
            dbcur.execute("CREATE TABLE IF NOT EXISTS service (""setting TEXT, ""value TEXT, ""UNIQUE(setting)"");")
            dbcur.execute("SELECT * FROM service WHERE setting = 'last_run'")
            fetch = dbcur.fetchone()
            if fetch == None:
                serviceProperty = "1970-01-01 23:59:00.000000"
                dbcur.execute("INSERT INTO service Values (?, ?)", ('last_run', serviceProperty))
                dbcon.commit()
            else:
                serviceProperty = str(fetch[1])
            dbcon.close()
        except:
            try: return dbcon.close()
            except: return

        try: control.window.setProperty(self.property, serviceProperty)
        except: return

        while not xbmc.abortRequested:
            try:
                serviceProperty = control.window.getProperty(self.property)

                t1 = datetime.timedelta(hours=6)
                t2 = datetime.datetime.strptime(serviceProperty, '%Y-%m-%d %H:%M:%S.%f')
                t3 = datetime.datetime.now()

                check = abs(t3 - t2) > t1
                if check == False: raise Exception()

                if (control.player.isPlaying() or control.condVisibility('Library.IsScanningVideo')): raise Exception()

                serviceProperty = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')

                control.window.setProperty(self.property, serviceProperty)

                try:
                    dbcon = database.connect(control.libcacheFile)
                    dbcur = dbcon.cursor()
                    dbcur.execute("CREATE TABLE IF NOT EXISTS service (""setting TEXT, ""value TEXT, ""UNIQUE(setting)"");")
                    dbcur.execute("DELETE FROM service WHERE setting = 'last_run'")
                    dbcur.execute("INSERT INTO service Values (?, ?)", ('last_run', serviceProperty))
                    dbcon.commit()
                    dbcon.close()
                except:
                    try: dbcon.close()
                    except: pass

                if not control.setting('library.service.update') == 'true': raise Exception()
                info = control.setting('library.service.notification') or 'true'
                self.update(info=info)
            except:
                pass

            control.sleep(10000)
Пример #29
0
def _get_database(db_name):
    from glob import glob
    path_db = 'special://profile/Database/%s' % db_name
    filelist = glob(control.transPath(path_db))
    if filelist: return filelist[-1]
    return None
Пример #30
0
from resources.lib.modules import control


LOGDEBUG = xbmc.LOGDEBUG
LOGINFO = xbmc.LOGINFO
LOGNOTICE = xbmc.LOGNOTICE if control.getKodiVersion() < 19 else xbmc.LOGINFO
LOGWARNING = xbmc.LOGWARNING
LOGERROR = xbmc.LOGERROR
LOGFATAL = xbmc.LOGFATAL
LOGNONE = xbmc.LOGNONE

name = control.addonInfo('name')
version = control.addonInfo('version')
DEBUGPREFIX = '[ Prophet DEBUG ]'
LOGPATH = control.transPath('special://logpath/')
log_file = os.path.join(LOGPATH, 'prophet.log')
debug_enabled = control.setting('addon.debug')
#debug_log = control.setting('debug.location')


def log(msg, trace=0):

    #print(DEBUGPREFIX + ' Debug Enabled?: ' + six.ensure_str(debug_enabled))
    #print(DEBUGPREFIX + ' Debug Log?: ' + six.ensure_str(debug_log))

    if not debug_enabled == 'true':
        return

    try:
        if trace == 1:
Пример #31
0
def download(name, image, url, duration):
    xbmc.log('ENTRY -> plexpvrdownloader.py download()', xbmc.LOGNOTICE)
    xbmc.log('    name: %s' % (name), xbmc.LOGNOTICE)
    xbmc.log('    image: %s' % (image), xbmc.LOGNOTICE)
    xbmc.log('    url: %s' % (url), xbmc.LOGNOTICE)
    xbmc.log('    duration: %s' % (duration), xbmc.LOGNOTICE)

    if url == None: return

    from resources.lib.modules import control

    try:
        headers = dict(urlparse.parse_qsl(url.rsplit('|', 1)[1]))
    except:
        headers = dict('')

    url = url.split('|')[0]

    content = re.compile('(.+?)\sS(\d*)E\d*$').findall(name)
    transname = name.translate(None, '\/:*?"<>|').strip('.')
    levels = ['../../../..', '../../..', '../..', '..']

    if len(content) == 0:
        dest = control.setting('movie.download.path')
        dest = control.transPath(dest)
        for level in levels:
            try:
                control.makeFile(os.path.abspath(os.path.join(dest, level)))
            except:
                pass
        control.makeFile(dest)
        dest = os.path.join(dest, transname)
        control.makeFile(dest)
    else:
        dest = control.setting('tv.download.path')
        dest = control.transPath(dest)
        for level in levels:
            try:
                control.makeFile(os.path.abspath(os.path.join(dest, level)))
            except:
                pass
        control.makeFile(dest)
        transtvshowtitle = content[0][0].translate(None,
                                                   '\/:*?"<>|').strip('.')
        dest = os.path.join(dest, transtvshowtitle)
        control.makeFile(dest)
        dest = os.path.join(dest, 'Season %01d' % int(content[0][1]))
        control.makeFile(dest)

    ext = os.path.splitext(urlparse.urlparse(url).path)[1][1:]
    if not ext in ['mp4', 'mkv', 'flv', 'avi', 'mpg']: ext = 'mp4'
    dest = os.path.join(dest, transname + '.' + ext)
    filename = dest
    xbmc.log('**** DOWNLOAD DEST ******* using dest %s' % dest, xbmc.LOGDEBUG)

    if dest.endswith(".flv"):
        xbmc.log(
            '   **** ERROR **** found flv file.  Ignoring flv files: %s' %
            dest, xbmc.LOGWARNING)
        return

    if os.path.exists(filename):
        #xbmc.log('############# download ############# using fileExists %s' % dest, xbmc.LOGWARNING)
        i = 0

        while os.path.exists(filename):
            i += 1
            filename = dest.replace('.%s', ' (%s).%s') % (ext, str(i), ext)
            #xbmc.log('############# download ############# using dest %s' % dest, xbmc.LOGWARNING)

    dest = filename
    xbmc.log('############# FINAL DESTINATION ############# %s' % dest,
             xbmc.LOGDEBUG)

    sysheaders = urllib.quote_plus(json.dumps(headers))

    sysurl = urllib.quote_plus(url)

    systitle = urllib.quote_plus(name)

    sysimage = urllib.quote_plus(image)

    xbmc.log('**** FINAL DOWNLOAD NAME ******* Downloading FILE %s' % dest,
             xbmc.LOGDEBUG)
    sysdest = urllib.quote_plus(dest)
    #xbmc.log('******** download*** using sysdest %s' % sysdest, xbmc.LOGWARNING)

    script = inspect.getfile(inspect.currentframe())
    cmd = 'RunScript(%s, %s, %s, %s, %s, %s, %s)' % (
        script, sysurl, sysdest, systitle, duration, sysimage, sysheaders)

    xbmc.log(
        '################################################################',
        xbmc.LOGDEBUG)
    xbmc.log(
        '######################## DOWNLOADING %s ########################' %
        dest, xbmc.LOGDEBUG)
    xbmc.log(
        '######################## DOWNLOADING script %s ########################'
        % script, xbmc.LOGDEBUG)
    xbmc.log(
        '######################## DOWNLOADING sysurl %s ########################'
        % sysurl, xbmc.LOGDEBUG)
    #xbmc.log('######################## DOWNLOADING sysdest %s ########################' % sysdest, xbmc.LOGWARNING)
    #xbmc.log('######################## DOWNLOADING systitle %s ########################' % systitle, xbmc.LOGWARNING)
    xbmc.log(
        '################################################################',
        xbmc.LOGDEBUG)

    #xbmc.sleep(20000)
    xbmc.executebuiltin(cmd)
    xbmc.log('EXIT <- plexpvrdownloader.py download()', xbmc.LOGNOTICE)
Пример #32
0
def Delete_Cache(url):
    print '############################################################       DELETING STANDARD CACHE             ###############################################################'
    xbmc_cache_path = os.path.join(control.transPath('special://home'),
                                   'cache')
    if os.path.exists(xbmc_cache_path) == True:
        for root, dirs, files in os.walk(xbmc_cache_path):
            file_count = 0
            file_count += len(files)
            if file_count > 0:
                if yesnoDialog(AddonTitle,
                               str(file_count) + " Cache files found",
                               "Do you want to delete them?",
                               yeslabel='YES',
                               nolabel='NO'):
                    for f in files:
                        try:
                            if (f == "kodi.log" or f == "kodi.old.log"
                                    or f == "xbmc.log" or f == "xbmc.old.log"
                                    or f == "spmc.log" or f == "spmc.old.log"
                                    or f == "ezclean.log"
                                    or f == "scrubsv2.log"):
                                continue
                            os.unlink(os.path.join(root, f))
                        except:
                            pass
                    for d in dirs:
                        try:
                            shutil.rmtree(os.path.join(root, d))
                        except:
                            pass
            else:
                pass
    if control.condVisibility('system.platform.ATV2'):
        atv2_cache_a = os.path.join(
            '/private/var/mobile/Library/Caches/AppleTV/Video/', 'Other')
        for root, dirs, files in os.walk(atv2_cache_a):
            file_count = 0
            file_count += len(files)
            if file_count > 0:
                if yesnoDialog(AddonTitle,
                               str(file_count) +
                               " Cache files found in 'Other'",
                               "Do you want to delete them?",
                               yeslabel='YES',
                               nolabel='NO'):
                    for f in files:
                        os.unlink(os.path.join(root, f))
                    for d in dirs:
                        shutil.rmtree(os.path.join(root, d))
            else:
                pass
        atv2_cache_b = os.path.join(
            '/private/var/mobile/Library/Caches/AppleTV/Video/',
            'LocalAndRental')
        for root, dirs, files in os.walk(atv2_cache_b):
            file_count = 0
            file_count += len(files)
            if file_count > 0:
                if yesnoDialog(AddonTitle,
                               str(file_count) +
                               " Cache files found in 'LocalAndRental'",
                               "Do you want to delete them?",
                               yeslabel='YES',
                               nolabel='NO'):
                    for f in files:
                        os.unlink(os.path.join(root, f))
                    for d in dirs:
                        shutil.rmtree(os.path.join(root, d))
            else:
                pass
    wtf_cache_path = os.path.join(
        control.transPath(
            'special://profile/addon_data/plugin.video.whatthefurk/cache'), '')
    if os.path.exists(wtf_cache_path) == True:
        for root, dirs, files in os.walk(wtf_cache_path):
            file_count = 0
            file_count += len(files)
            if file_count > 0:
                if yesnoDialog(AddonTitle,
                               str(file_count) + " Cache files found",
                               "Do you want to delete them?",
                               yeslabel='YES',
                               nolabel='NO'):
                    for f in files:
                        os.unlink(os.path.join(root, f))
                    for d in dirs:
                        shutil.rmtree(os.path.join(root, d))
            else:
                pass
    channel4_cache_path = os.path.join(
        control.transPath(
            'special://profile/addon_data/plugin.video.4od/cache'), '')
    if os.path.exists(channel4_cache_path) == True:
        for root, dirs, files in os.walk(channel4_cache_path):
            file_count = 0
            file_count += len(files)
            if file_count > 0:
                if yesnoDialog(AddonTitle,
                               str(file_count) + " Cache files found",
                               "Do you want to delete them?",
                               yeslabel='YES',
                               nolabel='NO'):
                    for f in files:
                        os.unlink(os.path.join(root, f))
                    for d in dirs:
                        shutil.rmtree(os.path.join(root, d))
            else:
                pass
    iplayer_cache_path = os.path.join(
        control.transPath(
            'special://profile/addon_data/plugin.video.iplayer/iplayer_http_cache'
        ), '')
    if os.path.exists(iplayer_cache_path) == True:
        for root, dirs, files in os.walk(iplayer_cache_path):
            file_count = 0
            file_count += len(files)
            if file_count > 0:
                if yesnoDialog(AddonTitle,
                               str(file_count) + " Cache files found",
                               "Do you want to delete them?",
                               yeslabel='YES',
                               nolabel='NO'):
                    for f in files:
                        os.unlink(os.path.join(root, f))
                    for d in dirs:
                        shutil.rmtree(os.path.join(root, d))
            else:
                pass
    downloader_cache_path = os.path.join(
        control.transPath(
            'special://profile/addon_data/script.module.simple.downloader'),
        '')
    if os.path.exists(downloader_cache_path) == True:
        for root, dirs, files in os.walk(downloader_cache_path):
            file_count = 0
            file_count += len(files)
            if file_count > 0:
                if yesnoDialog(AddonTitle,
                               str(file_count) + " Cache files found",
                               "Do you want to delete them?",
                               yeslabel='YES',
                               nolabel='NO'):
                    for f in files:
                        os.unlink(os.path.join(root, f))
                    for d in dirs:
                        shutil.rmtree(os.path.join(root, d))
            else:
                pass
    itv_cache_path = os.path.join(
        control.transPath(
            'special://profile/addon_data/plugin.video.itv/Images'), '')
    if os.path.exists(itv_cache_path) == True:
        for root, dirs, files in os.walk(itv_cache_path):
            file_count = 0
            file_count += len(files)
            if file_count > 0:
                if yesnoDialog(AddonTitle,
                               str(file_count) + "Cache files found",
                               "Do you want to delete them?",
                               yeslabel='YES',
                               nolabel='NO'):
                    for f in files:
                        os.unlink(os.path.join(root, f))
                    for d in dirs:
                        shutil.rmtree(os.path.join(root, d))
            else:
                pass
    temp_cache_path = os.path.join(control.transPath('special://home/temp'),
                                   '')
    if os.path.exists(temp_cache_path) == True:
        for root, dirs, files in os.walk(temp_cache_path):
            file_count = 0
            file_count += len(files)
            if file_count > 0:
                if yesnoDialog(AddonTitle,
                               str(file_count) + " Cache files found",
                               "Do you want to delete them?",
                               yeslabel='YES',
                               nolabel='NO'):
                    for f in files:
                        if (f == "kodi.log" or f == "kodi.old.log"
                                or f == "xbmc.log" or f == "xbmc.old.log"
                                or f == "spmc.log" or f == "spmc.old.log"
                                or f == "ezclean.log" or f == "scrubsv2.log"):
                            continue
                        os.unlink(os.path.join(root, f))
                    for d in dirs:
                        shutil.rmtree(os.path.join(root, d))
            else:
                pass
    OkDialog(AddonTitle, "Complete")
Пример #33
0
def download(name, iconimage, url):
    from resources.lib.modules import control
    control.busy()
    import json
    if url is None:
        control.idle()
        return

    try:

        url = evaluate(url)
        xbmc.log('URL-EVALUATE: %s' % url)
    except Exception:
        control.idle()
        xbmcgui.Dialog().ok(NAME, 'Download failed',
                            'Your service can\'t resolve this hoster',
                            'or Link is down')
        return
    try:
        headers = dict(urlparse.parse_qsl(url.rsplit('|', 1)[1]))
    except BaseException:
        headers = dict('')
    control.idle()
    title = re.sub('\[.+?\]', '', name)
    content = re.compile('(.+?)\s+[\.|\(|\[]S(\d+)E\d+[\.|\)|\]]',
                         re.I).findall(title)
    transname = title.translate(None, '\/:*?"<>|').strip('.')
    transname = re.sub('\[.+?\]', '', transname)
    levels = ['../../../..', '../../..', '../..', '..']
    if len(content) == 0:
        dest = control.setting('movie.download.path')
        dest = control.transPath(dest)
        for level in levels:
            try:
                control.makeFile(os.path.abspath(os.path.join(dest, level)))
            except:
                pass
        control.makeFile(dest)
        dest = os.path.join(dest, transname)
        control.makeFile(dest)
    else:
        dest = control.setting('tv.download.path')
        dest = control.transPath(dest)
        for level in levels:
            try:
                control.makeFile(os.path.abspath(os.path.join(dest, level)))
            except:
                pass
        control.makeFile(dest)
        tvtitle = re.sub('\[.+?\]', '', content[0])
        transtvshowtitle = tvtitle.translate(None, '\/:*?"<>|').strip('.')
        dest = os.path.join(dest, transtvshowtitle)
        control.makeFile(dest)
        dest = os.path.join(dest, 'Season %01d' % int(content[0][1]))
        control.makeFile(dest)
    control.idle()
    # ext = os.path.splitext(urlparse.urlparse(url).path)[1]

    ext = os.path.splitext(urlparse.urlparse(url).path)[1][1:]
    xbmc.log('URL-EXT: %s' % ext)
    if not ext in ['mp4', 'mkv', 'flv', 'avi', 'mpg']: ext = 'mp4'
    dest = os.path.join(dest, transname + '.' + ext)
    headers = urllib.quote_plus(json.dumps(headers))
    xbmc.log('URL-HEADERS: %s' % headers)

    from resources.lib.modules import downloader
    control.idle()
    downloader.doDownload(url, dest, name, iconimage, headers)
Пример #34
0
def clean_settings():
    def _make_content(dict_object):
        content = '<settings version="2">'
        for item in dict_object:
            if item['id'] in active_settings:
                if 'default' in item and 'value' in item:
                    content += '\n    <setting id="%s" default="%s">%s</setting>' % (
                        item['id'], item['default'], item['value'])
                elif 'default' in item:
                    content += '\n    <setting id="%s" default="%s"></setting>' % (
                        item['id'], item['default'])
                elif 'value' in item:
                    content += '\n    <setting id="%s">%s</setting>' % (
                        item['id'], item['value'])
                else:
                    content += '\n    <setting id="%s"></setting>'
            else:
                removed_settings.append(item)
        content += '\n</settings>'
        return content

    for addon_id in ('plugin.video.dg', 'script.module.fenomscrapers'):
        try:
            removed_settings = []
            active_settings = []
            current_user_settings = []
            addon = control.addon(id=addon_id)
            addon_name = addon.getAddonInfo('name')
            addon_dir = control.transPath(addon.getAddonInfo('path'))
            profile_dir = control.transPath(addon.getAddonInfo('profile'))
            active_settings_xml = control.joinPath(addon_dir, 'resources',
                                                   'settings.xml')
            root = ET.parse(active_settings_xml).getroot()
            for item in root.findall('./category/setting'):
                setting_id = item.get('id')
                if setting_id:
                    active_settings.append(setting_id)
            settings_xml = control.joinPath(profile_dir, 'settings.xml')
            root = ET.parse(settings_xml).getroot()
            for item in root:
                dict_item = {}
                setting_id = item.get('id')
                setting_default = item.get('default')
                setting_value = item.text
                dict_item['id'] = setting_id
                if setting_value:
                    dict_item['value'] = setting_value
                if setting_default:
                    dict_item['default'] = setting_default
                current_user_settings.append(dict_item)
            new_content = _make_content(current_user_settings)
            nfo_file = control.openFile(settings_xml, 'w')
            nfo_file.write(new_content)
            nfo_file.close()
            control.sleep(200)
            control.notification(title=addon_name,
                                 message=control.lang(32084).format(
                                     str(len(removed_settings))))
        except:
            from resources.lib.modules import log_utils
            log_utils.error()
            control.notification(title=addon_name, message=32115)
Пример #35
0
def download(name, image, url):

    if url == None: return

    from resources.lib.modules import control, cleantitle

    try:
        headers = dict(urllib_parse.parse_qsl(url.rsplit('|', 1)[1]))
    except:
        headers = dict('')

    url = url.split('|')[0]

    content = re.compile('(.+?)\sS(\d*)E\d*$').findall(name)
    try:
        transname = name.translate(None, '\/:*?"<>|').strip('.')
    except:
        transname = name.translate(str.maketrans('', '',
                                                 '\/:*?"<>|')).strip('.')
    transname = cleantitle.normalize(transname)
    levels = ['../../../..', '../../..', '../..', '..']

    if len(content) == 0:
        dest = control.setting('movie.download.path')
        dest = control.transPath(dest)
        for level in levels:
            try:
                control.makeFile(os.path.abspath(os.path.join(dest, level)))
            except:
                pass
        control.makeFile(dest)
        dest = os.path.join(dest, transname)
        control.makeFile(dest)
    else:
        dest = control.setting('tv.download.path')
        dest = control.transPath(dest)
        for level in levels:
            try:
                control.makeFile(os.path.abspath(os.path.join(dest, level)))
            except:
                pass
        control.makeFile(dest)
        try:
            transtvshowtitle = content[0][0].translate(None,
                                                       '\/:*?"<>|').strip('.')
        except:
            transtvshowtitle = content[0][0].translate(
                str.maketrans('', '', '\/:*?"<>|')).strip('.')
        dest = os.path.join(dest, transtvshowtitle)
        control.makeFile(dest)
        dest = os.path.join(dest, 'Season %01d' % int(content[0][1]))
        control.makeFile(dest)

    ext = os.path.splitext(urllib_parse.urlparse(url).path)[1][1:]
    if not ext in ['mp4', 'mkv', 'flv', 'avi', 'mpg']: ext = 'mp4'
    dest = os.path.join(dest, transname + '.' + ext)

    sysheaders = urllib_parse.quote_plus(json.dumps(headers))

    sysurl = urllib_parse.quote_plus(url)

    systitle = urllib_parse.quote_plus(name)

    sysimage = urllib_parse.quote_plus(image)

    sysdest = urllib_parse.quote_plus(dest)

    script = inspect.getfile(inspect.currentframe())
    cmd = 'RunScript(%s, %s, %s, %s, %s, %s)' % (
        script, sysurl, sysdest, systitle, sysimage, sysheaders)

    xbmc.executebuiltin(cmd)
Пример #36
0
	def __init__(self):
		self.library_folder = control.joinPath(control.transPath(control.setting('library.movie')), '')
		self.check_setting = control.setting('library.check_movie') or 'false'
		self.library_update = control.setting('library.update') or 'true' 
		self.dupe_chk = control.setting('library.check') or 'true'
Пример #37
0
	def service(self):
		self.property = '%s_service_property' % control.addonInfo('name').lower()
		try:
			lib_tools.create_folder(control.joinPath(control.transPath(control.setting('library.movie')), ''))
			lib_tools.create_folder(control.joinPath(control.transPath(control.setting('library.tv')), ''))
		except: pass
		try:
			control.makeFile(control.dataPath)
			dbcon = database.connect(control.libcacheFile)
			dbcur = dbcon.cursor()
			dbcur.execute('''CREATE TABLE IF NOT EXISTS service (setting TEXT, value TEXT, UNIQUE(setting));''')
			dbcur.connection.commit()
			fetch = dbcur.execute('''SELECT * FROM service WHERE setting="last_run"''').fetchone()
			if not fetch:
				last_service = "1970-01-01 23:59:00.000000"
				dbcur.execute('''INSERT INTO service Values (?, ?)''', ('last_run', last_service))
				dbcur.connection.commit()
			else:
				last_service = str(fetch[1])
		except:
			log_utils.error()
		finally:
			dbcur.close() ; dbcon.close()

		try:
			control.homeWindow.setProperty(self.property, last_service)
		except:
			log_utils.error()
			return

		while not control.monitor.abortRequested():
			try:
				last_service = control.homeWindow.getProperty(self.property)
				t1 = timedelta(hours=6)
				t2 = control.datetime_workaround(str(last_service), '%Y-%m-%d %H:%M:%S.%f', False)
				t3 = datetime.now()
				check = abs(t3 - t2) >= t1
				if not check: continue
				if (control.player.isPlaying() or control.condVisibility('Library.IsScanningVideo')): continue
				last_service = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
				control.homeWindow.setProperty(self.property, last_service)
				try:
					dbcon = database.connect(control.libcacheFile)
					dbcur = dbcon.cursor()
					dbcur.execute('''CREATE TABLE IF NOT EXISTS service (setting TEXT, value TEXT, UNIQUE(setting));''')
					dbcur.execute('''INSERT OR REPLACE INTO service Values (?, ?)''', ('last_run', last_service))
					dbcur.connection.commit()
				except:
					log_utils.error()
				finally:
					dbcur.close() ; dbcon.close()

				if control.setting('library.service.update') == 'false' or service_update is False:
					continue
				libepisodes().update()
				libmovies().list_update()
				libtvshows().list_update()

				if control.monitor.waitForAbort(60*15): break
			except:
				log_utils.error()
				continue