niming_backend/utils/misc.py

50 lines
1.6 KiB
Python
Raw Normal View History

2024-11-19 21:22:01 +08:00
from flask import jsonify, Response
2024-11-25 21:51:50 +08:00
from protobuf_files import niming_pb2
2024-11-19 21:22:01 +08:00
def error(message:str) -> Response:
2024-11-25 21:51:50 +08:00
return jsonify({"error":message})
2024-12-09 03:24:22 +08:00
def error_proto(message:str) -> bytes:
return niming_pb2.PostResponse(
status = niming_pb2.Status.Failed,
failed_message = message
).SerializeToString()
2024-12-17 01:08:35 +08:00
def internal_json2protobuf(role:str, otype:str, original:list) -> bytes:
2024-12-12 11:30:51 +08:00
if otype == 'a':
2024-12-17 01:08:35 +08:00
if role == "admin": rtype = niming_pb2.AdminFetchPostResponse
else: rtype = niming_pb2.FetchPostResponse
2024-12-12 11:30:51 +08:00
elif otype == 'c':
2024-12-17 01:08:35 +08:00
if role == "admin": rtype = niming_pb2.AdminFetchCommentResponse
else: rtype = niming_pb2.FetchCommentResponse
2024-12-12 11:30:51 +08:00
res = rtype()
2024-11-25 21:51:50 +08:00
for o in original:
2024-12-09 03:24:22 +08:00
# drop null object
2024-12-12 11:30:51 +08:00
o = {k:v for k, v in o.items() if v is not None}
2024-12-09 03:24:22 +08:00
2024-12-12 11:30:51 +08:00
if otype == "a":
ob = rtype.Message(id=o["id"])
if "igid" in o: ob.igid = o["igid"]
if "files_hash" in o: ob.files_hash.extend(o["files_hash"])
if "comments_hash" in o: ob.comments_hash.extend(o["comments_hash"])
2024-12-17 01:08:35 +08:00
# admin
if "mark" in o: ob.mark = o["mark"]
if "hash" in o: ob.hash = o["hash"]
if "ip" in o: ob.ip = o["ip"]
2024-12-12 11:30:51 +08:00
elif otype == "c":
ob = rtype.Message(sha1=o["sha1"])
2024-12-17 01:08:35 +08:00
# admin
if "mark" in o: ob.mark = o["mark"]
if "ip" in o: ob.ip = o["ip"]
if "hash" in o: ob.hash = o["hash"]
2024-12-12 11:30:51 +08:00
ob.content = o["content"]
2024-12-09 03:24:22 +08:00
2024-11-25 21:51:50 +08:00
res.posts.append(ob)
return res.SerializeToString()