Repos / pytaku / f8df3b0265
commit f8df3b02655b2217bbacf0bf775a2cf6929a2b73
Author: Bùi Thành Nhân <hi@imnhan.com>
Date:   Sat Aug 1 19:58:17 2020 +0700

    refactor proxy code
    
    ... into separate REPL-friendly functions to aid debugging.
    Also allow img urls straight from mangadex.org (previously only allowed
    the sN.mangadex.org subdomains).

diff --git a/src/pytaku/main.py b/src/pytaku/main.py
index 78c1d01..9bba60e 100644
--- a/src/pytaku/main.py
+++ b/src/pytaku/main.py
@@ -24,8 +24,7 @@ def title_view(title_id):
 def chapter_view(chapter_id):
     chapter = get_chapter(chapter_id)
     chapter["pages"] = [
-        url_for("proxy_view", b64_url=base64.urlsafe_b64encode(p.encode()).decode())
-        for p in chapter["pages"]
+        url_for("proxy_view", b64_url=_encode_proxy_url(p)) for p in chapter["pages"]
     ]
     return render_template("chapter.html", **chapter)
 
@@ -38,11 +37,25 @@ def search_view():
 @app.route("/proxy/<b64_url>")
 def proxy_view(b64_url):
     """Fine I'll do it"""
-    url = base64.urlsafe_b64decode(b64_url).decode()
-    if not re.match(r"^https://\w+\.mangadex\.org/data/.+$", url):
+    url = _decode_proxy_url(b64_url)
+    if not _is_manga_img_url(url):
         return "Nope"
     print("Proxying", url)
     md_resp = requests.get(url)
     resp = make_response(md_resp.content, md_resp.status_code)
     resp.headers.extend(**md_resp.headers)
     return resp
+
+
+def _encode_proxy_url(url):
+    return base64.urlsafe_b64encode(url.encode()).decode()
+
+
+def _decode_proxy_url(b64_url):
+    return base64.urlsafe_b64decode(b64_url).decode()
+
+
+def _is_manga_img_url(
+    url, pattern=re.compile(r"^https://(\w+\.)?mangadex\.org/data/.+$")
+):
+    return pattern.match(url)