parser.nim 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. import xmltree, sequtils, strutils, json
  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. location: profile.selectText(pre & "locationText").stripText(),
  12. website: profile.selectText(pre & "url").stripText(),
  13. bio: profile.getBio(pre & "bio"),
  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"),
  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: 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 "withheld" in node.attr("class"):
  77. return Tweet(tombstone: getTombstone(node.selectText(".Tombstone-label")))
  78. let tweet = node.select(".tweet")
  79. if tweet == nil:
  80. return Tweet()
  81. result = Tweet(
  82. id: tweet.attr("data-item-id"),
  83. threadId: tweet.attr("data-conversation-id"),
  84. text: getTweetText(tweet),
  85. time: getTimestamp(tweet),
  86. shortTime: getShortTime(tweet),
  87. profile: parseTweetProfile(tweet),
  88. stats: parseTweetStats(tweet),
  89. reply: parseTweetReply(tweet),
  90. hasThread: tweet.select(".content > .self-thread-context") != nil,
  91. pinned: "pinned" in tweet.attr("class"),
  92. available: true
  93. )
  94. result.getTweetMedia(tweet)
  95. result.getTweetCard(tweet)
  96. let by = tweet.selectText(".js-retweet-text > a > b")
  97. if by.len > 0:
  98. result.retweet = some Retweet(
  99. by: stripText(by),
  100. id: tweet.attr("data-retweet-id")
  101. )
  102. let quote = tweet.select(".QuoteTweet-innerContainer")
  103. if quote != nil:
  104. result.quote = some parseQuote(quote)
  105. let tombstone = tweet.select(".Tombstone")
  106. if tombstone != nil:
  107. if "unavailable" in tombstone.innerText():
  108. let quote = Quote(tombstone: getTombstone(node.selectText(".Tombstone-label")))
  109. result.quote = some quote
  110. proc parseThread*(nodes: XmlNode): Thread =
  111. if nodes == nil: return
  112. result = Thread()
  113. for n in nodes.filterIt(it.kind != xnText):
  114. let class = n.attr("class").toLower()
  115. if "tombstone" in class or "unavailable" in class or "withheld" in class:
  116. result.content.add Tweet()
  117. elif "morereplies" in class:
  118. result.more = getMoreReplies(n)
  119. else:
  120. result.content.add parseTweet(n)
  121. proc parseConversation*(node: XmlNode): Conversation =
  122. let tweet = node.select(".permalink-tweet-container")
  123. if tweet == nil:
  124. return Conversation(tweet: parseTweet(node.select(".permalink-tweet-withheld")))
  125. result = Conversation(
  126. tweet: parseTweet(tweet),
  127. before: parseThread(node.select(".in-reply-to .stream-items"))
  128. )
  129. let replies = node.select(".replies-to .stream-items")
  130. if replies == nil: return
  131. for i, reply in replies.filterIt(it.kind != xnText):
  132. let class = reply.attr("class").toLower()
  133. let thread = reply.select(".stream-items")
  134. if i == 0 and "self" in class:
  135. result.after = parseThread(thread)
  136. elif "lone" in class:
  137. result.replies.add parseThread(reply)
  138. else:
  139. result.replies.add parseThread(thread)
  140. proc parseTimeline*(node: XmlNode; after: string): Timeline =
  141. if node == nil: return Timeline()
  142. result = Timeline(
  143. content: parseThread(node.select(".stream > .stream-items")).content,
  144. minId: node.attr("data-min-position"),
  145. maxId: node.attr("data-max-position"),
  146. hasMore: node.select(".has-more-items") != nil,
  147. beginning: after.len == 0
  148. )
  149. proc parseVideo*(node: JsonNode; tweetId: string): Video =
  150. let
  151. track = node{"track"}
  152. cType = track["contentType"].to(string)
  153. pType = track["playbackType"].to(string)
  154. case cType
  155. of "media_entity":
  156. result = Video(
  157. playbackType: if "mp4" in pType: mp4 else: m3u8,
  158. contentId: track["contentId"].to(string),
  159. durationMs: track["durationMs"].to(int),
  160. views: track["viewCount"].to(string),
  161. url: track["playbackUrl"].to(string),
  162. available: track{"mediaAvailability"}["status"].to(string) == "available",
  163. reason: track{"mediaAvailability"}["reason"].to(string))
  164. of "vmap":
  165. result = Video(
  166. playbackType: vmap,
  167. durationMs: track.getOrDefault("durationMs").getInt(0),
  168. url: track["vmapUrl"].to(string),
  169. available: true)
  170. else:
  171. echo "Can't parse video of type ", cType
  172. result.videoId = tweetId
  173. result.thumb = node["posterImage"].to(string)
  174. proc parsePoll*(node: XmlNode): Poll =
  175. let
  176. choices = node.selectAll(".PollXChoice-choice")
  177. votes = node.selectText(".PollXChoice-footer--total")
  178. result.votes = votes.strip().split(" ")[0]
  179. result.status = node.selectText(".PollXChoice-footer--time")
  180. for choice in choices:
  181. for span in choice.select(".PollXChoice-choice--text").filterIt(it.kind != xnText):
  182. if span.attr("class").len == 0:
  183. result.options.add span.innerText()
  184. elif "progress" in span.attr("class"):
  185. result.values.add parseInt(span.innerText()[0 .. ^2])
  186. var highest = 0
  187. for i, n in result.values:
  188. if n > highest:
  189. highest = n
  190. result.leader = i
  191. proc parsePhotoRail*(node: XmlNode): seq[GalleryPhoto] =
  192. for img in node.selectAll(".tweet-media-img-placeholder"):
  193. result.add GalleryPhoto(
  194. url: img.attr("data-image-url"),
  195. tweetId: img.attr("data-tweet-id"),
  196. color: img.attr("background-color").replace("style: ", "")
  197. )
  198. proc parseCard*(card: var Card; node: XmlNode) =
  199. card.title = node.selectText("h2.TwitterCard-title")
  200. card.text = node.selectText("p.tcu-resetMargin")
  201. card.dest = node.selectText("span.SummaryCard-destination")
  202. if card.url.len == 0:
  203. card.url = node.select("a").attr("href")
  204. let image = node.select(".tcu-imageWrapper img")
  205. if image != nil:
  206. # workaround for issue 11713
  207. card.image = some image.attr("data-src").replace("gname", "g&name")
  208. if card.kind == liveEvent:
  209. card.text = card.title
  210. card.title = node.selectText(".TwitterCard-attribution--category")