From be15f1b001343a1a749422ec978cd76ccbf65116 Mon Sep 17 00:00:00 2001 From: Zed Date: Sun, 22 Dec 2019 01:45:07 +0100 Subject: [PATCH] Prevent 403 errors from outdated videos --- src/api/utils.nim | 3 +-- src/routes/media.nim | 19 +++++-------------- src/routes/router_utils.nim | 8 +++++++- 3 files changed, 13 insertions(+), 17 deletions(-) diff --git a/src/api/utils.nim b/src/api/utils.nim index f4484f3..0dcee25 100644 --- a/src/api/utils.nim +++ b/src/api/utils.nim @@ -47,9 +47,8 @@ proc fetchJson*(url: Uri; headers: HttpHeaders): Future[JsonNode] {.async.} = headers["accept"] = jsonAccept newClient() - var resp = "" try: - resp = await client.getContent($url) + let resp = await client.getContent($url) result = parseJson(resp) except: return nil diff --git a/src/routes/media.nim b/src/routes/media.nim index 00d8dfb..779ca3d 100644 --- a/src/routes/media.nim +++ b/src/routes/media.nim @@ -46,16 +46,8 @@ proc createMediaRouter*(cfg: Config) = let url = decodeUrl(@"url") cond isTwitterUrl(url) == true - let client = newAsyncHttpClient() - var content: string - try: - content = await client.getContent(url) - client.close - except: - discard - - if content.len == 0: - resp Http404 + let content = await safeFetch(url) + if content.len == 0: resp Http404 let filename = parseUri(url).path.split(".")[^1] resp content, settings.mimes.getMimetype(filename) @@ -68,18 +60,17 @@ proc createMediaRouter*(cfg: Config) = if getHmac(url) != @"sig": resp showError("Failed to verify signature", cfg) - let client = newAsyncHttpClient() - var content = await client.getContent(url) + var content = await safeFetch(url) + if content.len == 0: resp Http404 if ".vmap" in url: var m: RegexMatch discard content.find(re"""url="(.+.m3u8)"""", m) url = decodeUrl(content[m.group(0)[0]]) - content = await client.getContent(url) + content = await safeFetch(url) if ".m3u8" in url: content = proxifyVideo(content, prefs.proxyVideos) - client.close() let ext = parseUri(url).path.split(".")[^1] resp content, settings.mimes.getMimetype(ext) diff --git a/src/routes/router_utils.nim b/src/routes/router_utils.nim index 0aa46b4..cea1f4f 100644 --- a/src/routes/router_utils.nim +++ b/src/routes/router_utils.nim @@ -1,4 +1,4 @@ -import strutils, sequtils +import strutils, sequtils, asyncdispatch, httpclient import ../utils, ../prefs export utils, prefs @@ -13,3 +13,9 @@ template refPath*(): untyped {.dirty.} = proc getNames*(name: string): seq[string] = name.strip(chars={'/'}).split(",").filterIt(it.len > 0) + +proc safeFetch*(url: string): Future[string] {.async.} = + let client = newAsyncHttpClient() + try: result = await client.getContent(url) + except: discard + client.close()