parser.nim 14 KB

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