parser.nim 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. # SPDX-License-Identifier: AGPL-3.0-only
  2. import strutils, options, tables, times, math
  3. import packedjson, packedjson/deserialiser
  4. import types, parserutils, utils
  5. import experimental/parser/unifiedcard
  6. proc parseUser(js: JsonNode; id=""): User =
  7. if js.isNull: return
  8. result = User(
  9. id: if id.len > 0: id else: js{"id_str"}.getStr,
  10. username: js{"screen_name"}.getStr,
  11. fullname: js{"name"}.getStr,
  12. location: js{"location"}.getStr,
  13. bio: js{"description"}.getStr,
  14. userPic: js{"profile_image_url_https"}.getImageStr.replace("_normal", ""),
  15. banner: js.getBanner,
  16. following: js{"friends_count"}.getInt,
  17. followers: js{"followers_count"}.getInt,
  18. tweets: js{"statuses_count"}.getInt,
  19. likes: js{"favourites_count"}.getInt,
  20. media: js{"media_count"}.getInt,
  21. verified: js{"verified"}.getBool,
  22. protected: js{"protected"}.getBool,
  23. joinDate: js{"created_at"}.getTime
  24. )
  25. result.expandUserEntities(js)
  26. proc parseGraphList*(js: JsonNode): List =
  27. if js.isNull: return
  28. var list = js{"data", "user_by_screen_name", "list"}
  29. if list.isNull:
  30. list = js{"data", "list"}
  31. if list.isNull:
  32. return
  33. result = List(
  34. id: list{"id_str"}.getStr,
  35. name: list{"name"}.getStr,
  36. username: list{"user", "legacy", "screen_name"}.getStr,
  37. userId: list{"user", "rest_id"}.getStr,
  38. description: list{"description"}.getStr,
  39. members: list{"member_count"}.getInt,
  40. banner: list{"custom_banner_media", "media_info", "url"}.getImageStr
  41. )
  42. proc parsePoll(js: JsonNode): Poll =
  43. let vals = js{"binding_values"}
  44. # name format is pollNchoice_*
  45. for i in '1' .. js{"name"}.getStr[4]:
  46. let choice = "choice" & i
  47. result.values.add parseInt(vals{choice & "_count"}.getStrVal("0"))
  48. result.options.add vals{choice & "_label"}.getStrVal
  49. let time = vals{"end_datetime_utc", "string_value"}.getDateTime
  50. if time > now():
  51. let timeLeft = $(time - now())
  52. result.status = timeLeft[0 ..< timeLeft.find(",")]
  53. else:
  54. result.status = "Final results"
  55. result.leader = result.values.find(max(result.values))
  56. result.votes = result.values.sum
  57. proc parseGif(js: JsonNode): Gif =
  58. result = Gif(
  59. url: js{"video_info", "variants"}[0]{"url"}.getImageStr,
  60. thumb: js{"media_url_https"}.getImageStr
  61. )
  62. proc parseVideo(js: JsonNode): Video =
  63. result = Video(
  64. thumb: js{"media_url_https"}.getImageStr,
  65. views: js{"ext", "mediaStats", "r", "ok", "viewCount"}.getStr,
  66. available: js{"ext_media_availability", "status"}.getStr == "available",
  67. title: js{"ext_alt_text"}.getStr,
  68. durationMs: js{"video_info", "duration_millis"}.getInt
  69. # playbackType: mp4
  70. )
  71. with title, js{"additional_media_info", "title"}:
  72. result.title = title.getStr
  73. with description, js{"additional_media_info", "description"}:
  74. result.description = description.getStr
  75. for v in js{"video_info", "variants"}:
  76. result.variants.add VideoVariant(
  77. contentType: parseEnum[VideoType](v{"content_type"}.getStr("summary")),
  78. bitrate: v{"bitrate"}.getInt,
  79. url: v{"url"}.getStr
  80. )
  81. proc parsePromoVideo(js: JsonNode): Video =
  82. result = Video(
  83. thumb: js{"player_image_large"}.getImageVal,
  84. available: true,
  85. durationMs: js{"content_duration_seconds"}.getStrVal("0").parseInt * 1000,
  86. playbackType: vmap
  87. )
  88. var variant = VideoVariant(
  89. contentType: vmap,
  90. url: js{"player_hls_url"}.getStrVal(js{"player_stream_url"}.getStrVal(
  91. js{"amplify_url_vmap"}.getStrVal()))
  92. )
  93. if "m3u8" in variant.url:
  94. variant.contentType = m3u8
  95. result.playbackType = m3u8
  96. result.variants.add variant
  97. proc parseBroadcast(js: JsonNode): Card =
  98. let image = js{"broadcast_thumbnail_large"}.getImageVal
  99. result = Card(
  100. kind: broadcast,
  101. url: js{"broadcast_url"}.getStrVal,
  102. title: js{"broadcaster_display_name"}.getStrVal,
  103. text: js{"broadcast_title"}.getStrVal,
  104. image: image,
  105. video: some Video(thumb: image)
  106. )
  107. proc parseCard(js: JsonNode; urls: JsonNode): Card =
  108. const imageTypes = ["summary_photo_image", "player_image", "promo_image",
  109. "photo_image_full_size", "thumbnail_image", "thumbnail",
  110. "event_thumbnail", "image"]
  111. let
  112. vals = ? js{"binding_values"}
  113. name = js{"name"}.getStr
  114. kind = parseEnum[CardKind](name[(name.find(":") + 1) ..< name.len], unknown)
  115. if kind == unified:
  116. return parseUnifiedCard(vals{"unified_card", "string_value"}.getStr)
  117. result = Card(
  118. kind: kind,
  119. url: vals.getCardUrl(kind),
  120. dest: vals.getCardDomain(kind),
  121. title: vals.getCardTitle(kind),
  122. text: vals{"description"}.getStrVal
  123. )
  124. if result.url.len == 0:
  125. result.url = js{"url"}.getStr
  126. case kind
  127. of promoVideo, promoVideoConvo, appPlayer, videoDirectMessage:
  128. result.video = some parsePromoVideo(vals)
  129. if kind == appPlayer:
  130. result.text = vals{"app_category"}.getStrVal(result.text)
  131. of broadcast:
  132. result = parseBroadcast(vals)
  133. of liveEvent:
  134. result.text = vals{"event_title"}.getStrVal
  135. of player:
  136. result.url = vals{"player_url"}.getStrVal
  137. if "youtube.com" in result.url:
  138. result.url = result.url.replace("/embed/", "/watch?v=")
  139. of audiospace, unknown:
  140. result.title = "This card type is not supported."
  141. else: discard
  142. for typ in imageTypes:
  143. with img, vals{typ & "_large"}:
  144. result.image = img.getImageVal
  145. break
  146. for u in ? urls:
  147. if u{"url"}.getStr == result.url:
  148. result.url = u{"expanded_url"}.getStr
  149. break
  150. if kind in {videoDirectMessage, imageDirectMessage}:
  151. result.url.setLen 0
  152. if kind in {promoImageConvo, promoImageApp, imageDirectMessage} and
  153. result.url.len == 0 or result.url.startsWith("card://"):
  154. result.url = getPicUrl(result.image)
  155. proc parseTweet(js: JsonNode): Tweet =
  156. if js.isNull: return
  157. result = Tweet(
  158. id: js{"id_str"}.getId,
  159. threadId: js{"conversation_id_str"}.getId,
  160. replyId: js{"in_reply_to_status_id_str"}.getId,
  161. text: js{"full_text"}.getStr,
  162. time: js{"created_at"}.getTime,
  163. source: getSource(js),
  164. hasThread: js{"self_thread"}.notNull,
  165. available: true,
  166. user: User(id: js{"user_id_str"}.getStr),
  167. stats: TweetStats(
  168. replies: js{"reply_count"}.getInt,
  169. retweets: js{"retweet_count"}.getInt,
  170. likes: js{"favorite_count"}.getInt,
  171. quotes: js{"quote_count"}.getInt
  172. )
  173. )
  174. result.expandTweetEntities(js)
  175. if js{"is_quote_status"}.getBool:
  176. result.quote = some Tweet(id: js{"quoted_status_id_str"}.getId)
  177. with rt, js{"retweeted_status_id_str"}:
  178. result.retweet = some Tweet(id: rt.getId)
  179. return
  180. with jsCard, js{"card"}:
  181. let name = jsCard{"name"}.getStr
  182. if "poll" in name:
  183. if "image" in name:
  184. result.photos.add jsCard{"binding_values", "image_large"}.getImageVal
  185. result.poll = some parsePoll(jsCard)
  186. elif name == "amplify":
  187. result.video = some(parsePromoVideo(jsCard{"binding_values"}))
  188. else:
  189. result.card = some parseCard(jsCard, js{"entities", "urls"})
  190. with jsMedia, js{"extended_entities", "media"}:
  191. for m in jsMedia:
  192. case m{"type"}.getStr
  193. of "photo":
  194. result.photos.add m{"media_url_https"}.getImageStr
  195. of "video":
  196. result.video = some(parseVideo(m))
  197. with user, m{"additional_media_info", "source_user"}:
  198. result.attribution = some(parseUser(user))
  199. of "animated_gif":
  200. result.gif = some(parseGif(m))
  201. else: discard
  202. with jsWithheld, js{"withheld_in_countries"}:
  203. let withheldInCountries: seq[string] =
  204. if jsWithheld.kind != JArray: @[]
  205. else: jsWithheld.to(seq[string])
  206. # XX - Content is withheld in all countries
  207. # XY - Content is withheld due to a DMCA request.
  208. if js{"withheld_copyright"}.getBool or
  209. withheldInCountries.len > 0 and ("XX" in withheldInCountries or
  210. "XY" in withheldInCountries or
  211. "withheld" in result.text):
  212. result.text.removeSuffix(" Learn more.")
  213. result.available = false
  214. proc finalizeTweet(global: GlobalObjects; id: string): Tweet =
  215. let intId = if id.len > 0: parseBiggestInt(id) else: 0
  216. result = global.tweets.getOrDefault(id, Tweet(id: intId))
  217. if result.quote.isSome:
  218. let quote = get(result.quote).id
  219. if $quote in global.tweets:
  220. result.quote = some global.tweets[$quote]
  221. else:
  222. result.quote = some Tweet()
  223. if result.retweet.isSome:
  224. let rt = get(result.retweet).id
  225. if $rt in global.tweets:
  226. result.retweet = some finalizeTweet(global, $rt)
  227. else:
  228. result.retweet = some Tweet()
  229. proc parsePin(js: JsonNode; global: GlobalObjects): Tweet =
  230. let pin = js{"pinEntry", "entry", "entryId"}.getStr
  231. if pin.len == 0: return
  232. let id = pin.getId
  233. if id notin global.tweets: return
  234. global.tweets[id].pinned = true
  235. return finalizeTweet(global, id)
  236. proc parseGlobalObjects(js: JsonNode): GlobalObjects =
  237. result = GlobalObjects()
  238. let
  239. tweets = ? js{"globalObjects", "tweets"}
  240. users = ? js{"globalObjects", "users"}
  241. for k, v in users:
  242. result.users[k] = parseUser(v, k)
  243. for k, v in tweets:
  244. var tweet = parseTweet(v)
  245. if tweet.user.id in result.users:
  246. tweet.user = result.users[tweet.user.id]
  247. result.tweets[k] = tweet
  248. proc parseThread(js: JsonNode; global: GlobalObjects): tuple[thread: Chain, self: bool] =
  249. result.thread = Chain()
  250. let thread = js{"content", "item", "content", "conversationThread"}
  251. with cursor, thread{"showMoreCursor"}:
  252. result.thread.cursor = cursor{"value"}.getStr
  253. result.thread.hasMore = true
  254. for t in thread{"conversationComponents"}:
  255. let content = t{"conversationTweetComponent", "tweet"}
  256. if content{"displayType"}.getStr == "SelfThread":
  257. result.self = true
  258. var tweet = finalizeTweet(global, content{"id"}.getStr)
  259. if not tweet.available:
  260. tweet.tombstone = getTombstone(content{"tombstone"})
  261. result.thread.content.add tweet
  262. proc parseConversation*(js: JsonNode; tweetId: string): Conversation =
  263. result = Conversation(replies: Result[Chain](beginning: true))
  264. let global = parseGlobalObjects(? js)
  265. let instructions = ? js{"timeline", "instructions"}
  266. if instructions.len == 0:
  267. return
  268. for e in instructions[0]{"addEntries", "entries"}:
  269. let entry = e{"entryId"}.getStr
  270. if "tweet" in entry or "tombstone" in entry:
  271. let tweet = finalizeTweet(global, e.getEntryId)
  272. if $tweet.id != tweetId:
  273. result.before.content.add tweet
  274. else:
  275. result.tweet = tweet
  276. elif "conversationThread" in entry:
  277. let (thread, self) = parseThread(e, global)
  278. if thread.content.len > 0:
  279. if self:
  280. result.after = thread
  281. else:
  282. result.replies.content.add thread
  283. elif "cursor-showMore" in entry:
  284. result.replies.bottom = e.getCursor
  285. elif "cursor-bottom" in entry:
  286. result.replies.bottom = e.getCursor
  287. proc parseStatus*(js: JsonNode): Tweet =
  288. with e, js{"errors"}:
  289. if e.getError == tweetNotFound:
  290. return
  291. result = parseTweet(js)
  292. if not result.isNil:
  293. result.user = parseUser(js{"user"})
  294. with quote, js{"quoted_status"}:
  295. result.quote = some parseStatus(js{"quoted_status"})
  296. proc parseInstructions[T](res: var Result[T]; global: GlobalObjects; js: JsonNode) =
  297. if js.kind != JArray or js.len == 0:
  298. return
  299. for i in js:
  300. when T is Tweet:
  301. if res.beginning and i{"pinEntry"}.notNull:
  302. with pin, parsePin(i, global):
  303. res.content.add pin
  304. with r, i{"replaceEntry", "entry"}:
  305. if "top" in r{"entryId"}.getStr:
  306. res.top = r.getCursor
  307. elif "bottom" in r{"entryId"}.getStr:
  308. res.bottom = r.getCursor
  309. proc parseTimeline*(js: JsonNode; after=""): Timeline =
  310. result = Timeline(beginning: after.len == 0)
  311. let global = parseGlobalObjects(? js)
  312. let instructions = ? js{"timeline", "instructions"}
  313. if instructions.len == 0: return
  314. result.parseInstructions(global, instructions)
  315. var entries: JsonNode
  316. for i in instructions:
  317. if "addEntries" in i:
  318. entries = i{"addEntries", "entries"}
  319. for e in ? entries:
  320. let entry = e{"entryId"}.getStr
  321. if "tweet" in entry or entry.startsWith("sq-I-t") or "tombstone" in entry:
  322. let tweet = finalizeTweet(global, e.getEntryId)
  323. if not tweet.available: continue
  324. result.content.add tweet
  325. elif "cursor-top" in entry:
  326. result.top = e.getCursor
  327. elif "cursor-bottom" in entry:
  328. result.bottom = e.getCursor
  329. elif entry.startsWith("sq-C"):
  330. with cursor, e{"content", "operation", "cursor"}:
  331. if cursor{"cursorType"}.getStr == "Bottom":
  332. result.bottom = cursor{"value"}.getStr
  333. else:
  334. result.top = cursor{"value"}.getStr
  335. proc parsePhotoRail*(js: JsonNode): PhotoRail =
  336. for tweet in js:
  337. let
  338. t = parseTweet(tweet)
  339. url = if t.photos.len > 0: t.photos[0]
  340. elif t.video.isSome: get(t.video).thumb
  341. elif t.gif.isSome: get(t.gif).thumb
  342. elif t.card.isSome: get(t.card).image
  343. else: ""
  344. if url.len == 0: continue
  345. result.add GalleryPhoto(url: url, tweetId: $t.id)