contentdb/app/blueprints/users/profile.py

256 lines
8.3 KiB
Python
Raw Normal View History

2020-07-12 17:34:25 +02:00
# ContentDB
2021-01-30 17:59:42 +01:00
# Copyright (C) 2018-21 rubenwardy
2018-05-17 16:18:20 +02:00
#
# This program is free software: you can redistribute it and/or modify
2021-01-30 17:59:42 +01:00
# it under the terms of the GNU Affero General Public License as published by
2018-05-17 16:18:20 +02:00
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
2021-01-30 17:59:42 +01:00
# GNU Affero General Public License for more details.
2018-05-17 16:18:20 +02:00
#
2021-01-30 17:59:42 +01:00
# You should have received a copy of the GNU Affero General Public License
2018-05-17 16:18:20 +02:00
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import math
2021-08-18 23:09:41 +02:00
from typing import Optional
2018-05-17 16:18:20 +02:00
2018-03-18 19:05:53 +01:00
from flask import *
2021-07-26 00:41:34 +02:00
from flask_babel import gettext
from flask_login import current_user, login_required
2021-08-18 23:09:41 +02:00
from sqlalchemy import func
2020-12-04 03:23:04 +01:00
from app.models import *
from . import bp
from ...utils import get_daterange_options
2020-12-04 03:23:04 +01:00
2018-03-24 20:37:33 +01:00
@bp.route("/users/", methods=["GET"])
def list_all():
2020-07-12 21:59:06 +02:00
users = db.session.query(User, func.count(Package.id)) \
.select_from(User).outerjoin(Package) \
.order_by(db.desc(User.rank), db.asc(User.display_name)) \
.group_by(User.id).all()
2018-03-24 20:24:34 +01:00
return render_template("users/list.html", users=users)
2018-03-20 20:07:20 +01:00
2018-03-24 20:24:34 +01:00
2020-12-07 21:11:40 +01:00
@bp.route("/user/forum/<username>/")
def by_forums_username(username):
user = User.query.filter_by(forums_username=username).first()
if user:
return redirect(url_for("users.profile", username=user.username))
return render_template("users/forums_no_such_user.html", username=username)
2021-07-26 00:41:34 +02:00
class Medal:
description: str
color: Optional[str]
icon: str
title: Optional[str]
progress: Optional[Tuple[int, int]]
def __init__(self, description: str, **kwargs):
self.description = description
self.color = kwargs.get("color", "white")
self.icon = kwargs.get("icon", None)
self.title = kwargs.get("title", None)
self.progress = kwargs.get("progress", None)
@classmethod
def make_unlocked(cls, color: str, icon: str, title: str, description: str):
return Medal(description=description, color=color, icon=icon, title=title)
@classmethod
def make_locked(cls, description: str, progress: Tuple[int, int]):
2022-04-23 22:31:59 +02:00
if progress[0] is None or progress[1] is None:
raise Exception("Invalid progress")
2021-07-26 00:41:34 +02:00
return Medal(description=description, progress=progress)
def place_to_color(place: int) -> str:
if place == 1:
return "gold"
elif place == 2:
return "#888"
elif place == 3:
return "#cd7f32"
else:
2021-07-26 00:41:34 +02:00
return "white"
2021-07-26 00:41:34 +02:00
def get_user_medals(user: User) -> Tuple[List[Medal], List[Medal]]:
unlocked = []
locked = []
#
# REVIEWS
#
2021-08-18 23:09:41 +02:00
users_by_reviews = db.session.query(User.username, func.sum(PackageReview.score).label("karma")) \
2021-07-25 17:09:21 +02:00
.select_from(User).join(PackageReview) \
2021-08-18 23:09:41 +02:00
.group_by(User.username).order_by(text("karma DESC")).all()
try:
review_boundary = users_by_reviews[math.floor(len(users_by_reviews) * 0.25)][1] + 1
except IndexError:
review_boundary = None
2021-08-18 23:09:41 +02:00
usernames_by_reviews = [username for username, _ in users_by_reviews]
2021-07-25 17:09:21 +02:00
review_idx = None
review_percent = None
2021-08-18 23:09:41 +02:00
review_karma = 0
2021-07-25 17:09:21 +02:00
try:
2021-08-18 23:09:41 +02:00
review_idx = usernames_by_reviews.index(user.username)
2021-07-25 17:09:21 +02:00
review_percent = round(100 * review_idx / len(users_by_reviews), 1)
2021-08-18 23:09:41 +02:00
review_karma = max(users_by_reviews[review_idx][1], 0)
2021-07-25 17:09:21 +02:00
except ValueError:
pass
if review_percent is not None and review_percent < 25:
2021-07-26 00:41:34 +02:00
if review_idx == 0:
2021-08-18 23:09:41 +02:00
title = gettext(u"Top reviewer")
2021-07-26 00:41:34 +02:00
description = gettext(
2021-08-18 23:09:41 +02:00
u"%(display_name)s has written the most helpful reviews on ContentDB.",
2021-07-26 00:41:34 +02:00
display_name=user.display_name)
elif review_idx <= 2:
if review_idx == 1:
2021-08-18 23:09:41 +02:00
title = gettext(u"2nd most helpful reviewer")
2021-07-26 00:41:34 +02:00
else:
2021-08-18 23:09:41 +02:00
title = gettext(u"3rd most helpful reviewer")
2021-07-26 00:41:34 +02:00
description = gettext(
u"This puts %(display_name)s in the top %(perc)s%%",
display_name=user.display_name, perc=review_percent)
else:
title = gettext(u"Top %(perc)s%% reviewer", perc=review_percent)
2021-08-18 23:09:41 +02:00
description = gettext(u"Only %(place)d users have written more helpful reviews.", place=review_idx)
2021-07-26 00:41:34 +02:00
unlocked.append(Medal.make_unlocked(
place_to_color(review_idx + 1), "fa-star-half-alt", title, description))
2022-04-23 22:31:59 +02:00
elif review_boundary is not None:
2021-08-18 23:09:41 +02:00
description = gettext(u"Consider writing more helpful reviews to get a medal.")
2021-07-26 00:41:34 +02:00
if review_idx:
description += " " + gettext(u"You are in place %(place)s.", place=review_idx + 1)
locked.append(Medal.make_locked(
2021-08-18 23:09:41 +02:00
description, (review_karma, review_boundary)))
2021-07-26 00:41:34 +02:00
#
# TOP PACKAGES
#
2021-07-25 19:17:59 +02:00
all_package_ranks = db.session.query(
Package.type,
2021-07-25 19:17:59 +02:00
Package.author_id,
2021-07-26 00:41:34 +02:00
func.rank().over(
order_by=db.desc(Package.score),
partition_by=Package.type) \
.label("rank")).order_by(db.asc(text("rank"))) \
.filter_by(state=PackageState.APPROVED).subquery()
2021-07-25 19:17:59 +02:00
user_package_ranks = db.session.query(all_package_ranks) \
2021-07-26 00:41:34 +02:00
.filter_by(author_id=user.id) \
.filter(text("rank <= 30")) \
.all()
user_package_ranks = next(
(x for x in user_package_ranks if x[0] == PackageType.MOD or x[2] <= 10),
None)
if user_package_ranks:
2021-07-26 00:41:34 +02:00
top_rank = user_package_ranks[2]
top_type = PackageType.coerce(user_package_ranks[0])
2021-07-26 00:41:34 +02:00
if top_rank == 1:
2022-01-14 19:25:28 +01:00
title = gettext(u"Top %(type)s", type=top_type.text.lower())
2021-07-26 00:41:34 +02:00
else:
2022-01-14 19:25:28 +01:00
title = gettext(u"Top %(group)d %(type)s", group=top_rank, type=top_type.text.lower())
if top_type == PackageType.MOD:
icon = "fa-box"
elif top_type == PackageType.GAME:
icon = "fa-gamepad"
else:
icon = "fa-paint-brush"
2021-07-26 00:41:34 +02:00
description = gettext(u"%(display_name)s has a %(type)s placed at #%(place)d.",
2022-01-14 19:25:28 +01:00
display_name=user.display_name, type=top_type.text.lower(), place=top_rank)
2021-07-26 00:41:34 +02:00
unlocked.append(
Medal.make_unlocked(place_to_color(top_rank), icon, title, description))
2021-07-26 00:41:34 +02:00
#
# DOWNLOADS
#
total_downloads = db.session.query(func.sum(Package.downloads)) \
.select_from(User) \
.join(User.packages) \
.filter(User.id == user.id,
Package.state == PackageState.APPROVED).scalar()
if total_downloads is None:
pass
elif total_downloads < 50000:
description = gettext(u"Your packages have %(downloads)d downloads in total.", downloads=total_downloads)
description += " " + gettext(u"First medal is at 50k.")
locked.append(Medal.make_locked(description, (total_downloads, 50000)))
else:
if total_downloads >= 300000:
place = 1
title = gettext(u">300k downloads")
elif total_downloads >= 100000:
place = 2
title = gettext(u">100k downloads")
elif total_downloads >= 75000:
place = 3
title = gettext(u">75k downloads")
else:
place = 10
title = gettext(u">50k downloads")
description = gettext(u"Has received %(downloads)d downloads across all packages.",
display_name=user.display_name, downloads=total_downloads)
unlocked.append(Medal.make_unlocked(place_to_color(place), "fa-users", title, description))
return unlocked, locked
@bp.route("/users/<username>/")
def profile(username):
user = User.query.filter_by(username=username).first()
if not user:
abort(404)
if not current_user.is_authenticated or (user != current_user and not current_user.canAccessTodoList()):
packages = user.packages.filter_by(state=PackageState.APPROVED)
maintained_packages = user.maintained_packages.filter_by(state=PackageState.APPROVED)
else:
packages = user.packages.filter(Package.state != PackageState.DELETED)
maintained_packages = user.maintained_packages.filter(Package.state != PackageState.DELETED)
packages = packages.order_by(db.asc(Package.title)).all()
maintained_packages = maintained_packages \
.filter(Package.author != user) \
.order_by(db.asc(Package.title)).all()
2021-07-25 19:17:59 +02:00
2021-07-26 00:41:34 +02:00
unlocked, locked = get_user_medals(user)
2018-03-18 19:05:53 +01:00
# Process GET or invalid POST
return render_template("users/profile.html", user=user,
packages=packages, maintained_packages=maintained_packages,
2021-07-26 00:41:34 +02:00
medals_unlocked=unlocked, medals_locked=locked)
2020-12-05 02:20:00 +01:00
2022-11-09 21:52:31 +01:00
@bp.route("/user/stats/")
@login_required
def statistics_redirect():
return redirect(url_for("users.statistics", username=current_user.username))
2022-11-09 19:47:44 +01:00
@bp.route("/users/<username>/stats/")
def statistics(username):
user = User.query.filter_by(username=username).first()
if user is None:
abort(404)
downloads = db.session.query(func.sum(Package.downloads)).filter(Package.author==user).one()
start = request.args.get("start")
end = request.args.get("end")
return render_template("users/stats.html", user=user, downloads=downloads[0],
start=start, end=end, options=get_daterange_options(), noindex=start or end)