Пример #1
0
def insert(meta):
    try:
        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, ""item TEXT, ""time TEXT, ""UNIQUE(imdb, tmdb, tvdb, lang)"");")
        t = int(time.time())
        for m in meta:
            try:
                i = repr(m['item'])
                try:
                    dbcur.execute(
                        "DELETE FROM meta WHERE (imdb = '%s' and lang = '%s' and not imdb = '0') or (tmdb = '%s' and lang = '%s' and not tmdb = '0') or (tvdb = '%s' and lang = '%s' and not tvdb = '0')" % (
                            m['imdb'], m['lang'], m['tmdb'], m['lang'], m['tvdb'], m['lang']))
                except:
                    pass
                dbcur.execute("INSERT INTO meta Values (?, ?, ?, ?, ?, ?)",
                              (m['imdb'], m['tmdb'], m['tvdb'], m['lang'], i, t))
            except:
                pass

        dbcon.commit()
    except:
        return
Пример #2
0
    def add_progress_movies(self, meta):
		try:
			
			item = dict()
			typeofcontent = 'movies'
			print ("META DUMP FAVOURITES 3" , meta, typeofcontent)

			try: id = meta['imdb']
			except: id = meta['tvdb']
			
			if 'title' in meta: title = item['title'] = meta['title']
			if 'tvshowtitle' in meta: title = item['title'] = meta['tvshowtitle']
			if 'year' in meta: item['year'] = meta['year']
			if 'poster' in meta: item['poster'] = meta['poster']
			if 'fanart' in meta: item['fanart'] = meta['fanart']
			if 'imdb' in meta: item['imdb'] = meta['imdb']
			if 'tmdb' in meta: item['tmdb'] = meta['tmdb']
			if 'tvdb' in meta: item['tvdb'] = meta['tvdb']
			if 'tvrage' in meta: item['tvrage'] = meta['tvrage']
			
			

			control.makeFile(dataPath)
			dbcon = database.connect(progressFile)
			dbcur = dbcon.cursor()
			dbcur.execute("CREATE TABLE IF NOT EXISTS %s (""id TEXT, ""items TEXT, ""UNIQUE(id)"");" % typeofcontent)
			dbcur.execute("DELETE FROM %s WHERE id = '%s'" % (typeofcontent, id))
			dbcur.execute("INSERT INTO %s Values (?, ?)" % typeofcontent, (id, repr(item)))
			dbcon.commit()

			# control.refresh()
			# control.infoDialog('Added to Watchlist', heading=title)
		except:
			return
Пример #3
0
def inserttraktwatchedcheck(showid, rdate):

    try:

        control.makeFile(control.dataPath);
        dbcon = database.connect(control.synchFile);
        dbcur = dbcon.cursor();

        dbcur.execute("CREATE TABLE IF NOT EXISTS trakt_watched_check (""show_id TEXT, ""lastupdated TEXT, ""UNIQUE(show_id)"");")

        try:

            try: 
                dbcur.execute("DELETE FROM trakt_watched_check WHERE show_id = %s" % showid);

            except Exception as inst:
                #logger.error(inst);

                pass;

            dbcur.execute("INSERT INTO trakt_watched_check Values (?, ?)", (showid, rdate));

        except Exception as inst:
            #logger.error(inst);

            pass;

        dbcon.commit();

    except:
        return;
Пример #4
0
def inserttvdbseries(meta):

    try:

        control.makeFile(control.dataPath);
        dbcon = database.connect(control.synchFile);
        dbcur = dbcon.cursor();

        dbcur.execute("CREATE TABLE IF NOT EXISTS tvdb_series_info (""show_id TEXT, ""tvdbid TEXT, ""imdbid TEXT, ""seriesid TEXT, ""traktid TEXT, ""lastUpdated TEXT, ""seriesName TEXT, ""status TEXT, ""firstAired TEXT, ""firstEpisode TEXT, ""genre TEXT, ""network TEXT, ""siteRating TEXT, ""siteRatingCount TEXT, ""images TEXT, ""UNIQUE(show_id, tvdbid)"");")

        try:

            try: 
                dbcur.execute("DELETE FROM tvdb_series_info WHERE (show_id = '%s' and tvdbid = '%s')" % (meta['show_id'], meta['tvdbid']));

            except Exception as inst:
                #logger.error(inst);

                pass;

            dbcur.execute("INSERT INTO tvdb_series_info Values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", (meta['show_id'], meta['tvdbid'], meta['imdbid'], meta['seriesid'], meta['traktid'], meta['lastUpdated'], meta['seriesName'], meta['status'], meta['firstAired'], meta['firstEpisode'], meta['genre'], meta['network'], meta['siteRating'], meta['siteRatingCount'], meta['images']));

            #dbcur.execute("INSERT INTO tvdb_series_info Values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", meta.values()); #We like this idea but the values seem to have random placement due to restrictions on the dictionary

        except Exception as inst:
            #logger.error(inst);

            pass;

        dbcon.commit();

    except:
        return;
Пример #5
0
def get_favorites_menu(url):
    import resources.lib.indexers.bob
    indexer = resources.lib.indexers.bob.Indexer()
    try:
        control.makeFile(control.dataPath)
        dbcon = database.connect(control.cacheFile)
        dbcur = dbcon.cursor()
        dbcur.execute("SELECT DISTINCT(fav_type) from %s" % table)
        for row in dbcur:
            fav_type = row[0]
            if fav_type == "movie":
                poster = "http://norestrictions.club/norestrictions.club/main/icons/my_movies.jpg"
            elif fav_type == "tv show":
                poster = "http://norestrictions.club/norestrictions.club/main/icons/my_tv_shows.jpg"
            else:
                poster = "http://norestrictions.club/norestrictions.club/main/icons/my_blank.jpg"
            indexer.list.append({'name': fav_type.title(), 'url': url, 'action': 'getfavorites_%s' % fav_type, 'folder': True,
                                 'poster': poster})
        if indexer.list == []:
            import xbmcgui
            xbmcgui.Dialog().ok("Bob's Faves", "Add Your Bob Faves Here")
        indexer.worker()
        indexer.add_directory(indexer.list, parent_url=url)
    except:
        pass
Пример #6
0
    def strmFile(self, i):
        try:
            name, title, year, imdb, tmdb = i["title"], i["title"], i["year"], i["imdb"]

            sysname, systitle = urllib.quote_plus(name), urllib.quote_plus(title)

            transname = name.translate(None, '\/:*?"<>|').strip(".")

            content = "%s?action=play&name=%s&title=%s&year=%s&imdb=%s" % (sys.argv[0], sysname, systitle, year, imdb)

            control.makeFile(self.library_folder)
            folder = os.path.join(self.library_folder, transname)
            control.makeFile(folder)

            try:
                if not "ftp://" in folder:
                    raise Exception()
                from ftplib import FTP

                ftparg = re.compile("ftp://(.+?):(.+?)@(.+?):?(\d+)?/(.+/?)").findall(folder)
                ftp = FTP(ftparg[0][2], ftparg[0][0], ftparg[0][1])
                try:
                    ftp.cwd(ftparg[0][4])
                except:
                    ftp.mkd(ftparg[0][4])
                ftp.quit()
            except:
                pass

            stream = os.path.join(folder, transname + ".strm")
            file = control.openFile(stream, "w")
            file.write(str(content))
            file.close()
        except:
            pass
Пример #7
0
def addFavourite(meta, content, query):
    try:
        item = dict()
        meta = json.loads(meta)
        try: id = meta['imdb']
        except: id = meta['tvdb']

        if 'title' in meta: title = item['title'] = meta['title']
        if 'tvshowtitle' in meta: title = item['title'] = meta['tvshowtitle']
        if 'year' in meta: item['year'] = meta['year']
        if 'poster' in meta: item['poster'] = meta['poster']
        if 'fanart' in meta: item['fanart'] = meta['fanart']
        if 'imdb' in meta: item['imdb'] = meta['imdb']
        if 'tmdb' in meta: item['tmdb'] = meta['tmdb']
        if 'tvdb' in meta: item['tvdb'] = meta['tvdb']
        if 'tvrage' in meta: item['tvrage'] = meta['tvrage']

        control.makeFile(control.dataPath)
        dbcon = database.connect(control.favouritesFile)
        dbcur = dbcon.cursor()
        dbcur.execute("CREATE TABLE IF NOT EXISTS %s (""id TEXT, ""items TEXT, ""UNIQUE(id)"");" % content)
        dbcur.execute("DELETE FROM %s WHERE id = '%s'" % (content, id))
        dbcur.execute("INSERT INTO %s Values (?, ?)" % content, (id, repr(item)))
        dbcon.commit()

        if query == None: control.refresh()
        control.infoDialog(control.lang(30411).encode('utf-8'), heading=title)
    except:
        return
Пример #8
0
def fetchtraktprogresslastupdated():

    try:

        control.makeFile(control.dataPath);
        dbcon = database.connect(control.synchFile);
        dbcur = dbcon.cursor();

        dbcur.execute("CREATE TABLE IF NOT EXISTS trakt_progress_info (""trakt_series_id TEXT, ""trakt_episode_id TEXT, ""tvdbid TEXT, ""tvdbeid TEXT, ""season TEXT, ""episode TEXT, ""trakt_progress TEXT, ""lastupdated TEXT, ""UNIQUE(trakt_series_id, trakt_episode_id, tvdbid, tvdbeid)"");");

    except:
        return None;

    try:

        sql_stmt = """
            SELECT lastupdated
            FROM trakt_progress_info
        """;

        dbcur.execute(sql_stmt);

        match = dbcur.fetchall();
        
        if match is not None:
            return match[0][0];

        else:
            return None;


    except Exception as inst:
        #logger.error(inst);

        return None;
Пример #9
0
def updatefnqueue(meta, queuestate=0):

    try:

        control.makeFile(control.dataPath);
        dbcon = database.connect(control.synchFile);
        dbcur = dbcon.cursor();

        dbcur.execute("CREATE TABLE IF NOT EXISTS fn_queue_info (""asset_id TEXT, ""inqueue TEXT, ""UNIQUE(asset_id)"");");

        for m in meta:

            try:

                dbcur.execute("INSERT OR IGNORE INTO fn_queue_info (asset_id, inqueue) VALUES ('%s', %s)" % (m['asset_id'], queuestate));
                dbcur.execute("UPDATE fn_queue_info SET inqueue = %s WHERE asset_id = %s" % (queuestate, m['asset_id']));

            except Exception as inst:
                #logger.error(inst);

                pass;

        dbcon.commit();

    except Exception as inst:
        #logger.error(inst);

        return None;
Пример #10
0
def timeout(function, *args, **table):
    try:
        response = None

        f = repr(function)
        f = re.sub('.+\smethod\s|.+function\s|\sat\s.+|\sof\s.+', '', f)

        a = hashlib.md5()
        for i in args: a.update(str(i))
        a = str(a.hexdigest())
    except:
        pass

    try:
        table = table['table']
    except:
        table = 'rel_list'

    try:
        control.makeFile(control.dataPath)
        dbcon = database.connect(control.cacheFile)
        dbcur = dbcon.cursor()
        dbcur.execute("SELECT * FROM %s WHERE func = '%s' AND args = '%s'" % (table, f, a))
        match = dbcur.fetchone()
        return int(match[3])
    except:
        return
Пример #11
0
def addFavourite(meta, content):
    try:
        item = dict()
        meta = json.loads(meta)
        # print "META DUMP FAVOURITES %s" % meta
        try: id = meta['imdb']
        except: id = meta['tvdb']
        
        if 'title' in meta: title = item['title'] = meta['title']
        if 'tvshowtitle' in meta: title = item['title'] = meta['tvshowtitle']
        if 'year' in meta: item['year'] = meta['year']
        if 'poster' in meta: item['poster'] = meta['poster']
        if 'fanart' in meta: item['fanart'] = meta['fanart']
        if 'imdb' in meta: item['imdb'] = meta['imdb']
        if 'tmdb' in meta: item['tmdb'] = meta['tmdb']
        if 'tvdb' in meta: item['tvdb'] = meta['tvdb']
        if 'tvrage' in meta: item['tvrage'] = meta['tvrage']

        control.makeFile(dataPath)
        dbcon = database.connect(favouritesFile)
        dbcur = dbcon.cursor()
        dbcur.execute("CREATE TABLE IF NOT EXISTS %s (""id TEXT, ""items TEXT, ""UNIQUE(id)"");" % content)
        dbcur.execute("DELETE FROM %s WHERE id = '%s'" % (content, id))
        dbcur.execute("INSERT INTO %s Values (?, ?)" % content, (id, repr(item)))
        dbcon.commit()

        control.refresh()
        control.infoDialog('Added to Watchlist', heading=title)
    except:
        return
Пример #12
0
def addView(content):
    try:
        skin = control.skin
        skinPath = control.skinPath
        xml = os.path.join(skinPath,'addon.xml')
        file = control.openFile(xml)
        read = file.read().replace('\n','')
        file.close()
        try: src = re.compile('defaultresolution="(.+?)"').findall(read)[0]
        except: src = re.compile('<res.+?folder="(.+?)"').findall(read)[0]
        src = os.path.join(skinPath, src)
        src = os.path.join(src, 'MyVideoNav.xml')
        file = control.openFile(src)
        read = file.read().replace('\n','')
        file.close()
        views = re.compile('<views>(.+?)</views>').findall(read)[0]
        views = [int(x) for x in views.split(',')]
        for view in views:
            label = control.infoLabel('Control.GetLabel(%s)' % (view))
            if not (label == '' or label == None): break
        record = (skin, content, str(view))
        control.makeFile(control.dataPath)
        dbcon = database.connect(control.viewsFile)
        dbcur = dbcon.cursor()
        dbcur.execute("CREATE TABLE IF NOT EXISTS views (""skin TEXT, ""view_type TEXT, ""view_id TEXT, ""UNIQUE(skin, view_type)"");")
        dbcur.execute("DELETE FROM views WHERE skin = '%s' AND view_type = '%s'" % (record[0], record[1]))
        dbcur.execute("INSERT INTO views Values (?, ?, ?)", record)
        dbcon.commit()
        viewName = control.infoLabel('Container.Viewmode')

        control.infoDialog(control.lang(30491).encode('utf-8'), heading=viewName)
    except:
        return
Пример #13
0
def get_favorites(fav_type, url):
    try:
        import resources.lib.indexers.bob
        indexer = resources.lib.indexers.bob.Indexer()
        control.makeFile(control.dataPath)
        dbcon = database.connect(control.cacheFile)
        dbcur = dbcon.cursor()
        dbcur.execute("SELECT * FROM %s WHERE fav_type = '%s'" % (table, fav_type))
        import xbmc
        for match in dbcur:
            name = match[0].encode("utf-8")
            link = match[2].encode("utf-8")
            poster = match[3]
            fanart = match[4]
            if match[2].endswith('.xml'):
                item = {'name': name, 'url': urllib.quote(link).replace("http%3A", "http:"), 'action': 'directory', 'folder': True,
                        'content': '%s-favs' % fav_type, 'poster': poster, 'fanart': fanart}
            else:
                year = indexer.bob_get_tag_content(link, "year", "")
                imdb = indexer.bob_get_tag_content(link, "imdb", "")
                title = indexer.bob_get_tag_content(link, "title", "")
                item = {'name': name, 'vip': "", 'url': link, 'action': "play", 'folder': False, 'poster': poster,
                        'banner': '0', 'fanart': fanart, 'content': '%s-favs' % fav_type, 'imdb': imdb, 'tvdb': '0',
                        'tmdb': '0', 'title': title, 'originaltitle': title, 'tvshowtitle': '', 'year': year,
                        'premiered': '', 'season': '', 'episode': ''}
            indexer.list.append(item)
        if indexer.list == []:
            item = {'name': '..', 'url': 'plugin://plugin.video.bob', 'action': 'plugin', 'folder': False,
                        'content': '', 'poster': '0', 'fanart': '0'}
            indexer.list.append(item)
        indexer.worker()
        indexer.add_directory(indexer.list, parent_url=url)

    except:
        pass
Пример #14
0
    def add_progress_episodes(self, meta):
		try:

			item = dict()
			typeofcontent = 'episode'

			id = meta['tvdb']
			
			if 'title' in meta: title = item['title'] = meta['title']
			if 'tvshowtitle' in meta: item['tvshowtitle'] = meta['tvshowtitle']
			if 'year' in meta: item['year'] = meta['year']
			if 'poster' in meta: item['poster'] = meta['poster']
			if 'fanart' in meta: item['fanart'] = meta['fanart']
			if 'imdb' in meta: item['imdb'] = meta['imdb']
			if 'tmdb' in meta: item['tmdb'] = meta['tmdb']
			if 'tvdb' in meta: item['tvdb'] = meta['tvdb']
			if 'tvrage' in meta: item['tvrage'] = meta['tvrage']
			if 'episode' in meta: item['episode'] = meta['episode']
			if 'season' in meta: item['season'] = meta['season']
			if 'premiered' in meta: item['premiered'] = meta['premiered']
			if 'original_year' in meta: item['original_year'] = meta['original_year']


			control.makeFile(dataPath)
			dbcon = database.connect(progressFile)
			dbcur = dbcon.cursor()
			dbcur.execute("CREATE TABLE IF NOT EXISTS %s (""id TEXT, ""items TEXT, ""UNIQUE(id)"");" % typeofcontent)
			dbcur.execute("DELETE FROM %s WHERE id = '%s'" % (typeofcontent, id))
			dbcur.execute("INSERT INTO %s Values (?, ?)" % typeofcontent, (id, repr(item)))
			dbcon.commit()

		except:
			return
Пример #15
0
 def __init__(self):
     try:
         control.makeFile(control.dataPath)
         self.dbcon = database.connect(control.favoriteFile)
         self.dbcur = self.dbcon.cursor()
         self.dbcur.execute("CREATE TABLE IF NOT EXISTS favorites (""anime_id INTEGER, UNIQUE(anime_id) "");")
     except:
         pass
Пример #16
0
def bennu_download_get(function, timeout, *args, **table):
    try:
        response = None

        f = repr(function)
        f = re.sub('.+\smethod\s|.+function\s|\sat\s.+|\sof\s.+', '', f)

        a = hashlib.md5()
        for i in args: a.update(str(i))
        a = str(a.hexdigest())
    except:
        pass

    try:
        table = table['table']
    except:
        table = 'rel_list'

    try:
        control.makeFile(control.dataPath)
        dbcon = db.connect(control.cacheFile)
        dbcur = dbcon.cursor()
        dbcur.execute("SELECT * FROM %s WHERE func = '%s' AND args = '%s'" % (table, f, a))
        match = dbcur.fetchone()

        response = eval(match[2].encode('utf-8'))

        t1 = int(match[3])
        t2 = int(time.time())
        update = (abs(t2 - t1) / 3600) >= int(timeout)
        if update == False:
            return response
    except:
        pass

    try:
        r = function(*args)
        if (r == None or r == []) and not response == None:
            return response
        elif (r == None or r == []):
            return r
    except:
        return

    try:
        r = repr(r)
        t = int(time.time())
        dbcur.execute("CREATE TABLE IF NOT EXISTS %s (""func TEXT, ""args TEXT, ""response TEXT, ""added TEXT, ""UNIQUE(func, args)"");" % table)
        dbcur.execute("DELETE FROM %s WHERE func = '%s' AND args = '%s'" % (table, f, a))
        dbcur.execute("INSERT INTO %s Values (?, ?, ?, ?)" % table, (f, a, r, t))
        dbcon.commit()
    except:
        pass

    try:
        return eval(r.encode('utf-8'))
    except:
        pass
Пример #17
0
def remove_favorite(name, fav_type, link):
    try:
        control.makeFile(control.dataPath)
        dbcon = database.connect(control.cacheFile)
        dbcur = dbcon.cursor()
        dbcur.execute("DELETE FROM %s WHERE name = \"%s\" AND fav_type = \"%s\"" % (table, name, fav_type))
        dbcon.commit()
        return True
    except:
        return False
Пример #18
0
def inserttvdbtoken(token, edate, rdate):
    
    logger.debug('Attempting to update tvdbtoken DB.');
    
    try:

        logger.debug('Validating DB file exists.');

        control.makeFile(control.dataPath);

        dbcon = database.connect(control.synchFile);
        dbcur = dbcon.cursor();

        logger.debug('Creating tvdbtoken table if it does not exist.');

        dbcur.execute("CREATE TABLE IF NOT EXISTS tvdbtoken (""token TEXT, ""expiredate TEXT, ""refreshdate TEXT"");");

        try: 

            logger.debug('Attempting to delete tvdbtoken entry.');

            dbcur.execute("DELETE FROM tvdbtoken");

        except Exception as inst:

            #logger.error(inst);

            pass;

        
        try: 

            logger.debug('Attempting to insert tvdbtoken entry.');

            dbcur.execute("INSERT INTO tvdbtoken Values (?, ?, ?)", (token, edate, rdate));

        except Exception as inst:

            #logger.error(inst);

            pass;


        logger.debug('Commiting DB change.');
        
        dbcon.commit();

        return True;


    except Exception as inst:

        #logger.error(inst);

        return False;
Пример #19
0
def get(function, timeout, *args):
    try:
        response = None

        f = repr(function)
        f = re.sub('.+\smethod\s|.+function\s|\sat\s.+|\sof\s.+', '', f)

        a = hashlib.md5()
        for i in args: a.update(str(i))
        a = str(a.hexdigest())
    except:
        pass

    try:
        control.makeFile(control.dataPath)
        dbcon = database.connect(control.cachemetaFile)
        dbcur = dbcon.cursor()
        dbcur.execute("SELECT * FROM rel_list WHERE func = '%s' AND args = '%s'" % (f, a))
        match = dbcur.fetchone()

        response = eval(match[2].encode('utf-8'))

        t1 = int(match[3])
        t2 = int(time.time())
        update = (abs(t2 - t1) / 3600) >= int(timeout)
        if update == False:
            return response
    except:
        pass

    try:
        r = function(*args)
        if (r == None or r == []) and not response == None:
            return response
        elif (r == None or r == []):
            return r
    except:
        return

    try:
        insert = True
        if r['cover_url'] == '' or r['backdrop_url'] == '': insert = False
        r = repr(r)
        t = int(time.time())
        dbcur.execute("CREATE TABLE IF NOT EXISTS rel_list (""func TEXT, ""args TEXT, ""response TEXT, ""added TEXT, ""UNIQUE(func, args)"");")
        dbcur.execute("DELETE FROM rel_list WHERE func = '%s' AND args = '%s'" % (f, a))
        if insert == True: dbcur.execute("INSERT INTO rel_list Values (?, ?, ?, ?)", (f, a, r, t))
        dbcon.commit()
    except:
        pass

    try:
        return eval(r.encode('utf-8'))
    except:
        pass
Пример #20
0
def add_favorite(name, fav_type, link, poster, fanart):
    try:
        control.makeFile(control.dataPath)
        dbcon = database.connect(control.cacheFile)
        dbcur = dbcon.cursor()
        dbcur.execute(
            "CREATE TABLE IF NOT EXISTS %s (""name TEXT, ""fav_type TEXT, ""link TEXT, ""poster TEXT, ""fanart TEXT, ""UNIQUE(name, fav_type)"");" % table)
        dbcur.execute("INSERT INTO %s Values (?, ?, ?, ?, ?)" % table, (name, fav_type, link, poster, fanart))
        dbcon.commit()
        return True
    except:
        return False
Пример #21
0
    def prepareSources(self):
        try:
            control.makeFile(control.dataPath)

            self.sourceFile = control.providercacheFile

            dbcon = database.connect(self.sourceFile)
            dbcur = dbcon.cursor()
            dbcur.execute("CREATE TABLE IF NOT EXISTS rel_url (""source TEXT, ""imdb_id TEXT, ""season TEXT, ""episode TEXT, ""rel_url TEXT, ""UNIQUE(source, imdb_id, season, episode)"");")
            dbcur.execute("CREATE TABLE IF NOT EXISTS rel_src (""source TEXT, ""imdb_id TEXT, ""season TEXT, ""episode TEXT, ""hosts TEXT, ""added TEXT, ""UNIQUE(source, imdb_id, season, episode)"");")
        except:
            pass
Пример #22
0
def insert(uid, rctext, fninfo):
    
    try:

        control.makeFile(control.dataPath);

        dbcon = database.connect(control.cookiesFile);
        dbcur = dbcon.cursor();

        logger.debug('Creating cookie table if it does not exist.');

        dbcur.execute("CREATE TABLE IF NOT EXISTS cookies (""uid TEXT, ""rctext TEXT, ""fninfo TEXT, UNIQUE(uid)"");");

        try: 

            logger.debug('Attempting to delete cookie entry.');

            #dbcur.execute("DELETE * FROM cookies WHERE (uid = '%s')" % (uid));  # * Is causing a syntax error
            dbcur.execute("DELETE FROM cookies WHERE (uid = '%s')" % (uid));

        except Exception as inst:

            logger.error(inst);

            pass;

        
        try: 

            logger.debug('Attempting to insert cookie entry.');

            dbcur.execute("INSERT INTO cookies Values (?, ?, ?)", (uid, rctext, fninfo));

        except Exception as inst:

            logger.error(inst);

            pass;


        logger.debug('Commiting DB change.');
        
        dbcon.commit();

        return True;


    except Exception as inst:

        logger.error(inst);

        return False;
Пример #23
0
def insert(data):
    try:
        control.makeFile(control.dataPath)
        cacheFile = os.path.join(control.dataPath, 'regex.db')
        dbcon = database.connect(cacheFile)
        dbcur = dbcon.cursor()
        dbcur.execute("CREATE TABLE IF NOT EXISTS regex (""regex TEXT, ""response TEXT, ""UNIQUE(regex)"");")
        for i in data:
            try: dbcur.execute("INSERT INTO regex Values (?, ?)", (i['regex'], i['response']))
            except: pass
        dbcon.commit()
    except:
        return
Пример #24
0
def check_empty(fav_type = None):
    try:
        control.makeFile(control.dataPath)
        dbcon = database.connect(control.cacheFile)
        dbcur = dbcon.cursor()
        if not fav_type:
            dbcur.execute("SELECT * FROM %s" % (table))
        else:
            dbcur.execute("SELECT * FROM %s WHERE fav_type=%s" % (table, fav_type))
        for match in dbcur:
            return False
        return True
    except:
        return True
Пример #25
0
def deleteBookmark(name, year='0'):
    try:
        idFile = hashlib.md5()
        for i in name: idFile.update(str(i))
        for i in year: idFile.update(str(i))
        idFile = str(idFile.hexdigest())
        control.makeFile(control.dataPath)
        dbcon = database.connect(control.bookmarksFile)
        dbcur = dbcon.cursor()
        dbcur.execute("CREATE TABLE IF NOT EXISTS bookmark (""idFile TEXT, ""timeInSeconds TEXT, ""UNIQUE(idFile)"");")
        dbcur.execute("DELETE FROM bookmark WHERE idFile = '%s'" % idFile)
        dbcon.commit()
    except:
        pass
Пример #26
0
    def clearSources(self):
        try:
            control.idle()

            yes = control.yesnoDialog(control.lang(30510).encode('utf-8'), '', '')
            if not yes: return

            control.makeFile(control.dataPath)
            dbcon = database.connect(control.providercacheFile)
            dbcur = dbcon.cursor()
            dbcur.execute("DROP TABLE IF EXISTS rel_src")
            dbcur.execute("VACUUM")
            dbcon.commit()

            control.infoDialog(control.lang(30511).encode('utf-8'))
        except:
            pass
Пример #27
0
def getShowLocalIndicator(imdb):
    try:
        import sys,xbmc
        from resources.lib.modules import control
        

        total = '6'
        from metahandler import metahandlers
        metaget = metahandlers.MetaData(preparezip=False)
        try: from sqlite3 import dbapi2 as database
        except: from pysqlite2 import dbapi2 as database
        season_playcount = []
        season_file = control.seasons_meta
        id = imdb.encode('utf-8')	
        try:

            control.makeFile(control.dataPath)
            dbcon = database.connect(season_file)
            dbcur = dbcon.cursor()
            dbcur.execute("SELECT playcount FROM season_meta WHERE imdb = '%s'" % (id))
            match = dbcur.fetchall()
            for playcount in match:
				if '7' in str(playcount): play = '7'
				else: play = '6'
				season_playcount.append(play)
				
        except:
            pass			


        if "6" in season_playcount: 
			total = '6'
			return total
        elif int(len(season_playcount)) > 0:
			if not "6" in season_playcount:
				total = '7'
				metaget._update_watched(id, 'tvshow', int(total))

        total = metaget._get_watched('tvshow', id, '', '')  
        print ("ELYSIUM SEASON PLAYCOUNT", imdb, season_playcount, total)	       		
        total = str(total)
        return total
        
    except:
        return total
Пример #28
0
def insert(meta):
    try:
        if not meta: return
        control.makeFile(control.dataPath)
        metacacheFile = os.path.join(control.dataPath, 'meta.5.db')

        dbcon = database.connect(metacacheFile)
        dbcur = dbcon.cursor()
        dbcur.execute("CREATE TABLE IF NOT EXISTS meta (""imdb TEXT, ""tmdb TEXT, ""tvdb TEXT, ""lang TEXT, ""item TEXT, ""time TEXT, ""UNIQUE(imdb, tmdb, tvdb, lang)"");")
        t = int(time.time())
        r = False
        for m in meta:
            try:
                i = repr(m['item'])
                try: dbcur.execute("DELETE * FROM meta WHERE (imdb = '%s' and lang = '%s' and not imdb = '0') or (tmdb = '%s' and lang = '%s' and not tmdb = '0') or (tvdb = '%s' and lang = '%s' and not tvdb = '0')" % (m['imdb'], m['lang'], m['tmdb'], m['lang'], m['tvdb'], m['lang']))
                except: pass
                try: dbcur.execute("INSERT INTO meta Values (?, ?, ?, ?, ?, ?)", (m['imdb'], m['tmdb'], m['tvdb'], m['lang'], i, t))
                except: r = True ; break
            except:
                pass
        dbcon.commit()
        dbcon.close()

        if r == False: return

        control.deleteFile(metacacheFile)
        dbcon = database.connect(metacacheFile)
        dbcur = dbcon.cursor()
        dbcur.execute("CREATE TABLE IF NOT EXISTS meta (""imdb TEXT, ""tmdb TEXT, ""tvdb TEXT, ""lang TEXT, ""item TEXT, ""time TEXT, ""UNIQUE(imdb, tmdb, tvdb, lang)"");")
        t = int(time.time())
        r = False
        for m in meta:
            try:
                i = repr(m['item'])
                try: dbcur.execute("DELETE * FROM meta WHERE (imdb = '%s' and lang = '%s' and not imdb = '0') or (tmdb = '%s' and lang = '%s' and not tmdb = '0') or (tvdb = '%s' and lang = '%s' and not tvdb = '0')" % (m['imdb'], m['lang'], m['tmdb'], m['lang'], m['tvdb'], m['lang']))
                except: pass
                dbcur.execute("INSERT INTO meta Values (?, ?, ?, ?, ?, ?)", (m['imdb'], m['tmdb'], m['tvdb'], m['lang'], i, t))
            except:
                pass
        dbcon.commit()
        dbcon.close()
    except:
        return
Пример #29
0
    def create_folder(folder):
        try:
            folder = xbmc.makeLegalFilename(folder)
            control.makeFile(folder)

            try:
                if not 'ftp://' in folder: raise Exception()
                from ftplib import FTP
                ftparg = re.compile('ftp://(.+?):(.+?)@(.+?):?(\d+)?/(.+/?)').findall(folder)
                ftp = FTP(ftparg[0][2], ftparg[0][0], ftparg[0][1])
                try:
                    ftp.cwd(ftparg[0][4])
                except:
                    ftp.mkd(ftparg[0][4])
                ftp.quit()
            except:
                pass
        except:
            pass
Пример #30
0
def addView(content):
    try:
        skin = control.skin
        record = (skin, content, str(control.getCurrentViewId()))
        control.makeFile(control.dataPath)
        dbcon = database.connect(control.viewsFile)
        dbcur = dbcon.cursor()
        dbcur.execute("CREATE TABLE IF NOT EXISTS views (""skin TEXT, ""view_type TEXT, ""view_id TEXT, ""UNIQUE(skin, view_type)"");")
        dbcur.execute("DELETE FROM views WHERE skin = '%s' AND view_type = '%s'" % (record[0], record[1]))
        dbcur.execute("INSERT INTO views Values (?, ?, ?)", record)
        dbcon.commit()

        viewName = control.infoLabel('Container.Viewmode')
        skinName = control.addon(skin).getAddonInfo('name')
        skinIcon = control.addon(skin).getAddonInfo('icon')

        control.infoDialog(viewName, heading=skinName, sound=True, icon=skinIcon)
    except:
        return
Пример #31
0
def get(function, timeout, *args):
    try:
        response = None

        f = repr(function)
        f = re.sub('.+\smethod\s|.+function\s|\sat\s.+|\sof\s.+', '', f)

        a = hashlib.md5()
        for i in args:
            a.update(str(i))
        a = str(a.hexdigest())
    except:
        pass

    try:
        control.makeFile(control.dataPath)
        dbcon = database.connect(control.cachemetaFile)
        dbcur = dbcon.cursor()
        dbcur.execute(
            "SELECT * FROM rel_list WHERE func = '%s' AND args = '%s'" %
            (f, a))
        match = dbcur.fetchone()

        response = eval(match[2].encode('utf-8'))

        t1 = int(match[3])
        t2 = int(time.time())
        update = (abs(t2 - t1) / 3600) >= int(timeout)
        if update == False:
            return response
    except:
        pass

    try:
        r = function(*args)
        if (r == None or r == []) and not response == None:
            return response
        elif (r == None or r == []):
            return r
    except:
        return

    try:
        insert = True
        if r['cover_url'] == '' or r['backdrop_url'] == '': insert = False
        r = repr(r)
        t = int(time.time())
        dbcur.execute("CREATE TABLE IF NOT EXISTS rel_list ("
                      "func TEXT, "
                      "args TEXT, "
                      "response TEXT, "
                      "added TEXT, "
                      "UNIQUE(func, args)"
                      ");")
        dbcur.execute(
            "DELETE FROM rel_list WHERE func = '%s' AND args = '%s'" % (f, a))
        if insert == True:
            dbcur.execute("INSERT INTO rel_list Values (?, ?, ?, ?)",
                          (f, a, r, t))
        dbcon.commit()
    except:
        pass

    try:
        return eval(r.encode('utf-8'))
    except:
        pass
Пример #32
0
    def service(self):
        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('service_update') == 'true':
                    raise Exception()
                info = control.setting('service_notification') or 'true'
                self.update(None, info=info)
            except:
                pass

            control.sleep(10000)
Пример #33
0
	def range(self, url, list_name):
		control.idle()

		if not control.yesnoDialog(control.lang(32555).encode('utf-8'), '', ''):
			return

		if 'traktcollection' in url:
			message = 32661
		if 'traktwatchlist' in url:
			message = 32662
		if '/lists/' in url:
			message = 32674
		if '/likes/' in url:
			message = 32675

		if not control.condVisibility('Window.IsVisible(infodialog)') and not control.condVisibility('Player.HasVideo'):
			control.notification(title = 'default', message = message, icon = 'default', time = 1000, sound = notificationSound)

		from resources.lib.menus import tvshows
		items = tvshows.TVshows().get(url, idx=False)
		if items is None or items == []:
			if general_notification:
				control.notification(title = message, message = 33049, icon = 'INFO', time = 3000, sound=notificationSound)
			return

		contains = lib_tools.ckKodiSources()

		total_added = 0
		for i in items:
			try:
				if xbmc.abortRequested is True:#..I think this is deprecated and was for Gotham and earlier
				# xbmc.Monitor().abortRequested() #check this
					return sys.exit()
				files_added = self.add(i['title'], i['year'], i['imdb'], i['tvdb'], range=True)
				if general_notification and files_added > 0:
					control.notification(title = i['title'], message = 32554, icon = 'default', time = 1000, sound = notificationSound)
					total_added += 1
			except:
				log_utils.error()
				pass

		if '/users/' in url:
			try:
				type = 'tvshows'
				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.execute("INSERT OR REPLACE INTO lists Values (?, ?, ?)", (type, list_name, url))
				dbcur.connection.commit()
				dbcon.close()
			except:
				log_utils.error()
				try: dbcon.close()
				except: pass
				pass

		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 general_notification:
				control.notification(title = 'default', message = 'strm files written but library cannot be updated', icon = 'default', time = 2000, sound = notificationSound)
Пример #34
0
def _get_connection_debrid():
    control.makeFile(control.dataPath)
    conn = db.connect(control.dbFile)
    conn.row_factory = _dict_factory
    return conn
Пример #35
0
def get(function_, duration, *args, **table):

    try:

        response = None

        f = repr(function_)
        f = re.sub(r'.+\smethod\s|.+function\s|\sat\s.+|\sof\s.+', '', f)

        a = hashlib.md5()
        for i in args:
            a.update(str(i))
        a = str(a.hexdigest())

    except Exception:

        pass

    try:
        table = table['table']
    except Exception:
        table = 'rel_list'

    try:

        control.makeFile(control.dataPath)
        dbcon = db.connect(control.cacheFile)
        dbcur = dbcon.cursor()
        dbcur.execute(
            "SELECT * FROM {tn} WHERE func = '{f}' AND args = '{a}'".format(
                tn=table, f=f, a=a))
        match = dbcur.fetchone()

        try:
            response = evaluate(match[2].encode('utf-8'))
        except AttributeError:
            response = evaluate(match[2])

        t1 = int(match[3])
        t2 = int(time.time())
        update = (abs(t2 - t1) / 3600) >= int(duration)
        if not update:
            return response

    except Exception:

        pass

    try:

        r = function_(*args)
        if (r is None or r == []) and response is not None:
            return response
        elif r is None or r == []:
            return r

    except Exception:
        return

    try:

        r = repr(r)
        t = int(time.time())
        dbcur.execute("CREATE TABLE IF NOT EXISTS {} ("
                      "func TEXT, "
                      "args TEXT, "
                      "response TEXT, "
                      "added TEXT, "
                      "UNIQUE(func, args)"
                      ");".format(table))
        dbcur.execute(
            "DELETE FROM {0} WHERE func = '{1}' AND args = '{2}'".format(
                table, f, a))
        dbcur.execute("INSERT INTO {} Values (?, ?, ?, ?)".format(table),
                      (f, a, r, t))
        dbcon.commit()

    except Exception:
        pass

    try:
        return evaluate(r.encode('utf-8'))
    except Exception:
        return evaluate(r)
Пример #36
0
def insert(meta):
    try:
        if not meta: return
        control.makeFile(control.dataPath)
        metacacheFile = os.path.join(control.dataPath, 'meta.5.db')

        dbcon = database.connect(metacacheFile)
        dbcur = dbcon.cursor()
        dbcur.execute("CREATE TABLE IF NOT EXISTS meta ("
                      "imdb TEXT, "
                      "tmdb TEXT, "
                      "tvdb TEXT, "
                      "lang TEXT, "
                      "item TEXT, "
                      "time TEXT, "
                      "UNIQUE(imdb, tmdb, tvdb, lang)"
                      ");")
        t = int(time.time())
        r = False
        for m in meta:
            try:
                i = repr(m['item'])
                try:
                    dbcur.execute(
                        "DELETE * FROM meta WHERE (imdb = '%s' and lang = '%s' and not imdb = '0') or (tmdb = '%s' and lang = '%s' and not tmdb = '0') or (tvdb = '%s' and lang = '%s' and not tvdb = '0')"
                        % (m['imdb'], m['lang'], m['tmdb'], m['lang'],
                           m['tvdb'], m['lang']))
                except:
                    pass
                try:
                    dbcur.execute(
                        "INSERT INTO meta Values (?, ?, ?, ?, ?, ?)",
                        (m['imdb'], m['tmdb'], m['tvdb'], m['lang'], i, t))
                except:
                    r = True
                    break
            except:
                pass
        dbcon.commit()
        dbcon.close()

        if r == False: return

        control.deleteFile(metacacheFile)
        dbcon = database.connect(metacacheFile)
        dbcur = dbcon.cursor()
        dbcur.execute("CREATE TABLE IF NOT EXISTS meta ("
                      "imdb TEXT, "
                      "tmdb TEXT, "
                      "tvdb TEXT, "
                      "lang TEXT, "
                      "item TEXT, "
                      "time TEXT, "
                      "UNIQUE(imdb, tmdb, tvdb, lang)"
                      ");")
        t = int(time.time())
        r = False
        for m in meta:
            try:
                i = repr(m['item'])
                try:
                    dbcur.execute(
                        "DELETE * FROM meta WHERE (imdb = '%s' and lang = '%s' and not imdb = '0') or (tmdb = '%s' and lang = '%s' and not tmdb = '0') or (tvdb = '%s' and lang = '%s' and not tvdb = '0')"
                        % (m['imdb'], m['lang'], m['tmdb'], m['lang'],
                           m['tvdb'], m['lang']))
                except:
                    pass
                dbcur.execute(
                    "INSERT INTO meta Values (?, ?, ?, ?, ?, ?)",
                    (m['imdb'], m['tmdb'], m['tvdb'], m['lang'], i, t))
            except:
                pass
        dbcon.commit()
        dbcon.close()
    except:
        return
Пример #37
0
def get_connection_bookmarks():
    control.makeFile(control.dataPath)
    conn = db.connect(control.bookmarksFile)
    conn.row_factory = _dict_factory
    return conn
Пример #38
0
    def getSources(self,
                   title,
                   year,
                   imdb,
                   tvdb,
                   season,
                   episode,
                   tvshowtitle,
                   premiered,
                   presetDict=[],
                   timeout=30,
                   progress=True):
        sourceDict = []
        for package, name, is_pkg in pkgutil.walk_packages(__path__):
            sourceDict.append((name, is_pkg))
        sourceDict = [i[0] for i in sourceDict if i[1] == False]

        if not presetDict == []:
            sourceDict = [i for i in presetDict if i in sourceDict]

        content = 'movie' if tvshowtitle == None else 'episode'

        if content == 'movie':
            sourceDict = [
                i for i in sourceDict if i.endswith(('_mv', '_mv_tv'))
            ]
        else:
            sourceDict = [
                i for i in sourceDict if i.endswith(('_tv', '_mv_tv'))
            ]

        try:
            sourceDict = [(i,
                           control.setting('provider.' +
                                           re.sub('_mv_tv$|_mv$|_tv$', '', i)))
                          for i in sourceDict]
        except:
            sourceDict = [(i, 'true') for i in sourceDict]

        sourceDict = [i[0] for i in sourceDict if not i[1] == 'false']

        threads = []

        control.makeFile(control.dataPath)
        self.sourceFile = control.providercacheFile

        if content == 'movie':
            title = cleantitle.normalize(title)
            for source in sourceDict:
                threads.append(
                    workers.Thread(
                        self.getMovieSource, title, year, imdb,
                        re.sub('_mv_tv$|_mv$|_tv$', '', source),
                        __import__(source, globals(), locals(), [],
                                   -1).source()))
        else:
            tvshowtitle = cleantitle.normalize(tvshowtitle)
            for source in sourceDict:
                threads.append(
                    workers.Thread(
                        self.getEpisodeSource, title, year, imdb, tvdb, season,
                        episode, tvshowtitle, premiered,
                        re.sub('_mv_tv$|_mv$|_tv$', '', source),
                        __import__(source, globals(), locals(), [],
                                   -1).source()))

        try:
            timeout = int(control.setting('scrapers.timeout.1'))
        except:
            pass

        [i.start() for i in threads]

        control.idle()

        sourceLabel = [re.sub('_mv_tv$|_mv$|_tv$', '', i) for i in sourceDict]
        sourceLabel = [re.sub('v\d+$', '', i).upper() for i in sourceLabel]

        if progress == True:
            self.progressDialog = control.progressDialog
            self.progressDialog.create(control.addonInfo('name'), '')
            self.progressDialog.update(0)

        string1 = control.lang(30512).encode('utf-8')
        string2 = control.lang(30513).encode('utf-8')
        string3 = control.lang(30514).encode('utf-8')

        for i in range(0, timeout * 2):
            try:
                if xbmc.abortRequested == True: return sys.exit()

                try:
                    info = [
                        sourceLabel[int(re.sub('[^0-9]', '', str(x.getName())))
                                    - 1] for x in threads
                        if x.is_alive() == True
                    ]
                except:
                    info = []

                if len(info) > 5: info = len(info)

                if progress == True:
                    self.progressDialog.update(
                        int((100 / float(len(threads))) *
                            len([x
                                 for x in threads if x.is_alive() == False])),
                        str('%s: %s %s' % (string1, int(i * 0.5), string2)),
                        str('%s: %s' %
                            (string3, str(info).translate(None, "[]'"))))
                    if self.progressDialog.iscanceled(): break

                is_alive = [x.is_alive() for x in threads]
                if all(x == False for x in is_alive): break
                time.sleep(0.5)
            except:
                pass

        try:
            self.progressDialog.close()
        except:
            pass

        self.sourcesFilter()

        return self.sources
Пример #39
0
    def update(self, query=None, info='true'):
        if not query == None: control.idle()

        try:

            items = []
            season, episode = [], []
            show = [os.path.join(self.library_folder, i) for i in control.listDir(self.library_folder)[0]]
            for s in show:
                try: season += [os.path.join(s, i) for i in control.listDir(s)[0]]
                except: pass
            for s in season:
                try: episode.append([os.path.join(s, i) for i in control.listDir(s)[1] if i.endswith('.strm')][-1])
                except: pass

            for file in episode:
                try:
                    file = control.openFile(file)
                    read = file.read()
                    read = read.encode('utf-8')
                    file.close()

                    if not read.startswith(sys.argv[0]): raise Exception()

                    params = dict(urlparse.parse_qsl(read.replace('?','')))

                    try: tvshowtitle = params['tvshowtitle']
                    except: tvshowtitle = None
                    try: tvshowtitle = params['show']
                    except: pass
                    if tvshowtitle == None or tvshowtitle == '': raise Exception()

                    year, imdb, tvdb = params['year'], params['imdb'], params['tvdb']

                    imdb = 'tt' + re.sub('[^0-9]', '', str(imdb))

                    try: tmdb = params['tmdb']
                    except: tmdb = '0'

                    items.append({'tvshowtitle': tvshowtitle, 'year': year, 'imdb': imdb, 'tmdb': tmdb, 'tvdb': tvdb})
                except:
                    pass

            items = [i for x, i in enumerate(items) if i not in items[x + 1:]]
            if len(items) == 0: raise Exception()
        except:
            return

        try:
            lib = control.jsonrpc('{"jsonrpc": "2.0", "method": "VideoLibrary.GetTVShows", "params": {"properties" : ["imdbnumber", "title", "year"]}, "id": 1}')
            lib = unicode(lib, 'utf-8', errors='ignore')
            lib = json.loads(lib)['result']['tvshows']
        except:
            return

        if info == 'true' and not control.condVisibility('Window.IsVisible(infodialog)') and not control.condVisibility('Player.HasVideo'):
            control.infoDialog(control.lang(32553).encode('utf-8'), time=10000000)
            self.infoDialog = True

        try:
            control.makeFile(control.dataPath)
            dbcon = database.connect(control.libcacheFile)
            dbcur = dbcon.cursor()
            dbcur.execute("CREATE TABLE IF NOT EXISTS tvshows (""id TEXT, ""items TEXT, ""UNIQUE(id)"");")
        except:
            return

        try:
            from resources.lib.indexers import episodes
        except:
            return

        files_added = 0

        # __init__ doesn't get called from services so self.date never gets updated and new episodes are not added to the library
        self.datetime = (datetime.datetime.utcnow() - datetime.timedelta(hours = 5))
        self.date = (self.datetime - datetime.timedelta(hours = 24)).strftime('%Y%m%d')
        
        for item in items:
            it = None

            if xbmc.abortRequested == True: return sys.exit()

            try:
                dbcur.execute("SELECT * FROM tvshows WHERE id = '%s'" % item['tvdb'])
                fetch = dbcur.fetchone()
                it = eval(fetch[1].encode('utf-8'))
            except:
                pass

            try:
                if not it == None: raise Exception()

                it = episodes.episodes().get(item['tvshowtitle'], item['year'], item['imdb'], item['tvdb'], idx=False)

                status = it[0]['status'].lower()

                it = [{'title': i['title'], 'year': i['year'], 'imdb': i['imdb'], 'tvdb': i['tvdb'], 'season': i['season'], 'episode': i['episode'], 'tvshowtitle': i['tvshowtitle'], 'premiered': i['premiered']} for i in it]

                if status == 'continuing': raise Exception()
                dbcur.execute("INSERT INTO tvshows Values (?, ?)", (item['tvdb'], repr(it)))
                dbcon.commit()
            except:
                pass

            try:
                id = [item['imdb'], item['tvdb']]
                if not item['tmdb'] == '0': id += [item['tmdb']]

                ep = [x['title'].encode('utf-8') for x in lib if str(x['imdbnumber']) in id or (x['title'].encode('utf-8') == item['tvshowtitle'] and str(x['year']) == item['year'])][0]
                ep = control.jsonrpc('{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": {"filter":{"and": [{"field": "tvshow", "operator": "is", "value": "%s"}]}, "properties": ["season", "episode"]}, "id": 1}' % ep)
                ep = unicode(ep, 'utf-8', errors='ignore')
                ep = json.loads(ep).get('result', {}).get('episodes', {})
                ep = [{'season': int(i['season']), 'episode': int(i['episode'])} for i in ep]
                ep = sorted(ep, key=lambda x: (x['season'], x['episode']))[-1]

                num = [x for x,y in enumerate(it) if str(y['season']) == str(ep['season']) and str(y['episode']) == str(ep['episode'])][-1]
                it = [y for x,y in enumerate(it) if x > num]
                if len(it) == 0: continue
            except:
                continue

            for i in it:
                try:
                    if xbmc.abortRequested == True: return sys.exit()

                    premiered = i.get('premiered', '0')
                    if (premiered != '0' and int(re.sub('[^0-9]', '', str(premiered))) > int(self.date)) or (premiered == '0' and not self.include_unknown):
                        continue

                    libtvshows().strmFile(i)
                    files_added += 1
                except:
                    pass

        if self.infoDialog == True:
            control.infoDialog(control.lang(32554).encode('utf-8'), time=1)

        if self.library_setting == 'true' and not control.condVisibility('Library.IsScanningVideo') and files_added > 0:
            control.execute('UpdateLibrary(video)')
Пример #40
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)
def _get_connection():
    control.makeFile(control.dataPath)
    conn = db.connect(control.providercacheFile)
    conn.row_factory = _dict_factory
    return conn
Пример #42
0
def benelli_download_get(function, timeout, *args, **table):
    try:
        response = None

        f = repr(function)
        f = re.sub('.+\smethod\s|.+function\s|\sat\s.+|\sof\s.+', '', f)

        a = hashlib.md5()
        for i in args:
            a.update(str(i))
        a = str(a.hexdigest())
    except:
        pass

    try:
        table = table['table']
    except:
        table = 'rel_list'

    try:
        control.makeFile(control.dataPath)
        dbcon = db.connect(control.cacheFile)
        dbcur = dbcon.cursor()
        dbcur.execute("SELECT * FROM %s WHERE func = '%s' AND args = '%s'" %
                      (table, f, a))
        match = dbcur.fetchone()

        response = eval(match[2].encode('utf-8'))

        t1 = int(match[3])
        t2 = int(time.time())
        update = (abs(t2 - t1) / 3600) >= int(timeout)
        if update == False:
            return response
    except:
        pass

    try:
        r = function(*args)
        if (r == None or r == []) and not response == None:
            return response
        elif (r == None or r == []):
            return r
    except:
        return

    try:
        r = repr(r)
        t = int(time.time())
        dbcur.execute("CREATE TABLE IF NOT EXISTS %s ("
                      "func TEXT, "
                      "args TEXT, "
                      "response TEXT, "
                      "added TEXT, "
                      "UNIQUE(func, args)"
                      ");" % table)
        dbcur.execute("DELETE FROM %s WHERE func = '%s' AND args = '%s'" %
                      (table, f, a))
        dbcur.execute("INSERT INTO %s Values (?, ?, ?, ?)" % table,
                      (f, a, r, t))
        dbcon.commit()
    except:
        pass

    try:
        return eval(r.encode('utf-8'))
    except:
        pass
Пример #43
0
def download(name, image, url):
    if url == None: return

    from resources.lib.modules import control
    from resources.lib.modules import trakt

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

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

    sorter = re.compile('(.+?)\sS(\d*)E\d*$').findall(name)

    if control.setting('Download.auf.Deutsch'
                       ) != 'false':  #Option für Benennung auf Deutsch EIN
        if len(sorter) == 0:  #Filme
            title = name[:-7]
            transyear = name.replace("(", "").replace(")", "")
            year = transyear[-4:]
            imdb = trakt.SearchMovie(title, year, full=False)[0]
            imdb = imdb.get('movie', '0')
            imdb = imdb.get('ids', {}).get('imdb', '0')
            imdb = 'tt' + re.sub('[^0-9]', '', str(imdb))
            lang = 'de'
            germantitle = trakt.getMovieTranslation(imdb, lang)
            transname = germantitle.translate(
                None, '\/:*?"<>|').strip('.') + ' ' + '(' + str(year) + ')'
            name = transname
            levels = ['../../../..', '../../..', '../..', '..']
            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)
            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)
        else:  #Serien
            title = name[:-7]
            transyear = name.replace("(", "").replace(")", "")
            year = transyear[-4:]  #dirty year.... but working)
            episode = name.rsplit(' ', 1)
            imdb = trakt.SearchTVShow(title, year, full=False)[0]
            imdb = imdb.get('show', '0')
            imdb = imdb.get('ids', {}).get('imdb', '0')
            imdb = 'tt' + re.sub('[^0-9]', '', str(imdb))
            lang = 'de'
            germantitle = trakt.getTVShowTranslation(imdb, lang)
            transname = germantitle.translate(None, '\/:*?"<>|').strip('.')
            content = re.compile('(.+?)\sS(\d*)E\d*$').findall(name)
            transtvshowtitle = content[0][0].translate(None,
                                                       '\/:*?"<>|').strip('.')
            name = transname
            levels = ['../../../..', '../../..', '../..', '..']
            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)
            dest = os.path.join(dest, transname)
            control.makeFile(dest)
            ext = os.path.splitext(urlparse.urlparse(url).path)[1][1:]
            if not ext in ['mp4', 'mkv', 'flv', 'avi', 'mpg']: ext = 'mp4'
            DownloadSeasonName = control.setting('Download.Season.Name')
            if DownloadSeasonName == '0':
                dest = os.path.join(dest, 'Season %01d' % int(content[0][1]))
            else:
                pass
            if DownloadSeasonName == '1':
                dest = os.path.join(dest, 'S%01d' % int(content[0][1]))
            else:
                pass
            if DownloadSeasonName == '2':
                dest = os.path.join(dest, 'Staffel %01d' % int(content[0][1]))
            else:
                pass
            control.makeFile(dest)
            dest = os.path.join(dest, transname + ' ' + episode[1] + '.' + ext)
    else:  #Option für Benennung auf Deutsch AUS
        if len(sorter) == 0:  #Filme
            transname = name.translate(None, '\/:*?"<>|').strip('.')
            levels = ['../../../..', '../../..', '../..', '..']
            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)
            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)
        else:  #Serien
            transname = name.translate(None, '\/:*?"<>|').strip('.')
            content = re.compile('(.+?)\sS(\d*)E\d*$').findall(name)
            transtvshowtitle = content[0][0].translate(None,
                                                       '\/:*?"<>|').strip('.')
            name = transname
            levels = ['../../../..', '../../..', '../..', '..']
            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)
            dest = os.path.join(dest, transtvshowtitle)
            control.makeFile(dest)
            DownloadSeasonName = control.setting('Download.Season.Name')
            if DownloadSeasonName == '0':
                dest = os.path.join(dest, 'Season %01d' % int(content[0][1]))
            else:
                pass
            if DownloadSeasonName == '1':
                dest = os.path.join(dest, 'S%01d' % int(content[0][1]))
            else:
                pass
            if DownloadSeasonName == '2':
                dest = os.path.join(dest, 'Staffel %01d' % int(content[0][1]))
            else:
                pass
            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)
Пример #44
0
def download(name, image, url):
    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)

    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)
Пример #45
0
    def resolve(self, url):
        try:
            m3u8 = [
                '#EXTM3U',
                '#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="audio",DEFAULT=YES,AUTOSELECT=YES,NAME="Stream 1",URI="{audio_stream}"',
                '',
                '#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=0,NAME="{stream_name}",AUDIO="audio"',
                '{video_stream}'
            ]

            query = urlparse.parse_qs(url)
            query = dict([(key, query[key][0]) if query[key] else (key, '')
                          for key in query])

            auth = 'http://streamtorrent.tv/api/torrent/%s/%s.m3u8?json=true' % (
                query['vid_id'], query['stream_id'])

            r = client.request(auth)
            r = json.loads(r)
            try:
                url = r['url']
            except:
                url = None

            if not url == None:

                def dialog(url):
                    try:
                        self.disableScraper = control.yesnoDialog(
                            'To watch this video visit from any device',
                            '[COLOR skyblue]%s[/COLOR]' % url, '', 'Torba',
                            'Cancel', 'Settings')
                    except:
                        pass

                workers.Thread(dialog, url).start()
                control.sleep(3000)

                for i in range(100):
                    try:
                        if not control.condVisibility(
                                'Window.IsActive(yesnoDialog)'):
                            break

                        r = client.request(auth)
                        r = json.loads(r)
                        try:
                            url = r['url']
                        except:
                            url = None

                        if url == None: break

                        workers.Thread(dialog, url).start()
                        control.sleep(3000)
                    except:
                        pass

                if self.disableScraper:
                    control.openSettings(query='2.0')
                    return ''

                control.execute('Dialog.Close(yesnoDialog)')

            if not url == None: return

            stream_name = '%sp' % (query['height'])
            video_stream = r[stream_name]

            if not 'audio' in r: return video_stream

            audio_stream = r['audio']

            content = ('\n'.join(m3u8)).format(
                **{
                    'audio_stream': audio_stream,
                    'stream_name': stream_name,
                    'video_stream': video_stream
                })

            path = os.path.join(control.dataPath, 'torbase.m3u8')

            control.makeFile(control.dataPath)
            control.deleteFile(path)

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

            return path
        except:
            return
Пример #46
0
    def run(self):
        def download():
            return []

        result = cache.bennu_download_get(download, 600000000, table='rel_dl')

        for item in result:
            self.name = item['name']
            self.image = item['image']
            self.url = item['url']

            sysname = self.name.translate(None, '\/:*?"<>|').strip('.')

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

            ext = os.path.splitext(urlparse.urlparse(url).path)[1][1:].lower()

            hdlr = re.compile('.+? ([(]\d{4}[)]|S\d*E\d*)$').findall(self.name)
            if len(hdlr) == 0: self.content = 'Uncategorised'

            if ext in ['m4a', 'mp3', 'aac']: self.content = 'Music'

            hdlr = re.compile('.+? (S\d*E\d*)$').findall(self.name)
            if len(hdlr) > 0: self.content = 'TVShows'

            hdlr = re.compile('.+? [(](\d{4})[)]$').findall(self.name)
            if len(hdlr) > 0: self.content = 'Movies'

            if self.content == 'Movies':
                dest = os.path.join(downloadPath, self.content)
                control.makeFile(dest)
                dest = os.path.join(dest, sysname)
                control.makeFile(dest)

            elif self.content == 'TVShows':
                d = re.compile('(.+?) S(\d*)E(\d*)$').findall(sysname)[0]
                dest = os.path.join(downloadPath, self.content)
                control.makeFile(dest)
                dest = os.path.join(dest, d[0])
                control.makeFile(dest)
                dest = os.path.join(dest, 'Season %01d' % int(d[1]))
                control.makeFile(dest)

            else:
                dest = os.path.join(downloadPath, self.content)
                control.makeFile(dest)

            if not ext in [
                    'mp4', 'm4a', 'mp3', 'aac', 'mkv', 'flv', 'avi', 'mpg'
            ]:
                ext = 'mp4'

            dest = os.path.join(dest, sysname + '.' + ext)

            control.infoDialog(self.name + ' Is Downloading',
                               'Downloads Started',
                               self.image,
                               time=7000)

            try:
                req = urllib2.Request(url, headers=headers)
                resp = urllib2.urlopen(req, timeout=30)
            except Exception, e:
                removeDownload(self.url)
                print '%s ERROR - File Failed To Open' % (dest)
                continue

            try:
                self.size = int(resp.headers['Content-Length'])
            except:
                self.size = 0

            if self.size < 1:
                removeDownload(self.url)
                print '%s Unknown filesize - Unable to download' % (dest)
                continue

            try:
                resumable = 'bytes' in resp.headers['Accept-Ranges'].lower()
            except:
                resumable = False

            size = 1024 * 1024
            if self.size < size: size = self.size

            gb = '%.2f GB' % (float(self.size) / 1073741824)

            start = time.clock()

            total = 0
            notify = 0
            errors = 0
            count = 0
            resume = 0
            sleep = 0

            self.clear()

            control.window.setProperty(property + '.status', 'downloading')
            control.window.setProperty(property + '.name', str(self.name))
            control.window.setProperty(property + '.image', str(self.image))
            control.window.setProperty(property + '.size', str(gb))

            f = control.openFile(dest, 'wb')

            chunk = None
            chunks = []

            while True:
                downloaded = total
                for c in chunks:
                    downloaded += len(c)

                percent = min(100 * downloaded / self.size, 100)

                self.speed = str(
                    int((downloaded / 1024) /
                        (time.clock() - start))) + ' KB/s'
                self.percent = str(percent) + '%'

                control.window.setProperty(property + '.percent',
                                           str(self.percent))
                control.window.setProperty(property + '.speed',
                                           str(self.speed))

                if percent >= notify:
                    control.infoDialog('Downloaded %s' % self.percent,
                                       self.name,
                                       self.image,
                                       time=5000)
                    notify += 10

                chunk = None
                error = False

                try:
                    chunk = resp.read(size)
                    if not chunk:
                        if self.percent < 99:
                            error = True
                        else:
                            while len(chunks) > 0:
                                c = chunks.pop(0)
                                f.write(c)
                                del c

                            f.close()
                            print '%s download complete' % (dest)
                            break

                except Exception, e:
                    print str(e)
                    error = True
                    sleep = 10
                    errno = 0

                    if hasattr(e, 'errno'):
                        errno = e.errno

                    if errno == 10035:  # 'A non-blocking socket operation could not be completed immediately'
                        pass

                    if errno == 10054:  #'An existing connection was forcibly closed by the remote host'
                        errors = 10  #force resume
                        sleep = 30

                    if errno == 11001:  # 'getaddrinfo failed'
                        errors = 10  #force resume
                        sleep = 30

                if chunk:
                    errors = 0
                    chunks.append(chunk)
                    if len(chunks) > 5:
                        c = chunks.pop(0)
                        f.write(c)
                        total += len(c)
                        del c

                if error:
                    errors += 1
                    count += 1
                    print '%d Error(s) whilst downloading %s' % (count, dest)
                    control.sleep(sleep * 1000)

                if (resumable and errors > 0) or errors >= 10:
                    if (not resumable and resume >= 50) or resume >= 500:
                        #Give up!
                        print '%s download canceled - too many error whilst downloading' % (
                            dest)
                        break

                    resume += 1
                    errors = 0
                    if resumable:
                        chunks = []
                        #create new response
                        print 'Download resumed (%d) %s' % (resume, dest)
                        h = headers
                        h['Range'] = 'bytes=%d-' % int(total)
                        try:
                            resp = urllib2.urlopen(urllib2.Request(url,
                                                                   headers=h),
                                                   timeout=10)
                        except:
                            resp = None
                    else:
                        #use existing response
                        pass

                if control.window.getProperty(property + '.status') == 'stop':
                    control.infoDialog('Process Complete',
                                       'Downloads',
                                       time=5000)
                    return self.clear()
Пример #47
0
    def reset(self, current_time, media_length, name, year='0'):
        xbmc.log('line 665 Bookmarks reset call', 2)
        xbmc.log('line 666 current_time = %s' % current_time, 2)
        xbmc.log('line 667 media_length = %s' % media_length, 2)
        try:
            if not control.setting(
                    'bookmarks'
            ) == 'true' or media_length == 0 or current_time == 0:
                return

            try:
                timeInSeconds = str(current_time)

                ok = (int(current_time) > 180
                      and (current_time / media_length) <= .92)

                idFile = hashlib.md5()

                for i in name:
                    idFile.update(str(i))

                for i in year:
                    idFile.update(str(i))

                idFile = str(idFile.hexdigest())

                control.makeFile(control.dataPath)
                dbcon = database.connect(control.bookmarksFile)

                dbcur = dbcon.cursor()

                dbcur.execute("CREATE TABLE IF NOT EXISTS bookmark ("
                              "idFile TEXT, "
                              "timeInSeconds TEXT, "
                              "UNIQUE(idFile)"
                              ");")
                dbcur.execute("DELETE FROM bookmark WHERE idFile = '%s'" %
                              idFile)

                if ok:
                    dbcur.execute("INSERT INTO bookmark Values (?, ?)",
                                  (idFile, timeInSeconds))

                    minutes, seconds = divmod(float(timeInSeconds), 60)
                    hours, minutes = divmod(minutes, 60)

                    label = ('%02d:%02d:%02d' %
                             (hours, minutes, seconds)).encode('utf-8')
                    message = control.lang(32660).encode('utf-8')

                    control.notification(title=name,
                                         message=message + '(' + label + ')',
                                         icon='INFO',
                                         sound=False)
                dbcon.commit()
            except:
                import traceback
                traceback.print_exc()
                pass
        except:
            pass
Пример #48
0
def get(function, timeout_hour, *args, **kargs):
    # try:
    response = None

    force_refresh = kargs['force_refresh'] if 'force_refresh' in kargs else False
    kargs.pop('force_refresh', None)

    lock_obj = kargs['lock_obj'] if 'lock_obj' in kargs else None
    kargs.pop('lock_obj', None)

    f = repr(function)
    f = re.sub('.+\smethod\s|.+function\s|\sat\s.+|\sof\s.+', '', f)

    a = hashlib.md5()
    for i in args: a.update(str(i))
    for key in kargs:
        if key != 'table':
            a.update('%s=%s' % (key, str(kargs[key])))
    a = str(a.hexdigest())
    # except:
    #     pass

    try:
        table = kargs['table']
        kargs.pop('table')
    except:
        table = 'rel_list'

    try:
        control.makeFile(control.dataPath)
        dbcon = database.connect(control.cacheFile)
        dbcur = dbcon.cursor()

        if not force_refresh:
            response, found = __get_from_cache(dbcur, table, f, a, timeout_hour)
            if found:
                return response
        else:
            control.log('BYPASSING CACHE')
    except:
        control.log(traceback.format_exc(), control.LOGERROR)
        control.log('NO CACHE FOUND')

    if lock_obj:
        id = time.time()
        control.log('About to lock code (%s)...' % id)

        found = False

        with lock_obj:
            control.log('Executing locked (%s)' % id)

            try:
                result, found = __get_from_cache(dbcur, table, f, a, timeout_hour)
            except:
                control.log(traceback.format_exc(), control.LOGERROR)

            if not found:
                control.log('NO CACHE FOUND')
                result = __execute_origin(dbcur, dbcon, function, table, f, a, response, *args, **kargs)

        control.log('Lock released (%s)' % id)
        return result

    else:
        return __execute_origin(dbcur, dbcon, function, table, f, a, response, *args, **kargs)
Пример #49
0
    def getSources(self,
                   title,
                   year,
                   imdb,
                   tvdb,
                   season,
                   episode,
                   tvshowtitle,
                   premiered,
                   quality='HD',
                   timeout=20):
        u = None

        sourceDict = []
        for package, name, is_pkg in pkgutil.walk_packages(__path__):
            sourceDict.append((name, is_pkg))
        sourceDict = [i[0] for i in sourceDict if i[1] == False]

        content = 'movie' if tvshowtitle == None else 'episode'

        if content == 'movie':
            sourceDict = [
                i for i in sourceDict if i.endswith(('_mv', '_mv_tv'))
            ]
        else:
            sourceDict = [
                i for i in sourceDict if i.endswith(('_tv', '_mv_tv'))
            ]

        if quality == 'SD':
            quality = [
                'movie4k_mv', 'movie25_mv', 'pftv_tv', 'primewire_mv_tv',
                'watchfree_mv_tv', 'watchseries_tv'
            ]
            sourceDict = [i for i in sourceDict if i in quality]

        threads = []

        control.makeFile(control.dataPath)
        self.sourceFile = control.providercacheFile

        if content == 'movie':
            title = cleantitle.normalize(title)
            for source in sourceDict:
                threads.append(
                    workers.Thread(
                        self.getMovieSource, title, year, imdb,
                        re.sub('_mv_tv$|_mv$|_tv$', '', source),
                        __import__(source, globals(), locals(), [],
                                   -1).source()))
        else:
            tvshowtitle = cleantitle.normalize(tvshowtitle)
            for source in sourceDict:
                threads.append(
                    workers.Thread(
                        self.getEpisodeSource, title, year, imdb, tvdb, season,
                        episode, tvshowtitle, premiered,
                        re.sub('_mv_tv$|_mv$|_tv$', '', source),
                        __import__(source, globals(), locals(), [],
                                   -1).source()))

        [i.start() for i in threads]

        progressDialog = control.progressDialog
        progressDialog.create(control.addonInfo('name'),
                              control.lang(30726).encode('utf-8'))
        progressDialog.update(0)

        progressDialog.update(0,
                              control.lang(30726).encode('utf-8'),
                              control.lang(30731).encode('utf-8'))

        for i in range(0, timeout * 2):
            try:
                if progressDialog.iscanceled(): break
                if xbmc.abortRequested == True: return sys.exit()
                is_alive = [x.is_alive() for x in threads]
                if all(x == False for x in is_alive): break
                time.sleep(0.5)
            except:
                pass

        for i in range(0, 20 * 2):
            try:
                if progressDialog.iscanceled(): break
                if xbmc.abortRequested == True: return sys.exit()
                is_alive = [x.is_alive() for x in threads]
                if all(x == False for x in is_alive): break
                if self.sources: break
                time.sleep(0.5)
            except:
                pass

        progressDialog.update(50,
                              control.lang(30726).encode('utf-8'),
                              control.lang(30731).encode('utf-8'))

        items = self.sourcesFilter()

        filter = [
            i for i in items
            if i['source'].lower() in self.hostcapDict and i['debrid'] == ''
        ]
        items = [i for i in items if not i in filter]

        filter = [
            i for i in items
            if i['source'].lower() in self.hostblockDict and i['debrid'] == ''
        ]
        items = [i for i in items if not i in filter]

        items = [
            i for i in items if ('autoplay' in i and i['autoplay'] == True)
            or not 'autoplay' in i
        ]

        for i in range(len(items)):
            try:
                if progressDialog.iscanceled(): break
                if xbmc.abortRequested == True: return sys.exit()
                url = self.sourcesResolve(items[i])
                if u == None: u = url
                if not url == None: break
            except:
                pass

        try:
            progressDialog.close()
        except:
            pass

        return u
Пример #50
0
    def logDownload(self, title, percent, url, mode='add'):

        control.makeFile(control.dataPath)
        DBFile = control.logDownloads
        newData = []
        dupes   = []

        timeNow =  datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
        download_data = {}
        
        try:  # PREPARE AND SET DB SOURCES
            dbcon = database.connect(DBFile)
            dbcur = dbcon.cursor()
        except:pass     
    
        try: # CREATE DB
            dbcur.execute("CREATE TABLE IF NOT EXISTS downloads (""title TEXT, ""percent TEXT, ""status TEXT, ""url TEXT)")
        except:
            pass                
            
        if mode == 'add' or mode == 'update':
            try:
                status = 'running'
                dbcon = database.connect(DBFile)
                dbcur = dbcon.cursor()  
                try:
                    dbcur.execute("SELECT * FROM downloads WHERE title = '%s'" % (title))
                    match = dbcur.fetchone()
                    if len(match) > 0:
                        #print(("FOUND MATCH DATABASE", match[2]))
                        status = match[2]
                        dbcur.execute("DELETE FROM downloads WHERE title = '%s'" % (title))
                except:pass
                dbcur.execute("INSERT INTO downloads Values (?, ?, ?, ?)", (title, str(percent), 'running', url))
                dbcon.commit()
                
            except Exception as e:
                #print(("DATABASE ERROR", str(e)))
            
        elif mode == 'get':
            try:
                dbcon = database.connect(DBFile)
                dbcur = dbcon.cursor()  
                try:
                    dbcur.execute("SELECT * FROM downloads")
                    match = dbcur.fetchall()
                    return match
                except:pass
                
            except Exception as e:
                #print(("DATABASE ERROR", str(e)))
                
        elif mode == 'stop':
            try:
                status = 'stopped'
                dbcon = database.connect(DBFile)
                dbcur = dbcon.cursor()
                dbcur.execute("SELECT * FROM downloads WHERE title = '%s'" % (title))
                match = dbcur.fetchone()
                url = match[3]
                    
                dbcur.execute("DELETE FROM downloads WHERE title = '%s'" % (title))
                dbcur.execute("INSERT INTO downloads Values (?, ?, ?, ?)", (title, str(percent), 'stopped', url))
                dbcon.commit()
                
            except Exception as e:
                #print(("DATABASE ERROR", str(e)))
                    
        elif mode == 'delete':
            try:
                status = 'delete'
                dbcon = database.connect(DBFile)
                dbcur = dbcon.cursor()
                try:
                    dbcur.execute("SELECT * FROM downloads WHERE title = '%s'" % (title))
                    match = dbcur.fetchall()
                    for item in match:
                        loc = item[3]
                        try: os.remove(loc)
                        except:pass
                        
                    dbcur.execute("DELETE FROM downloads WHERE title = '%s'" % (title))
                    dbcon.commit()                  
                except:pass
                
            except Exception as e:
                #print(("DATABASE ERROR", str(e)))
                    
        elif mode == 'status':
            try:
                status = 'new'
                dbcon = database.connect(DBFile)
                dbcur = dbcon.cursor()  
                try:
                    dbcur.execute("SELECT * FROM downloads WHERE title = '%s'" % (title))
                    match = dbcur.fetchone()
                    if len(match) > 0:
                        status = match[2]
                        return status
                except: return 'new'
            except: return 'new'
            
        elif mode == 'completed':
            try:
                status = 'completed'
                dbcon = database.connect(DBFile)
                dbcur = dbcon.cursor()
                dbcur.execute("DELETE FROM downloads WHERE title = '%s'" % (title))
                dbcur.execute("INSERT INTO downloads Values (?, ?, ?, ?)", (title, '100', 'completed', url))
                dbcon.commit()
                
            except Exception as e:
Пример #51
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:
        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:
                    raise Exception()

                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:
            import traceback
            traceback.print_exc()
            pass

    dbcon.close()
    return items
Пример #52
0
def download(name, image, url, meta_name=None):
    # log_utils.log('name = %s' % str(name), log_utils.LOGDEBUG)
    file_format = control.setting('downloads.file.format')
    try:
        if not url:
            control.hide()
            return
        try:
            headers = dict(parse_qsl(url.rsplit('|', 1)[1]))
        except:
            headers = dict('')

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

        transname = name.translate(None, '\/:*?"<>|').strip('.')
        ext_list = ['.mp4', '.mkv', '.flv', '.avi', '.mpg']
        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':
                transname = meta_name.translate(None, '\/:*?"<>|').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.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)
            if meta_name:
                dest = os.path.join(
                    dest,
                    meta_name.translate(None, '\/:*?"<>|').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('[^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.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].translate(
                None, '\/:*?"<>|').strip('.').replace('.', ' ')
            if not meta_name:
                transtvshowtitle = titlecase(
                    re.sub('[^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 ['mp4', 'mkv', 'flv', 'avi', 'mpg']:
            ext = 'mp4'
        dest = os.path.join(dest, transname + '.' + ext)
        doDownload(url, dest, name, image, headers)
    except:
        log_utils.error()
Пример #53
0
	def update(self):
		contains = lib_tools.ckKodiSources()
		try:
			items = []
			season, episode = [], []
			show = [os.path.join(self.library_folder, i) for i in control.listDir(self.library_folder)[0]]

			for s in show:
				try:
					season += [os.path.join(s, i) for i in control.listDir(s)[0]]
				except:
					pass

			for s in season:
				try:
					episode.append([os.path.join(s, i) for i in control.listDir(s)[1] if i.endswith('.strm')][-1])
				except:
					pass

			for file in episode:
				try:
					file = control.openFile(file)
					read = file.read()
					read = read.encode('utf-8')
					file.close()

					if not read.startswith(sys.argv[0]):
						continue

					params = dict(urlparse.parse_qsl(read.replace('?','')))

					try:
						tvshowtitle = params['tvshowtitle']
					except:
						tvshowtitle = None

					try:
						tvshowtitle = params['show']
					except:
						pass

					if tvshowtitle is None or tvshowtitle == '':
						continue

					year, imdb, tvdb = params['year'], params['imdb'], params['tvdb']
					imdb = 'tt' + re.sub('[^0-9]', '', str(imdb))
					tmdb = params.get('tmdb', '0')

					items.append({'tvshowtitle': tvshowtitle, 'year': year, 'imdb': imdb, 'tmdb': tmdb, 'tvdb': tvdb})
				except:
					pass

			items = [i for x, i in enumerate(items) if i not in items[x + 1:]]

			if len(items) == 0:
				return
		except:
			log_utils.error()
			return

		try:
			lib = control.jsonrpc('{"jsonrpc": "2.0", "method": "VideoLibrary.GetTVShows", "params": {"properties": ["imdbnumber", "title", "year"]}, "id": 1 }')
			# lib = control.jsonrpc('{"jsonrpc": "2.0", "method": "VideoLibrary.GetTVShows", "params": {"filter":{"or": [{"field": "year", "operator": "is", "value": "%s"}, {"field": "year", "operator": "is", "value": "%s"}, {"field": "year", "operator": "is", "value": "%s"}]}, "properties": ["imdbnumber", "title", "year"]}, "id": 1}' % (year, str(int(year)+1), str(int(year)-1)))
			lib = unicode(lib, 'utf-8', errors='ignore')
			lib = json.loads(lib)['result']['tvshows']
		except:
			log_utils.error()
			return
 
		if service_notification and not control.condVisibility('Window.IsVisible(infodialog)') and not control.condVisibility('Player.HasVideo'):
			control.notification(title = 'default', message = 32553, icon = 'default', time = 1000, sound = notificationSound)

		try:
			control.makeFile(control.dataPath)
			dbcon = database.connect(control.libcacheFile)
			dbcur = dbcon.cursor()
			dbcur.execute("CREATE TABLE IF NOT EXISTS tvshows (""id TEXT, ""items TEXT, ""UNIQUE(id)"");")
			dbcur.connection.commit()
		except:
			log_utils.error()
			try: dbcon.close()
			except: pass
			return

		try:
			from resources.lib.menus import episodes
		except:
			return

		files_added = 0

		# __init__ doesn't get called from services so self.date never gets updated and new episodes are not added to the library
		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')

		for item in items:
			it = None

			if xbmc.abortRequested is True:
				try: dbcon.close()
				except: pass
				return sys.exit()

			try:
				dbcur.execute("SELECT * FROM tvshows WHERE id = '%s'" % item['tvdb'])
				fetch = dbcur.fetchone()
				if fetch is not None:
					it = eval(fetch[1].encode('utf-8'))
			except:
				log_utils.error()
				pass

			try:
				if it is not None:
					continue

				it = episodes.Episodes().get(item['tvshowtitle'], item['year'], item['imdb'], item['tvdb'], idx = False)

				status = it[0]['status'].lower()

				it = [{'title': i['title'], 'year': i['year'], 'imdb': i['imdb'], 'tvdb': i['tvdb'], 'season': i['season'], 'episode': i['episode'], 'tvshowtitle': i['tvshowtitle'], 'premiered': i['premiered']} for i in it]

				# if status == 'continuing': raise Exception()
				dbcur.execute("INSERT INTO tvshows Values (?, ?)", (item['tvdb'], repr(it)))
				dbcur.connection.commit()
			except:
				log_utils.error()
				pass

			try:
				id = [item['imdb'], item['tvdb']]

				if item['tmdb'] != '0':
					id += [item['tmdb']]

				ep = [x['title'].encode('utf-8') for x in lib if str(x['imdbnumber']) in id or (x['title'].encode('utf-8') == item['tvshowtitle'] and str(x['year']) == item['year'])][0]
				ep = control.jsonrpc('{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": {"filter":{"and": [{"field": "tvshow", "operator": "is", "value": "%s"}]}, "properties": ["season", "episode"]}, "id": 1}' % ep)
				ep = unicode(ep, 'utf-8', errors = 'ignore')
				ep = json.loads(ep).get('result', {}).get('episodes', {})
				ep = [{'season': int(i['season']), 'episode': int(i['episode'])} for i in ep]
				ep = sorted(ep, key = lambda x: (x['season'], x['episode']))[-1]

				num = [x for x,y in enumerate(it) if str(y['season']) == str(ep['season']) and str(y['episode']) == str(ep['episode'])][-1]
				it = [y for x,y in enumerate(it) if x > num]
				if len(it) == 0:
					continue
			except:
				log_utils.error()
				continue

			for i in it:
				try:
					if xbmc.abortRequested is True:
						return sys.exit()

					# Show Season Special(Season0).
					if str(i.get('season')) == '0' and control.setting('tv.specials') == 'false':
						continue

					premiered = i.get('premiered', '0')

					# Show Unaired items.
					if premiered == '0' and self.include_unknown == 'false':
						continue
					elif status == 'ended':
						pass
					elif int(re.sub('[^0-9]', '', str(premiered))) > int(re.sub('[^0-9]', '', str(self.date))):
						unaired = 'true'
						if self.showunaired != 'true':
							continue

					libtvshows().strmFile(i)
					files_added += 1
					if service_notification :
						control.notification(title = item['tvshowtitle'], message = 32678, icon = 'default', time = 1000, sound = notificationSound)
				except:
					log_utils.error()
					pass

		try: dbcon.close()
		except: pass

		if files_added == 0 and service_notification :
			control.notification(title = 'default', message = 'No Updates Found', icon = 'default', time = 1000, sound = notificationSound)

		if self.library_update == 'true' and not control.condVisibility('Library.IsScanningVideo') and files_added > 0:
			if contains:
				if service_notification:
					control.notification(title = 'default', message = 32554, icon = 'default', time = 1000, sound = notificationSound)
				control.sleep(10000)
				control.execute('UpdateLibrary(video)')
			elif service_notification:
				control.notification(title = 'default', message = 'strm files written but library cannot be updated', icon = 'default', time = 2000, sound = notificationSound)
Пример #54
0
def download(title, img, url):
    from resources.lib.modules import control
    control.busy()
    import json

    if url is None:
        return

    try:
        import resolveurl
        url = resolveurl.resolve(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(parse_qsl(url.rsplit('|', 1)[1]))
    except:
        headers = dict('')

    content = re.compile(r'(.+?)\s+[\.|\(|\[]S(\d+)E\d+[\.|\)|\]]', re.I).findall(title)
    transname = title.translate(None, r'\/:*?"<>|').strip('.')
    transname = re.sub(r'\[.+?\]', '', 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(r'\[.+?\]', '', content[0])
        transtvshowtitle = tvtitle.translate(None, r'\/:*?"<>|').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(url).path)[1][1:]
    if ext not in ['mp4', 'mkv', 'flv', 'avi', 'mpg']: ext = 'mp4'
    dest = os.path.join(dest, transname + '.' + ext)
    headers = urllib.quote_plus(json.dumps(headers))

    from resources.lib.modules import downloader
    control.idle()
    downloader.doDownload(url, dest, title, img, headers)
Пример #55
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.connection.commit()
			dbcur.execute("SELECT * FROM service WHERE setting = 'last_run'")
			fetch = dbcur.fetchone()
			if fetch is None:
				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])
			dbcon.close()
		except:
			log_utils.error()
			try:
				return dbcon.close()
			except:
				return

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

		while not xbmc.abortRequested:
			try:
				last_service = control.window.getProperty(self.property)
				t1 = datetime.timedelta(hours=6)
				t2 = datetime.datetime.strptime(last_service, '%Y-%m-%d %H:%M:%S.%f')
				t3 = datetime.datetime.now()

				check = abs(t3 - t2) >= t1
				if check is False:
					continue

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

				last_service = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
				control.window.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("DELETE FROM service WHERE setting = 'last_run'")
					dbcur.execute("INSERT INTO service Values (?, ?)", ('last_run', last_service))
					# dbcur.execute("INSERT OR REPLACE service Values (?, ?)", ('last_run', last_service))
					dbcur.connection.commit()
					dbcon.close()
				except:
					log_utils.error()
					try:
						dbcon.close()
					except:
						pass

				if not control.setting('library.service.update') == 'true':
					continue

				libmovies().list_update()
				libtvshows().list_update()
				libepisodes().update()
			except:
				log_utils.error()
				pass

			control.sleep(10000)
Пример #56
0
def download(name, image, url):
    # log_utils.log('name = %s' % str(name), log_utils.LOGDEBUG)
    try:
        if url is None:
            control.hide()
            return
        try:
            headers = dict(parse_qsl(url.rsplit('|', 1)[1]))
        except:
            headers = dict('')

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

        try:
            content = re.search(
                r'(.+?)(?:|\.| - |-|\s)(?:S|s|\s|\.)(\d{1,2})(?!\d)(?:-{0,1})(?:E{0,1}|e{0,1})[0-2]{1}[0-9]{1}(?!\w)',
                name.replace('\'', '')).groups()
            # log_utils.log('content = %s' % str(content), log_utils.LOGDEBUG)
        except:
            content = ()

        transname = name.translate(None, '\/:*?"<>|').strip('.')
        ext_list = ['.mp4', '.mkv', '.flv', '.avi', '.mpg']
        for i in ext_list:
            transname = transname.rstrip(i)

        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)

            try:
                movie_info = re.search(
                    r'(.+?)(?:\.{0,1}-{0,1}\.{0,1}|\s*)(?:\({0,1})((?:19|20)(?:[0-9]{2}))',
                    name.replace('\'', '')).groups()
                # log_utils.log('movie_info = %s' % str(movie_info), log_utils.LOGDEBUG)
            except:
                movie_info = ()

            if len(movie_info) != 0:
                movietitle = titlecase(
                    re.sub('[^A-Za-z0-9\s]+', ' ', movie_info[0]))
                dest = os.path.join(dest, movietitle + '_' + movie_info[1])
            else:
                dest = os.path.join(dest, transname)
            # log_utils.log('dest = %s' % str(dest), log_utils.LOGDEBUG)

            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].translate(
                None, '\/:*?"<>|').strip('.').replace('.', ' ')
            if not transtvshowtitle[0].isupper():
                transtvshowtitle = transtvshowtitle.capitalize()
            dest = os.path.join(dest, transtvshowtitle)
            control.makeFile(dest)
            dest = os.path.join(dest, 'Season %01d' % int(content[1]))
            control.makeFile(dest)
        ext = os.path.splitext(urlparse(url).path)[1][1:]
        if not ext in ['mp4', 'mkv', 'flv', 'avi', 'mpg']:
            ext = 'mp4'
        dest = os.path.join(dest, transname + '.' + ext)
        doDownload(url, dest, name, image, headers)
    except:
        log_utils.error()
        pass
Пример #57
0
    def strmFile(self, i):
        try:
            name, title, year, imdb, tmdb, tvdb, tvrage, season, episode, tvshowtitle, alter, date = i[
                'name'], i['title'], i['year'], i['imdb'], i['tmdb'], i[
                    'tvdb'], i['tvrage'], i['season'], i['episode'], i[
                        'tvshowtitle'], i['alter'], i['date']

            episodename, episodetitle = urllib.quote_plus(
                name), urllib.quote_plus(title)
            systitle, syspremiered = urllib.quote_plus(
                tvshowtitle), urllib.quote_plus(date)

            if self.version >= 15:
                transname = '%s (%s) S%02dE%02d' % (tvshowtitle.translate(
                    None, '\/:*?"<>|'), year, int(season), int(episode))
                transtitle = '%s (%s)' % (tvshowtitle.translate(
                    None, '\/:*?"<>|'), year)
            else:
                transname = name.translate(None, '\/:*?"<>|').strip('.')
                transtitle = tvshowtitle.translate(None,
                                                   '\/:*?"<>|').strip('.')

            transseason = 'Season %s' % season.translate(
                None, '\/:*?"<>|').strip('.')

            content = '%s?action=play&name=%s&title=%s&year=%s&imdb=%s&tmdb=%s&tvdb=%s&tvrage=%s&season=%s&episode=%s&tvshowtitle=%s&alter=%s&date=%s' % (
                sys.argv[0], episodename, episodetitle, year, imdb, tmdb, tvdb,
                tvrage, season, episode, systitle, alter, syspremiered)

            control.makeFile(self.library_folder)

            folder = os.path.join(self.library_folder, transtitle)
            control.makeFile(folder)

            try:
                if not 'ftp://' in folder: raise Exception()
                from ftplib import FTP
                ftparg = re.compile(
                    'ftp://(.+?):(.+?)@(.+?):?(\d+)?/(.+/?)').findall(folder)
                ftp = FTP(ftparg[0][2], ftparg[0][0], ftparg[0][1])
                try:
                    ftp.cwd(ftparg[0][4])
                except:
                    ftp.mkd(ftparg[0][4])
                ftp.quit()
            except:
                pass

            folder = os.path.join(folder, transseason)
            control.makeFile(folder)

            try:
                if not 'ftp://' in folder: raise Exception()
                from ftplib import FTP
                ftparg = re.compile(
                    'ftp://(.+?):(.+?)@(.+?):?(\d+)?/(.+/?)').findall(folder)
                ftp = FTP(ftparg[0][2], ftparg[0][0], ftparg[0][1])
                try:
                    ftp.cwd(ftparg[0][4])
                except:
                    ftp.mkd(ftparg[0][4])
                ftp.quit()
            except:
                pass

            stream = os.path.join(folder, transname + '.strm')
            file = control.openFile(stream, 'w')
            file.write(str(content))
            file.close()
        except:
            pass
Пример #58
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


# def local(items, link, poster, fanart):
	# try:
		# # dbcon = database.connect(control.metaFile())
		# dbcon = database.connect(control.metacacheFile)
		# dbcur = dbcon.cursor()
		# args = [i['imdb'] for i in items]
		# dbcur.execute('SELECT * FROM mv WHERE imdb IN (%s)' % ', '.join(list(map(lambda arg:  "'%s'" % arg, args))))
		# data = dbcur.fetchall()
	# except:
		# return items
	# for i in range(0, len(items)):
		# try:
			# item = items[i]
			# match = [x for x in data if x[1] == item['imdb']][0]
			# try:
				# if poster in item and item[poster] != '0':
					# raise Exception()
				# if match[2] == '0':
					# raise Exception()
				# items[i].update({poster: link % ('300', '/%s.jpg' % match[2])})
			# except:
				# pass
			# try:
				# if fanart in item and item[fanart] != '0':
					# raise Exception()
				# if match[3] == '0':
					# raise Exception()
				# items[i].update({fanart: link % ('1280', '/%s.jpg' % match[3])})
			# except:
				# pass
		# except:
			# pass
	# dbcon.close()
	# return items
Пример #59
0
def _get_connection_search():
    control.makeFile(control.dataPath)
    conn = db.connect(control.searchFile)
    conn.row_factory = _dict_factory
    return conn
Пример #60
0
def getSeasonIndicators2(tvshowtitle, imdb, tvdb, season):
    try:
        import sys, xbmc
        from resources.lib.modules import control

        if not trakt.getTraktIndicatorsInfo() == False: raise Exception()
        total = '6'
        from metahandler import metahandlers
        from resources.lib.indexers import episodes
        if not int('%01d' % int(season)) > 0: raise Exception()
        metaget = metahandlers.MetaData(preparezip=False)

        name = control.addonInfo('name')

        imdb = imdb.encode('utf-8')
        tvdb = tvdb.encode('utf-8')
        season = season.encode('utf-8')
        # metaget.get_meta('tvshow', '', imdb_id=imdb)

        items = episodes.episodes().get(tvshowtitle,
                                        '0',
                                        imdb,
                                        tvdb,
                                        '0',
                                        idx=False)
        try:
            items = [
                i for i in items
                if int('%01d' % int(season)) == int('%01d' % int(i['season']))
            ]
        except:
            pass
        season_playcount = []
        for i in range(len(items)):

            season, episode = items[i]['season'], items[i]['episode']
            playcount = metaget._get_watched_episode({
                'imdb_id': imdb,
                'season': season,
                'episode': episode,
                'premiered': ''
            })
            playcount = str(playcount)

            if playcount == '7': play = '1'
            else: play = '0'

            season_playcount.append(playcount)

        season_file = control.seasons_meta
        try:
            from sqlite3 import dbapi2 as database
        except:
            from pysqlite2 import dbapi2 as database

        try:

            control.makeFile(control.dataPath)
            dbcon = database.connect(season_file)
            dbcur = dbcon.cursor()
            dbcur.execute("CREATE TABLE IF NOT EXISTS season_meta ("
                          "imdb TEXT, "
                          "tvdb TEXT, "
                          "season TEXT, "
                          "playcount TEXT, "
                          "UNIQUE(imdb, tvdb, season, playcount)"
                          ");")
            dbcon.commit()
        except:
            pass

        if "6" in season_playcount:
            total = '6'
            dbcon = database.connect(season_file)
            dbcur = dbcon.cursor()
            dbcur.execute(
                "DELETE FROM season_meta WHERE imdb = '%s' AND season = '%s'" %
                (imdb, season))
            dbcur.execute("INSERT INTO season_meta Values (?, ?, ?, ?)",
                          (imdb, tvdb, season, total))
            dbcon.commit()

        elif int(len(season_playcount)) > 0:
            if not "6" in season_playcount:
                total = '7'
                dbcon = database.connect(season_file)
                dbcur = dbcon.cursor()
                dbcur.execute(
                    "DELETE FROM season_meta WHERE imdb = '%s' AND season = '%s'"
                    % (imdb, season))
                dbcur.execute("INSERT INTO season_meta Values (?, ?, ?, ?)",
                              (imdb, tvdb, season, total))
                dbcon.commit()

            # metaget.change_watched('season', name='', imdb_id=imdb, season=season, watched=int(total))
        return total

    except:
        return total