parser.nim 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. import xmltree, sequtils, strutils, json, options
  2. import types, parserutils, formatters
  3. proc parseTimelineProfile*(node: XmlNode): Profile =
  4. let profile = node.select(".ProfileHeaderCard")
  5. if profile == nil: return
  6. let pre = ".ProfileHeaderCard-"
  7. result = Profile(
  8. fullname: profile.getName(pre & "nameLink"),
  9. username: profile.getUsername(pre & "screenname"),
  10. joinDate: profile.getDate(pre & "joinDateText"),
  11. website: profile.selectAttr(pre & "urlText a", "title"),
  12. bio: profile.getBio(pre & "bio"),
  13. location: getLocation(profile),
  14. userpic: node.getAvatar(".profile-picture img"),
  15. verified: isVerified(profile),
  16. protected: isProtected(profile),
  17. banner: getTimelineBanner(node),
  18. media: getMediaCount(node)
  19. )
  20. result.getProfileStats(node.select(".ProfileNav-list"))
  21. proc parsePopupProfile*(node: XmlNode; selector=".profile-card"): Profile =
  22. let profile = node.select(selector)
  23. if profile == nil: return
  24. result = Profile(
  25. fullname: profile.getName(".fullname"),
  26. username: profile.getUsername(".username"),
  27. bio: profile.getBio(".bio", fallback=".ProfileCard-bio"),
  28. userpic: profile.getAvatar(".ProfileCard-avatarImage"),
  29. verified: isVerified(profile),
  30. protected: isProtected(profile),
  31. banner: getBanner(profile)
  32. )
  33. result.getPopupStats(profile)
  34. proc parseListProfile*(profile: XmlNode): Profile =
  35. result = Profile(
  36. fullname: profile.getName(".fullname"),
  37. username: profile.getUsername(".username"),
  38. bio: profile.getBio(".bio").stripText(),
  39. userpic: profile.getAvatar(".avatar"),
  40. verified: isVerified(profile),
  41. protected: isProtected(profile),
  42. )
  43. proc parseIntentProfile*(profile: XmlNode): Profile =
  44. result = Profile(
  45. fullname: profile.getName("a.fn.url.alternate-context"),
  46. username: profile.getUsername(".nickname"),
  47. bio: profile.getBio("p.note"),
  48. userpic: profile.select(".profile.summary").getAvatar("img.photo"),
  49. verified: profile.select("li.verified") != nil,
  50. protected: profile.select("li.protected") != nil,
  51. banner: getBanner(profile)
  52. )
  53. result.getIntentStats(profile)
  54. proc parseTweetProfile*(profile: XmlNode): Profile =
  55. result = Profile(
  56. fullname: profile.attr("data-name").stripText(),
  57. username: profile.attr("data-screen-name"),
  58. userpic: profile.getAvatar(".avatar"),
  59. verified: isVerified(profile)
  60. )
  61. proc parseQuote*(quote: XmlNode): Quote =
  62. result = Quote(
  63. id: parseBiggestInt(quote.attr("data-item-id")),
  64. text: getQuoteText(quote),
  65. reply: parseTweetReply(quote),
  66. hasThread: quote.select(".self-thread-context") != nil,
  67. available: true
  68. )
  69. result.profile = Profile(
  70. fullname: quote.selectText(".QuoteTweet-fullname").stripText(),
  71. username: quote.attr("data-screen-name"),
  72. verified: isVerified(quote)
  73. )
  74. result.getQuoteMedia(quote)
  75. proc parseTweet*(node: XmlNode): Tweet =
  76. if node == nil:
  77. return Tweet()
  78. if "withheld" in node.attr("class"):
  79. return Tweet(tombstone: getTombstone(node.selectText(".Tombstone-label")))
  80. let tweet = node.select(".tweet")
  81. if tweet == nil:
  82. return Tweet()
  83. result = Tweet(
  84. id: parseBiggestInt(tweet.attr("data-item-id")),
  85. threadId: parseBiggestInt(tweet.attr("data-conversation-id")),
  86. text: getTweetText(tweet),
  87. time: getTimestamp(tweet),
  88. shortTime: getShortTime(tweet),
  89. profile: parseTweetProfile(tweet),
  90. stats: parseTweetStats(tweet),
  91. reply: parseTweetReply(tweet),
  92. hasThread: tweet.select(".content > .self-thread-context") != nil,
  93. pinned: "pinned" in tweet.attr("class"),
  94. available: true
  95. )
  96. result.getTweetMedia(tweet)
  97. result.getTweetCard(tweet)
  98. let by = tweet.selectText(".js-retweet-text > a > b")
  99. if by.len > 0:
  100. result.retweet = some Retweet(
  101. by: stripText(by),
  102. id: parseBiggestInt(tweet.attr("data-retweet-id"))
  103. )
  104. let quote = tweet.select(".QuoteTweet-innerContainer")
  105. if quote != nil:
  106. result.quote = some parseQuote(quote)
  107. let tombstone = tweet.select(".Tombstone")
  108. if tombstone != nil:
  109. if "unavailable" in tombstone.innerText():
  110. let quote = Quote(tombstone: getTombstone(node.selectText(".Tombstone-label")))
  111. result.quote = some quote
  112. proc parseChain*(nodes: XmlNode): Chain =
  113. if nodes == nil: return
  114. result = Chain()
  115. for n in nodes.filterIt(it.kind != xnText):
  116. let class = n.attr("class").toLower()
  117. if "tombstone" in class or "unavailable" in class or "withheld" in class:
  118. result.content.add Tweet()
  119. elif "morereplies" in class:
  120. result.more = getMoreReplies(n)
  121. else:
  122. result.content.add parseTweet(n)
  123. proc parseConversation*(node: XmlNode; after: string): Conversation =
  124. let tweet = node.select(".permalink-tweet-container")
  125. if tweet == nil:
  126. return Conversation(tweet: parseTweet(node.select(".permalink-tweet-withheld")))
  127. result = Conversation(
  128. tweet: parseTweet(tweet),
  129. before: parseChain(node.select(".in-reply-to .stream-items")),
  130. replies: Result[Chain](
  131. minId: node.selectAttr(".replies-to .stream-container", "data-min-position"),
  132. hasMore: node.select(".stream-footer .has-more-items") != nil,
  133. beginning: after.len == 0
  134. )
  135. )
  136. if result.before != nil:
  137. let maxId = node.selectAttr(".in-reply-to .stream-container", "data-max-position")
  138. if maxId.len > 0:
  139. result.before.more = -1
  140. let showMore = node.selectAttr(".ThreadedConversation-showMoreThreads button",
  141. "data-cursor")
  142. if showMore.len > 0:
  143. result.replies.minId = showMore
  144. result.replies.hasMore = true
  145. let replies = node.select(".replies-to .stream-items")
  146. if replies == nil: return
  147. for i, reply in replies.filterIt(it.kind != xnText):
  148. let class = reply.attr("class").toLower()
  149. let thread = reply.select(".stream-items")
  150. if i == 0 and "self" in class:
  151. result.after = parseChain(thread)
  152. elif "lone" in class:
  153. result.replies.content.add parseChain(reply)
  154. else:
  155. result.replies.content.add parseChain(thread)
  156. proc parseTimeline*(node: XmlNode; after: string): Timeline =
  157. if node == nil: return Timeline()
  158. result = Timeline(
  159. content: parseChain(node.select(".stream > .stream-items")).content,
  160. minId: node.attr("data-min-position"),
  161. maxId: node.attr("data-max-position"),
  162. hasMore: node.select(".has-more-items") != nil,
  163. beginning: after.len == 0
  164. )
  165. proc parseVideo*(node: JsonNode; tweetId: int64): Video =
  166. let
  167. track = node{"track"}
  168. cType = track["contentType"].to(string)
  169. pType = track["playbackType"].to(string)
  170. case cType
  171. of "media_entity":
  172. result = Video(
  173. playbackType: if "mp4" in pType: mp4 else: m3u8,
  174. contentId: track["contentId"].to(string),
  175. durationMs: track["durationMs"].to(int),
  176. views: track["viewCount"].to(string),
  177. url: track["playbackUrl"].to(string),
  178. available: track{"mediaAvailability"}["status"].to(string) == "available",
  179. reason: track{"mediaAvailability"}["reason"].to(string))
  180. of "vmap":
  181. result = Video(
  182. playbackType: vmap,
  183. durationMs: track.getOrDefault("durationMs").getInt(0),
  184. url: track["vmapUrl"].to(string),
  185. available: true)
  186. else:
  187. echo "Can't parse video of type ", cType, " ", tweetId
  188. result.videoId = $tweetId
  189. result.thumb = node["posterImage"].to(string)
  190. proc parsePoll*(node: XmlNode): Poll =
  191. let
  192. choices = node.selectAll(".PollXChoice-choice")
  193. votes = node.selectText(".PollXChoice-footer--total")
  194. result.votes = votes.strip().split(" ")[0]
  195. result.status = node.selectText(".PollXChoice-footer--time")
  196. for choice in choices:
  197. for span in choice.select(".PollXChoice-choice--text").filterIt(it.kind != xnText):
  198. if span.attr("class").len == 0:
  199. result.options.add span.innerText()
  200. elif "progress" in span.attr("class"):
  201. result.values.add parseInt(span.innerText()[0 .. ^2])
  202. var highest = 0
  203. for i, n in result.values:
  204. if n > highest:
  205. highest = n
  206. result.leader = i
  207. proc parsePhotoRail*(node: XmlNode): seq[GalleryPhoto] =
  208. for img in node.selectAll(".tweet-media-img-placeholder"):
  209. result.add GalleryPhoto(
  210. url: img.attr("data-image-url"),
  211. tweetId: img.attr("data-tweet-id"),
  212. color: img.attr("background-color").replace("style: ", "")
  213. )
  214. proc parseCard*(card: var Card; node: XmlNode) =
  215. card.title = node.selectText("h2.TwitterCard-title")
  216. card.text = node.selectText("p.tcu-resetMargin")
  217. card.dest = node.selectText("span.SummaryCard-destination")
  218. if card.url.len == 0:
  219. card.url = node.selectAttr("a", "href")
  220. if card.url.len == 0:
  221. card.url = node.selectAttr(".ConvoCard-thankYouContent", "data-thank-you-url")
  222. let image = node.select(".tcu-imageWrapper img")
  223. if image != nil:
  224. # workaround for issue 11713
  225. card.image = some image.attr("data-src").replace("gname", "g&name")
  226. if card.kind == liveEvent:
  227. card.text = card.title
  228. card.title = node.selectText(".TwitterCard-attribution--category")