parser.nim 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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. let
  77. contentType = parseEnum[VideoType](v{"content_type"}.getStr("summary"))
  78. url = v{"url"}.getStr
  79. result.variants.add VideoVariant(
  80. contentType: contentType,
  81. bitrate: v{"bitrate"}.getInt,
  82. url: url,
  83. resolution: if contentType == mp4: getMp4Resolution(url) else: 0
  84. )
  85. proc parsePromoVideo(js: JsonNode): Video =
  86. result = Video(
  87. thumb: js{"player_image_large"}.getImageVal,
  88. available: true,
  89. durationMs: js{"content_duration_seconds"}.getStrVal("0").parseInt * 1000,
  90. playbackType: vmap
  91. )
  92. var variant = VideoVariant(
  93. contentType: vmap,
  94. url: js{"player_hls_url"}.getStrVal(js{"player_stream_url"}.getStrVal(
  95. js{"amplify_url_vmap"}.getStrVal()))
  96. )
  97. if "m3u8" in variant.url:
  98. variant.contentType = m3u8
  99. result.playbackType = m3u8
  100. result.variants.add variant
  101. proc parseBroadcast(js: JsonNode): Card =
  102. let image = js{"broadcast_thumbnail_large"}.getImageVal
  103. result = Card(
  104. kind: broadcast,
  105. url: js{"broadcast_url"}.getStrVal,
  106. title: js{"broadcaster_display_name"}.getStrVal,
  107. text: js{"broadcast_title"}.getStrVal,
  108. image: image,
  109. video: some Video(thumb: image)
  110. )
  111. proc parseCard(js: JsonNode; urls: JsonNode): Card =
  112. const imageTypes = ["summary_photo_image", "player_image", "promo_image",
  113. "photo_image_full_size", "thumbnail_image", "thumbnail",
  114. "event_thumbnail", "image"]
  115. let
  116. vals = ? js{"binding_values"}
  117. name = js{"name"}.getStr
  118. kind = parseEnum[CardKind](name[(name.find(":") + 1) ..< name.len], unknown)
  119. if kind == unified:
  120. return parseUnifiedCard(vals{"unified_card", "string_value"}.getStr)
  121. result = Card(
  122. kind: kind,
  123. url: vals.getCardUrl(kind),
  124. dest: vals.getCardDomain(kind),
  125. title: vals.getCardTitle(kind),
  126. text: vals{"description"}.getStrVal
  127. )
  128. if result.url.len == 0:
  129. result.url = js{"url"}.getStr
  130. case kind
  131. of promoVideo, promoVideoConvo, appPlayer, videoDirectMessage:
  132. result.video = some parsePromoVideo(vals)
  133. if kind == appPlayer:
  134. result.text = vals{"app_category"}.getStrVal(result.text)
  135. of broadcast:
  136. result = parseBroadcast(vals)
  137. of liveEvent:
  138. result.text = vals{"event_title"}.getStrVal
  139. of player:
  140. result.url = vals{"player_url"}.getStrVal
  141. if "youtube.com" in result.url:
  142. result.url = result.url.replace("/embed/", "/watch?v=")
  143. of audiospace, unknown:
  144. result.title = "This card type is not supported."
  145. else: discard
  146. for typ in imageTypes:
  147. with img, vals{typ & "_large"}:
  148. result.image = img.getImageVal
  149. break
  150. for u in ? urls:
  151. if u{"url"}.getStr == result.url:
  152. result.url = u{"expanded_url"}.getStr
  153. break
  154. if kind in {videoDirectMessage, imageDirectMessage}:
  155. result.url.setLen 0
  156. if kind in {promoImageConvo, promoImageApp, imageDirectMessage} and
  157. result.url.len == 0 or result.url.startsWith("card://"):
  158. result.url = getPicUrl(result.image)
  159. proc parseTweet(js: JsonNode): Tweet =
  160. if js.isNull: return
  161. result = Tweet(
  162. id: js{"id_str"}.getId,
  163. threadId: js{"conversation_id_str"}.getId,
  164. replyId: js{"in_reply_to_status_id_str"}.getId,
  165. text: js{"full_text"}.getStr,
  166. time: js{"created_at"}.getTime,
  167. source: getSource(js),
  168. hasThread: js{"self_thread"}.notNull,
  169. available: true,
  170. user: User(id: js{"user_id_str"}.getStr),
  171. stats: TweetStats(
  172. replies: js{"reply_count"}.getInt,
  173. retweets: js{"retweet_count"}.getInt,
  174. likes: js{"favorite_count"}.getInt,
  175. quotes: js{"quote_count"}.getInt
  176. )
  177. )
  178. # fix for pinned threads
  179. if result.hasThread and result.threadId == 0:
  180. result.threadId = js{"self_thread", "id_str"}.getId
  181. result.expandTweetEntities(js)
  182. if js{"is_quote_status"}.getBool:
  183. result.quote = some Tweet(id: js{"quoted_status_id_str"}.getId)
  184. with rt, js{"retweeted_status_id_str"}:
  185. result.retweet = some Tweet(id: rt.getId)
  186. return
  187. with jsCard, js{"card"}:
  188. let name = jsCard{"name"}.getStr
  189. if "poll" in name:
  190. if "image" in name:
  191. result.photos.add jsCard{"binding_values", "image_large"}.getImageVal
  192. result.poll = some parsePoll(jsCard)
  193. elif name == "amplify":
  194. result.video = some(parsePromoVideo(jsCard{"binding_values"}))
  195. else:
  196. result.card = some parseCard(jsCard, js{"entities", "urls"})
  197. with jsMedia, js{"extended_entities", "media"}:
  198. for m in jsMedia:
  199. case m{"type"}.getStr
  200. of "photo":
  201. result.photos.add m{"media_url_https"}.getImageStr
  202. of "video":
  203. result.video = some(parseVideo(m))
  204. with user, m{"additional_media_info", "source_user"}:
  205. result.attribution = some(parseUser(user))
  206. of "animated_gif":
  207. result.gif = some(parseGif(m))
  208. else: discard
  209. with jsWithheld, js{"withheld_in_countries"}:
  210. let withheldInCountries: seq[string] =
  211. if jsWithheld.kind != JArray: @[]
  212. else: jsWithheld.to(seq[string])
  213. # XX - Content is withheld in all countries
  214. # XY - Content is withheld due to a DMCA request.
  215. if js{"withheld_copyright"}.getBool or
  216. withheldInCountries.len > 0 and ("XX" in withheldInCountries or
  217. "XY" in withheldInCountries or
  218. "withheld" in result.text):
  219. result.text.removeSuffix(" Learn more.")
  220. result.available = false
  221. proc finalizeTweet(global: GlobalObjects; id: string): Tweet =
  222. let intId = if id.len > 0: parseBiggestInt(id) else: 0
  223. result = global.tweets.getOrDefault(id, Tweet(id: intId))
  224. if result.quote.isSome:
  225. let quote = get(result.quote).id
  226. if $quote in global.tweets:
  227. result.quote = some global.tweets[$quote]
  228. else:
  229. result.quote = some Tweet()
  230. if result.retweet.isSome:
  231. let rt = get(result.retweet).id
  232. if $rt in global.tweets:
  233. result.retweet = some finalizeTweet(global, $rt)
  234. else:
  235. result.retweet = some Tweet()
  236. proc parsePin(js: JsonNode; global: GlobalObjects): Tweet =
  237. let pin = js{"pinEntry", "entry", "entryId"}.getStr
  238. if pin.len == 0: return
  239. let id = pin.getId
  240. if id notin global.tweets: return
  241. global.tweets[id].pinned = true
  242. return finalizeTweet(global, id)
  243. proc parseGlobalObjects(js: JsonNode): GlobalObjects =
  244. result = GlobalObjects()
  245. let
  246. tweets = ? js{"globalObjects", "tweets"}
  247. users = ? js{"globalObjects", "users"}
  248. for k, v in users:
  249. result.users[k] = parseUser(v, k)
  250. for k, v in tweets:
  251. var tweet = parseTweet(v)
  252. if tweet.user.id in result.users:
  253. tweet.user = result.users[tweet.user.id]
  254. result.tweets[k] = tweet
  255. proc parseThread(js: JsonNode; global: GlobalObjects): tuple[thread: Chain, self: bool] =
  256. result.thread = Chain()
  257. let thread = js{"content", "item", "content", "conversationThread"}
  258. with cursor, thread{"showMoreCursor"}:
  259. result.thread.cursor = cursor{"value"}.getStr
  260. result.thread.hasMore = true
  261. for t in thread{"conversationComponents"}:
  262. let content = t{"conversationTweetComponent", "tweet"}
  263. if content{"displayType"}.getStr == "SelfThread":
  264. result.self = true
  265. var tweet = finalizeTweet(global, content{"id"}.getStr)
  266. if not tweet.available:
  267. tweet.tombstone = getTombstone(content{"tombstone"})
  268. result.thread.content.add tweet
  269. proc parseConversation*(js: JsonNode; tweetId: string): Conversation =
  270. result = Conversation(replies: Result[Chain](beginning: true))
  271. let global = parseGlobalObjects(? js)
  272. let instructions = ? js{"timeline", "instructions"}
  273. if instructions.len == 0:
  274. return
  275. for e in instructions[0]{"addEntries", "entries"}:
  276. let entry = e{"entryId"}.getStr
  277. if "tweet" in entry or "tombstone" in entry:
  278. let tweet = finalizeTweet(global, e.getEntryId)
  279. if $tweet.id != tweetId:
  280. result.before.content.add tweet
  281. else:
  282. result.tweet = tweet
  283. elif "conversationThread" in entry:
  284. let (thread, self) = parseThread(e, global)
  285. if thread.content.len > 0:
  286. if self:
  287. result.after = thread
  288. else:
  289. result.replies.content.add thread
  290. elif "cursor-showMore" in entry:
  291. result.replies.bottom = e.getCursor
  292. elif "cursor-bottom" in entry:
  293. result.replies.bottom = e.getCursor
  294. proc parseStatus*(js: JsonNode): Tweet =
  295. with e, js{"errors"}:
  296. if e.getError == tweetNotFound:
  297. return
  298. result = parseTweet(js)
  299. if not result.isNil:
  300. result.user = parseUser(js{"user"})
  301. with quote, js{"quoted_status"}:
  302. result.quote = some parseStatus(js{"quoted_status"})
  303. proc parseInstructions[T](res: var Result[T]; global: GlobalObjects; js: JsonNode) =
  304. if js.kind != JArray or js.len == 0:
  305. return
  306. for i in js:
  307. when T is Tweet:
  308. if res.beginning and i{"pinEntry"}.notNull:
  309. with pin, parsePin(i, global):
  310. res.content.add pin
  311. with r, i{"replaceEntry", "entry"}:
  312. if "top" in r{"entryId"}.getStr:
  313. res.top = r.getCursor
  314. elif "bottom" in r{"entryId"}.getStr:
  315. res.bottom = r.getCursor
  316. proc parseTimeline*(js: JsonNode; after=""): Timeline =
  317. result = Timeline(beginning: after.len == 0)
  318. let global = parseGlobalObjects(? js)
  319. let instructions = ? js{"timeline", "instructions"}
  320. if instructions.len == 0: return
  321. result.parseInstructions(global, instructions)
  322. var entries: JsonNode
  323. for i in instructions:
  324. if "addEntries" in i:
  325. entries = i{"addEntries", "entries"}
  326. for e in ? entries:
  327. let entry = e{"entryId"}.getStr
  328. if "tweet" in entry or entry.startsWith("sq-I-t") or "tombstone" in entry:
  329. let tweet = finalizeTweet(global, e.getEntryId)
  330. if not tweet.available: continue
  331. result.content.add tweet
  332. elif "cursor-top" in entry:
  333. result.top = e.getCursor
  334. elif "cursor-bottom" in entry:
  335. result.bottom = e.getCursor
  336. elif entry.startsWith("sq-C"):
  337. with cursor, e{"content", "operation", "cursor"}:
  338. if cursor{"cursorType"}.getStr == "Bottom":
  339. result.bottom = cursor{"value"}.getStr
  340. else:
  341. result.top = cursor{"value"}.getStr
  342. proc parsePhotoRail*(js: JsonNode): PhotoRail =
  343. for tweet in js:
  344. let
  345. t = parseTweet(tweet)
  346. url = if t.photos.len > 0: t.photos[0]
  347. elif t.video.isSome: get(t.video).thumb
  348. elif t.gif.isSome: get(t.gif).thumb
  349. elif t.card.isSome: get(t.card).image
  350. else: ""
  351. if url.len == 0: continue
  352. result.add GalleryPhoto(url: url, tweetId: $t.id)