Ver código fonte

save qr when saving content

Daniel Sheffield 1 ano atrás
pai
commit
9b22696a67
5 arquivos alterados com 40 adições e 15 exclusões
  1. 15 6
      app/rest/pyapi.py
  2. 2 2
      app/rest/qr.py
  3. 20 5
      app/rest/save.py
  4. 1 0
      app/rest/static/clip-qr.svg
  5. 2 2
      app/rest/templates/paste.tpl

+ 15 - 6
app/rest/pyapi.py

@@ -112,7 +112,6 @@ def clip():
         else:
             content = None
         link = f'{LOCATION}/clip/{_hash}' if content else f'{LOCATION}/clip'
-        svg = get_qr_code(content, fallback=link)
 
         response.content_type = 'text/html; charset=utf-8'
         form = template(
@@ -125,7 +124,7 @@ def clip():
         return template(
             'paste',
             form=form,
-            svg=svg,
+            qr=f'{LOCATION}/clip/{_hash}.qr' if content else f'{LOCATION}/grocery/static/clip-qr.svg',
             link=link,
             disabled=True if content else False,
             download=f'/clip/{_hash}' if content else None
@@ -134,7 +133,7 @@ def clip():
     if request.method == 'POST':
         content = validate_parameter(request, 'paste')
         if request.params.copy != 'true':
-            _b32 = save(content)
+            _b32 = save(content, LOCATION)
             return redirect(f'/clip?hash={_b32}')
 
         response.content_type = 'text/html; charset=utf-8'
@@ -146,11 +145,10 @@ def clip():
             disabled=False
         )
         link = f'{LOCATION}/clip'
-        svg = get_qr_code(content, fallback=link)
         return template(
             'paste',
             form=form,
-            svg=svg,
+            qr=f'{LOCATION}/grocery/static/clip-qr.svg',
             link=link,
             disabled=False,
             download=None
@@ -159,6 +157,17 @@ def clip():
 
 @route('/clip/<filename:path>', method='GET')
 def get_clip(filename):
+    ext = 'file'
+    if filename and filename.endswith('.qr'):
+        filename, ext = filename.split('.', 1)
+    
+    filename = filename and normalize_base32(filename)
+    path = f'{filename}/{filename}.{ext}'
+    
+    if ext == 'qr':
+        mimetype = 'image/svg+xml'
+        return static_file(path, root='app/rest/static', mimetype=mimetype)
+    
     filename = filename and normalize_base32(filename)
     if not request.params.raw.lower() == 'true':
         # TODO: return a form with timeout to a GET instead ?
@@ -168,7 +177,7 @@ def get_clip(filename):
     if isinstance(ret, HTTPError):
         return ret
 
-    return static_file('/'.join([filename,]*2) + '.file', root='app/rest/static')
+    return static_file(path, root='app/rest/static')
 
 
 @route('/upload', method=['GET', 'POST'])

+ 2 - 2
app/rest/qr.py

@@ -1,4 +1,4 @@
-import io
+from io import BytesIO
 from typing import Union
 from qrcode import QRCode
 from qrcode.constants import ERROR_CORRECT_L, ERROR_CORRECT_M, ERROR_CORRECT_Q, ERROR_CORRECT_H
@@ -26,7 +26,7 @@ def get_qr_code(data: Union[bytes, str], fallback: Union[bytes, str] = None):
         qr.add_data(data or fallback, optimize=0)
 
     img_1 = qr.make_image(image_factory=SvgPathImage)
-    with io.BytesIO() as f:
+    with BytesIO() as f:
         img_1.save(f)
         f.flush()
         ret = f.getvalue()

+ 20 - 5
app/rest/save.py

@@ -8,10 +8,17 @@ from hashlib import blake2b
 from io import BufferedRandom, BytesIO
 import os
 from uuid import uuid4
+
 from .hash_util import DIGEST_SIZE_BYTES, blake, bytes_to_base32
+from .qr import get_qr_code
+
+def save_qr(qr: bytes, _b32:str , directory: str) -> str:
+    fd = os.open(f'{directory}/{_b32}.qr', os.O_WRONLY | os.O_TRUNC | os.O_CREAT, 0o600)
+    with open(fd, "wb") as f:
+        f.write(qr)
 
 
-def save(content: bytes, root='app/rest/static') -> str:
+def save(content: bytes, location: str, root='app/rest/static') -> str:
     _bytes = blake(content, person='clip'.encode('utf-8'))
     _b32 = bytes_to_base32(_bytes)
     directory = f'{root}/{_b32}'
@@ -22,8 +29,19 @@ def save(content: bytes, root='app/rest/static') -> str:
     fd = os.open(f'{directory}/{_b32}.file', os.O_WRONLY | os.O_TRUNC | os.O_CREAT, 0o600)
     with open(fd, "wb") as f:
         f.write(content)
+    
+    link = f'{location}/clip/{_b32}'
+    svg = get_qr_code(content, fallback=link)
+    save_qr(svg, _b32, directory)
     return _b32
 
+
+def save_filename(name: str, _b32: str, directory: str):
+    fd = os.open(f'{directory}/{_b32}.name', os.O_WRONLY | os.O_TRUNC | os.O_CREAT, 0o600)
+    with open(fd, "w") as f:
+        f.write(name)
+
+
 def save_upload(name: str, content: BufferedRandom, root='app/rest/static') -> str:
     tmpdir = '/tmp/upload'
     try:
@@ -57,9 +75,6 @@ def save_upload(name: str, content: BufferedRandom, root='app/rest/static') -> s
         pass
 
     os.replace(f'{tmpdir}/{unique.hex}', f'{directory}/{_b32}.file')
-    fd = os.open(f'{directory}/{_b32}.name', os.O_WRONLY | os.O_TRUNC | os.O_CREAT, 0o600)
-    with open(fd, "w") as f:
-        f.write(name)
+    save_filename(name, _b32, directory)
 
     return _b32
-

Diferenças do arquivo suprimidas por serem muito extensas
+ 1 - 0
app/rest/static/clip-qr.svg


+ 2 - 2
app/rest/templates/paste.tpl

@@ -14,7 +14,7 @@ body {
   background-color: #080808;
   color: #cccccc;
 }
-svg {
+img {
   background-color: floralwhite;
   color: black;
   max-height: min(100vh, calc(100vw * 9 / 16));
@@ -44,7 +44,7 @@ svg {
         </div>
       </div>
       <div class="pure-u-1">
-        <p><details><summary> Show QR code ...</summary>{{!svg}}</details></p>
+        <p><details><summary> Show QR code ...</summary><img src="{{qr}}"/></details></p>
 {{!form}}
 <form id="download" method="get" action="{{ download }}">
 <input name="raw" type="text" hidden="true" value="true" />

Alguns arquivos não foram mostrados porque muitos arquivos mudaram nesse diff