diginext-utils 2.0.6 → 2.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (155) hide show
  1. package/dist/Checker.d.ts +5 -0
  2. package/dist/Checker.js +30 -0
  3. package/dist/Checker.js.map +1 -0
  4. package/dist/EventDispatcher.d.ts +11 -0
  5. package/dist/EventDispatcher.js +51 -0
  6. package/dist/EventDispatcher.js.map +1 -0
  7. package/dist/FileUpload.d.ts +11 -0
  8. package/dist/FileUpload.js +64 -0
  9. package/dist/FileUpload.js.map +1 -0
  10. package/dist/Slug.d.ts +4 -0
  11. package/dist/Slug.js +332 -0
  12. package/dist/Slug.js.map +1 -0
  13. package/dist/Timer.d.ts +3 -0
  14. package/dist/Timer.js +9 -0
  15. package/dist/Timer.js.map +1 -0
  16. package/dist/Validation.d.ts +4 -0
  17. package/dist/Validation.js +39 -0
  18. package/dist/Validation.js.map +1 -0
  19. package/dist/array.d.ts +91 -0
  20. package/dist/array.js +275 -0
  21. package/dist/array.js.map +1 -0
  22. package/dist/color.d.ts +10 -0
  23. package/dist/color.js +86 -0
  24. package/dist/color.js.map +1 -0
  25. package/dist/console/enableConsole.d.ts +1 -3
  26. package/dist/console/enableConsole.js +10 -14
  27. package/dist/console/enableConsole.js.map +1 -0
  28. package/dist/console/index.d.ts +3 -5
  29. package/dist/console/index.js +12 -16
  30. package/dist/console/index.js.map +1 -0
  31. package/dist/device/browser.d.ts +5 -7
  32. package/dist/device/browser.js +32 -34
  33. package/dist/device/browser.js.map +1 -0
  34. package/dist/device/camera.d.ts +7 -16
  35. package/dist/device/camera.js +166 -157
  36. package/dist/device/camera.js.map +1 -0
  37. package/dist/device.d.ts +4 -0
  38. package/dist/device.js +217 -0
  39. package/dist/device.js.map +1 -0
  40. package/dist/file/createDir.d.ts +1 -2
  41. package/dist/file/createDir.js +13 -20
  42. package/dist/file/createDir.js.map +1 -0
  43. package/dist/file/fileMove.d.ts +1 -3
  44. package/dist/file/fileMove.js +29 -35
  45. package/dist/file/fileMove.js.map +1 -0
  46. package/dist/file/findFilesByExt.d.ts +0 -1
  47. package/dist/file/findFilesByExt.js +41 -46
  48. package/dist/file/findFilesByExt.js.map +1 -0
  49. package/dist/index.d.ts +16 -0
  50. package/dist/index.js +33 -0
  51. package/dist/index.js.map +1 -0
  52. package/dist/math/diffDate.d.ts +1 -3
  53. package/dist/math/diffDate.js +10 -9
  54. package/dist/math/diffDate.js.map +1 -0
  55. package/dist/math/index.d.ts +8 -10
  56. package/dist/math/index.js +92 -48
  57. package/dist/math/index.js.map +1 -0
  58. package/dist/math/positiveNumber.d.ts +1 -3
  59. package/dist/math/positiveNumber.js +13 -27
  60. package/dist/math/positiveNumber.js.map +1 -0
  61. package/dist/name/en.d.ts +1 -3
  62. package/dist/name/en.js +17 -12
  63. package/dist/name/en.js.map +1 -0
  64. package/dist/name/vi.d.ts +1 -3
  65. package/dist/name/vi.js +23 -34
  66. package/dist/name/vi.js.map +1 -0
  67. package/dist/object.d.ts +23 -0
  68. package/dist/object.js +57 -0
  69. package/dist/object.js.map +1 -0
  70. package/dist/permission/requestCamera.d.ts +2 -3
  71. package/dist/permission/requestCamera.js +37 -25
  72. package/dist/permission/requestCamera.js.map +1 -0
  73. package/dist/permission/requestDeviceOrientationControl.d.ts +0 -1
  74. package/dist/permission/requestDeviceOrientationControl.js +35 -174
  75. package/dist/permission/requestDeviceOrientationControl.js.map +1 -0
  76. package/dist/string/formatNumber.d.ts +1 -3
  77. package/dist/string/formatNumber.js +11 -27
  78. package/dist/string/formatNumber.js.map +1 -0
  79. package/dist/string/generatePassword.d.ts +1 -3
  80. package/dist/string/generatePassword.js +20 -26
  81. package/dist/string/generatePassword.js.map +1 -0
  82. package/dist/string/generateUUID.d.ts +1 -3
  83. package/dist/string/generateUUID.js +33 -13
  84. package/dist/string/generateUUID.js.map +1 -0
  85. package/dist/string/index.d.ts +8 -10
  86. package/dist/string/index.js +118 -96
  87. package/dist/string/index.js.map +1 -0
  88. package/dist/string/random.d.ts +6 -8
  89. package/dist/string/random.js +20 -23
  90. package/dist/string/random.js.map +1 -0
  91. package/dist/string/trimNull.d.ts +1 -3
  92. package/dist/string/trimNull.js +15 -19
  93. package/dist/string/trimNull.js.map +1 -0
  94. package/dist/string/url.d.ts +7 -14
  95. package/dist/string/url.js +92 -77
  96. package/dist/string/url.js.map +1 -0
  97. package/package.json +6 -8
  98. package/src/Checker.ts +27 -0
  99. package/src/EventDispatcher.ts +60 -0
  100. package/src/FileUpload.ts +65 -0
  101. package/src/Slug.ts +364 -0
  102. package/src/Timer.ts +5 -0
  103. package/src/Validation.ts +35 -0
  104. package/src/array.ts +261 -0
  105. package/src/color.ts +89 -0
  106. package/src/console/enableConsole.ts +6 -0
  107. package/src/console/index.ts +11 -0
  108. package/src/device/browser.ts +29 -0
  109. package/src/device/camera.ts +209 -0
  110. package/src/device.ts +223 -0
  111. package/src/file/createDir.ts +14 -0
  112. package/src/file/fileMove.ts +32 -0
  113. package/src/file/findFilesByExt.ts +39 -0
  114. package/src/index.ts +17 -0
  115. package/src/math/diffDate.ts +8 -0
  116. package/src/math/index.ts +88 -0
  117. package/src/math/positiveNumber.ts +10 -0
  118. package/src/name/en.ts +24 -0
  119. package/src/name/vi.ts +21 -0
  120. package/src/object.ts +49 -0
  121. package/src/permission/requestCamera.ts +43 -0
  122. package/src/permission/requestDeviceOrientationControl.ts +33 -0
  123. package/src/string/formatNumber.ts +10 -0
  124. package/src/string/generatePassword.ts +16 -0
  125. package/src/string/generateUUID.ts +35 -0
  126. package/src/string/index.ts +145 -0
  127. package/src/string/random.ts +20 -0
  128. package/src/string/trimNull.ts +11 -0
  129. package/src/string/url.ts +109 -0
  130. package/dist/esm/chunk-5HIQS7HE.js +0 -40
  131. package/dist/esm/chunk-EZUCZHGV.js +0 -9
  132. package/dist/esm/chunk-HDM7KM5F.js +0 -20
  133. package/dist/esm/chunk-LNLCKCWC.js +0 -17
  134. package/dist/esm/chunk-X3K4KC75.js +0 -26
  135. package/dist/esm/console/enableConsole.js +0 -9
  136. package/dist/esm/console/index.js +0 -15
  137. package/dist/esm/device/browser.js +0 -34
  138. package/dist/esm/device/camera.js +0 -137
  139. package/dist/esm/file/createDir.js +0 -13
  140. package/dist/esm/file/fileMove.js +0 -29
  141. package/dist/esm/file/findFilesByExt.js +0 -39
  142. package/dist/esm/math/diffDate.js +0 -10
  143. package/dist/esm/math/index.js +0 -2
  144. package/dist/esm/math/positiveNumber.js +0 -16
  145. package/dist/esm/name/en.js +0 -17
  146. package/dist/esm/name/vi.js +0 -31
  147. package/dist/esm/permission/requestCamera.js +0 -2
  148. package/dist/esm/permission/requestDeviceOrientationControl.js +0 -175
  149. package/dist/esm/string/formatNumber.js +0 -10
  150. package/dist/esm/string/generatePassword.js +0 -16
  151. package/dist/esm/string/generateUUID.js +0 -14
  152. package/dist/esm/string/index.js +0 -86
  153. package/dist/esm/string/random.js +0 -2
  154. package/dist/esm/string/trimNull.js +0 -14
  155. package/dist/esm/string/url.js +0 -69
package/src/array.ts ADDED
@@ -0,0 +1,261 @@
1
+ import { randInt } from "./math";
2
+
3
+ export const sumArray = (array: [], key: string) => {
4
+ if (!array) {
5
+ console.warn("ARRAY NOT EXITED !");
6
+ return 0;
7
+ }
8
+ if (key) return array.reduce((c, v) => c + v[key], 0);
9
+ else return array.reduce((c, v) => c + v, 0);
10
+ };
11
+
12
+ /**
13
+ *
14
+ * @param {Array} array
15
+ * @param {string} key
16
+ * @returns {Number}
17
+ */
18
+ export const averageArray = (array: [], key: string) => {
19
+ if (!array) {
20
+ console.warn("ARRAY NOT EXITED !");
21
+ return 0;
22
+ }
23
+ return sumArray(array, key) / array.length || 0;
24
+ };
25
+
26
+ /**
27
+ *
28
+ * @param {Array} array
29
+ * @param {string} key
30
+ * @returns {Number}
31
+ */
32
+ export const minArray = (array: [], key: string) => {
33
+ if (!array) {
34
+ console.warn("ARRAY NOT EXITED !");
35
+ return 0;
36
+ }
37
+ if (array.length > 0) {
38
+ if (key) return array.reduce((c, v) => (c < v[key] ? c : v[key]));
39
+ else return array.reduce((c, v) => (c < v ? c : v));
40
+ }
41
+ return 0;
42
+ };
43
+
44
+ /**
45
+ *
46
+ * @param {Array} array
47
+ * @param {string} key
48
+ * @returns {Number}
49
+ */
50
+ export const maxArray = (array: [], key: string) => {
51
+ if (!array) {
52
+ console.warn("ARRAY NOT EXITED !");
53
+ return 0;
54
+ }
55
+ if (array.length > 0) {
56
+ if (key) return array.reduce((c, v) => (c > v[key] ? c : v[key]));
57
+ else return array.reduce((c, v) => (c > v ? c : v));
58
+ }
59
+ return 0;
60
+ };
61
+
62
+ /**
63
+ *
64
+ * @param {Array} array
65
+ * @param {string} key
66
+ * @returns {Array}
67
+ */
68
+ export const sortElementByString = (array: any, key: string) => {
69
+ if (!Array.isArray(array)) return [];
70
+ if (key)
71
+ return array.sort((x, y) => {
72
+ var a = x[key].toUpperCase(),
73
+ b = y[key].toUpperCase();
74
+ return a == b ? 0 : a > b ? 1 : -1;
75
+ });
76
+ console.log("NO KEY");
77
+ };
78
+
79
+ /**
80
+ *
81
+ * @param {Array} array
82
+ * @param {string} key
83
+ * @returns {Array}
84
+ */
85
+ export const sortElementByNumber = (array: any, key: string) => {
86
+ if (!Array.isArray(array)) return [];
87
+ if (key)
88
+ return array.sort((a, b) => {
89
+ return a[key] - b[key];
90
+ });
91
+ console.log("NO KEY");
92
+ };
93
+
94
+ /**
95
+ *
96
+ * @param {Array} array
97
+ * @returns {any}
98
+ */
99
+ export const firstElement = (array: any[]) => {
100
+ if (array) if (array.length || array.length > 0) return array[0];
101
+ return null;
102
+ };
103
+
104
+ /**
105
+ *
106
+ * @param {Array} array
107
+ * @returns {any}
108
+ */
109
+ export const lastElement = (array: any[]) => {
110
+ if (array) if (array.length || array.length > 0) return array[array.length - 1];
111
+ return null;
112
+ };
113
+
114
+ /**
115
+ *
116
+ * @param {Array} array
117
+ * @returns {any}
118
+ */
119
+ export const randomIndex = (array: any[]) => {
120
+ if (array) return randInt(0, array.length - 1);
121
+ return -1;
122
+ };
123
+
124
+ /**
125
+ *
126
+ * @param {Array} array
127
+ * @returns {any}
128
+ */
129
+ export const randomElement = (array: any[]) => {
130
+ if (array) return array[randomIndex(array)];
131
+ return null;
132
+ };
133
+
134
+ /**
135
+ * Remove same elements from 2 arrays
136
+ */
137
+ export const mergeAndMakeUniqueElement = (list1: any[], list2: any[], key: string) => {
138
+ if (!list1 || !list2) return;
139
+
140
+ if (key) {
141
+ return list1.concat(list2).filter((item, index, self) => {
142
+ return self.findIndex((x) => x[key] == item[key]) === index;
143
+ });
144
+ } else {
145
+ return list1.concat(list2).filter((x, index, self) => {
146
+ return self.indexOf(x) === index;
147
+ });
148
+ }
149
+ };
150
+
151
+ /**
152
+ * check target == toMatch
153
+ * @param {Array} target
154
+ * @param {Array} toMatch
155
+ * @returns {Boolean}
156
+ */
157
+ export const allMatchInArray = (target: any[], toMatch: any[]) => {
158
+ if (!target || !toMatch) return false;
159
+ const found = toMatch.every((item) => {
160
+ return target.includes(item);
161
+ });
162
+ return found;
163
+ };
164
+
165
+ export const removeItem = (item: any, array: any[]) => {
166
+ const index = array.indexOf(item);
167
+ if (index == -1) {
168
+ console.warn("[ArrayExtra.removeItem] Item not found.");
169
+ return array;
170
+ }
171
+ array.splice(index, 1);
172
+ return array;
173
+ };
174
+
175
+ export const removeItemByKey = (key: string, value: any, array: any[]) => {
176
+ const foundIndex = array.findIndex((item) => {
177
+ return item[key] == value;
178
+ });
179
+
180
+ if (foundIndex < 0) {
181
+ console.warn("[ArrayExtra.removeItemByKey] Item not found.", key, value);
182
+ return array;
183
+ }
184
+ array.splice(foundIndex, 1);
185
+ return array;
186
+ };
187
+
188
+ export const getRandom = (array: any[], n: number) => {
189
+ var result = new Array(n),
190
+ len = array.length,
191
+ taken = new Array(len);
192
+ if (n > len) throw new RangeError("getRandom: more elements taken than available");
193
+ while (n--) {
194
+ var x = Math.floor(Math.random() * len);
195
+ result[n] = array[x in taken ? taken[x] : x];
196
+ taken[x] = --len in taken ? taken[len] : len;
197
+ }
198
+ return result;
199
+ };
200
+
201
+ /**
202
+ * Get an array with shuffle element
203
+ */
204
+ export const getHalfRandom = (array: any[], n: number) => {
205
+ var n = Math.ceil(array.length / 2);
206
+ return getRandom(array, n);
207
+ };
208
+
209
+ /**
210
+ * Make array shuffle itself
211
+ */
212
+ export const shuffle = (array: any[]) => {
213
+ var i = array.length,
214
+ j,
215
+ temp;
216
+
217
+ if (array.length < 1) return array;
218
+
219
+ while (--i) {
220
+ j = Math.floor(Math.random() * (i + 1));
221
+ temp = array[i];
222
+ array[i] = array[j];
223
+ array[j] = temp;
224
+ }
225
+ return array;
226
+ };
227
+
228
+ /**
229
+ *
230
+ * @param {Array} array
231
+ * @param {Number} oldIndex
232
+ * @param {Number} newIndex
233
+ * @returns {Array}
234
+ */
235
+ export const moveIndex = (array: any[], oldIndex: number, newIndex: number) => {
236
+ if (newIndex >= array.length) {
237
+ var k = newIndex - array.length + 1;
238
+ while (k--) {
239
+ array.push(undefined);
240
+ }
241
+ }
242
+ array.splice(newIndex, 0, array.splice(oldIndex, 1)[0]);
243
+ return array;
244
+ };
245
+
246
+ export const moveArray = (array: any[], oldIndex: number, newIndex: number) => {
247
+ while (oldIndex < 0) {
248
+ oldIndex += array.length;
249
+ }
250
+ while (newIndex < 0) {
251
+ newIndex += array.length;
252
+ }
253
+ if (newIndex >= array.length) {
254
+ var k = newIndex - array.length;
255
+ while (k-- + 1) {
256
+ array.push(999);
257
+ }
258
+ }
259
+ array.splice(newIndex, 0, array.splice(oldIndex, 1)[0]);
260
+ return array;
261
+ };
package/src/color.ts ADDED
@@ -0,0 +1,89 @@
1
+ export const random = (hex = false) => {
2
+ return (hex ? "#" : "") + Math.floor(Math.random() * 16777215).toString(16);
3
+ };
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
+
10
+ export const pSBC = (p: any, c0: any, c1?: any, l?: any) => {
11
+ let r,
12
+ g,
13
+ b,
14
+ P,
15
+ f,
16
+ t,
17
+ h,
18
+ i = parseInt,
19
+ m = Math.round,
20
+ a: any = typeof c1 == "string";
21
+ if (typeof p != "number" || p < -1 || p > 1 || typeof c0 != "string" || (c0[0] != "r" && c0[0] != "#") || (c1 && !a))
22
+ return null;
23
+
24
+ const pSBCr = (d: any) => {
25
+ let n = d.length,
26
+ x: { r: number; g: number; b: number; a: number } = { r: 0, g: 0, b: 0, a: 1 };
27
+ if (n > 9) {
28
+ ([r, g, b, a] = d = d.split(",")), (n = d.length);
29
+ if (n < 3 || n > 4) return null;
30
+ (x.r = i(r[3] == "a" ? r.slice(5) : r.slice(4))),
31
+ (x.g = i(g)),
32
+ (x.b = i(b)),
33
+ (x.a = a ? parseFloat(a.toString()) : -1);
34
+ } else {
35
+ if (n == 8 || n == 6 || n < 4) return null;
36
+ if (n < 6) d = "#" + d[1] + d[1] + d[2] + d[2] + d[3] + d[3] + (n > 4 ? d[4] + d[4] : "");
37
+ d = i(d.slice(1), 16);
38
+ if (n == 9 || n == 5)
39
+ (x.r = (d >> 24) & 255), (x.g = (d >> 16) & 255), (x.b = (d >> 8) & 255), (x.a = m((d & 255) / 0.255) / 1000);
40
+ else (x.r = d >> 16), (x.g = (d >> 8) & 255), (x.b = d & 255), (x.a = -1);
41
+ }
42
+ return x;
43
+ };
44
+ (h = c0.length > 9),
45
+ (h = a ? (c1.length > 9 ? true : c1 == "c" ? !h : false) : h),
46
+ (f = pSBCr(c0)),
47
+ (P = p < 0),
48
+ (t = c1 && c1 != "c" ? pSBCr(c1) : P ? { r: 0, g: 0, b: 0, a: -1 } : { r: 255, g: 255, b: 255, a: -1 }),
49
+ (p = P ? p * -1 : p),
50
+ (P = 1 - p);
51
+ if (!f || !t || typeof f == "undefined") return null;
52
+ else 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));
53
+ else
54
+ (r = m((P * f.r ** 2 + p * t.r ** 2) ** 0.5)),
55
+ (g = m((P * f.g ** 2 + p * t.g ** 2) ** 0.5)),
56
+ (b = m((P * f.b ** 2 + p * t.b ** 2) ** 0.5));
57
+
58
+ (a = f.a), (t = t.a), (f = a >= 0 || t >= 0), (a = f ? (a < 0 ? t : t < 0 ? a : a * P + t * p) : 0);
59
+
60
+ if (h) return "rgb" + (f ? "a(" : "(") + r + "," + g + "," + b + (f ? "," + m(a * 1000) / 1000 : "") + ")";
61
+ else
62
+ return (
63
+ "#" +
64
+ (4294967296 + r * 16777216 + g * 65536 + b * 256 + (f ? m(a * 255) : 0)).toString(16).slice(1, f ? undefined : -2)
65
+ );
66
+ };
67
+
68
+ export const hexToRgb = (hex: string) => {
69
+ var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
70
+ return result
71
+ ? {
72
+ r: parseInt(result[1], 16),
73
+ g: parseInt(result[2], 16),
74
+ b: parseInt(result[3], 16),
75
+ }
76
+ : null;
77
+ };
78
+
79
+ export const hexDarken = (hex: string, amount: number) => {
80
+ return pSBC(-amount, hex);
81
+ };
82
+
83
+ export const hexLighten = (hex: string, amount: number) => {
84
+ return pSBC(amount, hex);
85
+ };
86
+
87
+ export const RGBToHex = (rgb: string | any) => {
88
+ return pSBC(0, rgb, "c", true);
89
+ };
@@ -0,0 +1,6 @@
1
+ import cloneDeep from "lodash/cloneDeep";
2
+ const _console = cloneDeep(console);
3
+
4
+ export function enableConsole() {
5
+ return _console;
6
+ }
@@ -0,0 +1,11 @@
1
+ export const disableConsole = (params: any) => {
2
+ for (var key in console) {
3
+ (console as any)[key] = function () {};
4
+ }
5
+ };
6
+
7
+ export const removeConsole = disableConsole;
8
+
9
+ export const showCredit = (params: any) => {
10
+ console.log("Developed by Digitop | https://www.wearetopgroup.com/?utm_src=console");
11
+ };
@@ -0,0 +1,29 @@
1
+ export const isPotrait = () => {
2
+ if (typeof window == "undefined") return false;
3
+
4
+ if (!window.orientation) return window.matchMedia("(orientation: portrait)").matches;
5
+ return !(window.orientation === 90 || window.orientation === -90);
6
+ };
7
+
8
+ export const isLandscape = () => {
9
+ return !isPotrait();
10
+ };
11
+
12
+ export const ua = () => {
13
+ if (typeof navigator == "undefined") return null;
14
+ if (typeof window == "undefined") return null;
15
+
16
+ return navigator.userAgent || navigator.vendor || (window as any).opera;
17
+ };
18
+
19
+ export const isFacebookWebview = () => {
20
+ var ua: any = ua();
21
+ if (typeof ua != "undefined") return ua.indexOf("FBAN") > -1 || ua.indexOf("FBAV") > -1;
22
+ };
23
+
24
+ export const isInAppWebview = () => {
25
+ const rules = ["WebView", "(iPhone|iPod|iPad)(?!.*Safari/)", "Android.*(wv|.0.0.0)"];
26
+ const regex = new RegExp(`(${rules.join("|")})`, "ig");
27
+ if (ua()) return Boolean(ua().match(regex));
28
+ return false;
29
+ };
@@ -0,0 +1,209 @@
1
+ import { requestCamera } from "../permission/requestCamera";
2
+
3
+ type GetWebcamParams = {
4
+ container?: HTMLElement;
5
+ facingMode: string;
6
+ audio: boolean;
7
+ };
8
+
9
+ export function getWebcam(params: GetWebcamParams = { facingMode: "environment", audio: true }) {
10
+ if (typeof window == "undefined") return;
11
+
12
+ const { container, facingMode = "environment", audio = true } = params;
13
+ const _container = container || document.body;
14
+
15
+ return new Promise(async (resolve, reject) => {
16
+ const video = document.createElement("video");
17
+ video.style.position = "absolute";
18
+ video.style.top = "0";
19
+ video.style.left = "0";
20
+ video.style.width = "100%";
21
+ video.style.height = "100%";
22
+ _container.append(video);
23
+
24
+ let inputCameras: any[] = [];
25
+ let currentCamera: any;
26
+
27
+ const requestedMediaConstraints: MediaStreamConstraints = {
28
+ video: {
29
+ facingMode: { exact: facingMode },
30
+ },
31
+ audio,
32
+ };
33
+
34
+ let stream: any;
35
+ let isAllowed = false;
36
+
37
+ console.log("[Camera.js] Requesting:", requestedMediaConstraints);
38
+ const res = await requestCamera({ audio });
39
+ if (!res) {
40
+ setTimeout(function () {
41
+ handleError({ name: "Error", message: "NotSupported" });
42
+ }, 50);
43
+ }
44
+
45
+ // start requesting media permissions:
46
+
47
+ // console.log("[Camera.js] Requesting:", requestedMediaConstraints);
48
+
49
+ // if (navigator.mediaDevices.enumerateDevices === undefined) {
50
+ // setTimeout(function () {
51
+ // handleError({ name: "Error", message: "NotSupported" });
52
+ // }, 50);
53
+ // } else {
54
+ navigator.mediaDevices.enumerateDevices().then(parseDevices).catch(handleError);
55
+ // }
56
+
57
+ function parseDevices(devices: MediaDeviceInfo[]) {
58
+ inputCameras = [];
59
+ let backCameras: any[] = [];
60
+
61
+ devices.forEach(function (device) {
62
+ if (device.kind == "videoinput" && typeof device.deviceId != "undefined" && device.deviceId != "") {
63
+ inputCameras.push(device);
64
+ }
65
+ });
66
+ // //alert (JSON.stringify (devices));
67
+ console.log("[Camera.js] inputCameras:", inputCameras);
68
+
69
+ if (inputCameras.length > 0) {
70
+ let cams = "";
71
+ let backCamera: any;
72
+
73
+ inputCameras.map((cam, index) => {
74
+ cams += `[${cam.deviceId}] ${cam.kind} | ${cam.label}\n`;
75
+ // console.log(cam);
76
+ let label = cam.label.toLowerCase();
77
+ if (label.indexOf("back") > -1 || label.indexOf("facetime") > -1) {
78
+ backCamera = cam;
79
+ backCameras.push(backCamera);
80
+ }
81
+ });
82
+
83
+ if (backCameras.length > 1) {
84
+ backCamera = backCameras[backCameras.length - 1];
85
+ }
86
+
87
+ console.log(`[Camera.js] All input sources:`, cams);
88
+ console.log(
89
+ `[Camera.js] This device has ${backCameras.length} back camera${backCameras.length > 1 ? "s" : ""}.`
90
+ );
91
+ console.log("[Camera.js] backCameras:", JSON.stringify(backCameras));
92
+
93
+ currentCamera = backCamera;
94
+
95
+ // if (scope.onGotDevices) {
96
+ // scope.onGotDevices(devices);
97
+ // }
98
+
99
+ // Lấy stream của camera sau
100
+ // (Lấy cái cuối cùng trong danh sách trước, thường sẽ là camera chính trên Android)
101
+ getStreamOfCameraId(backCamera.deviceId)
102
+ .then(onStreamReceived)
103
+ .catch((e) => {
104
+ if (backCameras.length > 1) {
105
+ // nếu thiết bị có nhiều hơn 1 camera sau -> thử lấy camera khác
106
+ backCamera = backCameras[backCameras.length - 2];
107
+ getStreamOfCameraId(backCamera.deviceId).then(onStreamReceived).catch(handleError);
108
+ } else if (backCameras.length > 2) {
109
+ // nếu thiết bị có nhiều hơn 2 camera sau -> thử lấy camera khác nữa
110
+ backCamera = backCameras[backCameras.length - 3];
111
+ getStreamOfCameraId(backCamera.deviceId).then(onStreamReceived).catch(handleError);
112
+ } else {
113
+ // nếu thiết bị đéo có camera sau...
114
+ handleError(e);
115
+ }
116
+ });
117
+ } else {
118
+ navigator.mediaDevices.getUserMedia(requestedMediaConstraints).then(onStreamReceived).catch(handleError);
119
+
120
+ // if (scope.onGotDevicesFailed) scope.onGotDevicesFailed();
121
+ }
122
+ }
123
+
124
+ function onStreamReceived(stream: any): void {
125
+ if (inputCameras.length == 0) {
126
+ console.log("[Camera.js] Not found any back cameras, request again?");
127
+ navigator.mediaDevices.enumerateDevices().then(parseDevices).catch(handleError);
128
+ return;
129
+ }
130
+
131
+ isAllowed = true;
132
+
133
+ playWebcamVideo(stream);
134
+ }
135
+
136
+ function playWebcamVideo(_stream: any) {
137
+ stream = _stream;
138
+
139
+ if ("srcObject" in video) {
140
+ // //alert ('GOT STREAM VIDEO OBJECT');
141
+ video.srcObject = _stream;
142
+ } else {
143
+ // //alert ('GOT STREAM VIDEO SOURCE URL');
144
+ // Avoid using this in new browsers, as it is going away.
145
+ video.src = window.URL.createObjectURL(_stream);
146
+ }
147
+
148
+ // required to tell iOS safari we don't want fullscreen
149
+ video.setAttribute("playsinline", "true");
150
+ video.setAttribute("muted", "true");
151
+ video.setAttribute("autoplay", "true");
152
+ video.muted = true;
153
+ video.autoplay = true;
154
+ video.style.objectFit = "cover";
155
+ video.play();
156
+
157
+ // auto play
158
+ video.addEventListener("canplay", function (e) {
159
+ // //alert ('CAN PLAY');
160
+ });
161
+
162
+ video.addEventListener("canplaythrough", function (e) {
163
+ // //alert ('CAN PLAY THROUGH');
164
+ });
165
+
166
+ video.addEventListener("error", (e) => console.log("[Camera.js] <video> error:", e));
167
+
168
+ video.addEventListener("stalled", function (e) {
169
+ // //alert ('CANNOT GET METADATA');
170
+ isAllowed = false;
171
+ console.log("[Camera.js] <video> stalled:", e);
172
+
173
+ reject();
174
+ });
175
+
176
+ video.addEventListener("loadedmetadata", function (e) {
177
+ if (currentCamera.label.toLowerCase().indexOf("facetime") > -1) {
178
+ video.style.transform = "scaleX(-1)";
179
+ video.style.webkitTransform = "scaleX(-1)";
180
+ }
181
+
182
+ video.play();
183
+
184
+ resolve(video);
185
+ });
186
+ }
187
+
188
+ function getStreamOfCameraId(id: any) {
189
+ const constraints = {
190
+ video: { deviceId: { exact: id } },
191
+ audio: false,
192
+ };
193
+
194
+ return new Promise((resolve, reject) => {
195
+ navigator.mediaDevices.getUserMedia(constraints).then(resolve).catch(reject);
196
+ });
197
+ }
198
+
199
+ function handleError(err: any) {
200
+ console.error(err);
201
+ const errMsg = "[Camera.js] " + err.name + ": " + err.message;
202
+ console.error(errMsg);
203
+
204
+ isAllowed = false;
205
+
206
+ reject();
207
+ }
208
+ });
209
+ }