api.nim 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. # SPDX-License-Identifier: AGPL-3.0-only
  2. import asyncdispatch, httpclient, strutils, sequtils, sugar
  3. import packedjson
  4. import types, query, formatters, consts, apiutils, parser, utils
  5. import experimental/parser
  6. # Helper to generate params object for GraphQL requests
  7. proc genParams(variables: string; fieldToggles = ""): seq[(string, string)] =
  8. result.add ("variables", variables)
  9. result.add ("features", gqlFeatures)
  10. if fieldToggles.len > 0:
  11. result.add ("fieldToggles", fieldToggles)
  12. proc apiUrl(endpoint, variables: string; fieldToggles = ""; skipTid = false): ApiUrl =
  13. return ApiUrl(endpoint: endpoint, params: genParams(variables, fieldToggles), skipTid: skipTid)
  14. proc apiReq(endpoint, variables: string; fieldToggles = ""; skipTid = false): ApiReq =
  15. let url = apiUrl(endpoint, variables, fieldToggles, skipTid)
  16. return ApiReq(cookie: url, oauth: url)
  17. proc cursorParam(after: string): string =
  18. ## JSON-escape the user-supplied cursor so it cannot break out of the GraphQL
  19. ## variables object (same input-validation class as the #1411 media SSRF).
  20. if after.len > 0: "\"cursor\":" & $(%after) & "," else: ""
  21. proc mediaUrl(id, cursor: string): ApiReq =
  22. result = ApiReq(
  23. cookie: apiUrl(graphUserMedia, userMediaVars % [id, cursor, "100"]),
  24. oauth: apiUrl(graphUserMediaV2, restIdVars % [id, cursor, "100"])
  25. )
  26. proc userTweetsUrl(id: string; cursor: string): ApiReq =
  27. return apiReq(graphUserTweetsV2, restIdVars % [id, cursor, "20"], userTweetsFieldToggles)
  28. proc userTweetsAndRepliesUrl(id: string; cursor: string): ApiReq =
  29. result = ApiReq(
  30. cookie: apiUrl(graphUserTweetsAndReplies, userTweetsAndRepliesVars % [id, cursor], userTweetsFieldToggles),
  31. oauth: apiUrl(graphUserTweetsAndRepliesV2, restIdVars % [id, cursor, "20"], userTweetsFieldToggles, skipTid=true)
  32. )
  33. proc tweetDetailUrl(id, cursor: string; mode = Relevance): ApiReq =
  34. return apiReq(graphTweet, tweetVars % [id, cursor, $mode])
  35. # let cookieVars = tweetDetailVars % [id, cursor]
  36. # result = ApiReq(
  37. # cookie: apiUrl(graphTweetDetail, cookieVars, tweetDetailFieldToggles),
  38. # oauth: apiUrl(graphTweet, tweetVars % [id, cursor])
  39. # )
  40. proc userUrl(username: string): ApiReq =
  41. let cookieVars = $(%*{"screen_name": username, "withGrokTranslatedBio": false})
  42. result = ApiReq(
  43. cookie: apiUrl(graphUser, cookieVars, tweetDetailFieldToggles),
  44. oauth: apiUrl(graphUserV2, $(%*{"screen_name": username}))
  45. )
  46. proc getGraphUser*(username: string): Future[User] {.async.} =
  47. if username.len == 0: return
  48. let js = await fetchRaw(userUrl(username))
  49. result = parseGraphUser(js)
  50. proc getGraphUserById*(id: string): Future[User] {.async.} =
  51. if id.len == 0 or id.any(c => not c.isDigit): return
  52. let
  53. url = apiReq(graphUserById, userByRestIdVars % id)
  54. js = await fetchRaw(url)
  55. result = parseGraphUser(js)
  56. proc getAboutAccount*(username: string): Future[AccountInfo] {.async.} =
  57. if username.len == 0: return
  58. let
  59. url = apiReq(graphAboutAccount, $(%*{"screenName": username}))
  60. js = await fetch(url)
  61. result = parseAboutAccount(js)
  62. proc restReq(endpoint: string; params: seq[(string, string)] = @[]): ApiReq =
  63. let url = ApiUrl(endpoint: endpoint, params: params)
  64. ApiReq(cookie: url, oauth: url)
  65. proc getBroadcastInfo*(id: string): Future[Broadcast] {.async.} =
  66. if id.len == 0: return
  67. let
  68. req = apiReq(graphBroadcast, $(%*{"id": id}))
  69. js = await fetch(req)
  70. result = parseBroadcastInfo(js)
  71. proc fetchBroadcastStream*(mediaKey: string): Future[string] {.async.} =
  72. if mediaKey.len == 0: return
  73. let
  74. streamReq = restReq(restLiveStream & mediaKey)
  75. streamJs = await fetch(streamReq)
  76. result = streamJs{"source", "noRedirectPlaybackUrl"}.getStr(
  77. streamJs{"source", "location"}.getStr)
  78. proc getAudioSpace*(id: string): Future[AudioSpace] {.async.} =
  79. if id.len == 0: return
  80. let
  81. variables = %*{
  82. "id": id,
  83. "isMetatagsQuery": false,
  84. "withReplays": true,
  85. "withListeners": true
  86. }
  87. req = apiReq(graphAudioSpace, $variables)
  88. js = await fetch(req)
  89. result = parseAudioSpace(js)
  90. proc getGraphUserTweets*(id: string; kind: TimelineKind; after=""): Future[Profile] {.async.} =
  91. if id.len == 0: return
  92. let
  93. cursor = cursorParam(after)
  94. url = case kind
  95. of TimelineKind.tweets: userTweetsUrl(id, cursor)
  96. of TimelineKind.replies: userTweetsAndRepliesUrl(id, cursor)
  97. of TimelineKind.media: mediaUrl(id, cursor)
  98. js = await fetch(url)
  99. result = parseGraphTimeline(js, after)
  100. proc getGraphCommunity*(id: string): Future[Community] {.async.} =
  101. if id.len == 0: return
  102. let
  103. url = apiReq(graphCommunity, $(%*{"communityId": id}))
  104. js = await fetch(url)
  105. result = parseGraphCommunity(js)
  106. proc getGraphCommunityTweets*(id: string; rankingMode: string; after=""): Future[Timeline] {.async.} =
  107. if id.len == 0: return
  108. let
  109. cursor = cursorParam(after)
  110. url = apiReq(graphCommunityTweets, communityTweetsVars % [id, cursor, rankingMode])
  111. js = await fetch(url)
  112. result = parseGraphCommunityTimeline(js, after)
  113. proc getGraphCommunityMedia*(id: string; after=""): Future[Timeline] {.async.} =
  114. if id.len == 0: return
  115. let
  116. cursor = cursorParam(after)
  117. url = apiReq(graphCommunityMedia, communityMediaVars % [id, cursor])
  118. js = await fetch(url)
  119. result = parseGraphCommunityTimeline(js, after)
  120. proc communitySliceReq(endpoint, variables: string): ApiReq =
  121. let url = ApiUrl(endpoint: endpoint, params: @[("variables", variables)])
  122. ApiReq(cookie: url, oauth: url)
  123. proc getGraphCommunityMembers*(id: string; after=""): Future[Result[User]] {.async.} =
  124. if id.len == 0: return
  125. let
  126. cursor = if after.len > 0: $(%after) else: "null"
  127. url = communitySliceReq(graphCommunityMembers, communityMembersVars % [id, cursor])
  128. js = await fetch(url)
  129. result = parseGraphCommunityMembers(js, after)
  130. proc getGraphCommunityModerators*(id: string): Future[Result[User]] {.async.} =
  131. if id.len == 0: return
  132. let
  133. url = communitySliceReq(graphCommunityModerators, communityMembersVars % [id, "null"])
  134. js = await fetch(url)
  135. result = parseGraphCommunityMembers(js)
  136. proc getGraphCommunityHashtags*(id, hashtag: string; after=""): Future[Timeline] {.async.} =
  137. if id.len == 0 or hashtag.len == 0: return
  138. let
  139. safeTag = multiReplace(hashtag, ("\"", ""), ("\\", ""))
  140. cursor = cursorParam(after)
  141. url = apiReq(graphCommunityHashtags, communityHashtagsVars % [id, cursor, safeTag])
  142. js = await fetch(url)
  143. result = parseGraphCommunityTimeline(js, after)
  144. proc getGraphListTweets*(id: string; after=""): Future[Timeline] {.async.} =
  145. if id.len == 0: return
  146. let
  147. cursor = cursorParam(after)
  148. url = apiReq(graphListTweets, restIdVars % [id, cursor, "20"])
  149. js = await fetch(url)
  150. result = parseGraphTimeline(js, after).tweets
  151. proc getGraphListBySlug*(name, list: string): Future[List] {.async.} =
  152. let
  153. variables = %*{"screenName": name, "listSlug": list}
  154. url = apiReq(graphListBySlug, $variables)
  155. js = await fetch(url)
  156. result = parseGraphList(js)
  157. proc getGraphList*(id: string): Future[List] {.async.} =
  158. let
  159. url = apiReq(graphListById, $(%*{"listId": id}))
  160. js = await fetch(url)
  161. result = parseGraphList(js)
  162. proc getGraphListMembers*(list: List; after=""): Future[Result[User]] {.async.} =
  163. if list.id.len == 0: return
  164. var
  165. variables = %*{
  166. "listId": list.id,
  167. "withBirdwatchPivots": false,
  168. "withDownvotePerspective": false,
  169. "withReactionsMetadata": false,
  170. "withReactionsPerspective": false
  171. }
  172. if after.len > 0:
  173. variables["cursor"] = % after
  174. let
  175. url = apiReq(graphListMembers, $variables)
  176. js = await fetchRaw(url)
  177. result = parseGraphListMembers(js, after)
  178. proc getGraphUserConnections(userId: string; endpoint: string; kind: QueryKind;
  179. after=""): Future[Result[User]] {.async.} =
  180. if userId.len == 0: return
  181. var variables = %*{
  182. "userId": userId,
  183. "count": 20,
  184. "includePromotedContent": false,
  185. "withGrokTranslatedBio": true
  186. }
  187. if after.len > 0:
  188. variables["cursor"] = %after
  189. let
  190. url = apiReq(endpoint, $variables)
  191. js = await fetchRaw(url)
  192. result = parseGraphFollowers(js, after, kind)
  193. proc getGraphFollowers*(userId: string; after=""): Future[Result[User]] {.async.} =
  194. result = await getGraphUserConnections(userId, graphFollowers, followers, after)
  195. proc getGraphFollowing*(userId: string; after=""): Future[Result[User]] {.async.} =
  196. result = await getGraphUserConnections(userId, graphFollowing, following, after)
  197. proc getGraphTweetResult*(id: string): Future[Tweet] {.async.} =
  198. if id.len == 0: return
  199. let
  200. url = apiReq(graphTweetResult, $(%*{"rest_id": id}))
  201. js = await fetch(url)
  202. result = parseGraphTweetResult(js)
  203. proc getTweetByRestId*(id: string): Future[Tweet] {.async.} =
  204. if id.len == 0: return
  205. let
  206. url = apiReq(graphTweetResultByRestId, tweetByRestIdVars % id, articleFieldToggles)
  207. js = await fetch(url)
  208. result = parseTweetByRestId(js)
  209. proc getGraphTweet(id: string; after=""; mode = Relevance): Future[Conversation] {.async.} =
  210. if id.len == 0: return
  211. let
  212. cursor = cursorParam(after)
  213. js = await fetch(tweetDetailUrl(id, cursor, mode))
  214. result = parseGraphConversation(js, id)
  215. proc getReplies*(id, after: string; mode = Relevance): Future[Result[Chain]] {.async.} =
  216. result = (await getGraphTweet(id, after, mode)).replies
  217. result.beginning = after.len == 0
  218. proc getTweet*(id: string; after=""; mode = Relevance): Future[Conversation] {.async.} =
  219. result = await getGraphTweet(id, mode=mode)
  220. if after.len > 0:
  221. result.replies = await getReplies(id, after, mode)
  222. proc getGraphEditHistory*(id: string): Future[EditHistory] {.async.} =
  223. if id.len == 0: return
  224. let
  225. url = apiReq(graphTweetEditHistory, tweetEditHistoryVars % id)
  226. js = await fetch(url)
  227. result = parseGraphEditHistory(js, id)
  228. proc getGraphTweetSearch*(query: Query; after=""): Future[Timeline] {.async.} =
  229. # workaround for #1372
  230. let maxId =
  231. if not after.startsWith("maxid:"): ""
  232. else: validateNumber(after[6..^1])
  233. let q = genQueryParam(query, maxId)
  234. if q.len == 0 or q == emptyQuery:
  235. return Timeline(query: query, beginning: true)
  236. let product =
  237. case query.kind
  238. of top: "Top"
  239. # profile media feeds (RSS, multi-user timelines) must stay chronological
  240. of media: (if query.fromUser.len == 0: "Media" else: "Latest")
  241. else: "Latest"
  242. var
  243. variables = %*{
  244. "rawQuery": q,
  245. "count": 20,
  246. "querySource": "typed_query",
  247. "product": product,
  248. "withGrokTranslatedBio":true,
  249. "withQuickPromoteEligibilityTweetFields":false
  250. }
  251. if after.len > 0 and maxId.len == 0:
  252. variables["cursor"] = % after
  253. let
  254. url = apiReq(graphSearchTimeline, $variables)
  255. js = await fetch(url)
  256. result = parseGraphSearch[Tweets](js, after)
  257. result.query = query
  258. # when no more items are available the API just returns the last page in
  259. # full. this detects that and clears the page instead.
  260. let prefix = min(64, min(after.len, result.bottom.len))
  261. if prefix > 0 and maxId.len == 0 and
  262. after[0..<prefix] == result.bottom[0..<prefix]:
  263. result.content.setLen(0)
  264. proc getGraphProductSearch[T](query: Query; product: string;
  265. after=""): Future[Result[T]] {.async.} =
  266. if query.text.len == 0:
  267. return Result[T](query: query, beginning: true)
  268. var
  269. variables = %*{
  270. "rawQuery": query.text,
  271. "count": 20,
  272. "querySource": "typed_query",
  273. "product": product,
  274. "withGrokTranslatedBio":true,
  275. "withQuickPromoteEligibilityTweetFields":false
  276. }
  277. if after.len > 0:
  278. variables["cursor"] = % after
  279. let
  280. url = apiReq(graphSearchTimeline, $variables)
  281. js = await fetch(url)
  282. result = parseGraphSearch[T](js, after)
  283. result.query = query
  284. proc getGraphUserSearch*(query: Query; after=""): Future[Result[User]] =
  285. getGraphProductSearch[User](query, "People", after)
  286. proc getGraphListSearch*(query: Query; after=""): Future[Result[ListSearchResult]] =
  287. getGraphProductSearch[ListSearchResult](query, "Lists", after)
  288. proc getPhotoRail*(id: string): Future[PhotoRail] {.async.} =
  289. if id.len == 0: return
  290. let js = await fetch(mediaUrl(id, ""))
  291. result = parseGraphPhotoRail(js)
  292. proc getGraphArticle*(id: string): Future[Article] {.async.} =
  293. if id.len == 0: return
  294. let
  295. url = apiReq(graphTweetResultByRestId, articleVars % id, articleFieldToggles)
  296. json = await fetchRaw(url)
  297. result = parseGraphArticle(json)
  298. proc getGraphTweetResults*(ids: seq[string]): Future[seq[Tweet]] {.async.} =
  299. if ids.len == 0: return
  300. let
  301. idsJson = "[" & ids.mapIt("\"" & it & "\"").join(",") & "]"
  302. url = apiReq(graphTweetResultsByRestIds, articleBatchVars % idsJson, articleFieldToggles)
  303. js = await fetch(url)
  304. result = parseGraphTweetResults(js)
  305. proc resolve*(url: string; prefs: Prefs): Future[string] {.async.} =
  306. let client = newAsyncHttpClient(maxRedirects=0)
  307. try:
  308. let resp = await client.request(url, HttpHead)
  309. result = resp.headers["location"].replaceUrls(prefs)
  310. except:
  311. discard
  312. finally:
  313. client.close()