parser.nim 13 KB

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