110 lines
4.0 KiB
Python
110 lines
4.0 KiB
Python
import hashlib
|
|
import io
|
|
import os
|
|
import unicodedata
|
|
import uuid
|
|
|
|
import boto3
|
|
from botocore.exceptions import ClientError
|
|
from fastapi import HTTPException, Request, Response
|
|
from fastapi.responses import JSONResponse
|
|
from PIL import Image, UnidentifiedImageError
|
|
from psycopg.types.json import Jsonb
|
|
from store import db, entity, stamp
|
|
|
|
bucket = "messenger"
|
|
s3 = boto3.client("s3",endpoint_url=os.environ["S3_ENDPOINT"],region_name="us-east-1")
|
|
queued = int(os.environ["LAB"]) >= 5
|
|
|
|
|
|
def ensure_bucket():
|
|
try:
|
|
s3.head_bucket(Bucket=bucket)
|
|
except ClientError as exc:
|
|
if exc.response["ResponseMetadata"]["HTTPStatusCode"] != 404:
|
|
raise
|
|
try:
|
|
s3.create_bucket(Bucket=bucket)
|
|
except ClientError as race:
|
|
if race.response["Error"]["Code"] != "BucketAlreadyOwnedByYou":
|
|
raise
|
|
|
|
|
|
def install_media(app, actor, store):
|
|
def owner(request):
|
|
user = actor(request)
|
|
if not user:
|
|
raise HTTPException(401)
|
|
return user["id"]
|
|
|
|
def permitted(chat, user):
|
|
try:
|
|
uuid.UUID(chat)
|
|
except ValueError:
|
|
raise HTTPException(400)
|
|
if not store.member_chat(chat,user):
|
|
raise HTTPException(404)
|
|
|
|
def metadata(att,request):
|
|
user = owner(request)
|
|
with db() as c:
|
|
row = c.execute("select doc from attachments where id=%s",(att,)).fetchone()
|
|
if not row:
|
|
raise HTTPException(404)
|
|
permitted(row[0]["chat_id"],user)
|
|
return row[0]
|
|
|
|
@app.post("/api/v1/chats/{chat}/attachments")
|
|
async def upload(chat:str,request:Request):
|
|
user = owner(request)
|
|
permitted(chat,user)
|
|
name = request.query_params.get("filename","")
|
|
if not 1<=len(name)<=255 or not name.strip() or any(ch in "/\\" or unicodedata.category(ch)=="Cc" for ch in name):
|
|
raise HTTPException(400)
|
|
data = bytearray()
|
|
async for part in request.stream():
|
|
if len(data)+len(part)>10485760:
|
|
raise HTTPException(413)
|
|
data.extend(part)
|
|
mime = request.headers.get("content-type","").split(";")[0]
|
|
try:
|
|
with Image.open(io.BytesIO(data)) as img:
|
|
if img.width*img.height>40000000:
|
|
raise HTTPException(413)
|
|
if mime not in ("image/png","image/jpeg") or Image.MIME.get(img.format)!=mime:
|
|
raise HTTPException(415)
|
|
img.verify()
|
|
with Image.open(io.BytesIO(data)) as img:
|
|
img.load()
|
|
except Image.DecompressionBombError:
|
|
raise HTTPException(413)
|
|
except (UnidentifiedImageError,OSError,ValueError,SyntaxError):
|
|
raise HTTPException(415)
|
|
doc = entity(chat_id=chat,owner_id=user,filename=name,content_type=mime,size_bytes=len(data),
|
|
sha256=hashlib.sha256(data).hexdigest(),status="queued" if queued else "ready",
|
|
variants=[],error_code=None,updated_at=stamp())
|
|
ensure_bucket()
|
|
s3.put_object(Bucket=bucket,Key=doc["id"],Body=bytes(data),ContentType=mime)
|
|
with db() as c:
|
|
c.execute("insert into attachments(id,chat,owner,doc) values(%s,%s,%s,%s)",(doc["id"],chat,user,Jsonb(doc)))
|
|
return JSONResponse(doc,status_code=202 if queued else 201)
|
|
|
|
@app.get("/api/v1/attachments/{att}")
|
|
def details(att:str,request:Request):
|
|
return metadata(att,request)
|
|
|
|
@app.get("/api/v1/attachments/{att}/content")
|
|
def download(att:str,request:Request,variant:str="original"):
|
|
doc = metadata(att,request)
|
|
if doc["status"]!="ready":
|
|
raise HTTPException(409)
|
|
key = att
|
|
mime = doc["content_type"]
|
|
if variant!="original":
|
|
item = next((v for v in doc["variants"] if v["name"]==variant),None)
|
|
if not item:
|
|
raise HTTPException(404)
|
|
key = att+"/"+variant
|
|
mime = item["content_type"]
|
|
return Response(s3.get_object(Bucket=bucket,Key=key)["Body"].read(),media_type=mime)
|