niming_backend/utils/misc.py

42 lines
1.2 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-12 11:30:51 +08:00
def internal_json2protobuf(original:dict) -> bytes:
otype = original["type"]
if otype == 'a':
rtype = niming_pb2.FetchPostResponse
elif otype == 'c':
rtype = niming_pb2.FetchCommentResponse
original = original["data"]
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"])
elif otype == "c":
ob = rtype.Message(sha1=o["sha1"])
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()