parser.nim 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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 parseUserLookup*(js: JsonNode; username: string): Profile =
  25. if js.isNull or js.kind == JArray and js.len == 0 or "error" in js:
  26. return Profile(username: username)
  27. result = parseProfile(js[0])
  28. proc parseGraphProfile*(js: JsonNode; username: string): Profile =
  29. if js.isNull: return
  30. with error, js{"errors"}:
  31. result = Profile(username: username)
  32. if error.getError == suspended:
  33. result.suspended = true
  34. return
  35. let user = js{"data", "user", "legacy"}
  36. let id = js{"data", "user", "rest_id"}.getStr
  37. parseProfile(user, id)
  38. proc parseGraphList*(js: JsonNode): List =
  39. if js.isNull: return
  40. var list = js{"data", "user_by_screen_name", "list"}
  41. if list.isNull:
  42. list = js{"data", "list"}
  43. if list.isNull:
  44. return
  45. result = List(
  46. id: list{"id_str"}.getStr,
  47. name: list{"name"}.getStr,
  48. username: list{"user", "legacy", "screen_name"}.getStr,
  49. userId: list{"user", "legacy", "id_str"}.getStr,
  50. description: list{"description"}.getStr,
  51. members: list{"member_count"}.getInt,
  52. banner: list{"custom_banner_media", "media_info", "url"}.getImageStr
  53. )
  54. proc parseListMembers*(js: JsonNode; cursor: string): Result[Profile] =
  55. result = Result[Profile](
  56. beginning: cursor.len == 0,
  57. query: Query(kind: userList)
  58. )
  59. if js.isNull: return
  60. result.top = js{"previous_cursor_str"}.getStr
  61. result.bottom = js{"next_cursor_str"}.getStr
  62. if result.bottom.len == 1:
  63. result.bottom.setLen 0
  64. for u in js{"users"}:
  65. result.content.add parseProfile(u)
  66. proc parsePoll(js: JsonNode): Poll =
  67. let vals = js{"binding_values"}
  68. # name format is pollNchoice_*
  69. for i in '1' .. js{"name"}.getStr[4]:
  70. let choice = "choice" & i
  71. result.values.add parseInt(vals{choice & "_count"}.getStrVal("0"))
  72. result.options.add vals{choice & "_label"}.getStrVal
  73. let time = vals{"end_datetime_utc", "string_value"}.getDateTime
  74. if time > getTime():
  75. let timeLeft = $(time - getTime())
  76. result.status = timeLeft[0 ..< timeLeft.find(",")]
  77. else:
  78. result.status = "Final results"
  79. result.leader = result.values.find(max(result.values))
  80. result.votes = result.values.sum
  81. proc parseGif(js: JsonNode): Gif =
  82. result = Gif(
  83. url: js{"video_info", "variants"}[0]{"url"}.getImageStr,
  84. thumb: js{"media_url_https"}.getImageStr
  85. )
  86. proc parseVideo(js: JsonNode): Video =
  87. result = Video(
  88. videoId: js{"id_str"}.getStr,
  89. thumb: js{"media_url_https"}.getImageStr,
  90. views: js{"ext", "mediaStats", "r", "ok", "viewCount"}.getStr,
  91. available: js{"ext_media_availability", "status"}.getStr == "available",
  92. title: js{"ext_alt_text"}.getStr,
  93. durationMs: js{"duration_millis"}.getInt
  94. )
  95. with title, js{"additional_media_info", "title"}:
  96. result.title = title.getStr
  97. for v in js{"video_info", "variants"}:
  98. result.variants.add VideoVariant(
  99. videoType: parseEnum[VideoType](v{"content_type"}.getStr("summary")),
  100. bitrate: v{"bitrate"}.getInt,
  101. url: v{"url"}.getStr
  102. )
  103. proc parsePromoVideo(js: JsonNode): Video =
  104. result = Video(
  105. thumb: js{"player_image_large"}.getImageVal,
  106. available: true,
  107. durationMs: js{"content_duration_seconds"}.getStrVal("0").parseInt * 1000,
  108. playbackType: vmap,
  109. videoId: js{"player_content_id"}.getStrVal(js{"card_id"}.getStrVal(
  110. js{"amplify_content_id"}.getStrVal())),
  111. )
  112. var variant = VideoVariant(
  113. videoType: vmap,
  114. url: js{"player_hls_url"}.getStrVal(js{"player_stream_url"}.getStrVal(
  115. js{"amplify_url_vmap"}.getStrVal()))
  116. )
  117. if "m3u8" in variant.url:
  118. variant.videoType = m3u8
  119. result.playbackType = m3u8
  120. result.variants.add variant
  121. proc parseBroadcast(js: JsonNode): Card =
  122. let image = js{"broadcast_thumbnail_large"}.getImageVal
  123. result = Card(
  124. kind: broadcast,
  125. url: js{"broadcast_url"}.getStrVal,
  126. title: js{"broadcaster_display_name"}.getStrVal,
  127. text: js{"broadcast_title"}.getStrVal,
  128. image: image,
  129. video: some Video(videoId: js{"broadcast_media_id"}.getStrVal, thumb: image)
  130. )
  131. proc parseCard(js: JsonNode; urls: JsonNode): Card =
  132. const imageTypes = ["summary_photo_image", "player_image", "promo_image",
  133. "photo_image_full_size", "thumbnail_image", "thumbnail",
  134. "event_thumbnail", "image"]
  135. let
  136. vals = ? js{"binding_values"}
  137. name = js{"name"}.getStr
  138. kind = parseEnum[CardKind](name[(name.find(":") + 1) ..< name.len])
  139. result = Card(
  140. kind: kind,
  141. url: vals.getCardUrl(kind),
  142. dest: vals.getCardDomain(kind),
  143. title: vals.getCardTitle(kind),
  144. text: vals{"description"}.getStrVal
  145. )
  146. if result.url.len == 0:
  147. result.url = js{"url"}.getStr
  148. case kind
  149. of promoVideo, promoVideoConvo, appPlayer, videoDirectMessage:
  150. result.video = some parsePromoVideo(vals)
  151. if kind == appPlayer:
  152. result.text = vals{"app_category"}.getStrVal(result.text)
  153. of broadcast:
  154. result = parseBroadcast(vals)
  155. of liveEvent:
  156. result.text = vals{"event_title"}.getStrVal
  157. of player:
  158. result.url = vals{"player_url"}.getStrVal
  159. if "youtube.com" in result.url:
  160. result.url = result.url.replace("/embed/", "/watch?v=")
  161. of unified:
  162. result.title = "This card type is not supported."
  163. else: discard
  164. for typ in imageTypes:
  165. with img, vals{typ & "_large"}:
  166. result.image = img.getImageVal
  167. break
  168. for u in ? urls:
  169. if u{"url"}.getStr == result.url:
  170. result.url = u{"expanded_url"}.getStr
  171. break
  172. if kind in {videoDirectMessage, imageDirectMessage}:
  173. result.url.setLen 0
  174. if kind in {promoImageConvo, promoImageApp, imageDirectMessage} and
  175. result.url.len == 0 or result.url.startsWith("card://"):
  176. result.url = getPicUrl(result.image)
  177. proc parseTweet(js: JsonNode): Tweet =
  178. if js.isNull: return
  179. result = Tweet(
  180. id: js{"id_str"}.getId,
  181. threadId: js{"conversation_id_str"}.getId,
  182. replyId: js{"in_reply_to_status_id_str"}.getId,
  183. text: js{"full_text"}.getStr,
  184. time: js{"created_at"}.getTime,
  185. hasThread: js{"self_thread"}.notNull,
  186. available: true,
  187. profile: Profile(id: js{"user_id_str"}.getStr),
  188. stats: TweetStats(
  189. replies: js{"reply_count"}.getInt,
  190. retweets: js{"retweet_count"}.getInt,
  191. likes: js{"favorite_count"}.getInt,
  192. )
  193. )
  194. result.expandTweetEntities(js)
  195. if js{"is_quote_status"}.getBool:
  196. result.quote = some Tweet(id: js{"quoted_status_id_str"}.getId)
  197. with rt, js{"retweeted_status_id_str"}:
  198. result.retweet = some Tweet(id: rt.getId)
  199. return
  200. with jsCard, js{"card"}:
  201. let name = jsCard{"name"}.getStr
  202. if "poll" in name:
  203. if "image" in name:
  204. result.photos.add jsCard{"binding_values", "image_large"}.getImageVal
  205. result.poll = some parsePoll(jsCard)
  206. elif name == "amplify":
  207. result.video = some(parsePromoVideo(jsCard{"binding_values"}))
  208. else:
  209. result.card = some parseCard(jsCard, js{"entities", "urls"})
  210. with jsMedia, js{"extended_entities", "media"}:
  211. for m in jsMedia:
  212. case m{"type"}.getStr
  213. of "photo":
  214. result.photos.add m{"media_url_https"}.getImageStr
  215. of "video":
  216. result.video = some(parseVideo(m))
  217. with user, m{"additional_media_info", "source_user"}:
  218. result.attribution = some(parseProfile(user))
  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. for tweet in js:
  346. let
  347. t = parseTweet(tweet)
  348. url = if t.photos.len > 0: t.photos[0]
  349. elif t.video.isSome: get(t.video).thumb
  350. elif t.gif.isSome: get(t.gif).thumb
  351. elif t.card.isSome: get(t.card).image
  352. else: ""
  353. if url.len == 0: continue
  354. result.add GalleryPhoto(url: url, tweetId: $t.id)