formatters.nim 6.4 KB

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