コード例 #1
0
 def run(self):
     try:
         xbmc.log(
             '[ plugin.video.venom ]  CheckSettingsFile Service Starting...',
             2)
         window.clearProperty('venom_settings')
         profile_dir = xbmc.translatePath(
             'special://profile/addon_data/plugin.video.venom/')
         if not control.existsPath(profile_dir):
             success = control.makeDirs(profile_dir)
             if success:
                 xbmc.log('%s : created successfully' % profile_dir, 2)
         else:
             xbmc.log('%s : already exists' % profile_dir, 2)
         settings_xml = control.joinPath(profile_dir, 'settings.xml')
         if not control.existsPath(settings_xml):
             control.setSetting('trakt.message1', '')
             xbmc.log('%s : created successfully' % settings_xml, 2)
         else:
             xbmc.log('%s : already exists' % settings_xml, 2)
         return xbmc.log(
             '[ plugin.video.venom ]  Finished CheckSettingsFile Service',
             2)
     except:
         log_utils.error()
コード例 #2
0
ファイル: service.py プロジェクト: deangrice07/dg.github.io
 def run(self):
     try:
         control.log(
             '[ plugin.video.dg ]  CheckSettingsFile Service Starting...',
             LOGINFO)
         window.clearProperty('dg_settings')
         profile_dir = control.dataPath
         if not control.existsPath(profile_dir):
             success = control.makeDirs(profile_dir)
             if success:
                 control.log('%s : created successfully' % profile_dir,
                             LOGINFO)
         else:
             control.log('%s : already exists' % profile_dir, LOGINFO)
         settings_xml = control.joinPath(profile_dir, 'settings.xml')
         if not control.existsPath(settings_xml):
             control.setSetting('trakt.message2', '')
             control.log('%s : created successfully' % settings_xml,
                         LOGINFO)
         else:
             control.log('%s : already exists' % settings_xml, LOGINFO)
         return control.log(
             '[ plugin.video.dg ]  Finished CheckSettingsFile Service',
             LOGINFO)
     except:
         log_utils.error()
コード例 #3
0
def upload_LogFile(name):
	from resources.lib.modules.control import notification
	url = 'https://paste.kodi.tv/'
	log_file = joinPath(LOGPATH, '%s.log' % name.lower())
	if not existsPath(log_file):
		return notification(message='Log File not found, likely logging is not enabled.')
	try:
		import requests
		from resources.lib.modules.control import addonVersion, selectDialog, getHighlightColor
		f = open(log_file, 'r', encoding='utf-8', errors='ignore')
		text = f.read()
		f.close()
		UserAgent = 'Venom %s' % addonVersion('plugin.video.venom')
		response = requests.post(url + 'documents', data=text.encode('utf-8', errors='ignore'), headers={'User-Agent': UserAgent})
		if 'key' in response.json():
			result = url + response.json()['key']
			log('%s log file uploaded to: %s' % (name, result))
			from sys import platform as sys_platform
			supported_platform = any(value in sys_platform for value in ('win32', 'linux2'))
			highlight_color = getHighlightColor()
			list = [('[COLOR %s]url:[/COLOR]  %s' % (highlight_color, str(result)), str(result))]
			if supported_platform: list += [('[COLOR %s]  -- Copy url To Clipboard[/COLOR]' % highlight_color, ' ')]
			select = selectDialog([i[0] for i in list], lang(32196) if name.lower() == 'venom' else lang(32199))
			if 'Copy url To Clipboard' in list[select][0]:
				from resources.lib.modules.source_utils import copy2clip
				copy2clip(list[select - 1][1])
		elif 'message' in response.json():
			notification(message='%s Log upload failed: %s' % (name, str(response.json()['message'])))
			log('%s Log upload failed: %s' % (name, str(response.json()['message'])), level=LOGERROR)
		else:
			notification(message='%s Log upload failed' % name)
			log('%s Log upload failed: %s' % (name, response.text), level=LOGERROR)
	except:
		error('%s log upload failed' % name)
		notification(message='pastebin post failed: See log for more info')
コード例 #4
0
def last_paused_at():
    last_paused = 0
    try:
        if not control.existsPath(control.dataPath):
            control.makeFile(control.dataPath)
        dbcon = db.connect(control.traktSyncFile)
        dbcur = dbcon.cursor()
        ck_table = dbcur.execute(
            '''SELECT * FROM sqlite_master WHERE type='table' AND name='service';'''
        ).fetchone()
        if ck_table:
            match = dbcur.execute(
                '''SELECT * FROM service WHERE setting="last_paused_at";'''
            ).fetchone()
            if match: last_paused = int(cleandate.iso_2_utc(match[1]))
            else:
                dbcur.execute(
                    '''INSERT OR REPLACE INTO service Values (?, ?)''',
                    ('last_paused_at', '1970-01-01T20:00:00.000Z'))
        else:
            dbcur.execute(
                '''CREATE TABLE IF NOT EXISTS service (setting TEXT, value TEXT, UNIQUE(setting));'''
            )
    except:
        log_utils.error()
    finally:
        dbcur.close()
        dbcon.close()
    return last_paused
コード例 #5
0
def get_connection():
    if not existsPath(dataPath): makeFile(dataPath)
    dbcon = db.connect(
        fanarttvCacheFile,
        timeout=60)  # added timeout 3/23/21 for concurrency with threads
    dbcon.row_factory = _dict_factory
    return dbcon
コード例 #6
0
def add_source(source_name, source_path, source_content, source_thumbnail, type='video'):
	xml_file = transPath('special://profile/sources.xml')
	if not 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)
コード例 #7
0
def log(msg, caller=None, level=LOGNOTICE):
	debug_enabled = control.setting('debug.enabled') == 'true'
	debug_log = control.setting('debug.location')

	if not debug_enabled: return
	try:
		if caller is not None and level == LOGDEBUG:
			func = inspect.currentframe().f_back.f_code
			line_number = inspect.currentframe().f_back.f_lineno
			caller = "%s.%s()" % (caller, func.co_name)
			msg = 'From func name: %s Line # :%s\n                       msg : %s' % (caller, line_number, msg)

		if caller is not None and level == LOGERROR:
			msg = 'From func name: %s.%s() Line # :%s\n                       msg : %s' % (caller[0], caller[1], caller[2], msg)
		try:
			if isinstance(msg, unicode):
				msg = '%s (ENCODED)' % (msg.encode('utf-8'))
		except: pass

		if debug_log == '1':
			log_file = control.joinPath(LOGPATH, 'venom.log')
			if not control.existsPath(log_file):
				f = open(log_file, 'w')
				f.close()
			with open(log_file, 'a') as f:
				line = '[%s %s] %s: %s' % (datetime.now().date(), str(datetime.now().time())[:8], DEBUGPREFIX, msg)
				f.write(line.rstrip('\r\n')+'\n')
		else:
			xbmc.log('%s: %s' % (DEBUGPREFIX, msg), level)
	except Exception as e:
		xbmc.log('Logging Failure: %s' % (e), LOGERROR)
コード例 #8
0
def fetch(items, lang = 'en', user=''):
    try:
        t2 = int(time.time())

        if not control.existsPath(control.dataPath):
            control.makeFile(control.dataPath)

        dbcon = database.connect(control.metacacheFile)
        dbcur = dbcon.cursor()
        dbcur.execute("CREATE TABLE IF NOT EXISTS meta (""imdb TEXT, ""tmdb TEXT, ""tvdb TEXT, ""lang TEXT, ""user TEXT, ""item TEXT, ""time TEXT, ""UNIQUE(imdb, tmdb, tvdb, lang, user)"");")
    except:
        return items

    for i in range(0, len(items)):
        try:
            dbcur.execute("SELECT * FROM meta WHERE (imdb = '%s' and lang = '%s' and user = '******' and not imdb = '0') or (tmdb = '%s' and lang = '%s' and user = '******' and not tmdb = '0') or (tvdb = '%s' and lang = '%s' and user = '******' and not tvdb = '0')" % (items[i]['imdb'], lang, user, items[i]['tmdb'], lang, user, items[i]['tvdb'], lang, user))
            # dbcur.execute("SELECT * FROM meta WHERE (imdb = '%s' and lang = '%s' and user = '******' and not imdb = '0') or (tvdb = '%s' and lang = '%s' and user = '******' and not tvdb = '0')" % (items[i]['imdb'], lang, user, items[i]['tvdb'], lang, user))
            match = dbcur.fetchone()
            if not match is None:
                t1 = int(match[6])
                update = (abs(t2 - t1) / 3600) >= 720
                if update is True:
                    raise Exception()
                item = eval(match[5].encode('utf-8'))
                item = dict((k, v) for k, v in item.iteritems() if not v == '0')
                items[i].update(item)
                items[i].update({'metacache': True})
        except:
            import traceback
            traceback.print_exc()
            pass
    return items
コード例 #9
0
def _find_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, 'rb') as fh:
            oldVersion = fh.read()
    except:
        oldVersion = '0'
    try:
        curVersion = control.addon('plugin.video.venom').getAddonInfo(
            'version')
        if oldVersion != curVersion:
            with open(versionFile, 'wb') as fh:
                fh.write(curVersion)
            return True
        else:
            return False
    except:
        log_utils.error()
        return False
コード例 #10
0
def update_cache_version():
    versionFile = control.joinPath(control.dataPath, 'cache.v')
    try:
        if not control.existsPath(versionFile):
            f = open(versionFile, 'w')
            f.close()
    except:
        from resources.lib.modules import log_utils
        log_utils.log('dg Addon Data Path Does not Exist. Creating Folder....',
                      __name__, log_utils.LOGDEBUG)
        ad_folder = control.transPath(
            'special://profile/addon_data/plugin.video.dg')
        control.makeDirs(ad_folder)
    try:
        with open(versionFile, 'r') as fh:
            oldVersion = fh.read()
    except:
        oldVersion = '0'
    try:
        curVersion = control.addon('plugin.video.dg').getAddonInfo('version')
        if oldVersion != curVersion:
            with open(versionFile, 'w') as fh:
                fh.write(curVersion)
            return oldVersion, True
        else:
            return oldVersion, False
    except:
        from resources.lib.modules import log_utils
        log_utils.error()
        return oldVersion, False
コード例 #11
0
def insert(meta):
	try:
		if not control.existsPath(control.dataPath):
			control.makeFile(control.dataPath)
		dbcon = database.connect(control.metacacheFile)
		dbcur = dbcon.cursor()
		dbcur.execute("CREATE TABLE IF NOT EXISTS meta (""imdb TEXT, ""tmdb TEXT, ""tvdb TEXT, ""lang TEXT, ""user TEXT, ""item TEXT, ""time TEXT, ""UNIQUE(imdb, tmdb, tvdb, lang, user)"");")
		t = int(time.time())
		for m in meta:
			if "user" not in m:
				m["user"] = ''
			if "lang" not in m:
				m["lang"] = 'en'
			i = repr(m['item'])
			try:
				dbcur.execute("INSERT OR REPLACE INTO meta Values (?, ?, ?, ?, ?, ?, ?)", (m.get('imdb', '0'), m.get('tmdb', '0'), m.get('tvdb', '0'), m['lang'], m['user'], i, t))
			except:
				pass
		dbcur.connection.commit()
	except:
		log_utils.error()
		pass
	try:
		dbcon.close()
	except:
		pass
	return
コード例 #12
0
def fetch(items, lang = 'en', user=''):
	try:
		t2 = int(time.time())

		if not control.existsPath(control.dataPath):
			control.makeFile(control.dataPath)

		dbcon = database.connect(control.metacacheFile)
		dbcur = dbcon.cursor()
		dbcur.execute("CREATE TABLE IF NOT EXISTS meta (""imdb TEXT, ""tmdb TEXT, ""tvdb TEXT, ""lang TEXT, ""user TEXT, ""item TEXT, ""time TEXT, ""UNIQUE(imdb, tmdb, tvdb, lang, user)"");")
		dbcur.connection.commit()
	except:
		log_utils.error()
		try:
			dbcon.close()
		except:
			pass
		return items

	for i in range(0, len(items)):
		try:
			# First lookup by TVDb and IMDb, since there are some incorrect shows on Trakt that have the same IMDb ID, but different TVDb IDs (eg: Gotham, Supergirl).
			try:
				dbcur.execute("SELECT * FROM meta WHERE (imdb = '%s' and tvdb = '%s' and lang = '%s' and user = '******' and not imdb = '0' and not tvdb = '0')" % (items[i].get('imdb', '0'), items[i].get('tvdb', '0'), lang, user))
				match = dbcur.fetchone()
				t1 = int(match[6])
			except:
				# Lookup both IMDb and TMDb for more accurate match.
				try:
					dbcur.execute("SELECT * FROM meta WHERE (imdb = '%s' and tmdb = '%s' and lang = '%s' and user = '******' and not imdb = '0' and not tmdb = '0')" % (items[i].get('imdb', '0'), items[i].get('tmdb', '0'), lang, user))
					match = dbcur.fetchone()
					t1 = int(match[6])
				except:
					# Last resort single ID lookup.
					try:
						dbcur.execute("SELECT * FROM meta WHERE (imdb = '%s' and lang = '%s' and user = '******' and not imdb = '0') OR (tmdb = '%s' and lang = '%s' and user = '******' and not tmdb = '0') OR (tvdb = '%s' and lang = '%s' and user = '******' and not tvdb = '0')" % (items[i].get('imdb', '0'), lang, user, items[i].get('tmdb', '0'), lang, user, items[i].get('tvdb', '0'), lang, user))
						match = dbcur.fetchone()
						t1 = int(match[6])
					except:
						pass

			if match is not None:
				update = (abs(t2 - t1) / 3600) >= 720
				if update is True:
					continue

				item = eval(match[5].encode('utf-8'))
				item = dict((k, v) for k, v in item.iteritems() if v != '0')

				items[i].update(item)
				items[i].update({'metacache': True})
		except:
			log_utils.error()
			pass

	try:
		dbcon.close()
	except:
		pass
	return items
コード例 #13
0
	def search(self):
		from resources.lib.menus import navigator
		navigator.Navigator().addDirectoryItem(32603, 'tvSearchnew', 'search.png', 'DefaultAddonsSearch.png', isFolder=False)
		try: from sqlite3 import dbapi2 as database
		except ImportError: from pysqlite2 import dbapi2 as database
		try:
			if not control.existsPath(control.dataPath): control.makeFile(control.dataPath)
			dbcon = database.connect(control.searchFile)
			dbcur = dbcon.cursor()
			dbcur.executescript('''CREATE TABLE IF NOT EXISTS tvshow (ID Integer PRIMARY KEY AUTOINCREMENT, term);''')
			dbcur.execute('''SELECT * FROM tvshow ORDER BY ID DESC''')
			dbcur.connection.commit()
			lst = []
			delete_option = False
			for (id, term) in dbcur.fetchall():
				if term not in str(lst):
					delete_option = True
					navigator.Navigator().addDirectoryItem(term, 'tvSearchterm&name=%s' % term, 'search.png', 'DefaultAddonsSearch.png', isSearch=True, table='tvshow')
					lst += [(term)]
		except:
			from resources.lib.modules import log_utils
			log_utils.error()
		finally:
			dbcur.close() ; dbcon.close()
		if delete_option:
			navigator.Navigator().addDirectoryItem(32605, 'cache_clearSearch', 'tools.png', 'DefaultAddonService.png', isFolder=False)
		navigator.Navigator().endDirectory()
コード例 #14
0
	def list_update(self):
		contains = lib_tools().ckKodiSources()
		if not contains: return
		try:
			if not control.existsPath(control.dataPath):
				control.makeFile(control.dataPath)
			dbcon = database.connect(control.libcacheFile)
			dbcur = dbcon.cursor()
			dbcur.execute('''CREATE TABLE IF NOT EXISTS lists (type TEXT, list_name TEXT, url TEXT, UNIQUE(type, list_name, url));''')
			dbcur.connection.commit()
		except:
			log_utils.error()
		try:
			results = dbcur.execute('''SELECT * FROM lists WHERE type="tvshows";''').fetchall()
			if not results:
				control.notification(message=32124)
				return
		except:
			log_utils.error()
		finally:
			dbcur.close() ; dbcon.close()

		for list in results:
			type = list[0]
			list_name = list[1]
			url = list[2]
			# type, list_name, url = list[0], list[1], list[2]

			try:
				if 'trakt' in url:
					from resources.lib.menus import tvshows
					items = tvshows.TVshows().trakt_list(url, control.setting('trakt.user').strip())
				if 'themoviedb' in url:
					from resources.lib.indexers import tmdb
					if '/list/' not in url: items = tmdb.TVshows().tmdb_list(url)
					else: items = tmdb.TVshows().tmdb_collections_list(url)
			except:
				log_utils.error()

			if not items: continue

			if service_notification and not control.condVisibility('Window.IsVisible(infodialog)') and not control.condVisibility('Player.HasVideo'):
				control.notification(title='list...' + list_name + ' - ' + type, message=32552)

			total_added = 0
			for i in items:
				if control.monitor.abortRequested(): return sys.exit()
				try:
					files_added = self.add(i['title'], i['year'], i['imdb'], i['tmdb'], i['tvdb'], range=True)
					if general_notification and files_added > 0: control.notification(title=i['title'], message=32554)
					if files_added > 0: total_added += 1
				except:
					log_utils.error()

		if self.library_update == 'true' and not control.condVisibility('Library.IsScanningVideo') and total_added > 0:
			if contains:
				control.sleep(10000)
				control.execute('UpdateLibrary(video)')
			elif service_notification: control.notification(message=32103)
コード例 #15
0
def get_connection():
    if not control.existsPath(control.dataPath):
        control.makeFile(control.dataPath)
    dbcon = db.connect(
        control.cacheFile,
        timeout=60)  # added timeout 3/23/21 for concurrency with threads
    dbcon.row_factory = _dict_factory
    return dbcon
コード例 #16
0
def fetch(items, lang='en', user=''):
    if not control.existsPath(control.dataPath):
        control.makeFile(control.dataPath)
    dbcon = db.connect(control.metacacheFile)
    dbcur = dbcon.cursor()
    ck_table = dbcur.execute(
        '''SELECT * FROM sqlite_master WHERE type='table' AND name='meta';'''
    ).fetchone()
    if not ck_table:
        dbcur.execute(
            '''CREATE TABLE IF NOT EXISTS meta (imdb TEXT, tmdb TEXT, tvdb TEXT, lang TEXT, user TEXT, item TEXT, time TEXT,
		UNIQUE(imdb, tmdb, tvdb, lang, user));''')
        dbcur.connection.commit()
        dbcur.close()
        dbcon.close()
        return items
    t2 = int(time.time())
    for i in range(0, len(items)):
        try:
            try:  # First lookup by TVDb and IMDb, since there are some incorrect shows on Trakt that have the same IMDb ID, but different TVDb IDs (eg: Gotham, Supergirl).
                match = dbcur.execute(
                    '''SELECT * FROM meta WHERE (imdb=? AND tvdb=? AND lang=? AND user=? AND NOT imdb='0' AND NOT tvdb='0')''',
                    (items[i].get('imdb', '0'), items[i].get(
                        'tvdb', '0'), lang, user)).fetchone()
                t1 = int(match[6])
            except:
                try:  # Lookup both IMDb and TMDb for more accurate match.
                    match = dbcur.execute(
                        '''SELECT * FROM meta WHERE (imdb=? AND tmdb=? AND lang=? AND user=? AND not imdb='0' AND NOT tmdb='0')''',
                        (items[i].get('imdb', '0'), items[i].get(
                            'tmdb', '0'), lang, user)).fetchone()
                    t1 = int(match[6])
                except:
                    try:  # Last resort single ID lookup.
                        match = dbcur.execute(
                            '''SELECT * FROM meta WHERE (imdb=? AND lang=? AND user=? AND NOT imdb='0') OR (tmdb=? AND lang=? AND user=? AND NOT tmdb='0') OR (tvdb=? AND lang=? AND user=? AND NOT tvdb='0')''',
                            (items[i].get(
                                'imdb', '0'), lang, user, items[i].get(
                                    'tmdb', '0'), lang, user, items[i].get(
                                        'tvdb', '0'), lang, user)).fetchone()
                        t1 = int(match[6])
                    except:
                        pass
            if match:
                update = (abs(t2 - t1) / 3600) >= 720
                if update: continue
                item = eval(match[5].encode('utf-8'))
                item = dict((k, v) for k, v in item.iteritems() if v != '0')
                items[i].update(item)
                items[i].update({'metacache': True})
        except:
            log_utils.error()
    try:
        dbcur.close()
        dbcon.close()
    except:
        pass
    return items
コード例 #17
0
def log(msg, caller=None, level=LOGINFO):
    debug_enabled = getSetting('debug.enabled') == 'true'
    if not debug_enabled: return
    debug_level = getSetting('debug.level')
    if level == LOGDEBUG and debug_level != '1': return
    debug_location = getSetting('debug.location')
    if isinstance(msg, int): msg = lang(msg)  # for strings.po translations
    try:
        if not msg.isprintable(
        ):  # ex. "\n" is not a printable character so returns False on those cases
            msg = '%s (NORMALIZED by log_utils.log())' % normalize(msg)
        if isinstance(msg, bytes):
            msg = '%s (ENCODED by log_utils.log())' % msg.decode(
                'utf-8', errors='replace')

        if caller is not None and level != LOGERROR:
            func = inspect.currentframe().f_back.f_code
            line_number = inspect.currentframe().f_back.f_lineno
            caller = "%s.%s()" % (caller, func.co_name)
            msg = 'From func name: %s Line # :%s\n                       msg : %s' % (
                caller, line_number, msg)
        elif caller is not None and level == LOGERROR:
            msg = 'From func name: %s.%s() Line # :%s\n                       msg : %s' % (
                caller[0], caller[1], caller[2], msg)

        if debug_location == '1':
            log_file = joinPath(LOGPATH, 'dg.log')
            if not existsPath(log_file):
                f = open(log_file, 'w')
                f.close()
            reverse_log = getSetting('debug.reversed') == 'true'
            if not reverse_log:
                with open(log_file, 'a', encoding='utf-8'
                          ) as f:  # with auto cleans up and closes
                    line = '[%s %s] %s: %s' % (
                        datetime.now().date(), str(datetime.now().time())[:8],
                        DEBUGPREFIX % debug_list[level], msg)
                    f.write(line.rstrip('\r\n') + '\n')
                    # f.writelines([line1, line2]) ## maybe an option for the 2 lines without using "\n"
            else:
                with open(log_file, 'r+', encoding='utf-8') as f:
                    line = '[%s %s] %s: %s' % (
                        datetime.now().date(), str(datetime.now().time())[:8],
                        DEBUGPREFIX % debug_list[level], msg)
                    log_file = f.read()
                    f.seek(0, 0)
                    f.write(line.rstrip('\r\n') + '\n' + log_file)
        else:
            import xbmc
            xbmc.log('%s: %s' % (DEBUGPREFIX % debug_list[level], msg), level)
    except Exception as e:
        import traceback
        traceback.print_exc()
        import xbmc
        xbmc.log(
            '[ plugin.video.dg ] log_utils.log() Logging Failure: %s' % (e),
            LOGERROR)
コード例 #18
0
def insert(meta):
    try:
        if not control.existsPath(control.dataPath):
            control.makeFile(control.dataPath)
        dbcon = database.connect(control.metacacheFile)
        dbcur = dbcon.cursor()
        dbcur.execute("CREATE TABLE IF NOT EXISTS meta ("
                      "imdb TEXT, "
                      "tmdb TEXT, "
                      "tvdb TEXT, "
                      "lang TEXT, "
                      "user TEXT, "
                      "item TEXT, "
                      "time TEXT, "
                      "UNIQUE(imdb, tmdb, tvdb, lang, user)"
                      ");")
        t = int(time.time())

        for m in meta:
            if "user" not in m:
                m["user"] = ''
            if "lang" not in m:
                m["lang"] = 'en'
            i = repr(m['item'])

            # Look for exact match to what is about to be written.
            try:
                dbcur.execute(
                    "SELECT * FROM meta WHERE (imdb = '%s' and tmdb = '%s' and tvdb = '%s' and lang = '%s' and user = '******')"
                    % (m.get('imdb', '0'), m.get(
                        'tmdb', '0'), m.get('tvdb', '0'), m['lang'],
                       m['user'])).fetchone()[0]  # Try to find entry.
                dbcur.execute(
                    "DELETE FROM meta WHERE (imdb = '%s' and tmdb = '%s' and tvdb = '%s' and lang = '%s' and user = '******')"
                    % (m.get('imdb', '0'), m.get('tmdb', '0'),
                       m.get('tvdb', '0'), m['lang'], m['user']))
                # log_utils.log("metacache exact match found and deleted", __name__, log_utils.LOGDEBUG)
            except:
                # log_utils.log("no exact metacache match", __name__, log_utils.LOGDEBUG)
                pass

            try:
                dbcur.execute("INSERT INTO meta Values (?, ?, ?, ?, ?, ?, ?)",
                              (m.get('imdb', '0'), m.get('tmdb', '0'),
                               m.get('tvdb', '0'), m['lang'], m['user'], i, t))
                # log_utils.log("metacache written", __name__, log_utils.LOGDEBUG)
            except:
                # log_utils.log("metacache write failed", __name__, log_utils.LOGDEBUG)
                pass

        dbcur.connection.commit()
        dbcon.close()
    except:
        dbcon.close()
        import traceback
        traceback.print_exc()
        return
コード例 #19
0
def get_connection():
	if not existsPath(dataPath): makeFile(dataPath)
	dbcon = db.connect(fanarttvCacheFile, timeout=60) # added timeout 3/23/21 for concurrency with threads
	dbcon.execute('''PRAGMA page_size = 32768''')
	dbcon.execute('''PRAGMA journal_mode = OFF''')
	dbcon.execute('''PRAGMA synchronous = OFF''')
	dbcon.execute('''PRAGMA temp_store = memory''')
	dbcon.execute('''PRAGMA mmap_size = 30000000000''')
	dbcon.row_factory = _dict_factory
	return dbcon
コード例 #20
0
def log(msg, caller=None, level=LOGNOTICE):
    debug_enabled = control.setting('debug.enabled') == 'true'
    if not debug_enabled: return
    debug_level = control.setting('debug.level')
    if level == LOGDEBUG and debug_level != '1': return
    debug_location = control.setting('debug.location')
    if isinstance(msg, int):
        msg = control.lang(msg)  # for strings.po translations
    try:
        if py_tools.isPY3:
            if not msg.isprintable(
            ):  # ex. "\n" is not a printable character so returns False on those sort of cases
                msg = '%s (NORMALIZED by log_utils.log())' % normalize(msg)
            if isinstance(msg, py_tools.binary_type):
                msg = '%s (ENCODED by log_utils.log())' % (py_tools.ensure_str(
                    msg, errors='replace'))
        else:
            if not is_printable(
                    msg
            ):  # if not all(c in printable for c in msg): # .isprintable() not available in py2
                msg = normalize(msg)
            if isinstance(msg, py_tools.binary_type):
                msg = '%s (ENCODED by log_utils.log())' % (
                    py_tools.ensure_text(msg))

        if caller is not None and level != LOGERROR:
            func = inspect.currentframe().f_back.f_code
            line_number = inspect.currentframe().f_back.f_lineno
            caller = "%s.%s()" % (caller, func.co_name)
            msg = 'From func name: %s Line # :%s\n                       msg : %s' % (
                caller, line_number, msg)
        elif caller is not None and level == LOGERROR:
            msg = 'From func name: %s.%s() Line # :%s\n                       msg : %s' % (
                caller[0], caller[1], caller[2], msg)

        if debug_location == '1':
            log_file = control.joinPath(LOGPATH, 'venom.log')
            if not control.existsPath(log_file):
                f = open(log_file, 'w')
                f.close()
            with open(log_file, 'a', encoding='utf-8') as f:
                line = '[%s %s] %s: %s' % (
                    datetime.now().date(), str(datetime.now().time())[:8],
                    DEBUGPREFIX % debug_list[level], msg)
                f.write(line.rstrip('\r\n') + '\n')
                # f.writelines([line1, line2]) ## maybe an option for the 2 lines without using "\n"
        else:
            xbmc.log('%s: %s' % (DEBUGPREFIX % debug_list[level], msg, level))
    except Exception as e:
        import traceback
        traceback.print_exc()
        xbmc.log(
            '[ plugin.video.venom ] log_utils.log() Logging Failure: %s' % (e),
            LOGERROR)
コード例 #21
0
 def run(self):
     try:
         profile_dir = xbmc.translatePath(
             'special://profile/addon_data/plugin.video.venom/')
         if not control.existsPath(profile_dir):
             success = control.makeDirs(profile_dir)
             if success:
                 xbmc.log('%s : created successfully' % profile_dir, 2)
         else:
             xbmc.log('%s : already exists' % profile_dir, 2)
         settings_xml = control.joinPath(profile_dir, 'settings.xml')
         if not control.existsPath(settings_xml):
             control.setSetting('clear.all.cache', '')
             xbmc.log('%s : created successfully' % settings_xml, 2)
         else:
             xbmc.log('%s : already exists' % settings_xml, 2)
         return
     except:
         import traceback
         traceback.print_exc()
         pass
コード例 #22
0
def fetch_bookmarks(imdb, tmdb='', tvdb='', season=None, episode=None):
    progress = '0'
    try:
        if not control.existsPath(control.dataPath):
            control.makeFile(control.dataPath)
        dbcon = db.connect(control.traktSyncFile)
        dbcur = dbcon.cursor()
        ck_table = dbcur.execute(
            '''SELECT * FROM sqlite_master WHERE type='table' AND name='bookmarks';'''
        ).fetchone()
        if not ck_table:
            dbcur.execute(
                '''CREATE TABLE IF NOT EXISTS bookmarks (imdb TEXT, tmdb TEXT, tvdb TEXT, season TEXT, episode TEXT, percent_played TEXT, paused_at TEXT,
			UNIQUE(imdb, tmdb, tvdb, season, episode));''')
            dbcur.connection.commit()
            dbcur.close()
            dbcon.close()
            return progress
        if not episode:
            try:  # Lookup both IMDb and TMDb first for more accurate match.
                match = dbcur.execute(
                    '''SELECT * FROM bookmarks WHERE (imdb=? AND tmdb=? AND NOT imdb='' AND NOT tmdb='')''',
                    (imdb, tmdb)).fetchone()
                progress = match[5]
            except:
                try:
                    match = dbcur.execute(
                        '''SELECT * FROM bookmarks WHERE (imdb=? AND NOT imdb='')''',
                        (imdb, )).fetchone()
                    progress = match[5]
                except:
                    pass
        else:
            try:  # Lookup both IMDb and TVDb first for more accurate match.
                match = dbcur.execute(
                    '''SELECT * FROM bookmarks WHERE (imdb=? AND tvdb=? AND season=? AND episode=? AND NOT imdb='' AND NOT tvdb='')''',
                    (imdb, tvdb, season, episode)).fetchone()
                progress = match[5]
            except:
                try:
                    match = dbcur.execute(
                        '''SELECT * FROM bookmarks WHERE (tvdb=? AND season=? AND episode=? AND NOT tvdb='')''',
                        (tvdb, season, episode)).fetchone()
                    progress = match[5]
                except:
                    pass
    except:
        log_utils.error()
    finally:
        dbcur.close()
        dbcon.close()
    return progress
コード例 #23
0
def view_LogFile(name):
	try:
		from resources.lib.windows.textviewer import TextViewerXML
		from resources.lib.modules.control import addonPath
		log_file = joinPath(LOGPATH, '%s.log' % name.lower())
		if not existsPath(log_file):
			from resources.lib.modules.control import notification
			return notification(message='Log File not found, likely logging is not enabled.')
		f = open(log_file, 'r', encoding='utf-8', errors='ignore')
		text = f.read()
		f.close()
		heading = '[B]%s -  LogFile[/B]' % name
		windows = TextViewerXML('textviewer.xml', addonPath('plugin.video.venom'), heading=heading, text=text)
		windows.run()
		del windows
	except:
		error()
コード例 #24
0
def clear_logFile():
	cleared = False
	try:
		from resources.lib.modules.control import yesnoDialog
		if not yesnoDialog(lang(32056), '', ''): return 'canceled'
		log_file = joinPath(LOGPATH, 'venom.log')
		if not existsPath(log_file):
			f = open(log_file, 'w')
			return f.close()
		f = open(log_file, 'r+')
		f.truncate(0) # need '0' when using r
		f.close()
		cleared = True
	except Exception as e:
		import xbmc
		xbmc.log('[ plugin.video.venom ] log_utils.clear_logFile() Failure: %s' % (e), LOGERROR)
		cleared = False
	return cleared
コード例 #25
0
def delete_bookmark(items):
    try:
        if not control.existsPath(control.dataPath):
            control.makeFile(control.dataPath)
        dbcon = db.connect(control.traktSyncFile)
        dbcur = dbcon.cursor()
        ck_table = dbcur.execute(
            '''SELECT * FROM sqlite_master WHERE type='table' AND name='bookmarks';'''
        ).fetchone()
        if not ck_table:
            dbcur.execute(
                '''CREATE TABLE IF NOT EXISTS bookmarks (imdb TEXT, tmdb TEXT, tvdb TEXT, season TEXT, episode TEXT, percent_played TEXT, paused_at TEXT,
			UNIQUE(imdb, tmdb, tvdb, season, episode));''')
            dbcur.execute(
                '''CREATE TABLE IF NOT EXISTS service (setting TEXT, value TEXT, UNIQUE(setting));'''
            )
            dbcur.connection.commit()
            return
        for i in items:
            if i.get('type') == 'episode':
                ids = i.get('show').get('ids')
                imdb, tvdb, season, episode, = str(ids.get('imdb', '')), str(
                    ids.get('tvdb',
                            '')), str(i.get('episode').get('season')), str(
                                i.get('episode').get('number'))
            else:
                tvdb, season, episode = '', '', ''
                ids = i.get('movie').get('ids')
                imdb = str(ids.get('imdb', ''))
            try:
                dbcur.execute(
                    '''DELETE FROM bookmarks WHERE (imdb=? AND tvdb=? AND season=? AND episode=?)''',
                    (imdb, tvdb, season, episode))
                dbcur.execute(
                    '''INSERT OR REPLACE INTO service Values (?, ?)''',
                    ('last_paused_at', i.get('paused_at', '')))
                dbcur.connection.commit()
            except:
                pass
    except:
        log_utils.error()
    finally:
        dbcur.close()
        dbcon.close()
コード例 #26
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
コード例 #27
0
def log(msg, caller=None, level=LOGNOTICE):
    debug_enabled = control.setting('debug.enabled') == 'true'
    if not debug_enabled: return
    debug_level = control.setting('debug.level')
    if level == LOGDEBUG and debug_level != '1': return
    debug_location = control.setting('debug.location')

    try:
        if caller is not None and level != LOGERROR:
            func = inspect.currentframe().f_back.f_code
            line_number = inspect.currentframe().f_back.f_lineno
            caller = "%s.%s()" % (caller, func.co_name)
            msg = 'From func name: %s Line # :%s\n                       msg : %s' % (
                caller, line_number, msg)
        if caller is not None and level == LOGERROR:
            msg = 'From func name: %s.%s() Line # :%s\n                       msg : %s' % (
                caller[0], caller[1], caller[2], msg)
        try:
            if isinstance(msg, py_tools.text_type):
                # msg = msg.encode('ascii', errors='ignore').decode('ascii', errors='ignore') moved this to `ensure_str(), check if it's correct.
                msg = '%s (ENCODED)' % (py_tools.ensure_str(msg,
                                                            errors='replace'))
        except:
            pass

        if debug_location == '1':
            log_file = control.joinPath(LOGPATH, 'venom.log')
            if not control.existsPath(log_file):
                f = open(log_file, 'w')
                f.close()
            with open(log_file, 'a') as f:
                line = '[%s %s] %s: %s' % (
                    datetime.now().date(), str(datetime.now().time())[:8],
                    DEBUGPREFIX % debug_list[level], msg)
                f.write(line.rstrip('\r\n') + '\n')
        else:
            xbmc.log('%s: %s' % (DEBUGPREFIX % debug_list[level], msg, level))
    except Exception as e:
        xbmc.log(
            '[ plugin.video.venom ] log_utils.log() Logging Failure: %s' % (e),
            LOGERROR)
コード例 #28
0
def insert_bookmarks(items, new_scrobble=False):
    try:
        if not control.existsPath(control.dataPath):
            control.makeFile(control.dataPath)
        dbcon = db.connect(control.traktSyncFile)
        dbcur = dbcon.cursor()
        dbcur.execute(
            '''CREATE TABLE IF NOT EXISTS bookmarks (imdb TEXT, tmdb TEXT, tvdb TEXT, season TEXT, episode TEXT, percent_played TEXT, paused_at TEXT,
		UNIQUE(imdb, tmdb, tvdb, season, episode));''')
        dbcur.execute(
            '''CREATE TABLE IF NOT EXISTS service (setting TEXT, value TEXT, UNIQUE(setting));'''
        )
        if not new_scrobble:
            dbcur.execute('''DELETE FROM bookmarks''')
            dbcur.execute('''VACUUM''')
        for i in items:
            imdb, tmdb, tvdb, season, episode = '', '', '', '', ''
            if i.get('type') == 'episode':
                ids = i.get('show').get('ids')
                imdb, tmdb, tvdb, season, episode = str(ids.get(
                    'imdb', '')), str(ids.get('tmdb', '')), str(
                        ids.get('tvdb',
                                '')), str(i.get('episode').get('season')), str(
                                    i.get('episode').get('number'))
            else:
                ids = i.get('movie').get('ids')
                imdb, tmdb = str(ids.get('imdb', '')), str(ids.get('tmdb', ''))
            dbcur.execute(
                '''INSERT OR REPLACE INTO bookmarks Values (?, ?, ?, ?, ?, ?, ?)''',
                (imdb, tmdb, tvdb, season, episode, i.get(
                    'progress', ''), i.get('paused_at', '')))
        timestamp = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S.000Z")
        dbcur.execute('''INSERT OR REPLACE INTO service Values (?, ?)''',
                      ('last_paused_at', timestamp))
        dbcur.connection.commit()
    except:
        log_utils.error()
    finally:
        dbcur.close()
        dbcon.close()
コード例 #29
0
def insert(meta):
	try:
		if not control.existsPath(control.dataPath):
			control.makeFile(control.dataPath)
		dbcon = database.connect(control.metacacheFile)
		dbcur = dbcon.cursor()
		dbcur.execute("CREATE TABLE IF NOT EXISTS meta (""imdb TEXT, ""tmdb TEXT, ""tvdb TEXT, ""lang TEXT, ""user TEXT, ""item TEXT, ""time TEXT, ""UNIQUE(imdb, tmdb, tvdb, lang, user)"");")
		t = int(time.time())

		for m in meta:
			if "user" not in m:
				m["user"] = ''
			if "lang" not in m:
				m["lang"] = 'en'
			i = repr(m['item'])

			# # Look for exact match to what is about to be written.
			# try:
				# dbcur.execute("SELECT * FROM meta WHERE (imdb = '%s' and tmdb = '%s' and tvdb = '%s' and lang = '%s' and user = '******')" % (m.get('imdb', '0'), m.get('tmdb', '0'), m.get('tvdb', '0'), m['lang'], m['user'])).fetchone()[0] # Try to find entry.
				# dbcur.execute("DELETE FROM meta WHERE (imdb = '%s' and tmdb = '%s' and tvdb = '%s' and lang = '%s' and user = '******')" % (m.get('imdb', '0'), m.get('tmdb', '0'), m.get('tvdb', '0'), m['lang'], m['user']))
			# except:
				# pass

			try:
				# dbcur.execute("INSERT INTO meta Values (?, ?, ?, ?, ?, ?, ?)", (m.get('imdb', '0'), m.get('tmdb', '0'), m.get('tvdb', '0'), m['lang'], m['user'], i, t))
				dbcur.execute("INSERT OR REPLACE INTO meta Values (?, ?, ?, ?, ?, ?, ?)", (m.get('imdb', '0'), m.get('tmdb', '0'), m.get('tvdb', '0'), m['lang'], m['user'], i, t))

			except:
				pass

		dbcur.connection.commit()
	except:
		log_utils.error()
		pass

	try:
		dbcon.close()
	except:
		pass
	return
コード例 #30
0
def get(name):
    nameDict = {
        'DG': 'plugin.video.dg',
        'MyAccounts': 'script.module.myaccounts',
        'FenomScrapers': 'script.module.fenomscrapers'
    }
    addon_path = addonPath(nameDict[name])
    addon_version = addonVersion(nameDict[name])
    changelog_file = joinPath(addon_path, 'changelog.txt')
    if not existsPath(changelog_file):
        from resources.lib.modules.control import notification
        return notification(message='ChangeLog File not found.')
    f = open(changelog_file, 'r', encoding='utf-8', errors='ignore')
    text = f.read()
    f.close()
    heading = '[B]%s -  v%s - ChangeLog[/B]' % (name, addon_version)
    windows = TextViewerXML('textviewer.xml',
                            addonPath('plugin.video.dg'),
                            heading=heading,
                            text=text)
    windows.run()
    del windows