Files
cookie/backend/routes/notifications.py
T

103 lines
2.8 KiB
Python

"""
通知管理路由
"""
import requests
from flask import Blueprint, request, jsonify
from models.database import db, Notification, User
from datetime import datetime
notification_bp = Blueprint('notifications', __name__)
@notification_bp.route('/', methods=['GET'])
def get_notifications():
"""获取通知列表"""
user_id = request.args.get('user_id')
if user_id:
notifications = Notification.query.filter_by(user_id=user_id).order_by(Notification.created_at.desc()).all()
else:
notifications = Notification.query.order_by(Notification.created_at.desc()).all()
return jsonify([notification.to_dict() for notification in notifications])
@notification_bp.route('/', methods=['POST'])
def send_notification():
"""发送通知"""
data = request.json
user_id = data.get('user_id')
website_id = data.get('website_id')
title = data.get('title')
content = data.get('content')
# 获取用户的爱语飞飞令牌
user = User.query.get_or_404(user_id)
if not user.iyuu_token:
return jsonify({'message': '用户未配置爱语飞飞令牌'}), 400
# 发送爱语飞飞通知
send_success = _send_iyuu_notification(user.iyuu_token, title, content)
# 创建通知记录
notification = Notification(
user_id=user_id,
website_id=website_id,
title=title,
content=content,
status='sent' if send_success else 'failed',
send_time=datetime.utcnow() if send_success else None
)
db.session.add(notification)
db.session.commit()
return jsonify(notification.to_dict()), 201
def _send_iyuu_notification(token, title, content):
"""通过爱语飞飞发送通知"""
try:
url = f"https://iyuu.cn/{token}.send"
response = requests.post(
url,
json={
'text': title,
'desp': content
},
timeout=10
)
response.raise_for_status()
result = response.json()
if result.get('errcode') == 0:
return True
else:
return False
except requests.RequestException:
return False
except Exception:
return False
# 为Notification模型添加to_dict方法
def notification_to_dict(self):
return {
'id': self.id,
'user_id': self.user_id,
'website_id': self.website_id,
'title': self.title,
'content': self.content,
'status': self.status,
'send_time': self.send_time.isoformat() if self.send_time else None,
'created_at': self.created_at.isoformat() if self.created_at else None,
'updated_at': self.updated_at.isoformat() if self.updated_at else None
}
Notification.to_dict = notification_to_dict