59 lines
1.7 KiB
Python
59 lines
1.7 KiB
Python
|
|
from __future__ import annotations
|
||
|
|
|
||
|
|
import base64
|
||
|
|
|
||
|
|
|
||
|
|
class WeChatBase64Adapter:
|
||
|
|
@staticmethod
|
||
|
|
def encode_image(data: bytes) -> str:
|
||
|
|
return base64.b64encode(data).decode("ascii")
|
||
|
|
|
||
|
|
@staticmethod
|
||
|
|
def decode_image(data_url: str) -> bytes:
|
||
|
|
if data_url.startswith("data:"):
|
||
|
|
_, b64 = data_url.split(",", 1)
|
||
|
|
return base64.b64decode(b64)
|
||
|
|
return base64.b64decode(data_url)
|
||
|
|
|
||
|
|
@staticmethod
|
||
|
|
def build_image_data_url(mime_type: str, data: bytes) -> str:
|
||
|
|
return f"data:{mime_type};base64,{base64.b64encode(data).decode('ascii')}"
|
||
|
|
|
||
|
|
@staticmethod
|
||
|
|
def encode_voice(data: bytes) -> str:
|
||
|
|
return base64.b64encode(data).decode("ascii")
|
||
|
|
|
||
|
|
@staticmethod
|
||
|
|
def encode_video(data: bytes) -> str:
|
||
|
|
return base64.b64encode(data).decode("ascii")
|
||
|
|
|
||
|
|
@staticmethod
|
||
|
|
def decode_media(b64_data: str) -> bytes:
|
||
|
|
return base64.b64decode(b64_data)
|
||
|
|
|
||
|
|
@staticmethod
|
||
|
|
def get_media_mime_type(media_type: str) -> str:
|
||
|
|
mime_map = {
|
||
|
|
"image": "image/png",
|
||
|
|
"voice": "audio/amr",
|
||
|
|
"video": "video/mp4",
|
||
|
|
"file": "application/octet-stream",
|
||
|
|
}
|
||
|
|
return mime_map.get(media_type, "application/octet-stream")
|
||
|
|
|
||
|
|
@staticmethod
|
||
|
|
def encode_file(data: bytes) -> str:
|
||
|
|
return base64.b64encode(data).decode("ascii")
|
||
|
|
|
||
|
|
@staticmethod
|
||
|
|
def decode_file(b64_data: str) -> bytes:
|
||
|
|
return base64.b64decode(b64_data)
|
||
|
|
|
||
|
|
@staticmethod
|
||
|
|
def encode_text(text: str) -> str:
|
||
|
|
return base64.b64encode(text.encode("utf-8")).decode("ascii")
|
||
|
|
|
||
|
|
@staticmethod
|
||
|
|
def decode_text(b64_data: str) -> str:
|
||
|
|
return base64.b64decode(b64_data).decode("utf-8")
|