parser.nim 13 KB

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