api.nim 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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
  5. import experimental/parser as newParser
  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 = ""): ApiUrl =
  13. return ApiUrl(endpoint: endpoint, params: genParams(variables, fieldToggles))
  14. proc apiReq(endpoint, variables: string; fieldToggles = ""): ApiReq =
  15. let url = apiUrl(endpoint, variables, fieldToggles)
  16. return ApiReq(cookie: url, oauth: url)
  17. proc mediaUrl(id: string; cursor: string): ApiReq =
  18. result = ApiReq(
  19. cookie: apiUrl(graphUserMedia, userMediaVars % [id, cursor]),
  20. oauth: apiUrl(graphUserMediaV2, restIdVars % [id, cursor])
  21. )
  22. proc userTweetsUrl(id: string; cursor: string): ApiReq =
  23. result = ApiReq(
  24. # cookie: apiUrl(graphUserTweets, userTweetsVars % [id, cursor], userTweetsFieldToggles),
  25. oauth: apiUrl(graphUserTweetsV2, restIdVars % [id, cursor])
  26. )
  27. # might change this in the future pending testing
  28. result.cookie = result.oauth
  29. proc userTweetsAndRepliesUrl(id: string; cursor: string): ApiReq =
  30. let cookieVars = userTweetsAndRepliesVars % [id, cursor]
  31. result = ApiReq(
  32. cookie: apiUrl(graphUserTweetsAndReplies, cookieVars, userTweetsFieldToggles),
  33. oauth: apiUrl(graphUserTweetsAndRepliesV2, restIdVars % [id, cursor])
  34. )
  35. proc tweetDetailUrl(id: string; cursor: string): ApiReq =
  36. let cookieVars = tweetDetailVars % [id, cursor]
  37. result = ApiReq(
  38. # cookie: apiUrl(graphTweetDetail, cookieVars, tweetDetailFieldToggles),
  39. cookie: apiUrl(graphTweet, tweetVars % [id, cursor]),
  40. oauth: apiUrl(graphTweet, tweetVars % [id, cursor])
  41. )
  42. proc userUrl(username: string): ApiReq =
  43. let cookieVars = """{"screen_name":"$1","withGrokTranslatedBio":false}""" % username
  44. result = ApiReq(
  45. cookie: apiUrl(graphUser, cookieVars, tweetDetailFieldToggles),
  46. oauth: apiUrl(graphUserV2, """{"screen_name": "$1"}""" % username)
  47. )
  48. proc getGraphUser*(username: string): Future[User] {.async.} =
  49. if username.len == 0: return
  50. let js = await fetchRaw(userUrl(username))
  51. result = parseGraphUser(js)
  52. proc getGraphUserById*(id: string): Future[User] {.async.} =
  53. if id.len == 0 or id.any(c => not c.isDigit): return
  54. let
  55. url = apiReq(graphUserById, """{"rest_id": "$1"}""" % id)
  56. js = await fetchRaw(url)
  57. result = parseGraphUser(js)
  58. proc getGraphUserTweets*(id: string; kind: TimelineKind; after=""): Future[Profile] {.async.} =
  59. if id.len == 0: return
  60. let
  61. cursor = if after.len > 0: "\"cursor\":\"$1\"," % after else: ""
  62. url = case kind
  63. of TimelineKind.tweets: userTweetsUrl(id, cursor)
  64. of TimelineKind.replies: userTweetsAndRepliesUrl(id, cursor)
  65. of TimelineKind.media: mediaUrl(id, cursor)
  66. js = await fetch(url)
  67. result = parseGraphTimeline(js, after)
  68. proc getGraphListTweets*(id: string; after=""): Future[Timeline] {.async.} =
  69. if id.len == 0: return
  70. let
  71. cursor = if after.len > 0: "\"cursor\":\"$1\"," % after else: ""
  72. url = apiReq(graphListTweets, restIdVars % [id, cursor])
  73. js = await fetch(url)
  74. result = parseGraphTimeline(js, after).tweets
  75. proc getGraphListBySlug*(name, list: string): Future[List] {.async.} =
  76. let
  77. variables = %*{"screenName": name, "listSlug": list}
  78. url = apiReq(graphListBySlug, $variables)
  79. js = await fetch(url)
  80. result = parseGraphList(js)
  81. proc getGraphList*(id: string): Future[List] {.async.} =
  82. let
  83. url = apiReq(graphListById, """{"listId": "$1"}""" % id)
  84. js = await fetch(url)
  85. result = parseGraphList(js)
  86. proc getGraphListMembers*(list: List; after=""): Future[Result[User]] {.async.} =
  87. if list.id.len == 0: return
  88. var
  89. variables = %*{
  90. "listId": list.id,
  91. "withBirdwatchPivots": false,
  92. "withDownvotePerspective": false,
  93. "withReactionsMetadata": false,
  94. "withReactionsPerspective": false
  95. }
  96. if after.len > 0:
  97. variables["cursor"] = % after
  98. let
  99. url = apiReq(graphListMembers, $variables)
  100. js = await fetchRaw(url)
  101. result = parseGraphListMembers(js, after)
  102. proc getGraphTweetResult*(id: string): Future[Tweet] {.async.} =
  103. if id.len == 0: return
  104. let
  105. url = apiReq(graphTweetResult, """{"rest_id": "$1"}""" % id)
  106. js = await fetch(url)
  107. result = parseGraphTweetResult(js)
  108. proc getGraphTweet(id: string; after=""): Future[Conversation] {.async.} =
  109. if id.len == 0: return
  110. let
  111. cursor = if after.len > 0: "\"cursor\":\"$1\"," % after else: ""
  112. js = await fetch(tweetDetailUrl(id, cursor))
  113. result = parseGraphConversation(js, id)
  114. proc getReplies*(id, after: string): Future[Result[Chain]] {.async.} =
  115. result = (await getGraphTweet(id, after)).replies
  116. result.beginning = after.len == 0
  117. proc getTweet*(id: string; after=""): Future[Conversation] {.async.} =
  118. result = await getGraphTweet(id)
  119. if after.len > 0:
  120. result.replies = await getReplies(id, after)
  121. proc getGraphEditHistory*(id: string): Future[EditHistory] {.async.} =
  122. if id.len == 0: return
  123. let
  124. url = apiReq(graphTweetEditHistory, tweetEditHistoryVars % id)
  125. js = await fetch(url)
  126. result = parseGraphEditHistory(js, id)
  127. proc getGraphTweetSearch*(query: Query; after=""): Future[Timeline] {.async.} =
  128. let q = genQueryParam(query)
  129. if q.len == 0 or q == emptyQuery:
  130. return Timeline(query: query, beginning: true)
  131. var
  132. variables = %*{
  133. "rawQuery": q,
  134. "query_source": "typedQuery",
  135. "count": 20,
  136. "product": "Latest",
  137. "withDownvotePerspective": false,
  138. "withReactionsMetadata": false,
  139. "withReactionsPerspective": false
  140. }
  141. if after.len > 0:
  142. variables["cursor"] = % after
  143. let
  144. url = apiReq(graphSearchTimeline, $variables)
  145. js = await fetch(url)
  146. result = parseGraphSearch[Tweets](js, after)
  147. result.query = query
  148. # when no more items are available the API just returns the last page in
  149. # full. this detects that and clears the page instead.
  150. if after.len > 0 and result.bottom.len > 0 and
  151. after[0..<64] == result.bottom[0..<64]:
  152. result.content.setLen(0)
  153. proc getGraphUserSearch*(query: Query; after=""): Future[Result[User]] {.async.} =
  154. if query.text.len == 0:
  155. return Result[User](query: query, beginning: true)
  156. var
  157. variables = %*{
  158. "rawQuery": query.text,
  159. "query_source": "typedQuery",
  160. "count": 20,
  161. "product": "People",
  162. "withDownvotePerspective": false,
  163. "withReactionsMetadata": false,
  164. "withReactionsPerspective": false
  165. }
  166. if after.len > 0:
  167. variables["cursor"] = % after
  168. result.beginning = false
  169. let
  170. url = apiReq(graphSearchTimeline, $variables)
  171. js = await fetch(url)
  172. result = parseGraphSearch[User](js, after)
  173. result.query = query
  174. proc getPhotoRail*(id: string): Future[PhotoRail] {.async.} =
  175. if id.len == 0: return
  176. let js = await fetch(mediaUrl(id, ""))
  177. result = parseGraphPhotoRail(js)
  178. proc resolve*(url: string; prefs: Prefs): Future[string] {.async.} =
  179. let client = newAsyncHttpClient(maxRedirects=0)
  180. try:
  181. let resp = await client.request(url, HttpHead)
  182. result = resp.headers["location"].replaceUrls(prefs)
  183. except:
  184. discard
  185. finally:
  186. client.close()