formatters.nim 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. # SPDX-License-Identifier: AGPL-3.0-only
  2. import strutils, strformat, times, uri, tables, xmltree, htmlparser, htmlgen, math
  3. import std/[enumerate, re]
  4. import types, utils, query
  5. const
  6. cards = "cards.twitter.com/cards"
  7. tco = "https://t.co"
  8. twitter = parseUri("https://x.com")
  9. let
  10. twRegex = re"(?<=(?<!\S)https:\/\/|(?<=\s))(www\.|mobile\.)?twitter\.com"
  11. twLinkRegex = re"""<a href="https:\/\/twitter.com([^"]+)">twitter\.com(\S+)</a>"""
  12. xRegex = re"(?<=(?<!\S)https:\/\/|(?<=\s))(www\.|mobile\.)?x\.com"
  13. xLinkRegex = re"""<a href="https:\/\/x.com([^"]+)">x\.com(\S+)</a>"""
  14. ytRegex = re(r"([A-z.]+\.)?youtu(be\.com|\.be)", {reStudy, reIgnoreCase})
  15. rdRegex = re"(?<![.b])((www|np|new|amp|old)\.)?reddit.com"
  16. rdShortRegex = re"(?<![.b])redd\.it\/"
  17. # Videos cannot be supported uniformly between Teddit and Libreddit,
  18. # so v.redd.it links will not be replaced.
  19. # Images aren't supported due to errors from Teddit when the image
  20. # wasn't first displayed via a post on the Teddit instance.
  21. wwwRegex = re"https?://(www[0-9]?\.)?"
  22. m3u8Regex = re"""url="(.+.m3u8)""""
  23. userPicRegex = re"_(normal|bigger|mini|200x200|400x400)(\.[A-z]+)$"
  24. extRegex = re"(\.[A-z]+)$"
  25. illegalXmlRegex = re"(*UTF8)[^\x09\x0A\x0D\x20-\x{D7FF}\x{E000}-\x{FFFD}\x{10000}-\x{10FFFF}]"
  26. proc getUrlPrefix*(cfg: Config): string =
  27. if cfg.useHttps: https & cfg.hostname
  28. else: "http://" & cfg.hostname
  29. proc shorten*(text: string; length=28): string =
  30. result = text
  31. if result.len > length:
  32. result = result[0 ..< length] & "…"
  33. proc shortLink*(text: string; length=28): string =
  34. result = text.replace(wwwRegex, "").shorten(length)
  35. proc stripHtml*(text: string; shorten=false): string =
  36. var html = parseHtml(text)
  37. for el in html.findAll("a"):
  38. let link = el.attr("href")
  39. if "http" in link:
  40. if el.len == 0: continue
  41. el[0].text =
  42. if shorten: link.shortLink
  43. else: link
  44. html.innerText()
  45. proc sanitizeXml*(text: string): string =
  46. text.replace(illegalXmlRegex, "")
  47. proc replaceUrls*(body: string; prefs: Prefs; absolute=""): string =
  48. result = body
  49. if prefs.replaceYouTube.len > 0 and "youtu" in result:
  50. let youtubeHost = strip(prefs.replaceYouTube, chars={'/'})
  51. result = result.replace(ytRegex, youtubeHost)
  52. if prefs.replaceTwitter.len > 0:
  53. let twitterHost = strip(prefs.replaceTwitter, chars={'/'})
  54. if tco in result:
  55. result = result.replace(tco, https & twitterHost & "/t.co")
  56. if "x.com" in result:
  57. result = result.replace(xRegex, twitterHost)
  58. result = result.replacef(xLinkRegex, a(
  59. twitterHost & "$2", href = https & twitterHost & "$1"))
  60. if "twitter.com" in result:
  61. result = result.replace(cards, twitterHost & "/cards")
  62. result = result.replace(twRegex, twitterHost)
  63. result = result.replacef(twLinkRegex, a(
  64. twitterHost & "$2", href = https & twitterHost & "$1"))
  65. if prefs.replaceReddit.len > 0 and ("reddit.com" in result or "redd.it" in result):
  66. let redditHost = strip(prefs.replaceReddit, chars={'/'})
  67. result = result.replace(rdShortRegex, redditHost & "/comments/")
  68. result = result.replace(rdRegex, redditHost)
  69. if redditHost in result and "/gallery/" in result:
  70. result = result.replace("/gallery/", "/comments/")
  71. if absolute.len > 0 and "href" in result:
  72. result = result.replace("href=\"/", &"href=\"{absolute}/")
  73. proc getM3u8Url*(content: string): string =
  74. var matches: array[1, string]
  75. if re.find(content, m3u8Regex, matches) != -1:
  76. result = matches[0]
  77. proc proxifyVideo*(manifest: string; proxy: bool; manifestUrl = ""): string =
  78. let (baseUrl, basePath) =
  79. if manifestUrl.len > 0:
  80. let
  81. u = parseUri(manifestUrl)
  82. origin = u.scheme & "://" & u.hostname
  83. idx = manifestUrl.rfind('/')
  84. dirPath = if idx > 8: manifestUrl[0 .. idx] else: ""
  85. (origin, dirPath)
  86. else:
  87. ("https://video.twimg.com", "")
  88. var replacements: seq[(string, string)]
  89. for line in manifest.splitLines:
  90. let url =
  91. if line.startsWith("#EXT-X-MAP:URI"): line[16 .. ^2]
  92. elif line.startsWith("#EXT-X-MEDIA") and "URI=" in line:
  93. line[line.find("URI=") + 5 .. -1 + line.find("\"", start= 5 + line.find("URI="))]
  94. else: line
  95. let resolved =
  96. if url.startsWith('/'): baseUrl & url
  97. elif basePath.len > 0 and url.len > 0 and not url.startsWith('#') and
  98. not url.startsWith("http") and ('.' in url): basePath & url
  99. else: ""
  100. if resolved.len > 0:
  101. replacements.add (url, if proxy: resolved.getVidUrl else: resolved)
  102. return manifest.multiReplace(replacements)
  103. proc getUserPic*(userPic: string; style=""): string =
  104. userPic.replacef(userPicRegex, "$2").replacef(extRegex, style & "$1")
  105. proc getUserPic*(user: User; style=""): string =
  106. getUserPic(user.userPic, style)
  107. proc getVideoEmbed*(cfg: Config; id: int64): string =
  108. &"{getUrlPrefix(cfg)}/i/videos/{id}"
  109. proc pageTitle*(user: User): string =
  110. &"{user.fullname} (@{user.username})"
  111. proc pageTitle*(tweet: Tweet): string =
  112. &"{pageTitle(tweet.user)}: \"{stripHtml(tweet.text)}\""
  113. proc pageDesc*(user: User): string =
  114. if user.bio.len > 0:
  115. stripHtml(user.bio)
  116. else:
  117. "The latest tweets from " & user.fullname
  118. proc getJoinDate*(user: User): string =
  119. if user.joinDate.year == 0: return ""
  120. user.joinDate.format("'Joined' MMMM YYYY")
  121. proc getJoinDateFull*(user: User): string =
  122. if user.joinDate.year == 0: return ""
  123. user.joinDate.format("h:mm tt - d MMM YYYY")
  124. proc getTime*(tweet: Tweet): string =
  125. if tweet.time.year == 0: return ""
  126. tweet.time.format("MMM d', 'YYYY' · 'h:mm tt' UTC'")
  127. proc getRfc822Time*(tweet: Tweet): string =
  128. if tweet.time.year == 0: return ""
  129. tweet.time.format("ddd', 'dd MMM yyyy HH:mm:ss 'GMT'")
  130. proc getShortTime*(time: DateTime): string =
  131. if time.year == 0: return ""
  132. let now = now()
  133. let since = now - time
  134. if now.year != time.year:
  135. result = time.format("d MMM yyyy")
  136. elif since.inDays >= 1:
  137. result = time.format("MMM d")
  138. elif since.inHours >= 1:
  139. result = $since.inHours & "h"
  140. elif since.inMinutes >= 1:
  141. result = $since.inMinutes & "m"
  142. elif since.inSeconds > 1:
  143. result = $since.inSeconds & "s"
  144. else:
  145. result = "now"
  146. proc getShortTime*(tweet: Tweet): string =
  147. getShortTime(tweet.time)
  148. proc getDuration*(ms: int): string =
  149. let
  150. sec = int(round(ms / 1000))
  151. min = floorDiv(sec, 60)
  152. hour = floorDiv(min, 60)
  153. if hour > 0:
  154. &"{hour}:{min mod 60:02}:{sec mod 60:02}"
  155. else:
  156. &"{min mod 60}:{sec mod 60:02}"
  157. proc getDuration*(video: Video): string =
  158. getDuration(video.durationMs)
  159. proc getLink*(id: int64; username="i"; focus=true): string =
  160. var username = username
  161. if username.len == 0:
  162. username = "i"
  163. result = &"/{username}/status/{id}"
  164. if focus: result &= "#m"
  165. proc getLink*(tweet: Tweet; focus=true): string =
  166. if tweet.id == 0: return
  167. var username = tweet.user.username
  168. return getLink(tweet.id, username, focus)
  169. proc getTwitterLink*(path: string; params: Table[string, string]): string =
  170. var
  171. username = params.getOrDefault("name")
  172. query = initQuery(params, username)
  173. path = path
  174. if "," in username:
  175. query.fromUser = username.split(",")
  176. path = "/search"
  177. if "/search" notin path and query.fromUser.len < 2:
  178. return $(twitter / path)
  179. let p = {
  180. "f": if query.kind == users: "user" else: "live",
  181. "q": genQueryParam(query),
  182. "src": "typed_query"
  183. }
  184. result = $(twitter / path ? p)
  185. if username.len > 0:
  186. result = result.replace("/" & username, "")
  187. proc getLocation*(u: User | Tweet): (string, string) =
  188. if "://" in u.location: return (u.location, "")
  189. let loc = u.location.split(":")
  190. let url = if loc.len > 1: "/search?f=tweets&q=place:" & loc[1] else: ""
  191. (loc[0], url)
  192. proc getSuspended*(username: string): string =
  193. &"User \"{username}\" has been suspended"
  194. proc titleize*(str: string): string =
  195. const
  196. lowercase = {'a'..'z'}
  197. delims = {' ', '('}
  198. result = str
  199. for i, c in enumerate(str):
  200. if c in lowercase and (i == 0 or str[i - 1] in delims):
  201. result[i] = c.toUpperAscii