parserutils.nim 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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. block:
  26. let ident {.inject.} = value
  27. if ident != nil: body
  28. template `with`*(ident; value: JsonNode; body): untyped =
  29. block:
  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 getSource*(js: JsonNode): string =
  109. let src = js{"source"}.getStr
  110. result = src.substr(src.find('>') + 1, src.rfind('<') - 1)
  111. proc getMp4Resolution*(url: string): int =
  112. # parses the height out of a URL like this one:
  113. # https://video.twimg.com/ext_tw_video/<tweet-id>/pu/vid/720x1280/<random>.mp4
  114. const vidSep = "/vid/"
  115. let
  116. vidIdx = url.find(vidSep) + vidSep.len
  117. resIdx = url.find('x', vidIdx) + 1
  118. res = url[resIdx ..< url.find("/", resIdx)]
  119. try:
  120. return parseInt(res)
  121. except ValueError:
  122. # cannot determine resolution (e.g. m3u8/non-mp4 video)
  123. return 0
  124. proc extractSlice(js: JsonNode): Slice[int] =
  125. result = js["indices"][0].getInt ..< js["indices"][1].getInt
  126. proc extractUrls(result: var seq[ReplaceSlice]; js: JsonNode;
  127. textLen: int; hideTwitter = false) =
  128. let
  129. url = js["expanded_url"].getStr
  130. slice = js.extractSlice
  131. if hideTwitter and slice.b.succ >= textLen and url.isTwitterUrl:
  132. if slice.a < textLen:
  133. result.add ReplaceSlice(kind: rkRemove, slice: slice)
  134. else:
  135. result.add ReplaceSlice(kind: rkUrl, url: url,
  136. display: url.shortLink, slice: slice)
  137. proc extractHashtags(result: var seq[ReplaceSlice]; js: JsonNode) =
  138. result.add ReplaceSlice(kind: rkHashtag, slice: js.extractSlice)
  139. proc replacedWith(runes: seq[Rune]; repls: openArray[ReplaceSlice];
  140. textSlice: Slice[int]): string =
  141. template extractLowerBound(i: int; idx): int =
  142. if i > 0: repls[idx].slice.b.succ else: textSlice.a
  143. result = newStringOfCap(runes.len)
  144. for i, rep in repls:
  145. result.add $runes[extractLowerBound(i, i - 1) ..< rep.slice.a]
  146. case rep.kind
  147. of rkHashtag:
  148. let
  149. name = $runes[rep.slice.a.succ .. rep.slice.b]
  150. symbol = $runes[rep.slice.a]
  151. result.add a(symbol & name, href = "/search?q=%23" & name)
  152. of rkMention:
  153. result.add a($runes[rep.slice], href = rep.url, title = rep.display)
  154. of rkUrl:
  155. result.add a(rep.display, href = rep.url)
  156. of rkRemove:
  157. discard
  158. let rest = extractLowerBound(repls.len, ^1) ..< textSlice.b
  159. if rest.a <= rest.b:
  160. result.add $runes[rest]
  161. proc deduplicate(s: var seq[ReplaceSlice]) =
  162. var
  163. len = s.len
  164. i = 0
  165. while i < len:
  166. var j = i + 1
  167. while j < len:
  168. if s[i].slice.a == s[j].slice.a:
  169. s.del j
  170. dec len
  171. else:
  172. inc j
  173. inc i
  174. proc cmp(x, y: ReplaceSlice): int = cmp(x.slice.a, y.slice.b)
  175. proc expandUserEntities*(user: var User; js: JsonNode) =
  176. let
  177. orig = user.bio.toRunes
  178. ent = ? js{"entities"}
  179. with urls, ent{"url", "urls"}:
  180. user.website = urls[0]{"expanded_url"}.getStr
  181. var replacements = newSeq[ReplaceSlice]()
  182. with urls, ent{"description", "urls"}:
  183. for u in urls:
  184. replacements.extractUrls(u, orig.high)
  185. replacements.deduplicate
  186. replacements.sort(cmp)
  187. user.bio = orig.replacedWith(replacements, 0 .. orig.len)
  188. user.bio = user.bio.replacef(unRegex, unReplace)
  189. .replacef(htRegex, htReplace)
  190. proc expandTweetEntities*(tweet: Tweet; js: JsonNode) =
  191. let
  192. orig = tweet.text.toRunes
  193. textRange = js{"display_text_range"}
  194. textSlice = textRange{0}.getInt .. textRange{1}.getInt
  195. hasQuote = js{"is_quote_status"}.getBool
  196. hasCard = tweet.card.isSome
  197. var replyTo = ""
  198. if tweet.replyId != 0:
  199. with reply, js{"in_reply_to_screen_name"}:
  200. tweet.reply.add reply.getStr
  201. replyTo = reply.getStr
  202. let ent = ? js{"entities"}
  203. var replacements = newSeq[ReplaceSlice]()
  204. with urls, ent{"urls"}:
  205. for u in urls:
  206. let urlStr = u["url"].getStr
  207. if urlStr.len == 0 or urlStr notin tweet.text:
  208. continue
  209. replacements.extractUrls(u, textSlice.b, hideTwitter = hasQuote)
  210. if hasCard and u{"url"}.getStr == get(tweet.card).url:
  211. get(tweet.card).url = u{"expanded_url"}.getStr
  212. with media, ent{"media"}:
  213. for m in media:
  214. replacements.extractUrls(m, textSlice.b, hideTwitter = true)
  215. if "hashtags" in ent:
  216. for hashtag in ent["hashtags"]:
  217. replacements.extractHashtags(hashtag)
  218. if "symbols" in ent:
  219. for symbol in ent["symbols"]:
  220. replacements.extractHashtags(symbol)
  221. if "user_mentions" in ent:
  222. for mention in ent["user_mentions"]:
  223. let
  224. name = mention{"screen_name"}.getStr
  225. slice = mention.extractSlice
  226. idx = tweet.reply.find(name)
  227. if slice.a >= textSlice.a:
  228. replacements.add ReplaceSlice(kind: rkMention, slice: slice,
  229. url: "/" & name, display: mention["name"].getStr)
  230. if idx > -1 and name != replyTo:
  231. tweet.reply.delete idx
  232. elif idx == -1 and tweet.replyId != 0:
  233. tweet.reply.add name
  234. replacements.deduplicate
  235. replacements.sort(cmp)
  236. tweet.text = orig.replacedWith(replacements, textSlice)
  237. .strip(leading=false)