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
package/dist/index.cjs CHANGED
@@ -217,1414 +217,1427 @@ class SidechatAPIError extends Error {
217
217
  }
218
218
  }
219
219
 
220
- /**
221
- * API client class for making requests to Sidechat's private API. You'll need to [authenticate]{@tutorial Authentication} before using most of the methods.
222
- * @class
223
- * @since 2.0.0-alpha.0
224
- */
225
- class SidechatAPIClient {
226
- /**
227
- * User bearer token
228
- * @type {SidechatAuthToken}
229
- * */
230
- userToken;
231
-
232
- /**
233
- * Default headers for every API request
234
- * @type {Object}
235
- * @static
236
- * @constant
237
- */
238
- defaultHeaders = {
239
- Accept: "application/json",
240
- "Content-Type": "application/json",
241
- "App-Version": "6.0.0",
242
- Dnt: 1,
243
- };
244
-
245
- /**
246
- * Root URL for every API request
247
- * @type {String}
248
- * @default "https://api.sidechat.lol"
249
- */
250
- apiRoot = "https://api.sidechat.lol";
251
-
252
- /**
253
- * Create a new instance of the API client
254
- * @param {SidechatAuthToken} [token] - user bearer token
255
- * @param {String} rootUrl - custom API root URL for mocking or using other server
256
- */
257
- constructor(token = "", rootUrl = "") {
258
- if (token) {
259
- this.userToken = token;
260
- }
261
- if (rootUrl) {
262
- this.apiRoot = rootUrl;
263
- }
264
- }
265
-
266
- /**
267
- * 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
268
- * @method
269
- * @param {SidechatAuthToken} token - user bearer token
270
- */
271
- setToken = (token) => {
272
- this.userToken = token;
273
- };
274
-
275
- /**
276
- * Manually set the root URL for all API requests. This can be used for mocking requests or redirecting them to a different server
277
- * @method
278
- * @param {String} url - new root URL to set
279
- * @since 2.3.9
280
- */
281
- setAPIRoot = (url) => {
282
- this.apiRoot = url;
283
- };
284
-
285
- /**
286
- * Run an arbitrary API request using the current client's authentication
287
- * @method
288
- * @param {String} endpoint - API endpoint to request (e.g. "/v1/posts")
289
- * @param {"GET"|"POST"|"PUT"|"DELETE"|"PATCH"|"OPTIONS"} [method] - HTTP method to use
290
- * @param {Object} [body] - body to send with the request
291
- * @param {Object} [headers] - custom headers to send with the request
292
- * @param {Boolean} [stripHeaders] - remove the default headers from the request
293
- * @since 2.4.9
294
- */
295
- sendRequest = (
296
- endpoint,
297
- method = "GET",
298
- body = undefined,
299
- headers = {},
300
- stripHeaders = false
301
- ) => {
302
- let requestHeaders = this.defaultHeaders;
303
- if (stripHeaders) {
304
- headers = {};
305
- }
306
- requestHeaders = { ...requestHeaders, ...headers };
307
- return fetch(`${this.apiRoot}${endpoint}`, {
308
- headers: { Authorization: `Bearer ${this.userToken}`, ...requestHeaders },
309
- body: body,
310
- method: method,
311
- });
312
- };
313
-
314
- /**
315
- * Initiate the login process with a phone number. Should be followed up with verifySMSCode().
316
- * @method
317
- * @since 1.0.0
318
- * @param {Number} phoneNumber - US phone number (WITHOUT +1) to send verification code to
319
- */
320
- loginViaSMS = async (phoneNumber) => {
321
- try {
322
- const res = await fetch(`${this.apiRoot}/v1/login_register`, {
323
- method: "POST",
324
- headers: this.defaultHeaders,
325
- body: JSON.stringify({
326
- phone_number: `+1${phoneNumber}`,
327
- version: 3,
328
- }),
329
- });
330
- const json = await res.json();
331
- return json;
332
- } catch (err) {
333
- console.error(err);
334
- throw new SidechatAPIError("Failed to request SMS verification.");
335
- }
336
- };
337
-
338
- /**
339
- * Verify the code sent via SMS with loginViaSMS(). If this function succeeds, the user will be authenticated for future requests.
340
- * @method
341
- * @since 1.0.0
342
- * @param {Number} phoneNumber - US phone number (WITHOUT +1) that verification code was sent to
343
- * @param {String} code - the verification code
344
- */
345
- verifySMSCode = async (phoneNumber, code) => {
346
- try {
347
- const res = await fetch(`${this.apiRoot}/v1/verify_phone_number`, {
348
- method: "POST",
349
- headers: this.defaultHeaders,
350
- body: JSON.stringify({
351
- phone_number: `+1${phoneNumber}`,
352
- code: code.toUpperCase(),
353
- }),
354
- });
355
- const json = await res.json();
356
- if (json?.logged_in_user?.token) {
357
- this.userToken = json.logged_in_user.token;
358
- }
359
- return json;
360
- } catch (err) {
361
- console.error(err);
362
- throw new SidechatAPIError("Failed verify this code.");
363
- }
364
- };
365
-
366
- /**
367
- * Set the user's age. If this function succeeds, the user will be authenticated for future requests.
368
- * @method
369
- * @since 1.0.0
370
- * @param {Number} age - user's age in years
371
- * @param {String} registrationID - the registration ID generated by verifySMSCode()
372
- */
373
- setAge = async (age, registrationID) => {
374
- if (age < 13) {
375
- throw new SidechatAPIError("You're too young to use Offsides.");
376
- }
377
- try {
378
- const res = await fetch(`${this.apiRoot}/v1/complete_registration`, {
379
- method: "POST",
380
- headers: this.defaultHeaders,
381
- body: JSON.stringify({
382
- age: Number(age),
383
- registration_id: registrationID,
384
- }),
385
- });
386
- const json = await res.json();
387
- if (json.token) {
388
- this.userToken = json.token;
389
- }
390
- return json;
391
- } catch (err) {
392
- console.error(err);
393
- throw new SidechatAPIError("Failed verify this code.");
394
- }
395
- };
396
-
397
- /**
398
- * Initiate the email setup process. Should be followed up with checkEmailVerification().
399
- * @method
400
- * @since 1.0.0
401
- * @param {String} email - school email address to send verification code to
402
- * @tutorial Email Registration
403
- */
404
- registerEmail = async (email) => {
405
- if (!this.userToken) {
406
- throw new SidechatAPIError("User is not authenticated.");
407
- }
408
- try {
409
- const res = await fetch(`${this.apiRoot}/v2/users/register_email`, {
410
- method: "POST",
411
- headers: {
412
- ...this.defaultHeaders,
413
- Authorization: `Bearer ${this.userToken}`,
414
- },
415
- body: JSON.stringify({
416
- email: email,
417
- }),
418
- });
419
- const json = await res.json();
420
- if (json.message) {
421
- throw new SidechatAPIError(json.message);
422
- }
423
- return json;
424
- } catch (err) {
425
- console.error(err);
426
- throw new SidechatAPIError("Failed to request email verification.");
427
- }
428
- };
429
-
430
- /**
431
- * Check is the user's email is verified.
432
- * @method
433
- * @since 1.0.0
434
- */
435
- checkEmailVerification = async () => {
436
- if (!this.userToken) {
437
- throw new SidechatAPIError("User is not authenticated.");
438
- }
439
- try {
440
- const res = await fetch(`${this.apiRoot}/v1/users/check_email_verified`, {
441
- method: "GET",
442
- headers: {
443
- ...this.defaultHeaders,
444
- Authorization: `Bearer ${this.userToken}`,
445
- },
446
- });
447
- const json = await res.json();
448
- if (json.verified_email_updates_response) {
449
- return json.verified_email_updates_response;
450
- } else if (json.changing_phone_number_verified_email_user) {
451
- return json.changing_phone_number_verified_email_user;
452
- } else {
453
- throw new SidechatAPIError(json?.message || "Email is not verified.");
454
- }
455
- } catch (err) {
456
- console.error(err);
457
- throw new SidechatAPIError("Email is not verified.");
458
- }
459
- };
460
-
461
- /**
462
- * Set the device ID of the current user
463
- * @method
464
- * @since 1.0.0
465
- * @param {String} deviceId - the device ID to set
466
- */
467
- setDeviceID = async (deviceID) => {
468
- if (!this.userToken) {
469
- throw new SidechatAPIError("User is not authenticated.");
470
- }
471
- try {
472
- const res = await fetch(`${this.apiRoot}/v1/register_device_token`, {
473
- method: "POST",
474
- headers: {
475
- ...this.defaultHeaders,
476
- Authorization: `Bearer ${this.userToken}`,
477
- },
478
- body: JSON.stringify({
479
- build_type: "release",
480
- bundle_id: "com.flowerave.sidechat",
481
- device_token: deviceID,
482
- }),
483
- });
484
- const json = await res.json();
485
- return json;
486
- } catch (err) {
487
- console.error(err);
488
- throw new SidechatAPIError("Failed verify this code.");
489
- }
490
- };
491
-
492
- /**
493
- * Get updated status for user and group
494
- * @method
495
- * @since 1.0.0
496
- * @deprecated since 2.1.0, will be removed by 3.0.0. Please use `getUpdates` instead!
497
- * @param {String} [groupID] - ID of a specific group to retrieve info from. Falls back to user's primary group.
498
- */
499
- getUserAndGroup = async (groupID = "") => {
500
- const json = await this.getUpdates(groupID);
501
- return json;
502
- };
503
-
504
- /**
505
- * Get updated status for user and group
506
- * @method
507
- * @since 2.1.0
508
- * @param {String} [groupID] - ID of a specific group to retrieve info from. Falls back to user's primary group.
509
- */
510
- getUpdates = async (groupID = "") => {
511
- if (!this.userToken) {
512
- throw new SidechatAPIError("User is not authenticated.");
513
- }
514
- try {
515
- const res = await fetch(
516
- `${this.apiRoot}/v1/updates?group_id=${groupID}`,
517
- {
518
- method: "GET",
519
- headers: {
520
- ...this.defaultHeaders,
521
- Authorization: `Bearer ${this.userToken}`,
522
- },
523
- }
524
- );
525
- const json = await res.json();
526
- return json;
527
- } catch (err) {
528
- console.error(err);
529
- throw new SidechatAPIError(`Failed to get posts from group.`);
530
- }
531
- };
532
-
533
- /**
534
- * Fetches posts from the specified category in a group
535
- * @method
536
- * @since 1.0.0
537
- * @param {String} groupID - group ID
538
- * @param {"hot"|"recent"|"top"} category - category to filter posts
539
- * @param {SidechatCursorString} [cursor] - cursor string
540
- * @returns {SidechatPostsAndCursor} List of posts and cursor
541
- */
542
- getGroupPosts = async (groupID, category = "hot", cursor) => {
543
- if (!this.userToken) {
544
- throw new SidechatAPIError("User is not authenticated.");
545
- }
546
- try {
547
- const res = await fetch(
548
- `${this.apiRoot}/v1/posts?${cursor ? "cursor=" + encodeURIComponent(cursor) + "&" : ""
549
- }group_id=${groupID}&type=${category}`,
550
- {
551
- method: "GET",
552
- headers: {
553
- ...this.defaultHeaders,
554
- Authorization: `Bearer ${this.userToken}`,
555
- },
556
- }
557
- );
558
- const json = await res.json();
559
- return json;
560
- } catch (err) {
561
- console.error(err);
562
- throw new SidechatAPIError(`Failed to get posts from group.`);
563
- }
564
- };
565
-
566
- /**
567
- * Upvote or downvote, or unvote a post
568
- * @method
569
- * @since 2.0.0-alpha.0
570
- * @param {String} postID - post ID to vote on
571
- * @param {SidechatVoteString} action - whether to upvote, downvote, or reset vote
572
- */
573
- setVote = async (postID, action) => {
574
- if (!this.userToken) {
575
- throw new SidechatAPIError("User is not authenticated.");
576
- }
577
- try {
578
- const res = await fetch(`${this.apiRoot}/v1/posts/set_vote`, {
579
- method: "POST",
580
- headers: {
581
- ...this.defaultHeaders,
582
- Authorization: `Bearer ${this.userToken}`,
583
- },
584
- body: JSON.stringify({
585
- post_id: postID,
586
- vote_status: action,
587
- }),
588
- });
589
- const json = await res.json();
590
- return json;
591
- } catch (err) {
592
- console.error(err);
593
- throw new SidechatAPIError(`Failed to change the vote on post.`);
594
- }
595
- };
596
-
597
- /**
598
- * Fetches a single post with just its ID
599
- * @method
600
- * @since 2.3.0
601
- * @param {String} postID - ID of post to fetch
602
- * @param {Boolean} includeDeleted - undocumented
603
- * @returns {SidechatPostOrComment} post object
604
- */
605
- getPost = async (postID, includeDeleted = false) => {
606
- if (!this.userToken) {
607
- throw new SidechatAPIError("User is not authenticated.");
608
- }
609
- try {
610
- const res = await fetch(
611
- `${this.apiRoot}/v1/posts/get?include_deleted=${includeDeleted}&post_id=${postID}`,
612
- {
613
- method: "GET",
614
- headers: {
615
- ...this.defaultHeaders,
616
- Authorization: `Bearer ${this.userToken}`,
617
- },
618
- }
619
- );
620
- const json = await res.json();
621
- return json.post;
622
- } catch (err) {
623
- console.error(err);
624
- throw new SidechatAPIError(`Failed to get post from ID.`);
625
- }
626
- };
627
-
628
- /**
629
- * Fetches the posts or comments that the user has created
630
- * @method
631
- * @since 2.3.5
632
- * @param {"posts"|"comments"} contentType - type of user content to fetch
633
- * @returns {SidechatPostOrComment[]} post object
634
- */
635
- getUserContent = async (contentType) => {
636
- if (!this.userToken) {
637
- throw new SidechatAPIError("User is not authenticated.");
638
- }
639
- if (contentType == "posts") {
640
- contentType = "my_posts";
641
- } else if (contentType == "comments") {
642
- contentType = "my_comments";
643
- }
644
- try {
645
- const res = await fetch(`${this.apiRoot}/v1/posts&type=${contentType}`, {
646
- method: "GET",
647
- headers: {
648
- ...this.defaultHeaders,
649
- Authorization: `Bearer ${this.userToken}`,
650
- },
651
- });
652
- const json = await res.json();
653
- return json.posts;
654
- } catch (err) {
655
- console.error(err);
656
- throw new SidechatAPIError(`Failed to get content from user.`);
657
- }
658
- };
659
-
660
- /**
661
- * Get all the commments on a post
662
- * @method
663
- * @since 2.0.0-alpha.0
664
- * @param {String} postID - post ID to get comments for
665
- * @returns {SidechatPostOrComment[]} list of comments
666
- */
667
- getPostComments = async (postID) => {
668
- if (!this.userToken) {
669
- throw new SidechatAPIError("User is not authenticated.");
670
- }
671
- try {
672
- const res = await fetch(
673
- `${this.apiRoot}/v1/posts/comments/?post_id=${postID}`,
674
- {
675
- method: "GET",
676
- headers: {
677
- ...this.defaultHeaders,
678
- Authorization: `Bearer ${this.userToken}`,
679
- },
680
- }
681
- );
682
- const json = await res.json();
683
- // Function to preprocess the comments and organize them into a nested structure
684
- function preprocessComments(apiComments) {
685
- // Map to store comments by their IDs for efficient lookup
686
- const commentMap = new Map();
687
- // List to store top-level comments
688
- const topLevelComments = [];
689
-
690
- // Iterate through the API comments
691
- apiComments.forEach((comment) => {
692
- // Store the comment in the map with its ID as the key
693
- commentMap.set(comment.id, comment);
694
- // Get the parent comment using the reply_post_id
695
- const parentComment = commentMap.get(comment.reply_post_id);
696
- // Check if the comment is a top-level comment
697
- if (
698
- !parentComment ||
699
- comment.reply_post_id === comment.parent_post_id
700
- ) {
701
- // If it's a top-level comment, push it to the topLevelComments array
702
- topLevelComments.push(comment);
703
- } else {
704
- // If it's a reply, add it to the parent comment's replies array
705
- if (!parentComment.replies) parentComment.replies = [];
706
- parentComment.replies.push(comment);
707
- }
708
- });
709
-
710
- // Flatten the nested structure and return a single list of comments
711
- return flattenComments(topLevelComments);
712
- }
713
-
714
- // Function to flatten nested comments into a single list
715
- function flattenComments(comments) {
716
- // Use reduce to flatten the nested comments array into a single list
717
- return comments.reduce((flatComments, comment) => {
718
- // Push the current comment to the flatComments array
719
- flatComments.push(comment);
720
- // If the current comment has replies, recursively flatten them and push to the flatComments array
721
- if (comment.replies)
722
- flatComments.push(...flattenComments(comment.replies));
723
- // Return the flatComments array
724
- return flatComments;
725
- }, []);
726
- }
727
-
728
- const sortedComments = preprocessComments(json.posts);
729
- return sortedComments;
730
- } catch (err) {
731
- console.error(err);
732
- throw new SidechatAPIError(`Failed to get comments on post.`);
733
- }
734
- };
735
-
736
- /**
737
- * Gets groups to be displayed on the "Explore Groups" page
738
- * @method
739
- * @since 2.0.0-alpha.0
740
- * @param {Boolean} onePage - whether or not results should be returned as a single page
741
- * @returns {SidechatGroup[]}
742
- */
743
- getAvailableGroups = async (onePage = true) => {
744
- if (!this.userToken) {
745
- throw new SidechatAPIError("User is not authenticated.");
746
- }
747
- try {
748
- const res = await fetch(`${this.apiRoot}/v1/groups/explore`, {
749
- method: "GET",
750
- headers: {
751
- ...this.defaultHeaders,
752
- "App-Version": onePage ? "0" : this.defaultHeaders["App-Version"],
753
- Authorization: `Bearer ${this.userToken}`,
754
- },
755
- });
756
- const json = await res.json();
757
- return await json.groups;
758
- } catch (err) {
759
- console.error(err);
760
- throw new SidechatAPIError(`Failed to get groups from explore.`);
761
- }
762
- };
763
-
764
- /**
765
- * Searches for new groups based on a query keyword
766
- * @method
767
- * @since 2.6.0
768
- * @param {String} query - the string to search for. This will be encoded, so strings with spaces and special characters are okay.
769
- * @returns {SidechatGroup[]}
770
- */
771
- searchAvailableGroups = async (query) => {
772
- if (!this.userToken) {
773
- throw new SidechatAPIError("User is not authenticated.");
774
- }
775
- try {
776
- const res = await fetch(`${this.apiRoot}/v1/groups/explore/search?term=${encodeURIComponent(query)}`, {
777
- method: "GET",
778
- headers: {
779
- ...this.defaultHeaders,
780
- Authorization: `Bearer ${this.userToken}`,
781
- },
782
- });
783
- const json = await res.json();
784
- return await json.results;
785
- } catch (err) {
786
- console.error(err);
787
- throw new SidechatAPIError(`Failed to search groups.`);
788
- }
789
- };
790
-
791
- /**
792
- * 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.
793
- * @method
794
- * @since 2.0.6
795
- * @returns {SidechatLibraryAsset[]}
796
- */
797
- getAssetLibrary = async () => {
798
- if (!this.userToken) {
799
- throw new SidechatAPIError("User is not authenticated.");
800
- }
801
- try {
802
- const res = await fetch(`${this.apiRoot}/v1/assets/library`, {
803
- method: "GET",
804
- headers: {
805
- ...this.defaultHeaders,
806
- Authorization: `Bearer ${this.userToken}`,
807
- },
808
- });
809
- const json = await res.json();
810
- return await json.items;
811
- } catch (err) {
812
- console.error(err);
813
- throw new SidechatAPIError(`Failed to get asset library.`);
814
- }
815
- };
816
-
817
- /**
818
- * Gets the current authenticated user and a list of the groups of which they are members.
819
- * @method
820
- * @since 2.1.0
821
- * @returns {SidechatCurrentUser}
822
- */
823
- getCurrentUser = async () => {
824
- if (!this.userToken) {
825
- throw new SidechatAPIError("User is not authenticated.");
826
- }
827
- try {
828
- const res = await fetch(`${this.apiRoot}/v1/users/me`, {
829
- method: "GET",
830
- headers: {
831
- ...this.defaultHeaders,
832
- Authorization: `Bearer ${this.userToken}`,
833
- },
834
- });
835
- const json = await res.json();
836
- return await json;
837
- } catch (err) {
838
- console.error(err);
839
- throw new SidechatAPIError(`Failed to get asset library.`);
840
- }
841
- };
842
-
843
- /**
844
- * Gets the metadata of a group from its ID
845
- * @method
846
- * @since 2.1.0
847
- * @param {String} [groupID] - alphanumeric ID of a group to get. Falls back to user's primary group.
848
- * @returns {SidechatGroup}
849
- */
850
- getGroupMetadata = async (groupID = "") => {
851
- if (!this.userToken) {
852
- throw new SidechatAPIError("User is not authenticated.");
853
- }
854
- try {
855
- const res = await fetch(`${this.apiRoot}/v1/groups/${groupID}`, {
856
- method: "GET",
857
- headers: {
858
- ...this.defaultHeaders,
859
- Authorization: `Bearer ${this.userToken}`,
860
- },
861
- });
862
- const json = await res.json();
863
- return await json.group;
864
- } catch (err) {
865
- console.error(err);
866
- throw new SidechatAPIError(`Failed to get group metadata.`);
867
- }
868
- };
869
-
870
- /**
871
- * Joins or leaves a group
872
- * @method
873
- * @param {String} groupID - alphanumeric ID of group to join or leave
874
- * @param {Boolean} isMember - whether or not the user should be a member of the group
875
- * @since 2.3.8
876
- */
877
- setGroupMembership = async (groupID, isMember) => {
878
- if (!this.userToken) {
879
- throw new SidechatAPIError("User is not authenticated.");
880
- }
881
- try {
882
- const res = await fetch(
883
- `${this.apiRoot}/v1/groups/${isMember ? "join" : "leave"}`,
884
- {
885
- method: "POST",
886
- headers: {
887
- ...this.defaultHeaders,
888
- Authorization: `Bearer ${this.userToken}`,
889
- },
890
- body: JSON.stringify({
891
- group_id: groupID,
892
- }),
893
- }
894
- );
895
- const json = await res.json();
896
- return await json;
897
- } catch (err) {
898
- console.error(err);
899
- throw new SidechatAPIError(`Failed to modify group membership.`);
900
- }
901
- };
902
-
903
- /**
904
- * Creates a comment on a post
905
- * @method
906
- * @since 2.2.0
907
- * @param {String} parentPostID - alphanumeric ID of post on which this comment is made
908
- * @param {String} text - text content of comment
909
- * @param {String} groupID - alphanumeric ID of group in which the parent post resides
910
- * @param {String} [replyCommentID] - alphanumeric ID of comment to reply to. Falls back to parentPostID
911
- * @param {String} [topLevelReplyID] - alphanumeric ID of the top-level comment to reply to. Used only when replying to replies. Falls back to parentPostID
912
- * @param {SidechatSimpleAsset[]} [assetList] - list of assets to attach
913
- * @param {Boolean} [disableDMs] - prevent direct messages being sent to comment's author
914
- * @param {Boolean} [anonymous] - whether or not to hide user's name and icon on comment
915
- * @returns {SidechatPostOrComment} created comment
916
- */
917
- createComment = async (
918
- parentPostID,
919
- text,
920
- groupID,
921
- replyCommentID,
922
- topLevelReplyID,
923
- assetList = [],
924
- disableDMs = false,
925
- anonymous = false
926
- ) => {
927
- if (!this.userToken) {
928
- throw new SidechatAPIError("User is not authenticated.");
929
- }
930
- try {
931
- const res = await fetch(`${this.apiRoot}/v1/posts`, {
932
- method: "POST",
933
- headers: {
934
- ...this.defaultHeaders,
935
- Authorization: `Bearer ${this.userToken}`,
936
- },
937
- body: JSON.stringify({
938
- type: "comment",
939
- assets: assetList,
940
- group_ids: [groupID],
941
- text: text,
942
- reply_post_id: topLevelReplyID || replyCommentID || parentPostID,
943
- reply_comment_post_id: replyCommentID || parentPostID,
944
- parent_post_id: parentPostID,
945
- dms_disabled: disableDMs,
946
- using_identity: !anonymous,
947
- }),
948
- });
949
- const json = await res.json();
950
- return await json.comment;
951
- } catch (err) {
952
- console.error(err);
953
- throw new SidechatAPIError(`Failed to post comment.`);
954
- }
955
- };
956
-
957
- /**
958
- * Creates a new post in the specified group
959
- * @method
960
- * @since 2.2.0
961
- * @param {String} text - text content of comment
962
- * @param {String} groupID - alphanumeric ID of group in which the parent post resides
963
- * @param {SidechatSimpleAsset[]} [assetList] - list of assets to attach.
964
- * @param {Boolean} [disableDMs] - prevent direct messages from being sent to post's author
965
- * @param {Boolean} [disableComments] - whether or not comments should be disabled on post
966
- * @param {Boolean} [anonymous] - whether or not to hide user's name and icon on post
967
- * @returns {SidechatPostOrComment} the created post
968
- */
969
- createPost = async (
970
- text,
971
- groupID,
972
- assetList = [],
973
- disableDMs = false,
974
- disableComments = false,
975
- anonymous = false,
976
- repostId = undefined
977
- ) => {
978
- if (!this.userToken) {
979
- throw new SidechatAPIError("User is not authenticated.");
980
- }
981
- try {
982
- const res = await fetch(`${this.apiRoot}/v1/posts`, {
983
- method: "POST",
984
- headers: {
985
- ...this.defaultHeaders,
986
- Authorization: `Bearer ${this.userToken}`,
987
- },
988
- body: JSON.stringify({
989
- type: "post",
990
- assets: assetList,
991
- group_ids: [groupID],
992
- text: text,
993
- attachments: [],
994
- dms_disabled: disableDMs,
995
- comments_disabled: disableComments,
996
- using_identity: !anonymous,
997
- quote_post_id: repostId
998
- }),
999
- });
1000
- const json = await res.json();
1001
- return await json.posts[0];
1002
- } catch (err) {
1003
- console.error(err);
1004
- throw new SidechatAPIError(`Failed to make post.`);
1005
- }
1006
- };
1007
-
1008
- /**
1009
- * Deletes a post or comment that the user created
1010
- * @method
1011
- * @since 2.2.0
1012
- * @param {String} postOrCommentID - alphanumeric ID of post to delete
1013
- */
1014
- deletePostOrComment = async (postOrCommentID) => {
1015
- if (!this.userToken) {
1016
- throw new SidechatAPIError("User is not authenticated.");
1017
- }
1018
- try {
1019
- const res = await fetch(`${this.apiRoot}/v1/posts/delete`, {
1020
- method: "POST",
1021
- headers: {
1022
- ...this.defaultHeaders,
1023
- Authorization: `Bearer ${this.userToken}`,
1024
- },
1025
- body: JSON.stringify({
1026
- post_id: postOrCommentID,
1027
- }),
1028
- });
1029
- const json = await res.json();
1030
- return await json;
1031
- } catch (err) {
1032
- console.error(err);
1033
- throw new SidechatAPIError(`Failed to delete post.`);
1034
- }
1035
- };
1036
-
1037
- /**
1038
- * Votes on a poll attached to a post
1039
- * @method
1040
- * @param {String} pollId - alphanumeric ID of poll to vote on
1041
- * @param {Number} choiceIndex - index of the choice to vote on
1042
- * @since 2.5.4
1043
- */
1044
- voteOnPoll = async (pollId, choiceIndex) => {
1045
- if (!this.userToken) {
1046
- throw new SidechatAPIError("User is not authenticated.");
1047
- }
1048
- try {
1049
- const res = await fetch(`${this.apiRoot}/v1/polls/vote`, {
1050
- method: "POST",
1051
- headers: {
1052
- ...this.defaultHeaders,
1053
- Authorization: `Bearer ${this.userToken}`,
1054
- },
1055
- body: JSON.stringify({
1056
- poll_id: pollId,
1057
- choice: choiceIndex,
1058
- }),
1059
- });
1060
- const json = await res.json();
1061
- return await json;
1062
- } catch (err) {
1063
- console.error(err);
1064
- throw new SidechatAPIError(`Failed to vote on poll`);
1065
- }
1066
- };
1067
-
1068
- /**
1069
- * Marks that the user has viewed results on a poll. Note that this does not actually return the results of the poll.
1070
- * @method
1071
- * @param {String} pollId - alphanumeric ID of poll to vote on
1072
- * @since 2.5.4
1073
- */
1074
- viewPollResults = async (pollId) => {
1075
- if (!this.userToken) {
1076
- throw new SidechatAPIError("User is not authenticated.");
1077
- }
1078
- try {
1079
- const res = await fetch(`${this.apiRoot}/v1/polls/view_results`, {
1080
- method: "POST",
1081
- headers: {
1082
- ...this.defaultHeaders,
1083
- Authorization: `Bearer ${this.userToken}`,
1084
- },
1085
- body: JSON.stringify({
1086
- poll_id: pollId,
1087
- }),
1088
- });
1089
- const json = await res.json();
1090
- return await json;
1091
- } catch (err) {
1092
- console.error(err);
1093
- throw new SidechatAPIError(`Failed to mark poll results as viewed.`);
1094
- }
1095
- };
1096
-
1097
- /**
1098
- * Uploads an asset to AWS S3 for use in posts and comments. Currently photos only
1099
- * @method
1100
- * @param {String} uri - URI of the asset to upload
1101
- * @param {String} mimeType - mimetype of the asset (e.g. "image/png")
1102
- * @param {String} [name] - filename of the asset
1103
- * @returns {String} URL of the uploaded asset
1104
- * @since 2.5.1
1105
- */
1106
- uploadAsset = async (uri, mimeType, name = "") => {
1107
- if (!this.userToken) {
1108
- throw new SidechatAPIError("User is not authenticated.");
1109
- }
1110
-
1111
- let imageType = mimeType.split("/")[1];
1112
- if (!["png", "jpeg", "gif"].includes(imageType)) {
1113
- throw new SidechatAPIError("Unsupported image format.");
1114
- }
1115
-
1116
- const data = new FormData();
1117
- data.append("image", {
1118
- name: name,
1119
- type: mimeType,
1120
- uri: uri,
1121
- });
1122
-
1123
- const urlReq = await this.sendRequest(`/v1/assets/upload_url?content_type=${imageType}`);
1124
- const urlJson = await urlReq.json();
1125
-
1126
- try {
1127
- const uploadReq = await fetch(urlJson.upload_url, {
1128
- body: data.getAll("image")[0],
1129
- method: "PUT",
1130
- headers: {
1131
- "Content-Type": mimeType,
1132
- },
1133
- });
1134
- if (uploadReq.status == 200) {
1135
- return `${this.apiRoot}/v1/assets/library/${urlJson.asset_id}`;
1136
- } else {
1137
- throw new SidechatAPIError(
1138
- `Couldn't upload image - error ${uploadReq.status}`
1139
- );
1140
- }
1141
- } catch (e) {
1142
- throw new SidechatAPIError(e.message);
1143
- }
1144
- };
1145
-
1146
- /**
1147
- * Sets the conversation icon of a user
1148
- * @method
1149
- * @since 2.2.1
1150
- * @param {String} userID - alphanumeric ID of user
1151
- * @param {String} emoji - emoji to set as icon
1152
- * @param {String} primaryColor - hex string (including #) of primary color
1153
- * @param {String} secondaryColor - hex string (including #) of secondary color
1154
- */
1155
- setUserIcon = async (userID, emoji, primaryColor, secondaryColor) => {
1156
- if (!this.userToken) {
1157
- throw new SidechatAPIError("User is not authenticated.");
1158
- }
1159
- try {
1160
- const res = await fetch(`${this.apiRoot}/v1/users/${userID}`, {
1161
- method: "PATCH",
1162
- headers: {
1163
- ...this.defaultHeaders,
1164
- "App-Version": "0",
1165
- Authorization: `Bearer ${this.userToken}`,
1166
- },
1167
- body: JSON.stringify({
1168
- conversation_icon: {
1169
- emoji: emoji,
1170
- secondary_color: secondaryColor,
1171
- is_migrated: true,
1172
- color: primaryColor,
1173
- },
1174
- }),
1175
- });
1176
- const json = await res.json();
1177
- return await json;
1178
- } catch (err) {
1179
- console.error(err);
1180
- throw new SidechatAPIError(`Failed to set icon.`);
1181
- }
1182
- };
1183
-
1184
- /**
1185
- * Sets the bio text of a user
1186
- * @method
1187
- * @since 2.5.6
1188
- * @param {String} userID - alphanumeric ID of user
1189
- * @param {String} bio - text to set as bio
1190
- */
1191
- setUserBio = async (userID, bio) => {
1192
- if (!this.userToken) {
1193
- throw new SidechatAPIError("User is not authenticated.");
1194
- }
1195
- try {
1196
- const res = await fetch(`${this.apiRoot}/v1/users/${userID}`, {
1197
- method: "PATCH",
1198
- headers: {
1199
- ...this.defaultHeaders,
1200
- "App-Version": "5.4.22",
1201
- Authorization: `Bearer ${this.userToken}`,
1202
- },
1203
- body: JSON.stringify({
1204
- bio: bio
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 set bio.`);
1212
- }
1213
- };
1214
-
1215
- /**
1216
- * Checks if user can set their username to a string
1217
- * @method
1218
- * @since 2.3.6
1219
- * @param {String} username - string to check
1220
- * @returns {Boolean} whether or not username is valid and unused
1221
- */
1222
- checkUsername = async (username) => {
1223
- if (!this.userToken) {
1224
- throw new SidechatAPIError("User is not authenticated.");
1225
- }
1226
- try {
1227
- const res = await fetch(
1228
- `${this.apiRoot}/v1/users/username?username=${username}`,
1229
- {
1230
- method: "GET",
1231
- headers: {
1232
- ...this.defaultHeaders,
1233
- Authorization: `Bearer ${this.userToken}`,
1234
- },
1235
- }
1236
- );
1237
- if (res?.status == 200 || res?.status == 204) {
1238
- return true;
1239
- } else {
1240
- return false;
1241
- }
1242
- } catch (err) {
1243
- console.error(err);
1244
- throw new SidechatAPIError(`Failed to check username.`);
1245
- }
1246
- };
1247
-
1248
- /**
1249
- * Changes the username of the current user
1250
- * @method
1251
- * @since 2.3.6
1252
- * @param {String} userID - alphanumeric ID of user
1253
- * @param {String} username - new username to set
1254
- */
1255
- setUsername = async (userID, username) => {
1256
- if (!this.userToken) {
1257
- throw new SidechatAPIError("User is not authenticated.");
1258
- }
1259
- try {
1260
- const res = await fetch(`${this.apiRoot}/v1/users/${userID}`, {
1261
- method: "PATCH",
1262
- headers: {
1263
- ...this.defaultHeaders,
1264
- Authorization: `Bearer ${this.userToken}`,
1265
- },
1266
- body: JSON.stringify({
1267
- username: username,
1268
- }),
1269
- });
1270
- const json = await res.json();
1271
- return await json.user;
1272
- } catch (err) {
1273
- console.error(err);
1274
- throw new SidechatAPIError(`Failed to set icon.`);
1275
- }
1276
- };
1277
-
1278
- /**
1279
- * Fetches a public user profile
1280
- * @method
1281
- * @since 2.6.0
1282
- * @param {String} username - username of the user to fetch
1283
- * @returns {SidechatProfile}
1284
- */
1285
- getUserProfile = async (username) => {
1286
- if (!this.userToken) {
1287
- throw new SidechatAPIError("User is not authenticated.");
1288
- }
1289
- try {
1290
- const res = await fetch(`${this.apiRoot}/v1/groups/username?username=${username}`, {
1291
- method: "GET",
1292
- headers: {
1293
- ...this.defaultHeaders,
1294
- Authorization: `Bearer ${this.userToken}`,
1295
- }
1296
- });
1297
- const json = await res.json();
1298
- return await json.group;
1299
- } catch (err) {
1300
- console.error(err);
1301
- throw new SidechatAPIError(`Failed to set icon.`);
1302
- }
1303
- };
1304
-
1305
- /**
1306
- * Fetches a public user's posts
1307
- * @method
1308
- * @since 2.6.0
1309
- * @param {String} username - username of the user to fetch
1310
- * @returns {SidechatPostOrComment[]}
1311
- */
1312
- getUserPosts = async (username) => {
1313
- if (!this.userToken) {
1314
- throw new SidechatAPIError("User is not authenticated.");
1315
- }
1316
- try {
1317
- const res = await fetch(`${this.apiRoot}/v1/users/posts?username=${username}`, {
1318
- method: "GET",
1319
- headers: {
1320
- ...this.defaultHeaders,
1321
- Authorization: `Bearer ${this.userToken}`,
1322
- }
1323
- });
1324
- const json = await res.json();
1325
- return await json.posts;
1326
- } catch (err) {
1327
- console.error(err);
1328
- throw new SidechatAPIError(`Failed to set icon.`);
1329
- }
1330
- };
1331
-
1332
- /**
1333
- * Marks an activity item as read
1334
- * @method
1335
- * @since 2.3.2
1336
- * @param {String} activityID - alphanumeric ID of activity object
1337
- */
1338
- readActivity = async (activityID) => {
1339
- if (!this.userToken) {
1340
- throw new SidechatAPIError("User is not authenticated.");
1341
- }
1342
- try {
1343
- const res = await fetch(`${this.apiRoot}/v1/activity/seen`, {
1344
- method: "POST",
1345
- headers: {
1346
- ...this.defaultHeaders,
1347
- Authorization: `Bearer ${this.userToken}`,
1348
- },
1349
- body: JSON.stringify({
1350
- ids: [activityID],
1351
- }),
1352
- });
1353
- const json = await res.json();
1354
- return await json;
1355
- } catch (err) {
1356
- console.error(err);
1357
- throw new SidechatAPIError(`Failed to mark activity as read.`);
1358
- }
1359
- };
1360
-
1361
- /**
1362
- * Retrieves joinable group chats
1363
- * @method
1364
- * @since 2.3.5
1365
- */
1366
- getGroupChats = async () => {
1367
- if (!this.userToken) {
1368
- throw new SidechatAPIError("User is not authenticated.");
1369
- }
1370
- try {
1371
- const res = await fetch(`${this.apiRoot}/v1/chats/explore`, {
1372
- method: "GET",
1373
- headers: {
1374
- ...this.defaultHeaders,
1375
- Authorization: `Bearer ${this.userToken}`,
1376
- },
1377
- });
1378
- const json = await res.json();
1379
- return await json.chats;
1380
- } catch (err) {
1381
- console.error(err);
1382
- throw new SidechatAPIError(`Failed to get groupchats.`);
1383
- }
1384
- };
1385
-
1386
- /**
1387
- * Joins a group chat. To mimic the official client, use the user's display name and icon by default.
1388
- * @method
1389
- * @param {String} groupChatID - alphanumeric ID of group chat to join
1390
- * @param {String} displayName - display name to use in chat
1391
- * @param {String} emoji - emoji to use as icon
1392
- * @param {String} primaryColor - hex string of primary color
1393
- * @param {String} secondaryColor - hex string of secondary color
1394
- * @since 2.3.5
1395
- */
1396
- joinGroupChat = async (
1397
- groupChatID,
1398
- displayName,
1399
- emoji,
1400
- primaryColor,
1401
- secondaryColor
1402
- ) => {
1403
- if (!this.userToken) {
1404
- throw new SidechatAPIError("User is not authenticated.");
1405
- }
1406
- try {
1407
- const res = await fetch(`${this.apiRoot}/v1/chats/groups/join`, {
1408
- method: "POST",
1409
- headers: {
1410
- ...this.defaultHeaders,
1411
- Authorization: `Bearer ${this.userToken}`,
1412
- },
1413
- body: JSON.stringify({
1414
- chat_id: groupChatID,
1415
- identity: {
1416
- display_name: displayName,
1417
- emoji: emoji,
1418
- secondary_color: secondaryColor,
1419
- color: primaryColor,
1420
- },
1421
- }),
1422
- });
1423
- const json = await res.json();
1424
- return await json;
1425
- } catch (err) {
1426
- console.error(err);
1427
- throw new SidechatAPIError(`Failed to join groupchat.`);
1428
- }
1429
- };
1430
-
1431
- /**
1432
- * Gets a list of the user's direct messages
1433
- * @method
1434
- * @returns {SidechatDirectThread[]}
1435
- * @since 2.4.4
1436
- */
1437
- getDMs = async () => {
1438
- if (!this.userToken) {
1439
- throw new SidechatAPIError("User is not authenticated.");
1440
- }
1441
- try {
1442
- const res = await fetch(`${this.apiRoot}/v1/chats`, {
1443
- method: "GET",
1444
- headers: {
1445
- ...this.defaultHeaders,
1446
- Authorization: `Bearer ${this.userToken}`,
1447
- },
1448
- });
1449
- const json = await res.json();
1450
- const list = await json.chats;
1451
- let r = [];
1452
- list.forEach((o) => {
1453
- r.push(o.chat);
1454
- });
1455
- return await r;
1456
- } catch (err) {
1457
- console.error(err);
1458
- throw new SidechatAPIError(`Failed to fetch DMs.`);
1459
- }
1460
- };
1461
-
1462
- /**
1463
- * Gets a single direct message thread
1464
- * @method
1465
- * @param {String} id - alphanumeric ID of the chat to fetch
1466
- * @returns {SidechatDirectThread}
1467
- * @since 2.4.4
1468
- */
1469
- getDMThread = async (id) => {
1470
- if (!this.userToken) {
1471
- throw new SidechatAPIError("User is not authenticated.");
1472
- }
1473
- try {
1474
- const res = await fetch(
1475
- `${this.apiRoot}/v1/chats/messages?chat_id=${id}`,
1476
- {
1477
- method: "GET",
1478
- headers: {
1479
- ...this.defaultHeaders,
1480
- Authorization: `Bearer ${this.userToken}`,
1481
- },
1482
- }
1483
- );
1484
- const json = await res.json();
1485
- return await json.chat;
1486
- } catch (err) {
1487
- console.error(err);
1488
- throw new SidechatAPIError(`Failed to fetch DM thread.`);
1489
- }
1490
- };
1491
-
1492
- /**
1493
- * Sends a message to an existing direct message thread - note that you must first use startDM() to start a thread.
1494
- * @method
1495
- * @param {String} chatID - alphanumeric ID of the chat to send to
1496
- * @param {String} text - text content of message
1497
- * @param {String} clientID - alphanumeric device ID
1498
- * @param {SidechatAsset[]} assets - array of assets to send
1499
- * @param {Boolean} anonymous - whether the DM should be sent anonymously
1500
- * @since 2.4.4
1501
- */
1502
- sendDM = async (chatID, text, clientID, assets = [], anonymous = false) => {
1503
- if (!this.userToken) {
1504
- throw new SidechatAPIError("User is not authenticated.");
1505
- }
1506
- try {
1507
- const res = await fetch(`${this.apiRoot}/v1/chats/send`, {
1508
- method: "POST",
1509
- headers: {
1510
- ...this.defaultHeaders,
1511
- Authorization: `Bearer ${this.userToken}`,
1512
- },
1513
- body: JSON.stringify({
1514
- chat_id: chatID,
1515
- text: text,
1516
- client_id: clientID,
1517
- anonymous: anonymous,
1518
- assets: assets,
1519
- }),
1520
- });
1521
- const json = await res.json();
1522
- return await json;
1523
- } catch (err) {
1524
- console.error(err);
1525
- throw new SidechatAPIError(`Failed to send message.`);
1526
- }
1527
- };
1528
-
1529
- /**
1530
- * Creates a new direct message thread
1531
- * @method
1532
- * @param {String} text - text content of message
1533
- * @param {String} clientID - alphanumeric ID of devide
1534
- * @param {String} postID - alphanumeric ID of post or comment
1535
- * @param {Boolean} anonymous - whether the DM should be sent anonymously
1536
- * @param {"feed"} postContext - context of post (mostly undocumented, defaults to "feed")
1537
- * @since 2.4.4
1538
- */
1539
- startDM = async (
1540
- text,
1541
- clientID,
1542
- postID,
1543
- anonymous = false,
1544
- postContext = "feed"
1545
- ) => {
1546
- if (!this.userToken) {
1547
- throw new SidechatAPIError("User is not authenticated.");
1548
- }
1549
- try {
1550
- const res = await fetch(`${this.apiRoot}/v1/chats/start`, {
1551
- method: "POST",
1552
- headers: {
1553
- ...this.defaultHeaders,
1554
- Authorization: `Bearer ${this.userToken}`,
1555
- },
1556
- body: JSON.stringify({
1557
- text: text,
1558
- client_id: clientID,
1559
- post_id: postID,
1560
- anonymous: anonymous,
1561
- post_context: postContext,
1562
- }),
1563
- });
1564
- const json = await res.json();
1565
- return await json;
1566
- } catch (err) {
1567
- console.error(err);
1568
- throw new SidechatAPIError(`Failed to start DM.`);
1569
- }
1570
- };
1571
-
1572
- /**
1573
- * Hides posts from user
1574
- * @method
1575
- * @param {String} postID - alphanumeric ID of post to hide
1576
- * @since 2.6.2
1577
- */
1578
- hidePostsFromUser = async (postID) => {
1579
- if (!this.userToken) {
1580
- throw new SidechatAPIError("User is not authenticated.");
1581
- }
1582
- try {
1583
- const res = await fetch(`${this.apiRoot}/v1/posts/hide_posts_from_user`, {
1584
- method: "POST",
1585
- headers: {
1586
- ...this.defaultHeaders,
1587
- Authorization: `Bearer ${this.userToken}`,
1588
- },
1589
- body: JSON.stringify({
1590
- post_id: postID,
1591
- post_context: "feed",
1592
- report: false
1593
- }),
1594
- });
1595
- const json = await res.json();
1596
- return await json;
1597
- } catch (err) {
1598
- console.error(err);
1599
- throw new SidechatAPIError(`Failed to hide post.`);
1600
- }
1601
- };
1602
-
1603
- /**
1604
- * Unhides all posts from all users
1605
- * @method
1606
- * @since 2.6.2
1607
- */
1608
- unhidePostsFromAllUsers = async () => {
1609
- if (!this.userToken) {
1610
- throw new SidechatAPIError("User is not authenticated.");
1611
- }
1612
- try {
1613
- const res = await fetch(`${this.apiRoot}/v1/users/unhide_all`, {
1614
- method: "POST",
1615
- headers: {
1616
- ...this.defaultHeaders,
1617
- Authorization: `Bearer ${this.userToken}`,
1618
- },
1619
- body: JSON.stringify({}),
1620
- });
1621
- const json = await res.json();
1622
- return await json;
1623
- } catch (err) {
1624
- console.error(err);
1625
- throw new SidechatAPIError(`Failed to unhide post.`);
1626
- }
1627
- };
220
+ /** @import * as types from "../types/SidechatTypes.js" */
221
+
222
+ /**
223
+ * API client class for making requests to Sidechat's private API. You'll need to [authenticate]{@tutorial Authentication} before using most of the methods.
224
+ * @class
225
+ * @since 2.0.0-alpha.0
226
+ */
227
+ class SidechatAPIClient {
228
+ /**
229
+ * User bearer token
230
+ * @type {types.SidechatAuthToken}
231
+ * */
232
+ userToken;
233
+
234
+ /**
235
+ * Default headers for every API request
236
+ * @type {Object}
237
+ * @static
238
+ * @constant
239
+ */
240
+ defaultHeaders = {
241
+ Accept: "application/json",
242
+ "Content-Type": "application/json",
243
+ "App-Version": "6.0.0",
244
+ Dnt: 1,
245
+ };
246
+
247
+ /**
248
+ * Root URL for every API request
249
+ * @type {String}
250
+ * @default "https://api.sidechat.lol"
251
+ */
252
+ apiRoot = "https://api.sidechat.lol";
253
+
254
+ /**
255
+ * Create a new instance of the API client
256
+ * @param {types.SidechatAuthToken} [token] - user bearer token
257
+ * @param {String} rootUrl - custom API root URL for mocking or using other server
258
+ */
259
+ constructor(token = "", rootUrl = "") {
260
+ if (token) {
261
+ this.userToken = token;
262
+ }
263
+ if (rootUrl) {
264
+ this.apiRoot = rootUrl;
265
+ }
266
+ }
267
+
268
+ /**
269
+ * 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
270
+ * @method
271
+ * @param {types.SidechatAuthToken} token - user bearer token
272
+ */
273
+ setToken = (token) => {
274
+ this.userToken = token;
275
+ };
276
+
277
+ /**
278
+ * Manually set the root URL for all API requests. This can be used for mocking requests or redirecting them to a different server
279
+ * @method
280
+ * @param {String} url - new root URL to set
281
+ * @since 2.3.9
282
+ */
283
+ setAPIRoot = (url) => {
284
+ this.apiRoot = url;
285
+ };
286
+
287
+ /**
288
+ * Run an arbitrary API request using the current client's authentication
289
+ * @method
290
+ * @param {String} endpoint - API endpoint to request (e.g. "/v1/posts")
291
+ * @param {"GET"|"POST"|"PUT"|"DELETE"|"PATCH"|"OPTIONS"} [method] - HTTP method to use
292
+ * @param {Object} [body] - body to send with the request
293
+ * @param {Object} [headers] - custom headers to send with the request
294
+ * @param {Boolean} [stripHeaders] - remove the default headers from the request
295
+ * @since 2.4.9
296
+ */
297
+ sendRequest = (
298
+ endpoint,
299
+ method = "GET",
300
+ body = undefined,
301
+ headers = {},
302
+ stripHeaders = false
303
+ ) => {
304
+ let requestHeaders = this.defaultHeaders;
305
+ if (stripHeaders) {
306
+ headers = {};
307
+ }
308
+ requestHeaders = { ...requestHeaders, ...headers };
309
+ return fetch(`${this.apiRoot}${endpoint}`, {
310
+ headers: { Authorization: `Bearer ${this.userToken}`, ...requestHeaders },
311
+ body: body,
312
+ method: method,
313
+ });
314
+ };
315
+
316
+ /**
317
+ * Initiate the login process with a phone number. Should be followed up with verifySMSCode().
318
+ * @method
319
+ * @since 1.0.0
320
+ * @param {Number} phoneNumber - US phone number (WITHOUT +1) to send verification code to
321
+ */
322
+ loginViaSMS = async (phoneNumber) => {
323
+ try {
324
+ const res = await fetch(`${this.apiRoot}/v1/login_register`, {
325
+ method: "POST",
326
+ headers: this.defaultHeaders,
327
+ body: JSON.stringify({
328
+ phone_number: `+1${phoneNumber}`,
329
+ version: 3,
330
+ }),
331
+ });
332
+ const json = await res.json();
333
+ return json;
334
+ } catch (err) {
335
+ console.error(err);
336
+ throw new SidechatAPIError("Failed to request SMS verification.");
337
+ }
338
+ };
339
+
340
+ /**
341
+ * Verify the code sent via SMS with loginViaSMS(). If this function succeeds, the user will be authenticated for future requests.
342
+ * @method
343
+ * @since 1.0.0
344
+ * @param {Number} phoneNumber - US phone number (WITHOUT +1) that verification code was sent to
345
+ * @param {String} code - the verification code
346
+ */
347
+ verifySMSCode = async (phoneNumber, code) => {
348
+ try {
349
+ const res = await fetch(`${this.apiRoot}/v1/verify_phone_number`, {
350
+ method: "POST",
351
+ headers: this.defaultHeaders,
352
+ body: JSON.stringify({
353
+ phone_number: `+1${phoneNumber}`,
354
+ code: code.toUpperCase(),
355
+ }),
356
+ });
357
+ const json = await res.json();
358
+ if (json?.logged_in_user?.token) {
359
+ this.userToken = json.logged_in_user.token;
360
+ }
361
+ return json;
362
+ } catch (err) {
363
+ console.error(err);
364
+ throw new SidechatAPIError("Failed verify this code.");
365
+ }
366
+ };
367
+
368
+ /**
369
+ * Set the user's age. If this function succeeds, the user will be authenticated for future requests.
370
+ * @method
371
+ * @since 1.0.0
372
+ * @param {Number} age - user's age in years
373
+ * @param {String} registrationID - the registration ID generated by verifySMSCode()
374
+ */
375
+ setAge = async (age, registrationID) => {
376
+ if (age < 13) {
377
+ throw new SidechatAPIError("You're too young to use Offsides.");
378
+ }
379
+ try {
380
+ const res = await fetch(`${this.apiRoot}/v1/complete_registration`, {
381
+ method: "POST",
382
+ headers: this.defaultHeaders,
383
+ body: JSON.stringify({
384
+ age: Number(age),
385
+ registration_id: registrationID,
386
+ }),
387
+ });
388
+ const json = await res.json();
389
+ if (json.token) {
390
+ this.userToken = json.token;
391
+ }
392
+ return json;
393
+ } catch (err) {
394
+ console.error(err);
395
+ throw new SidechatAPIError("Failed verify this code.");
396
+ }
397
+ };
398
+
399
+ /**
400
+ * Initiate the email setup process. Should be followed up with checkEmailVerification().
401
+ * @method
402
+ * @since 1.0.0
403
+ * @param {String} email - school email address to send verification code to
404
+ * @tutorial Email Registration
405
+ */
406
+ registerEmail = async (email) => {
407
+ if (!this.userToken) {
408
+ throw new SidechatAPIError("User is not authenticated.");
409
+ }
410
+ try {
411
+ const res = await fetch(`${this.apiRoot}/v2/users/register_email`, {
412
+ method: "POST",
413
+ headers: {
414
+ ...this.defaultHeaders,
415
+ Authorization: `Bearer ${this.userToken}`,
416
+ },
417
+ body: JSON.stringify({
418
+ email: email,
419
+ }),
420
+ });
421
+ const json = await res.json();
422
+ if (json.message) {
423
+ throw new SidechatAPIError(json.message);
424
+ }
425
+ return json;
426
+ } catch (err) {
427
+ console.error(err);
428
+ throw new SidechatAPIError("Failed to request email verification.");
429
+ }
430
+ };
431
+
432
+ /**
433
+ * Check is the user's email is verified.
434
+ * @method
435
+ * @since 1.0.0
436
+ */
437
+ checkEmailVerification = async () => {
438
+ if (!this.userToken) {
439
+ throw new SidechatAPIError("User is not authenticated.");
440
+ }
441
+ try {
442
+ const res = await fetch(`${this.apiRoot}/v1/users/check_email_verified`, {
443
+ method: "GET",
444
+ headers: {
445
+ ...this.defaultHeaders,
446
+ Authorization: `Bearer ${this.userToken}`,
447
+ },
448
+ });
449
+ const json = await res.json();
450
+ if (json.verified_email_updates_response) {
451
+ return json.verified_email_updates_response;
452
+ } else if (json.changing_phone_number_verified_email_user) {
453
+ return json.changing_phone_number_verified_email_user;
454
+ } else {
455
+ throw new SidechatAPIError(json?.message || "Email is not verified.");
456
+ }
457
+ } catch (err) {
458
+ console.error(err);
459
+ throw new SidechatAPIError("Email is not verified.");
460
+ }
461
+ };
462
+
463
+ /**
464
+ * Set the device ID of the current user
465
+ * @method
466
+ * @since 1.0.0
467
+ * @param {String} deviceId - the device ID to set
468
+ */
469
+ setDeviceID = async (deviceID) => {
470
+ if (!this.userToken) {
471
+ throw new SidechatAPIError("User is not authenticated.");
472
+ }
473
+ try {
474
+ const res = await fetch(`${this.apiRoot}/v1/register_device_token`, {
475
+ method: "POST",
476
+ headers: {
477
+ ...this.defaultHeaders,
478
+ Authorization: `Bearer ${this.userToken}`,
479
+ },
480
+ body: JSON.stringify({
481
+ build_type: "release",
482
+ bundle_id: "com.flowerave.sidechat",
483
+ device_token: deviceID,
484
+ }),
485
+ });
486
+ const json = await res.json();
487
+ return json;
488
+ } catch (err) {
489
+ console.error(err);
490
+ throw new SidechatAPIError("Failed verify this code.");
491
+ }
492
+ };
493
+
494
+ /**
495
+ * Get updated status for user and group
496
+ * @method
497
+ * @since 1.0.0
498
+ * @deprecated since 2.1.0, will be removed by 3.0.0. Please use `getUpdates` instead!
499
+ * @param {String} [groupID] - ID of a specific group to retrieve info from. Falls back to user's primary group.
500
+ */
501
+ getUserAndGroup = async (groupID = "") => {
502
+ const json = await this.getUpdates(groupID);
503
+ return json;
504
+ };
505
+
506
+ /**
507
+ * Get updated status for user and group
508
+ * @method
509
+ * @since 2.1.0
510
+ * @param {String} [groupID] - ID of a specific group to retrieve info from. Falls back to user's primary group.
511
+ */
512
+ getUpdates = async (groupID = "") => {
513
+ if (!this.userToken) {
514
+ throw new SidechatAPIError("User is not authenticated.");
515
+ }
516
+ try {
517
+ const res = await fetch(
518
+ `${this.apiRoot}/v1/updates?group_id=${groupID}`,
519
+ {
520
+ method: "GET",
521
+ headers: {
522
+ ...this.defaultHeaders,
523
+ Authorization: `Bearer ${this.userToken}`,
524
+ },
525
+ }
526
+ );
527
+ const json = await res.json();
528
+ return json;
529
+ } catch (err) {
530
+ console.error(err);
531
+ throw new SidechatAPIError(`Failed to get posts from group.`);
532
+ }
533
+ };
534
+
535
+ /**
536
+ * Fetches posts from the specified category in a group
537
+ * @method
538
+ * @since 1.0.0
539
+ * @param {String} groupID - group ID
540
+ * @param {"hot"|"recent"|"top"} category - category to filter posts
541
+ * @param {types.SidechatCursorString} [cursor] - cursor string
542
+ * @returns {Promise<types.SidechatPostsAndCursor>} List of posts and cursor
543
+ */
544
+ getGroupPosts = async (groupID, category = "hot", cursor) => {
545
+ if (!this.userToken) {
546
+ throw new SidechatAPIError("User is not authenticated.");
547
+ }
548
+ try {
549
+ const res = await fetch(
550
+ `${this.apiRoot}/v1/posts?${cursor ? "cursor=" + encodeURIComponent(cursor) + "&" : ""
551
+ }group_id=${groupID}&type=${category}`,
552
+ {
553
+ method: "GET",
554
+ headers: {
555
+ ...this.defaultHeaders,
556
+ Authorization: `Bearer ${this.userToken}`,
557
+ },
558
+ }
559
+ );
560
+ const json = await res.json();
561
+ return json;
562
+ } catch (err) {
563
+ console.error(err);
564
+ throw new SidechatAPIError(`Failed to get posts from group.`);
565
+ }
566
+ };
567
+
568
+ /**
569
+ * Upvote or downvote, or unvote a post
570
+ * @method
571
+ * @since 2.0.0-alpha.0
572
+ * @param {String} postID - post ID to vote on
573
+ * @param {types.SidechatVoteString} action - whether to upvote, downvote, or reset vote
574
+ */
575
+ setVote = async (postID, action) => {
576
+ if (!this.userToken) {
577
+ throw new SidechatAPIError("User is not authenticated.");
578
+ }
579
+ try {
580
+ const res = await fetch(`${this.apiRoot}/v1/posts/set_vote`, {
581
+ method: "POST",
582
+ headers: {
583
+ ...this.defaultHeaders,
584
+ Authorization: `Bearer ${this.userToken}`,
585
+ },
586
+ body: JSON.stringify({
587
+ post_id: postID,
588
+ vote_status: action,
589
+ }),
590
+ });
591
+ const json = await res.json();
592
+ return json;
593
+ } catch (err) {
594
+ console.error(err);
595
+ throw new SidechatAPIError(`Failed to change the vote on post.`);
596
+ }
597
+ };
598
+
599
+ /**
600
+ * Fetches a single post with just its ID
601
+ * @method
602
+ * @since 2.3.0
603
+ * @param {String} postID - ID of post to fetch
604
+ * @param {Boolean} includeDeleted - undocumented
605
+ * @returns {Promise<types.SidechatPostOrComment>} post object
606
+ */
607
+ getPost = async (postID, includeDeleted = false) => {
608
+ if (!this.userToken) {
609
+ throw new SidechatAPIError("User is not authenticated.");
610
+ }
611
+ try {
612
+ const res = await fetch(
613
+ `${this.apiRoot}/v1/posts/get?include_deleted=${includeDeleted}&post_id=${postID}`,
614
+ {
615
+ method: "GET",
616
+ headers: {
617
+ ...this.defaultHeaders,
618
+ Authorization: `Bearer ${this.userToken}`,
619
+ },
620
+ }
621
+ );
622
+ const json = await res.json();
623
+ return json.post;
624
+ } catch (err) {
625
+ console.error(err);
626
+ throw new SidechatAPIError(`Failed to get post from ID.`);
627
+ }
628
+ };
629
+
630
+ /**
631
+ * Fetches the posts or comments that the user has created
632
+ * @method
633
+ * @since 2.3.5
634
+ * @param {"posts"|"comments"} contentType - type of user content to fetch
635
+ * @returns {Promise<types.SidechatPostOrComment[]>} post object
636
+ */
637
+ getUserContent = async (contentType) => {
638
+ if (!this.userToken) {
639
+ throw new SidechatAPIError("User is not authenticated.");
640
+ }
641
+ if (contentType == "posts") {
642
+ contentType = "my_posts";
643
+ } else if (contentType == "comments") {
644
+ contentType = "my_comments";
645
+ }
646
+ try {
647
+ const res = await fetch(`${this.apiRoot}/v1/posts&type=${contentType}`, {
648
+ method: "GET",
649
+ headers: {
650
+ ...this.defaultHeaders,
651
+ Authorization: `Bearer ${this.userToken}`,
652
+ },
653
+ });
654
+ const json = await res.json();
655
+ return json.posts;
656
+ } catch (err) {
657
+ console.error(err);
658
+ throw new SidechatAPIError(`Failed to get content from user.`);
659
+ }
660
+ };
661
+
662
+ /**
663
+ * Get all the commments on a post
664
+ * @method
665
+ * @since 2.0.0-alpha.0
666
+ * @param {String} postID - post ID to get comments for
667
+ * @returns {Promise<types.SidechatPostOrComment[]>} list of comments
668
+ */
669
+ getPostComments = async (postID) => {
670
+ if (!this.userToken) {
671
+ throw new SidechatAPIError("User is not authenticated.");
672
+ }
673
+ try {
674
+ const res = await fetch(
675
+ `${this.apiRoot}/v1/posts/comments/?post_id=${postID}`,
676
+ {
677
+ method: "GET",
678
+ headers: {
679
+ ...this.defaultHeaders,
680
+ Authorization: `Bearer ${this.userToken}`,
681
+ },
682
+ }
683
+ );
684
+ const json = await res.json();
685
+ // Function to preprocess the comments and organize them into a nested structure
686
+ function preprocessComments(apiComments) {
687
+ // Map to store comments by their IDs for efficient lookup
688
+ const commentMap = new Map();
689
+ // List to store top-level comments
690
+ const topLevelComments = [];
691
+
692
+ // Iterate through the API comments
693
+ apiComments.forEach((comment) => {
694
+ // Store the comment in the map with its ID as the key
695
+ commentMap.set(comment.id, comment);
696
+ // Get the parent comment using the reply_post_id
697
+ const parentComment = commentMap.get(comment.reply_post_id);
698
+ // Check if the comment is a top-level comment
699
+ if (
700
+ !parentComment ||
701
+ comment.reply_post_id === comment.parent_post_id
702
+ ) {
703
+ // If it's a top-level comment, push it to the topLevelComments array
704
+ topLevelComments.push(comment);
705
+ } else {
706
+ // If it's a reply, add it to the parent comment's replies array
707
+ if (!parentComment.replies) parentComment.replies = [];
708
+ parentComment.replies.push(comment);
709
+ }
710
+ });
711
+
712
+ // Flatten the nested structure and return a single list of comments
713
+ return flattenComments(topLevelComments);
714
+ }
715
+
716
+ // Function to flatten nested comments into a single list
717
+ function flattenComments(comments) {
718
+ // Use reduce to flatten the nested comments array into a single list
719
+ return comments.reduce((flatComments, comment) => {
720
+ // Push the current comment to the flatComments array
721
+ flatComments.push(comment);
722
+ // If the current comment has replies, recursively flatten them and push to the flatComments array
723
+ if (comment.replies)
724
+ flatComments.push(...flattenComments(comment.replies));
725
+ // Return the flatComments array
726
+ return flatComments;
727
+ }, []);
728
+ }
729
+
730
+ const sortedComments = preprocessComments(json.posts);
731
+ return sortedComments;
732
+ } catch (err) {
733
+ console.error(err);
734
+ throw new SidechatAPIError(`Failed to get comments on post.`);
735
+ }
736
+ };
737
+
738
+ /**
739
+ * Gets groups to be displayed on the "Explore Groups" page
740
+ * @method
741
+ * @since 2.0.0-alpha.0
742
+ * @param {Boolean} onePage - whether or not results should be returned as a single page
743
+ * @returns {Promise<types.SidechatGroup[]>}
744
+ */
745
+ getAvailableGroups = async (onePage = true) => {
746
+ if (!this.userToken) {
747
+ throw new SidechatAPIError("User is not authenticated.");
748
+ }
749
+ try {
750
+ const res = await fetch(`${this.apiRoot}/v1/groups/explore`, {
751
+ method: "GET",
752
+ headers: {
753
+ ...this.defaultHeaders,
754
+ "App-Version": onePage ? "0" : this.defaultHeaders["App-Version"],
755
+ Authorization: `Bearer ${this.userToken}`,
756
+ },
757
+ });
758
+ const json = await res.json();
759
+ return await json.groups;
760
+ } catch (err) {
761
+ console.error(err);
762
+ throw new SidechatAPIError(`Failed to get groups from explore.`);
763
+ }
764
+ };
765
+
766
+ /**
767
+ * Searches for new groups based on a query keyword
768
+ * @method
769
+ * @since 2.6.0
770
+ * @param {String} query - the string to search for. This will be encoded, so strings with spaces and special characters are okay.
771
+ * @returns {Promise<types.SidechatGroup[]>}
772
+ */
773
+ searchAvailableGroups = async (query) => {
774
+ if (!this.userToken) {
775
+ throw new SidechatAPIError("User is not authenticated.");
776
+ }
777
+ try {
778
+ const res = await fetch(`${this.apiRoot}/v1/groups/explore/search?term=${encodeURIComponent(query)}`, {
779
+ method: "GET",
780
+ headers: {
781
+ ...this.defaultHeaders,
782
+ Authorization: `Bearer ${this.userToken}`,
783
+ },
784
+ });
785
+ const json = await res.json();
786
+ return await json.results;
787
+ } catch (err) {
788
+ console.error(err);
789
+ throw new SidechatAPIError(`Failed to search groups.`);
790
+ }
791
+ };
792
+
793
+ /**
794
+ * 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.
795
+ * @method
796
+ * @since 2.0.6
797
+ * @returns {Promise<types.SidechatLibraryAsset[]>}
798
+ */
799
+ getAssetLibrary = async () => {
800
+ if (!this.userToken) {
801
+ throw new SidechatAPIError("User is not authenticated.");
802
+ }
803
+ try {
804
+ const res = await fetch(`${this.apiRoot}/v1/assets/library`, {
805
+ method: "GET",
806
+ headers: {
807
+ ...this.defaultHeaders,
808
+ Authorization: `Bearer ${this.userToken}`,
809
+ },
810
+ });
811
+ const json = await res.json();
812
+ return await json.items;
813
+ } catch (err) {
814
+ console.error(err);
815
+ throw new SidechatAPIError(`Failed to get asset library.`);
816
+ }
817
+ };
818
+
819
+ /**
820
+ * Gets the current authenticated user and a list of the groups of which they are members.
821
+ * @method
822
+ * @since 2.1.0
823
+ * @returns {Promise<types.SidechatCurrentUser>}
824
+ */
825
+ getCurrentUser = async () => {
826
+ if (!this.userToken) {
827
+ throw new SidechatAPIError("User is not authenticated.");
828
+ }
829
+ try {
830
+ const res = await fetch(`${this.apiRoot}/v1/users/me`, {
831
+ method: "GET",
832
+ headers: {
833
+ ...this.defaultHeaders,
834
+ Authorization: `Bearer ${this.userToken}`,
835
+ },
836
+ });
837
+ const json = await res.json();
838
+ return await json;
839
+ } catch (err) {
840
+ console.error(err);
841
+ throw new SidechatAPIError(`Failed to get asset library.`);
842
+ }
843
+ };
844
+
845
+ /**
846
+ * Gets the metadata of a group from its ID
847
+ * @method
848
+ * @since 2.1.0
849
+ * @param {String} [groupID] - alphanumeric ID of a group to get. Falls back to user's primary group.
850
+ * @returns {Promise<types.SidechatGroup>}
851
+ */
852
+ getGroupMetadata = async (groupID = "") => {
853
+ if (!this.userToken) {
854
+ throw new SidechatAPIError("User is not authenticated.");
855
+ }
856
+ try {
857
+ const res = await fetch(`${this.apiRoot}/v1/groups/${groupID}`, {
858
+ method: "GET",
859
+ headers: {
860
+ ...this.defaultHeaders,
861
+ Authorization: `Bearer ${this.userToken}`,
862
+ },
863
+ });
864
+ const json = await res.json();
865
+ return await json.group;
866
+ } catch (err) {
867
+ console.error(err);
868
+ throw new SidechatAPIError(`Failed to get group metadata.`);
869
+ }
870
+ };
871
+
872
+ /**
873
+ * Joins or leaves a group
874
+ * @method
875
+ * @param {String} groupID - alphanumeric ID of group to join or leave
876
+ * @param {Boolean} isMember - whether or not the user should be a member of the group
877
+ * @since 2.3.8
878
+ */
879
+ setGroupMembership = async (groupID, isMember) => {
880
+ if (!this.userToken) {
881
+ throw new SidechatAPIError("User is not authenticated.");
882
+ }
883
+ try {
884
+ const res = await fetch(
885
+ `${this.apiRoot}/v1/groups/${isMember ? "join" : "leave"}`,
886
+ {
887
+ method: "POST",
888
+ headers: {
889
+ ...this.defaultHeaders,
890
+ Authorization: `Bearer ${this.userToken}`,
891
+ },
892
+ body: JSON.stringify({
893
+ group_id: groupID,
894
+ }),
895
+ }
896
+ );
897
+ const json = await res.json();
898
+ return await json;
899
+ } catch (err) {
900
+ console.error(err);
901
+ throw new SidechatAPIError(`Failed to modify group membership.`);
902
+ }
903
+ };
904
+
905
+ /**
906
+ * Creates a comment on a post
907
+ * @method
908
+ * @since 2.2.0
909
+ * @param {String} parentPostID - alphanumeric ID of post on which this comment is made
910
+ * @param {String} text - text content of comment
911
+ * @param {String} groupID - alphanumeric ID of group in which the parent post resides
912
+ * @param {String} [replyCommentID] - alphanumeric ID of comment to reply to. Falls back to parentPostID
913
+ * @param {String} [topLevelReplyID] - alphanumeric ID of the top-level comment to reply to. Used only when replying to replies. Falls back to parentPostID
914
+ * @param {types.SidechatSimpleAsset[]} [assetList] - list of assets to attach
915
+ * @param {Boolean} [disableDMs] - prevent direct messages being sent to comment's author
916
+ * @param {Boolean} [anonymous] - whether or not to hide user's name and icon on comment
917
+ * @returns {Promise<types.SidechatPostOrComment>} created comment
918
+ */
919
+ createComment = async (
920
+ parentPostID,
921
+ text,
922
+ groupID,
923
+ replyCommentID,
924
+ topLevelReplyID,
925
+ assetList = [],
926
+ disableDMs = false,
927
+ anonymous = false
928
+ ) => {
929
+ if (!this.userToken) {
930
+ throw new SidechatAPIError("User is not authenticated.");
931
+ }
932
+ try {
933
+ const res = await fetch(`${this.apiRoot}/v1/posts`, {
934
+ method: "POST",
935
+ headers: {
936
+ ...this.defaultHeaders,
937
+ Authorization: `Bearer ${this.userToken}`,
938
+ },
939
+ body: JSON.stringify({
940
+ type: "comment",
941
+ assets: assetList,
942
+ group_ids: [groupID],
943
+ text: text,
944
+ reply_post_id: topLevelReplyID || replyCommentID || parentPostID,
945
+ reply_comment_post_id: replyCommentID || parentPostID,
946
+ parent_post_id: parentPostID,
947
+ dms_disabled: disableDMs,
948
+ using_identity: !anonymous,
949
+ }),
950
+ });
951
+ const json = await res.json();
952
+ return await json.comment;
953
+ } catch (err) {
954
+ console.error(err);
955
+ throw new SidechatAPIError(`Failed to post comment.`);
956
+ }
957
+ };
958
+
959
+ /**
960
+ * Creates a new post in the specified group
961
+ * @method
962
+ * @since 2.2.0
963
+ * @param {String} text - text content of comment
964
+ * @param {String} groupID - alphanumeric ID of group in which the parent post resides
965
+ * @param {types.SidechatSimpleAsset[]} [assetList] - list of assets to attach.
966
+ * @param {Boolean} [disableDMs] - prevent direct messages from being sent to post's author
967
+ * @param {Boolean} [disableComments] - whether or not comments should be disabled on post
968
+ * @param {Boolean} [anonymous] - whether or not to hide user's name and icon on post
969
+ * @param {Array<String>} [pollOptions] - List of poll options. If provided, a poll will be created with these options.
970
+ * @returns {Promise<types.SidechatPostOrComment>} the created post
971
+ */
972
+ createPost = async (
973
+ text,
974
+ groupID,
975
+ assetList = [],
976
+ disableDMs = false,
977
+ disableComments = false,
978
+ anonymous = false,
979
+ repostId = undefined,
980
+ pollOptions = undefined
981
+ ) => {
982
+ if (!this.userToken) {
983
+ throw new SidechatAPIError("User is not authenticated.");
984
+ }
985
+ try {
986
+ // Build the request body
987
+ const body = {
988
+ type: "post",
989
+ assets: assetList,
990
+ group_ids: [groupID],
991
+ text: text,
992
+ attachments: [],
993
+ dms_disabled: disableDMs,
994
+ comments_disabled: disableComments,
995
+ using_identity: !anonymous,
996
+ quote_post_id: repostId
997
+ };
998
+ // If pollOptions is provided and is a non-empty array, add poll_request
999
+ if (Array.isArray(pollOptions) && pollOptions.length > 0) {
1000
+ body.poll_request = {
1001
+ allows_view_results: true,
1002
+ choices: pollOptions
1003
+ };
1004
+ }
1005
+ const res = await fetch(`${this.apiRoot}/v1/posts`, {
1006
+ method: "POST",
1007
+ headers: {
1008
+ ...this.defaultHeaders,
1009
+ Authorization: `Bearer ${this.userToken}`,
1010
+ },
1011
+ body: JSON.stringify(body),
1012
+ });
1013
+ const json = await res.json();
1014
+ return await json.posts[0];
1015
+ } catch (err) {
1016
+ console.error(err);
1017
+ throw new SidechatAPIError(`Failed to make post.`);
1018
+ }
1019
+ };
1020
+
1021
+ /**
1022
+ * Deletes a post or comment that the user created
1023
+ * @method
1024
+ * @since 2.2.0
1025
+ * @param {String} postOrCommentID - alphanumeric ID of post to delete
1026
+ */
1027
+ deletePostOrComment = async (postOrCommentID) => {
1028
+ if (!this.userToken) {
1029
+ throw new SidechatAPIError("User is not authenticated.");
1030
+ }
1031
+ try {
1032
+ const res = await fetch(`${this.apiRoot}/v1/posts/delete`, {
1033
+ method: "POST",
1034
+ headers: {
1035
+ ...this.defaultHeaders,
1036
+ Authorization: `Bearer ${this.userToken}`,
1037
+ },
1038
+ body: JSON.stringify({
1039
+ post_id: postOrCommentID,
1040
+ }),
1041
+ });
1042
+ const json = await res.json();
1043
+ return await json;
1044
+ } catch (err) {
1045
+ console.error(err);
1046
+ throw new SidechatAPIError(`Failed to delete post.`);
1047
+ }
1048
+ };
1049
+
1050
+ /**
1051
+ * Votes on a poll attached to a post
1052
+ * @method
1053
+ * @param {String} pollId - alphanumeric ID of poll to vote on
1054
+ * @param {Number} choiceIndex - index of the choice to vote on
1055
+ * @since 2.5.4
1056
+ */
1057
+ voteOnPoll = async (pollId, choiceIndex) => {
1058
+ if (!this.userToken) {
1059
+ throw new SidechatAPIError("User is not authenticated.");
1060
+ }
1061
+ try {
1062
+ const res = await fetch(`${this.apiRoot}/v1/polls/vote`, {
1063
+ method: "POST",
1064
+ headers: {
1065
+ ...this.defaultHeaders,
1066
+ Authorization: `Bearer ${this.userToken}`,
1067
+ },
1068
+ body: JSON.stringify({
1069
+ poll_id: pollId,
1070
+ choice: choiceIndex,
1071
+ }),
1072
+ });
1073
+ const json = await res.json();
1074
+ return await json;
1075
+ } catch (err) {
1076
+ console.error(err);
1077
+ throw new SidechatAPIError(`Failed to vote on poll`);
1078
+ }
1079
+ };
1080
+
1081
+ /**
1082
+ * Marks that the user has viewed results on a poll. Note that this does not actually return the results of the poll.
1083
+ * @method
1084
+ * @param {String} pollId - alphanumeric ID of poll to vote on
1085
+ * @since 2.5.4
1086
+ */
1087
+ viewPollResults = async (pollId) => {
1088
+ if (!this.userToken) {
1089
+ throw new SidechatAPIError("User is not authenticated.");
1090
+ }
1091
+ try {
1092
+ const res = await fetch(`${this.apiRoot}/v1/polls/view_results`, {
1093
+ method: "POST",
1094
+ headers: {
1095
+ ...this.defaultHeaders,
1096
+ Authorization: `Bearer ${this.userToken}`,
1097
+ },
1098
+ body: JSON.stringify({
1099
+ poll_id: pollId,
1100
+ }),
1101
+ });
1102
+ const json = await res.json();
1103
+ return await json;
1104
+ } catch (err) {
1105
+ console.error(err);
1106
+ throw new SidechatAPIError(`Failed to mark poll results as viewed.`);
1107
+ }
1108
+ };
1109
+
1110
+ /**
1111
+ * Uploads an asset to AWS S3 for use in posts and comments. Currently photos only
1112
+ * @method
1113
+ * @param {String} uri - URI of the asset to upload
1114
+ * @param {String} mimeType - mimetype of the asset (e.g. "image/png")
1115
+ * @param {String} [name] - filename of the asset
1116
+ * @returns {Promise<String>} URL of the uploaded asset
1117
+ * @since 2.5.1
1118
+ */
1119
+ uploadAsset = async (uri, mimeType, name = "") => {
1120
+ if (!this.userToken) {
1121
+ throw new SidechatAPIError("User is not authenticated.");
1122
+ }
1123
+
1124
+ let imageType = mimeType.split("/")[1];
1125
+ if (!["png", "jpeg", "gif"].includes(imageType)) {
1126
+ throw new SidechatAPIError("Unsupported image format.");
1127
+ }
1128
+
1129
+ const data = new FormData();
1130
+ data.append("image", {
1131
+ name: name,
1132
+ type: mimeType,
1133
+ uri: uri,
1134
+ });
1135
+
1136
+ const urlReq = await this.sendRequest(`/v1/assets/upload_url?content_type=${imageType}`);
1137
+ const urlJson = await urlReq.json();
1138
+
1139
+ try {
1140
+ const uploadReq = await fetch(urlJson.upload_url, {
1141
+ body: data.getAll("image")[0],
1142
+ method: "PUT",
1143
+ headers: {
1144
+ "Content-Type": mimeType,
1145
+ },
1146
+ });
1147
+ if (uploadReq.status == 200) {
1148
+ return `${this.apiRoot}/v1/assets/library/${urlJson.asset_id}`;
1149
+ } else {
1150
+ throw new SidechatAPIError(
1151
+ `Couldn't upload image - error ${uploadReq.status}`
1152
+ );
1153
+ }
1154
+ } catch (e) {
1155
+ throw new SidechatAPIError(e.message);
1156
+ }
1157
+ };
1158
+
1159
+ /**
1160
+ * Sets the conversation icon of a user
1161
+ * @method
1162
+ * @since 2.2.1
1163
+ * @param {String} userID - alphanumeric ID of user
1164
+ * @param {String} emoji - emoji to set as icon
1165
+ * @param {String} primaryColor - hex string (including #) of primary color
1166
+ * @param {String} secondaryColor - hex string (including #) of secondary color
1167
+ */
1168
+ setUserIcon = async (userID, emoji, primaryColor, secondaryColor) => {
1169
+ if (!this.userToken) {
1170
+ throw new SidechatAPIError("User is not authenticated.");
1171
+ }
1172
+ try {
1173
+ const res = await fetch(`${this.apiRoot}/v1/users/${userID}`, {
1174
+ method: "PATCH",
1175
+ headers: {
1176
+ ...this.defaultHeaders,
1177
+ "App-Version": "0",
1178
+ Authorization: `Bearer ${this.userToken}`,
1179
+ },
1180
+ body: JSON.stringify({
1181
+ conversation_icon: {
1182
+ emoji: emoji,
1183
+ secondary_color: secondaryColor,
1184
+ is_migrated: true,
1185
+ color: primaryColor,
1186
+ },
1187
+ }),
1188
+ });
1189
+ const json = await res.json();
1190
+ return await json;
1191
+ } catch (err) {
1192
+ console.error(err);
1193
+ throw new SidechatAPIError(`Failed to set icon.`);
1194
+ }
1195
+ };
1196
+
1197
+ /**
1198
+ * Sets the bio text of a user
1199
+ * @method
1200
+ * @since 2.5.6
1201
+ * @param {String} userID - alphanumeric ID of user
1202
+ * @param {String} bio - text to set as bio
1203
+ */
1204
+ setUserBio = async (userID, bio) => {
1205
+ if (!this.userToken) {
1206
+ throw new SidechatAPIError("User is not authenticated.");
1207
+ }
1208
+ try {
1209
+ const res = await fetch(`${this.apiRoot}/v1/users/${userID}`, {
1210
+ method: "PATCH",
1211
+ headers: {
1212
+ ...this.defaultHeaders,
1213
+ "App-Version": "5.4.22",
1214
+ Authorization: `Bearer ${this.userToken}`,
1215
+ },
1216
+ body: JSON.stringify({
1217
+ bio: bio
1218
+ }),
1219
+ });
1220
+ const json = await res.json();
1221
+ return await json;
1222
+ } catch (err) {
1223
+ console.error(err);
1224
+ throw new SidechatAPIError(`Failed to set bio.`);
1225
+ }
1226
+ };
1227
+
1228
+ /**
1229
+ * Checks if user can set their username to a string
1230
+ * @method
1231
+ * @since 2.3.6
1232
+ * @param {String} username - string to check
1233
+ * @returns {Promise<Boolean>} whether or not username is valid and unused
1234
+ */
1235
+ checkUsername = async (username) => {
1236
+ if (!this.userToken) {
1237
+ throw new SidechatAPIError("User is not authenticated.");
1238
+ }
1239
+ try {
1240
+ const res = await fetch(
1241
+ `${this.apiRoot}/v1/users/username?username=${username}`,
1242
+ {
1243
+ method: "GET",
1244
+ headers: {
1245
+ ...this.defaultHeaders,
1246
+ Authorization: `Bearer ${this.userToken}`,
1247
+ },
1248
+ }
1249
+ );
1250
+ if (res?.status == 200 || res?.status == 204) {
1251
+ return true;
1252
+ } else {
1253
+ return false;
1254
+ }
1255
+ } catch (err) {
1256
+ console.error(err);
1257
+ throw new SidechatAPIError(`Failed to check username.`);
1258
+ }
1259
+ };
1260
+
1261
+ /**
1262
+ * Changes the username of the current user
1263
+ * @method
1264
+ * @since 2.3.6
1265
+ * @param {String} userID - alphanumeric ID of user
1266
+ * @param {String} username - new username to set
1267
+ */
1268
+ setUsername = async (userID, username) => {
1269
+ if (!this.userToken) {
1270
+ throw new SidechatAPIError("User is not authenticated.");
1271
+ }
1272
+ try {
1273
+ const res = await fetch(`${this.apiRoot}/v1/users/${userID}`, {
1274
+ method: "PATCH",
1275
+ headers: {
1276
+ ...this.defaultHeaders,
1277
+ Authorization: `Bearer ${this.userToken}`,
1278
+ },
1279
+ body: JSON.stringify({
1280
+ username: username,
1281
+ }),
1282
+ });
1283
+ const json = await res.json();
1284
+ return await json.user;
1285
+ } catch (err) {
1286
+ console.error(err);
1287
+ throw new SidechatAPIError(`Failed to set icon.`);
1288
+ }
1289
+ };
1290
+
1291
+ /**
1292
+ * Fetches a public user profile
1293
+ * @method
1294
+ * @since 2.6.0
1295
+ * @param {String} username - username of the user to fetch
1296
+ * @returns {Promise<types.SidechatProfile>}
1297
+ */
1298
+ getUserProfile = async (username) => {
1299
+ if (!this.userToken) {
1300
+ throw new SidechatAPIError("User is not authenticated.");
1301
+ }
1302
+ try {
1303
+ const res = await fetch(`${this.apiRoot}/v1/groups/username?username=${username}`, {
1304
+ method: "GET",
1305
+ headers: {
1306
+ ...this.defaultHeaders,
1307
+ Authorization: `Bearer ${this.userToken}`,
1308
+ }
1309
+ });
1310
+ const json = await res.json();
1311
+ return await json.group;
1312
+ } catch (err) {
1313
+ console.error(err);
1314
+ throw new SidechatAPIError(`Failed to set icon.`);
1315
+ }
1316
+ };
1317
+
1318
+ /**
1319
+ * Fetches a public user's posts
1320
+ * @method
1321
+ * @since 2.6.0
1322
+ * @param {String} username - username of the user to fetch
1323
+ * @returns {Promise<types.SidechatPostOrComment[]>}
1324
+ */
1325
+ getUserPosts = async (username) => {
1326
+ if (!this.userToken) {
1327
+ throw new SidechatAPIError("User is not authenticated.");
1328
+ }
1329
+ try {
1330
+ const res = await fetch(`${this.apiRoot}/v1/users/posts?username=${username}`, {
1331
+ method: "GET",
1332
+ headers: {
1333
+ ...this.defaultHeaders,
1334
+ Authorization: `Bearer ${this.userToken}`,
1335
+ }
1336
+ });
1337
+ const json = await res.json();
1338
+ return await json.posts;
1339
+ } catch (err) {
1340
+ console.error(err);
1341
+ throw new SidechatAPIError(`Failed to set icon.`);
1342
+ }
1343
+ };
1344
+
1345
+ /**
1346
+ * Marks an activity item as read
1347
+ * @method
1348
+ * @since 2.3.2
1349
+ * @param {String} activityID - alphanumeric ID of activity object
1350
+ */
1351
+ readActivity = async (activityID) => {
1352
+ if (!this.userToken) {
1353
+ throw new SidechatAPIError("User is not authenticated.");
1354
+ }
1355
+ try {
1356
+ const res = await fetch(`${this.apiRoot}/v1/activity/seen`, {
1357
+ method: "POST",
1358
+ headers: {
1359
+ ...this.defaultHeaders,
1360
+ Authorization: `Bearer ${this.userToken}`,
1361
+ },
1362
+ body: JSON.stringify({
1363
+ ids: [activityID],
1364
+ }),
1365
+ });
1366
+ const json = await res.json();
1367
+ return await json;
1368
+ } catch (err) {
1369
+ console.error(err);
1370
+ throw new SidechatAPIError(`Failed to mark activity as read.`);
1371
+ }
1372
+ };
1373
+
1374
+ /**
1375
+ * Retrieves joinable group chats
1376
+ * @method
1377
+ * @since 2.3.5
1378
+ */
1379
+ getGroupChats = async () => {
1380
+ if (!this.userToken) {
1381
+ throw new SidechatAPIError("User is not authenticated.");
1382
+ }
1383
+ try {
1384
+ const res = await fetch(`${this.apiRoot}/v1/chats/explore`, {
1385
+ method: "GET",
1386
+ headers: {
1387
+ ...this.defaultHeaders,
1388
+ Authorization: `Bearer ${this.userToken}`,
1389
+ },
1390
+ });
1391
+ const json = await res.json();
1392
+ return await json.chats;
1393
+ } catch (err) {
1394
+ console.error(err);
1395
+ throw new SidechatAPIError(`Failed to get groupchats.`);
1396
+ }
1397
+ };
1398
+
1399
+ /**
1400
+ * Joins a group chat. To mimic the official client, use the user's display name and icon by default.
1401
+ * @method
1402
+ * @param {String} groupChatID - alphanumeric ID of group chat to join
1403
+ * @param {String} displayName - display name to use in chat
1404
+ * @param {String} emoji - emoji to use as icon
1405
+ * @param {String} primaryColor - hex string of primary color
1406
+ * @param {String} secondaryColor - hex string of secondary color
1407
+ * @since 2.3.5
1408
+ */
1409
+ joinGroupChat = async (
1410
+ groupChatID,
1411
+ displayName,
1412
+ emoji,
1413
+ primaryColor,
1414
+ secondaryColor
1415
+ ) => {
1416
+ if (!this.userToken) {
1417
+ throw new SidechatAPIError("User is not authenticated.");
1418
+ }
1419
+ try {
1420
+ const res = await fetch(`${this.apiRoot}/v1/chats/groups/join`, {
1421
+ method: "POST",
1422
+ headers: {
1423
+ ...this.defaultHeaders,
1424
+ Authorization: `Bearer ${this.userToken}`,
1425
+ },
1426
+ body: JSON.stringify({
1427
+ chat_id: groupChatID,
1428
+ identity: {
1429
+ display_name: displayName,
1430
+ emoji: emoji,
1431
+ secondary_color: secondaryColor,
1432
+ color: primaryColor,
1433
+ },
1434
+ }),
1435
+ });
1436
+ const json = await res.json();
1437
+ return await json;
1438
+ } catch (err) {
1439
+ console.error(err);
1440
+ throw new SidechatAPIError(`Failed to join groupchat.`);
1441
+ }
1442
+ };
1443
+
1444
+ /**
1445
+ * Gets a list of the user's direct messages
1446
+ * @method
1447
+ * @returns {Promise<types.SidechatDirectThread[]>}
1448
+ * @since 2.4.4
1449
+ */
1450
+ getDMs = async () => {
1451
+ if (!this.userToken) {
1452
+ throw new SidechatAPIError("User is not authenticated.");
1453
+ }
1454
+ try {
1455
+ const res = await fetch(`${this.apiRoot}/v1/chats`, {
1456
+ method: "GET",
1457
+ headers: {
1458
+ ...this.defaultHeaders,
1459
+ Authorization: `Bearer ${this.userToken}`,
1460
+ },
1461
+ });
1462
+ const json = await res.json();
1463
+ const list = await json.chats;
1464
+ let r = [];
1465
+ list.forEach((o) => {
1466
+ r.push(o.chat);
1467
+ });
1468
+ return await r;
1469
+ } catch (err) {
1470
+ console.error(err);
1471
+ throw new SidechatAPIError(`Failed to fetch DMs.`);
1472
+ }
1473
+ };
1474
+
1475
+ /**
1476
+ * Gets a single direct message thread
1477
+ * @method
1478
+ * @param {String} id - alphanumeric ID of the chat to fetch
1479
+ * @returns {Promise<types.SidechatDirectThread>}
1480
+ * @since 2.4.4
1481
+ */
1482
+ getDMThread = async (id) => {
1483
+ if (!this.userToken) {
1484
+ throw new SidechatAPIError("User is not authenticated.");
1485
+ }
1486
+ try {
1487
+ const res = await fetch(
1488
+ `${this.apiRoot}/v1/chats/messages?chat_id=${id}`,
1489
+ {
1490
+ method: "GET",
1491
+ headers: {
1492
+ ...this.defaultHeaders,
1493
+ Authorization: `Bearer ${this.userToken}`,
1494
+ },
1495
+ }
1496
+ );
1497
+ const json = await res.json();
1498
+ return await json.chat;
1499
+ } catch (err) {
1500
+ console.error(err);
1501
+ throw new SidechatAPIError(`Failed to fetch DM thread.`);
1502
+ }
1503
+ };
1504
+
1505
+ /**
1506
+ * Sends a message to an existing direct message thread - note that you must first use startDM() to start a thread.
1507
+ * @method
1508
+ * @param {String} chatID - alphanumeric ID of the chat to send to
1509
+ * @param {String} text - text content of message
1510
+ * @param {String} clientID - alphanumeric device ID
1511
+ * @param {types.SidechatAsset[]} assets - array of assets to send
1512
+ * @param {Boolean} anonymous - whether the DM should be sent anonymously
1513
+ * @since 2.4.4
1514
+ */
1515
+ sendDM = async (chatID, text, clientID, assets = [], anonymous = false) => {
1516
+ if (!this.userToken) {
1517
+ throw new SidechatAPIError("User is not authenticated.");
1518
+ }
1519
+ try {
1520
+ const res = await fetch(`${this.apiRoot}/v1/chats/send`, {
1521
+ method: "POST",
1522
+ headers: {
1523
+ ...this.defaultHeaders,
1524
+ Authorization: `Bearer ${this.userToken}`,
1525
+ },
1526
+ body: JSON.stringify({
1527
+ chat_id: chatID,
1528
+ text: text,
1529
+ client_id: clientID,
1530
+ anonymous: anonymous,
1531
+ assets: assets,
1532
+ }),
1533
+ });
1534
+ const json = await res.json();
1535
+ return await json;
1536
+ } catch (err) {
1537
+ console.error(err);
1538
+ throw new SidechatAPIError(`Failed to send message.`);
1539
+ }
1540
+ };
1541
+
1542
+ /**
1543
+ * Creates a new direct message thread
1544
+ * @method
1545
+ * @param {String} text - text content of message
1546
+ * @param {String} clientID - alphanumeric ID of devide
1547
+ * @param {String} postID - alphanumeric ID of post or comment
1548
+ * @param {Boolean} anonymous - whether the DM should be sent anonymously
1549
+ * @param {"feed"} postContext - context of post (mostly undocumented, defaults to "feed")
1550
+ * @since 2.4.4
1551
+ */
1552
+ startDM = async (
1553
+ text,
1554
+ clientID,
1555
+ postID,
1556
+ anonymous = false,
1557
+ postContext = "feed"
1558
+ ) => {
1559
+ if (!this.userToken) {
1560
+ throw new SidechatAPIError("User is not authenticated.");
1561
+ }
1562
+ try {
1563
+ const res = await fetch(`${this.apiRoot}/v1/chats/start`, {
1564
+ method: "POST",
1565
+ headers: {
1566
+ ...this.defaultHeaders,
1567
+ Authorization: `Bearer ${this.userToken}`,
1568
+ },
1569
+ body: JSON.stringify({
1570
+ text: text,
1571
+ client_id: clientID,
1572
+ post_id: postID,
1573
+ anonymous: anonymous,
1574
+ post_context: postContext,
1575
+ }),
1576
+ });
1577
+ const json = await res.json();
1578
+ return await json;
1579
+ } catch (err) {
1580
+ console.error(err);
1581
+ throw new SidechatAPIError(`Failed to start DM.`);
1582
+ }
1583
+ };
1584
+
1585
+ /**
1586
+ * Hides posts from user
1587
+ * @method
1588
+ * @param {String} postID - alphanumeric ID of post to hide
1589
+ * @since 2.6.2
1590
+ */
1591
+ hidePostsFromUser = async (postID) => {
1592
+ if (!this.userToken) {
1593
+ throw new SidechatAPIError("User is not authenticated.");
1594
+ }
1595
+ try {
1596
+ const res = await fetch(`${this.apiRoot}/v1/posts/hide_posts_from_user`, {
1597
+ method: "POST",
1598
+ headers: {
1599
+ ...this.defaultHeaders,
1600
+ Authorization: `Bearer ${this.userToken}`,
1601
+ },
1602
+ body: JSON.stringify({
1603
+ post_id: postID,
1604
+ post_context: "feed",
1605
+ report: false
1606
+ }),
1607
+ });
1608
+ const json = await res.json();
1609
+ return await json;
1610
+ } catch (err) {
1611
+ console.error(err);
1612
+ throw new SidechatAPIError(`Failed to hide post.`);
1613
+ }
1614
+ };
1615
+
1616
+ /**
1617
+ * Unhides all posts from all users
1618
+ * @method
1619
+ * @since 2.6.2
1620
+ */
1621
+ unhidePostsFromAllUsers = async () => {
1622
+ if (!this.userToken) {
1623
+ throw new SidechatAPIError("User is not authenticated.");
1624
+ }
1625
+ try {
1626
+ const res = await fetch(`${this.apiRoot}/v1/users/unhide_all`, {
1627
+ method: "POST",
1628
+ headers: {
1629
+ ...this.defaultHeaders,
1630
+ Authorization: `Bearer ${this.userToken}`,
1631
+ },
1632
+ body: JSON.stringify({}),
1633
+ });
1634
+ const json = await res.json();
1635
+ return await json;
1636
+ } catch (err) {
1637
+ console.error(err);
1638
+ throw new SidechatAPIError(`Failed to unhide post.`);
1639
+ }
1640
+ };
1628
1641
  }
1629
1642
 
1630
1643
  /**