diginext-utils 0.0.1

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/src/Camera.js ADDED
@@ -0,0 +1,412 @@
1
+ import gsap from "gsap";
2
+
3
+ // check for device orientation support
4
+ var DEVICE_ORIENTATION = {
5
+ VERTICAL: "vertical",
6
+ HORIZONTAL: "horizontal",
7
+ };
8
+ var deviceOrientation = DEVICE_ORIENTATION.VERTICAL;
9
+
10
+ var video;
11
+
12
+ /**
13
+ * @type {AppWebcam}
14
+ */
15
+ var webcam;
16
+ var isWebcamSupport = false;
17
+
18
+ // var onSetupComplete;
19
+
20
+ function requestWebcam({ container, onRejected, onReady }) {
21
+ // options = options || {};
22
+
23
+ var video = document.createElement("video");
24
+ video.style.position = "absolute";
25
+ video.style.top = 0;
26
+ video.style.left = 0;
27
+ video.style.width = "100%";
28
+ video.style.height = "100%";
29
+ container.append(video);
30
+
31
+ gsap.set(video, { opacity: 1 });
32
+
33
+ // $(video).css("z-index", "-2");
34
+ // $(video).css("position", "absolute");
35
+ // $(video).css("top", "0px");
36
+ // $(video).css("left", "0px");
37
+
38
+ stopWebcam();
39
+
40
+ webcam = new AppWebcam(video);
41
+ webcam.onReady = function (e) {
42
+ setupApp();
43
+
44
+ isWebcamSupport = true;
45
+
46
+ if (onReady) onReady(e);
47
+ };
48
+
49
+ webcam.onRejected = function (e) {
50
+ setupApp();
51
+
52
+ isWebcamSupport = false;
53
+
54
+ // if (typeof gaTrackingClick != "undefined") gaTrackingClick('request_permission', 'reject_camera');
55
+
56
+ if (onRejected) onRejected(e);
57
+ };
58
+
59
+ return webcam;
60
+ }
61
+
62
+ function setupApp() {
63
+ var _isAllow = false;
64
+
65
+ if (typeof webcam != "undefined") {
66
+ if (webcam.isAllowed) {
67
+ gsap.to(video, { duration: 2, opacity: 1 });
68
+ _isAllow = true;
69
+ }
70
+ }
71
+ }
72
+
73
+ function stopWebcam() {
74
+ if (webcam) webcam.remove();
75
+ }
76
+
77
+ /**
78
+ * @param {HTMLVideoElement} videoElement
79
+ */
80
+ function AppWebcam(videoElement) {
81
+ // define scope
82
+ var scope = this;
83
+
84
+ // private vars
85
+ /**
86
+ * @type {MediaDeviceInfo[]}
87
+ */
88
+ var inputCameras = [];
89
+
90
+ /**
91
+ * @type {MediaStreamConstraints}
92
+ */
93
+ var requestedMediaConstraints = {
94
+ video: {
95
+ // width: 640,
96
+ // height: 480,
97
+ facingMode: { exact: "environment" },
98
+ // facingMode: 'environment'
99
+ },
100
+ audio: false,
101
+ };
102
+
103
+ /**
104
+ * @type {MediaStream}
105
+ */
106
+ var stream;
107
+ var isAllowed = false;
108
+ /**
109
+ * @type {HTMLVideoElement}
110
+ */
111
+ var video;
112
+ var canvas = document.createElement("canvas");
113
+ canvas.setAttribute("id", "AppWebcam" + new Date().getTime());
114
+
115
+ // var requestWidth = deviceOrientation == DEVICE_ORIENTATION.VERTICAL
116
+ // ? 360
117
+ // : 640;
118
+ // var requestHeight = deviceOrientation == DEVICE_ORIENTATION.VERTICAL
119
+ // ? 640
120
+ // : 360;
121
+
122
+ this.currentCamera = null;
123
+
124
+ // initialise
125
+ init();
126
+
127
+ // constructor
128
+ function init() {
129
+ if (!videoElement) {
130
+ video = document.createElement("video");
131
+ } else {
132
+ video = videoElement;
133
+ }
134
+ //alert("!");
135
+
136
+ // canvasElement = document.getElementById ('canvas');
137
+ // canvasElement.width = window.innerWidth - 50;
138
+ // canvasElement.height = canvasElement.width;
139
+ // canvas = canvasElement.getContext ('2d');
140
+ // loadingMessage = document.getElementById ('loadingMessage');
141
+
142
+ // Older browsers might not implement mediaDevices at all, so we set an empty object first
143
+ if (navigator.mediaDevices === undefined) {
144
+ navigator.mediaDevices = {};
145
+ }
146
+
147
+ // Some browsers partially implement mediaDevices. We can't just assign an object
148
+ // with getUserMedia as it would overwrite existing properties.
149
+ // Here, we will just add the getUserMedia property if it's missing.
150
+ if (navigator.mediaDevices.getUserMedia === undefined) {
151
+ navigator.mediaDevices.getUserMedia = function (constraints) {
152
+ // First get ahold of the legacy getUserMedia, if present
153
+ var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
154
+
155
+ // Some browsers just don't implement it - return a rejected promise with an error
156
+ // to keep a consistent interface
157
+ if (!getUserMedia) {
158
+ return Promise.reject(new Error("getUserMedia is not implemented in this browser"));
159
+ }
160
+
161
+ // Otherwise, wrap the call to the old navigator.getUserMedia with a Promise
162
+ return new Promise(function (resolve, reject) {
163
+ getUserMedia.call(navigator, constraints, resolve, reject);
164
+ });
165
+ };
166
+ }
167
+
168
+ // start requesting media permissions:
169
+
170
+ console.log("[Camera.js] Requesting:", requestedMediaConstraints);
171
+
172
+ if (navigator.mediaDevices.enumerateDevices === undefined) {
173
+ setTimeout(function () {
174
+ handleError({ name: "Error", message: "NotSupported" });
175
+ }, 50);
176
+ } else {
177
+ navigator.mediaDevices.enumerateDevices().then(parseDevices).catch(handleError);
178
+ }
179
+
180
+ // navigator.mediaDevices.getUserMedia(requestedMediaConstraints).then(() => {
181
+ // if (typeof navigator.mediaDevices.enumerateDevices == "undefined") {
182
+ // setTimeout(function () {
183
+ // handleError({ name: 'Error', message: 'NotSupported' });
184
+ // }, 50);
185
+ // } else {
186
+ // navigator.mediaDevices
187
+ // .enumerateDevices()
188
+ // .then(parseDevices)
189
+ // .catch(handleError);
190
+ // }
191
+ // }).catch(handleError);
192
+ }
193
+
194
+ /**
195
+ * @param {MediaDeviceInfo[]} devices
196
+ */
197
+ function parseDevices(devices) {
198
+ inputCameras = [];
199
+ var backCameras = [];
200
+
201
+ devices.forEach(function (device) {
202
+ if (device.kind == "videoinput" && typeof device.deviceId != "undefined" && device.deviceId != "") {
203
+ inputCameras.push(device);
204
+ }
205
+ });
206
+ // //alert (JSON.stringify (devices));
207
+ console.log("[Camera.js] inputCameras:", inputCameras);
208
+
209
+ if (inputCameras.length > 0) {
210
+ var cams = "";
211
+ var backCamera;
212
+
213
+ inputCameras.map((cam, index) => {
214
+ cams += `[${cam.deviceId}] ${cam.kind} | ${cam.label}\n`;
215
+ // console.log(cam);
216
+ var label = cam.label.toLowerCase();
217
+ if (label.indexOf("back") > -1 || label.indexOf("facetime") > -1) {
218
+ backCamera = cam;
219
+ backCameras.push(backCamera);
220
+ }
221
+ });
222
+
223
+ if (backCameras.length > 1) {
224
+ backCamera = backCameras[backCameras.length - 1];
225
+ }
226
+
227
+ console.log(`[Camera.js] All input sources:`, cams);
228
+ console.log(`[Camera.js] This device has ${backCameras.length} back camera${backCameras.length > 1 ? "s" : ""}.`);
229
+ console.log("[Camera.js] backCameras:", JSON.stringify(backCameras));
230
+
231
+ scope.currentCamera = backCamera;
232
+
233
+ if (scope.onGotDevices) {
234
+ scope.onGotDevices(devices);
235
+ }
236
+
237
+ // Lấy stream của camera sau
238
+ // (Lấy cái cuối cùng trong danh sách trước, thường sẽ là camera chính trên Android)
239
+ getStreamOfCameraId(backCamera.deviceId)
240
+ .then(onStreamReceived)
241
+ .catch((e) => {
242
+ if (backCameras.length > 1) {
243
+ // nếu thiết bị có nhiều hơn 1 camera sau -> thử lấy camera khác
244
+ backCamera = backCameras[backCameras.length - 2];
245
+ getStreamOfCameraId(backCamera.deviceId).then(onStreamReceived).catch(handleError);
246
+ } else if (backCameras.length > 2) {
247
+ // nếu thiết bị có nhiều hơn 2 camera sau -> thử lấy camera khác nữa
248
+ backCamera = backCameras[backCameras.length - 3];
249
+ getStreamOfCameraId(backCamera.deviceId).then(onStreamReceived).catch(handleError);
250
+ } else {
251
+ // nếu thiết bị đéo có camera sau...
252
+ handleError(e);
253
+ }
254
+ });
255
+ } else {
256
+ navigator.mediaDevices.getUserMedia(requestedMediaConstraints).then(onStreamReceived).catch(handleError);
257
+
258
+ if (scope.onGotDevicesFailed) scope.onGotDevicesFailed();
259
+ }
260
+ }
261
+
262
+ function getStreamOfCameraId(id) {
263
+ var constraints = {
264
+ video: { deviceId: { exact: id } },
265
+ audio: false,
266
+ };
267
+
268
+ return new Promise((resolve, reject) => {
269
+ navigator.mediaDevices.getUserMedia(constraints).then(resolve).catch(reject);
270
+ });
271
+ }
272
+
273
+ /**
274
+ * @param {MediaStream} stream
275
+ */
276
+ function onStreamReceived(stream) {
277
+ if (inputCameras.length == 0) {
278
+ console.log("[Camera.js] Not found any back cameras, request again?");
279
+ navigator.mediaDevices.enumerateDevices().then(parseDevices).catch(handleError);
280
+ return;
281
+ }
282
+
283
+ isAllowed = true;
284
+
285
+ playWebcamVideo(stream);
286
+ }
287
+
288
+ /**
289
+ * @param {MediaStream} _stream
290
+ */
291
+ function playWebcamVideo(_stream) {
292
+ stream = _stream;
293
+
294
+ if ("srcObject" in video) {
295
+ // //alert ('GOT STREAM VIDEO OBJECT');
296
+ video.srcObject = _stream;
297
+ } else {
298
+ // //alert ('GOT STREAM VIDEO SOURCE URL');
299
+ // Avoid using this in new browsers, as it is going away.
300
+ video.src = window.URL.createObjectURL(_stream);
301
+ }
302
+
303
+ // required to tell iOS safari we don't want fullscreen
304
+ video.setAttribute("playsinline", true);
305
+ video.setAttribute("muted", true);
306
+ video.setAttribute("autoplay", true);
307
+ video.muted = true;
308
+ video.autoplay = true;
309
+ video.style.objectFit = "cover";
310
+ video.play();
311
+
312
+ // auto play
313
+ video.addEventListener("canplay", function (e) {
314
+ // //alert ('CAN PLAY');
315
+ });
316
+
317
+ video.addEventListener("canplaythrough", function (e) {
318
+ // //alert ('CAN PLAY THROUGH');
319
+ });
320
+
321
+ video.addEventListener("error", (e) => console.log("[Camera.js] <video> error:", e));
322
+
323
+ video.addEventListener("stalled", function (e) {
324
+ // //alert ('CANNOT GET METADATA');
325
+ isAllowed = false;
326
+ console.log("[Camera.js] <video> stalled:", e);
327
+ if (scope.onRejected != null) scope.onRejected(e);
328
+ });
329
+
330
+ video.addEventListener("loadedmetadata", function (e) {
331
+ canvas.width = video.videoWidth;
332
+ canvas.height = video.videoHeight;
333
+
334
+ canvas.style.width = window.outerWidth + "px";
335
+ canvas.style.height = window.outerHeight + "px";
336
+
337
+ if (scope.currentCamera.label.toLowerCase().indexOf("facetime") > -1) {
338
+ video.style.transform = "scaleX(-1)";
339
+ video.style.webkitTransform = "scaleX(-1)";
340
+ }
341
+
342
+ video.play();
343
+
344
+ if (scope.onReady) scope.onReady(video);
345
+ });
346
+ }
347
+
348
+ function handleError(err) {
349
+ console.error(err);
350
+ var errMsg = "[Camera.js] " + err.name + ": " + err.message;
351
+ console.error(errMsg);
352
+
353
+ isAllowed = false;
354
+
355
+ if (scope.onRejected != null) scope.onRejected(err);
356
+ }
357
+
358
+ function drawVideo() {
359
+ var ctx = canvas.getContext("2d");
360
+
361
+ canvas.width = video.videoWidth;
362
+ canvas.height = video.videoHeight;
363
+
364
+ ctx.drawImage(video, 0, 0, video.videoWidth, video.videoHeight);
365
+ }
366
+
367
+ function captureAsBase64(callback) {
368
+ console.log(`[Camera.js] Base64 captured -> ${video.videoWidth}x${video.videoHeight}`);
369
+
370
+ drawVideo();
371
+
372
+ TweenMax.delayedCall(0.2, function () {
373
+ var screenshot = canvas.toDataURL("image/png");
374
+ if (callback) callback(screenshot);
375
+ });
376
+ }
377
+
378
+ function captureAsImageData() {
379
+ drawVideo();
380
+
381
+ var ctx = canvas.getContext("2d");
382
+ return ctx.getImageData(0, 0, video.videoWidth, video.videoHeight);
383
+ }
384
+
385
+ function dispose() {}
386
+
387
+ function enable() {}
388
+
389
+ function disable() {}
390
+
391
+ function remove() {
392
+ if (stream) stream.getTracks().forEach((track) => track.stop());
393
+ }
394
+
395
+ // exports
396
+ this.enable = enable;
397
+ this.disable = disable;
398
+ this.video = video;
399
+ this.inputCameras = inputCameras;
400
+ this.canvas = canvas;
401
+ this.captureAsBase64 = captureAsBase64;
402
+ this.captureAsImageData = captureAsImageData;
403
+ this.onReady = null;
404
+ this.onRejected = null;
405
+ this.onGotDevices = null;
406
+ this.onGotDevicesFailed = null;
407
+ this.init = init;
408
+ this.remove = remove;
409
+ this.stream = stream;
410
+ }
411
+
412
+ export { video, webcam, isWebcamSupport, requestWebcam, stopWebcam };
package/src/Checker.js ADDED
@@ -0,0 +1,24 @@
1
+ const isJSON = (content) => {
2
+ if (typeof content == "object") {
3
+ try {
4
+ content = JSON.stringify(content);
5
+ } catch (err) {
6
+ return false;
7
+ }
8
+ }
9
+
10
+ if (typeof content == "string") {
11
+ try {
12
+ content = JSON.parse(content);
13
+ } catch (err) {
14
+ return false;
15
+ }
16
+ }
17
+
18
+ if (typeof content != "object") {
19
+ return false;
20
+ }
21
+ return true;
22
+ };
23
+
24
+ export { isJSON };
package/src/Color.js ADDED
@@ -0,0 +1,81 @@
1
+ class Color {
2
+ static random = (hex = false) => {
3
+ return (hex ? "#" : "") + Math.floor(Math.random() * 16777215).toString(16);
4
+ };
5
+ // This function (pSBC) will take a HEX or RGB web color.
6
+ // pSBC can shade it darker or lighter, or blend it with a second color, and can also pass it right thru but convert from Hex to RGB (Hex2RGB) or RGB to Hex (RGB2Hex).
7
+ // All without you even knowing what color format you are using.
8
+ // Version 4.0 (pref: https://github.com/PimpTrizkit/PJs/wiki/12.-Shade,-Blend-and-Convert-a-Web-Color-(pSBC.js));
9
+ static pSBC = (p, c0, c1, l) => {
10
+ let r,
11
+ g,
12
+ b,
13
+ P,
14
+ f,
15
+ t,
16
+ h,
17
+ i = parseInt,
18
+ m = Math.round,
19
+ a = typeof c1 == "string";
20
+ if (typeof p != "number" || p < -1 || p > 1 || typeof c0 != "string" || (c0[0] != "r" && c0[0] != "#") || (c1 && !a)) return null;
21
+ if (!this.pSBCr)
22
+ this.pSBCr = (d) => {
23
+ let n = d.length,
24
+ x = {};
25
+ if (n > 9) {
26
+ ([r, g, b, a] = d = d.split(",")), (n = d.length);
27
+ if (n < 3 || n > 4) return null;
28
+ (x.r = i(r[3] == "a" ? r.slice(5) : r.slice(4))), (x.g = i(g)), (x.b = i(b)), (x.a = a ? parseFloat(a) : -1);
29
+ } else {
30
+ if (n == 8 || n == 6 || n < 4) return null;
31
+ if (n < 6) d = "#" + d[1] + d[1] + d[2] + d[2] + d[3] + d[3] + (n > 4 ? d[4] + d[4] : "");
32
+ d = i(d.slice(1), 16);
33
+ if (n == 9 || n == 5)
34
+ (x.r = (d >> 24) & 255), (x.g = (d >> 16) & 255), (x.b = (d >> 8) & 255), (x.a = m((d & 255) / 0.255) / 1000);
35
+ else (x.r = d >> 16), (x.g = (d >> 8) & 255), (x.b = d & 255), (x.a = -1);
36
+ }
37
+ return x;
38
+ };
39
+ (h = c0.length > 9),
40
+ (h = a ? (c1.length > 9 ? true : c1 == "c" ? !h : false) : h),
41
+ (f = this.pSBCr(c0)),
42
+ (P = p < 0),
43
+ (t = c1 && c1 != "c" ? this.pSBCr(c1) : P ? { r: 0, g: 0, b: 0, a: -1 } : { r: 255, g: 255, b: 255, a: -1 }),
44
+ (p = P ? p * -1 : p),
45
+ (P = 1 - p);
46
+ if (!f || !t) return null;
47
+ if (l) (r = m(P * f.r + p * t.r)), (g = m(P * f.g + p * t.g)), (b = m(P * f.b + p * t.b));
48
+ else
49
+ (r = m((P * f.r ** 2 + p * t.r ** 2) ** 0.5)),
50
+ (g = m((P * f.g ** 2 + p * t.g ** 2) ** 0.5)),
51
+ (b = m((P * f.b ** 2 + p * t.b ** 2) ** 0.5));
52
+ (a = f.a), (t = t.a), (f = a >= 0 || t >= 0), (a = f ? (a < 0 ? t : t < 0 ? a : a * P + t * p) : 0);
53
+ if (h) return "rgb" + (f ? "a(" : "(") + r + "," + g + "," + b + (f ? "," + m(a * 1000) / 1000 : "") + ")";
54
+ else return "#" + (4294967296 + r * 16777216 + g * 65536 + b * 256 + (f ? m(a * 255) : 0)).toString(16).slice(1, f ? undefined : -2);
55
+ };
56
+
57
+ static hexToRgb(hex) {
58
+ var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
59
+ return result
60
+ ? {
61
+ r: parseInt(result[1], 16),
62
+ g: parseInt(result[2], 16),
63
+ b: parseInt(result[3], 16),
64
+ }
65
+ : null;
66
+ }
67
+
68
+ static hexDarken(hex, amount) {
69
+ return Color.pSBC(-amount, hex);
70
+ }
71
+
72
+ static hexLighten(hex, amount) {
73
+ return Color.pSBC(amount, hex);
74
+ }
75
+
76
+ static RGBToHex(rgb) {
77
+ return Color.pSBC(0, rgb, "c", true);
78
+ }
79
+ }
80
+
81
+ export default Color;
package/src/Console.js ADDED
@@ -0,0 +1,18 @@
1
+ import { cloneDeep } from "lodash";
2
+ var _console = cloneDeep(console);
3
+
4
+ export default {
5
+ enable(params) {
6
+ return _console;
7
+ },
8
+
9
+ disable() {
10
+ for (var i in console) {
11
+ console[i] = function () {};
12
+ }
13
+ },
14
+
15
+ showCredit() {
16
+ console.log("Developed by Digitop | https://www.wearetopgroup.com/?utm_src=console");
17
+ },
18
+ };
package/src/Device.js ADDED
@@ -0,0 +1,56 @@
1
+ var _requestedDeviceOrientation = false;
2
+ var _isDeviceOrientationSupport = false;
3
+
4
+ export default {
5
+ get isPotrait() {
6
+ if (window && !window.orientation) return window.matchMedia("(orientation: portrait)").matches;
7
+ return !((window && window.orientation === 90) || (window && window.orientation === -90));
8
+ },
9
+
10
+ get isLandscape() {
11
+ return !this.isPotrait;
12
+ },
13
+
14
+ get isDeviceOrientationSupport() {
15
+ // if (!_requestedDeviceOrientation) {
16
+ // await this.requestDeviceOrientationData()
17
+ // }
18
+ return _isDeviceOrientationSupport;
19
+ },
20
+
21
+ async requestDeviceOrientationData() {
22
+ if (!window) {
23
+ // not supported
24
+ console.warn("`window` not found");
25
+ _isDeviceOrientationSupport = false;
26
+ return;
27
+ }
28
+
29
+ // console.log(window)
30
+ if (window.DeviceOrientationEvent !== undefined && typeof window.DeviceOrientationEvent.requestPermission === "function") {
31
+ console.log("This browser can be requested for `DeviceOrientationEvent` permission");
32
+ try {
33
+ const response = await window.DeviceOrientationEvent.requestPermission();
34
+ // console.log(response)
35
+ if (response == "granted") {
36
+ console.log("`DeviceOrientationEvent` permission -> granted!");
37
+ _isDeviceOrientationSupport = true;
38
+ } else {
39
+ // rejected
40
+ console.log("`DeviceOrientationEvent` permission ->", response);
41
+ _isDeviceOrientationSupport = false;
42
+ }
43
+ } catch (error) {
44
+ // not supported
45
+ console.log(error);
46
+ _isDeviceOrientationSupport = false;
47
+ }
48
+ } else {
49
+ // not supported
50
+ console.warn("`window.DeviceOrientationEvent` not found");
51
+ _isDeviceOrientationSupport = false;
52
+ }
53
+
54
+ return _isDeviceOrientationSupport;
55
+ },
56
+ };
@@ -0,0 +1,58 @@
1
+ export default class EventDispatcher {
2
+ constructor() {}
3
+
4
+ addEventListener(type, listener) {
5
+ if (this._listeners === undefined) this._listeners = {};
6
+
7
+ const listeners = this._listeners;
8
+
9
+ if (listeners[type] === undefined) {
10
+ listeners[type] = [];
11
+ }
12
+
13
+ if (listeners[type].indexOf(listener) === -1) {
14
+ listeners[type].push(listener);
15
+ }
16
+ }
17
+
18
+ hasEventListener(type, listener) {
19
+ if (this._listeners === undefined) return false;
20
+
21
+ const listeners = this._listeners;
22
+
23
+ return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1;
24
+ }
25
+
26
+ removeEventListener(type, listener) {
27
+ if (this._listeners === undefined) return;
28
+
29
+ const listeners = this._listeners;
30
+ const listenerArray = listeners[type];
31
+
32
+ if (listenerArray !== undefined) {
33
+ const index = listenerArray.indexOf(listener);
34
+
35
+ if (index !== -1) {
36
+ listenerArray.splice(index, 1);
37
+ }
38
+ }
39
+ }
40
+
41
+ dispatchEvent(event) {
42
+ if (this._listeners === undefined) return;
43
+
44
+ const listeners = this._listeners;
45
+ const listenerArray = listeners[event.type];
46
+
47
+ if (listenerArray !== undefined) {
48
+ event.target = this;
49
+
50
+ // Make a copy, in case listeners are removed while iterating.
51
+ const array = listenerArray.slice(0);
52
+
53
+ for (let i = 0, l = array.length; i < l; i++) {
54
+ array[i].call(this, event);
55
+ }
56
+ }
57
+ }
58
+ }
@@ -0,0 +1,59 @@
1
+ var logFile = "[FileUpload.js] ";
2
+
3
+ export default {
4
+ uploadBlob({ blob, url, params, onComplete, onError }) {
5
+ var formData = new FormData();
6
+ formData.append("upload", blob, "img_" + +new Date() + ".jpg");
7
+
8
+ if (params) {
9
+ Object.keys(params).forEach((key) => {
10
+ var val = obj[key];
11
+ formData.append(key, val);
12
+ });
13
+ }
14
+
15
+ var request = new XMLHttpRequest();
16
+ request.open("POST", url);
17
+ request.send(formData);
18
+
19
+ request.onreadystatechange = function () {
20
+ if (this.readyState == 4) {
21
+ // Typical action to be performed when the document is ready:
22
+ if (this.status == 200) {
23
+ // var response = JSON.parse(request.response) || "";
24
+ var response = {};
25
+ try {
26
+ response = JSON.parse(request.response) || "";
27
+ } catch (error) {
28
+ console.error(logFile, "Can't part JSON of the response");
29
+ }
30
+ var statusOfSafety = response.status || 0;
31
+
32
+ if (statusOfSafety == 1) {
33
+ console.log(logFile, "request: ", request);
34
+ var data = response.data || {};
35
+ console.log(logFile, data);
36
+
37
+ var url = data["url"];
38
+
39
+ if (onComplete) onComplete(url);
40
+ } else {
41
+ var errMsg = "Ảnh có nội dung không phù hợp.";
42
+ console.error(logFile, errMsg);
43
+ if (onError) onError(errMsg);
44
+ }
45
+ } else {
46
+ var errMsg = "Upload ảnh không thành công!";
47
+ console.error(logFile, errMsg);
48
+ if (onError) onError(errMsg);
49
+ }
50
+ }
51
+ };
52
+
53
+ request.onerror = function (res) {
54
+ var errMsg = "Upload ảnh không thành công!";
55
+ console.error(logFile, errMsg, "=>", res);
56
+ if (onError) onError(errMsg);
57
+ };
58
+ },
59
+ };