Esempio n. 1
0
def update_completion_date():
    try:
        json_data = request.get_json()
        media_id = int(json_data['element_id'])
        media_list = json_data['element_type']
        media_date = json_data['element_date']
    except:
        return '', 400

    # Check if <media_list> exist and is valid
    try:
        list_type = ListType(media_list)
        models = get_models_group(list_type)
    except:
        return '', 400

    # Get the media info
    media = models[1].query.filter_by(user_id=current_user.id,
                                      media_id=media_id).first()
    if not media:
        return '', 400

    # Change the completion date only if the status' media is COMPLETED
    if media.status == Status.COMPLETED:
        media.completion_date = media_date

    # Commit the session
    db.session.commit()
    app.logger.info(
        f"[User {current_user.id}] {list_type}'s completion date [ID {media_id}] changed."
    )

    return '', 204
Esempio n. 2
0
def add_favorite():
    try:
        json_data = request.get_json()
        media_id = int(json_data['element_id'])
        media_list = json_data['element_type']
        favorite = bool(json_data['favorite'])
    except:
        return '', 400

    # Check if the <media_list> exist and is valid
    try:
        list_type = ListType(media_list)
        models = get_models_group(list_type)
    except ValueError:
        return '', 400

    # Check if the <media_id> is in the current user's list
    media = models[1].query.filter_by(user_id=current_user.id,
                                      media_id=media_id).first()
    if not media:
        return '', 400

    # Add <favorite> and commit the changes
    media.favorite = favorite
    db.session.commit()

    return '', 204
Esempio n. 3
0
def lock_media():
    try:
        json_data = request.get_json()
        media_id = json_data['element_id']
        media_list = json_data['element_type']
        lock_status = bool(json_data['lock_status'])
    except:
        return '', 400

    # Check if the user is admin or manager
    if current_user.role == RoleType.USER:
        return '', 403

    # Check if <list_type> exist and is valid
    try:
        models = get_models_group(ListType(media_list))
    except:
        return '', 400

    media = models[0].query.filter_by(id=media_id).first()
    if not media:
        return '', 400

    media.lock_status = lock_status
    db.session.commit()
    app.logger.info(f"{media_list} [ID {media_id}] successfully locked.")

    return '', 204
Esempio n. 4
0
def delete_element():
    try:
        json_data = request.get_json()
        media_id = int(json_data['delete'])
        media_list = json_data['element_type']
    except:
        return '', 400

    # Check if <list_type> exist and is valid
    try:
        models = get_models_group(ListType(media_list))
    except:
        return '', 400

    media = models[1].query.filter_by(user_id=current_user.id,
                                      media_id=media_id).first()
    if not media:
        return '', 400

    try:
        old_total = media.total
    except:
        old_total = media.playtime

    media.compute_new_time_spent(old_data=old_total, new_data=0)

    # Delete the media from the user's list
    db.session.delete(media)
    db.session.commit()
    app.logger.info(
        f"[User {current_user.id}] {media_list} [ID {media_id}] successfully removed."
    )

    return '', 204
Esempio n. 5
0
def update_episode():
    try:
        json_data = request.get_json()
        new_episode = int(json_data['episode']) + 1
        media_id = int(json_data['element_id'])
        media_list = json_data['element_type']
    except:
        return '', 400

    # Check if <media_list> exist and is valid
    try:
        list_type = ListType(media_list)
        models = get_models_group(list_type)
    except ValueError:
        return '', 400

    # Check if the media exists
    media = models[1].query.filter_by(user_id=current_user.id,
                                      media_id=media_id).first()
    if not media:
        return '', 400

    # Check if the episode number is between 1 and <last_episode>
    if 1 > new_episode or new_episode > media.media.eps_per_season[
            media.current_season - 1].episodes:
        return '', 400

    # Get the old data
    old_season = media.current_season
    old_episode = media.last_episode_watched
    old_total = media.total

    # Set the new data
    new_watched = sum(
        [x.episodes
         for x in media.media.eps_per_season[:old_season - 1]]) + new_episode
    media.last_episode_watched = new_episode
    new_total = new_watched + (media.rewatched * media.media.total_episodes)
    media.total = new_total
    app.logger.info(
        f"[User {current_user.id}] {list_type} [ID {media_id}] episode updated to {new_episode}"
    )

    # Set the last updates
    UserLastUpdate.set_last_update(media=media.media,
                                   media_type=list_type,
                                   old_season=old_season,
                                   new_season=old_season,
                                   old_episode=old_episode,
                                   new_episode=new_episode)

    # Compute new time spent
    media.compute_new_time_spent(old_data=old_total, new_data=new_total)

    # Commit the changes
    db.session.commit()

    return '', 204
Esempio n. 6
0
def mymedialist(media_list,
                user_name,
                category=None,
                genre='All',
                sorting=None,
                page_val=1):
    # Check if <media_list> is valid
    try:
        list_type = ListType(media_list)
        models = get_models_group(list_type)
    except ValueError:
        return abort(400)

    # Check if <user> can see <media_list>
    user = current_user.check_autorization(user_name)

    # Add <views_count> to the profile
    current_user.add_view_count(user, list_type)

    # Initialize the search form
    search_form = SearchForm()

    # Get the query if it exists
    q = request.args.get('q')

    # Get the sorting
    if sorting is None:
        sorting = models[1].default_sorting()

    # Get the category
    if category is None:
        category = models[1].default_category()

    # Get the template
    html_template = models[1].html_template()

    # Get the corresponding data depending on the selected category
    if category != 'Stats':
        # media_data = MediaListQuery(models, user.id, category, genre, sorting, page_val, q)
        category, media_data = get_media_query(user, list_type, category,
                                               genre, sorting, page_val, q)
    else:
        media_data = models[1].get_more_stats(user)

    # Commit the changes
    db.session.commit()

    return render_template(html_template,
                           title="{}'s {}".format(user_name, media_list),
                           user=user,
                           search_q=q,
                           media_list=media_list,
                           search_form=search_form,
                           category=category,
                           genre=genre,
                           sorting=sorting,
                           page=page_val,
                           data=media_data)
Esempio n. 7
0
def update_rewatch():
    try:
        json_data = request.get_json()
        new_rewatch = int(json_data['rewatch'])
        media_id = int(json_data['element_id'])
        media_list = json_data['element_type']
    except:
        return '', 400

    # Check if the <media_list> exist and is valid
    try:
        list_type = ListType(media_list)
    except ValueError:
        return '', 400

    # Check that <new_rewatch> is between [0-10]
    if 0 > new_rewatch > 10:
        return '', 400

    media = check_media(media_id, list_type)
    if not media or (media[1].status != Status.COMPLETED
                     and media[1].status != Status.COMPLETED_ANIMATION):
        return '', 400

    # Get the old data
    old_rewatch = media[1].rewatched

    # Set the new data
    media[1].rewatched = new_rewatch
    app.logger.info('[{}] Series ID {} re-watched {}x times'.format(
        current_user.id, media_id, new_rewatch))

    # total eps/movies watched
    if list_type != ListType.MOVIES:
        media[1].eps_watched = media[0].total_episodes + (
            new_rewatch * media[0].total_episodes)
    elif list_type == ListType.MOVIES:
        media[1].eps_watched = 1 + new_rewatch

    # Commit the changes
    db.session.commit()

    # Compute the new time spent
    if list_type != ListType.MOVIES:
        compute_time_spent(media=media[0],
                           list_type=list_type,
                           old_rewatch=old_rewatch,
                           new_rewatch=new_rewatch)
    elif list_type == ListType.MOVIES:
        compute_time_spent(media=media[0],
                           list_type=list_type,
                           movie_status=media[1].status,
                           old_rewatch=old_rewatch,
                           new_rewatch=new_rewatch)

    return '', 204
Esempio n. 8
0
def add_element():
    try:
        json_data = request.get_json()
        media_id = json_data['element_id']
        media_list = json_data['element_type']
        media_cat = json_data['element_cat']
    except:
        return '', 400

    # Check <media_list>
    try:
        list_type = ListType(media_list)
        models = get_models_group(list_type)
    except:
        return '', 400

    # Check <status> parameter
    try:
        new_status = Status(media_cat)
    except:
        return '', 400

    # Check that the <media> is not in the user's list
    in_list = models[1].query.filter_by(user_id=current_user.id,
                                        media_id=media_id).first()
    if in_list:
        return '', 400

    # Check if <media> exists
    media = models[0].query.filter_by(id=media_id).first()
    if not media:
        return '', 400

    # Add the media to the user
    new_watched = media.add_media_to_user(new_status)

    # Commit the changes
    db.session.commit()
    app.logger.info(
        f"[User {current_user.id}] {list_type} Added [ID {media_id}] in the category: {new_status}"
    )

    # Set the last update
    UserLastUpdate.set_last_update(media=media,
                                   media_type=list_type,
                                   new_status=new_status)

    # Compute new time spent
    in_list = models[1].query.filter_by(user_id=current_user.id,
                                        media_id=media_id).first()
    in_list.compute_new_time_spent(new_data=new_watched)

    # Commit the last updates and the new time spent changes
    db.session.commit()

    return '', 204
Esempio n. 9
0
def update_category():
    try:
        json_data = request.get_json()
        media_new_cat = json_data['status']
        media_id = int(json_data['element_id'])
        media_list = json_data['element_type']
    except:
        return '', 400

    # Check if <media_list> exist and is valid
    try:
        list_type = ListType(media_list)
        models = get_models_group(list_type)
    except:
        return '', 400

    # Check the <status> parameter
    try:
        new_status = Status(media_new_cat)
    except:
        return '', 400

    # Get the media
    media = models[1].query.filter_by(user_id=current_user.id,
                                      media_id=media_id).first()
    if not media:
        return '', 400

    # Change the <status> and get the data to compute <last_updates> and <new_time_spent>
    try:
        old_total = media.total
    except:
        old_total = media.playtime
    old_status = media.status
    new_total = media.category_changes(new_status)

    # Set the last updates
    UserLastUpdate.set_last_update(media=media.media,
                                   media_type=list_type,
                                   old_status=old_status,
                                   new_status=new_status,
                                   old_playtime=old_total,
                                   new_playtime=new_total)

    # Compute the new time spent
    media.compute_new_time_spent(old_data=old_total, new_data=new_total)

    # Commit the session
    db.session.commit()
    app.logger.info(
        f"[User {current_user.id}] {list_type}'s category [ID {media_id}] changed to {new_status}"
    )

    return '', 204
Esempio n. 10
0
def update_page():
    try:
        json_data = request.get_json()
        new_page = int(json_data['page'])
        media_id = int(json_data['element_id'])
        media_list = json_data['element_type']
    except:
        return '', 400

    # Check if <media_list> exist and is valid
    try:
        list_type = ListType(media_list)
        models = get_models_group(list_type)
    except ValueError:
        return '', 400

    # Check if the media exists
    media = models[1].query.filter_by(user_id=current_user.id,
                                      media_id=media_id).first()
    if not media:
        return '', 400

    # Check if the page number is between 0 and max(pages)
    if new_page > int(media.media.pages) or new_page < 0:
        return "The number of pages cannot be below 0 or greater than the total pages.", 400

    # Get the old data
    old_page = media.actual_page
    old_total = media.total

    # Set the new data
    media.actual_page = new_page
    new_total = new_page + (media.rewatched * media.media.pages)
    media.total = new_total
    app.logger.info(
        f"[User {current_user.id}] {list_type} [ID {media_id}] page updated from {old_page} to {new_page}"
    )

    # Set the last updates
    UserLastUpdate.set_last_update(media=media.media,
                                   media_type=list_type,
                                   old_page=old_page,
                                   new_page=new_page,
                                   old_status=media.status)

    # Compute new time spent
    media.compute_new_time_spent(old_data=old_total, new_data=new_total)

    # Commit the changes
    db.session.commit()

    return '', 204
Esempio n. 11
0
def update_playtime():
    try:
        json_data = request.get_json()
        new_playtime = int(json_data['playtime']) * 60  # To get minutes
        media_id = int(json_data['media_id'])
        media_list = json_data['media_type']
    except:
        return '', 400

    if new_playtime < 0:
        return '', 400

    # Check if <media_list> exist and valid
    try:
        list_type = ListType(media_list)
        models = get_models_group(list_type)
    except ValueError:
        return '', 400

    media = models[1].query.filter_by(user_id=current_user.id,
                                      media_id=media_id).first()
    if not media:
        return '', 400

    # Set the last updates
    UserLastUpdate.set_last_update(media=media.media,
                                   media_type=list_type,
                                   old_playtime=media.playtime,
                                   new_playtime=new_playtime,
                                   old_status=media.status)

    # Compute the new time spent
    media.compute_new_time_spent(new_data=new_playtime)

    # Update new playtime
    media.playtime = new_playtime

    # Commit the changes
    db.session.commit()
    app.logger.info(
        f"[{current_user.id}] Games ID {media_id} playtime updated to {new_playtime}"
    )

    return '', 204
Esempio n. 12
0
def delete_element():
    try:
        json_data = request.get_json()
        media_id = int(json_data['delete'])
        media_list = json_data['element_type']
    except:
        return '', 400

    # Check if the <media_list> exist and is valid
    try:
        list_type = ListType(media_list)
    except ValueError:
        return '', 400

    media = check_media(media_id, list_type)
    if media is None:
        return '', 400

    # Get the old data
    old_rewatch = media[1].rewatched

    # Compute the new time spent
    if list_type == ListType.SERIES or list_type == ListType.ANIME:
        old_watched = media[1].eps_watched
        compute_time_spent(media=media[0],
                           old_watched=old_watched,
                           list_type=list_type,
                           old_rewatch=old_rewatch)
    elif list_type == ListType.MOVIES:
        compute_time_spent(media=media[0],
                           list_type=list_type,
                           movie_status=media[1].status,
                           movie_delete=True,
                           old_rewatch=old_rewatch)

    # Delete the media from the user's list
    db.session.delete(media[1])
    db.session.commit()
    app.logger.info('[User {}] {} [ID {}] successfully removed.'.format(
        current_user.id, list_type.value.replace('list', ''), media_id))

    return '', 204
Esempio n. 13
0
def update_feeling():
    try:
        json_data = request.get_json()
        new_feeling = json_data['feeling']
        media_id = int(json_data['element_id'])
        media_list = json_data['element_type']
    except:
        return '', 400

    # Check if <media_list> exist and valid
    try:
        list_type = ListType(media_list)
        models = get_models_group(list_type)
    except ValueError:
        return '', 400

    # Check that <new_feeling> is null or between 1 and 4
    try:
        if 0 > int(new_feeling) or int(new_feeling) > 5:
            return '', 400
    except:
        new_feeling = None

    media = models[1].query.filter_by(user_id=current_user.id,
                                      media_id=media_id).first()
    if not media:
        return '', 400

    # Set the new data
    media.feeling = new_feeling
    app.logger.info(
        f"[{current_user.id}] Media ID {media_id} feeling updated to {new_feeling}"
    )

    # Commit the changes
    db.session.commit()

    return '', 204
Esempio n. 14
0
def update_score():
    try:
        json_data = request.get_json()
        new_score = json_data['score']
        media_id = int(json_data['element_id'])
        media_list = json_data['element_type']
    except:
        return '', 400

    # Check if <media_list> exist and valid
    try:
        list_type = ListType(media_list)
        models = get_models_group(list_type)
    except ValueError:
        return '', 400

    # Check that <new_score> is '---' or between [0-10]
    try:
        if 0 > float(new_score) or float(new_score) > 10:
            return '', 400
    except:
        new_score = None

    media = models[1].query.filter_by(user_id=current_user.id,
                                      media_id=media_id).first()
    if not media:
        return '', 400

    # Set the new data
    media.score = new_score
    app.logger.info(
        f"[{current_user.id}] Series ID {media_id} score updated to {new_score}"
    )

    # Commit the changes
    db.session.commit()

    return '', 204
Esempio n. 15
0
def update_rewatch():
    try:
        json_data = request.get_json()
        new_rewatch = int(json_data['rewatch'])
        media_id = int(json_data['element_id'])
        media_list = json_data['element_type']
    except:
        return '', 400

    # Check if the <media_list> exist and is valid
    try:
        list_type = ListType(media_list)
        models = get_models_group(list_type)
    except ValueError:
        return '', 400

    # Check that <new_rewatch> is between [0-10]
    if 0 > new_rewatch > 10:
        return '', 400

    media = models[1].query.filter_by(user_id=current_user.id,
                                      media_id=media_id).first()
    if not media or media.status != Status.COMPLETED:
        return '', 400

    # Update rewatch and total data watched
    old_total = media.total
    new_total = media.update_total_watched(new_rewatch)

    # Compute the new time spent
    media.compute_new_time_spent(old_data=old_total, new_data=new_total)

    # Commit the changes
    db.session.commit()
    app.logger.info('[{}] Media ID {} rewatched {}x times'.format(
        current_user.id, media_id, new_rewatch))

    return '', 204
Esempio n. 16
0
def update_score():
    try:
        json_data = request.get_json()
        new_score = json_data['score']
        media_id = int(json_data['element_id'])
        media_list = json_data['element_type']
    except:
        return '', 400

    # Check if <media_list> exist and valid
    try:
        list_type = ListType(media_list)
    except ValueError:
        return '', 400

    # Check that <new_score> is '---' or between [0-10]
    try:
        if 0 > float(new_score) > 10:
            return '', 400
    except:
        new_score = -1

    media = check_media(media_id, list_type)
    if not media:
        return '', 400

    # Get the old data
    old_score = media[1].score

    # Set the new data
    media[1].score = new_score
    app.logger.info('[{}] Series ID {} score updated from {} to {}'.format(
        current_user.id, media_id, old_score, new_score))

    # Commit the changes
    db.session.commit()

    return '', 204
Esempio n. 17
0
def add_favorite():
    try:
        json_data = request.get_json()
        media_id = int(json_data['element_id'])
        media_list = json_data['element_type']
        favorite = bool(json_data['favorite'])
    except:
        return '', 400

    # Check if the <media_list> exist and is valid
    try:
        list_type = ListType(media_list)
    except ValueError:
        return '', 400

    # Check if <favorite> is a boolean
    if type(favorite) is not bool:
        return '', 400

    # Check if the <media_id> is in the current user's list
    if list_type == ListType.SERIES:
        media = SeriesList.query.filter_by(user_id=current_user.id,
                                           media_id=media_id).first()
    elif list_type == ListType.ANIME:
        media = AnimeList.query.filter_by(user_id=current_user.id,
                                          media_id=media_id).first()
    elif list_type == ListType.MOVIES:
        media = MoviesList.query.filter_by(user_id=current_user.id,
                                           media_id=media_id).first()

    if not media:
        return '', 400

    # Add <favorite> and commit the changes
    media.favorite = favorite
    db.session.commit()

    return '', 204
Esempio n. 18
0
def lock_media():
    try:
        json_data = request.get_json()
        media_id = json_data['element_id']
        media_list = json_data['element_type']
        lock_status = json_data['lock_status']
    except:
        return '', 400

    # Check if the user is admin or manager
    if current_user.role == RoleType.USER:
        return '', 403

    # Check if <list_type> exist and is valid
    try:
        list_type = ListType(media_list)
    except ValueError:
        return '', 400

    # Check if <lock_status> is boolean
    if type(lock_status) is not bool:
        return '', 400

    if list_type == ListType.SERIES:
        media = Series.query.filter_by(id=media_id).first()
    elif list_type == ListType.ANIME:
        media = Anime.query.filter_by(id=media_id).first()
    elif list_type == ListType.MOVIES:
        media = Movies.query.filter_by(id=media_id).first()

    if not media:
        return '', 400

    media.lock_status = lock_status
    db.session.commit()

    return '', 204
Esempio n. 19
0
def add_element():
    try:
        json_data = request.get_json()
        media_id = json_data['element_id']
        media_list = json_data['element_type']
        media_cat = json_data['element_cat']
    except:
        return '', 400

    # Check if the <media_list> exist and is valid
    try:
        list_type = ListType(media_list)
    except ValueError:
        return '', 400

    # Check if <status> is valid compared to <list_type>
    new_status = check_cat_type(list_type, media_cat)
    if not new_status:
        return '', 400

    # Check if the <media>
    media = check_media(media_id, list_type, add=True)
    if media is None:
        return '', 400

    # Setup the <season>, <episode> and <category> of the <media>
    new_watched = 1
    if list_type == ListType.SERIES or list_type == ListType.ANIME:
        new_season = 1
        new_episode = 1
        if new_status == Status.COMPLETED:
            new_season = len(media.eps_per_season)
            new_episode = media.eps_per_season[-1].episodes
            new_watched = media.total_episodes
        elif new_status == Status.RANDOM or new_status == Status.PLAN_TO_WATCH:
            new_episode = 0
            new_watched = 0
    elif list_type == ListType.MOVIES:
        if new_status == Status.COMPLETED:
            if MoviesGenre.query.filter_by(media_id=media.id,
                                           genre="Animation").first():
                new_status = Status.COMPLETED_ANIMATION
        else:
            new_watched = 0

    # Add <media> to the <user>
    if list_type == ListType.SERIES:
        user_list = SeriesList(user_id=current_user.id,
                               media_id=media.id,
                               current_season=new_season,
                               last_episode_watched=new_episode,
                               status=new_status,
                               eps_watched=new_watched)
    elif list_type == ListType.ANIME:
        user_list = AnimeList(user_id=current_user.id,
                              media_id=media.id,
                              current_season=new_season,
                              last_episode_watched=new_episode,
                              status=new_status,
                              eps_watched=new_watched)
    elif list_type == ListType.MOVIES:
        user_list = MoviesList(user_id=current_user.id,
                               media_id=media.id,
                               status=new_status,
                               eps_watched=new_watched)

    # Commit the changes
    db.session.add(user_list)
    db.session.commit()
    app.logger.info('[User {}] {} Added [ID {}] in the category: {}'.format(
        current_user.id, list_type.value.replace('list', ''), media_id,
        new_status.value))

    # Set the last update
    set_last_update(media=media, media_type=list_type, new_status=new_status)

    # Compute the new time spent
    if list_type == ListType.SERIES or list_type == ListType.ANIME:
        compute_time_spent(media=media,
                           new_watched=new_watched,
                           list_type=list_type)
    elif list_type == ListType.MOVIES:
        compute_time_spent(media=media,
                           list_type=list_type,
                           movie_status=new_status,
                           movie_add=True)

    return '', 204
Esempio n. 20
0
def media_sheet(media_type, media_id):
    # Check if <media_type> is valid
    try:
        media_type = MediaType(media_type)
        models = get_models_group(media_type)
        list_type = ListType(media_type.value.lower() + 'list')
    except ValueError:
        abort(400)

    # Check if <media_id> came from an API
    from_api = request.args.get('search')

    # Check <media> in local DB
    search = {'id': media_id}
    if from_api:
        search = {'api_id': media_id}
    media = models[0].query.filter_by(**search).first()

    # If not <media> and <api_id>: Add <media> to DB, else abort.
    if not media:
        if from_api:
            API_model = ApiData.get_API_model(media_type)
            try:
                media = API_model(API_id=media_id).save_media_to_db()
                db.session.commit()
            except Exception as e:
                flash(
                    'Sorry, a problem occured trying to load the media info. Please try again later.',
                    'warning')
                app.logger.error(
                    '[ERROR] - Occured trying to add media ({}) ID [{}] to DB: {}'
                    .format(list_type.value, media_id, e))
                location = request.referrer or '/'
                return redirect(location)
        else:
            abort(400)

    # If <media> and <api_id>: redirect for URL with media.id instead of media.api_id
    if media and from_api:
        return redirect(
            url_for('main.media_sheet',
                    media_type=media_type.value,
                    media_id=media.id))

    # Get the list info of the user on this media
    list_info = media.get_user_list_info()

    # Get the HTML template
    template = models[0].media_sheet_template()

    # Get the history of the media for the user
    media_updates = UserLastUpdate.query.filter(UserLastUpdate.user_id == current_user.id,
                                                UserLastUpdate.media_type == list_type,
                                                UserLastUpdate.media_id == media_id)\
        .order_by(UserLastUpdate.date.desc()).all()
    history = current_user._shape_to_dict_updates(media_updates)

    # Get the Genre form for books
    form = GenreForm()
    form_cover = CoverForm()
    genres = None
    if list_type == ListType.BOOKS:
        genres = db.session.query(func.group_concat(BooksGenre.genre.distinct())) \
            .filter(BooksGenre.media_id == media_id).first()

    return render_template(template,
                           title=media.name,
                           media=media,
                           list_info=list_info,
                           form=form,
                           genres=genres,
                           media_list=list_type.value,
                           form_cover=form_cover,
                           media_updates=history)
Esempio n. 21
0
def change_element_category():
    try:
        json_data = request.get_json()
        media_new_cat = json_data['status']
        media_id = int(json_data['element_id'])
        media_list = json_data['element_type']
    except:
        return '', 400

    # Check the <media_list> parameter
    try:
        list_type = ListType(media_list)
    except ValueError:
        return '', 400

    # Check if the <status> parameter
    new_status = check_cat_type(list_type, media_new_cat)
    if not new_status:
        return '', 400

    # Recover the media
    media = check_media(media_id, list_type)
    if media is None:
        return '', 400

    # Get the old status
    old_status = media[1].status

    # Set the new status
    media[1].status = new_status

    # Get the old rewatched
    old_rewatch = media[1].rewatched
    # Reset the rewatched time multiplier
    media[1].rewatched = 0

    # Set and change accordingly <last_episode_watched>, <current_season> and <eps_watched> for anime and series
    if list_type == ListType.SERIES or list_type == ListType.ANIME:
        old_watched = media[1].eps_watched
        if new_status == Status.COMPLETED:
            media[1].current_season = len(media[0].eps_per_season)
            media[1].last_episode_watched = media[0].eps_per_season[
                -1].episodes
            media[1].eps_watched = media[0].total_episodes
            new_watched = media[0].total_episodes
        elif new_status == Status.RANDOM or new_status == Status.PLAN_TO_WATCH:
            media[1].current_season = 1
            media[1].last_episode_watched = 0
            media[1].eps_watched = 0
            new_watched = 0
        else:
            new_watched = old_watched
    elif list_type == ListType.MOVIES:
        if new_status == Status.COMPLETED or new_status == Status.COMPLETED_ANIMATION:
            media[1].eps_watched = 1
        else:
            media[1].eps_watched = 0

    # Set the last updates
    set_last_update(media=media[0],
                    media_type=list_type,
                    old_status=old_status,
                    new_status=new_status)

    # Compute the new time spent
    if list_type == ListType.SERIES or list_type == ListType.ANIME:
        compute_time_spent(media=media[0],
                           list_type=list_type,
                           old_watched=old_watched,
                           new_watched=new_watched,
                           old_rewatch=old_rewatch)
    elif list_type == ListType.MOVIES:
        compute_time_spent(media=media[0],
                           list_type=list_type,
                           movie_status=media[1].status,
                           old_rewatch=old_rewatch,
                           movie_runtime=media[0].runtime)

    db.session.commit()
    app.logger.info(
        "[User {}] {}'s category [ID {}] changed from {} to {}.".format(
            current_user.id, media_id, list_type.value.replace('list', ''),
            old_status.value, new_status.value))

    return '', 204
Esempio n. 22
0
def update_element_episode():
    try:
        json_data = request.get_json()
        new_episode = int(json_data['episode']) + 1
        media_id = int(json_data['element_id'])
        media_list = json_data['element_type']
    except:
        return '', 400

    # Check if the media_list exist and is valid
    try:
        list_type = ListType(media_list)
    except ValueError:
        return '', 400
    finally:
        if list_type == ListType.MOVIES:
            return '', 400

    # Check if the media exists
    media = check_media(media_id, list_type)
    if not media or media[1].status == Status.RANDOM or media[
            1].status == Status.PLAN_TO_WATCH:
        return '', 400

    # Check if the episode number is between 1 and <last_episode>
    if 1 > new_episode > media[0].eps_per_season[media[1].current_season -
                                                 1].episodes:
        return '', 400

    # Get the old data
    old_season = media[1].current_season
    old_episode = media[1].last_episode_watched
    old_watched = media[1].eps_watched

    # Set the new data
    new_watched = sum(
        [x.episodes
         for x in media[0].eps_per_season[:old_season - 1]]) + new_episode
    media[1].last_episode_watched = new_episode
    media[1].eps_watched = new_watched + (media[1].rewatched *
                                          media[0].total_episodes)
    app.logger.info(
        '[User {}] {} [ID {}] episode updated from {} to {}'.format(
            current_user.id, list_type.value.replace('list', ''), media_id,
            old_episode, new_episode))

    # Commit the changes
    db.session.commit()

    # Set the last updates
    set_last_update(media=media[0],
                    media_type=list_type,
                    old_season=old_season,
                    new_season=old_season,
                    old_episode=old_episode,
                    new_episode=new_episode)

    # Compute the new time spent
    compute_time_spent(media=media[0],
                       old_watched=old_watched,
                       new_watched=new_watched,
                       list_type=list_type)

    return '', 204
Esempio n. 23
0
def mymedialist(media_list,
                user_name,
                category=Status.WATCHING,
                genre='All',
                sorting='title-A-Z',
                page_val=1):
    # Check if the <user> can see the <media_list>
    user = current_user.check_autorization(user_name)

    # Check if <media_list> is valid
    try:
        list_type = ListType(media_list)
    except ValueError:
        abort(400)

    # Add views_count to the profile
    current_user.add_view_count(user, list_type)

    # Select <search> category if query is not none
    q = request.args.get('q')
    if q:
        category = Status.SEARCH

    # Check the sorting value
    try:
        sorting_bis = _SORTING[sorting]
    except KeyError:
        abort(400)

    # Recover the template
    html_template = 'medialist_tv.html'
    if list_type == ListType.SERIES:
        all_genres = _SERIES_GENRES
    elif list_type == ListType.ANIME:
        all_genres = _ANIME_GENRES
    elif list_type == ListType.MOVIES:
        all_genres = _MOVIES_GENRES
        if category == Status.WATCHING:
            category = Status.COMPLETED
        html_template = 'medialist_movies.html'

    # Retrieve the corresponding media_data
    query, category = get_media_query(user.id, list_type, category, genre,
                                      sorting, page_val, q)

    # Get the actual page, total number of pages and the total number of media from the query
    items = query.items
    info_pages = {
        'actual_page': query.page,
        'total_pages': query.pages,
        'total_media': query.total
    }

    # Get <common_media> and <total_media>
    common_media, total_media = get_media_count(user.id, list_type)

    try:
        percentage = int((len(common_media) / total_media) * 100)
    except ZeroDivisionError:
        percentage = 0
    common_elements = [len(common_media), total_media, percentage]

    # Recover the data to a dict
    items_data_list = []
    for item in items:
        add_data = MediaListDict(item, common_media,
                                 list_type).redirect_medialist()
        items_data_list.append(add_data)

    return render_template(html_template,
                           title="{}'s {}".format(user_name, media_list),
                           media_data=items_data_list,
                           common_elements=common_elements,
                           media_list=media_list,
                           username=user_name,
                           genre=genre,
                           user_id=str(user.id),
                           info_pages=info_pages,
                           category=category,
                           sorting=sorting,
                           page=page_val,
                           all_genres=all_genres,
                           sorting_bis=sorting_bis,
                           search_query=q)