@nomad-media/public 1.1.13 → 1.1.14

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.
package/README.md CHANGED
@@ -1,28 +1,37 @@
1
- # Nomad Media Public
2
- This package contains the public version of the Nomad Media SDK. It includes all of the media methods of the SDK.
1
+ ## Prerequisites
3
2
 
4
- ## Minimum Requirements
5
- - Node.js 12.0.0
3
+ - Node package manager (npm).
6
4
 
7
- ## Installation
8
- To use the Nomad SDK, download the npm nomad-media-npm.
5
+ > 📘 Note
6
+ >
7
+ > You can download npm [here](https://nodejs.org/en/download).
9
8
 
9
+ ## Setup
10
+
11
+ To use the Nomad SDK, download the @nomad-media npm. There are two versions, the full version which includes all of the Nomad-Media endpoints, and the public version which only includes the media endpoints.
12
+
13
+ To install the full version, use the following command:
14
+ ```shell
15
+ npm install @nomad-media/full
16
+ ```
17
+
18
+ To install the public version, use the following command:
10
19
  ```shell
11
20
  npm install @nomad-media/public
12
21
  ```
13
22
 
14
- Then to import it, you can either use the default version, or the debug version. The difference is that the debug version isn't compressed and has more documentation and named parameters.
23
+ Then to import it, you can either use the default version, or the debug version. The difference is that the debug version isn't compressed and has more documentation and named parameters. Both full and public have a debug version. Currently the debug version's tooltips don't show up. This is an issue with npm.
15
24
 
16
25
  To use the default version use:
17
26
 
18
27
  ```javascript
19
- import NomadMediaSDK from "@nomad-media/public";
28
+ import NomadMediaSDK from "@nomad-media/full";
20
29
  ```
21
30
 
22
31
  To use the debug version user:
23
32
 
24
33
  ```javascript
25
- import NomadMediaSDK from "@nomad-media/public/debug";
34
+ import NomadMediaSDK from "@nomad-media/full/debug";
26
35
  ```
27
36
 
28
37
  To initialize the sdk, call the NomadMediaSDK class as shown below:
@@ -41,22 +50,39 @@ const config = {
41
50
  "password": "password",
42
51
  "serviceApiUrl": "serverApiUrl",
43
52
  "apiType": "admin",
44
- "debugMode": true
53
+ "debugMode": true,
54
+ "singleton": false
45
55
  };
46
56
  ```
47
- serviceApiUrl: Specifies the url of the server you are trying to connect to.
48
57
 
49
58
  apiType: Specifies whether the function you are trying to run is **admin** or **portal**.
50
59
 
51
60
  debugMode: Specifies when running functions, whether of not to print api call information.
52
61
 
62
+ singleton: Whether or not to only create one class instance.
63
+
64
+ Place the config in a file called config.js and import it into your project.
65
+
53
66
  You are now ready to use the SDK in your project.
54
67
 
55
68
  > 📘 Contact: Make sure to contact Nomad Media support to get username, password, and url for your enviromnent.
56
69
 
57
70
  > 🚧 Make sure to keep your configuration options secret and do not share them publicly.
58
71
 
59
- ## Nomad SDK Documentation
72
+ ## Upgrading NPM
73
+
74
+ To upgrade the npm, use the following command:
75
+
76
+ ```shell
77
+ npm update @nomad-media/full
78
+ ```
79
+
80
+ ## Nomad SDK References
81
+
82
+ An overview of all of the Nomad SDK methods. Includes prameter details for the methods. Scroll down to the Nomad SDK section.
83
+
84
+ [Nomad SDK References](https://developer.nomad-cms.com/reference)
85
+
86
+ ## Nomad SDK NPM Samples
60
87
 
61
- - [Nomad SDK Modules](https://developer.nomad-cms.com/docs/nomad-api-modules)
62
- - [Nomad SDK NPM Samples](https://github.com/Nomad-Media/samples-js)
88
+ [Nomad SDK NPM Samples](https://github.com/Nomad-Media/samples-js)
@@ -131,6 +131,10 @@
131
131
 
132
132
 
133
133
 
134
+
135
+
136
+
137
+
134
138
 
135
139
 
136
140
 
@@ -249,6 +253,14 @@
249
253
 
250
254
 
251
255
 
256
+
257
+
258
+
259
+
260
+
261
+
262
+
263
+
252
264
 
253
265
 
254
266
 
@@ -263,8 +275,6 @@
263
275
 
264
276
 
265
277
 
266
- import { promises as fs } from 'fs';
267
- import path from 'path';
268
278
 
269
279
  /**
270
280
  * @class NomadSDK
@@ -284,14 +294,14 @@ class NomadMediaSDK {
284
294
  this.expirationSeconds = null;
285
295
  this.userSessionId = null;
286
296
  this.id = null
287
- this.debugMode = config.debugMode || false;
297
+ this.debug = config.debugMode || false;
288
298
 
289
299
  if (this.config.serviceApiUrl[this.config.serviceApiUrl.length - 1] === "/")
290
300
  {
291
301
  this.config.serviceApiUrl = this.config.serviceApiUrl.slice(0, -1);
292
302
  }
293
303
 
294
- NomadMediaSDK.instance = this;
304
+ if (this.config.singleton) NomadMediaSDK.instance = this;
295
305
 
296
306
  return this;
297
307
  }
@@ -316,7 +326,7 @@ class NomadMediaSDK {
316
326
  * @async
317
327
  * @description Logs in using the username and password from the config.
318
328
  * @returns {Promise<void>} - A promise that resolves when the login is successful.
319
- * Updates the token, refresh token, expiration seconds, and user session ID class varibles.
329
+ * Updates the token, refresh token, expiration seconds, and user session ID class variables.
320
330
  * @throws {Error} - An error is thrown if the login fails.
321
331
  */
322
332
  async login()
@@ -326,8 +336,9 @@ class NomadMediaSDK {
326
336
 
327
337
  try
328
338
  {
329
- const LOGIN_INFO = await _login(this, this.config.username, this.config.password,
330
- this.config.serviceApiUrl, this.debugMode);
339
+ const LOGIN_INFO = await _login(this);
340
+ if (!LOGIN_INFO) throw new Error("Login failed");
341
+
331
342
  this.token = LOGIN_INFO["token"];
332
343
  this.refreshTokenVal = LOGIN_INFO["refreshToken"];
333
344
  this.expirationSeconds = LOGIN_INFO["expirationSeconds"];
@@ -360,7 +371,7 @@ class NomadMediaSDK {
360
371
 
361
372
  try
362
373
  {
363
- await _logout(this, this.token, this.config.serviceApiUrl, this.debugMode);
374
+ await _logout(this);
364
375
  this.token = null;
365
376
  this.refreshTokenVal = null;
366
377
  this.expirationSeconds = null;
@@ -371,7 +382,7 @@ class NomadMediaSDK {
371
382
  }
372
383
  catch (error)
373
384
  {
374
- _printDatetime("Loggout failed");
385
+ _printDatetime("Logout failed");
375
386
  throw error;
376
387
  }
377
388
  }
@@ -388,10 +399,14 @@ class NomadMediaSDK {
388
399
  {
389
400
  _printDatetime(`Refreshing token`);
390
401
 
402
+ if (this.token === null && this.config.username)
403
+ {
404
+ await this._init();
405
+ }
406
+
391
407
  try
392
408
  {
393
- const REFRESHED = await _refreshToken(this, this.token, this.config.serviceApiUrl,
394
- this.refreshTokenVal, this.debugMode);
409
+ const REFRESHED = await _refreshToken(this);
395
410
  if (REFRESHED) _printDatetime(`Token refresh successful`);
396
411
  }
397
412
  catch (error)
@@ -418,7 +433,7 @@ class NomadMediaSDK {
418
433
 
419
434
  try
420
435
  {
421
- await _forgotPassword(this, this.config.serviceApiUrl, USERNAME, this.debugMode);
436
+ await _forgotPassword(this);
422
437
  _printDatetime(`Code sent to ${USERNAME}`);
423
438
  }
424
439
  catch (error)
@@ -447,8 +462,7 @@ class NomadMediaSDK {
447
462
 
448
463
  try
449
464
  {
450
- await _resetPassword(this, this.config.serviceApiUrl, USERNAME, CODE, NEW_PASSWORD,
451
- this.debugMode);
465
+ await _resetPassword(this, CODE, NEW_PASSWORD);
452
466
  _printDatetime(`Password reset for ${USERNAME}`);
453
467
  }
454
468
  catch (error)
@@ -487,8 +501,7 @@ class NomadMediaSDK {
487
501
 
488
502
  try
489
503
  {
490
- await _clearContinueWatching(this, this.token, this.config.serviceApiUrl, USER_ID, ASSET_ID,
491
- this.debugMode);
504
+ await _clearContinueWatching(this, USER_ID, ASSET_ID);
492
505
  _printDatetime(`Continue watching cleared`);
493
506
  }
494
507
  catch (error)
@@ -526,7 +539,7 @@ class NomadMediaSDK {
526
539
  {
527
540
  USER_ID = USER_ID || this.id;
528
541
 
529
- await _clearWatchlist(this, this.token, this.config.serviceApiUrl, USER_ID, this.debugMode);
542
+ await _clearWatchlist(this, USER_ID);
530
543
  _printDatetime(`Watchlist cleared`);
531
544
  }
532
545
  catch (error)
@@ -565,8 +578,7 @@ class NomadMediaSDK {
565
578
 
566
579
  try
567
580
  {
568
- const GET_FORMS_INFO = await _createForm(this, this.token, this.config.serviceApiUrl,
569
- CONTENT_DEFINITION_ID, FORM_INFO, this.debugMode);
581
+ const GET_FORMS_INFO = await _createForm(this, CONTENT_DEFINITION_ID, FORM_INFO);
570
582
  if (GET_FORMS_INFO) _printDatetime(`Form created`);
571
583
  return GET_FORMS_INFO;
572
584
  }
@@ -605,8 +617,7 @@ class NomadMediaSDK {
605
617
 
606
618
  try
607
619
  {
608
- const GET_CONTENT_COOKIES_INFO = await _getContentCookies(this, this.token,
609
- this.config.serviceApiUrl, CONTENT_ID, this.debugMode);
620
+ const GET_CONTENT_COOKIES_INFO = await _getContentCookies(this, CONTENT_ID);
610
621
  if (GET_CONTENT_COOKIES_INFO) _printDatetime(`Content cookies gotten`);
611
622
  return GET_CONTENT_COOKIES_INFO;
612
623
  }
@@ -642,8 +653,7 @@ class NomadMediaSDK {
642
653
 
643
654
  try
644
655
  {
645
- const GET_DYNAMIC_CONTENTS_INFO = await _getDefaultSiteConfig(this, this.token,
646
- this.config.serviceApiUrl, this.debugMode);
656
+ const GET_DYNAMIC_CONTENTS_INFO = await _getDefaultSiteConfig(this);
647
657
  if (GET_DYNAMIC_CONTENTS_INFO) _printDatetime(`Default site config gotten`);
648
658
  return GET_DYNAMIC_CONTENTS_INFO;
649
659
  }
@@ -675,8 +685,7 @@ class NomadMediaSDK {
675
685
 
676
686
  try
677
687
  {
678
- const GET_DYNAMIC_CONTENT_INFO = await _getDynamicContent(this, this.token,
679
- this.config.serviceApiUrl, DYNAMIC_CONTENT_RECORD_ID, this.debugMode);
688
+ const GET_DYNAMIC_CONTENT_INFO = await _getDynamicContent(this, DYNAMIC_CONTENT_RECORD_ID);
680
689
  if (GET_DYNAMIC_CONTENT_INFO) _printDatetime(`Dynamic content gotten: ${DYNAMIC_CONTENT_RECORD_ID}`);
681
690
  return GET_DYNAMIC_CONTENT_INFO;
682
691
  }
@@ -712,8 +721,7 @@ class NomadMediaSDK {
712
721
 
713
722
  try
714
723
  {
715
- const GET_DYNAMIC_CONTENTS_INFO = await _getDynamicContents(this, this.token,
716
- this.config.serviceApiUrl, this.debugMode);
724
+ const GET_DYNAMIC_CONTENTS_INFO = await _getDynamicContents(this);
717
725
  if (GET_DYNAMIC_CONTENTS_INFO) _printDatetime(`Dynamic contents gotten`);
718
726
  return GET_DYNAMIC_CONTENTS_INFO;
719
727
  }
@@ -729,12 +737,13 @@ class NomadMediaSDK {
729
737
  * @async
730
738
  * @description Gets media group.
731
739
  * @param {string} MEDIA_GROUP_ID - The ID of the media group.
740
+ * @param { Array<string> } FILTER_IDS - The IDs of the media group items to filter by.
732
741
  * @returns {Promise<JSON>} - A promise that resolves when the media group is gotten.
733
742
  * Returns the information of the gotten media group.
734
743
  * @throws {Error} - An error is thrown if the media group fails to get.
735
744
  * @throws {Error} - An error is thrown if the API type is not portal.
736
745
  */
737
- async getMediaGroup(MEDIA_GROUP_ID)
746
+ async getMediaGroup(MEDIA_GROUP_ID, FILTER_IDS)
738
747
  {
739
748
  if (this.token === null && this.config.username)
740
749
  {
@@ -750,8 +759,7 @@ class NomadMediaSDK {
750
759
 
751
760
  try
752
761
  {
753
- const GET_MEDIA_GROUP_INFO = await _getMediaGroup(this, this.token, this.config.serviceApiUrl,
754
- MEDIA_GROUP_ID, this.debugMode);
762
+ const GET_MEDIA_GROUP_INFO = await _getMediaGroup(this, MEDIA_GROUP_ID, FILTER_IDS);
755
763
  if (GET_MEDIA_GROUP_INFO) _printDatetime(`Media group gotten: ${MEDIA_GROUP_ID}`);
756
764
  return GET_MEDIA_GROUP_INFO;
757
765
  }
@@ -788,8 +796,7 @@ class NomadMediaSDK {
788
796
 
789
797
  try
790
798
  {
791
- const GET_MEDIA_ITEM_INFO = await _getMediaItem(this, this.token, this.config.serviceApiUrl,
792
- MEDIA_ITEM_ID, this.debugMode);
799
+ const GET_MEDIA_ITEM_INFO = await _getMediaItem(this, MEDIA_ITEM_ID);
793
800
  if (GET_MEDIA_ITEM_INFO) _printDatetime(`Media item gotten: ${MEDIA_ITEM_ID}`);
794
801
  return GET_MEDIA_ITEM_INFO;
795
802
  }
@@ -827,8 +834,7 @@ class NomadMediaSDK {
827
834
 
828
835
  try
829
836
  {
830
- const GET_MY_CONTENT_INFO = await _getMyContent(this, this.token, this.config.serviceApiUrl,
831
- this.debugMode);
837
+ const GET_MY_CONTENT_INFO = await _getMyContent(this);
832
838
  if (GET_MY_CONTENT_INFO) _printDatetime(`My content gotten`);
833
839
  return GET_MY_CONTENT_INFO;
834
840
  }
@@ -860,8 +866,7 @@ class NomadMediaSDK {
860
866
 
861
867
  try
862
868
  {
863
- const GET_MY_GROUP_INFO = await _getMyGroup(this, this.token, this.config.serviceApiUrl,
864
- GROUP_ID, this.debugMode);
869
+ const GET_MY_GROUP_INFO = await _getMyGroup(this, GROUP_ID);
865
870
  if (GET_MY_GROUP_INFO) _printDatetime(`My group gotten: ${GROUP_ID}`);
866
871
  return GET_MY_GROUP_INFO;
867
872
  }
@@ -893,8 +898,7 @@ class NomadMediaSDK {
893
898
 
894
899
  try
895
900
  {
896
- const GET_DYNAMIC_CONTENT_INFO = await _getSiteConfig(this, this.token,
897
- this.config.serviceApiUrl, SITE_CONFIG_RECORD_ID, this.debugMode);
901
+ const GET_DYNAMIC_CONTENT_INFO = await _getSiteConfig(this, SITE_CONFIG_RECORD_ID);
898
902
  if (GET_DYNAMIC_CONTENT_INFO) _printDatetime(`Site config gotten: ${SITE_CONFIG_RECORD_ID}`);
899
903
  return GET_DYNAMIC_CONTENT_INFO;
900
904
  }
@@ -936,8 +940,7 @@ class NomadMediaSDK {
936
940
 
937
941
  try
938
942
  {
939
- const MEDIA_SEARCH_INFO = await _mediaSearch(this, this.token, this.config.serviceApiUrl,
940
- QUERY, IDS, SORT_FIELDS, OFFSET, SIZE, this.debugMode);
943
+ const MEDIA_SEARCH_INFO = await _mediaSearch(this, QUERY, IDS, SORT_FIELDS, OFFSET, SIZE);
941
944
  if (MEDIA_SEARCH_INFO) _printDatetime(`Media search complete`);
942
945
  return MEDIA_SEARCH_INFO;
943
946
  }
@@ -950,7 +953,7 @@ class NomadMediaSDK {
950
953
 
951
954
  // misc functions
952
955
  /**
953
- * @function miscFunctons
956
+ * @function miscFunctions
954
957
  * @async
955
958
  * @description Calls any nomad function given URL method and body.
956
959
  * @param {string} URL_PATH - The URL path of the function.
@@ -988,11 +991,7 @@ class NomadMediaSDK {
988
991
  HEADERS.append("Authorization", `Bearer ${this.token}`);
989
992
  }
990
993
 
991
- if (this.debugMode)
992
- {
993
- console.log(`URL: ${API_URL}\nMETHOD: ${METHOD}`);
994
- if (BODY) console.log(`BODY: ${JSON.stringify(BODY, null, 4 )}`);
995
- }
994
+ if (this.debug) console.log(`URL: ${API_URL}\nMETHOD: ${METHOD}` + (BODY ? `\nBODY: ${JSON.stringify(BODY, null, 4)}` : ""));
996
995
 
997
996
  const REQUEST = {
998
997
  method: METHOD,
@@ -1037,32 +1036,32 @@ export default NomadMediaSDK;
1037
1036
 
1038
1037
 
1039
1038
 
1040
- async function _forgotPassword(instance, URL, USERNAME, DEBUG_MODE)
1039
+ async function _forgotPassword(instance)
1041
1040
  {
1042
- const API_URL = `${URL}/api/account/forgot-password`;
1041
+ const API_URL = `${instance.config.serviceApiUrl}/api/account/forgot-password`;
1043
1042
 
1044
1043
  const BODY = {
1045
- username: USERNAME
1044
+ username: instance.config.username
1046
1045
  };
1047
1046
 
1048
- return await _sendRequest(instance, null, "Forgot Password", API_URL, "POST", null, BODY, DEBUG_MODE);
1047
+ return await _sendRequest(instance, "Forgot Password", API_URL, "POST", undefined, BODY);
1049
1048
  }
1050
1049
 
1051
1050
 
1052
1051
 
1053
1052
 
1054
- async function _login(instance, USERNAME, PASSWORD, URL, DEBUG_MODE)
1053
+ async function _login(instance)
1055
1054
  {
1056
- const API_URL = `${URL}/api/account/login`;
1055
+ const API_URL = `${instance.config.serviceApiUrl}/api/account/login`;
1057
1056
 
1058
1057
  const BODY = {
1059
- "userName": USERNAME,
1060
- "password": PASSWORD
1058
+ "userName": instance.config.username,
1059
+ "password": instance.config.password
1061
1060
  };
1062
1061
 
1063
1062
  try
1064
1063
  {
1065
- return await _sendRequest(instance, null, "Login", API_URL, "POST", null, BODY, DEBUG_MODE);
1064
+ return await _sendRequest(instance, "Login", API_URL, "POST", undefined, BODY);
1066
1065
  }
1067
1066
  catch (error)
1068
1067
  {
@@ -1081,11 +1080,11 @@ async function _login(instance, USERNAME, PASSWORD, URL, DEBUG_MODE)
1081
1080
 
1082
1081
 
1083
1082
 
1084
- async function _logout(instance, AUTH_TOKEN, URL, DEBUG_MODE)
1083
+ async function _logout(instance)
1085
1084
  {
1086
- const API_URL = `${URL}/api/account/logout`;
1085
+ const API_URL = `${instance.config.serviceApiUrl}/api/account/logout`;
1087
1086
 
1088
- return await _sendRequest(instance, AUTH_TOKEN, "Logout", API_URL, "POST", null, null, DEBUG_MODE);
1087
+ return await _sendRequest(instance, "Logout", API_URL, "POST", undefined, undefined);
1089
1088
  }
1090
1089
 
1091
1090
 
@@ -1094,15 +1093,15 @@ async function _logout(instance, AUTH_TOKEN, URL, DEBUG_MODE)
1094
1093
 
1095
1094
 
1096
1095
 
1097
- async function _refreshToken(instance, AUTH_TOKEN, URL, REFRESH_TOKEN, DEBUG_MODE)
1096
+ async function _refreshToken(instance)
1098
1097
  {
1099
- const API_URL = `${URL}/api/account/refresh-token`;
1098
+ const API_URL = `${instance.config.serviceApiUrl}/api/account/refresh-token`;
1100
1099
 
1101
1100
  const BODY = {
1102
- refreshToken: REFRESH_TOKEN
1101
+ refreshToken: instance.refreshTokenVal
1103
1102
  };
1104
1103
 
1105
- const TOKEN_INFO = await _sendRequest(instance, AUTH_TOKEN, "Refreshing Token", API_URL, "POST", null, BODY, DEBUG_MODE);
1104
+ const TOKEN_INFO = await _sendRequest(instance, "Refreshing Token", API_URL, "POST", undefined, BODY);
1106
1105
  instance.token = TOKEN_INFO.token;
1107
1106
 
1108
1107
  return true;
@@ -1112,74 +1111,76 @@ async function _refreshToken(instance, AUTH_TOKEN, URL, REFRESH_TOKEN, DEBUG_MOD
1112
1111
 
1113
1112
 
1114
1113
 
1115
- async function _resetPassword(instance, URL, USERNAME, TOKEN, NEW_PASSWORD, DEBUG_MODE)
1114
+ async function _resetPassword(instance, CODE, NEW_PASSWORD)
1116
1115
  {
1117
- const API_URL = `${URL}/api/account/reset-password`;
1116
+ const API_URL = `${instance.config.serviceApiUrl}/api/account/reset-password`;
1118
1117
 
1119
1118
  const BODY = {
1120
- userName: USERNAME,
1121
- TOKEN: TOKEN,
1119
+ userName: instance.username,
1120
+ token: CODE,
1122
1121
  newPassword: NEW_PASSWORD
1123
1122
  };
1124
1123
 
1125
- return await _sendRequest(instance, null, "Reset Password", API_URL, "POST", null, BODY, DEBUG_MODE);
1124
+ return await _sendRequest(instance, "Reset Password", API_URL, "POST", undefined, BODY);
1125
+ }
1126
+
1127
+
1128
+ function _apiExceptionHandler(error, message)
1129
+ {
1130
+ // Check if we have a response object and error message
1131
+ if (!error)
1132
+ {
1133
+ console.error(message);
1134
+ }
1135
+
1136
+ // Check if error is a string
1137
+ if (typeof error === "string")
1138
+ {
1139
+ console.error(`${message}: ${error}`);
1140
+ }
1141
+ else if (error.errors)
1142
+ {
1143
+ if (Array.isArray(error.errors))
1144
+ {
1145
+ let errorString = "";
1146
+ for (let errorIdx = 0; errorIdx < error.errors.length; errorIdx++)
1147
+ {
1148
+ errorString += `${error.errors[errorIdx].code}: ${error.errors[errorIdx].field}: ${error.errors[errorIdx].message}\n`;
1149
+ }
1150
+ console.error(`${message}: ${errorString}`);
1151
+ }
1152
+ else if (typeof error.errors === "object")
1153
+ {
1154
+ let errorString = "";
1155
+ for (let key in error.errors)
1156
+ {
1157
+ if (Object.prototype.hasOwnProperty.call(error.errors, key))
1158
+ {
1159
+ errorString += `${key}: ${error.errors[key]}\n`;
1160
+ }
1161
+ }
1162
+ console.error(`${message}: ${errorString}`);
1163
+ }
1164
+ }
1165
+ else
1166
+ {
1167
+ console.error(`${message}: ${error.message}`);
1168
+ }
1169
+
1170
+ return null;
1171
+ }
1172
+
1173
+
1174
+ import { getRandomValues } from 'crypto';
1175
+
1176
+ function _newGuid()
1177
+ {
1178
+ return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, (c) =>
1179
+ (c ^ (getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16)
1180
+ );
1126
1181
  }
1127
1182
 
1128
1183
 
1129
- function _apiExceptionHandler(error, message) {
1130
- // Check if we have a response object and error message
1131
- if (!error) {
1132
- console.error(message);
1133
- }
1134
-
1135
- // Check if error is a string
1136
- if (typeof error === "string") {
1137
- console.error(`${message}: ${error}`);
1138
- }
1139
- else if (error.errors)
1140
- {
1141
- if (Array.isArray(error.errors)) {
1142
- let errorString = "";
1143
- for (let errorIdx = 0; errorIdx < error.errors.length; errorIdx++)
1144
- {
1145
- errorString += `${error.errors[errorIdx].code}: ${error.errors[errorIdx].field}: ${error.errors[errorIdx].message}\n`;
1146
- }
1147
- console.error(`${message}: ${errorString}`);
1148
- }
1149
- else if (typeof error.errors === "object") {
1150
- let errorString = "";
1151
- for (let key in error.errors) {
1152
- if (Object.prototype.hasOwnProperty.call(error.errors, key)) {
1153
- errorString += `${key}: ${error.errors[key]}\n`;
1154
- }
1155
- }
1156
- console.error(`${message}: ${errorString}`);
1157
- }
1158
- }
1159
- else
1160
- {
1161
- console.error(`${message}: ${error.message}`);
1162
- }
1163
-
1164
- return null;
1165
- }
1166
-
1167
-
1168
- /**
1169
- * New GUID
1170
- *
1171
- * @returns UUID v4 GUID
1172
- */
1173
-
1174
- import { getRandomValues } from 'crypto';
1175
-
1176
- function _newGuid() {
1177
- return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, (c) =>
1178
- (c ^ (getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16)
1179
- );
1180
- }
1181
-
1182
-
1183
1184
 
1184
1185
  function _printDatetime(msg)
1185
1186
  {
@@ -1189,25 +1190,76 @@ function _printDatetime(msg)
1189
1190
  }
1190
1191
 
1191
1192
 
1193
+ import { promises as fs } from 'fs';
1194
+ import path from 'path';
1195
+
1196
+ async function _processFile(FILE)
1197
+ {
1198
+ let FILE_PATH = null;
1199
+ if (typeof FILE === "string")
1200
+ {
1201
+ // if running in node
1202
+ if (typeof window === "undefined")
1203
+ {
1204
+ FILE_PATH = FILE;
1205
+ FILE = await fs.stat(FILE);
1206
+ FILE.originalName = path.basename(FILE_PATH);
1207
+ if (!FILE.buffer)
1208
+ {
1209
+ FILE.buffer = await fs.readFile(FILE_PATH);
1210
+ }
1211
+ }
1212
+ else
1213
+ {
1214
+ throw new Error("File path is not supported in browser");
1215
+ }
1216
+ }
1217
+ else
1218
+ {
1219
+ FILE.originalName = FILE.name;
1220
+ // if running in browser
1221
+ if (!FILE.buffer)
1222
+ {
1223
+ FILE.buffer = await _readFileAsArrayBuffer(FILE);
1224
+ }
1225
+ }
1226
+
1227
+ return FILE;
1228
+ }
1229
+
1230
+ async function _readFileAsArrayBuffer(file)
1231
+ {
1232
+ return new Promise((resolve, reject) =>
1233
+ {
1234
+ /* eslint-disable no-undef */
1235
+ const reader = new FileReader();
1236
+ /* eslint-enable no-undef */
1237
+ reader.onload = () => resolve(reader.result);
1238
+ reader.onerror = reject;
1239
+ reader.readAsArrayBuffer(file);
1240
+ });
1241
+ }
1242
+
1243
+
1192
1244
 
1193
1245
 
1194
1246
 
1195
1247
 
1196
1248
  import axios from 'axios';
1197
1249
 
1198
- const MAX_RETRIES = 5;
1199
- const TIMEOUT = 30000;
1200
- const SLEEP_TIME = .5;
1250
+ const MAX_RETRIES = 3;
1251
+ const TIMEOUT = 10000;
1252
+ const SLEEP_TIME = 2;
1201
1253
 
1202
- async function _sendRequest(instance, AUTH_TOKEN, FUNCTION_NAME, URL, METHOD_TYPE, PARAMS, BODY, DEBUG)
1254
+ async function _sendRequest(instance, FUNCTION_NAME, URL, METHOD_TYPE, PARAMS, BODY)
1203
1255
  {
1204
1256
  const HEADERS = {
1205
1257
  "Content-Type": "application/json"
1206
1258
  };
1207
1259
 
1208
- if (AUTH_TOKEN) HEADERS["Authorization"] = `Bearer ${AUTH_TOKEN}`;
1260
+ if (instance.token) HEADERS["Authorization"] = `Bearer ${instance.token}`;
1209
1261
 
1210
- if (DEBUG && FUNCTION_NAME !== "Login") console.log(`URL: ${URL}\nMETHOD: ${METHOD_TYPE}` + (PARAMS && PARAMS.size === 0 ? `\nPARAMS: ${JSON.stringify(PARAMS, null, 4)}` : "") + (BODY ? `\nBODY: ${JSON.stringify(BODY, null, 4)}` : ""));
1262
+ if (instance.debug && FUNCTION_NAME !== "Login") console.log(`URL: ${URL}\nMETHOD: ${METHOD_TYPE}` + (PARAMS && PARAMS.size === 0 ? `\nPARAMS: ${JSON.stringify(PARAMS, null, 4)}` : "") + (BODY ? `\nBODY: ${JSON.stringify(BODY, null, 4)}` : ""));
1211
1263
 
1212
1264
  let retries = 0;
1213
1265
  let RESPONSE = null;
@@ -1216,7 +1268,6 @@ async function _sendRequest(instance, AUTH_TOKEN, FUNCTION_NAME, URL, METHOD_TYP
1216
1268
  {
1217
1269
  try
1218
1270
  {
1219
- refreshedToken = true;
1220
1271
  RESPONSE = await axios({
1221
1272
  method: METHOD_TYPE,
1222
1273
  url: URL,
@@ -1235,6 +1286,11 @@ async function _sendRequest(instance, AUTH_TOKEN, FUNCTION_NAME, URL, METHOD_TYP
1235
1286
  }
1236
1287
  catch (error)
1237
1288
  {
1289
+ if (retries >= MAX_RETRIES)
1290
+ {
1291
+ return _apiExceptionHandler(error.response?.data.message ? error.response.data.message : error.message, `${FUNCTION_NAME} failed`);
1292
+ }
1293
+
1238
1294
  if (error?.response?.status === 403 && FUNCTION_NAME !== "Refresh Token" && !refreshedToken)
1239
1295
  {
1240
1296
  await instance.refreshToken();
@@ -1243,7 +1299,7 @@ async function _sendRequest(instance, AUTH_TOKEN, FUNCTION_NAME, URL, METHOD_TYP
1243
1299
  }
1244
1300
  else if (error.code === 'ECONNABORTED')
1245
1301
  {
1246
- await _sleep(SLEEP_TIME * 2 ** (retries - 1));
1302
+ await _sleep(SLEEP_TIME * 2 ** (retries + 1));
1247
1303
  }
1248
1304
  else
1249
1305
  {
@@ -1257,181 +1313,187 @@ async function _sendRequest(instance, AUTH_TOKEN, FUNCTION_NAME, URL, METHOD_TYP
1257
1313
  }
1258
1314
 
1259
1315
 
1260
- async function _sleep(duration) {
1261
- // Check for valid duration
1262
- if (!duration || duration === 0) {
1263
- // Ignore
1264
- return;
1265
- }
1266
-
1267
- // Sleep
1268
- return new Promise((resolve) => {
1269
- setTimeout(() => {
1270
- resolve();
1271
- }, duration * 1000);
1272
- });
1273
- }
1274
-
1275
-
1276
-
1277
- function _slugify(text) {
1278
- if (!text || text.trim().length === 0) return "";
1279
- return text
1280
- .toString()
1281
- .normalize("NFD")
1282
- .replace(/[\u0300-\u036f]/g, "")
1283
- .toLowerCase()
1284
- .trim()
1285
- .replace(/\s+/g, "-")
1286
- .replace(/[^\w-]+/g, "")
1287
- .replace(/--+/g, "-");
1288
- }
1289
-
1290
-
1291
-
1292
-
1293
-
1294
- async function _clearContinueWatching(instance, AUTH_TOKEN, URL, USER_ID, ASSET_ID, DEBUG_MODE)
1316
+ async function _sleep(duration)
1317
+ {
1318
+ // Check for valid duration
1319
+ if (!duration || duration === 0)
1320
+ {
1321
+ // Ignore
1322
+ return;
1323
+ }
1324
+
1325
+ // Sleep
1326
+ return new Promise((resolve) => {
1327
+ setTimeout(() => {
1328
+ resolve();
1329
+ }, duration * 1000);
1330
+ });
1331
+ }
1332
+
1333
+
1334
+
1335
+ function _slugify(text)
1336
+ {
1337
+ if (!text || text.trim().length === 0) return "";
1338
+ return text
1339
+ .toString()
1340
+ .normalize("NFD")
1341
+ .replace(/[\u0300-\u036f]/g, "")
1342
+ .toLowerCase()
1343
+ .trim()
1344
+ .replace(/\s+/g, "-")
1345
+ .replace(/[^\w-]+/g, "")
1346
+ .replace(/--+/g, "-");
1347
+ }
1348
+
1349
+
1350
+
1351
+
1352
+
1353
+ async function _clearContinueWatching(instance, USER_ID, ASSET_ID)
1295
1354
  {
1296
- const API_URL = `${URL}/api/media/clear-watching`;
1355
+ const API_URL = `${instance.config.serviceApiUrl}/api/media/clear-watching`;
1297
1356
 
1298
1357
  const PARAMS = {
1299
1358
  userId: USER_ID,
1300
1359
  assetId: ASSET_ID
1301
1360
  };
1302
1361
 
1303
- return await _sendRequest(instance, AUTH_TOKEN, "Clear Continue Watching", API_URL, "POST", PARAMS, null, DEBUG_MODE);
1362
+ return await _sendRequest(instance, "Clear Continue Watching", API_URL, "POST", PARAMS, undefined);
1304
1363
  }
1305
1364
 
1306
1365
 
1307
1366
 
1308
1367
 
1309
- async function _clearWatchlist(instance, AUTH_TOKEN, URL, USER_ID, DEBUG_MODE)
1368
+ async function _clearWatchlist(instance, USER_ID)
1310
1369
  {
1311
- const API_URL = `${URL}/api/media/clear-watchlist?userId=${USER_ID}`;
1370
+ const API_URL = `${instance.config.serviceApiUrl}/api/media/clear-watchlist?userId=${USER_ID}`;
1312
1371
 
1313
- return await _sendRequest(instance, AUTH_TOKEN, "Clear Watchlist", API_URL, "POST", null, null, DEBUG_MODE);
1372
+ return await _sendRequest(instance, "Clear Watchlist", API_URL, "POST", undefined, undefined);
1314
1373
  }
1315
1374
 
1316
1375
 
1317
-
1318
-
1319
- async function _createForm(instance, AUTH_TOKEN, URL, CONTENT_DEFINITION_ID, FORM_INFO, DEBUG_MODE)
1320
- {
1321
- const API_URL = `${URL}/api/media/form/${CONTENT_DEFINITION_ID}`;
1322
-
1323
- const BODY = FORM_INFO;
1324
-
1325
- return await _sendRequest(instance, AUTH_TOKEN, "Creating Form", API_URL, "POST", null, BODY, DEBUG_MODE);
1326
- }
1327
-
1376
+
1377
+
1378
+ async function _createForm(instance, CONTENT_DEFINITION_ID, FORM_INFO)
1379
+ {
1380
+ const API_URL = `${instance.config.serviceApiUrl}/api/media/form/${CONTENT_DEFINITION_ID}`;
1381
+
1382
+ const BODY = FORM_INFO;
1383
+
1384
+ return await _sendRequest(instance, "Creating Form", API_URL, "POST", undefined, BODY);
1385
+ }
1386
+
1328
1387
 
1329
1388
 
1330
1389
 
1331
- async function _getContentCookies(instance, AUTH_TOKEN, URL, ID, DEBUG_MODE)
1390
+ async function _getContentCookies(instance, ID)
1332
1391
  {
1333
- const API_URL = `${URL}/api/media/set-cookies/${ID}`;
1392
+ const API_URL = `${instance.config.serviceApiUrl}/api/media/set-cookies/${ID}`;
1334
1393
 
1335
- return await _sendRequest(instance, AUTH_TOKEN, "Get Content Cookies", API_URL, "GET", undefined, undefined, DEBUG_MODE);
1394
+ return await _sendRequest(instance, "Get Content Cookies", API_URL, "GET", undefined, undefined);
1336
1395
  }
1337
1396
 
1338
1397
 
1339
1398
 
1340
1399
 
1341
- async function _getDefaultSiteConfig(instance, AUTH_TOKEN, URL, DEBUG_MODE)
1400
+ async function _getDefaultSiteConfig(instance)
1342
1401
  {
1343
- const API_URL = `${URL}/api/media/config`;
1402
+ const API_URL = `${instance.config.serviceApiUrl}/api/media/config`;
1344
1403
 
1345
- return await _sendRequest(instance, AUTH_TOKEN, "Get Default Site Config", API_URL, "GET", undefined, undefined, DEBUG_MODE);
1404
+ return await _sendRequest(instance, "Get Default Site Config", API_URL, "GET", undefined, undefined);
1346
1405
  }
1347
1406
 
1348
1407
 
1349
1408
 
1350
1409
 
1351
- async function _getDynamicContent(instance, AUTH_TOKEN, URL, ID, DEBUG_MODE)
1410
+ async function _getDynamicContent(instance, ID)
1352
1411
  {
1353
- const API_URL = `${URL}/api/media/content/${ID}`;
1412
+ const API_URL = `${instance.config.serviceApiUrl}/api/media/content/${ID}`;
1354
1413
 
1355
- return await _sendRequest(instance, AUTH_TOKEN, "Get Dynamic Content", API_URL, "GET", undefined, undefined, DEBUG_MODE);
1414
+ return await _sendRequest(instance, "Get Dynamic Content", API_URL, "GET", undefined, undefined);
1356
1415
  }
1357
1416
 
1358
1417
 
1359
1418
 
1360
1419
 
1361
- async function _getDynamicContents(instance, AUTH_TOKEN, URL, DEBUG_MODE)
1420
+ async function _getDynamicContents(instance)
1362
1421
  {
1363
- const API_URL = `${URL}/api/media/content`;
1422
+ const API_URL = `${instance.config.serviceApiUrl}/api/media/content`;
1364
1423
 
1365
- return await _sendRequest(instance, AUTH_TOKEN, "Get Dynamic Contents", API_URL, "GET", undefined, undefined, DEBUG_MODE);
1424
+ return await _sendRequest(instance, "Get Dynamic Contents", API_URL, "GET", undefined, undefined);
1366
1425
  }
1367
1426
 
1368
1427
 
1369
1428
 
1370
1429
 
1371
- async function _getMediaGroup(instance, AUTH_TOKEN, URL, ID, DEBUG_MODE)
1430
+ async function _getMediaGroup(instance, ID, FILTER_IDS)
1372
1431
  {
1373
- const API_URL = `${URL}/api/media/group/${ID}`;
1432
+ let apiUrl = `${instance.config.serviceApiUrl}/api/media/group/${ID}`;
1433
+ if (FILTER_IDS && FILTER_IDS.length > 0) {
1434
+ apiUrl += '?' + FILTER_IDS.map(id => `filterIds=${id}`).join('&');
1435
+ }
1374
1436
 
1375
- return await _sendRequest(instance, AUTH_TOKEN, "Get Media Group", API_URL, "GET", undefined, undefined, DEBUG_MODE);
1437
+ return await _sendRequest(instance, "Get Media Group", apiUrl, "GET", undefined, undefined);
1376
1438
  }
1377
1439
 
1378
1440
 
1379
1441
 
1380
1442
 
1381
- async function _getMediaItem(instance, AUTH_TOKEN, URL, ID, DEBUG_MODE)
1443
+ async function _getMediaItem(instance, ID)
1382
1444
  {
1383
- const API_URL = `${URL}/api/media/item/${ID}`;
1445
+ const API_URL = `${instance.config.serviceApiUrl}/api/media/item/${ID}`;
1384
1446
 
1385
- return await _sendRequest(instance, AUTH_TOKEN, "Get Media Item", API_URL, "GET", undefined, undefined, DEBUG_MODE);
1447
+ return await _sendRequest(instance, "Get Media Item", API_URL, "GET", undefined, undefined);
1386
1448
  }
1387
1449
 
1388
1450
 
1389
1451
 
1390
1452
 
1391
- async function _getMyContent(instance, AUTH_TOKEN, URL, DEBUG_MODE)
1453
+ async function _getMyContent(instance)
1392
1454
  {
1393
- const API_URL = `${URL}/api/media/my-content`;
1455
+ const API_URL = `${instance.config.serviceApiUrl}/api/media/my-content`;
1394
1456
 
1395
- return await _sendRequest(instance, AUTH_TOKEN, "Get My Content", API_URL, "GET", undefined, undefined, DEBUG_MODE);
1457
+ return await _sendRequest(instance, "Get My Content", API_URL, "GET", undefined, undefined);
1396
1458
  }
1397
1459
 
1398
1460
 
1399
1461
 
1400
1462
 
1401
- async function _getMyGroup(instance, AUTH_TOKEN, URL, ID, DEBUG_MODE)
1463
+ async function _getMyGroup(instance, ID)
1402
1464
  {
1403
- const API_URL = `${URL}/api/media/my-group/${ID}`;
1465
+ const API_URL = `${instance.config.serviceApiUrl}/api/media/my-group/${ID}`;
1404
1466
 
1405
- return await _sendRequest(instance, AUTH_TOKEN, "Get My Group", API_URL, "GET", undefined, undefined, DEBUG_MODE);
1467
+ return await _sendRequest(instance, "Get My Group", API_URL, "GET", undefined, undefined);
1406
1468
  }
1407
1469
 
1408
1470
 
1409
1471
 
1410
1472
 
1411
- async function _getSiteConfig(instance, AUTH_TOKEN, URL, ID, DEBUG_MODE)
1473
+ async function _getSiteConfig(instance, ID)
1412
1474
  {
1413
- const API_URL = `${URL}/api/media/config/${ID}`;
1475
+ const API_URL = `${instance.config.serviceApiUrl}/api/media/config/${ID}`;
1414
1476
 
1415
- return await _sendRequest(instance, AUTH_TOKEN, "Get Site Config", API_URL, "GET", undefined, undefined, DEBUG_MODE);
1477
+ return await _sendRequest(instance, "Get Site Config", API_URL, "GET", undefined, undefined);
1416
1478
  }
1417
1479
 
1418
1480
 
1419
-
1420
-
1421
- async function _mediaSearch(instance, AUTH_TOKEN, URL, SEARCH_QUERY, IDS, SORT_FIELDS,
1422
- PAGE_OFFSET, PAGE_SIZE, DEBUG_MODE)
1423
- {
1424
- const API_URL = `${URL}/api/media/search`;
1425
-
1426
- const BODY = {
1427
- searchQuery: SEARCH_QUERY,
1428
- ids: IDS,
1429
- sortFields: SORT_FIELDS
1430
- };
1431
-
1432
- PAGE_OFFSET ? BODY["pageOffset"] = PAGE_OFFSET : BODY["pageOffset"] = 0;
1433
- PAGE_SIZE ? BODY["pageSize"] = PAGE_SIZE : BODY["pageSize"] = 100;
1434
-
1435
- return await _sendRequest(instance, AUTH_TOKEN, "Media Search", API_URL, "POST", null, BODY, DEBUG_MODE);
1436
- }
1437
-
1481
+
1482
+
1483
+ async function _mediaSearch(instance, SEARCH_QUERY, IDS, SORT_FIELDS,
1484
+ PAGE_OFFSET, PAGE_SIZE)
1485
+ {
1486
+ const API_URL = `${instance.config.serviceApiUrl}/api/media/search`;
1487
+
1488
+ const BODY = {
1489
+ searchQuery: SEARCH_QUERY,
1490
+ ids: IDS,
1491
+ sortFields: SORT_FIELDS
1492
+ };
1493
+
1494
+ PAGE_OFFSET ? BODY["pageOffset"] = PAGE_OFFSET : BODY["pageOffset"] = 0;
1495
+ PAGE_SIZE ? BODY["pageSize"] = PAGE_SIZE : BODY["pageSize"] = 100;
1496
+
1497
+ return await _sendRequest(instance, "Media Search", API_URL, "POST", undefined, BODY);
1498
+ }
1499
+
@@ -1,5 +1,6 @@
1
- import{promises as fs}from"fs";import path from"path";class NomadMediaSDK{constructor(t={}){return NomadMediaSDK.instance||(this.config=t,this.token=null,this.refreshTokenVal=null,this.expirationSeconds=null,this.userSessionId=null,this.id=null,this.debugMode=t.debugMode||!1,"/"===this.config.serviceApiUrl[this.config.serviceApiUrl.length-1]&&(this.config.serviceApiUrl=this.config.serviceApiUrl.slice(0,-1)),NomadMediaSDK.instance=this)}async _init(){await this.login()}async login(){_printDatetime("Logging in as "+this.config.username);try{var t=await _login(this,this.config.username,this.config.password,this.config.serviceApiUrl,this.debugMode);this.token=t.token,this.refreshTokenVal=t.refreshToken,this.expirationSeconds=t.expirationSeconds,this.userSessionId=t.userSessionId,this.id=t.id,_printDatetime("Login successful")}catch(t){throw _printDatetime("Login failed"),t}}async logout(){null===this.token&&this.config.username&&await this._init(),_printDatetime("Logging out");try{await _logout(this,this.token,this.config.serviceApiUrl,this.debugMode),this.token=null,this.refreshTokenVal=null,this.expirationSeconds=null,this.userSessionId=null,this.id=null,_printDatetime("Logout successful")}catch(t){throw _printDatetime("Loggout failed"),t}}async refreshToken(){_printDatetime("Refreshing token");try{await _refreshToken(this,this.token,this.config.serviceApiUrl,this.refreshTokenVal,this.debugMode)&&_printDatetime("Token refresh successful")}catch(t){throw _printDatetime("Token refresh failed"),t}}async forgotPassword(){var e=this.config.username;_printDatetime("Sending code to "+e);try{await _forgotPassword(this,this.config.serviceApiUrl,e,this.debugMode),_printDatetime("Code sent to "+e)}catch(t){throw _printDatetime("Code failed to send to "+e),t}}async resetPassword(t,e){var i=this.config.username;_printDatetime("Resetting password for "+i);try{await _resetPassword(this,this.config.serviceApiUrl,i,t,e,this.debugMode),_printDatetime("Password reset for "+i)}catch(t){throw _printDatetime("Password failed to reset for "+i),t}}async clearContinueWatching(t,e){if(null===this.token&&this.config.username&&await this._init(),"portal"!==this.config.apiType)throw new Error("This function is only available for portal API type.");_printDatetime("Clearing continue watching");try{await _clearContinueWatching(this,this.token,this.config.serviceApiUrl,t,e,this.debugMode),_printDatetime("Continue watching cleared")}catch(t){throw _printDatetime("Continue watching failed to clear"),t}}async clearWatchlist(t){if(null===this.token&&this.config.username&&await this._init(),"portal"!==this.config.apiType)throw new Error("This function is only available for portal API type.");_printDatetime("Clearing watchlist");try{t=t||this.id,await _clearWatchlist(this,this.token,this.config.serviceApiUrl,t,this.debugMode),_printDatetime("Watchlist cleared")}catch(t){throw _printDatetime("Watchlist failed to clear"),t}}async createForm(t,e){if(null===this.token&&this.config.username&&await this._init(),"portal"!==this.config.apiType)throw new Error("This function is only available for portal API type.");_printDatetime("Creating form");try{var i=await _createForm(this,this.token,this.config.serviceApiUrl,t,e,this.debugMode);return i&&_printDatetime("Form created"),i}catch(t){throw _printDatetime("Form failed to create"),t}}async getContentCookies(t){if(null===this.token&&this.config.username&&await this._init(),"portal"!==this.config.apiType)throw new Error("This function is only available for portal API type.");_printDatetime("Getting content cookies");try{var e=await _getContentCookies(this,this.token,this.config.serviceApiUrl,t,this.debugMode);return e&&_printDatetime("Content cookies gotten"),e}catch(t){throw _printDatetime("Content cookies failed to get"),t}}async getDefaultSiteConfig(){if(null===this.token&&this.config.username&&await this._init(),"portal"!==this.config.apiType)throw new Error("This function is only available for portal API type.");_printDatetime("Getting default site config");try{var t=await _getDefaultSiteConfig(this,this.token,this.config.serviceApiUrl,this.debugMode);return t&&_printDatetime("Default site config gotten"),t}catch(t){throw _printDatetime("Default site config failed to get"),t}}async getDynamicContent(e){null===this.token&&this.config.username&&await this._init(),_printDatetime("Getting dynamic content: "+e);try{var t=await _getDynamicContent(this,this.token,this.config.serviceApiUrl,e,this.debugMode);return t&&_printDatetime("Dynamic content gotten: "+e),t}catch(t){throw _printDatetime("Dynamic content failed to get: "+e),t}}async getDynamicContents(){if(null===this.token&&this.config.username&&await this._init(),"portal"!==this.config.apiType)throw new Error("This function is only available for portal API type.");_printDatetime("Getting dynamic contents");try{var t=await _getDynamicContents(this,this.token,this.config.serviceApiUrl,this.debugMode);return t&&_printDatetime("Dynamic contents gotten"),t}catch(t){throw _printDatetime("Dynamic contents failed to get"),t}}async getMediaGroup(e){if(null===this.token&&this.config.username&&await this._init(),"portal"!==this.config.apiType)throw new Error("This function is only available for portal API type.");_printDatetime("Getting media group: "+e);try{var t=await _getMediaGroup(this,this.token,this.config.serviceApiUrl,e,this.debugMode);return t&&_printDatetime("Media group gotten: "+e),t}catch(t){throw _printDatetime("Media group failed to get: "+e),t}}async getMediaItem(e){if(null===this.token&&this.config.username&&await this._init(),"portal"!==this.config.apiType)throw new Error("This function is only available for portal API type.");_printDatetime("Getting media item: "+e);try{var t=await _getMediaItem(this,this.token,this.config.serviceApiUrl,e,this.debugMode);return t&&_printDatetime("Media item gotten: "+e),t}catch(t){throw _printDatetime("Media item failed to get: "+e),t}}async getMyContent(){if(null===this.token&&this.config.username&&await this._init(),"portal"!==this.config.apiType)throw new Error("This function is not available for portal API type.");_printDatetime("Getting my content");try{var t=await _getMyContent(this,this.token,this.config.serviceApiUrl,this.debugMode);return t&&_printDatetime("My content gotten"),t}catch(t){throw _printDatetime("My content failed to get"),t}}async getMyGroup(e){null===this.token&&this.config.username&&await this._init(),_printDatetime("Getting my group: "+e);try{var t=await _getMyGroup(this,this.token,this.config.serviceApiUrl,e,this.debugMode);return t&&_printDatetime("My group gotten: "+e),t}catch(t){throw _printDatetime("My group failed to get: "+e),t}}async getSiteConfig(e){null===this.token&&this.config.username&&await this._init(),_printDatetime("Getting site config: "+e);try{var t=await _getSiteConfig(this,this.token,this.config.serviceApiUrl,e,this.debugMode);return t&&_printDatetime("Site config gotten: "+e),t}catch(t){throw _printDatetime("Site config failed to get: "+e),t}}async mediaSearch(t,e,i,n,r){if(null===this.token&&this.config.username&&await this._init(),"portal"!==this.config.apiType)throw new Error("This function is only available for portal API type.");_printDatetime("Searching media...");try{var a=await _mediaSearch(this,this.token,this.config.serviceApiUrl,t,e,i,n,r,this.debugMode);return a&&_printDatetime("Media search complete"),a}catch(t){throw _printDatetime("Media search failed"),t}}async miscFunctions(e,i,n,r){null===this.token&&this.config.username&&await this._init(),_printDatetime("Calling function: "+e);try{let t=this.config.serviceApiUrl+"/"+e;r&&(t=(t=(t=t.replace("/api","")).replace("app-api.","")).replace("admin-app.",""));var a=new Headers,o=(a.append("Content-Type","application/json"),null!==this.token&&a.append("Authorization","Bearer "+this.token),this.debugMode&&(console.log(`URL: ${t}
2
- METHOD: `+i),n)&&console.log("BODY: "+JSON.stringify(n,null,4)),{method:i,headers:a}),s=(n&&(o.body=JSON.stringify(n)),await fetch(t,o)),c=await s.text();if(!s.ok)try{throw JSON.parse(c)}catch(t){throw c}try{return JSON.parse(c)}catch(t){return c}}catch(t){_apiExceptionHandler(t,"API call failed")}}}export default NomadMediaSDK;async function _forgotPassword(t,e,i,n){return _sendRequest(t,null,"Forgot Password",e+"/api/account/forgot-password","POST",null,{username:i},n)}async function _login(t,e,i,n,r){n+="/api/account/login",e={userName:e,password:i};try{return await _sendRequest(t,null,"Login",n,"POST",null,e,r)}catch(t){throw t.message.includes("409")?new Error("Invalid username or password"):t}}async function _logout(t,e,i,n){return _sendRequest(t,e,"Logout",i+"/api/account/logout","POST",null,null,n)}async function _refreshToken(t,e,i,n,r){e=await _sendRequest(t,e,"Refreshing Token",i+"/api/account/refresh-token","POST",null,{refreshToken:n},r);return t.token=e.token,!0}async function _resetPassword(t,e,i,n,r,a){return _sendRequest(t,null,"Reset Password",e+"/api/account/reset-password","POST",null,{userName:i,TOKEN:n,newPassword:r},a)}function _apiExceptionHandler(i,n){if(i||console.error(n),"string"==typeof i)console.error(n+": "+i);else if(i.errors){if(Array.isArray(i.errors)){let e="";for(let t=0;t<i.errors.length;t++)e+=`${i.errors[t].code}: ${i.errors[t].field}: ${i.errors[t].message}\n`;console.error(n+": "+e)}else if("object"==typeof i.errors){let t="";for(var e in i.errors)Object.prototype.hasOwnProperty.call(i.errors,e)&&(t+=`${e}: ${i.errors[e]}\n`);console.error(n+": "+t)}}else console.error(n+": "+i.message);return null}import{getRandomValues}from"crypto";function _newGuid(){return([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,t=>(t^getRandomValues(new Uint8Array(1))[0]&15>>t/4).toString(16))}function _printDatetime(t){var e=(new Date).toLocaleTimeString();console.log(e+": "+t)}import axios from"axios";let MAX_RETRIES=5,TIMEOUT=3e4,SLEEP_TIME=.5;async function _sendRequest(e,t,i,n,r,a,o,s){var c={"Content-Type":"application/json"};t&&(c.Authorization="Bearer "+t),s&&"Login"!==i&&console.log(`URL: ${n}
3
- METHOD: `+r+(a&&0===a.size?`
4
- PARAMS: `+JSON.stringify(a,null,4):"")+(o?`
5
- BODY: `+JSON.stringify(o,null,4):""));let l=0,h=null,u=!1;do{try{if(u=!0,200<=(h=await axios({method:r,url:n,headers:c,params:a,data:o,timeout:TIMEOUT})).status&&h.status<300)break;throw new Error}catch(t){if(403!==t?.response?.status||"Refresh Token"===i||u){if("ECONNABORTED"!==t.code)return _apiExceptionHandler((t.response?.data.message?t.response.data:t).message,i+" failed");await _sleep(SLEEP_TIME*2**(l-1))}else await e.refreshToken(),c.Authorization="Bearer "+e.token,u=!0;++l}}while((!h||h.status<200||300<=h.status)&&l<MAX_RETRIES);try{return h.data}catch(t){}}async function _sleep(e){if(e&&0!==e)return new Promise(t=>{setTimeout(()=>{t()},1e3*e)})}function _slugify(t){return t&&0!==t.trim().length?t.toString().normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase().trim().replace(/\s+/g,"-").replace(/[^\w-]+/g,"").replace(/--+/g,"-"):""}async function _clearContinueWatching(t,e,i,n,r,a){return _sendRequest(t,e,"Clear Continue Watching",i+"/api/media/clear-watching","POST",{userId:n,assetId:r},null,a)}async function _clearWatchlist(t,e,i,n,r){return _sendRequest(t,e,"Clear Watchlist",i+"/api/media/clear-watchlist?userId="+n,"POST",null,null,r)}async function _createForm(t,e,i,n,r,a){return _sendRequest(t,e,"Creating Form",i+"/api/media/form/"+n,"POST",null,r,a)}async function _getContentCookies(t,e,i,n,r){return _sendRequest(t,e,"Get Content Cookies",i+"/api/media/set-cookies/"+n,"GET",void 0,void 0,r)}async function _getDefaultSiteConfig(t,e,i,n){return _sendRequest(t,e,"Get Default Site Config",i+"/api/media/config","GET",void 0,void 0,n)}async function _getDynamicContent(t,e,i,n,r){return _sendRequest(t,e,"Get Dynamic Content",i+"/api/media/content/"+n,"GET",void 0,void 0,r)}async function _getDynamicContents(t,e,i,n){return _sendRequest(t,e,"Get Dynamic Contents",i+"/api/media/content","GET",void 0,void 0,n)}async function _getMediaGroup(t,e,i,n,r){return _sendRequest(t,e,"Get Media Group",i+"/api/media/group/"+n,"GET",void 0,void 0,r)}async function _getMediaItem(t,e,i,n,r){return _sendRequest(t,e,"Get Media Item",i+"/api/media/item/"+n,"GET",void 0,void 0,r)}async function _getMyContent(t,e,i,n){return _sendRequest(t,e,"Get My Content",i+"/api/media/my-content","GET",void 0,void 0,n)}async function _getMyGroup(t,e,i,n,r){return _sendRequest(t,e,"Get My Group",i+"/api/media/my-group/"+n,"GET",void 0,void 0,r)}async function _getSiteConfig(t,e,i,n,r){return _sendRequest(t,e,"Get Site Config",i+"/api/media/config/"+n,"GET",void 0,void 0,r)}async function _mediaSearch(t,e,i,n,r,a,o,s,c){i+="/api/media/search",n={searchQuery:n,ids:r,sortFields:a};return n.pageOffset=o||0,n.pageSize=s||100,_sendRequest(t,e,"Media Search",i,"POST",null,n,c)}
1
+ class NomadMediaSDK{constructor(t={}){return NomadMediaSDK.instance||(this.config=t,this.token=null,this.refreshTokenVal=null,this.expirationSeconds=null,this.userSessionId=null,this.id=null,this.debug=t.debugMode||!1,"/"===this.config.serviceApiUrl[this.config.serviceApiUrl.length-1]&&(this.config.serviceApiUrl=this.config.serviceApiUrl.slice(0,-1)),this.config.singleton&&(NomadMediaSDK.instance=this),this)}async _init(){await this.login()}async login(){_printDatetime("Logging in as "+this.config.username);try{var t=await _login(this);if(!t)throw new Error("Login failed");this.token=t.token,this.refreshTokenVal=t.refreshToken,this.expirationSeconds=t.expirationSeconds,this.userSessionId=t.userSessionId,this.id=t.id,_printDatetime("Login successful")}catch(t){throw _printDatetime("Login failed"),t}}async logout(){null===this.token&&this.config.username&&await this._init(),_printDatetime("Logging out");try{await _logout(this),this.token=null,this.refreshTokenVal=null,this.expirationSeconds=null,this.userSessionId=null,this.id=null,_printDatetime("Logout successful")}catch(t){throw _printDatetime("Logout failed"),t}}async refreshToken(){_printDatetime("Refreshing token"),null===this.token&&this.config.username&&await this._init();try{await _refreshToken(this)&&_printDatetime("Token refresh successful")}catch(t){throw _printDatetime("Token refresh failed"),t}}async forgotPassword(){var e=this.config.username;_printDatetime("Sending code to "+e);try{await _forgotPassword(this),_printDatetime("Code sent to "+e)}catch(t){throw _printDatetime("Code failed to send to "+e),t}}async resetPassword(t,e){var i=this.config.username;_printDatetime("Resetting password for "+i);try{await _resetPassword(this,t,e),_printDatetime("Password reset for "+i)}catch(t){throw _printDatetime("Password failed to reset for "+i),t}}async clearContinueWatching(t,e){if(null===this.token&&this.config.username&&await this._init(),"portal"!==this.config.apiType)throw new Error("This function is only available for portal API type.");_printDatetime("Clearing continue watching");try{await _clearContinueWatching(this,t,e),_printDatetime("Continue watching cleared")}catch(t){throw _printDatetime("Continue watching failed to clear"),t}}async clearWatchlist(t){if(null===this.token&&this.config.username&&await this._init(),"portal"!==this.config.apiType)throw new Error("This function is only available for portal API type.");_printDatetime("Clearing watchlist");try{await _clearWatchlist(this,t=t||this.id),_printDatetime("Watchlist cleared")}catch(t){throw _printDatetime("Watchlist failed to clear"),t}}async createForm(t,e){if(null===this.token&&this.config.username&&await this._init(),"portal"!==this.config.apiType)throw new Error("This function is only available for portal API type.");_printDatetime("Creating form");try{var i=await _createForm(this,t,e);return i&&_printDatetime("Form created"),i}catch(t){throw _printDatetime("Form failed to create"),t}}async getContentCookies(t){if(null===this.token&&this.config.username&&await this._init(),"portal"!==this.config.apiType)throw new Error("This function is only available for portal API type.");_printDatetime("Getting content cookies");try{var e=await _getContentCookies(this,t);return e&&_printDatetime("Content cookies gotten"),e}catch(t){throw _printDatetime("Content cookies failed to get"),t}}async getDefaultSiteConfig(){if(null===this.token&&this.config.username&&await this._init(),"portal"!==this.config.apiType)throw new Error("This function is only available for portal API type.");_printDatetime("Getting default site config");try{var t=await _getDefaultSiteConfig(this);return t&&_printDatetime("Default site config gotten"),t}catch(t){throw _printDatetime("Default site config failed to get"),t}}async getDynamicContent(e){null===this.token&&this.config.username&&await this._init(),_printDatetime("Getting dynamic content: "+e);try{var t=await _getDynamicContent(this,e);return t&&_printDatetime("Dynamic content gotten: "+e),t}catch(t){throw _printDatetime("Dynamic content failed to get: "+e),t}}async getDynamicContents(){if(null===this.token&&this.config.username&&await this._init(),"portal"!==this.config.apiType)throw new Error("This function is only available for portal API type.");_printDatetime("Getting dynamic contents");try{var t=await _getDynamicContents(this);return t&&_printDatetime("Dynamic contents gotten"),t}catch(t){throw _printDatetime("Dynamic contents failed to get"),t}}async getMediaGroup(e,t){if(null===this.token&&this.config.username&&await this._init(),"portal"!==this.config.apiType)throw new Error("This function is only available for portal API type.");_printDatetime("Getting media group: "+e);try{var i=await _getMediaGroup(this,e,t);return i&&_printDatetime("Media group gotten: "+e),i}catch(t){throw _printDatetime("Media group failed to get: "+e),t}}async getMediaItem(e){if(null===this.token&&this.config.username&&await this._init(),"portal"!==this.config.apiType)throw new Error("This function is only available for portal API type.");_printDatetime("Getting media item: "+e);try{var t=await _getMediaItem(this,e);return t&&_printDatetime("Media item gotten: "+e),t}catch(t){throw _printDatetime("Media item failed to get: "+e),t}}async getMyContent(){if(null===this.token&&this.config.username&&await this._init(),"portal"!==this.config.apiType)throw new Error("This function is not available for portal API type.");_printDatetime("Getting my content");try{var t=await _getMyContent(this);return t&&_printDatetime("My content gotten"),t}catch(t){throw _printDatetime("My content failed to get"),t}}async getMyGroup(e){null===this.token&&this.config.username&&await this._init(),_printDatetime("Getting my group: "+e);try{var t=await _getMyGroup(this,e);return t&&_printDatetime("My group gotten: "+e),t}catch(t){throw _printDatetime("My group failed to get: "+e),t}}async getSiteConfig(e){null===this.token&&this.config.username&&await this._init(),_printDatetime("Getting site config: "+e);try{var t=await _getSiteConfig(this,e);return t&&_printDatetime("Site config gotten: "+e),t}catch(t){throw _printDatetime("Site config failed to get: "+e),t}}async mediaSearch(t,e,i,n,r){if(null===this.token&&this.config.username&&await this._init(),"portal"!==this.config.apiType)throw new Error("This function is only available for portal API type.");_printDatetime("Searching media...");try{var a=await _mediaSearch(this,t,e,i,n,r);return a&&_printDatetime("Media search complete"),a}catch(t){throw _printDatetime("Media search failed"),t}}async miscFunctions(e,i,n,r){null===this.token&&this.config.username&&await this._init(),_printDatetime("Calling function: "+e);try{let t=this.config.serviceApiUrl+"/"+e;r&&(t=(t=(t=t.replace("/api","")).replace("app-api.","")).replace("admin-app.",""));var a=new Headers,o=(a.append("Content-Type","application/json"),null!==this.token&&a.append("Authorization","Bearer "+this.token),this.debug&&console.log(`URL: ${t}
2
+ METHOD: `+i+(n?`
3
+ BODY: `+JSON.stringify(n,null,4):"")),{method:i,headers:a}),s=(n&&(o.body=JSON.stringify(n)),await fetch(t,o)),c=await s.text();if(!s.ok)try{throw JSON.parse(c)}catch(t){throw c}try{return JSON.parse(c)}catch(t){return c}}catch(t){_apiExceptionHandler(t,"API call failed")}}}export default NomadMediaSDK;async function _forgotPassword(t){return _sendRequest(t,"Forgot Password",t.config.serviceApiUrl+"/api/account/forgot-password","POST",void 0,{username:t.config.username})}async function _login(t){var e=t.config.serviceApiUrl+"/api/account/login",i={userName:t.config.username,password:t.config.password};try{return await _sendRequest(t,"Login",e,"POST",void 0,i)}catch(t){throw t.message.includes("409")?new Error("Invalid username or password"):t}}async function _logout(t){return _sendRequest(t,"Logout",t.config.serviceApiUrl+"/api/account/logout","POST",void 0,void 0)}async function _refreshToken(t){var e=await _sendRequest(t,"Refreshing Token",t.config.serviceApiUrl+"/api/account/refresh-token","POST",void 0,{refreshToken:t.refreshTokenVal});return t.token=e.token,!0}async function _resetPassword(t,e,i){return _sendRequest(t,"Reset Password",t.config.serviceApiUrl+"/api/account/reset-password","POST",void 0,{userName:t.username,token:e,newPassword:i})}function _apiExceptionHandler(i,n){if(i||console.error(n),"string"==typeof i)console.error(n+": "+i);else if(i.errors){if(Array.isArray(i.errors)){let e="";for(let t=0;t<i.errors.length;t++)e+=`${i.errors[t].code}: ${i.errors[t].field}: ${i.errors[t].message}\n`;console.error(n+": "+e)}else if("object"==typeof i.errors){let t="";for(var e in i.errors)Object.prototype.hasOwnProperty.call(i.errors,e)&&(t+=`${e}: ${i.errors[e]}\n`);console.error(n+": "+t)}}else console.error(n+": "+i.message);return null}import{getRandomValues}from"crypto";function _newGuid(){return([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,t=>(t^getRandomValues(new Uint8Array(1))[0]&15>>t/4).toString(16))}function _printDatetime(t){var e=(new Date).toLocaleTimeString();console.log(e+": "+t)}import{promises as fs}from"fs";import path from"path";async function _processFile(t){var e;if("string"==typeof t){if("undefined"!=typeof window)throw new Error("File path is not supported in browser");e=t,(t=await fs.stat(t)).originalName=path.basename(e),t.buffer||(t.buffer=await fs.readFile(e))}else t.originalName=t.name,t.buffer||(t.buffer=await _readFileAsArrayBuffer(t));return t}async function _readFileAsArrayBuffer(n){return new Promise((t,e)=>{let i=new FileReader;i.onload=()=>t(i.result),i.onerror=e,i.readAsArrayBuffer(n)})}import axios from"axios";let MAX_RETRIES=3,TIMEOUT=1e4,SLEEP_TIME=2;async function _sendRequest(e,i,t,n,r,a){var o={"Content-Type":"application/json"};e.token&&(o.Authorization="Bearer "+e.token),e.debug&&"Login"!==i&&console.log(`URL: ${t}
4
+ METHOD: `+n+(r&&0===r.size?`
5
+ PARAMS: `+JSON.stringify(r,null,4):"")+(a?`
6
+ BODY: `+JSON.stringify(a,null,4):""));let s=0,c=null,l=!1;do{try{if(200<=(c=await axios({method:n,url:t,headers:o,params:r,data:a,timeout:TIMEOUT})).status&&c.status<300)break;throw new Error}catch(t){if(s>=MAX_RETRIES)return _apiExceptionHandler((t.response?.data.message?t.response.data:t).message,i+" failed");if(403!==t?.response?.status||"Refresh Token"===i||l){if("ECONNABORTED"!==t.code)return _apiExceptionHandler((t.response?.data.message?t.response.data:t).message,i+" failed");await _sleep(SLEEP_TIME*2**(s+1))}else await e.refreshToken(),o.Authorization="Bearer "+e.token,l=!0;++s}}while((!c||c.status<200||300<=c.status)&&s<MAX_RETRIES);try{return c.data}catch(t){}}async function _sleep(e){if(e&&0!==e)return new Promise(t=>{setTimeout(()=>{t()},1e3*e)})}function _slugify(t){return t&&0!==t.trim().length?t.toString().normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase().trim().replace(/\s+/g,"-").replace(/[^\w-]+/g,"").replace(/--+/g,"-"):""}async function _clearContinueWatching(t,e,i){return _sendRequest(t,"Clear Continue Watching",t.config.serviceApiUrl+"/api/media/clear-watching","POST",{userId:e,assetId:i},void 0)}async function _clearWatchlist(t,e){return _sendRequest(t,"Clear Watchlist",t.config.serviceApiUrl+"/api/media/clear-watchlist?userId="+e,"POST",void 0,void 0)}async function _createForm(t,e,i){return _sendRequest(t,"Creating Form",t.config.serviceApiUrl+"/api/media/form/"+e,"POST",void 0,i)}async function _getContentCookies(t,e){return _sendRequest(t,"Get Content Cookies",t.config.serviceApiUrl+"/api/media/set-cookies/"+e,"GET",void 0,void 0)}async function _getDefaultSiteConfig(t){return _sendRequest(t,"Get Default Site Config",t.config.serviceApiUrl+"/api/media/config","GET",void 0,void 0)}async function _getDynamicContent(t,e){return _sendRequest(t,"Get Dynamic Content",t.config.serviceApiUrl+"/api/media/content/"+e,"GET",void 0,void 0)}async function _getDynamicContents(t){return _sendRequest(t,"Get Dynamic Contents",t.config.serviceApiUrl+"/api/media/content","GET",void 0,void 0)}async function _getMediaGroup(t,e,i){let n=t.config.serviceApiUrl+"/api/media/group/"+e;return i&&0<i.length&&(n+="?"+i.map(t=>"filterIds="+t).join("&")),_sendRequest(t,"Get Media Group",n,"GET",void 0,void 0)}async function _getMediaItem(t,e){return _sendRequest(t,"Get Media Item",t.config.serviceApiUrl+"/api/media/item/"+e,"GET",void 0,void 0)}async function _getMyContent(t){return _sendRequest(t,"Get My Content",t.config.serviceApiUrl+"/api/media/my-content","GET",void 0,void 0)}async function _getMyGroup(t,e){return _sendRequest(t,"Get My Group",t.config.serviceApiUrl+"/api/media/my-group/"+e,"GET",void 0,void 0)}async function _getSiteConfig(t,e){return _sendRequest(t,"Get Site Config",t.config.serviceApiUrl+"/api/media/config/"+e,"GET",void 0,void 0)}async function _mediaSearch(t,e,i,n,r,a){var o=t.config.serviceApiUrl+"/api/media/search",e={searchQuery:e,ids:i,sortFields:n};return e.pageOffset=r||0,e.pageSize=a||100,_sendRequest(t,"Media Search",o,"POST",void 0,e)}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nomad-media/public",
3
- "version": "1.1.13",
3
+ "version": "1.1.14",
4
4
  "description": "Nomad Media NPM",
5
5
  "main": "dist/nomad-media-sdk.min.js",
6
6
  "type": "module",