parser.nim 9.1 KB

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