media.nim 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import asyncfile, uri, strutils, httpclient, os
  2. import jester, regex
  3. import router_utils
  4. import ".."/[types, formatters]
  5. import ../views/general
  6. export asyncfile, httpclient, os, strutils
  7. export regex
  8. proc createMediaRouter*(cfg: Config) =
  9. router media:
  10. get "/pic/@url":
  11. cond "http" in @"url"
  12. cond "twimg" in @"url"
  13. let uri = parseUri(decodeUrl(@"url"))
  14. cond isTwitterUrl($uri) == true
  15. let path = uri.path.split("/")[2 .. ^1].join("/")
  16. let filename = cfg.cacheDir / cleanFilename(path & uri.query)
  17. if not existsDir(cfg.cacheDir):
  18. createDir(cfg.cacheDir)
  19. if not existsFile(filename):
  20. let client = newAsyncHttpClient()
  21. try:
  22. await client.downloadFile($uri, filename)
  23. client.close()
  24. except:
  25. discard
  26. if not existsFile(filename):
  27. halt Http404
  28. let file = openAsync(filename)
  29. let buf = await readAll(file)
  30. file.close()
  31. resp buf, mimetype(filename)
  32. get "/gif/@url":
  33. cond "http" in @"url"
  34. cond "twimg" in @"url"
  35. cond "mp4" in @"url" or "gif" in @"url"
  36. let url = decodeUrl(@"url")
  37. cond isTwitterUrl(url) == true
  38. let client = newAsyncHttpClient()
  39. var content: string
  40. try:
  41. content = await client.getContent(url)
  42. client.close
  43. except:
  44. discard
  45. if content.len == 0:
  46. halt Http404
  47. resp content, mimetype(url)
  48. get "/video/@sig/@url":
  49. cond "http" in @"url"
  50. var url = decodeUrl(@"url")
  51. let prefs = cookiePrefs()
  52. if getHmac(url) != @"sig":
  53. resp showError("Failed to verify signature", cfg.title)
  54. let client = newAsyncHttpClient()
  55. var content = await client.getContent(url)
  56. if ".vmap" in url:
  57. var m: RegexMatch
  58. discard content.find(re"""url="(.+.m3u8)"""", m)
  59. url = decodeUrl(content[m.group(0)[0]])
  60. content = await client.getContent(url)
  61. if ".m3u8" in url:
  62. content = proxifyVideo(content, prefs.proxyVideos)
  63. client.close()
  64. resp content, mimetype(url)