formatters.nim 6.2 KB

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