parserutils.nim 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. # SPDX-License-Identifier: AGPL-3.0-only
  2. import std/[strutils, times, macros, htmlgen, options, algorithm, re]
  3. import std/unicode except strip
  4. import packedjson
  5. import types, utils, formatters
  6. let
  7. unRegex = re"(^|[^A-z0-9-_./?])@([A-z0-9_]{1,15})"
  8. unReplace = "$1<a href=\"/$2\">@$2</a>"
  9. htRegex = re"(^|[^\w-_./?])([#$]|#)([\w_]+)"
  10. htReplace = "$1<a href=\"/search?q=%23$3\">$2$3</a>"
  11. type
  12. ReplaceSliceKind = enum
  13. rkRemove, rkUrl, rkHashtag, rkMention
  14. ReplaceSlice = object
  15. slice: Slice[int]
  16. kind: ReplaceSliceKind
  17. url, display: string
  18. template isNull*(js: JsonNode): bool = js.kind == JNull
  19. template notNull*(js: JsonNode): bool = js.kind != JNull
  20. template `?`*(js: JsonNode): untyped =
  21. let j = js
  22. if j.isNull: return
  23. j
  24. template with*(ident, value, body): untyped =
  25. if true:
  26. let ident {.inject.} = value
  27. if ident != nil: body
  28. template with*(ident; value: JsonNode; body): untyped =
  29. if true:
  30. let ident {.inject.} = value
  31. if value.notNull: body
  32. template getCursor*(js: JsonNode): string =
  33. js{"content", "operation", "cursor", "value"}.getStr
  34. template getError*(js: JsonNode): Error =
  35. if js.kind != JArray or js.len == 0: null
  36. else: Error(js[0]{"code"}.getInt)
  37. template parseTime(time: string; f: static string; flen: int): DateTime =
  38. if time.len != flen: return
  39. parse(time, f, utc())
  40. proc getDateTime*(js: JsonNode): DateTime =
  41. parseTime(js.getStr, "yyyy-MM-dd\'T\'HH:mm:ss\'Z\'", 20)
  42. proc getTime*(js: JsonNode): DateTime =
  43. parseTime(js.getStr, "ddd MMM dd hh:mm:ss \'+0000\' yyyy", 30)
  44. proc getId*(id: string): string {.inline.} =
  45. let start = id.rfind("-")
  46. if start < 0: return id
  47. id[start + 1 ..< id.len]
  48. proc getId*(js: JsonNode): int64 {.inline.} =
  49. case js.kind
  50. of JString: return parseBiggestInt(js.getStr("0"))
  51. of JInt: return js.getBiggestInt()
  52. else: return 0
  53. proc getEntryId*(js: JsonNode): string {.inline.} =
  54. let entry = js{"entryId"}.getStr
  55. if entry.len == 0: return
  56. if "tweet" in entry or "sq-I-t" in entry:
  57. return entry.getId
  58. elif "tombstone" in entry:
  59. return js{"content", "item", "content", "tombstone", "tweet", "id"}.getStr
  60. else:
  61. echo "unknown entry: ", entry
  62. return
  63. template getStrVal*(js: JsonNode; default=""): string =
  64. js{"string_value"}.getStr(default)
  65. proc getImageStr*(js: JsonNode): string =
  66. result = js.getStr
  67. result.removePrefix(https)
  68. result.removePrefix(twimg)
  69. template getImageVal*(js: JsonNode): string =
  70. js{"image_value", "url"}.getImageStr
  71. proc getCardUrl*(js: JsonNode; kind: CardKind): string =
  72. result = js{"website_url"}.getStrVal
  73. if kind == promoVideoConvo:
  74. result = js{"thank_you_url"}.getStrVal(result)
  75. if result.startsWith("card://"):
  76. result = ""
  77. proc getCardDomain*(js: JsonNode; kind: CardKind): string =
  78. result = js{"vanity_url"}.getStrVal(js{"domain"}.getStr)
  79. if kind == promoVideoConvo:
  80. result = js{"thank_you_vanity_url"}.getStrVal(result)
  81. proc getCardTitle*(js: JsonNode; kind: CardKind): string =
  82. result = js{"title"}.getStrVal
  83. if kind == promoVideoConvo:
  84. result = js{"thank_you_text"}.getStrVal(result)
  85. elif kind == liveEvent:
  86. result = js{"event_category"}.getStrVal
  87. elif kind in {videoDirectMessage, imageDirectMessage}:
  88. result = js{"cta1"}.getStrVal
  89. proc getBanner*(js: JsonNode): string =
  90. let url = js{"profile_banner_url"}.getImageStr
  91. if url.len > 0:
  92. return url & "/1500x500"
  93. let color = js{"profile_link_color"}.getStr
  94. if color.len > 0:
  95. return '#' & color
  96. # use primary color from profile picture color histogram
  97. with p, js{"profile_image_extensions", "mediaColor", "r", "ok", "palette"}:
  98. if p.len > 0:
  99. let pal = p[0]{"rgb"}
  100. result = "#"
  101. result.add toHex(pal{"red"}.getInt, 2)
  102. result.add toHex(pal{"green"}.getInt, 2)
  103. result.add toHex(pal{"blue"}.getInt, 2)
  104. return
  105. proc getTombstone*(js: JsonNode): string =
  106. result = js{"tombstoneInfo", "richText", "text"}.getStr
  107. result.removeSuffix(" Learn more")
  108. proc getMp4Resolution*(url: string): int =
  109. # parses the height out of a URL like this one:
  110. # https://video.twimg.com/ext_tw_video/<tweet-id>/pu/vid/720x1280/<random>.mp4
  111. const vidSep = "/vid/"
  112. let
  113. vidIdx = url.find(vidSep) + vidSep.len
  114. resIdx = url.find('x', vidIdx) + 1
  115. res = url[resIdx ..< url.find("/", resIdx)]
  116. try:
  117. return parseInt(res)
  118. except ValueError:
  119. # cannot determine resolution (e.g. m3u8/non-mp4 video)
  120. return 0
  121. proc extractSlice(js: JsonNode): Slice[int] =
  122. result = js["indices"][0].getInt ..< js["indices"][1].getInt
  123. proc extractUrls(result: var seq[ReplaceSlice]; js: JsonNode;
  124. textLen: int; hideTwitter = false) =
  125. let
  126. url = js["expanded_url"].getStr
  127. slice = js.extractSlice
  128. if hideTwitter and slice.b.succ >= textLen and url.isTwitterUrl:
  129. if slice.a < textLen:
  130. result.add ReplaceSlice(kind: rkRemove, slice: slice)
  131. else:
  132. result.add ReplaceSlice(kind: rkUrl, url: url,
  133. display: url.shortLink, slice: slice)
  134. proc extractHashtags(result: var seq[ReplaceSlice]; js: JsonNode) =
  135. result.add ReplaceSlice(kind: rkHashtag, slice: js.extractSlice)
  136. proc replacedWith(runes: seq[Rune]; repls: openArray[ReplaceSlice];
  137. textSlice: Slice[int]): string =
  138. template extractLowerBound(i: int; idx): int =
  139. if i > 0: repls[idx].slice.b.succ else: textSlice.a
  140. result = newStringOfCap(runes.len)
  141. for i, rep in repls:
  142. result.add $runes[extractLowerBound(i, i - 1) ..< rep.slice.a]
  143. case rep.kind
  144. of rkHashtag:
  145. let
  146. name = $runes[rep.slice.a.succ .. rep.slice.b]
  147. symbol = $runes[rep.slice.a]
  148. result.add a(symbol & name, href = "/search?q=%23" & name)
  149. of rkMention:
  150. result.add a($runes[rep.slice], href = rep.url, title = rep.display)
  151. of rkUrl:
  152. result.add a(rep.display, href = rep.url)
  153. of rkRemove:
  154. discard
  155. let rest = extractLowerBound(repls.len, ^1) ..< textSlice.b
  156. if rest.a <= rest.b:
  157. result.add $runes[rest]
  158. proc deduplicate(s: var seq[ReplaceSlice]) =
  159. var
  160. len = s.len
  161. i = 0
  162. while i < len:
  163. var j = i + 1
  164. while j < len:
  165. if s[i].slice.a == s[j].slice.a:
  166. s.del j
  167. dec len
  168. else:
  169. inc j
  170. inc i
  171. proc cmp(x, y: ReplaceSlice): int = cmp(x.slice.a, y.slice.b)
  172. proc expandUserEntities*(user: var User; js: JsonNode) =
  173. let
  174. orig = user.bio.toRunes
  175. ent = ? js{"entities"}
  176. with urls, ent{"url", "urls"}:
  177. user.website = urls[0]{"expanded_url"}.getStr
  178. var replacements = newSeq[ReplaceSlice]()
  179. with urls, ent{"description", "urls"}:
  180. for u in urls:
  181. replacements.extractUrls(u, orig.high)
  182. replacements.deduplicate
  183. replacements.sort(cmp)
  184. user.bio = orig.replacedWith(replacements, 0 .. orig.len)
  185. user.bio = user.bio.replacef(unRegex, unReplace)
  186. .replacef(htRegex, htReplace)
  187. proc expandTweetEntities*(tweet: Tweet; js: JsonNode) =
  188. let
  189. orig = tweet.text.toRunes
  190. textRange = js{"display_text_range"}
  191. textSlice = textRange{0}.getInt .. textRange{1}.getInt
  192. hasQuote = js{"is_quote_status"}.getBool
  193. hasCard = tweet.card.isSome
  194. var replyTo = ""
  195. if tweet.replyId != 0:
  196. with reply, js{"in_reply_to_screen_name"}:
  197. tweet.reply.add reply.getStr
  198. replyTo = reply.getStr
  199. let ent = ? js{"entities"}
  200. var replacements = newSeq[ReplaceSlice]()
  201. with urls, ent{"urls"}:
  202. for u in urls:
  203. let urlStr = u["url"].getStr
  204. if urlStr.len == 0 or urlStr notin tweet.text:
  205. continue
  206. replacements.extractUrls(u, textSlice.b, hideTwitter = hasQuote)
  207. if hasCard and u{"url"}.getStr == get(tweet.card).url:
  208. get(tweet.card).url = u{"expanded_url"}.getStr
  209. with media, ent{"media"}:
  210. for m in media:
  211. replacements.extractUrls(m, textSlice.b, hideTwitter = true)
  212. if "hashtags" in ent:
  213. for hashtag in ent["hashtags"]:
  214. replacements.extractHashtags(hashtag)
  215. if "symbols" in ent:
  216. for symbol in ent["symbols"]:
  217. replacements.extractHashtags(symbol)
  218. if "user_mentions" in ent:
  219. for mention in ent["user_mentions"]:
  220. let
  221. name = mention{"screen_name"}.getStr
  222. slice = mention.extractSlice
  223. idx = tweet.reply.find(name)
  224. if slice.a >= textSlice.a:
  225. replacements.add ReplaceSlice(kind: rkMention, slice: slice,
  226. url: "/" & name, display: mention["name"].getStr)
  227. if idx > -1 and name != replyTo:
  228. tweet.reply.delete idx
  229. elif idx == -1 and tweet.replyId != 0:
  230. tweet.reply.add name
  231. replacements.deduplicate
  232. replacements.sort(cmp)
  233. tweet.text = orig.replacedWith(replacements, textSlice)
  234. .strip(leading=false)