@swan-admin/swan-ai-measurements 1.0.58 → 1.0.59

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/dist/auth.js ADDED
@@ -0,0 +1,133 @@
1
+ import axios from "axios";
2
+ import { API_ENDPOINTS, APP_AUTH_BASE_URL, APP_AUTH_WEBSOCKET_URL, APP_BASE_URL, REQUIRED_MESSAGE } from "./constants.js";
3
+ import { checkParameters } from "./utils.js";
4
+ /**
5
+ * Represents a Auth class for handling authentication operations.
6
+ */
7
+ export default class Auth {
8
+ #socketRef;
9
+ /**
10
+ * The access key used for authentication.
11
+ * @type {string}
12
+ * @private
13
+ */
14
+ #accessKey;
15
+ /**
16
+ * Constructs a new instance of the Auth class.
17
+ * @param {string} accessKey - The access key used for authentication.
18
+ */
19
+ constructor(accessKey) {
20
+ this.#accessKey = accessKey;
21
+ }
22
+ /**
23
+ * Register a new user.
24
+ * @param {Object} params - The parameters for user registration.
25
+ * @param {string} params.email - The email of the user.
26
+ * @param {string} params.appVerifyUrl - The verification URL.
27
+ * @param {string} [params.gender] - Optional. The gender of the user.
28
+ * @param {string} [params.height] - Optional. The height of the user.
29
+ * @param {string} params.username - Optional. The username of the user.
30
+ * @returns {Promise} - The axios response promise.
31
+ */
32
+ registerUser({ email, appVerifyUrl, gender, height, username }) {
33
+ if (checkParameters(email, appVerifyUrl) === false) {
34
+ throw new Error(REQUIRED_MESSAGE);
35
+ }
36
+ let body = {
37
+ username,
38
+ email,
39
+ appVerifyUrl,
40
+ };
41
+ if (gender && height) {
42
+ body = { ...body, attributes: { gender, height } };
43
+ }
44
+ return axios.post(`${APP_AUTH_BASE_URL}${API_ENDPOINTS.REGISTER_USER}`, body, {
45
+ headers: { "X-Api-Key": this.#accessKey },
46
+ });
47
+ }
48
+ /**
49
+ * Verify a user token.
50
+ * @param {string} token
51
+ * @returns {Promise}
52
+ */
53
+ verifyToken = (token, accessKey) => {
54
+ if (checkParameters(token) === false) {
55
+ throw new Error(REQUIRED_MESSAGE);
56
+ }
57
+ return axios.post(`${APP_AUTH_BASE_URL}${API_ENDPOINTS.VERIFY_USER}`, null, {
58
+ params: { token },
59
+ headers: { "X-Api-Key": this.#accessKey },
60
+ });
61
+ };
62
+ /**
63
+ * Add a user.
64
+ * @param {Object} params
65
+ * @param {string} params.scanId - The scan ID.
66
+ * @param {string} params.email - The email of the user.
67
+ * @param {string} params.name - The name of the user.
68
+ * @param {string} params.height - The height of the user.
69
+ * @param {string} params.gender - The gender of the user.
70
+ * @param {boolean} [params.offsetMarketingConsent] - Optional. The marketing consent offset.
71
+ * @returns {Promise} - The axios response promise.
72
+ */
73
+ addUser = ({ scanId, email, name, height, gender, offsetMarketingConsent }) => {
74
+ if (checkParameters(scanId, email, height, gender) === false) {
75
+ throw new Error(REQUIRED_MESSAGE);
76
+ }
77
+ return axios.post(`${APP_AUTH_BASE_URL}${API_ENDPOINTS.ADD_USER}`, {
78
+ scan_id: scanId,
79
+ email,
80
+ name,
81
+ offsetMarketingConsent,
82
+ attributes: JSON.stringify({ height, gender }),
83
+ }, { headers: { "X-Api-Key": this.#accessKey } });
84
+ };
85
+ /**
86
+ * Get user details.
87
+ * @param {string} email
88
+ * @returns {Promise}
89
+ */
90
+ getUserDetail = (email) => {
91
+ if (checkParameters(email) === false) {
92
+ throw new Error(REQUIRED_MESSAGE);
93
+ }
94
+ return axios.get(`${APP_BASE_URL}${API_ENDPOINTS.GET_USER_DETAIL}/${email}`, {
95
+ headers: { "X-Api-Key": this.#accessKey },
96
+ });
97
+ };
98
+ /**
99
+ * Handle authentication via WebSocket.
100
+ * @param {Object} params
101
+ * @param {string} params.email - The email address of the user.
102
+ * @param {string} params.scanId - The scan ID associated with the user.
103
+ * @param {function} [params.onError] - Optional. Callback function to handle errors.
104
+ * @param {function} [params.onSuccess] - Optional. Callback function to handle successful authentication.
105
+ * @param {function} [params.onClose] - Optional. Callback function to handle the WebSocket close event.
106
+ * @param {function} [params.onOpen] - Optional. Callback function to handle the WebSocket open event.
107
+ */
108
+ handleAuthSocket = ({ email, scanId, onError, onSuccess, onClose, onOpen }) => {
109
+ if (checkParameters(email, scanId) === false) {
110
+ throw new Error(REQUIRED_MESSAGE);
111
+ }
112
+ this.#socketRef?.close?.();
113
+ this.#socketRef = new WebSocket(`${APP_AUTH_WEBSOCKET_URL}${API_ENDPOINTS.AUTH}`);
114
+ const detailObj = {
115
+ email,
116
+ scanId,
117
+ };
118
+ this.#socketRef.onopen = () => {
119
+ this.#socketRef.send(JSON.stringify(detailObj));
120
+ onOpen?.();
121
+ };
122
+ this.#socketRef.onmessage = (event) => {
123
+ const data = JSON.parse(event.data);
124
+ onSuccess?.(data);
125
+ };
126
+ this.#socketRef.onclose = () => {
127
+ onClose?.();
128
+ };
129
+ this.#socketRef.onerror = (event) => {
130
+ onError?.(event);
131
+ };
132
+ };
133
+ }
@@ -0,0 +1,40 @@
1
+ export const APP_BASE_URL = "https://fitview-server-staging.ft2a64raup4pg.us-east-1.cs.amazonlightsail.com";
2
+ export const APP_AUTH_BASE_URL = "https://staging.api.getswan.co";
3
+ export const APP_AUTH_WEBSOCKET_URL = "wss://staging.wsnotify.api.getswan.co";
4
+ export const APP_TRY_ON_WEBSOCKET_URL = "wss://bucbzczxjk.execute-api.ap-south-1.amazonaws.com";
5
+ export const APP_RECOMMENDATION_WEBSOCKET_URL = "wss://staging.wsnotify.api.getswan.co/scanning";
6
+ export const APP_POSE_DETECTION_WEbSOCKET_URL = "https://posedetect-service-staging.ft2a64raup4pg.us-east-1.cs.amazonlightsail.com";
7
+ export const UPPY_FILE_UPLOAD_ENDPOINT = {
8
+ UPLOAD_START: "/upload/start",
9
+ UPLOAD_COMPLETE: "/upload/complete",
10
+ UPLOAD_SIGN_PART: "/upload/signpart",
11
+ UPLOAD_ABORT: "/upload/abort",
12
+ };
13
+ export const API_ENDPOINTS = {
14
+ GET_USER_DETAIL: "/api/user",
15
+ REGISTER_USER: "/auth/register",
16
+ VERIFY_USER: "/auth/verify",
17
+ ADD_USER: "/user",
18
+ CUSTOM_CUSTOMER: "/customers/custom",
19
+ MODEL: "/model",
20
+ TRY_ON_SCAN: "/tryon/scan",
21
+ TRY_ON_IMAGE_UPLOAD: "/tryon/user-image-urls/upload",
22
+ TRY_ON_IMAGE_DOWNLOAD: "/tryon/user-image-urls/download",
23
+ TRY_ON_IMAGE_URLS: "/tryon/user-image-urls",
24
+ TRY_ON_RESULT_IMAGE_DOWNLOAD: "/tryon/result-image-urls/download",
25
+ TRY_ON: "/tryon",
26
+ AUTH: "/auth",
27
+ };
28
+ export const requiredMetaData = [
29
+ "gender",
30
+ "scan_id",
31
+ "email",
32
+ "focal_length",
33
+ "height",
34
+ "customer_store_url",
35
+ "scan_type",
36
+ "callback_url",
37
+ "clothes_fit",
38
+ ];
39
+ export const REQUIRED_MESSAGE = "Please verify required parameters";
40
+ export const REQUIRED_MESSAGE_FOR_META_DATA = "Please verify required parameters in meta data";
package/dist/custom.js ADDED
@@ -0,0 +1,49 @@
1
+ import axios from "axios";
2
+ import { API_ENDPOINTS, APP_AUTH_BASE_URL, REQUIRED_MESSAGE } from "./constants.js";
3
+ import { checkParameters } from "./utils.js";
4
+ /**
5
+ * Represents a Custom class for handling custom operations.
6
+ */
7
+ class Custom {
8
+ /**
9
+ * The access key used for authentication.
10
+ * @type {string}
11
+ * @private
12
+ */
13
+ #accessKey;
14
+ /**
15
+ * Constructs a new instance of the Custom class.
16
+ * @param {string} accessKey - The access key used for authentication.
17
+ */
18
+ constructor(accessKey) {
19
+ this.#accessKey = accessKey;
20
+ }
21
+ /**
22
+ * Retrieves custom customer configuration based on the store URL.
23
+ * @param {string} store_url - The URL of the store.
24
+ * @returns {Promise} - A promise that resolves with the custom customer configuration.
25
+ * @throws {Error} - If required parameters are missing.
26
+ */
27
+ getCustomCustomerConfig = (store_url) => {
28
+ if (checkParameters(store_url) === false) {
29
+ throw new Error(REQUIRED_MESSAGE);
30
+ }
31
+ return axios.get(`${APP_AUTH_BASE_URL}${API_ENDPOINTS.CUSTOM_CUSTOMER}`, {
32
+ params: { store_url },
33
+ headers: { "X-Api-Key": this.#accessKey },
34
+ });
35
+ };
36
+ /**
37
+ * Retrieves the model URL based on the model ID.
38
+ * @param {string} id - The ID of the model.
39
+ * @returns {Promise} - A promise that resolves with the model URL.
40
+ * @throws {Error} - If required parameters are missing.
41
+ */
42
+ getModelUrl = (id) => {
43
+ if (checkParameters(id) === false) {
44
+ throw new Error(REQUIRED_MESSAGE);
45
+ }
46
+ return axios.get(`${APP_AUTH_BASE_URL}${API_ENDPOINTS.MODEL}/${id}`, { headers: { "X-Api-Key": this.#accessKey } });
47
+ };
48
+ }
49
+ export default Custom;
@@ -0,0 +1,136 @@
1
+ import { REQUIRED_MESSAGE, REQUIRED_MESSAGE_FOR_META_DATA, UPPY_FILE_UPLOAD_ENDPOINT } from "./constants.js";
2
+ import { checkMetaDataValue, checkParameters, fetchData } from "./utils.js";
3
+ /**
4
+ * Class representing a file uploader using Uppy for multipart uploads.
5
+ */
6
+ class FileUpload {
7
+ /**
8
+ * The Uppy instance.
9
+ * @type {Object}
10
+ * @private
11
+ */
12
+ #uppyIns;
13
+ /**
14
+ * Reference to the Uppy module.
15
+ * @type {Object}
16
+ * @private
17
+ */
18
+ #Uppy;
19
+ /**
20
+ * Reference to the AwsS3Multipart module.
21
+ * @type {Object}
22
+ * @private
23
+ */
24
+ #AwsS3Multipart;
25
+ /**
26
+ * The access key used for authentication.
27
+ * @type {string}
28
+ * @private
29
+ */
30
+ #accessKey;
31
+ /**
32
+ * Constructs a new instance of the FileUpload class.
33
+ * @param {string} accessKey - The access key used for authentication.
34
+ */
35
+ constructor(accessKey) {
36
+ this.initializeModules();
37
+ this.#accessKey = accessKey;
38
+ }
39
+ /**
40
+ * Asynchronously initializes the Uppy and AwsS3Multipart modules.
41
+ * @private
42
+ */
43
+ async initializeModules() {
44
+ this.#Uppy = (await import("@uppy/core")).default;
45
+ this.#AwsS3Multipart = (await import("@uppy/aws-s3-multipart")).default;
46
+ }
47
+ /**
48
+ * Uploads a file with optional metadata and scan ID.
49
+ * @param {Object} params - The parameters for file upload.
50
+ * @param {File} params.file - The file to upload.
51
+ * @param {Object} params.objMetaData - Optional. Metadata associated with the file.
52
+ * @param {string} params.scanId - Optional. The ID of the scan.
53
+ * @returns {Promise} - A promise that resolves when the file is uploaded successfully.
54
+ * @throws {Error} - If required parameters are missing or metadata value is invalid.
55
+ */
56
+ async uploadFile({ file, objMetaData, scanId }) {
57
+ if (checkParameters(file, objMetaData, scanId) === false) {
58
+ throw new Error(REQUIRED_MESSAGE);
59
+ }
60
+ if (checkMetaDataValue(objMetaData) === false) {
61
+ throw new Error(REQUIRED_MESSAGE_FOR_META_DATA);
62
+ }
63
+ if (!this.#Uppy || !this.#AwsS3Multipart) {
64
+ await this.initializeModules();
65
+ }
66
+ return new Promise((resolve, reject) => {
67
+ if (this.#uppyIns) {
68
+ this.#uppyIns.close();
69
+ }
70
+ this.#uppyIns = new this.#Uppy({ autoProceed: true });
71
+ this.#uppyIns.use(this.#AwsS3Multipart, {
72
+ limit: 10,
73
+ retryDelays: [0, 1000, 3000, 5000],
74
+ getChunkSize: () => 5 * 1024 * 1024,
75
+ createMultipartUpload: (file) => {
76
+ const objectKey = `${scanId}.${file.extension}`;
77
+ return fetchData({
78
+ path: UPPY_FILE_UPLOAD_ENDPOINT.UPLOAD_START,
79
+ apiKey: this.#accessKey,
80
+ body: {
81
+ objectKey,
82
+ contentType: file.type,
83
+ objectMetadata: objMetaData,
84
+ },
85
+ });
86
+ },
87
+ completeMultipartUpload: (file, { uploadId, key, parts }) => fetchData({
88
+ path: UPPY_FILE_UPLOAD_ENDPOINT.UPLOAD_COMPLETE,
89
+ apiKey: this.#accessKey,
90
+ body: {
91
+ uploadId,
92
+ objectKey: key,
93
+ parts,
94
+ originalFileName: file.name,
95
+ },
96
+ }),
97
+ signPart: (file, partData) => fetchData({
98
+ path: UPPY_FILE_UPLOAD_ENDPOINT.UPLOAD_SIGN_PART,
99
+ apiKey: this.#accessKey,
100
+ body: {
101
+ objectKey: partData.key,
102
+ uploadId: partData.uploadId,
103
+ partNumber: partData.partNumber,
104
+ },
105
+ }),
106
+ abortMultipartUpload: (file, { uploadId, key }) => fetchData({
107
+ path: UPPY_FILE_UPLOAD_ENDPOINT.UPLOAD_ABORT,
108
+ apiKey: this.#accessKey,
109
+ body: {
110
+ uploadId,
111
+ objectKey: key,
112
+ originalFileName: file.name,
113
+ },
114
+ }),
115
+ });
116
+ this.#uppyIns.addFile({
117
+ source: "manual",
118
+ name: file.name,
119
+ type: file.type,
120
+ data: file,
121
+ });
122
+ this.#uppyIns.on("upload-error", (file, error, response) => {
123
+ reject(error);
124
+ });
125
+ this.#uppyIns.on("upload-success", () => {
126
+ resolve({ message: "file uploaded successfully" });
127
+ });
128
+ this.#uppyIns.on("complete", (result) => {
129
+ if (this.#uppyIns) {
130
+ this.#uppyIns.close();
131
+ }
132
+ });
133
+ });
134
+ }
135
+ }
136
+ export default FileUpload;
@@ -0,0 +1,19 @@
1
+ import Auth from "./auth";
2
+ import Custom from "./custom";
3
+ import FileUpload from "./fileUpload";
4
+ import Measurement from "./measurement";
5
+ import PoseDetection from "./poseDetection";
6
+ import TryOn from "./tryOn";
7
+
8
+ export default class Swan {
9
+ constructor(accessKey: string);
10
+
11
+ auth: Auth;
12
+ custom: Custom;
13
+ fileUpload: FileUpload;
14
+ measurement: Measurement;
15
+ poseDetection: PoseDetection;
16
+ tryOn: TryOn;
17
+
18
+ #private;
19
+ }
package/dist/index.js ADDED
@@ -0,0 +1,19 @@
1
+ import Auth from "./auth.js";
2
+ import Custom from "./custom.js";
3
+ import FileUpload from "./fileUpload.js";
4
+ import Measurement from "./measurement.js";
5
+ import PoseDetection from "./poseDetection.js";
6
+ import TryOn from "./tryOn.js";
7
+ class Swan {
8
+ #accessKey;
9
+ constructor(accessKey) {
10
+ this.#accessKey = accessKey;
11
+ }
12
+ auth = new Auth(this.#accessKey);
13
+ custom = new Custom(this.#accessKey);
14
+ fileUpload = new FileUpload(this.#accessKey);
15
+ measurement = new Measurement(this.#accessKey);
16
+ poseDetection = new PoseDetection(this.#accessKey);
17
+ tryOn = new TryOn(this.#accessKey);
18
+ }
19
+ export default Swan;
@@ -0,0 +1,198 @@
1
+ import axios from "axios";
2
+ import { API_ENDPOINTS, APP_AUTH_BASE_URL, APP_RECOMMENDATION_WEBSOCKET_URL, APP_TRY_ON_WEBSOCKET_URL, REQUIRED_MESSAGE } from "./constants.js";
3
+ import { checkParameters } from "./utils.js";
4
+ /**
5
+ * Class representing measurement-related functionality.
6
+ */
7
+ class Measurement {
8
+ #tryOnSocketRef = null;
9
+ #measurementSocketRef = null;
10
+ #timerPollingRef = null;
11
+ #timerWaitingRef = null;
12
+ #count = 1;
13
+ #accessKey;
14
+ /**
15
+ * Constructs a new instance of the Measurement class.
16
+ * @param {string} accessKey - The access key used for authentication.
17
+ */
18
+ constructor(accessKey) {
19
+ this.#accessKey = accessKey;
20
+ }
21
+ /**
22
+ * Retrieves the measurement status for a given scan ID.
23
+ * @param {string} scanId - The ID of the scan.
24
+ * @returns {Promise} - The axios response promise.
25
+ * @throws {Error} - If the required parameter is missing.
26
+ */
27
+ getMeasurementStatus(scanId) {
28
+ if (checkParameters(scanId) === false) {
29
+ throw new Error(REQUIRED_MESSAGE);
30
+ }
31
+ const url = `${APP_AUTH_BASE_URL}/measurements?scanId=${scanId}`;
32
+ return axios.get(url, {
33
+ headers: { "X-Api-Key": this.#accessKey },
34
+ });
35
+ }
36
+ /**
37
+ * Retrieves the try-on measurements for a given scan ID, shop domain, and product name.
38
+ * @param {Object} params - The parameters for the try-on measurements.
39
+ * @param {string} params.scanId - The ID of the scan.
40
+ * @param {string} params.shopDomain - The shop domain.
41
+ * @param {string} params.productName - The product name.
42
+ * @returns {Promise} - The axios response promise.
43
+ * @throws {Error} - If the required parameters are missing.
44
+ */
45
+ getTryOnMeasurements({ scanId, shopDomain, productName }) {
46
+ if (checkParameters(scanId, shopDomain, productName) === false) {
47
+ throw new Error(REQUIRED_MESSAGE);
48
+ }
49
+ const tryOnUrl = `${APP_AUTH_BASE_URL}${API_ENDPOINTS.TRY_ON_SCAN}/${scanId}/shop/${shopDomain}/product/${productName}`;
50
+ return axios.get(tryOnUrl, { headers: { "X-Api-Key": this.#accessKey } });
51
+ }
52
+ /**
53
+ * Handles the try-on WebSocket connection.
54
+ * @param {Object} params - The parameters for the WebSocket connection.
55
+ * @param {string} params.shopDomain - The shop domain.
56
+ * @param {string} params.scanId - The ID of the scan.
57
+ * @param {string} params.productName - The product name.
58
+ * @param {function} [params.onError] - Optional. Callback function to handle errors.
59
+ * @param {function} [params.onSuccess] - Optional. Callback function to handle successful messages.
60
+ * @param {function} [params.onClose] - Optional. Callback function to handle WebSocket close event.
61
+ * @param {function} [params.onOpen] - Optional. Callback function to handle WebSocket open event.
62
+ */
63
+ handleTryOnSocket({ shopDomain, scanId, productName, onError, onSuccess, onClose, onOpen }) {
64
+ if (checkParameters(shopDomain, scanId, productName) === false) {
65
+ throw new Error(REQUIRED_MESSAGE);
66
+ }
67
+ this.#tryOnSocketRef?.close();
68
+ const url = `${APP_TRY_ON_WEBSOCKET_URL}/develop?store_url=${shopDomain}&product_name=${productName}&scan_id=${scanId}`;
69
+ this.#tryOnSocketRef = new WebSocket(url);
70
+ this.#tryOnSocketRef.onopen = () => {
71
+ onOpen?.();
72
+ };
73
+ this.#tryOnSocketRef.onmessage = (event) => {
74
+ const data = JSON.parse(event.data);
75
+ if (data?.tryOnProcessStatus === "available") {
76
+ onSuccess?.(data);
77
+ }
78
+ else {
79
+ onError?.({ message: "failed to get image urls" });
80
+ }
81
+ };
82
+ this.#tryOnSocketRef.onclose = () => {
83
+ onClose?.();
84
+ };
85
+ this.#tryOnSocketRef.onerror = (event) => {
86
+ onError?.(event);
87
+ };
88
+ }
89
+ /**
90
+ * Checks the measurement status and handles polling.
91
+ * @param {Object} params - The parameters for checking measurements.
92
+ * @param {string} params.scanId - The ID of the scan.
93
+ * @param {function} [params.onSuccess] - Optional. Callback function to handle successful status check.
94
+ * @param {function} [params.onError] - Optional. Callback function to handle errors.
95
+ * @private
96
+ */
97
+ async #getMeasurementsCheck({ scanId, onSuccess, onError }) {
98
+ try {
99
+ const res = await this.getMeasurementStatus(scanId);
100
+ if (res?.data && res?.data?.[0]?.isMeasured === true) {
101
+ onSuccess?.(res?.data);
102
+ clearInterval(this.#timerPollingRef);
103
+ }
104
+ else {
105
+ if (this.#count < 8) {
106
+ this.#count++;
107
+ this.#handlePolling({ scanId, onSuccess, onError });
108
+ }
109
+ else {
110
+ this.#count = 1;
111
+ clearInterval(this.#timerPollingRef);
112
+ onError?.({ scanStatus: "failed", message: "Scan not found", isMeasured: false });
113
+ }
114
+ }
115
+ }
116
+ catch (e) {
117
+ clearInterval(this.#timerPollingRef);
118
+ onError?.(e);
119
+ }
120
+ }
121
+ /**
122
+ * Handles polling for measurements.
123
+ * @param {Object} params - The parameters for polling.
124
+ * @param {string} params.scanId - The ID of the scan.
125
+ * @param {function} [params.onSuccess] - Optional. Callback function to handle successful polling.
126
+ * @param {function} [params.onError] - Optional. Callback function to handle errors.
127
+ * @private
128
+ */
129
+ #handlePolling({ scanId, onSuccess, onError }) {
130
+ clearInterval(this.#timerPollingRef);
131
+ this.#timerPollingRef = setTimeout(() => {
132
+ this.#getMeasurementsCheck({ scanId, onSuccess, onError });
133
+ }, this.#count * 5000);
134
+ }
135
+ /**
136
+ * Disconnects the measurement WebSocket and clears the timeout.
137
+ * @private
138
+ */
139
+ #disconnectSocket() {
140
+ this.#measurementSocketRef?.close();
141
+ clearTimeout(this.#timerWaitingRef);
142
+ }
143
+ /**
144
+ * Handles the timeout for the measurement WebSocket.
145
+ * @param {Object} params - The parameters for handling timeout.
146
+ * @param {string} params.scanId - The ID of the scan.
147
+ * @param {function} [params.onSuccess] - Optional. Callback function to handle successful timeout.
148
+ * @param {function} [params.onError] - Optional. Callback function to handle errors.
149
+ * @private
150
+ */
151
+ #handleTimeOut({ scanId, onSuccess, onError }) {
152
+ this.#count = 1;
153
+ this.#timerWaitingRef = setTimeout(() => {
154
+ this.#handlePolling({ scanId, onSuccess, onError });
155
+ this.#disconnectSocket();
156
+ }, 2 * 60000);
157
+ }
158
+ /**
159
+ * Handles the measurement WebSocket connection.
160
+ * @param {Object} params - The parameters for the WebSocket connection.
161
+ * @param {string} params.scanId - The ID of the scan.
162
+ * @param {function} [params.onError] - Optional. Callback function to handle errors.
163
+ * @param {function} [params.onSuccess] - Optional. Callback function to handle successful messages.
164
+ * @param {function} [params.onClose] - Optional. Callback function to handle WebSocket close event.
165
+ * @param {function} [params.onOpen] - Optional. Callback function to handle WebSocket open event.
166
+ */
167
+ handleMeasurementSocket({ scanId, onError, onSuccess, onClose, onOpen }) {
168
+ if (checkParameters(scanId) === false) {
169
+ throw new Error(REQUIRED_MESSAGE);
170
+ }
171
+ setTimeout(() => {
172
+ this.#disconnectSocket();
173
+ const url = `${APP_RECOMMENDATION_WEBSOCKET_URL}?scanId=${scanId}`;
174
+ this.#measurementSocketRef = new WebSocket(url);
175
+ this.#measurementSocketRef.onopen = () => {
176
+ onOpen?.();
177
+ this.#handleTimeOut({ scanId, onSuccess, onError });
178
+ };
179
+ this.#measurementSocketRef.onmessage = (event) => {
180
+ const data = JSON.parse(event.data);
181
+ if (data?.code === 200 && data?.scanStatus === "success") {
182
+ onSuccess?.(data);
183
+ }
184
+ else {
185
+ onError?.(data);
186
+ }
187
+ clearTimeout(this.#timerWaitingRef);
188
+ };
189
+ this.#measurementSocketRef.onclose = () => {
190
+ onClose?.();
191
+ };
192
+ this.#measurementSocketRef.onerror = (event) => {
193
+ onError?.(event);
194
+ };
195
+ }, 5000);
196
+ }
197
+ }
198
+ export default Measurement;
@@ -0,0 +1,72 @@
1
+ import { io } from "socket.io-client";
2
+ import { APP_POSE_DETECTION_WEbSOCKET_URL } from "./constants.js";
3
+ /**
4
+ * Class representing pose detection functionality.
5
+ */
6
+ class PoseDetection {
7
+ #socketRef = null;
8
+ #accessKey;
9
+ /**
10
+ * Constructs a new instance of the PoseDetection class.
11
+ * @param {string} accessKey - The access key used for authentication.
12
+ */
13
+ constructor(accessKey) {
14
+ this.#accessKey = accessKey;
15
+ }
16
+ /**
17
+ * Connects to the pose detection WebSocket server.
18
+ * @returns {Promise<string>} - A promise that resolves with the socket ID on successful connection.
19
+ */
20
+ connect() {
21
+ return new Promise((resolve, reject) => {
22
+ this.#socketRef = io.connect(APP_POSE_DETECTION_WEbSOCKET_URL);
23
+ this.#socketRef?.on("connect", () => {
24
+ resolve(this.#socketRef.id);
25
+ });
26
+ this.#socketRef?.on("connect_error", (err) => reject(err));
27
+ });
28
+ }
29
+ /**
30
+ * Emits a video frame to the pose detection server.
31
+ * @param {Object} params - The parameters for emitting the video frame.
32
+ * @param {string} params.image - The image data.
33
+ * @param {string} params.scanId - The unique scan ID.
34
+ * @throws {Error} - If the socket is not connected.
35
+ */
36
+ videoEmit({ image, scanId }) {
37
+ if (!this.#socketRef) {
38
+ throw new Error("Socket is not connected");
39
+ }
40
+ this.#socketRef.emit("video", {
41
+ image,
42
+ user_unique_key: scanId,
43
+ });
44
+ }
45
+ /**
46
+ * Disconnects from the pose detection WebSocket server.
47
+ */
48
+ disconnect() {
49
+ this.#socketRef?.disconnect?.();
50
+ }
51
+ /**
52
+ * Registers a callback function to handle pose status updates.
53
+ * @param {function} callBack - The callback function to handle pose status updates.
54
+ * @throws {Error} - If the socket is not connected.
55
+ */
56
+ poseStatus(callBack) {
57
+ if (!this.#socketRef) {
58
+ throw new Error("Socket is not connected");
59
+ }
60
+ this.#socketRef.on("pose_status", (data) => {
61
+ callBack?.(data);
62
+ });
63
+ }
64
+ /**
65
+ * Checks if the socket is connected.
66
+ * @returns {boolean} - True if the socket is connected, false otherwise.
67
+ */
68
+ connected() {
69
+ return !!this.#socketRef?.connected;
70
+ }
71
+ }
72
+ export default PoseDetection;