2020-05-23 18:53:29 +02:00
|
|
|
from flask import g
|
|
|
|
from flask import jsonify
|
|
|
|
from flask import request
|
|
|
|
|
|
|
|
from app.api.base import api_bp, require_api_auth
|
|
|
|
from app.config import PAGE_LIMIT
|
2021-10-12 14:36:47 +02:00
|
|
|
from app.db import Session
|
2020-05-23 18:53:29 +02:00
|
|
|
from app.models import Notification
|
|
|
|
|
|
|
|
|
|
|
|
@api_bp.route("/notifications", methods=["GET"])
|
|
|
|
@require_api_auth
|
|
|
|
def get_notifications():
|
|
|
|
"""
|
|
|
|
Get notifications
|
|
|
|
|
|
|
|
Input:
|
|
|
|
- page: in url. Starts at 0
|
|
|
|
|
2020-05-23 22:51:00 +02:00
|
|
|
Output:
|
|
|
|
- more: boolean. Whether there's more notification to load
|
|
|
|
- notifications: list of notifications.
|
|
|
|
- id
|
|
|
|
- message
|
|
|
|
- read
|
|
|
|
- created_at
|
2020-05-23 18:53:29 +02:00
|
|
|
"""
|
|
|
|
user = g.user
|
|
|
|
try:
|
|
|
|
page = int(request.args.get("page"))
|
|
|
|
except (ValueError, TypeError):
|
|
|
|
return jsonify(error="page must be provided in request query"), 400
|
|
|
|
|
|
|
|
notifications = (
|
2021-10-12 14:36:47 +02:00
|
|
|
Notification.filter_by(user_id=user.id)
|
2020-05-23 18:53:29 +02:00
|
|
|
.order_by(Notification.read, Notification.created_at.desc())
|
2020-05-23 22:51:00 +02:00
|
|
|
.limit(PAGE_LIMIT + 1) # load a record more to know whether there's more
|
2020-05-23 18:53:29 +02:00
|
|
|
.offset(page * PAGE_LIMIT)
|
|
|
|
.all()
|
|
|
|
)
|
|
|
|
|
2020-05-23 22:51:00 +02:00
|
|
|
have_more = len(notifications) > PAGE_LIMIT
|
|
|
|
|
2020-05-23 18:53:29 +02:00
|
|
|
return (
|
|
|
|
jsonify(
|
2020-05-23 22:51:00 +02:00
|
|
|
more=have_more,
|
|
|
|
notifications=[
|
2020-05-23 18:53:29 +02:00
|
|
|
{
|
|
|
|
"id": notification.id,
|
|
|
|
"message": notification.message,
|
|
|
|
"read": notification.read,
|
|
|
|
"created_at": notification.created_at.humanize(),
|
|
|
|
}
|
2020-05-23 22:51:00 +02:00
|
|
|
for notification in notifications[:PAGE_LIMIT]
|
|
|
|
],
|
2020-05-23 18:53:29 +02:00
|
|
|
),
|
|
|
|
200,
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
@api_bp.route("/notifications/<notification_id>/read", methods=["POST"])
|
|
|
|
@require_api_auth
|
|
|
|
def mark_as_read(notification_id):
|
|
|
|
"""
|
|
|
|
Mark a notification as read
|
|
|
|
Input:
|
|
|
|
notification_id: in url
|
|
|
|
Output:
|
|
|
|
200 if updated successfully
|
|
|
|
|
|
|
|
"""
|
|
|
|
user = g.user
|
|
|
|
notification = Notification.get(notification_id)
|
|
|
|
|
|
|
|
if not notification or notification.user_id != user.id:
|
|
|
|
return jsonify(error="Forbidden"), 403
|
|
|
|
|
|
|
|
notification.read = True
|
2021-10-12 14:36:47 +02:00
|
|
|
Session.commit()
|
2020-05-23 18:53:29 +02:00
|
|
|
|
|
|
|
return jsonify(done=True), 200
|