parserutils.nim 8.0 KB

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