niming_backend/utils/misc.py
2024-12-12 03:30:51 +00:00

42 lines
1.2 KiB
Python

from flask import jsonify, Response
from protobuf_files import niming_pb2
def error(message:str) -> Response:
return jsonify({"error":message})
def error_proto(message:str) -> bytes:
return niming_pb2.PostResponse(
status = niming_pb2.Status.Failed,
failed_message = message
).SerializeToString()
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()
for o in original:
# drop null object
o = {k:v for k, v in o.items() if v is not None}
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"]
res.posts.append(ob)
return res.SerializeToString()