sidechat.js 2.6.4 → 2.6.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (212) hide show
  1. package/.github/workflows/static.yml +0 -0
  2. package/README.md +0 -0
  3. package/dist/classes/SidechatAPIClient.d.ts +50 -47
  4. package/dist/classes/SidechatAPIClient.d.ts.map +1 -1
  5. package/dist/classes/SidechatAPIError.d.ts +0 -0
  6. package/dist/classes/SidechatAPIError.d.ts.map +0 -0
  7. package/dist/classes/SidechatColorList.d.ts +0 -0
  8. package/dist/classes/SidechatColorList.d.ts.map +0 -0
  9. package/dist/index.cjs +1421 -1408
  10. package/dist/index.d.mts +0 -0
  11. package/dist/index.d.ts +0 -0
  12. package/dist/index.d.ts.map +0 -0
  13. package/dist/index.mjs +1421 -1408
  14. package/dist/types/SidechatTypes.d.ts +0 -0
  15. package/dist/types/SidechatTypes.d.ts.map +0 -0
  16. package/docs/sidechat.js/2.5.6/SidechatAPIClient.html +0 -0
  17. package/docs/sidechat.js/2.5.6/SidechatAPIError.html +0 -0
  18. package/docs/sidechat.js/2.5.6/SidechatColorList.html +0 -0
  19. package/docs/sidechat.js/2.5.6/classes_SidechatAPIClient.js.html +0 -0
  20. package/docs/sidechat.js/2.5.6/classes_SidechatAPIError.js.html +0 -0
  21. package/docs/sidechat.js/2.5.6/classes_SidechatColorList.js.html +0 -0
  22. package/docs/sidechat.js/2.5.6/data/search.json +0 -0
  23. package/docs/sidechat.js/2.5.6/fonts/Inconsolata-Regular.ttf +0 -0
  24. package/docs/sidechat.js/2.5.6/fonts/OpenSans-Regular.ttf +0 -0
  25. package/docs/sidechat.js/2.5.6/fonts/WorkSans-Bold.ttf +0 -0
  26. package/docs/sidechat.js/2.5.6/global.html +0 -0
  27. package/docs/sidechat.js/2.5.6/index.html +0 -0
  28. package/docs/sidechat.js/2.5.6/scripts/core.js +0 -0
  29. package/docs/sidechat.js/2.5.6/scripts/core.min.js +0 -0
  30. package/docs/sidechat.js/2.5.6/scripts/resize.js +0 -0
  31. package/docs/sidechat.js/2.5.6/scripts/search.js +0 -0
  32. package/docs/sidechat.js/2.5.6/scripts/search.min.js +0 -0
  33. package/docs/sidechat.js/2.5.6/scripts/third-party/Apache-License-2.0.txt +0 -0
  34. package/docs/sidechat.js/2.5.6/scripts/third-party/fuse.js +0 -0
  35. package/docs/sidechat.js/2.5.6/scripts/third-party/hljs-line-num-original.js +0 -0
  36. package/docs/sidechat.js/2.5.6/scripts/third-party/hljs-line-num.js +0 -0
  37. package/docs/sidechat.js/2.5.6/scripts/third-party/hljs-original.js +0 -0
  38. package/docs/sidechat.js/2.5.6/scripts/third-party/hljs.js +0 -0
  39. package/docs/sidechat.js/2.5.6/scripts/third-party/popper.js +0 -0
  40. package/docs/sidechat.js/2.5.6/scripts/third-party/tippy.js +0 -0
  41. package/docs/sidechat.js/2.5.6/scripts/third-party/tocbot.js +0 -0
  42. package/docs/sidechat.js/2.5.6/scripts/third-party/tocbot.min.js +0 -0
  43. package/docs/sidechat.js/2.5.6/styles/clean-jsdoc-theme-base.css +0 -0
  44. package/docs/sidechat.js/2.5.6/styles/clean-jsdoc-theme-dark.css +0 -0
  45. package/docs/sidechat.js/2.5.6/styles/clean-jsdoc-theme-light.css +0 -0
  46. package/docs/sidechat.js/2.5.6/styles/clean-jsdoc-theme-scrollbar.css +0 -0
  47. package/docs/sidechat.js/2.5.6/styles/clean-jsdoc-theme-without-scrollbar.min.css +0 -0
  48. package/docs/sidechat.js/2.5.6/styles/clean-jsdoc-theme.min.css +0 -0
  49. package/docs/sidechat.js/2.5.6/tutorial-Authentication.html +0 -0
  50. package/docs/sidechat.js/2.5.6/tutorial-Email Registration.html +0 -0
  51. package/docs/sidechat.js/2.5.6/types_SidechatTypes.js.html +0 -0
  52. package/docs/sidechat.js/2.6.0/SidechatAPIClient.html +0 -0
  53. package/docs/sidechat.js/2.6.0/SidechatAPIError.html +0 -0
  54. package/docs/sidechat.js/2.6.0/SidechatColorList.html +0 -0
  55. package/docs/sidechat.js/2.6.0/classes_SidechatAPIClient.js.html +0 -0
  56. package/docs/sidechat.js/2.6.0/classes_SidechatAPIError.js.html +0 -0
  57. package/docs/sidechat.js/2.6.0/classes_SidechatColorList.js.html +0 -0
  58. package/docs/sidechat.js/2.6.0/data/search.json +0 -0
  59. package/docs/sidechat.js/2.6.0/fonts/Inconsolata-Regular.ttf +0 -0
  60. package/docs/sidechat.js/2.6.0/fonts/OpenSans-Regular.ttf +0 -0
  61. package/docs/sidechat.js/2.6.0/fonts/WorkSans-Bold.ttf +0 -0
  62. package/docs/sidechat.js/2.6.0/global.html +0 -0
  63. package/docs/sidechat.js/2.6.0/index.html +0 -0
  64. package/docs/sidechat.js/2.6.0/scripts/core.js +0 -0
  65. package/docs/sidechat.js/2.6.0/scripts/core.min.js +0 -0
  66. package/docs/sidechat.js/2.6.0/scripts/resize.js +0 -0
  67. package/docs/sidechat.js/2.6.0/scripts/search.js +0 -0
  68. package/docs/sidechat.js/2.6.0/scripts/search.min.js +0 -0
  69. package/docs/sidechat.js/2.6.0/scripts/third-party/Apache-License-2.0.txt +0 -0
  70. package/docs/sidechat.js/2.6.0/scripts/third-party/fuse.js +0 -0
  71. package/docs/sidechat.js/2.6.0/scripts/third-party/hljs-line-num-original.js +0 -0
  72. package/docs/sidechat.js/2.6.0/scripts/third-party/hljs-line-num.js +0 -0
  73. package/docs/sidechat.js/2.6.0/scripts/third-party/hljs-original.js +0 -0
  74. package/docs/sidechat.js/2.6.0/scripts/third-party/hljs.js +0 -0
  75. package/docs/sidechat.js/2.6.0/scripts/third-party/popper.js +0 -0
  76. package/docs/sidechat.js/2.6.0/scripts/third-party/tippy.js +0 -0
  77. package/docs/sidechat.js/2.6.0/scripts/third-party/tocbot.js +0 -0
  78. package/docs/sidechat.js/2.6.0/scripts/third-party/tocbot.min.js +0 -0
  79. package/docs/sidechat.js/2.6.0/styles/clean-jsdoc-theme-base.css +0 -0
  80. package/docs/sidechat.js/2.6.0/styles/clean-jsdoc-theme-dark.css +0 -0
  81. package/docs/sidechat.js/2.6.0/styles/clean-jsdoc-theme-light.css +0 -0
  82. package/docs/sidechat.js/2.6.0/styles/clean-jsdoc-theme-scrollbar.css +0 -0
  83. package/docs/sidechat.js/2.6.0/styles/clean-jsdoc-theme-without-scrollbar.min.css +0 -0
  84. package/docs/sidechat.js/2.6.0/styles/clean-jsdoc-theme.min.css +0 -0
  85. package/docs/sidechat.js/2.6.0/tutorial-Authentication.html +0 -0
  86. package/docs/sidechat.js/2.6.0/tutorial-Email Registration.html +0 -0
  87. package/docs/sidechat.js/2.6.0/types_SidechatTypes.js.html +0 -0
  88. package/docs/sidechat.js/2.6.1/SidechatAPIClient.html +0 -0
  89. package/docs/sidechat.js/2.6.1/SidechatAPIError.html +0 -0
  90. package/docs/sidechat.js/2.6.1/SidechatColorList.html +0 -0
  91. package/docs/sidechat.js/2.6.1/classes_SidechatAPIClient.js.html +0 -0
  92. package/docs/sidechat.js/2.6.1/classes_SidechatAPIError.js.html +0 -0
  93. package/docs/sidechat.js/2.6.1/classes_SidechatColorList.js.html +0 -0
  94. package/docs/sidechat.js/2.6.1/data/search.json +0 -0
  95. package/docs/sidechat.js/2.6.1/fonts/Inconsolata-Regular.ttf +0 -0
  96. package/docs/sidechat.js/2.6.1/fonts/OpenSans-Regular.ttf +0 -0
  97. package/docs/sidechat.js/2.6.1/fonts/WorkSans-Bold.ttf +0 -0
  98. package/docs/sidechat.js/2.6.1/global.html +0 -0
  99. package/docs/sidechat.js/2.6.1/index.html +0 -0
  100. package/docs/sidechat.js/2.6.1/scripts/core.js +0 -0
  101. package/docs/sidechat.js/2.6.1/scripts/core.min.js +0 -0
  102. package/docs/sidechat.js/2.6.1/scripts/resize.js +0 -0
  103. package/docs/sidechat.js/2.6.1/scripts/search.js +0 -0
  104. package/docs/sidechat.js/2.6.1/scripts/search.min.js +0 -0
  105. package/docs/sidechat.js/2.6.1/scripts/third-party/Apache-License-2.0.txt +0 -0
  106. package/docs/sidechat.js/2.6.1/scripts/third-party/fuse.js +0 -0
  107. package/docs/sidechat.js/2.6.1/scripts/third-party/hljs-line-num-original.js +0 -0
  108. package/docs/sidechat.js/2.6.1/scripts/third-party/hljs-line-num.js +0 -0
  109. package/docs/sidechat.js/2.6.1/scripts/third-party/hljs-original.js +0 -0
  110. package/docs/sidechat.js/2.6.1/scripts/third-party/hljs.js +0 -0
  111. package/docs/sidechat.js/2.6.1/scripts/third-party/popper.js +0 -0
  112. package/docs/sidechat.js/2.6.1/scripts/third-party/tippy.js +0 -0
  113. package/docs/sidechat.js/2.6.1/scripts/third-party/tocbot.js +0 -0
  114. package/docs/sidechat.js/2.6.1/scripts/third-party/tocbot.min.js +0 -0
  115. package/docs/sidechat.js/2.6.1/styles/clean-jsdoc-theme-base.css +0 -0
  116. package/docs/sidechat.js/2.6.1/styles/clean-jsdoc-theme-dark.css +0 -0
  117. package/docs/sidechat.js/2.6.1/styles/clean-jsdoc-theme-light.css +0 -0
  118. package/docs/sidechat.js/2.6.1/styles/clean-jsdoc-theme-scrollbar.css +0 -0
  119. package/docs/sidechat.js/2.6.1/styles/clean-jsdoc-theme-without-scrollbar.min.css +0 -0
  120. package/docs/sidechat.js/2.6.1/styles/clean-jsdoc-theme.min.css +0 -0
  121. package/docs/sidechat.js/2.6.1/tutorial-Authentication.html +0 -0
  122. package/docs/sidechat.js/2.6.1/tutorial-Email Registration.html +0 -0
  123. package/docs/sidechat.js/2.6.1/types_SidechatTypes.js.html +0 -0
  124. package/docs/sidechat.js/2.6.4/SidechatAPIClient.html +0 -0
  125. package/docs/sidechat.js/2.6.4/SidechatAPIError.html +0 -0
  126. package/docs/sidechat.js/2.6.4/SidechatColorList.html +0 -0
  127. package/docs/sidechat.js/2.6.4/classes_SidechatAPIClient.js.html +0 -0
  128. package/docs/sidechat.js/2.6.4/classes_SidechatAPIError.js.html +0 -0
  129. package/docs/sidechat.js/2.6.4/classes_SidechatColorList.js.html +0 -0
  130. package/docs/sidechat.js/2.6.4/data/search.json +0 -0
  131. package/docs/sidechat.js/2.6.4/fonts/Inconsolata-Regular.ttf +0 -0
  132. package/docs/sidechat.js/2.6.4/fonts/OpenSans-Regular.ttf +0 -0
  133. package/docs/sidechat.js/2.6.4/fonts/WorkSans-Bold.ttf +0 -0
  134. package/docs/sidechat.js/2.6.4/global.html +0 -0
  135. package/docs/sidechat.js/2.6.4/index.html +0 -0
  136. package/docs/sidechat.js/2.6.4/scripts/core.js +0 -0
  137. package/docs/sidechat.js/2.6.4/scripts/core.min.js +0 -0
  138. package/docs/sidechat.js/2.6.4/scripts/resize.js +0 -0
  139. package/docs/sidechat.js/2.6.4/scripts/search.js +0 -0
  140. package/docs/sidechat.js/2.6.4/scripts/search.min.js +0 -0
  141. package/docs/sidechat.js/2.6.4/scripts/third-party/Apache-License-2.0.txt +0 -0
  142. package/docs/sidechat.js/2.6.4/scripts/third-party/fuse.js +0 -0
  143. package/docs/sidechat.js/2.6.4/scripts/third-party/hljs-line-num-original.js +0 -0
  144. package/docs/sidechat.js/2.6.4/scripts/third-party/hljs-line-num.js +0 -0
  145. package/docs/sidechat.js/2.6.4/scripts/third-party/hljs-original.js +0 -0
  146. package/docs/sidechat.js/2.6.4/scripts/third-party/hljs.js +0 -0
  147. package/docs/sidechat.js/2.6.4/scripts/third-party/popper.js +0 -0
  148. package/docs/sidechat.js/2.6.4/scripts/third-party/tippy.js +0 -0
  149. package/docs/sidechat.js/2.6.4/scripts/third-party/tocbot.js +0 -0
  150. package/docs/sidechat.js/2.6.4/scripts/third-party/tocbot.min.js +0 -0
  151. package/docs/sidechat.js/2.6.4/styles/clean-jsdoc-theme-base.css +0 -0
  152. package/docs/sidechat.js/2.6.4/styles/clean-jsdoc-theme-dark.css +0 -0
  153. package/docs/sidechat.js/2.6.4/styles/clean-jsdoc-theme-light.css +0 -0
  154. package/docs/sidechat.js/2.6.4/styles/clean-jsdoc-theme-scrollbar.css +0 -0
  155. package/docs/sidechat.js/2.6.4/styles/clean-jsdoc-theme-without-scrollbar.min.css +0 -0
  156. package/docs/sidechat.js/2.6.4/styles/clean-jsdoc-theme.min.css +0 -0
  157. package/docs/sidechat.js/2.6.4/tutorial-Authentication.html +0 -0
  158. package/docs/sidechat.js/2.6.4/tutorial-Email Registration.html +0 -0
  159. package/docs/sidechat.js/2.6.4/types_SidechatTypes.js.html +0 -0
  160. package/docs/sidechat.js/2.6.5/SidechatAPIClient.html +3 -0
  161. package/docs/sidechat.js/2.6.5/SidechatAPIError.html +3 -0
  162. package/docs/sidechat.js/2.6.5/SidechatColorList.html +3 -0
  163. package/docs/sidechat.js/2.6.5/classes_SidechatAPIClient.js.html +1429 -0
  164. package/docs/sidechat.js/2.6.5/classes_SidechatAPIError.js.html +16 -0
  165. package/docs/sidechat.js/2.6.5/classes_SidechatColorList.js.html +79 -0
  166. package/docs/sidechat.js/2.6.5/data/search.json +1 -0
  167. package/docs/sidechat.js/2.6.5/fonts/Inconsolata-Regular.ttf +0 -0
  168. package/docs/sidechat.js/2.6.5/fonts/OpenSans-Regular.ttf +0 -0
  169. package/docs/sidechat.js/2.6.5/fonts/WorkSans-Bold.ttf +0 -0
  170. package/docs/sidechat.js/2.6.5/global.html +3 -0
  171. package/docs/sidechat.js/2.6.5/index.html +4 -0
  172. package/docs/sidechat.js/2.6.5/scripts/core.js +726 -0
  173. package/docs/sidechat.js/2.6.5/scripts/core.min.js +23 -0
  174. package/docs/sidechat.js/2.6.5/scripts/resize.js +90 -0
  175. package/docs/sidechat.js/2.6.5/scripts/search.js +265 -0
  176. package/docs/sidechat.js/2.6.5/scripts/search.min.js +6 -0
  177. package/docs/sidechat.js/2.6.5/scripts/third-party/Apache-License-2.0.txt +202 -0
  178. package/docs/sidechat.js/2.6.5/scripts/third-party/fuse.js +9 -0
  179. package/docs/sidechat.js/2.6.5/scripts/third-party/hljs-line-num-original.js +369 -0
  180. package/docs/sidechat.js/2.6.5/scripts/third-party/hljs-line-num.js +1 -0
  181. package/docs/sidechat.js/2.6.5/scripts/third-party/hljs-original.js +5171 -0
  182. package/docs/sidechat.js/2.6.5/scripts/third-party/hljs.js +1 -0
  183. package/docs/sidechat.js/2.6.5/scripts/third-party/popper.js +5 -0
  184. package/docs/sidechat.js/2.6.5/scripts/third-party/tippy.js +1 -0
  185. package/docs/sidechat.js/2.6.5/scripts/third-party/tocbot.js +672 -0
  186. package/docs/sidechat.js/2.6.5/scripts/third-party/tocbot.min.js +1 -0
  187. package/docs/sidechat.js/2.6.5/styles/clean-jsdoc-theme-base.css +1159 -0
  188. package/docs/sidechat.js/2.6.5/styles/clean-jsdoc-theme-dark.css +412 -0
  189. package/docs/sidechat.js/2.6.5/styles/clean-jsdoc-theme-light.css +482 -0
  190. package/docs/sidechat.js/2.6.5/styles/clean-jsdoc-theme-scrollbar.css +30 -0
  191. package/docs/sidechat.js/2.6.5/styles/clean-jsdoc-theme-without-scrollbar.min.css +1 -0
  192. package/docs/sidechat.js/2.6.5/styles/clean-jsdoc-theme.min.css +1 -0
  193. package/docs/sidechat.js/2.6.5/tutorial-Authentication.html +14 -0
  194. package/docs/sidechat.js/2.6.5/tutorial-Email Registration.html +6 -0
  195. package/docs/sidechat.js/2.6.5/types_SidechatTypes.js.html +204 -0
  196. package/docs/tutorials/Authentication.md +0 -0
  197. package/docs/tutorials/Email Registration.md +0 -0
  198. package/jsdoc.json +0 -0
  199. package/package.json +1 -1
  200. package/rollup.config.mjs +0 -0
  201. package/src/classes/SidechatAPIClient.js +1426 -1414
  202. package/src/classes/SidechatAPIError.js +0 -0
  203. package/src/classes/SidechatColorList.js +0 -0
  204. package/src/index.js +0 -0
  205. package/src/tests/colorTest.js +0 -0
  206. package/src/tests/commentTest.js +0 -0
  207. package/src/tests/directMessageTest.js +0 -0
  208. package/src/tests/logInTest.js +0 -0
  209. package/src/tests/postTest.js +0 -0
  210. package/src/tests/updatesTest.js +0 -0
  211. package/src/types/SidechatTypes.js +0 -0
  212. package/tsconfig.json +0 -0
@@ -1,1414 +1,1426 @@
1
- import "../types/SidechatTypes.js";
2
- import SidechatAPIError from "../classes/SidechatAPIError.js";
3
-
4
- /**
5
- * API client class for making requests to Sidechat's private API. You'll need to [authenticate]{@tutorial Authentication} before using most of the methods.
6
- * @class
7
- * @since 2.0.0-alpha.0
8
- */
9
- class SidechatAPIClient {
10
- /**
11
- * User bearer token
12
- * @type {SidechatAuthToken}
13
- * */
14
- userToken;
15
-
16
- /**
17
- * Default headers for every API request
18
- * @type {Object}
19
- * @static
20
- * @constant
21
- */
22
- defaultHeaders = {
23
- Accept: "application/json",
24
- "Content-Type": "application/json",
25
- "App-Version": "6.0.0",
26
- Dnt: 1,
27
- };
28
-
29
- /**
30
- * Root URL for every API request
31
- * @type {String}
32
- * @default "https://api.sidechat.lol"
33
- */
34
- apiRoot = "https://api.sidechat.lol";
35
-
36
- /**
37
- * Create a new instance of the API client
38
- * @param {SidechatAuthToken} [token] - user bearer token
39
- * @param {String} rootUrl - custom API root URL for mocking or using other server
40
- */
41
- constructor(token = "", rootUrl = "") {
42
- if (token) {
43
- this.userToken = token;
44
- }
45
- if (rootUrl) {
46
- this.apiRoot = rootUrl;
47
- }
48
- }
49
-
50
- /**
51
- * Manually set the currently signed in user's token. Generally try to avoid this and instead either pass a token to the constructor or login automatically through the auth functions
52
- * @method
53
- * @param {SidechatAuthToken} token - user bearer token
54
- */
55
- setToken = (token) => {
56
- this.userToken = token;
57
- };
58
-
59
- /**
60
- * Manually set the root URL for all API requests. This can be used for mocking requests or redirecting them to a different server
61
- * @method
62
- * @param {String} url - new root URL to set
63
- * @since 2.3.9
64
- */
65
- setAPIRoot = (url) => {
66
- this.apiRoot = url;
67
- };
68
-
69
- /**
70
- * Run an arbitrary API request using the current client's authentication
71
- * @method
72
- * @param {String} endpoint - API endpoint to request (e.g. "/v1/posts")
73
- * @param {"GET"|"POST"|"PUT"|"DELETE"|"PATCH"|"OPTIONS"} [method] - HTTP method to use
74
- * @param {Object} [body] - body to send with the request
75
- * @param {Object} [headers] - custom headers to send with the request
76
- * @param {Boolean} [stripHeaders] - remove the default headers from the request
77
- * @since 2.4.9
78
- */
79
- sendRequest = (
80
- endpoint,
81
- method = "GET",
82
- body = undefined,
83
- headers = {},
84
- stripHeaders = false
85
- ) => {
86
- let requestHeaders = this.defaultHeaders;
87
- if (stripHeaders) {
88
- headers = {};
89
- }
90
- requestHeaders = { ...requestHeaders, ...headers };
91
- return fetch(`${this.apiRoot}${endpoint}`, {
92
- headers: { Authorization: `Bearer ${this.userToken}`, ...requestHeaders },
93
- body: body,
94
- method: method,
95
- });
96
- };
97
-
98
- /**
99
- * Initiate the login process with a phone number. Should be followed up with verifySMSCode().
100
- * @method
101
- * @since 1.0.0
102
- * @param {Number} phoneNumber - US phone number (WITHOUT +1) to send verification code to
103
- */
104
- loginViaSMS = async (phoneNumber) => {
105
- try {
106
- const res = await fetch(`${this.apiRoot}/v1/login_register`, {
107
- method: "POST",
108
- headers: this.defaultHeaders,
109
- body: JSON.stringify({
110
- phone_number: `+1${phoneNumber}`,
111
- version: 3,
112
- }),
113
- });
114
- const json = await res.json();
115
- return json;
116
- } catch (err) {
117
- console.error(err);
118
- throw new SidechatAPIError("Failed to request SMS verification.");
119
- }
120
- };
121
-
122
- /**
123
- * Verify the code sent via SMS with loginViaSMS(). If this function succeeds, the user will be authenticated for future requests.
124
- * @method
125
- * @since 1.0.0
126
- * @param {Number} phoneNumber - US phone number (WITHOUT +1) that verification code was sent to
127
- * @param {String} code - the verification code
128
- */
129
- verifySMSCode = async (phoneNumber, code) => {
130
- try {
131
- const res = await fetch(`${this.apiRoot}/v1/verify_phone_number`, {
132
- method: "POST",
133
- headers: this.defaultHeaders,
134
- body: JSON.stringify({
135
- phone_number: `+1${phoneNumber}`,
136
- code: code.toUpperCase(),
137
- }),
138
- });
139
- const json = await res.json();
140
- if (json?.logged_in_user?.token) {
141
- this.userToken = json.logged_in_user.token;
142
- }
143
- return json;
144
- } catch (err) {
145
- console.error(err);
146
- throw new SidechatAPIError("Failed verify this code.");
147
- }
148
- };
149
-
150
- /**
151
- * Set the user's age. If this function succeeds, the user will be authenticated for future requests.
152
- * @method
153
- * @since 1.0.0
154
- * @param {Number} age - user's age in years
155
- * @param {String} registrationID - the registration ID generated by verifySMSCode()
156
- */
157
- setAge = async (age, registrationID) => {
158
- if (age < 13) {
159
- throw new SidechatAPIError("You're too young to use Offsides.");
160
- }
161
- try {
162
- const res = await fetch(`${this.apiRoot}/v1/complete_registration`, {
163
- method: "POST",
164
- headers: this.defaultHeaders,
165
- body: JSON.stringify({
166
- age: Number(age),
167
- registration_id: registrationID,
168
- }),
169
- });
170
- const json = await res.json();
171
- if (json.token) {
172
- this.userToken = json.token;
173
- }
174
- return json;
175
- } catch (err) {
176
- console.error(err);
177
- throw new SidechatAPIError("Failed verify this code.");
178
- }
179
- };
180
-
181
- /**
182
- * Initiate the email setup process. Should be followed up with checkEmailVerification().
183
- * @method
184
- * @since 1.0.0
185
- * @param {String} email - school email address to send verification code to
186
- * @tutorial Email Registration
187
- */
188
- registerEmail = async (email) => {
189
- if (!this.userToken) {
190
- throw new SidechatAPIError("User is not authenticated.");
191
- }
192
- try {
193
- const res = await fetch(`${this.apiRoot}/v2/users/register_email`, {
194
- method: "POST",
195
- headers: {
196
- ...this.defaultHeaders,
197
- Authorization: `Bearer ${this.userToken}`,
198
- },
199
- body: JSON.stringify({
200
- email: email,
201
- }),
202
- });
203
- const json = await res.json();
204
- if (json.message) {
205
- throw new SidechatAPIError(json.message);
206
- }
207
- return json;
208
- } catch (err) {
209
- console.error(err);
210
- throw new SidechatAPIError("Failed to request email verification.");
211
- }
212
- };
213
-
214
- /**
215
- * Check is the user's email is verified.
216
- * @method
217
- * @since 1.0.0
218
- */
219
- checkEmailVerification = async () => {
220
- if (!this.userToken) {
221
- throw new SidechatAPIError("User is not authenticated.");
222
- }
223
- try {
224
- const res = await fetch(`${this.apiRoot}/v1/users/check_email_verified`, {
225
- method: "GET",
226
- headers: {
227
- ...this.defaultHeaders,
228
- Authorization: `Bearer ${this.userToken}`,
229
- },
230
- });
231
- const json = await res.json();
232
- if (json.verified_email_updates_response) {
233
- return json.verified_email_updates_response;
234
- } else if (json.changing_phone_number_verified_email_user) {
235
- return json.changing_phone_number_verified_email_user;
236
- } else {
237
- throw new SidechatAPIError(json?.message || "Email is not verified.");
238
- }
239
- } catch (err) {
240
- console.error(err);
241
- throw new SidechatAPIError("Email is not verified.");
242
- }
243
- };
244
-
245
- /**
246
- * Set the device ID of the current user
247
- * @method
248
- * @since 1.0.0
249
- * @param {String} deviceId - the device ID to set
250
- */
251
- setDeviceID = async (deviceID) => {
252
- if (!this.userToken) {
253
- throw new SidechatAPIError("User is not authenticated.");
254
- }
255
- try {
256
- const res = await fetch(`${this.apiRoot}/v1/register_device_token`, {
257
- method: "POST",
258
- headers: {
259
- ...this.defaultHeaders,
260
- Authorization: `Bearer ${this.userToken}`,
261
- },
262
- body: JSON.stringify({
263
- build_type: "release",
264
- bundle_id: "com.flowerave.sidechat",
265
- device_token: deviceID,
266
- }),
267
- });
268
- const json = await res.json();
269
- return json;
270
- } catch (err) {
271
- console.error(err);
272
- throw new SidechatAPIError("Failed verify this code.");
273
- }
274
- };
275
-
276
- /**
277
- * Get updated status for user and group
278
- * @method
279
- * @since 1.0.0
280
- * @deprecated since 2.1.0, will be removed by 3.0.0. Please use `getUpdates` instead!
281
- * @param {String} [groupID] - ID of a specific group to retrieve info from. Falls back to user's primary group.
282
- */
283
- getUserAndGroup = async (groupID = "") => {
284
- const json = await this.getUpdates(groupID);
285
- return json;
286
- };
287
-
288
- /**
289
- * Get updated status for user and group
290
- * @method
291
- * @since 2.1.0
292
- * @param {String} [groupID] - ID of a specific group to retrieve info from. Falls back to user's primary group.
293
- */
294
- getUpdates = async (groupID = "") => {
295
- if (!this.userToken) {
296
- throw new SidechatAPIError("User is not authenticated.");
297
- }
298
- try {
299
- const res = await fetch(
300
- `${this.apiRoot}/v1/updates?group_id=${groupID}`,
301
- {
302
- method: "GET",
303
- headers: {
304
- ...this.defaultHeaders,
305
- Authorization: `Bearer ${this.userToken}`,
306
- },
307
- }
308
- );
309
- const json = await res.json();
310
- return json;
311
- } catch (err) {
312
- console.error(err);
313
- throw new SidechatAPIError(`Failed to get posts from group.`);
314
- }
315
- };
316
-
317
- /**
318
- * Fetches posts from the specified category in a group
319
- * @method
320
- * @since 1.0.0
321
- * @param {String} groupID - group ID
322
- * @param {"hot"|"recent"|"top"} category - category to filter posts
323
- * @param {SidechatCursorString} [cursor] - cursor string
324
- * @returns {SidechatPostsAndCursor} List of posts and cursor
325
- */
326
- getGroupPosts = async (groupID, category = "hot", cursor) => {
327
- if (!this.userToken) {
328
- throw new SidechatAPIError("User is not authenticated.");
329
- }
330
- try {
331
- const res = await fetch(
332
- `${this.apiRoot}/v1/posts?${cursor ? "cursor=" + encodeURIComponent(cursor) + "&" : ""
333
- }group_id=${groupID}&type=${category}`,
334
- {
335
- method: "GET",
336
- headers: {
337
- ...this.defaultHeaders,
338
- Authorization: `Bearer ${this.userToken}`,
339
- },
340
- }
341
- );
342
- const json = await res.json();
343
- return json;
344
- } catch (err) {
345
- console.error(err);
346
- throw new SidechatAPIError(`Failed to get posts from group.`);
347
- }
348
- };
349
-
350
- /**
351
- * Upvote or downvote, or unvote a post
352
- * @method
353
- * @since 2.0.0-alpha.0
354
- * @param {String} postID - post ID to vote on
355
- * @param {SidechatVoteString} action - whether to upvote, downvote, or reset vote
356
- */
357
- setVote = async (postID, action) => {
358
- if (!this.userToken) {
359
- throw new SidechatAPIError("User is not authenticated.");
360
- }
361
- try {
362
- const res = await fetch(`${this.apiRoot}/v1/posts/set_vote`, {
363
- method: "POST",
364
- headers: {
365
- ...this.defaultHeaders,
366
- Authorization: `Bearer ${this.userToken}`,
367
- },
368
- body: JSON.stringify({
369
- post_id: postID,
370
- vote_status: action,
371
- }),
372
- });
373
- const json = await res.json();
374
- return json;
375
- } catch (err) {
376
- console.error(err);
377
- throw new SidechatAPIError(`Failed to change the vote on post.`);
378
- }
379
- };
380
-
381
- /**
382
- * Fetches a single post with just its ID
383
- * @method
384
- * @since 2.3.0
385
- * @param {String} postID - ID of post to fetch
386
- * @param {Boolean} includeDeleted - undocumented
387
- * @returns {SidechatPostOrComment} post object
388
- */
389
- getPost = async (postID, includeDeleted = false) => {
390
- if (!this.userToken) {
391
- throw new SidechatAPIError("User is not authenticated.");
392
- }
393
- try {
394
- const res = await fetch(
395
- `${this.apiRoot}/v1/posts/get?include_deleted=${includeDeleted}&post_id=${postID}`,
396
- {
397
- method: "GET",
398
- headers: {
399
- ...this.defaultHeaders,
400
- Authorization: `Bearer ${this.userToken}`,
401
- },
402
- }
403
- );
404
- const json = await res.json();
405
- return json.post;
406
- } catch (err) {
407
- console.error(err);
408
- throw new SidechatAPIError(`Failed to get post from ID.`);
409
- }
410
- };
411
-
412
- /**
413
- * Fetches the posts or comments that the user has created
414
- * @method
415
- * @since 2.3.5
416
- * @param {"posts"|"comments"} contentType - type of user content to fetch
417
- * @returns {SidechatPostOrComment[]} post object
418
- */
419
- getUserContent = async (contentType) => {
420
- if (!this.userToken) {
421
- throw new SidechatAPIError("User is not authenticated.");
422
- }
423
- if (contentType == "posts") {
424
- contentType = "my_posts";
425
- } else if (contentType == "comments") {
426
- contentType = "my_comments";
427
- }
428
- try {
429
- const res = await fetch(`${this.apiRoot}/v1/posts&type=${contentType}`, {
430
- method: "GET",
431
- headers: {
432
- ...this.defaultHeaders,
433
- Authorization: `Bearer ${this.userToken}`,
434
- },
435
- });
436
- const json = await res.json();
437
- return json.posts;
438
- } catch (err) {
439
- console.error(err);
440
- throw new SidechatAPIError(`Failed to get content from user.`);
441
- }
442
- };
443
-
444
- /**
445
- * Get all the commments on a post
446
- * @method
447
- * @since 2.0.0-alpha.0
448
- * @param {String} postID - post ID to get comments for
449
- * @returns {SidechatPostOrComment[]} list of comments
450
- */
451
- getPostComments = async (postID) => {
452
- if (!this.userToken) {
453
- throw new SidechatAPIError("User is not authenticated.");
454
- }
455
- try {
456
- const res = await fetch(
457
- `${this.apiRoot}/v1/posts/comments/?post_id=${postID}`,
458
- {
459
- method: "GET",
460
- headers: {
461
- ...this.defaultHeaders,
462
- Authorization: `Bearer ${this.userToken}`,
463
- },
464
- }
465
- );
466
- const json = await res.json();
467
- // Function to preprocess the comments and organize them into a nested structure
468
- function preprocessComments(apiComments) {
469
- // Map to store comments by their IDs for efficient lookup
470
- const commentMap = new Map();
471
- // List to store top-level comments
472
- const topLevelComments = [];
473
-
474
- // Iterate through the API comments
475
- apiComments.forEach((comment) => {
476
- // Store the comment in the map with its ID as the key
477
- commentMap.set(comment.id, comment);
478
- // Get the parent comment using the reply_post_id
479
- const parentComment = commentMap.get(comment.reply_post_id);
480
- // Check if the comment is a top-level comment
481
- if (
482
- !parentComment ||
483
- comment.reply_post_id === comment.parent_post_id
484
- ) {
485
- // If it's a top-level comment, push it to the topLevelComments array
486
- topLevelComments.push(comment);
487
- } else {
488
- // If it's a reply, add it to the parent comment's replies array
489
- if (!parentComment.replies) parentComment.replies = [];
490
- parentComment.replies.push(comment);
491
- }
492
- });
493
-
494
- // Flatten the nested structure and return a single list of comments
495
- return flattenComments(topLevelComments);
496
- }
497
-
498
- // Function to flatten nested comments into a single list
499
- function flattenComments(comments) {
500
- // Use reduce to flatten the nested comments array into a single list
501
- return comments.reduce((flatComments, comment) => {
502
- // Push the current comment to the flatComments array
503
- flatComments.push(comment);
504
- // If the current comment has replies, recursively flatten them and push to the flatComments array
505
- if (comment.replies)
506
- flatComments.push(...flattenComments(comment.replies));
507
- // Return the flatComments array
508
- return flatComments;
509
- }, []);
510
- }
511
-
512
- const sortedComments = preprocessComments(json.posts);
513
- return sortedComments;
514
- } catch (err) {
515
- console.error(err);
516
- throw new SidechatAPIError(`Failed to get comments on post.`);
517
- }
518
- };
519
-
520
- /**
521
- * Gets groups to be displayed on the "Explore Groups" page
522
- * @method
523
- * @since 2.0.0-alpha.0
524
- * @param {Boolean} onePage - whether or not results should be returned as a single page
525
- * @returns {SidechatGroup[]}
526
- */
527
- getAvailableGroups = async (onePage = true) => {
528
- if (!this.userToken) {
529
- throw new SidechatAPIError("User is not authenticated.");
530
- }
531
- try {
532
- const res = await fetch(`${this.apiRoot}/v1/groups/explore`, {
533
- method: "GET",
534
- headers: {
535
- ...this.defaultHeaders,
536
- "App-Version": onePage ? "0" : this.defaultHeaders["App-Version"],
537
- Authorization: `Bearer ${this.userToken}`,
538
- },
539
- });
540
- const json = await res.json();
541
- return await json.groups;
542
- } catch (err) {
543
- console.error(err);
544
- throw new SidechatAPIError(`Failed to get groups from explore.`);
545
- }
546
- };
547
-
548
- /**
549
- * Searches for new groups based on a query keyword
550
- * @method
551
- * @since 2.6.0
552
- * @param {String} query - the string to search for. This will be encoded, so strings with spaces and special characters are okay.
553
- * @returns {SidechatGroup[]}
554
- */
555
- searchAvailableGroups = async (query) => {
556
- if (!this.userToken) {
557
- throw new SidechatAPIError("User is not authenticated.");
558
- }
559
- try {
560
- const res = await fetch(`${this.apiRoot}/v1/groups/explore/search?term=${encodeURIComponent(query)}`, {
561
- method: "GET",
562
- headers: {
563
- ...this.defaultHeaders,
564
- Authorization: `Bearer ${this.userToken}`,
565
- },
566
- });
567
- const json = await res.json();
568
- return await json.results;
569
- } catch (err) {
570
- console.error(err);
571
- throw new SidechatAPIError(`Failed to search groups.`);
572
- }
573
- };
574
-
575
- /**
576
- * Retrieves the entire accessible asset library. Be warned that as of the time of this documentation, it's a 1.5MB JSON download and this request is very expensive.
577
- * @method
578
- * @since 2.0.6
579
- * @returns {SidechatLibraryAsset[]}
580
- */
581
- getAssetLibrary = async () => {
582
- if (!this.userToken) {
583
- throw new SidechatAPIError("User is not authenticated.");
584
- }
585
- try {
586
- const res = await fetch(`${this.apiRoot}/v1/assets/library`, {
587
- method: "GET",
588
- headers: {
589
- ...this.defaultHeaders,
590
- Authorization: `Bearer ${this.userToken}`,
591
- },
592
- });
593
- const json = await res.json();
594
- return await json.items;
595
- } catch (err) {
596
- console.error(err);
597
- throw new SidechatAPIError(`Failed to get asset library.`);
598
- }
599
- };
600
-
601
- /**
602
- * Gets the current authenticated user and a list of the groups of which they are members.
603
- * @method
604
- * @since 2.1.0
605
- * @returns {SidechatCurrentUser}
606
- */
607
- getCurrentUser = async () => {
608
- if (!this.userToken) {
609
- throw new SidechatAPIError("User is not authenticated.");
610
- }
611
- try {
612
- const res = await fetch(`${this.apiRoot}/v1/users/me`, {
613
- method: "GET",
614
- headers: {
615
- ...this.defaultHeaders,
616
- Authorization: `Bearer ${this.userToken}`,
617
- },
618
- });
619
- const json = await res.json();
620
- return await json;
621
- } catch (err) {
622
- console.error(err);
623
- throw new SidechatAPIError(`Failed to get asset library.`);
624
- }
625
- };
626
-
627
- /**
628
- * Gets the metadata of a group from its ID
629
- * @method
630
- * @since 2.1.0
631
- * @param {String} [groupID] - alphanumeric ID of a group to get. Falls back to user's primary group.
632
- * @returns {SidechatGroup}
633
- */
634
- getGroupMetadata = async (groupID = "") => {
635
- if (!this.userToken) {
636
- throw new SidechatAPIError("User is not authenticated.");
637
- }
638
- try {
639
- const res = await fetch(`${this.apiRoot}/v1/groups/${groupID}`, {
640
- method: "GET",
641
- headers: {
642
- ...this.defaultHeaders,
643
- Authorization: `Bearer ${this.userToken}`,
644
- },
645
- });
646
- const json = await res.json();
647
- return await json.group;
648
- } catch (err) {
649
- console.error(err);
650
- throw new SidechatAPIError(`Failed to get group metadata.`);
651
- }
652
- };
653
-
654
- /**
655
- * Joins or leaves a group
656
- * @method
657
- * @param {String} groupID - alphanumeric ID of group to join or leave
658
- * @param {Boolean} isMember - whether or not the user should be a member of the group
659
- * @since 2.3.8
660
- */
661
- setGroupMembership = async (groupID, isMember) => {
662
- if (!this.userToken) {
663
- throw new SidechatAPIError("User is not authenticated.");
664
- }
665
- try {
666
- const res = await fetch(
667
- `${this.apiRoot}/v1/groups/${isMember ? "join" : "leave"}`,
668
- {
669
- method: "POST",
670
- headers: {
671
- ...this.defaultHeaders,
672
- Authorization: `Bearer ${this.userToken}`,
673
- },
674
- body: JSON.stringify({
675
- group_id: groupID,
676
- }),
677
- }
678
- );
679
- const json = await res.json();
680
- return await json;
681
- } catch (err) {
682
- console.error(err);
683
- throw new SidechatAPIError(`Failed to modify group membership.`);
684
- }
685
- };
686
-
687
- /**
688
- * Creates a comment on a post
689
- * @method
690
- * @since 2.2.0
691
- * @param {String} parentPostID - alphanumeric ID of post on which this comment is made
692
- * @param {String} text - text content of comment
693
- * @param {String} groupID - alphanumeric ID of group in which the parent post resides
694
- * @param {String} [replyCommentID] - alphanumeric ID of comment to reply to. Falls back to parentPostID
695
- * @param {String} [topLevelReplyID] - alphanumeric ID of the top-level comment to reply to. Used only when replying to replies. Falls back to parentPostID
696
- * @param {SidechatSimpleAsset[]} [assetList] - list of assets to attach
697
- * @param {Boolean} [disableDMs] - prevent direct messages being sent to comment's author
698
- * @param {Boolean} [anonymous] - whether or not to hide user's name and icon on comment
699
- * @returns {SidechatPostOrComment} created comment
700
- */
701
- createComment = async (
702
- parentPostID,
703
- text,
704
- groupID,
705
- replyCommentID,
706
- topLevelReplyID,
707
- assetList = [],
708
- disableDMs = false,
709
- anonymous = false
710
- ) => {
711
- if (!this.userToken) {
712
- throw new SidechatAPIError("User is not authenticated.");
713
- }
714
- try {
715
- const res = await fetch(`${this.apiRoot}/v1/posts`, {
716
- method: "POST",
717
- headers: {
718
- ...this.defaultHeaders,
719
- Authorization: `Bearer ${this.userToken}`,
720
- },
721
- body: JSON.stringify({
722
- type: "comment",
723
- assets: assetList,
724
- group_ids: [groupID],
725
- text: text,
726
- reply_post_id: topLevelReplyID || replyCommentID || parentPostID,
727
- reply_comment_post_id: replyCommentID || parentPostID,
728
- parent_post_id: parentPostID,
729
- dms_disabled: disableDMs,
730
- using_identity: !anonymous,
731
- }),
732
- });
733
- const json = await res.json();
734
- return await json.comment;
735
- } catch (err) {
736
- console.error(err);
737
- throw new SidechatAPIError(`Failed to post comment.`);
738
- }
739
- };
740
-
741
- /**
742
- * Creates a new post in the specified group
743
- * @method
744
- * @since 2.2.0
745
- * @param {String} text - text content of comment
746
- * @param {String} groupID - alphanumeric ID of group in which the parent post resides
747
- * @param {SidechatSimpleAsset[]} [assetList] - list of assets to attach.
748
- * @param {Boolean} [disableDMs] - prevent direct messages from being sent to post's author
749
- * @param {Boolean} [disableComments] - whether or not comments should be disabled on post
750
- * @param {Boolean} [anonymous] - whether or not to hide user's name and icon on post
751
- * @returns {SidechatPostOrComment} the created post
752
- */
753
- createPost = async (
754
- text,
755
- groupID,
756
- assetList = [],
757
- disableDMs = false,
758
- disableComments = false,
759
- anonymous = false,
760
- repostId = undefined
761
- ) => {
762
- if (!this.userToken) {
763
- throw new SidechatAPIError("User is not authenticated.");
764
- }
765
- try {
766
- const res = await fetch(`${this.apiRoot}/v1/posts`, {
767
- method: "POST",
768
- headers: {
769
- ...this.defaultHeaders,
770
- Authorization: `Bearer ${this.userToken}`,
771
- },
772
- body: JSON.stringify({
773
- type: "post",
774
- assets: assetList,
775
- group_ids: [groupID],
776
- text: text,
777
- attachments: [],
778
- dms_disabled: disableDMs,
779
- comments_disabled: disableComments,
780
- using_identity: !anonymous,
781
- quote_post_id: repostId
782
- }),
783
- });
784
- const json = await res.json();
785
- return await json.posts[0];
786
- } catch (err) {
787
- console.error(err);
788
- throw new SidechatAPIError(`Failed to make post.`);
789
- }
790
- };
791
-
792
- /**
793
- * Deletes a post or comment that the user created
794
- * @method
795
- * @since 2.2.0
796
- * @param {String} postOrCommentID - alphanumeric ID of post to delete
797
- */
798
- deletePostOrComment = async (postOrCommentID) => {
799
- if (!this.userToken) {
800
- throw new SidechatAPIError("User is not authenticated.");
801
- }
802
- try {
803
- const res = await fetch(`${this.apiRoot}/v1/posts/delete`, {
804
- method: "POST",
805
- headers: {
806
- ...this.defaultHeaders,
807
- Authorization: `Bearer ${this.userToken}`,
808
- },
809
- body: JSON.stringify({
810
- post_id: postOrCommentID,
811
- }),
812
- });
813
- const json = await res.json();
814
- return await json;
815
- } catch (err) {
816
- console.error(err);
817
- throw new SidechatAPIError(`Failed to delete post.`);
818
- }
819
- };
820
-
821
- /**
822
- * Votes on a poll attached to a post
823
- * @method
824
- * @param {String} pollId - alphanumeric ID of poll to vote on
825
- * @param {Number} choiceIndex - index of the choice to vote on
826
- * @since 2.5.4
827
- */
828
- voteOnPoll = async (pollId, choiceIndex) => {
829
- if (!this.userToken) {
830
- throw new SidechatAPIError("User is not authenticated.");
831
- }
832
- try {
833
- const res = await fetch(`${this.apiRoot}/v1/polls/vote`, {
834
- method: "POST",
835
- headers: {
836
- ...this.defaultHeaders,
837
- Authorization: `Bearer ${this.userToken}`,
838
- },
839
- body: JSON.stringify({
840
- poll_id: pollId,
841
- choice: choiceIndex,
842
- }),
843
- });
844
- const json = await res.json();
845
- return await json;
846
- } catch (err) {
847
- console.error(err);
848
- throw new SidechatAPIError(`Failed to vote on poll`);
849
- }
850
- };
851
-
852
- /**
853
- * Marks that the user has viewed results on a poll. Note that this does not actually return the results of the poll.
854
- * @method
855
- * @param {String} pollId - alphanumeric ID of poll to vote on
856
- * @since 2.5.4
857
- */
858
- viewPollResults = async (pollId) => {
859
- if (!this.userToken) {
860
- throw new SidechatAPIError("User is not authenticated.");
861
- }
862
- try {
863
- const res = await fetch(`${this.apiRoot}/v1/polls/view_results`, {
864
- method: "POST",
865
- headers: {
866
- ...this.defaultHeaders,
867
- Authorization: `Bearer ${this.userToken}`,
868
- },
869
- body: JSON.stringify({
870
- poll_id: pollId,
871
- }),
872
- });
873
- const json = await res.json();
874
- return await json;
875
- } catch (err) {
876
- console.error(err);
877
- throw new SidechatAPIError(`Failed to mark poll results as viewed.`);
878
- }
879
- };
880
-
881
- /**
882
- * Uploads an asset to AWS S3 for use in posts and comments. Currently photos only
883
- * @method
884
- * @param {String} uri - URI of the asset to upload
885
- * @param {String} mimeType - mimetype of the asset (e.g. "image/png")
886
- * @param {String} [name] - filename of the asset
887
- * @returns {String} URL of the uploaded asset
888
- * @since 2.5.1
889
- */
890
- uploadAsset = async (uri, mimeType, name = "") => {
891
- if (!this.userToken) {
892
- throw new SidechatAPIError("User is not authenticated.");
893
- }
894
-
895
- let imageType = mimeType.split("/")[1];
896
- if (!["png", "jpeg", "gif"].includes(imageType)) {
897
- throw new SidechatAPIError("Unsupported image format.");
898
- }
899
-
900
- const data = new FormData();
901
- data.append("image", {
902
- name: name,
903
- type: mimeType,
904
- uri: uri,
905
- });
906
-
907
- const urlReq = await this.sendRequest(`/v1/assets/upload_url?content_type=${imageType}`);
908
- const urlJson = await urlReq.json();
909
-
910
- try {
911
- const uploadReq = await fetch(urlJson.upload_url, {
912
- body: data.getAll("image")[0],
913
- method: "PUT",
914
- headers: {
915
- "Content-Type": mimeType,
916
- },
917
- });
918
- if (uploadReq.status == 200) {
919
- return `${this.apiRoot}/v1/assets/library/${urlJson.asset_id}`;
920
- } else {
921
- throw new SidechatAPIError(
922
- `Couldn't upload image - error ${uploadReq.status}`
923
- );
924
- }
925
- } catch (e) {
926
- throw new SidechatAPIError(e.message);
927
- }
928
- };
929
-
930
- /**
931
- * Sets the conversation icon of a user
932
- * @method
933
- * @since 2.2.1
934
- * @param {String} userID - alphanumeric ID of user
935
- * @param {String} emoji - emoji to set as icon
936
- * @param {String} primaryColor - hex string (including #) of primary color
937
- * @param {String} secondaryColor - hex string (including #) of secondary color
938
- */
939
- setUserIcon = async (userID, emoji, primaryColor, secondaryColor) => {
940
- if (!this.userToken) {
941
- throw new SidechatAPIError("User is not authenticated.");
942
- }
943
- try {
944
- const res = await fetch(`${this.apiRoot}/v1/users/${userID}`, {
945
- method: "PATCH",
946
- headers: {
947
- ...this.defaultHeaders,
948
- "App-Version": "0",
949
- Authorization: `Bearer ${this.userToken}`,
950
- },
951
- body: JSON.stringify({
952
- conversation_icon: {
953
- emoji: emoji,
954
- secondary_color: secondaryColor,
955
- is_migrated: true,
956
- color: primaryColor,
957
- },
958
- }),
959
- });
960
- const json = await res.json();
961
- return await json;
962
- } catch (err) {
963
- console.error(err);
964
- throw new SidechatAPIError(`Failed to set icon.`);
965
- }
966
- };
967
-
968
- /**
969
- * Sets the bio text of a user
970
- * @method
971
- * @since 2.5.6
972
- * @param {String} userID - alphanumeric ID of user
973
- * @param {String} bio - text to set as bio
974
- */
975
- setUserBio = async (userID, bio) => {
976
- if (!this.userToken) {
977
- throw new SidechatAPIError("User is not authenticated.");
978
- }
979
- try {
980
- const res = await fetch(`${this.apiRoot}/v1/users/${userID}`, {
981
- method: "PATCH",
982
- headers: {
983
- ...this.defaultHeaders,
984
- "App-Version": "5.4.22",
985
- Authorization: `Bearer ${this.userToken}`,
986
- },
987
- body: JSON.stringify({
988
- bio: bio
989
- }),
990
- });
991
- const json = await res.json();
992
- return await json;
993
- } catch (err) {
994
- console.error(err);
995
- throw new SidechatAPIError(`Failed to set bio.`);
996
- }
997
- };
998
-
999
- /**
1000
- * Checks if user can set their username to a string
1001
- * @method
1002
- * @since 2.3.6
1003
- * @param {String} username - string to check
1004
- * @returns {Boolean} whether or not username is valid and unused
1005
- */
1006
- checkUsername = async (username) => {
1007
- if (!this.userToken) {
1008
- throw new SidechatAPIError("User is not authenticated.");
1009
- }
1010
- try {
1011
- const res = await fetch(
1012
- `${this.apiRoot}/v1/users/username?username=${username}`,
1013
- {
1014
- method: "GET",
1015
- headers: {
1016
- ...this.defaultHeaders,
1017
- Authorization: `Bearer ${this.userToken}`,
1018
- },
1019
- }
1020
- );
1021
- if (res?.status == 200 || res?.status == 204) {
1022
- return true;
1023
- } else {
1024
- return false;
1025
- }
1026
- } catch (err) {
1027
- console.error(err);
1028
- throw new SidechatAPIError(`Failed to check username.`);
1029
- }
1030
- };
1031
-
1032
- /**
1033
- * Changes the username of the current user
1034
- * @method
1035
- * @since 2.3.6
1036
- * @param {String} userID - alphanumeric ID of user
1037
- * @param {String} username - new username to set
1038
- */
1039
- setUsername = async (userID, username) => {
1040
- if (!this.userToken) {
1041
- throw new SidechatAPIError("User is not authenticated.");
1042
- }
1043
- try {
1044
- const res = await fetch(`${this.apiRoot}/v1/users/${userID}`, {
1045
- method: "PATCH",
1046
- headers: {
1047
- ...this.defaultHeaders,
1048
- Authorization: `Bearer ${this.userToken}`,
1049
- },
1050
- body: JSON.stringify({
1051
- username: username,
1052
- }),
1053
- });
1054
- const json = await res.json();
1055
- return await json.user;
1056
- } catch (err) {
1057
- console.error(err);
1058
- throw new SidechatAPIError(`Failed to set icon.`);
1059
- }
1060
- };
1061
-
1062
- /**
1063
- * Fetches a public user profile
1064
- * @method
1065
- * @since 2.6.0
1066
- * @param {String} username - username of the user to fetch
1067
- * @returns {SidechatProfile}
1068
- */
1069
- getUserProfile = async (username) => {
1070
- if (!this.userToken) {
1071
- throw new SidechatAPIError("User is not authenticated.");
1072
- }
1073
- try {
1074
- const res = await fetch(`${this.apiRoot}/v1/groups/username?username=${username}`, {
1075
- method: "GET",
1076
- headers: {
1077
- ...this.defaultHeaders,
1078
- Authorization: `Bearer ${this.userToken}`,
1079
- }
1080
- });
1081
- const json = await res.json();
1082
- return await json.group;
1083
- } catch (err) {
1084
- console.error(err);
1085
- throw new SidechatAPIError(`Failed to set icon.`);
1086
- }
1087
- };
1088
-
1089
- /**
1090
- * Fetches a public user's posts
1091
- * @method
1092
- * @since 2.6.0
1093
- * @param {String} username - username of the user to fetch
1094
- * @returns {SidechatPostOrComment[]}
1095
- */
1096
- getUserPosts = async (username) => {
1097
- if (!this.userToken) {
1098
- throw new SidechatAPIError("User is not authenticated.");
1099
- }
1100
- try {
1101
- const res = await fetch(`${this.apiRoot}/v1/users/posts?username=${username}`, {
1102
- method: "GET",
1103
- headers: {
1104
- ...this.defaultHeaders,
1105
- Authorization: `Bearer ${this.userToken}`,
1106
- }
1107
- });
1108
- const json = await res.json();
1109
- return await json.posts;
1110
- } catch (err) {
1111
- console.error(err);
1112
- throw new SidechatAPIError(`Failed to set icon.`);
1113
- }
1114
- };
1115
-
1116
- /**
1117
- * Marks an activity item as read
1118
- * @method
1119
- * @since 2.3.2
1120
- * @param {String} activityID - alphanumeric ID of activity object
1121
- */
1122
- readActivity = async (activityID) => {
1123
- if (!this.userToken) {
1124
- throw new SidechatAPIError("User is not authenticated.");
1125
- }
1126
- try {
1127
- const res = await fetch(`${this.apiRoot}/v1/activity/seen`, {
1128
- method: "POST",
1129
- headers: {
1130
- ...this.defaultHeaders,
1131
- Authorization: `Bearer ${this.userToken}`,
1132
- },
1133
- body: JSON.stringify({
1134
- ids: [activityID],
1135
- }),
1136
- });
1137
- const json = await res.json();
1138
- return await json;
1139
- } catch (err) {
1140
- console.error(err);
1141
- throw new SidechatAPIError(`Failed to mark activity as read.`);
1142
- }
1143
- };
1144
-
1145
- /**
1146
- * Retrieves joinable group chats
1147
- * @method
1148
- * @since 2.3.5
1149
- */
1150
- getGroupChats = async () => {
1151
- if (!this.userToken) {
1152
- throw new SidechatAPIError("User is not authenticated.");
1153
- }
1154
- try {
1155
- const res = await fetch(`${this.apiRoot}/v1/chats/explore`, {
1156
- method: "GET",
1157
- headers: {
1158
- ...this.defaultHeaders,
1159
- Authorization: `Bearer ${this.userToken}`,
1160
- },
1161
- });
1162
- const json = await res.json();
1163
- return await json.chats;
1164
- } catch (err) {
1165
- console.error(err);
1166
- throw new SidechatAPIError(`Failed to get groupchats.`);
1167
- }
1168
- };
1169
-
1170
- /**
1171
- * Joins a group chat. To mimic the official client, use the user's display name and icon by default.
1172
- * @method
1173
- * @param {String} groupChatID - alphanumeric ID of group chat to join
1174
- * @param {String} displayName - display name to use in chat
1175
- * @param {String} emoji - emoji to use as icon
1176
- * @param {String} primaryColor - hex string of primary color
1177
- * @param {String} secondaryColor - hex string of secondary color
1178
- * @since 2.3.5
1179
- */
1180
- joinGroupChat = async (
1181
- groupChatID,
1182
- displayName,
1183
- emoji,
1184
- primaryColor,
1185
- secondaryColor
1186
- ) => {
1187
- if (!this.userToken) {
1188
- throw new SidechatAPIError("User is not authenticated.");
1189
- }
1190
- try {
1191
- const res = await fetch(`${this.apiRoot}/v1/chats/groups/join`, {
1192
- method: "POST",
1193
- headers: {
1194
- ...this.defaultHeaders,
1195
- Authorization: `Bearer ${this.userToken}`,
1196
- },
1197
- body: JSON.stringify({
1198
- chat_id: groupChatID,
1199
- identity: {
1200
- display_name: displayName,
1201
- emoji: emoji,
1202
- secondary_color: secondaryColor,
1203
- color: primaryColor,
1204
- },
1205
- }),
1206
- });
1207
- const json = await res.json();
1208
- return await json;
1209
- } catch (err) {
1210
- console.error(err);
1211
- throw new SidechatAPIError(`Failed to join groupchat.`);
1212
- }
1213
- };
1214
-
1215
- /**
1216
- * Gets a list of the user's direct messages
1217
- * @method
1218
- * @returns {SidechatDirectThread[]}
1219
- * @since 2.4.4
1220
- */
1221
- getDMs = async () => {
1222
- if (!this.userToken) {
1223
- throw new SidechatAPIError("User is not authenticated.");
1224
- }
1225
- try {
1226
- const res = await fetch(`${this.apiRoot}/v1/chats`, {
1227
- method: "GET",
1228
- headers: {
1229
- ...this.defaultHeaders,
1230
- Authorization: `Bearer ${this.userToken}`,
1231
- },
1232
- });
1233
- const json = await res.json();
1234
- const list = await json.chats;
1235
- let r = [];
1236
- list.forEach((o) => {
1237
- r.push(o.chat);
1238
- });
1239
- return await r;
1240
- } catch (err) {
1241
- console.error(err);
1242
- throw new SidechatAPIError(`Failed to fetch DMs.`);
1243
- }
1244
- };
1245
-
1246
- /**
1247
- * Gets a single direct message thread
1248
- * @method
1249
- * @param {String} id - alphanumeric ID of the chat to fetch
1250
- * @returns {SidechatDirectThread}
1251
- * @since 2.4.4
1252
- */
1253
- getDMThread = async (id) => {
1254
- if (!this.userToken) {
1255
- throw new SidechatAPIError("User is not authenticated.");
1256
- }
1257
- try {
1258
- const res = await fetch(
1259
- `${this.apiRoot}/v1/chats/messages?chat_id=${id}`,
1260
- {
1261
- method: "GET",
1262
- headers: {
1263
- ...this.defaultHeaders,
1264
- Authorization: `Bearer ${this.userToken}`,
1265
- },
1266
- }
1267
- );
1268
- const json = await res.json();
1269
- return await json.chat;
1270
- } catch (err) {
1271
- console.error(err);
1272
- throw new SidechatAPIError(`Failed to fetch DM thread.`);
1273
- }
1274
- };
1275
-
1276
- /**
1277
- * Sends a message to an existing direct message thread - note that you must first use startDM() to start a thread.
1278
- * @method
1279
- * @param {String} chatID - alphanumeric ID of the chat to send to
1280
- * @param {String} text - text content of message
1281
- * @param {String} clientID - alphanumeric device ID
1282
- * @param {SidechatAsset[]} assets - array of assets to send
1283
- * @param {Boolean} anonymous - whether the DM should be sent anonymously
1284
- * @since 2.4.4
1285
- */
1286
- sendDM = async (chatID, text, clientID, assets = [], anonymous = false) => {
1287
- if (!this.userToken) {
1288
- throw new SidechatAPIError("User is not authenticated.");
1289
- }
1290
- try {
1291
- const res = await fetch(`${this.apiRoot}/v1/chats/send`, {
1292
- method: "POST",
1293
- headers: {
1294
- ...this.defaultHeaders,
1295
- Authorization: `Bearer ${this.userToken}`,
1296
- },
1297
- body: JSON.stringify({
1298
- chat_id: chatID,
1299
- text: text,
1300
- client_id: clientID,
1301
- anonymous: anonymous,
1302
- assets: assets,
1303
- }),
1304
- });
1305
- const json = await res.json();
1306
- return await json;
1307
- } catch (err) {
1308
- console.error(err);
1309
- throw new SidechatAPIError(`Failed to send message.`);
1310
- }
1311
- };
1312
-
1313
- /**
1314
- * Creates a new direct message thread
1315
- * @method
1316
- * @param {String} text - text content of message
1317
- * @param {String} clientID - alphanumeric ID of devide
1318
- * @param {String} postID - alphanumeric ID of post or comment
1319
- * @param {Boolean} anonymous - whether the DM should be sent anonymously
1320
- * @param {"feed"} postContext - context of post (mostly undocumented, defaults to "feed")
1321
- * @since 2.4.4
1322
- */
1323
- startDM = async (
1324
- text,
1325
- clientID,
1326
- postID,
1327
- anonymous = false,
1328
- postContext = "feed"
1329
- ) => {
1330
- if (!this.userToken) {
1331
- throw new SidechatAPIError("User is not authenticated.");
1332
- }
1333
- try {
1334
- const res = await fetch(`${this.apiRoot}/v1/chats/start`, {
1335
- method: "POST",
1336
- headers: {
1337
- ...this.defaultHeaders,
1338
- Authorization: `Bearer ${this.userToken}`,
1339
- },
1340
- body: JSON.stringify({
1341
- text: text,
1342
- client_id: clientID,
1343
- post_id: postID,
1344
- anonymous: anonymous,
1345
- post_context: postContext,
1346
- }),
1347
- });
1348
- const json = await res.json();
1349
- return await json;
1350
- } catch (err) {
1351
- console.error(err);
1352
- throw new SidechatAPIError(`Failed to start DM.`);
1353
- }
1354
- };
1355
-
1356
- /**
1357
- * Hides posts from user
1358
- * @method
1359
- * @param {String} postID - alphanumeric ID of post to hide
1360
- * @since 2.6.2
1361
- */
1362
- hidePostsFromUser = async (postID) => {
1363
- if (!this.userToken) {
1364
- throw new SidechatAPIError("User is not authenticated.");
1365
- }
1366
- try {
1367
- const res = await fetch(`${this.apiRoot}/v1/posts/hide_posts_from_user`, {
1368
- method: "POST",
1369
- headers: {
1370
- ...this.defaultHeaders,
1371
- Authorization: `Bearer ${this.userToken}`,
1372
- },
1373
- body: JSON.stringify({
1374
- post_id: postID,
1375
- post_context: "feed",
1376
- report: false
1377
- }),
1378
- });
1379
- const json = await res.json();
1380
- return await json;
1381
- } catch (err) {
1382
- console.error(err);
1383
- throw new SidechatAPIError(`Failed to hide post.`);
1384
- }
1385
- };
1386
-
1387
- /**
1388
- * Unhides all posts from all users
1389
- * @method
1390
- * @since 2.6.2
1391
- */
1392
- unhidePostsFromAllUsers = async () => {
1393
- if (!this.userToken) {
1394
- throw new SidechatAPIError("User is not authenticated.");
1395
- }
1396
- try {
1397
- const res = await fetch(`${this.apiRoot}/v1/users/unhide_all`, {
1398
- method: "POST",
1399
- headers: {
1400
- ...this.defaultHeaders,
1401
- Authorization: `Bearer ${this.userToken}`,
1402
- },
1403
- body: JSON.stringify({}),
1404
- });
1405
- const json = await res.json();
1406
- return await json;
1407
- } catch (err) {
1408
- console.error(err);
1409
- throw new SidechatAPIError(`Failed to unhide post.`);
1410
- }
1411
- };
1412
- }
1413
-
1414
- export default SidechatAPIClient;
1
+ import SidechatAPIError from "../classes/SidechatAPIError.js";
2
+
3
+ /** @import * as types from "../types/SidechatTypes.js" */
4
+
5
+ /**
6
+ * API client class for making requests to Sidechat's private API. You'll need to [authenticate]{@tutorial Authentication} before using most of the methods.
7
+ * @class
8
+ * @since 2.0.0-alpha.0
9
+ */
10
+ class SidechatAPIClient {
11
+ /**
12
+ * User bearer token
13
+ * @type {types.SidechatAuthToken}
14
+ * */
15
+ userToken;
16
+
17
+ /**
18
+ * Default headers for every API request
19
+ * @type {Object}
20
+ * @static
21
+ * @constant
22
+ */
23
+ defaultHeaders = {
24
+ Accept: "application/json",
25
+ "Content-Type": "application/json",
26
+ "App-Version": "6.0.0",
27
+ Dnt: 1,
28
+ };
29
+
30
+ /**
31
+ * Root URL for every API request
32
+ * @type {String}
33
+ * @default "https://api.sidechat.lol"
34
+ */
35
+ apiRoot = "https://api.sidechat.lol";
36
+
37
+ /**
38
+ * Create a new instance of the API client
39
+ * @param {types.SidechatAuthToken} [token] - user bearer token
40
+ * @param {String} rootUrl - custom API root URL for mocking or using other server
41
+ */
42
+ constructor(token = "", rootUrl = "") {
43
+ if (token) {
44
+ this.userToken = token;
45
+ }
46
+ if (rootUrl) {
47
+ this.apiRoot = rootUrl;
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Manually set the currently signed in user's token. Generally try to avoid this and instead either pass a token to the constructor or login automatically through the auth functions
53
+ * @method
54
+ * @param {types.SidechatAuthToken} token - user bearer token
55
+ */
56
+ setToken = (token) => {
57
+ this.userToken = token;
58
+ };
59
+
60
+ /**
61
+ * Manually set the root URL for all API requests. This can be used for mocking requests or redirecting them to a different server
62
+ * @method
63
+ * @param {String} url - new root URL to set
64
+ * @since 2.3.9
65
+ */
66
+ setAPIRoot = (url) => {
67
+ this.apiRoot = url;
68
+ };
69
+
70
+ /**
71
+ * Run an arbitrary API request using the current client's authentication
72
+ * @method
73
+ * @param {String} endpoint - API endpoint to request (e.g. "/v1/posts")
74
+ * @param {"GET"|"POST"|"PUT"|"DELETE"|"PATCH"|"OPTIONS"} [method] - HTTP method to use
75
+ * @param {Object} [body] - body to send with the request
76
+ * @param {Object} [headers] - custom headers to send with the request
77
+ * @param {Boolean} [stripHeaders] - remove the default headers from the request
78
+ * @since 2.4.9
79
+ */
80
+ sendRequest = (
81
+ endpoint,
82
+ method = "GET",
83
+ body = undefined,
84
+ headers = {},
85
+ stripHeaders = false
86
+ ) => {
87
+ let requestHeaders = this.defaultHeaders;
88
+ if (stripHeaders) {
89
+ headers = {};
90
+ }
91
+ requestHeaders = { ...requestHeaders, ...headers };
92
+ return fetch(`${this.apiRoot}${endpoint}`, {
93
+ headers: { Authorization: `Bearer ${this.userToken}`, ...requestHeaders },
94
+ body: body,
95
+ method: method,
96
+ });
97
+ };
98
+
99
+ /**
100
+ * Initiate the login process with a phone number. Should be followed up with verifySMSCode().
101
+ * @method
102
+ * @since 1.0.0
103
+ * @param {Number} phoneNumber - US phone number (WITHOUT +1) to send verification code to
104
+ */
105
+ loginViaSMS = async (phoneNumber) => {
106
+ try {
107
+ const res = await fetch(`${this.apiRoot}/v1/login_register`, {
108
+ method: "POST",
109
+ headers: this.defaultHeaders,
110
+ body: JSON.stringify({
111
+ phone_number: `+1${phoneNumber}`,
112
+ version: 3,
113
+ }),
114
+ });
115
+ const json = await res.json();
116
+ return json;
117
+ } catch (err) {
118
+ console.error(err);
119
+ throw new SidechatAPIError("Failed to request SMS verification.");
120
+ }
121
+ };
122
+
123
+ /**
124
+ * Verify the code sent via SMS with loginViaSMS(). If this function succeeds, the user will be authenticated for future requests.
125
+ * @method
126
+ * @since 1.0.0
127
+ * @param {Number} phoneNumber - US phone number (WITHOUT +1) that verification code was sent to
128
+ * @param {String} code - the verification code
129
+ */
130
+ verifySMSCode = async (phoneNumber, code) => {
131
+ try {
132
+ const res = await fetch(`${this.apiRoot}/v1/verify_phone_number`, {
133
+ method: "POST",
134
+ headers: this.defaultHeaders,
135
+ body: JSON.stringify({
136
+ phone_number: `+1${phoneNumber}`,
137
+ code: code.toUpperCase(),
138
+ }),
139
+ });
140
+ const json = await res.json();
141
+ if (json?.logged_in_user?.token) {
142
+ this.userToken = json.logged_in_user.token;
143
+ }
144
+ return json;
145
+ } catch (err) {
146
+ console.error(err);
147
+ throw new SidechatAPIError("Failed verify this code.");
148
+ }
149
+ };
150
+
151
+ /**
152
+ * Set the user's age. If this function succeeds, the user will be authenticated for future requests.
153
+ * @method
154
+ * @since 1.0.0
155
+ * @param {Number} age - user's age in years
156
+ * @param {String} registrationID - the registration ID generated by verifySMSCode()
157
+ */
158
+ setAge = async (age, registrationID) => {
159
+ if (age < 13) {
160
+ throw new SidechatAPIError("You're too young to use Offsides.");
161
+ }
162
+ try {
163
+ const res = await fetch(`${this.apiRoot}/v1/complete_registration`, {
164
+ method: "POST",
165
+ headers: this.defaultHeaders,
166
+ body: JSON.stringify({
167
+ age: Number(age),
168
+ registration_id: registrationID,
169
+ }),
170
+ });
171
+ const json = await res.json();
172
+ if (json.token) {
173
+ this.userToken = json.token;
174
+ }
175
+ return json;
176
+ } catch (err) {
177
+ console.error(err);
178
+ throw new SidechatAPIError("Failed verify this code.");
179
+ }
180
+ };
181
+
182
+ /**
183
+ * Initiate the email setup process. Should be followed up with checkEmailVerification().
184
+ * @method
185
+ * @since 1.0.0
186
+ * @param {String} email - school email address to send verification code to
187
+ * @tutorial Email Registration
188
+ */
189
+ registerEmail = async (email) => {
190
+ if (!this.userToken) {
191
+ throw new SidechatAPIError("User is not authenticated.");
192
+ }
193
+ try {
194
+ const res = await fetch(`${this.apiRoot}/v2/users/register_email`, {
195
+ method: "POST",
196
+ headers: {
197
+ ...this.defaultHeaders,
198
+ Authorization: `Bearer ${this.userToken}`,
199
+ },
200
+ body: JSON.stringify({
201
+ email: email,
202
+ }),
203
+ });
204
+ const json = await res.json();
205
+ if (json.message) {
206
+ throw new SidechatAPIError(json.message);
207
+ }
208
+ return json;
209
+ } catch (err) {
210
+ console.error(err);
211
+ throw new SidechatAPIError("Failed to request email verification.");
212
+ }
213
+ };
214
+
215
+ /**
216
+ * Check is the user's email is verified.
217
+ * @method
218
+ * @since 1.0.0
219
+ */
220
+ checkEmailVerification = async () => {
221
+ if (!this.userToken) {
222
+ throw new SidechatAPIError("User is not authenticated.");
223
+ }
224
+ try {
225
+ const res = await fetch(`${this.apiRoot}/v1/users/check_email_verified`, {
226
+ method: "GET",
227
+ headers: {
228
+ ...this.defaultHeaders,
229
+ Authorization: `Bearer ${this.userToken}`,
230
+ },
231
+ });
232
+ const json = await res.json();
233
+ if (json.verified_email_updates_response) {
234
+ return json.verified_email_updates_response;
235
+ } else if (json.changing_phone_number_verified_email_user) {
236
+ return json.changing_phone_number_verified_email_user;
237
+ } else {
238
+ throw new SidechatAPIError(json?.message || "Email is not verified.");
239
+ }
240
+ } catch (err) {
241
+ console.error(err);
242
+ throw new SidechatAPIError("Email is not verified.");
243
+ }
244
+ };
245
+
246
+ /**
247
+ * Set the device ID of the current user
248
+ * @method
249
+ * @since 1.0.0
250
+ * @param {String} deviceId - the device ID to set
251
+ */
252
+ setDeviceID = async (deviceID) => {
253
+ if (!this.userToken) {
254
+ throw new SidechatAPIError("User is not authenticated.");
255
+ }
256
+ try {
257
+ const res = await fetch(`${this.apiRoot}/v1/register_device_token`, {
258
+ method: "POST",
259
+ headers: {
260
+ ...this.defaultHeaders,
261
+ Authorization: `Bearer ${this.userToken}`,
262
+ },
263
+ body: JSON.stringify({
264
+ build_type: "release",
265
+ bundle_id: "com.flowerave.sidechat",
266
+ device_token: deviceID,
267
+ }),
268
+ });
269
+ const json = await res.json();
270
+ return json;
271
+ } catch (err) {
272
+ console.error(err);
273
+ throw new SidechatAPIError("Failed verify this code.");
274
+ }
275
+ };
276
+
277
+ /**
278
+ * Get updated status for user and group
279
+ * @method
280
+ * @since 1.0.0
281
+ * @deprecated since 2.1.0, will be removed by 3.0.0. Please use `getUpdates` instead!
282
+ * @param {String} [groupID] - ID of a specific group to retrieve info from. Falls back to user's primary group.
283
+ */
284
+ getUserAndGroup = async (groupID = "") => {
285
+ const json = await this.getUpdates(groupID);
286
+ return json;
287
+ };
288
+
289
+ /**
290
+ * Get updated status for user and group
291
+ * @method
292
+ * @since 2.1.0
293
+ * @param {String} [groupID] - ID of a specific group to retrieve info from. Falls back to user's primary group.
294
+ */
295
+ getUpdates = async (groupID = "") => {
296
+ if (!this.userToken) {
297
+ throw new SidechatAPIError("User is not authenticated.");
298
+ }
299
+ try {
300
+ const res = await fetch(
301
+ `${this.apiRoot}/v1/updates?group_id=${groupID}`,
302
+ {
303
+ method: "GET",
304
+ headers: {
305
+ ...this.defaultHeaders,
306
+ Authorization: `Bearer ${this.userToken}`,
307
+ },
308
+ }
309
+ );
310
+ const json = await res.json();
311
+ return json;
312
+ } catch (err) {
313
+ console.error(err);
314
+ throw new SidechatAPIError(`Failed to get posts from group.`);
315
+ }
316
+ };
317
+
318
+ /**
319
+ * Fetches posts from the specified category in a group
320
+ * @method
321
+ * @since 1.0.0
322
+ * @param {String} groupID - group ID
323
+ * @param {"hot"|"recent"|"top"} category - category to filter posts
324
+ * @param {types.SidechatCursorString} [cursor] - cursor string
325
+ * @returns {Promise<types.SidechatPostsAndCursor>} List of posts and cursor
326
+ */
327
+ getGroupPosts = async (groupID, category = "hot", cursor) => {
328
+ if (!this.userToken) {
329
+ throw new SidechatAPIError("User is not authenticated.");
330
+ }
331
+ try {
332
+ const res = await fetch(
333
+ `${this.apiRoot}/v1/posts?${cursor ? "cursor=" + encodeURIComponent(cursor) + "&" : ""
334
+ }group_id=${groupID}&type=${category}`,
335
+ {
336
+ method: "GET",
337
+ headers: {
338
+ ...this.defaultHeaders,
339
+ Authorization: `Bearer ${this.userToken}`,
340
+ },
341
+ }
342
+ );
343
+ const json = await res.json();
344
+ return json;
345
+ } catch (err) {
346
+ console.error(err);
347
+ throw new SidechatAPIError(`Failed to get posts from group.`);
348
+ }
349
+ };
350
+
351
+ /**
352
+ * Upvote or downvote, or unvote a post
353
+ * @method
354
+ * @since 2.0.0-alpha.0
355
+ * @param {String} postID - post ID to vote on
356
+ * @param {types.SidechatVoteString} action - whether to upvote, downvote, or reset vote
357
+ */
358
+ setVote = async (postID, action) => {
359
+ if (!this.userToken) {
360
+ throw new SidechatAPIError("User is not authenticated.");
361
+ }
362
+ try {
363
+ const res = await fetch(`${this.apiRoot}/v1/posts/set_vote`, {
364
+ method: "POST",
365
+ headers: {
366
+ ...this.defaultHeaders,
367
+ Authorization: `Bearer ${this.userToken}`,
368
+ },
369
+ body: JSON.stringify({
370
+ post_id: postID,
371
+ vote_status: action,
372
+ }),
373
+ });
374
+ const json = await res.json();
375
+ return json;
376
+ } catch (err) {
377
+ console.error(err);
378
+ throw new SidechatAPIError(`Failed to change the vote on post.`);
379
+ }
380
+ };
381
+
382
+ /**
383
+ * Fetches a single post with just its ID
384
+ * @method
385
+ * @since 2.3.0
386
+ * @param {String} postID - ID of post to fetch
387
+ * @param {Boolean} includeDeleted - undocumented
388
+ * @returns {Promise<types.SidechatPostOrComment>} post object
389
+ */
390
+ getPost = async (postID, includeDeleted = false) => {
391
+ if (!this.userToken) {
392
+ throw new SidechatAPIError("User is not authenticated.");
393
+ }
394
+ try {
395
+ const res = await fetch(
396
+ `${this.apiRoot}/v1/posts/get?include_deleted=${includeDeleted}&post_id=${postID}`,
397
+ {
398
+ method: "GET",
399
+ headers: {
400
+ ...this.defaultHeaders,
401
+ Authorization: `Bearer ${this.userToken}`,
402
+ },
403
+ }
404
+ );
405
+ const json = await res.json();
406
+ return json.post;
407
+ } catch (err) {
408
+ console.error(err);
409
+ throw new SidechatAPIError(`Failed to get post from ID.`);
410
+ }
411
+ };
412
+
413
+ /**
414
+ * Fetches the posts or comments that the user has created
415
+ * @method
416
+ * @since 2.3.5
417
+ * @param {"posts"|"comments"} contentType - type of user content to fetch
418
+ * @returns {Promise<types.SidechatPostOrComment[]>} post object
419
+ */
420
+ getUserContent = async (contentType) => {
421
+ if (!this.userToken) {
422
+ throw new SidechatAPIError("User is not authenticated.");
423
+ }
424
+ if (contentType == "posts") {
425
+ contentType = "my_posts";
426
+ } else if (contentType == "comments") {
427
+ contentType = "my_comments";
428
+ }
429
+ try {
430
+ const res = await fetch(`${this.apiRoot}/v1/posts&type=${contentType}`, {
431
+ method: "GET",
432
+ headers: {
433
+ ...this.defaultHeaders,
434
+ Authorization: `Bearer ${this.userToken}`,
435
+ },
436
+ });
437
+ const json = await res.json();
438
+ return json.posts;
439
+ } catch (err) {
440
+ console.error(err);
441
+ throw new SidechatAPIError(`Failed to get content from user.`);
442
+ }
443
+ };
444
+
445
+ /**
446
+ * Get all the commments on a post
447
+ * @method
448
+ * @since 2.0.0-alpha.0
449
+ * @param {String} postID - post ID to get comments for
450
+ * @returns {Promise<types.SidechatPostOrComment[]>} list of comments
451
+ */
452
+ getPostComments = async (postID) => {
453
+ if (!this.userToken) {
454
+ throw new SidechatAPIError("User is not authenticated.");
455
+ }
456
+ try {
457
+ const res = await fetch(
458
+ `${this.apiRoot}/v1/posts/comments/?post_id=${postID}`,
459
+ {
460
+ method: "GET",
461
+ headers: {
462
+ ...this.defaultHeaders,
463
+ Authorization: `Bearer ${this.userToken}`,
464
+ },
465
+ }
466
+ );
467
+ const json = await res.json();
468
+ // Function to preprocess the comments and organize them into a nested structure
469
+ function preprocessComments(apiComments) {
470
+ // Map to store comments by their IDs for efficient lookup
471
+ const commentMap = new Map();
472
+ // List to store top-level comments
473
+ const topLevelComments = [];
474
+
475
+ // Iterate through the API comments
476
+ apiComments.forEach((comment) => {
477
+ // Store the comment in the map with its ID as the key
478
+ commentMap.set(comment.id, comment);
479
+ // Get the parent comment using the reply_post_id
480
+ const parentComment = commentMap.get(comment.reply_post_id);
481
+ // Check if the comment is a top-level comment
482
+ if (
483
+ !parentComment ||
484
+ comment.reply_post_id === comment.parent_post_id
485
+ ) {
486
+ // If it's a top-level comment, push it to the topLevelComments array
487
+ topLevelComments.push(comment);
488
+ } else {
489
+ // If it's a reply, add it to the parent comment's replies array
490
+ if (!parentComment.replies) parentComment.replies = [];
491
+ parentComment.replies.push(comment);
492
+ }
493
+ });
494
+
495
+ // Flatten the nested structure and return a single list of comments
496
+ return flattenComments(topLevelComments);
497
+ }
498
+
499
+ // Function to flatten nested comments into a single list
500
+ function flattenComments(comments) {
501
+ // Use reduce to flatten the nested comments array into a single list
502
+ return comments.reduce((flatComments, comment) => {
503
+ // Push the current comment to the flatComments array
504
+ flatComments.push(comment);
505
+ // If the current comment has replies, recursively flatten them and push to the flatComments array
506
+ if (comment.replies)
507
+ flatComments.push(...flattenComments(comment.replies));
508
+ // Return the flatComments array
509
+ return flatComments;
510
+ }, []);
511
+ }
512
+
513
+ const sortedComments = preprocessComments(json.posts);
514
+ return sortedComments;
515
+ } catch (err) {
516
+ console.error(err);
517
+ throw new SidechatAPIError(`Failed to get comments on post.`);
518
+ }
519
+ };
520
+
521
+ /**
522
+ * Gets groups to be displayed on the "Explore Groups" page
523
+ * @method
524
+ * @since 2.0.0-alpha.0
525
+ * @param {Boolean} onePage - whether or not results should be returned as a single page
526
+ * @returns {Promise<types.SidechatGroup[]>}
527
+ */
528
+ getAvailableGroups = async (onePage = true) => {
529
+ if (!this.userToken) {
530
+ throw new SidechatAPIError("User is not authenticated.");
531
+ }
532
+ try {
533
+ const res = await fetch(`${this.apiRoot}/v1/groups/explore`, {
534
+ method: "GET",
535
+ headers: {
536
+ ...this.defaultHeaders,
537
+ "App-Version": onePage ? "0" : this.defaultHeaders["App-Version"],
538
+ Authorization: `Bearer ${this.userToken}`,
539
+ },
540
+ });
541
+ const json = await res.json();
542
+ return await json.groups;
543
+ } catch (err) {
544
+ console.error(err);
545
+ throw new SidechatAPIError(`Failed to get groups from explore.`);
546
+ }
547
+ };
548
+
549
+ /**
550
+ * Searches for new groups based on a query keyword
551
+ * @method
552
+ * @since 2.6.0
553
+ * @param {String} query - the string to search for. This will be encoded, so strings with spaces and special characters are okay.
554
+ * @returns {Promise<types.SidechatGroup[]>}
555
+ */
556
+ searchAvailableGroups = async (query) => {
557
+ if (!this.userToken) {
558
+ throw new SidechatAPIError("User is not authenticated.");
559
+ }
560
+ try {
561
+ const res = await fetch(`${this.apiRoot}/v1/groups/explore/search?term=${encodeURIComponent(query)}`, {
562
+ method: "GET",
563
+ headers: {
564
+ ...this.defaultHeaders,
565
+ Authorization: `Bearer ${this.userToken}`,
566
+ },
567
+ });
568
+ const json = await res.json();
569
+ return await json.results;
570
+ } catch (err) {
571
+ console.error(err);
572
+ throw new SidechatAPIError(`Failed to search groups.`);
573
+ }
574
+ };
575
+
576
+ /**
577
+ * Retrieves the entire accessible asset library. Be warned that as of the time of this documentation, it's a 1.5MB JSON download and this request is very expensive.
578
+ * @method
579
+ * @since 2.0.6
580
+ * @returns {Promise<types.SidechatLibraryAsset[]>}
581
+ */
582
+ getAssetLibrary = async () => {
583
+ if (!this.userToken) {
584
+ throw new SidechatAPIError("User is not authenticated.");
585
+ }
586
+ try {
587
+ const res = await fetch(`${this.apiRoot}/v1/assets/library`, {
588
+ method: "GET",
589
+ headers: {
590
+ ...this.defaultHeaders,
591
+ Authorization: `Bearer ${this.userToken}`,
592
+ },
593
+ });
594
+ const json = await res.json();
595
+ return await json.items;
596
+ } catch (err) {
597
+ console.error(err);
598
+ throw new SidechatAPIError(`Failed to get asset library.`);
599
+ }
600
+ };
601
+
602
+ /**
603
+ * Gets the current authenticated user and a list of the groups of which they are members.
604
+ * @method
605
+ * @since 2.1.0
606
+ * @returns {Promise<types.SidechatCurrentUser>}
607
+ */
608
+ getCurrentUser = async () => {
609
+ if (!this.userToken) {
610
+ throw new SidechatAPIError("User is not authenticated.");
611
+ }
612
+ try {
613
+ const res = await fetch(`${this.apiRoot}/v1/users/me`, {
614
+ method: "GET",
615
+ headers: {
616
+ ...this.defaultHeaders,
617
+ Authorization: `Bearer ${this.userToken}`,
618
+ },
619
+ });
620
+ const json = await res.json();
621
+ return await json;
622
+ } catch (err) {
623
+ console.error(err);
624
+ throw new SidechatAPIError(`Failed to get asset library.`);
625
+ }
626
+ };
627
+
628
+ /**
629
+ * Gets the metadata of a group from its ID
630
+ * @method
631
+ * @since 2.1.0
632
+ * @param {String} [groupID] - alphanumeric ID of a group to get. Falls back to user's primary group.
633
+ * @returns {Promise<types.SidechatGroup>}
634
+ */
635
+ getGroupMetadata = async (groupID = "") => {
636
+ if (!this.userToken) {
637
+ throw new SidechatAPIError("User is not authenticated.");
638
+ }
639
+ try {
640
+ const res = await fetch(`${this.apiRoot}/v1/groups/${groupID}`, {
641
+ method: "GET",
642
+ headers: {
643
+ ...this.defaultHeaders,
644
+ Authorization: `Bearer ${this.userToken}`,
645
+ },
646
+ });
647
+ const json = await res.json();
648
+ return await json.group;
649
+ } catch (err) {
650
+ console.error(err);
651
+ throw new SidechatAPIError(`Failed to get group metadata.`);
652
+ }
653
+ };
654
+
655
+ /**
656
+ * Joins or leaves a group
657
+ * @method
658
+ * @param {String} groupID - alphanumeric ID of group to join or leave
659
+ * @param {Boolean} isMember - whether or not the user should be a member of the group
660
+ * @since 2.3.8
661
+ */
662
+ setGroupMembership = async (groupID, isMember) => {
663
+ if (!this.userToken) {
664
+ throw new SidechatAPIError("User is not authenticated.");
665
+ }
666
+ try {
667
+ const res = await fetch(
668
+ `${this.apiRoot}/v1/groups/${isMember ? "join" : "leave"}`,
669
+ {
670
+ method: "POST",
671
+ headers: {
672
+ ...this.defaultHeaders,
673
+ Authorization: `Bearer ${this.userToken}`,
674
+ },
675
+ body: JSON.stringify({
676
+ group_id: groupID,
677
+ }),
678
+ }
679
+ );
680
+ const json = await res.json();
681
+ return await json;
682
+ } catch (err) {
683
+ console.error(err);
684
+ throw new SidechatAPIError(`Failed to modify group membership.`);
685
+ }
686
+ };
687
+
688
+ /**
689
+ * Creates a comment on a post
690
+ * @method
691
+ * @since 2.2.0
692
+ * @param {String} parentPostID - alphanumeric ID of post on which this comment is made
693
+ * @param {String} text - text content of comment
694
+ * @param {String} groupID - alphanumeric ID of group in which the parent post resides
695
+ * @param {String} [replyCommentID] - alphanumeric ID of comment to reply to. Falls back to parentPostID
696
+ * @param {String} [topLevelReplyID] - alphanumeric ID of the top-level comment to reply to. Used only when replying to replies. Falls back to parentPostID
697
+ * @param {types.SidechatSimpleAsset[]} [assetList] - list of assets to attach
698
+ * @param {Boolean} [disableDMs] - prevent direct messages being sent to comment's author
699
+ * @param {Boolean} [anonymous] - whether or not to hide user's name and icon on comment
700
+ * @returns {Promise<types.SidechatPostOrComment>} created comment
701
+ */
702
+ createComment = async (
703
+ parentPostID,
704
+ text,
705
+ groupID,
706
+ replyCommentID,
707
+ topLevelReplyID,
708
+ assetList = [],
709
+ disableDMs = false,
710
+ anonymous = false
711
+ ) => {
712
+ if (!this.userToken) {
713
+ throw new SidechatAPIError("User is not authenticated.");
714
+ }
715
+ try {
716
+ const res = await fetch(`${this.apiRoot}/v1/posts`, {
717
+ method: "POST",
718
+ headers: {
719
+ ...this.defaultHeaders,
720
+ Authorization: `Bearer ${this.userToken}`,
721
+ },
722
+ body: JSON.stringify({
723
+ type: "comment",
724
+ assets: assetList,
725
+ group_ids: [groupID],
726
+ text: text,
727
+ reply_post_id: topLevelReplyID || replyCommentID || parentPostID,
728
+ reply_comment_post_id: replyCommentID || parentPostID,
729
+ parent_post_id: parentPostID,
730
+ dms_disabled: disableDMs,
731
+ using_identity: !anonymous,
732
+ }),
733
+ });
734
+ const json = await res.json();
735
+ return await json.comment;
736
+ } catch (err) {
737
+ console.error(err);
738
+ throw new SidechatAPIError(`Failed to post comment.`);
739
+ }
740
+ };
741
+
742
+ /**
743
+ * Creates a new post in the specified group
744
+ * @method
745
+ * @since 2.2.0
746
+ * @param {String} text - text content of comment
747
+ * @param {String} groupID - alphanumeric ID of group in which the parent post resides
748
+ * @param {types.SidechatSimpleAsset[]} [assetList] - list of assets to attach.
749
+ * @param {Boolean} [disableDMs] - prevent direct messages from being sent to post's author
750
+ * @param {Boolean} [disableComments] - whether or not comments should be disabled on post
751
+ * @param {Boolean} [anonymous] - whether or not to hide user's name and icon on post
752
+ * @param {Array<String>} [pollOptions] - List of poll options. If provided, a poll will be created with these options.
753
+ * @returns {Promise<types.SidechatPostOrComment>} the created post
754
+ */
755
+ createPost = async (
756
+ text,
757
+ groupID,
758
+ assetList = [],
759
+ disableDMs = false,
760
+ disableComments = false,
761
+ anonymous = false,
762
+ repostId = undefined,
763
+ pollOptions = undefined
764
+ ) => {
765
+ if (!this.userToken) {
766
+ throw new SidechatAPIError("User is not authenticated.");
767
+ }
768
+ try {
769
+ // Build the request body
770
+ const body = {
771
+ type: "post",
772
+ assets: assetList,
773
+ group_ids: [groupID],
774
+ text: text,
775
+ attachments: [],
776
+ dms_disabled: disableDMs,
777
+ comments_disabled: disableComments,
778
+ using_identity: !anonymous,
779
+ quote_post_id: repostId
780
+ };
781
+ // If pollOptions is provided and is a non-empty array, add poll_request
782
+ if (Array.isArray(pollOptions) && pollOptions.length > 0) {
783
+ body.poll_request = {
784
+ allows_view_results: true,
785
+ choices: pollOptions
786
+ };
787
+ }
788
+ const res = await fetch(`${this.apiRoot}/v1/posts`, {
789
+ method: "POST",
790
+ headers: {
791
+ ...this.defaultHeaders,
792
+ Authorization: `Bearer ${this.userToken}`,
793
+ },
794
+ body: JSON.stringify(body),
795
+ });
796
+ const json = await res.json();
797
+ return await json.posts[0];
798
+ } catch (err) {
799
+ console.error(err);
800
+ throw new SidechatAPIError(`Failed to make post.`);
801
+ }
802
+ };
803
+
804
+ /**
805
+ * Deletes a post or comment that the user created
806
+ * @method
807
+ * @since 2.2.0
808
+ * @param {String} postOrCommentID - alphanumeric ID of post to delete
809
+ */
810
+ deletePostOrComment = async (postOrCommentID) => {
811
+ if (!this.userToken) {
812
+ throw new SidechatAPIError("User is not authenticated.");
813
+ }
814
+ try {
815
+ const res = await fetch(`${this.apiRoot}/v1/posts/delete`, {
816
+ method: "POST",
817
+ headers: {
818
+ ...this.defaultHeaders,
819
+ Authorization: `Bearer ${this.userToken}`,
820
+ },
821
+ body: JSON.stringify({
822
+ post_id: postOrCommentID,
823
+ }),
824
+ });
825
+ const json = await res.json();
826
+ return await json;
827
+ } catch (err) {
828
+ console.error(err);
829
+ throw new SidechatAPIError(`Failed to delete post.`);
830
+ }
831
+ };
832
+
833
+ /**
834
+ * Votes on a poll attached to a post
835
+ * @method
836
+ * @param {String} pollId - alphanumeric ID of poll to vote on
837
+ * @param {Number} choiceIndex - index of the choice to vote on
838
+ * @since 2.5.4
839
+ */
840
+ voteOnPoll = async (pollId, choiceIndex) => {
841
+ if (!this.userToken) {
842
+ throw new SidechatAPIError("User is not authenticated.");
843
+ }
844
+ try {
845
+ const res = await fetch(`${this.apiRoot}/v1/polls/vote`, {
846
+ method: "POST",
847
+ headers: {
848
+ ...this.defaultHeaders,
849
+ Authorization: `Bearer ${this.userToken}`,
850
+ },
851
+ body: JSON.stringify({
852
+ poll_id: pollId,
853
+ choice: choiceIndex,
854
+ }),
855
+ });
856
+ const json = await res.json();
857
+ return await json;
858
+ } catch (err) {
859
+ console.error(err);
860
+ throw new SidechatAPIError(`Failed to vote on poll`);
861
+ }
862
+ };
863
+
864
+ /**
865
+ * Marks that the user has viewed results on a poll. Note that this does not actually return the results of the poll.
866
+ * @method
867
+ * @param {String} pollId - alphanumeric ID of poll to vote on
868
+ * @since 2.5.4
869
+ */
870
+ viewPollResults = async (pollId) => {
871
+ if (!this.userToken) {
872
+ throw new SidechatAPIError("User is not authenticated.");
873
+ }
874
+ try {
875
+ const res = await fetch(`${this.apiRoot}/v1/polls/view_results`, {
876
+ method: "POST",
877
+ headers: {
878
+ ...this.defaultHeaders,
879
+ Authorization: `Bearer ${this.userToken}`,
880
+ },
881
+ body: JSON.stringify({
882
+ poll_id: pollId,
883
+ }),
884
+ });
885
+ const json = await res.json();
886
+ return await json;
887
+ } catch (err) {
888
+ console.error(err);
889
+ throw new SidechatAPIError(`Failed to mark poll results as viewed.`);
890
+ }
891
+ };
892
+
893
+ /**
894
+ * Uploads an asset to AWS S3 for use in posts and comments. Currently photos only
895
+ * @method
896
+ * @param {String} uri - URI of the asset to upload
897
+ * @param {String} mimeType - mimetype of the asset (e.g. "image/png")
898
+ * @param {String} [name] - filename of the asset
899
+ * @returns {Promise<String>} URL of the uploaded asset
900
+ * @since 2.5.1
901
+ */
902
+ uploadAsset = async (uri, mimeType, name = "") => {
903
+ if (!this.userToken) {
904
+ throw new SidechatAPIError("User is not authenticated.");
905
+ }
906
+
907
+ let imageType = mimeType.split("/")[1];
908
+ if (!["png", "jpeg", "gif"].includes(imageType)) {
909
+ throw new SidechatAPIError("Unsupported image format.");
910
+ }
911
+
912
+ const data = new FormData();
913
+ data.append("image", {
914
+ name: name,
915
+ type: mimeType,
916
+ uri: uri,
917
+ });
918
+
919
+ const urlReq = await this.sendRequest(`/v1/assets/upload_url?content_type=${imageType}`);
920
+ const urlJson = await urlReq.json();
921
+
922
+ try {
923
+ const uploadReq = await fetch(urlJson.upload_url, {
924
+ body: data.getAll("image")[0],
925
+ method: "PUT",
926
+ headers: {
927
+ "Content-Type": mimeType,
928
+ },
929
+ });
930
+ if (uploadReq.status == 200) {
931
+ return `${this.apiRoot}/v1/assets/library/${urlJson.asset_id}`;
932
+ } else {
933
+ throw new SidechatAPIError(
934
+ `Couldn't upload image - error ${uploadReq.status}`
935
+ );
936
+ }
937
+ } catch (e) {
938
+ throw new SidechatAPIError(e.message);
939
+ }
940
+ };
941
+
942
+ /**
943
+ * Sets the conversation icon of a user
944
+ * @method
945
+ * @since 2.2.1
946
+ * @param {String} userID - alphanumeric ID of user
947
+ * @param {String} emoji - emoji to set as icon
948
+ * @param {String} primaryColor - hex string (including #) of primary color
949
+ * @param {String} secondaryColor - hex string (including #) of secondary color
950
+ */
951
+ setUserIcon = async (userID, emoji, primaryColor, secondaryColor) => {
952
+ if (!this.userToken) {
953
+ throw new SidechatAPIError("User is not authenticated.");
954
+ }
955
+ try {
956
+ const res = await fetch(`${this.apiRoot}/v1/users/${userID}`, {
957
+ method: "PATCH",
958
+ headers: {
959
+ ...this.defaultHeaders,
960
+ "App-Version": "0",
961
+ Authorization: `Bearer ${this.userToken}`,
962
+ },
963
+ body: JSON.stringify({
964
+ conversation_icon: {
965
+ emoji: emoji,
966
+ secondary_color: secondaryColor,
967
+ is_migrated: true,
968
+ color: primaryColor,
969
+ },
970
+ }),
971
+ });
972
+ const json = await res.json();
973
+ return await json;
974
+ } catch (err) {
975
+ console.error(err);
976
+ throw new SidechatAPIError(`Failed to set icon.`);
977
+ }
978
+ };
979
+
980
+ /**
981
+ * Sets the bio text of a user
982
+ * @method
983
+ * @since 2.5.6
984
+ * @param {String} userID - alphanumeric ID of user
985
+ * @param {String} bio - text to set as bio
986
+ */
987
+ setUserBio = async (userID, bio) => {
988
+ if (!this.userToken) {
989
+ throw new SidechatAPIError("User is not authenticated.");
990
+ }
991
+ try {
992
+ const res = await fetch(`${this.apiRoot}/v1/users/${userID}`, {
993
+ method: "PATCH",
994
+ headers: {
995
+ ...this.defaultHeaders,
996
+ "App-Version": "5.4.22",
997
+ Authorization: `Bearer ${this.userToken}`,
998
+ },
999
+ body: JSON.stringify({
1000
+ bio: bio
1001
+ }),
1002
+ });
1003
+ const json = await res.json();
1004
+ return await json;
1005
+ } catch (err) {
1006
+ console.error(err);
1007
+ throw new SidechatAPIError(`Failed to set bio.`);
1008
+ }
1009
+ };
1010
+
1011
+ /**
1012
+ * Checks if user can set their username to a string
1013
+ * @method
1014
+ * @since 2.3.6
1015
+ * @param {String} username - string to check
1016
+ * @returns {Promise<Boolean>} whether or not username is valid and unused
1017
+ */
1018
+ checkUsername = async (username) => {
1019
+ if (!this.userToken) {
1020
+ throw new SidechatAPIError("User is not authenticated.");
1021
+ }
1022
+ try {
1023
+ const res = await fetch(
1024
+ `${this.apiRoot}/v1/users/username?username=${username}`,
1025
+ {
1026
+ method: "GET",
1027
+ headers: {
1028
+ ...this.defaultHeaders,
1029
+ Authorization: `Bearer ${this.userToken}`,
1030
+ },
1031
+ }
1032
+ );
1033
+ if (res?.status == 200 || res?.status == 204) {
1034
+ return true;
1035
+ } else {
1036
+ return false;
1037
+ }
1038
+ } catch (err) {
1039
+ console.error(err);
1040
+ throw new SidechatAPIError(`Failed to check username.`);
1041
+ }
1042
+ };
1043
+
1044
+ /**
1045
+ * Changes the username of the current user
1046
+ * @method
1047
+ * @since 2.3.6
1048
+ * @param {String} userID - alphanumeric ID of user
1049
+ * @param {String} username - new username to set
1050
+ */
1051
+ setUsername = async (userID, username) => {
1052
+ if (!this.userToken) {
1053
+ throw new SidechatAPIError("User is not authenticated.");
1054
+ }
1055
+ try {
1056
+ const res = await fetch(`${this.apiRoot}/v1/users/${userID}`, {
1057
+ method: "PATCH",
1058
+ headers: {
1059
+ ...this.defaultHeaders,
1060
+ Authorization: `Bearer ${this.userToken}`,
1061
+ },
1062
+ body: JSON.stringify({
1063
+ username: username,
1064
+ }),
1065
+ });
1066
+ const json = await res.json();
1067
+ return await json.user;
1068
+ } catch (err) {
1069
+ console.error(err);
1070
+ throw new SidechatAPIError(`Failed to set icon.`);
1071
+ }
1072
+ };
1073
+
1074
+ /**
1075
+ * Fetches a public user profile
1076
+ * @method
1077
+ * @since 2.6.0
1078
+ * @param {String} username - username of the user to fetch
1079
+ * @returns {Promise<types.SidechatProfile>}
1080
+ */
1081
+ getUserProfile = async (username) => {
1082
+ if (!this.userToken) {
1083
+ throw new SidechatAPIError("User is not authenticated.");
1084
+ }
1085
+ try {
1086
+ const res = await fetch(`${this.apiRoot}/v1/groups/username?username=${username}`, {
1087
+ method: "GET",
1088
+ headers: {
1089
+ ...this.defaultHeaders,
1090
+ Authorization: `Bearer ${this.userToken}`,
1091
+ }
1092
+ });
1093
+ const json = await res.json();
1094
+ return await json.group;
1095
+ } catch (err) {
1096
+ console.error(err);
1097
+ throw new SidechatAPIError(`Failed to set icon.`);
1098
+ }
1099
+ };
1100
+
1101
+ /**
1102
+ * Fetches a public user's posts
1103
+ * @method
1104
+ * @since 2.6.0
1105
+ * @param {String} username - username of the user to fetch
1106
+ * @returns {Promise<types.SidechatPostOrComment[]>}
1107
+ */
1108
+ getUserPosts = async (username) => {
1109
+ if (!this.userToken) {
1110
+ throw new SidechatAPIError("User is not authenticated.");
1111
+ }
1112
+ try {
1113
+ const res = await fetch(`${this.apiRoot}/v1/users/posts?username=${username}`, {
1114
+ method: "GET",
1115
+ headers: {
1116
+ ...this.defaultHeaders,
1117
+ Authorization: `Bearer ${this.userToken}`,
1118
+ }
1119
+ });
1120
+ const json = await res.json();
1121
+ return await json.posts;
1122
+ } catch (err) {
1123
+ console.error(err);
1124
+ throw new SidechatAPIError(`Failed to set icon.`);
1125
+ }
1126
+ };
1127
+
1128
+ /**
1129
+ * Marks an activity item as read
1130
+ * @method
1131
+ * @since 2.3.2
1132
+ * @param {String} activityID - alphanumeric ID of activity object
1133
+ */
1134
+ readActivity = async (activityID) => {
1135
+ if (!this.userToken) {
1136
+ throw new SidechatAPIError("User is not authenticated.");
1137
+ }
1138
+ try {
1139
+ const res = await fetch(`${this.apiRoot}/v1/activity/seen`, {
1140
+ method: "POST",
1141
+ headers: {
1142
+ ...this.defaultHeaders,
1143
+ Authorization: `Bearer ${this.userToken}`,
1144
+ },
1145
+ body: JSON.stringify({
1146
+ ids: [activityID],
1147
+ }),
1148
+ });
1149
+ const json = await res.json();
1150
+ return await json;
1151
+ } catch (err) {
1152
+ console.error(err);
1153
+ throw new SidechatAPIError(`Failed to mark activity as read.`);
1154
+ }
1155
+ };
1156
+
1157
+ /**
1158
+ * Retrieves joinable group chats
1159
+ * @method
1160
+ * @since 2.3.5
1161
+ */
1162
+ getGroupChats = async () => {
1163
+ if (!this.userToken) {
1164
+ throw new SidechatAPIError("User is not authenticated.");
1165
+ }
1166
+ try {
1167
+ const res = await fetch(`${this.apiRoot}/v1/chats/explore`, {
1168
+ method: "GET",
1169
+ headers: {
1170
+ ...this.defaultHeaders,
1171
+ Authorization: `Bearer ${this.userToken}`,
1172
+ },
1173
+ });
1174
+ const json = await res.json();
1175
+ return await json.chats;
1176
+ } catch (err) {
1177
+ console.error(err);
1178
+ throw new SidechatAPIError(`Failed to get groupchats.`);
1179
+ }
1180
+ };
1181
+
1182
+ /**
1183
+ * Joins a group chat. To mimic the official client, use the user's display name and icon by default.
1184
+ * @method
1185
+ * @param {String} groupChatID - alphanumeric ID of group chat to join
1186
+ * @param {String} displayName - display name to use in chat
1187
+ * @param {String} emoji - emoji to use as icon
1188
+ * @param {String} primaryColor - hex string of primary color
1189
+ * @param {String} secondaryColor - hex string of secondary color
1190
+ * @since 2.3.5
1191
+ */
1192
+ joinGroupChat = async (
1193
+ groupChatID,
1194
+ displayName,
1195
+ emoji,
1196
+ primaryColor,
1197
+ secondaryColor
1198
+ ) => {
1199
+ if (!this.userToken) {
1200
+ throw new SidechatAPIError("User is not authenticated.");
1201
+ }
1202
+ try {
1203
+ const res = await fetch(`${this.apiRoot}/v1/chats/groups/join`, {
1204
+ method: "POST",
1205
+ headers: {
1206
+ ...this.defaultHeaders,
1207
+ Authorization: `Bearer ${this.userToken}`,
1208
+ },
1209
+ body: JSON.stringify({
1210
+ chat_id: groupChatID,
1211
+ identity: {
1212
+ display_name: displayName,
1213
+ emoji: emoji,
1214
+ secondary_color: secondaryColor,
1215
+ color: primaryColor,
1216
+ },
1217
+ }),
1218
+ });
1219
+ const json = await res.json();
1220
+ return await json;
1221
+ } catch (err) {
1222
+ console.error(err);
1223
+ throw new SidechatAPIError(`Failed to join groupchat.`);
1224
+ }
1225
+ };
1226
+
1227
+ /**
1228
+ * Gets a list of the user's direct messages
1229
+ * @method
1230
+ * @returns {Promise<types.SidechatDirectThread[]>}
1231
+ * @since 2.4.4
1232
+ */
1233
+ getDMs = async () => {
1234
+ if (!this.userToken) {
1235
+ throw new SidechatAPIError("User is not authenticated.");
1236
+ }
1237
+ try {
1238
+ const res = await fetch(`${this.apiRoot}/v1/chats`, {
1239
+ method: "GET",
1240
+ headers: {
1241
+ ...this.defaultHeaders,
1242
+ Authorization: `Bearer ${this.userToken}`,
1243
+ },
1244
+ });
1245
+ const json = await res.json();
1246
+ const list = await json.chats;
1247
+ let r = [];
1248
+ list.forEach((o) => {
1249
+ r.push(o.chat);
1250
+ });
1251
+ return await r;
1252
+ } catch (err) {
1253
+ console.error(err);
1254
+ throw new SidechatAPIError(`Failed to fetch DMs.`);
1255
+ }
1256
+ };
1257
+
1258
+ /**
1259
+ * Gets a single direct message thread
1260
+ * @method
1261
+ * @param {String} id - alphanumeric ID of the chat to fetch
1262
+ * @returns {Promise<types.SidechatDirectThread>}
1263
+ * @since 2.4.4
1264
+ */
1265
+ getDMThread = async (id) => {
1266
+ if (!this.userToken) {
1267
+ throw new SidechatAPIError("User is not authenticated.");
1268
+ }
1269
+ try {
1270
+ const res = await fetch(
1271
+ `${this.apiRoot}/v1/chats/messages?chat_id=${id}`,
1272
+ {
1273
+ method: "GET",
1274
+ headers: {
1275
+ ...this.defaultHeaders,
1276
+ Authorization: `Bearer ${this.userToken}`,
1277
+ },
1278
+ }
1279
+ );
1280
+ const json = await res.json();
1281
+ return await json.chat;
1282
+ } catch (err) {
1283
+ console.error(err);
1284
+ throw new SidechatAPIError(`Failed to fetch DM thread.`);
1285
+ }
1286
+ };
1287
+
1288
+ /**
1289
+ * Sends a message to an existing direct message thread - note that you must first use startDM() to start a thread.
1290
+ * @method
1291
+ * @param {String} chatID - alphanumeric ID of the chat to send to
1292
+ * @param {String} text - text content of message
1293
+ * @param {String} clientID - alphanumeric device ID
1294
+ * @param {types.SidechatAsset[]} assets - array of assets to send
1295
+ * @param {Boolean} anonymous - whether the DM should be sent anonymously
1296
+ * @since 2.4.4
1297
+ */
1298
+ sendDM = async (chatID, text, clientID, assets = [], anonymous = false) => {
1299
+ if (!this.userToken) {
1300
+ throw new SidechatAPIError("User is not authenticated.");
1301
+ }
1302
+ try {
1303
+ const res = await fetch(`${this.apiRoot}/v1/chats/send`, {
1304
+ method: "POST",
1305
+ headers: {
1306
+ ...this.defaultHeaders,
1307
+ Authorization: `Bearer ${this.userToken}`,
1308
+ },
1309
+ body: JSON.stringify({
1310
+ chat_id: chatID,
1311
+ text: text,
1312
+ client_id: clientID,
1313
+ anonymous: anonymous,
1314
+ assets: assets,
1315
+ }),
1316
+ });
1317
+ const json = await res.json();
1318
+ return await json;
1319
+ } catch (err) {
1320
+ console.error(err);
1321
+ throw new SidechatAPIError(`Failed to send message.`);
1322
+ }
1323
+ };
1324
+
1325
+ /**
1326
+ * Creates a new direct message thread
1327
+ * @method
1328
+ * @param {String} text - text content of message
1329
+ * @param {String} clientID - alphanumeric ID of devide
1330
+ * @param {String} postID - alphanumeric ID of post or comment
1331
+ * @param {Boolean} anonymous - whether the DM should be sent anonymously
1332
+ * @param {"feed"} postContext - context of post (mostly undocumented, defaults to "feed")
1333
+ * @since 2.4.4
1334
+ */
1335
+ startDM = async (
1336
+ text,
1337
+ clientID,
1338
+ postID,
1339
+ anonymous = false,
1340
+ postContext = "feed"
1341
+ ) => {
1342
+ if (!this.userToken) {
1343
+ throw new SidechatAPIError("User is not authenticated.");
1344
+ }
1345
+ try {
1346
+ const res = await fetch(`${this.apiRoot}/v1/chats/start`, {
1347
+ method: "POST",
1348
+ headers: {
1349
+ ...this.defaultHeaders,
1350
+ Authorization: `Bearer ${this.userToken}`,
1351
+ },
1352
+ body: JSON.stringify({
1353
+ text: text,
1354
+ client_id: clientID,
1355
+ post_id: postID,
1356
+ anonymous: anonymous,
1357
+ post_context: postContext,
1358
+ }),
1359
+ });
1360
+ const json = await res.json();
1361
+ return await json;
1362
+ } catch (err) {
1363
+ console.error(err);
1364
+ throw new SidechatAPIError(`Failed to start DM.`);
1365
+ }
1366
+ };
1367
+
1368
+ /**
1369
+ * Hides posts from user
1370
+ * @method
1371
+ * @param {String} postID - alphanumeric ID of post to hide
1372
+ * @since 2.6.2
1373
+ */
1374
+ hidePostsFromUser = async (postID) => {
1375
+ if (!this.userToken) {
1376
+ throw new SidechatAPIError("User is not authenticated.");
1377
+ }
1378
+ try {
1379
+ const res = await fetch(`${this.apiRoot}/v1/posts/hide_posts_from_user`, {
1380
+ method: "POST",
1381
+ headers: {
1382
+ ...this.defaultHeaders,
1383
+ Authorization: `Bearer ${this.userToken}`,
1384
+ },
1385
+ body: JSON.stringify({
1386
+ post_id: postID,
1387
+ post_context: "feed",
1388
+ report: false
1389
+ }),
1390
+ });
1391
+ const json = await res.json();
1392
+ return await json;
1393
+ } catch (err) {
1394
+ console.error(err);
1395
+ throw new SidechatAPIError(`Failed to hide post.`);
1396
+ }
1397
+ };
1398
+
1399
+ /**
1400
+ * Unhides all posts from all users
1401
+ * @method
1402
+ * @since 2.6.2
1403
+ */
1404
+ unhidePostsFromAllUsers = async () => {
1405
+ if (!this.userToken) {
1406
+ throw new SidechatAPIError("User is not authenticated.");
1407
+ }
1408
+ try {
1409
+ const res = await fetch(`${this.apiRoot}/v1/users/unhide_all`, {
1410
+ method: "POST",
1411
+ headers: {
1412
+ ...this.defaultHeaders,
1413
+ Authorization: `Bearer ${this.userToken}`,
1414
+ },
1415
+ body: JSON.stringify({}),
1416
+ });
1417
+ const json = await res.json();
1418
+ return await json;
1419
+ } catch (err) {
1420
+ console.error(err);
1421
+ throw new SidechatAPIError(`Failed to unhide post.`);
1422
+ }
1423
+ };
1424
+ }
1425
+
1426
+ export default SidechatAPIClient;