contentdb/app/blueprints/packages/reviews.py

277 lines
9.1 KiB
Python
Raw Normal View History

2020-07-12 17:34:25 +02:00
# ContentDB
2020-07-09 05:10:09 +02:00
# Copyright (C) 2020 rubenwardy
#
# 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
2020-07-09 05:10:09 +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.
2020-07-09 05:10:09 +02:00
#
2021-01-30 17:59:42 +01:00
# You should have received a copy of the GNU Affero General Public License
2020-07-09 05:10:09 +02:00
# along with this program. If not, see <https://www.gnu.org/licenses/>.
2023-06-19 20:32:36 +02:00
2022-01-01 23:17:39 +01:00
from collections import namedtuple
2020-07-09 05:10:09 +02:00
import typing
from flask import render_template, request, redirect, flash, url_for, abort, jsonify
2024-06-08 12:12:42 +02:00
from flask_babel import gettext, lazy_gettext, get_locale
from flask_login import current_user, login_required
2020-07-09 05:10:09 +02:00
from flask_wtf import FlaskForm
2023-06-19 20:32:36 +02:00
from wtforms import StringField, TextAreaField, SubmitField, RadioField
2024-06-08 12:12:42 +02:00
from wtforms.validators import InputRequired, Length, DataRequired
from wtforms_sqlalchemy.fields import QuerySelectField
2023-06-19 20:32:36 +02:00
from app.models import db, PackageReview, Thread, ThreadReply, NotificationType, PackageReviewVote, Package, UserRank, \
2024-06-08 12:12:42 +02:00
Permission, AuditSeverity, PackageState, Language
2023-06-19 20:32:36 +02:00
from app.tasks.webhooktasks import post_discord_webhook
2023-06-19 22:27:49 +02:00
from app.utils import is_package_page, add_notification, get_int_or_abort, is_yes, is_safe_url, rank_required, \
add_audit_log, has_blocked_domains, should_return_json, normalize_line_endings
2023-06-19 20:32:36 +02:00
from . import bp
2020-07-09 05:10:09 +02:00
2020-07-10 21:30:31 +02:00
@bp.route("/reviews/")
def list_reviews():
2020-12-04 00:41:11 +01:00
page = get_int_or_abort(request.args.get("page"), 1)
num = min(40, get_int_or_abort(request.args.get("n"), 100))
2023-04-23 22:49:53 +02:00
pagination = PackageReview.query.order_by(db.desc(PackageReview.created_at)).paginate(page=page, per_page=num)
2020-12-04 00:41:11 +01:00
return render_template("packages/reviews_list.html", pagination=pagination, reviews=pagination.items)
2020-07-10 21:30:31 +02:00
2024-06-08 12:12:42 +02:00
def get_default_language():
locale = get_locale()
if locale:
return Language.query.filter_by(id=locale.language).first()
return None
2020-07-09 05:10:09 +02:00
class ReviewForm(FlaskForm):
2023-08-06 21:55:55 +02:00
title = StringField(lazy_gettext("Title"), [InputRequired(), Length(3, 100)])
2024-06-08 12:12:42 +02:00
language = QuerySelectField(lazy_gettext("Language"), [DataRequired()],
allow_blank=True,
query_factory=lambda: Language.query.order_by(db.asc(Language.title)),
get_pk=lambda a: a.id,
get_label=lambda a: a.title,
default=get_default_language)
comment = TextAreaField(lazy_gettext("Comment"), [InputRequired(), Length(10, 2000)], filters=[normalize_line_endings])
2023-04-15 03:37:58 +02:00
rating = RadioField(lazy_gettext("Rating"), [InputRequired()],
choices=[("5", lazy_gettext("Yes")), ("3", lazy_gettext("Neutral")), ("1", lazy_gettext("No"))])
btn_submit = SubmitField(lazy_gettext("Save"))
2020-07-09 05:10:09 +02:00
2023-04-15 03:37:58 +02:00
2020-07-09 05:10:09 +02:00
@bp.route("/packages/<author>/<name>/review/", methods=["GET", "POST"])
@login_required
@is_package_page
def review(package):
if current_user in package.maintainers:
2022-01-07 22:46:16 +01:00
flash(gettext("You can't review your own package!"), "danger")
return redirect(package.get_url("packages.view"))
2023-01-02 16:51:19 +01:00
if package.state != PackageState.APPROVED:
abort(404)
2020-07-09 05:10:09 +02:00
review = PackageReview.query.filter_by(package=package, author=current_user).first()
can_review = review is not None or current_user.can_review_ratelimit()
2022-05-09 13:40:01 +02:00
if not can_review:
flash(gettext("You've reviewed too many packages recently. Please wait before trying again, and consider making your reviews more detailed"), "danger")
2020-07-09 05:10:09 +02:00
form = ReviewForm(formdata=request.form, obj=review)
# Set default values
if request.method == "GET" and review:
form.title.data = review.thread.title
2023-04-15 03:37:58 +02:00
form.rating.data = str(review.rating)
form.comment.data = review.thread.first_reply.comment
2020-07-09 05:10:09 +02:00
# Validate and submit
2022-05-09 13:40:01 +02:00
elif can_review and form.validate_on_submit():
if has_blocked_domains(form.comment.data, current_user.username, f"review of {package.get_id()}"):
2023-01-12 17:43:08 +01:00
flash(gettext("Linking to blocked sites is not allowed"), "danger")
2020-07-09 05:10:09 +02:00
else:
2023-01-03 13:17:01 +01:00
was_new = False
if not review:
was_new = True
review = PackageReview()
review.package = package
review.author = current_user
db.session.add(review)
2020-07-09 05:10:09 +02:00
2023-04-15 03:37:58 +02:00
review.rating = int(form.rating.data)
2024-06-08 12:12:42 +02:00
review.language = form.language.data
2020-07-09 05:10:09 +02:00
2023-01-03 13:17:01 +01:00
thread = review.thread
if not thread:
thread = Thread()
thread.author = current_user
thread.private = False
thread.package = package
thread.review = review
db.session.add(thread)
2020-07-09 05:10:09 +02:00
2023-01-03 13:17:01 +01:00
thread.watchers.append(current_user)
2020-07-09 05:32:13 +02:00
2023-01-03 13:17:01 +01:00
reply = ThreadReply()
reply.thread = thread
reply.author = current_user
reply.comment = form.comment.data
db.session.add(reply)
2020-07-09 05:10:09 +02:00
2023-01-03 13:17:01 +01:00
thread.replies.append(reply)
else:
reply = thread.first_reply
reply.comment = form.comment.data
2020-07-09 05:10:09 +02:00
2023-01-03 13:17:01 +01:00
thread.title = form.title.data
2021-08-17 22:16:43 +02:00
2023-01-03 13:17:01 +01:00
db.session.commit()
2020-07-09 05:10:09 +02:00
package.recalculate_score()
2023-01-03 13:17:01 +01:00
if was_new:
notif_msg = "New review '{}'".format(form.title.data)
type = NotificationType.NEW_REVIEW
else:
notif_msg = "Updated review '{}'".format(form.title.data)
type = NotificationType.OTHER
2023-06-19 22:27:49 +02:00
add_notification(package.maintainers, current_user, type, notif_msg,
url_for("threads.view", id=thread.id), package)
2023-01-03 13:17:01 +01:00
if was_new:
2024-06-09 12:50:21 +02:00
msg = f"Reviewed {package.title} ({review.language.title}): {thread.get_view_url(absolute=True)}"
post_discord_webhook.delay(thread.author.display_name, msg, False)
2023-01-03 13:17:01 +01:00
db.session.commit()
return redirect(package.get_url("packages.view"))
2020-07-09 05:10:09 +02:00
2020-12-04 03:23:04 +01:00
return render_template("packages/review_create_edit.html",
2020-07-10 20:26:37 +02:00
form=form, package=package, review=review)
@bp.route("/packages/<author>/<name>/reviews/<reviewer>/delete/", methods=["POST"])
2020-07-10 20:26:37 +02:00
@login_required
@is_package_page
def delete_review(package, reviewer):
review = PackageReview.query \
.filter(PackageReview.package == package, PackageReview.author.has(username=reviewer)) \
.first()
2020-07-10 20:26:37 +02:00
if review is None or review.package != package:
abort(404)
if not review.check_perm(current_user, Permission.DELETE_REVIEW):
abort(403)
2020-07-10 20:26:37 +02:00
thread = review.thread
reply = ThreadReply()
reply.thread = thread
reply.author = current_user
reply.comment = "_converted review into a thread_"
2022-04-23 21:53:38 +02:00
reply.is_status_update = True
2020-07-10 20:26:37 +02:00
db.session.add(reply)
thread.review = None
msg = "Converted review by {} to thread".format(review.author.display_name)
2023-06-19 22:27:49 +02:00
add_audit_log(AuditSeverity.MODERATION if current_user.username != reviewer else AuditSeverity.NORMAL,
current_user, msg, thread.get_view_url(), thread.package)
notif_msg = "Deleted review '{}', comments were kept as a thread".format(thread.title)
2023-06-19 22:27:49 +02:00
add_notification(package.maintainers, current_user, NotificationType.OTHER, notif_msg, url_for("threads.view", id=thread.id), package)
2020-07-10 20:26:37 +02:00
db.session.delete(review)
2022-02-09 20:11:31 +01:00
package.recalculate_score()
2022-02-09 20:11:31 +01:00
2020-07-10 20:26:37 +02:00
db.session.commit()
return redirect(thread.get_view_url())
2021-08-18 23:09:41 +02:00
def handle_review_vote(package: Package, review_id: int) -> typing.Optional[str]:
2021-08-18 23:09:41 +02:00
if current_user in package.maintainers:
return gettext("You can't vote on the reviews on your own package!")
2021-08-18 23:09:41 +02:00
review: PackageReview = PackageReview.query.get(review_id)
if review is None or review.package != package:
abort(404)
if review.author == current_user:
return gettext("You can't vote on your own reviews!")
2021-08-18 23:09:41 +02:00
2023-06-19 22:27:49 +02:00
is_positive = is_yes(request.form["is_positive"])
2021-08-19 14:45:32 +02:00
2021-08-18 23:09:41 +02:00
vote = PackageReviewVote.query.filter_by(review=review, user=current_user).first()
if vote is None:
vote = PackageReviewVote()
vote.review = review
vote.user = current_user
2021-08-19 14:45:32 +02:00
vote.is_positive = is_positive
2021-08-18 23:09:41 +02:00
db.session.add(vote)
2021-08-19 14:45:32 +02:00
elif vote.is_positive == is_positive:
db.session.delete(vote)
2021-08-18 23:09:41 +02:00
else:
2021-08-19 14:45:32 +02:00
vote.is_positive = is_positive
2021-08-18 23:09:41 +02:00
review.update_score()
db.session.commit()
@bp.route("/packages/<author>/<name>/review/<int:review_id>/", methods=["POST"])
@login_required
@is_package_page
def review_vote(package, review_id):
msg = handle_review_vote(package, review_id)
if should_return_json():
if msg:
return jsonify({"success": False, "error": msg}), 403
else:
return jsonify({"success": True})
if msg:
flash(msg, "danger")
2021-08-18 23:09:41 +02:00
next_url = request.args.get("r")
if next_url and is_safe_url(next_url):
return redirect(next_url)
else:
return redirect(review.thread.get_view_url())
2022-01-01 23:17:39 +01:00
@bp.route("/packages/<author>/<name>/review-votes/")
@rank_required(UserRank.ADMIN)
@is_package_page
def review_votes(package):
user_biases = {}
for review in package.reviews:
review_sign = review.as_weight()
2022-01-01 23:17:39 +01:00
for vote in review.votes:
user_biases[vote.user.username] = user_biases.get(vote.user.username, [0, 0])
vote_sign = 1 if vote.is_positive else -1
vote_bias = review_sign * vote_sign
if vote_bias == 1:
user_biases[vote.user.username][0] += 1
else:
user_biases[vote.user.username][1] += 1
2023-11-19 14:49:36 +01:00
reviews = package.reviews.all()
2022-01-01 23:17:39 +01:00
BiasInfo = namedtuple("BiasInfo", "username balance with_ against no_vote perc_with")
user_biases_info = []
for username, bias in user_biases.items():
total_votes = bias[0] + bias[1]
balance = bias[0] - bias[1]
perc_with = round((100 * bias[0]) / total_votes)
2023-11-19 14:49:36 +01:00
user_biases_info.append(BiasInfo(username, balance, bias[0], bias[1], len(reviews) - total_votes, perc_with))
2022-01-01 23:17:39 +01:00
user_biases_info.sort(key=lambda x: -abs(x.balance))
2023-11-19 14:49:36 +01:00
return render_template("packages/review_votes.html", package=package, reviews=reviews,
user_biases=user_biases_info)