File size: 2,036 Bytes
0a1b571
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
from typing import Optional

from fastapi import Request, Response
from pydantic.color import Color

from hibiapi.api.qrcode import (
    COLOR_BLACK,
    COLOR_WHITE,
    Config,
    HostUrl,
    QRCodeLevel,
    QRInfo,
    ReturnEncode,
)
from hibiapi.utils.routing import SlashRouter
from hibiapi.utils.temp import TempFile

QR_CALLBACK_TEMPLATE = (
    r"""function {fun}(){document.write('<img class="qrcode" src="{url}"/>');}"""
)

__mount__, __config__ = "qrcode", Config
router = SlashRouter(tags=["QRCode"])


@router.get(
    "/",
    responses={
        200: {
            "content": {"image/png": {}, "text/javascript": {}, "application/json": {}},
            "description": "Avaliable to return an javascript, image or json.",
        }
    },
    response_model=QRInfo,
)
async def qrcode_api(
    request: Request,
    *,
    text: str,
    size: int = 200,
    logo: Optional[HostUrl] = None,
    encode: ReturnEncode = ReturnEncode.raw,
    level: QRCodeLevel = QRCodeLevel.MEDIUM,
    bgcolor: Color = COLOR_BLACK,
    fgcolor: Color = COLOR_WHITE,
    fun: str = "qrcode",
):
    qr = await QRInfo.new(
        text, size=size, logo=logo, level=level, bgcolor=bgcolor, fgcolor=fgcolor
    )
    qr.url = TempFile.to_url(request, qr.path)  # type:ignore
    """function {fun}(){document.write('<img class="qrcode" src="{url}"/>');}"""
    return (
        qr
        if encode == ReturnEncode.json
        else Response(
            content=qr.json(),
            media_type="application/json",
            headers={"Location": qr.url},
            status_code=302,
        )
        if encode == ReturnEncode.raw
        else Response(
            content=f"{fun}({qr.json()})",
            media_type="text/javascript",
        )
        if encode == ReturnEncode.jsc
        else Response(
            content="function "
            + fun
            + '''(){document.write('<img class="qrcode" src="'''
            + qr.url
            + """"/>');}""",
            media_type="text/javascript",
        )
    )