[lint] main.py
All checks were successful
ci/woodpecker/push/lint Pipeline was successful
ci/woodpecker/push/test Pipeline was successful

This commit is contained in:
SouthFox 2023-07-29 18:22:16 +08:00
parent 49a191ef72
commit 64278302fa

View file

@ -1,21 +1,20 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import logging """Some application path."""
from typing import Any
import sys import sys
import fastapi import fastapi
import httpx
import json
from fastapi import FastAPI from fastapi import FastAPI
from fastapi import Depends from fastapi import Depends
from fastapi import Request from fastapi import Request
from fastapi import Response from fastapi import Response
from fastapi.exceptions import HTTPException from fastapi.exceptions import HTTPException
from sqlalchemy.util import monkeypatch_proxied_specials
from starlette.responses import JSONResponse from starlette.responses import JSONResponse
from typing import Any
from loguru import logger from loguru import logger
from sqlalchemy import select
from app import models
from app.utils import precheck from app.utils import precheck
from app.database import get_db_session from app.database import get_db_session
from app.config import DEBUG from app.config import DEBUG
@ -26,11 +25,11 @@ from app.config import ID
from app.config import USERNAME from app.config import USERNAME
from app.config import VERSION from app.config import VERSION
from app.database import AsyncSession from app.database import AsyncSession
from app.database import get_db_session
from app.boxes import save_incoming from app.boxes import save_incoming
from app.activitypub import VisibilityEnum
from app.boxes import _send_create
from app.orgpython import to_html
from sqlalchemy import select
from app import models
def _check_0rtt_early_data(request: Request) -> None: def _check_0rtt_early_data(request: Request) -> None:
@ -46,18 +45,20 @@ logger.remove()
logger.add(sys.stdout, level="DEBUG" if DEBUG else "INFO") logger.add(sys.stdout, level="DEBUG" if DEBUG else "INFO")
logger.add("output.log", level="DEBUG") logger.add("output.log", level="DEBUG")
class ActivityPubResponse(JSONResponse): class ActivityPubResponse(JSONResponse): #pylint: disable=too-few-public-methods
"""Simple wrap JSONresponse return ActivityPub response."""
media_type = "application/activity+json" media_type = "application/activity+json"
def is_ap_requested(req: Request) -> bool: def is_ap_requested(req: Request) -> bool:
"""Check resquest is ActivityPub request."""
accept_value = req.headers.get("accept") accept_value = req.headers.get("accept")
if not accept_value: if not accept_value:
return False return False
for i in { for i in [
"application/activity+json", "application/activity+json",
"application/ld+json", "application/ld+json",
}: ]:
if accept_value.startswith(i): if accept_value.startswith(i):
return True return True
@ -68,51 +69,54 @@ def is_ap_requested(req: Request) -> bool:
async def index( async def index(
request: Request request: Request
): ):
"""Return index page."""
if is_ap_requested(request): if is_ap_requested(request):
return ActivityPubResponse(ME) return ActivityPubResponse(ME)
return ME return ME
@app.post("/inbox") @app.post("/inbox")
async def inbox( async def inbox(
request: Request, request: Request,
db_session: AsyncSession = Depends(get_db_session), db_session: AsyncSession = Depends(get_db_session),
httpsig_checker = Depends(precheck.inbox_prechecker), httpsig_checker = Depends(precheck.inbox_prechecker),
) -> Response: ) -> Response:
"""ActivityPub inbox endpoint."""
payload = await request.json() payload = await request.json()
if httpsig_checker: if not httpsig_checker:
if await save_incoming(db_session, payload):
return Response(status_code=202)
else:
return Response(
status_code=406,
content="invalid activitypub object"
)
else:
return Response( return Response(
status_code=406, status_code=406,
content="invalid http-sig" content="invalid http-sig"
) )
if not await save_incoming(db_session, payload):
return Response(
status_code=406,
content="invalid activitypub object"
)
return Response(status_code=202)
@app.post("/outbox") @app.post("/outbox")
async def outbox( async def outbox(
request: Request, request: Request,
db_session: AsyncSession = Depends(get_db_session), db_session: AsyncSession = Depends(get_db_session),
) -> Response: ) -> Response:
"""ActivityPub outbox endpoint, now only process client post request."""
payload = await request.body() payload = await request.body()
content = payload.decode("utf-8") content = payload.decode("utf-8")
logger.info(content) logger.info(content)
post_token = request.headers.get("Authorization") post_token = request.headers.get("Authorization")
if POST_TOKEN is not None \ if POST_TOKEN is None \
and POST_TOKEN == post_token.split(" ")[1]: # type: ignore and POST_TOKEN != post_token.split(" ")[1]: # type: ignore
logger.info("True token") logger.warning("Non-valid post token!")
return Response(status_code=406)
from app.activitypub import VisibilityEnum logger.info("True token")
from app.boxes import _send_create
from app.orgpython import to_html
content = to_html(content).replace("\n", "") content = to_html(content).replace("\n", "")
@ -123,17 +127,14 @@ async def outbox(
VisibilityEnum.PUBLIC VisibilityEnum.PUBLIC
) )
return Response(status_code=200) return Response(status_code=200)
else:
logger.warning("Non-valid post token!")
return Response(status_code=406)
@app.get("/tail/{public_id}") @app.get("/tail/{public_id}")
async def outbox_activity_by_public_id( async def outbox_activity_by_public_id(
public_id: str, public_id: str,
request: Request,
db_session: AsyncSession = Depends(get_db_session), db_session: AsyncSession = Depends(get_db_session),
) -> ActivityPubResponse: ) -> ActivityPubResponse:
"""Return note page."""
outbox_object = ( outbox_object = (
await db_session.execute( await db_session.execute(
select(models.OutboxObject).where( select(models.OutboxObject).where(
@ -178,8 +179,10 @@ async def wellknown_webfinger(resource: str) -> JSONResponse:
headers={"Access-Control-Allow-Origin": "*"}, headers={"Access-Control-Allow-Origin": "*"},
) )
@app.get("/.well-known/nodeinfo") @app.get("/.well-known/nodeinfo")
async def well_known_nodeinfo() -> dict[str, Any]: async def well_known_nodeinfo() -> dict[str, Any]:
"""Exposes nodeinfo path."""
return { return {
"links": [ "links": [
{ {
@ -191,9 +194,8 @@ async def well_known_nodeinfo() -> dict[str, Any]:
@app.get("/nodeinfo/2.0") @app.get("/nodeinfo/2.0")
async def nodeinfo( async def nodeinfo():
db_session: AsyncSession = Depends(get_db_session), """Return site nodeinfo."""
):
return JSONResponse( return JSONResponse(
{ {
"version": "2.0", "version": "2.0",