Beispiel #1
0
def show_season_path_from_ep_s(ep_s, create_if_missing=True):
    show_s = guess_ds_folder(ep_s)
    if show_s.lower().startswith("marvels agents of"):
        show_s = "Marvels Agents of S.H.I.E.L.D"
    if db.exists(show_s):  # Will compare lowercase strings...
        show_folder = db.data(show_s, "folder")
    else:
        pr.warning(f"could not determine show for episode, guessed [{show_s}]")
        show_folder = show_s
    season_n = guess_season(ep_s)
    path = _show_path_season(show_folder, season_n)
    if ftool.is_existing_folder(_show_path(show_folder)):
        pr.info(f"show path exists [{_show_path(show_folder)}]")
    if not ftool.is_existing_folder(path):
        pr.warning(f"path does not exist [{path}]")
        if create_if_missing:
            script_name = os.path.basename(__file__)
            if user_input.yes_no(f"create path {path}?",
                                 script_name=script_name):
                os.makedirs(path)
                return path
        else:
            return None
    else:
        pr.info(f"found existing path: [{path}]")
    return path
Beispiel #2
0
def check_status():
    pr.info("confirming episode status flags...")
    need_save = False
    for ep in __flatten_eps():
        if ep["status"] == "deleted":
            if ftool.is_existing_file(ep['full_path']):
                pr.warning(f"not deleted: [{ep['full_path']}]")
                si = ep["season_index"]
                ei = ep["episode_index"]
                show_d = db.data(ep["show"])
                show_d["seasons"][si]["episodes"][ei]['status'] = "ok"
                db.update(ep["show"], db.data(ep["show"], key=None))
                need_save = True
        else:
            if not ftool.is_existing_file(ep['full_path']):
                pr.info(f"found deleted: [{ep['full_path']}]")
                si = ep["season_index"]
                ei = ep["episode_index"]
                show_d = db.data(ep["show"])
                show_d["seasons"][si]["episodes"][ei]['status'] = "deleted"
                db.update(ep["show"], db.data(ep["show"], key=None))
                need_save = True
    if need_save:
        db.save()
        ftool.copy_dbs_to_webserver("tv")
Beispiel #3
0
def determine_year(folder):
    re_year = re.compile("(19|20)\d{2}")
    year = re_year.search(folder)
    if year is not None:
        return year.group(0)
    else:
        pr.warning("could not guess year for {}".format(folder))
        return None
Beispiel #4
0
def has_nfo(show):
    show_s = to_show_s(show)
    full_path = _show_path(show_s)
    if not os.path.exists(full_path):
        pr.warning("path {} does not exists".format(full_path))
        return False
    for file in os.listdir(full_path):
        if file.endswith(".nfo"):
            return True
    return False
Beispiel #5
0
 def update(self, table, column, value, column_to_match, match_data):
     query = f"UPDATE {table} SET {column} = %s WHERE {table}.{column_to_match} = %s"
     data = (value, match_data)
     if self.__run_query(query, data):
         self.__commit()
         pr.info(f"updated: {match_data} : {column} = {value}")
         return True
     else:
         pr.warning(f"failed update: {match_data} : {column} = {value}")
         return False
Beispiel #6
0
 def save(self):
     with open(self._db_file, 'w', encoding='utf8') as outfile:
         str_ = json.dumps(self._loaded_db,
             indent=4, sort_keys=True,
             separators=(',', ': '), ensure_ascii=False)
         outfile.write(to_unicode(str_))
     pr.success("saved database to {}!".format(self._db_file))
     if self.backup_to_ds():
         pr.success("backed up database!")
     else:
         pr.warning("could not backup database!")
Beispiel #7
0
 def update(self, movie_folder, key, data):
     if not self.exists(movie_folder):
         pr.warning("update: {} is not in database!".format(movie_folder))
     else:
         try:
             self._loaded_db[movie_folder][key] = data
             if key is 'omdb':
                 data = "omdb-search"
             pr.info("Updated {} : {} = {}".format(movie_folder, key, data))
         except:
             pr.warning("update: Could not update {}!".format(movie_folder))
Beispiel #8
0
def determine_title(folder, replace_dots_with=' '):
    re_title = re.compile(".+?(?=\.(\d{4}|REPACK|720p|1080p|DVD|BluRay))")
    title = re_title.search(folder)
    if title is not None:
        title = re.sub('(REPACK|LiMiTED|EXTENDED|Unrated)', '.',
                       title.group(0))
        title = re.sub('\.', replace_dots_with, title)
        return title
    else:
        pr.warning("could not guess title for {}".format(folder))
        return None
Beispiel #9
0
 def _load_db(self):
     if filetools.is_file_empty(self._db_file):
         self._loaded_db = {}
         pr.warning("creating empty database")
     else:
         try:
             with open(self._db_file, 'r') as db:
                 self._loaded_db = json.load(db)
                 pr.info("loaded database file: [ {} ]".format(self._db_file))
         except:
             pr.error("Could not open file: {0}".format(self._db_file))
             self._loaded_db = None
Beispiel #10
0
 def data(self, show_s, key=None):
     if isinstance(show_s, dict) and "folder" in show_s:
         show_s = show_s["folder"]
     if self.exists(show_s):
         show_s = self._show_s_to_formatted_key(show_s)
         if key is None:
             return self._loaded_db[show_s]
         else:
             if key in self._loaded_db[show_s]:
                 return self._loaded_db[show_s][key]
     pr.warning(f"[data] could not retrieve data for show")
     return None
Beispiel #11
0
 def update(self, show_folder, data, key = None):
     if not self.exists(show_folder):
         pr.warning("update: {} is not in database!".format(show_folder))
     else:
         try:
             if key:
                 self._loaded_db[show_folder][key] = data
                 if key is 'omdb':
                     data = "omdb-search"
                 pr.info("updated {} : {} = {}".format(show_folder, key, data))
             else:
                 self._loaded_db[show_folder] = data
                 pr.info("updated {} with new data!".format(show_folder, data))
         except:
             pr.warning("update: Could not update {}!".format(show_folder))
Beispiel #12
0
def db_maintainance():
    pr.info("running moviedb maintainance...")
    need_save = False
    for mov in mlist:
        if db.movie_data(mov, 'status') == "deleted":
            continue
        full_path = os.path.join(mov_root, db.movie_data(mov, 'letter'), db.movie_data(mov, 'folder'))
        # Update movies with missing status
        if not db.movie_data(mov, 'status'):
            if os.path.isdir(full_path):
                db.update(mov, 'status', "ok")
                need_save = True
        if not db.movie_data(mov, 'nfo') or not db.movie_data(mov, 'imdb'):
            if try_add_nfo(mov):
                need_save = True
        # Try to update missing omdb-data
        data = db.movie_data(mov, 'omdb')
        if not data or 'Error' in data:
            if update_omdb_search(mov):
                need_save = True
        # Wrong title...
        elif "Title" in data and data['Title'].startswith("#"):
            pr.warning(f"{mov} has faulty title: [{data['Title']}]")
            if update_omdb_search(mov):
                if "Title" in data and not data['Title'].startswith("#"):
                    need_save = True
                elif data['Title'].startswith("#"):
                    pr.info("omdb data still contains faulty title, using folder as title")
                    title = mtool.determine_title(db.movie_data(mov, 'folder'))
                    pr.info(f"guessed title: [{title}]")
                    data['Title'] = title
                    db.update(mov, 'omdb', data)
                    need_save = True
        sub_data = db.movie_data(mov, 'subs')
        for lang in ['en', 'sv']:
            if not sub_data[lang]:
                sub = mtool.has_subtitle(full_path, lang)
                if sub:
                    pr.info(f"found [{lang}] sub for {mov}")
                    sub_data[lang] = sub
                    db.update(mov, 'subs', sub_data)
                    need_save = True
    if need_save:
        db.save()
        ftool.copy_dbs_to_webserver("movie")
    else:
        pr.info("nothing updated")
Beispiel #13
0
def check_nfo():
    global shows
    skiplist = ["Vad Blir Det For Mat"]
    for show in shows:
        if show.startswith("@"):  # Diskstation
            continue
        if show in skiplist:
            pr.info(f"in skiplist: [{show}]")
            continue
        if tvtool.has_nfo(show):
            if tvtool.nfo_to_imdb(show):
                pr.info("{} has tvshow.nfo".format(show))
            else:
                pr.warning("{} has non-imdb tvshow.nfo".format(show))
                tvtool.add_nfo_manual(show, replace=True)
        else:
            tvtool.add_nfo_manual(show)
Beispiel #14
0
 def insert(self, table, columns = [], data=[]):
     if len(columns) != len(data):
         pr.warning("columns and data doesnt match!")
         return
     query = f"INSERT INTO {table} ("
     for column in columns:
         query += f"{column},"
     query = query[:-1] + ") VALUES ("
     for column in columns:
         query += r"%s,"
     query = query[:-1] + ")"
     result = self.__run_query(query, tuple(data))
     if result:
         self.__commit()
         pr.info(f"inserted {data} into table {table}")
         return True
     else:
         return False
Beispiel #15
0
 def select(self, table, columns = [], column_to_match = None, match_data = None):
     column_string = ""
     if not columns:
         column_string = "*"
     else:
         for column in columns:
             column_string = f"{column_string},{column}"
     column_string = column_string.strip(',')
     query = f"SELECT {column_string} FROM {table} WHERE {column_to_match} = %s"
     data = (match_data,)
     result = self.__run_query(query, data)
     result_list = []
     if result:
         self.__commit()
         pr.info(f"selected: {columns}")
         for column_string in self.cursor:
             print(f"result: {str(column_string)}")
             result_list.append(str(column_string))
         return result
     else:
         pr.warning(f"failed select query")
         return False