easyproctor-hml 3.2.0 → 3.2.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/README.md +33 -0
- package/esm/index.js +11 -9
- package/index.js +11 -9
- package/interfaces/ParamsConfig.d.ts +1 -0
- package/package.json +1 -1
- package/plugins/recorder.d.ts +1 -0
- package/unpkg/easyproctor.min.js +3 -3
package/README.md
CHANGED
|
@@ -263,17 +263,25 @@ const {
|
|
|
263
263
|
token: "...",
|
|
264
264
|
});
|
|
265
265
|
```
|
|
266
|
+
|
|
266
267
|
## Release Note V 3.2.0
|
|
267
268
|
- Fix: melhoria na sincronizacao dos alertas de tela
|
|
268
269
|
- Fix: melhoria no corte do audio para analise
|
|
269
270
|
- Fator de qualidade parametrizavel
|
|
270
271
|
- Alerta de microfone mutado adicionado
|
|
271
272
|
|
|
273
|
+
## Release Note V 3.1.0
|
|
274
|
+
- Fix: tratamento para ignorar bug do import pacote fix-webm-duration
|
|
275
|
+
- Analise da tela para capturar uso de ferramenta de captura de tela
|
|
276
|
+
|
|
272
277
|
## Release Note V 3.0.0
|
|
273
278
|
- Envio do vídeo por partes durante o exame para o proctoring REALTIME
|
|
274
279
|
- Fix: correção do bug do import pacote fix-webm-duration
|
|
275
280
|
- Possibilidade de check automático no check devices através do parametro 'auto'
|
|
276
281
|
|
|
282
|
+
## Release Note V 2.7.1
|
|
283
|
+
- Fix: removendo envio do video por incompatibilidade no iOS
|
|
284
|
+
|
|
277
285
|
## Release Note V 2.7.0
|
|
278
286
|
- Implementação da comunicação com a API para o proctoring do tipo realtime
|
|
279
287
|
- Envio do vídeo durante o exame
|
|
@@ -303,6 +311,31 @@ const {
|
|
|
303
311
|
- Melhorias de performance
|
|
304
312
|
- Ajuste Realtime para PC
|
|
305
313
|
|
|
314
|
+
## Release Note V 2.5.5
|
|
315
|
+
- Fix: Correção de bug de rotação do realtime
|
|
316
|
+
|
|
317
|
+
## Release Note V 2.6.0
|
|
318
|
+
- Implementação da comunicação entre componente e navegador seguro
|
|
319
|
+
|
|
320
|
+
## Release Note V 2.5.8
|
|
321
|
+
- removendo fechamento do webm com a duração para refinamento
|
|
322
|
+
|
|
323
|
+
## Release Note V 2.5.7
|
|
324
|
+
- Ajustes na verificação biometrica
|
|
325
|
+
- Estrategia de erro no upload final do video
|
|
326
|
+
- Fechando webm com a duração
|
|
327
|
+
- Ajustes na finalização da sessao para evitar alertas após o encerramento do stream
|
|
328
|
+
- Ajuste no onRealtimeAlerts
|
|
329
|
+
|
|
330
|
+
## Release Note V 2.5.6
|
|
331
|
+
- Novo método de gravação com tratamento de retry
|
|
332
|
+
- Ajuste parametrização do realtime
|
|
333
|
+
- Ajuste de sincronização dos alertas de acordo com a gravação
|
|
334
|
+
- Separação da visualização do stream (checkDevices e capturePhoto) da gravação
|
|
335
|
+
- Melhorias de performance
|
|
336
|
+
- Ajuste Realtime para PC
|
|
337
|
+
|
|
338
|
+
|
|
306
339
|
## Release Note V 2.5.5
|
|
307
340
|
- Fix: Correção de bug de rotação do realtime
|
|
308
341
|
|
package/esm/index.js
CHANGED
|
@@ -12864,7 +12864,7 @@ function recorder(stream, buffer, onBufferSizeError = false, onBufferSizeErrorCa
|
|
|
12864
12864
|
console.error("Timeout ao iniciar o recorder");
|
|
12865
12865
|
reject(new Error("Timeout ao iniciar o recorder"));
|
|
12866
12866
|
}
|
|
12867
|
-
},
|
|
12867
|
+
}, 1e4 * ((recorderOpts == null ? void 0 : recorderOpts.timeoutMultiplierFactor) || 1));
|
|
12868
12868
|
});
|
|
12869
12869
|
}
|
|
12870
12870
|
async function startRecording() {
|
|
@@ -13890,7 +13890,8 @@ var _CameraRecorder = class _CameraRecorder {
|
|
|
13890
13890
|
detectPerson: false,
|
|
13891
13891
|
detectFace: false,
|
|
13892
13892
|
detectCellPhone: false,
|
|
13893
|
-
cameraVideoQuality: 1
|
|
13893
|
+
cameraVideoQuality: 1,
|
|
13894
|
+
timeoutMultiplierFactor: 1
|
|
13894
13895
|
}
|
|
13895
13896
|
};
|
|
13896
13897
|
this.options = {
|
|
@@ -14206,7 +14207,7 @@ Setting: ${JSON.stringify(settings, null, 2)}`
|
|
|
14206
14207
|
await new Promise((r3) => setTimeout(r3, 300));
|
|
14207
14208
|
}
|
|
14208
14209
|
async startRecording() {
|
|
14209
|
-
var _a2, _b, _c2, _d, _e3, _f, _g, _h, _i3;
|
|
14210
|
+
var _a2, _b, _c2, _d, _e3, _f, _g, _h, _i3, _j;
|
|
14210
14211
|
await this.startStream();
|
|
14211
14212
|
await this.attachAndWarmup(this.cameraStream);
|
|
14212
14213
|
const recorderOpts = this.isChunkEnabled ? {
|
|
@@ -14214,7 +14215,8 @@ Setting: ${JSON.stringify(settings, null, 2)}`
|
|
|
14214
14215
|
onChunkAvailable: (blob, idx) => {
|
|
14215
14216
|
this.handleNewChunk(blob, idx);
|
|
14216
14217
|
},
|
|
14217
|
-
quality: (_a2 = this.paramsConfig.videoBehaviourParameters) == null ? void 0 : _a2.cameraVideoQuality
|
|
14218
|
+
quality: (_a2 = this.paramsConfig.videoBehaviourParameters) == null ? void 0 : _a2.cameraVideoQuality,
|
|
14219
|
+
timeoutMultiplierFactor: ((_b = this.paramsConfig.videoBehaviourParameters) == null ? void 0 : _b.timeoutMultiplierFactor) || 1
|
|
14218
14220
|
} : {};
|
|
14219
14221
|
const {
|
|
14220
14222
|
startRecording,
|
|
@@ -14243,7 +14245,7 @@ Setting: ${JSON.stringify(settings, null, 2)}`
|
|
|
14243
14245
|
this.getDuration = getDuration;
|
|
14244
14246
|
this.chunkIndex = 0;
|
|
14245
14247
|
if (this.isChunkEnabled) {
|
|
14246
|
-
(
|
|
14248
|
+
(_c2 = this.backgroundUpload) == null ? void 0 : _c2.start();
|
|
14247
14249
|
this.setupLifecycleListeners();
|
|
14248
14250
|
}
|
|
14249
14251
|
try {
|
|
@@ -14252,7 +14254,7 @@ Setting: ${JSON.stringify(settings, null, 2)}`
|
|
|
14252
14254
|
} catch (error) {
|
|
14253
14255
|
console.log("Camera Recorder error", error);
|
|
14254
14256
|
this.stopRecording();
|
|
14255
|
-
const maxRetries = ((
|
|
14257
|
+
const maxRetries = ((_d = this.paramsConfig.videoBehaviourParameters) == null ? void 0 : _d.maxRetries) || 3;
|
|
14256
14258
|
if (this.currentRetries < maxRetries) {
|
|
14257
14259
|
console.log("Camera Recorder retry", this.currentRetries);
|
|
14258
14260
|
this.currentRetries++;
|
|
@@ -14262,13 +14264,13 @@ Setting: ${JSON.stringify(settings, null, 2)}`
|
|
|
14262
14264
|
}
|
|
14263
14265
|
}
|
|
14264
14266
|
this.stopped = false;
|
|
14265
|
-
if (((
|
|
14267
|
+
if (((_e3 = this.paramsConfig.videoBehaviourParameters) == null ? void 0 : _e3.detectPerson) || ((_f = this.paramsConfig.videoBehaviourParameters) == null ? void 0 : _f.detectCellPhone) || ((_g = this.paramsConfig.videoBehaviourParameters) == null ? void 0 : _g.detectFace)) {
|
|
14266
14268
|
await this.initializeDetectors();
|
|
14267
14269
|
}
|
|
14268
|
-
if ((
|
|
14270
|
+
if ((_h = this.paramsConfig.videoBehaviourParameters) == null ? void 0 : _h.detectFace) {
|
|
14269
14271
|
await this.faceDetection.enableCam(this.cameraStream);
|
|
14270
14272
|
}
|
|
14271
|
-
if (((
|
|
14273
|
+
if (((_i3 = this.paramsConfig.videoBehaviourParameters) == null ? void 0 : _i3.detectPerson) || ((_j = this.paramsConfig.videoBehaviourParameters) == null ? void 0 : _j.detectCellPhone)) {
|
|
14272
14274
|
await this.objectDetection.enableCam(this.cameraStream);
|
|
14273
14275
|
}
|
|
14274
14276
|
this.filesToUpload = [];
|
package/index.js
CHANGED
|
@@ -30961,7 +30961,7 @@ function recorder(stream4, buffer, onBufferSizeError = false, onBufferSizeErrorC
|
|
|
30961
30961
|
console.error("Timeout ao iniciar o recorder");
|
|
30962
30962
|
reject(new Error("Timeout ao iniciar o recorder"));
|
|
30963
30963
|
}
|
|
30964
|
-
},
|
|
30964
|
+
}, 1e4 * ((recorderOpts == null ? void 0 : recorderOpts.timeoutMultiplierFactor) || 1));
|
|
30965
30965
|
});
|
|
30966
30966
|
}
|
|
30967
30967
|
async function startRecording() {
|
|
@@ -31987,7 +31987,8 @@ var _CameraRecorder = class _CameraRecorder {
|
|
|
31987
31987
|
detectPerson: false,
|
|
31988
31988
|
detectFace: false,
|
|
31989
31989
|
detectCellPhone: false,
|
|
31990
|
-
cameraVideoQuality: 1
|
|
31990
|
+
cameraVideoQuality: 1,
|
|
31991
|
+
timeoutMultiplierFactor: 1
|
|
31991
31992
|
}
|
|
31992
31993
|
};
|
|
31993
31994
|
this.options = {
|
|
@@ -32303,7 +32304,7 @@ Setting: ${JSON.stringify(settings, null, 2)}`
|
|
|
32303
32304
|
await new Promise((r3) => setTimeout(r3, 300));
|
|
32304
32305
|
}
|
|
32305
32306
|
async startRecording() {
|
|
32306
|
-
var _a2, _b, _c2, _d, _e3, _f, _g, _h, _i3;
|
|
32307
|
+
var _a2, _b, _c2, _d, _e3, _f, _g, _h, _i3, _j;
|
|
32307
32308
|
await this.startStream();
|
|
32308
32309
|
await this.attachAndWarmup(this.cameraStream);
|
|
32309
32310
|
const recorderOpts = this.isChunkEnabled ? {
|
|
@@ -32311,7 +32312,8 @@ Setting: ${JSON.stringify(settings, null, 2)}`
|
|
|
32311
32312
|
onChunkAvailable: (blob, idx) => {
|
|
32312
32313
|
this.handleNewChunk(blob, idx);
|
|
32313
32314
|
},
|
|
32314
|
-
quality: (_a2 = this.paramsConfig.videoBehaviourParameters) == null ? void 0 : _a2.cameraVideoQuality
|
|
32315
|
+
quality: (_a2 = this.paramsConfig.videoBehaviourParameters) == null ? void 0 : _a2.cameraVideoQuality,
|
|
32316
|
+
timeoutMultiplierFactor: ((_b = this.paramsConfig.videoBehaviourParameters) == null ? void 0 : _b.timeoutMultiplierFactor) || 1
|
|
32315
32317
|
} : {};
|
|
32316
32318
|
const {
|
|
32317
32319
|
startRecording,
|
|
@@ -32340,7 +32342,7 @@ Setting: ${JSON.stringify(settings, null, 2)}`
|
|
|
32340
32342
|
this.getDuration = getDuration;
|
|
32341
32343
|
this.chunkIndex = 0;
|
|
32342
32344
|
if (this.isChunkEnabled) {
|
|
32343
|
-
(
|
|
32345
|
+
(_c2 = this.backgroundUpload) == null ? void 0 : _c2.start();
|
|
32344
32346
|
this.setupLifecycleListeners();
|
|
32345
32347
|
}
|
|
32346
32348
|
try {
|
|
@@ -32349,7 +32351,7 @@ Setting: ${JSON.stringify(settings, null, 2)}`
|
|
|
32349
32351
|
} catch (error) {
|
|
32350
32352
|
console.log("Camera Recorder error", error);
|
|
32351
32353
|
this.stopRecording();
|
|
32352
|
-
const maxRetries = ((
|
|
32354
|
+
const maxRetries = ((_d = this.paramsConfig.videoBehaviourParameters) == null ? void 0 : _d.maxRetries) || 3;
|
|
32353
32355
|
if (this.currentRetries < maxRetries) {
|
|
32354
32356
|
console.log("Camera Recorder retry", this.currentRetries);
|
|
32355
32357
|
this.currentRetries++;
|
|
@@ -32359,13 +32361,13 @@ Setting: ${JSON.stringify(settings, null, 2)}`
|
|
|
32359
32361
|
}
|
|
32360
32362
|
}
|
|
32361
32363
|
this.stopped = false;
|
|
32362
|
-
if (((
|
|
32364
|
+
if (((_e3 = this.paramsConfig.videoBehaviourParameters) == null ? void 0 : _e3.detectPerson) || ((_f = this.paramsConfig.videoBehaviourParameters) == null ? void 0 : _f.detectCellPhone) || ((_g = this.paramsConfig.videoBehaviourParameters) == null ? void 0 : _g.detectFace)) {
|
|
32363
32365
|
await this.initializeDetectors();
|
|
32364
32366
|
}
|
|
32365
|
-
if ((
|
|
32367
|
+
if ((_h = this.paramsConfig.videoBehaviourParameters) == null ? void 0 : _h.detectFace) {
|
|
32366
32368
|
await this.faceDetection.enableCam(this.cameraStream);
|
|
32367
32369
|
}
|
|
32368
|
-
if (((
|
|
32370
|
+
if (((_i3 = this.paramsConfig.videoBehaviourParameters) == null ? void 0 : _i3.detectPerson) || ((_j = this.paramsConfig.videoBehaviourParameters) == null ? void 0 : _j.detectCellPhone)) {
|
|
32369
32371
|
await this.objectDetection.enableCam(this.cameraStream);
|
|
32370
32372
|
}
|
|
32371
32373
|
this.filesToUpload = [];
|
|
@@ -24,6 +24,7 @@ export type VideoBehaviourParameters = {
|
|
|
24
24
|
realtimeCaptureInterval?: number;
|
|
25
25
|
cameraVideoQuality?: number;
|
|
26
26
|
screenVideoQuality?: number;
|
|
27
|
+
timeoutMultiplierFactor?: number;
|
|
27
28
|
};
|
|
28
29
|
export default interface IParamsConfig {
|
|
29
30
|
audioBehaviourParameters?: AudioBehaviourParameters;
|
package/package.json
CHANGED
package/plugins/recorder.d.ts
CHANGED
|
@@ -3,6 +3,7 @@ export interface RecorderOptions {
|
|
|
3
3
|
timeslice?: number;
|
|
4
4
|
onChunkAvailable?: (blob: Blob, chunkIndex: number) => void;
|
|
5
5
|
quality?: number;
|
|
6
|
+
timeoutMultiplierFactor?: number;
|
|
6
7
|
}
|
|
7
8
|
export default function recorder(stream: MediaStream, buffer: Blob[], onBufferSizeError?: boolean, onBufferSizeErrorCallback?: (e?: any) => void, recorderOpts?: RecorderOptions): {
|
|
8
9
|
startRecording: () => Promise<void>;
|
package/unpkg/easyproctor.min.js
CHANGED
|
@@ -68,7 +68,7 @@ Minimum version required to store current data is: `+o+`.
|
|
|
68
68
|
`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...r){let n=new this(t);return r.forEach(i=>n.set(i)),n}static accessor(t){let n=(this[Ig]=this[Ig]={accessors:{}}).accessors,i=this.prototype;function o(s){let a=Fo(s);n[a]||(c_(i,s),n[a]=!0)}return I.isArray(t)?t.forEach(o):o(t),this}};Mi.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);I.reduceDescriptors(Mi.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(n){this[r]=n}}});I.freezeMethods(Mi);var at=Mi;function Lo(e,t){let r=this||Li,n=t||r,i=at.from(n.headers),o=n.data;return I.forEach(e,function(a){o=a.call(r,o,i.normalize(),t?t.status:void 0)}),i.normalize(),o}function Mo(e){return!!(e&&e.__CANCEL__)}function Rg(e,t,r){le.call(this,e??"canceled",le.ERR_CANCELED,t,r),this.name="CanceledError"}I.inherits(Rg,le,{__CANCEL__:!0});var Ur=Rg;function No(e,t,r){let n=r.config.validateStatus;!r.status||!n||n(r.status)?e(r):t(new le("Request failed with status code "+r.status,[le.ERR_BAD_REQUEST,le.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function ld(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function l_(e,t){e=e||10;let r=new Array(e),n=new Array(e),i=0,o=0,s;return t=t!==void 0?t:1e3,function(c){let l=Date.now(),h=n[o];s||(s=l),r[i]=c,n[i]=l;let d=o,g=0;for(;d!==i;)g+=r[d++],d=d%e;if(i=(i+1)%e,i===o&&(o=(o+1)%e),l-s<t)return;let p=h&&l-h;return p?Math.round(g*1e3/p):void 0}}var Pg=l_;function h_(e,t){let r=0,n=1e3/t,i,o,s=(l,h=Date.now())=>{r=h,i=null,o&&(clearTimeout(o),o=null),e.apply(null,l)};return[(...l)=>{let h=Date.now(),d=h-r;d>=n?s(l,h):(i=l,o||(o=setTimeout(()=>{o=null,s(i)},n-d)))},()=>i&&s(i)]}var Dg=h_;var Ni=(e,t,r=3)=>{let n=0,i=Pg(50,250);return Dg(o=>{let s=o.loaded,a=o.lengthComputable?o.total:void 0,c=s-n,l=i(c),h=s<=a;n=s;let d={loaded:s,total:a,progress:a?s/a:void 0,bytes:c,rate:l||void 0,estimated:l&&a&&h?(a-s)/l:void 0,event:o,lengthComputable:a!=null,[t?"download":"upload"]:!0};e(d)},r)},hd=(e,t)=>{let r=e!=null;return[n=>t[0]({lengthComputable:r,total:e,loaded:n}),t[1]]},dd=e=>(...t)=>I.asap(()=>e(...t));var Bg=je.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,je.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(je.origin),je.navigator&&/(msie|trident)/i.test(je.navigator.userAgent)):()=>!0;var Og=je.hasStandardBrowserEnv?{write(e,t,r,n,i,o){let s=[e+"="+encodeURIComponent(t)];I.isNumber(r)&&s.push("expires="+new Date(r).toGMTString()),I.isString(n)&&s.push("path="+n),I.isString(i)&&s.push("domain="+i),o===!0&&s.push("secure"),document.cookie=s.join("; ")},read(e){let t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function ud(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function pd(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function zo(e,t,r){let n=!ud(t);return e&&(n||r==!1)?pd(e,t):t}var Ug=e=>e instanceof at?{...e}:e;function vr(e,t){t=t||{};let r={};function n(l,h,d,g){return I.isPlainObject(l)&&I.isPlainObject(h)?I.merge.call({caseless:g},l,h):I.isPlainObject(h)?I.merge({},h):I.isArray(h)?h.slice():h}function i(l,h,d,g){if(I.isUndefined(h)){if(!I.isUndefined(l))return n(void 0,l,d,g)}else return n(l,h,d,g)}function o(l,h){if(!I.isUndefined(h))return n(void 0,h)}function s(l,h){if(I.isUndefined(h)){if(!I.isUndefined(l))return n(void 0,l)}else return n(void 0,h)}function a(l,h,d){if(d in t)return n(l,h);if(d in e)return n(void 0,l)}let c={url:o,method:o,data:o,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:a,headers:(l,h,d)=>i(Ug(l),Ug(h),d,!0)};return I.forEach(Object.keys(Object.assign({},e,t)),function(h){let d=c[h]||i,g=d(e[h],t[h],h);I.isUndefined(g)&&d!==a||(r[h]=g)}),r}var Ca=e=>{let t=vr({},e),{data:r,withXSRFToken:n,xsrfHeaderName:i,xsrfCookieName:o,headers:s,auth:a}=t;t.headers=s=at.from(s),t.url=Uo(zo(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),a&&s.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):"")));let c;if(I.isFormData(r)){if(je.hasStandardBrowserEnv||je.hasStandardBrowserWebWorkerEnv)s.setContentType(void 0);else if((c=s.getContentType())!==!1){let[l,...h]=c?c.split(";").map(d=>d.trim()).filter(Boolean):[];s.setContentType([l||"multipart/form-data",...h].join("; "))}}if(je.hasStandardBrowserEnv&&(n&&I.isFunction(n)&&(n=n(t)),n||n!==!1&&Bg(t.url))){let l=i&&o&&Og.read(o);l&&s.set(i,l)}return t};var d_=typeof XMLHttpRequest<"u",Fg=d_&&function(e){return new Promise(function(r,n){let i=Ca(e),o=i.data,s=at.from(i.headers).normalize(),{responseType:a,onUploadProgress:c,onDownloadProgress:l}=i,h,d,g,p,m;function f(){p&&p(),m&&m(),i.cancelToken&&i.cancelToken.unsubscribe(h),i.signal&&i.signal.removeEventListener("abort",h)}let b=new XMLHttpRequest;b.open(i.method.toUpperCase(),i.url,!0),b.timeout=i.timeout;function v(){if(!b)return;let k=at.from("getAllResponseHeaders"in b&&b.getAllResponseHeaders()),x={data:!a||a==="text"||a==="json"?b.responseText:b.response,status:b.status,statusText:b.statusText,headers:k,config:e,request:b};No(function(A){r(A),f()},function(A){n(A),f()},x),b=null}"onloadend"in b?b.onloadend=v:b.onreadystatechange=function(){!b||b.readyState!==4||b.status===0&&!(b.responseURL&&b.responseURL.indexOf("file:")===0)||setTimeout(v)},b.onabort=function(){b&&(n(new le("Request aborted",le.ECONNABORTED,e,b)),b=null)},b.onerror=function(){n(new le("Network Error",le.ERR_NETWORK,e,b)),b=null},b.ontimeout=function(){let R=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded",x=i.transitional||Sa;i.timeoutErrorMessage&&(R=i.timeoutErrorMessage),n(new le(R,x.clarifyTimeoutError?le.ETIMEDOUT:le.ECONNABORTED,e,b)),b=null},o===void 0&&s.setContentType(null),"setRequestHeader"in b&&I.forEach(s.toJSON(),function(R,x){b.setRequestHeader(x,R)}),I.isUndefined(i.withCredentials)||(b.withCredentials=!!i.withCredentials),a&&a!=="json"&&(b.responseType=i.responseType),l&&([g,m]=Ni(l,!0),b.addEventListener("progress",g)),c&&b.upload&&([d,p]=Ni(c),b.upload.addEventListener("progress",d),b.upload.addEventListener("loadend",p)),(i.cancelToken||i.signal)&&(h=k=>{b&&(n(!k||k.type?new Ur(null,e,b):k),b.abort(),b=null)},i.cancelToken&&i.cancelToken.subscribe(h),i.signal&&(i.signal.aborted?h():i.signal.addEventListener("abort",h)));let S=ld(i.url);if(S&&je.protocols.indexOf(S)===-1){n(new le("Unsupported protocol "+S+":",le.ERR_BAD_REQUEST,e));return}b.send(o||null)})};var u_=(e,t)=>{let{length:r}=e=e?e.filter(Boolean):[];if(t||r){let n=new AbortController,i,o=function(l){if(!i){i=!0,a();let h=l instanceof Error?l:this.reason;n.abort(h instanceof le?h:new Ur(h instanceof Error?h.message:h))}},s=t&&setTimeout(()=>{s=null,o(new le(`timeout ${t} of ms exceeded`,le.ETIMEDOUT))},t),a=()=>{e&&(s&&clearTimeout(s),s=null,e.forEach(l=>{l.unsubscribe?l.unsubscribe(o):l.removeEventListener("abort",o)}),e=null)};e.forEach(l=>l.addEventListener("abort",o));let{signal:c}=n;return c.unsubscribe=()=>I.asap(a),c}},Lg=u_;var p_=function*(e,t){let r=e.byteLength;if(!t||r<t){yield e;return}let n=0,i;for(;n<r;)i=n+t,yield e.slice(n,i),n=i},f_=async function*(e,t){for await(let r of m_(e))yield*p_(r,t)},m_=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}let t=e.getReader();try{for(;;){let{done:r,value:n}=await t.read();if(r)break;yield n}}finally{await t.cancel()}},fd=(e,t,r,n)=>{let i=f_(e,t),o=0,s,a=c=>{s||(s=!0,n&&n(c))};return new ReadableStream({async pull(c){try{let{done:l,value:h}=await i.next();if(l){a(),c.close();return}let d=h.byteLength;if(r){let g=o+=d;r(g)}c.enqueue(new Uint8Array(h))}catch(l){throw a(l),l}},cancel(c){return a(c),i.return()}},{highWaterMark:2})};var Aa=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",Ng=Aa&&typeof ReadableStream=="function",g_=Aa&&(typeof TextEncoder=="function"?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),zg=(e,...t)=>{try{return!!e(...t)}catch{return!1}},y_=Ng&&zg(()=>{let e=!1,t=new Request(je.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),Mg=64*1024,md=Ng&&zg(()=>I.isReadableStream(new Response("").body)),xa={stream:md&&(e=>e.body)};Aa&&(e=>{["text","arrayBuffer","blob","formData","stream"].forEach(t=>{!xa[t]&&(xa[t]=I.isFunction(e[t])?r=>r[t]():(r,n)=>{throw new le(`Response type '${t}' is not supported`,le.ERR_NOT_SUPPORT,n)})})})(new Response);var b_=async e=>{if(e==null)return 0;if(I.isBlob(e))return e.size;if(I.isSpecCompliantForm(e))return(await new Request(je.origin,{method:"POST",body:e}).arrayBuffer()).byteLength;if(I.isArrayBufferView(e)||I.isArrayBuffer(e))return e.byteLength;if(I.isURLSearchParams(e)&&(e=e+""),I.isString(e))return(await g_(e)).byteLength},v_=async(e,t)=>{let r=I.toFiniteNumber(e.getContentLength());return r??b_(t)},jg=Aa&&(async e=>{let{url:t,method:r,data:n,signal:i,cancelToken:o,timeout:s,onDownloadProgress:a,onUploadProgress:c,responseType:l,headers:h,withCredentials:d="same-origin",fetchOptions:g}=Ca(e);l=l?(l+"").toLowerCase():"text";let p=Lg([i,o&&o.toAbortSignal()],s),m,f=p&&p.unsubscribe&&(()=>{p.unsubscribe()}),b;try{if(c&&y_&&r!=="get"&&r!=="head"&&(b=await v_(h,n))!==0){let x=new Request(t,{method:"POST",body:n,duplex:"half"}),O;if(I.isFormData(n)&&(O=x.headers.get("content-type"))&&h.setContentType(O),x.body){let[A,M]=hd(b,Ni(dd(c)));n=fd(x.body,Mg,A,M)}}I.isString(d)||(d=d?"include":"omit");let v="credentials"in Request.prototype;m=new Request(t,{...g,signal:p,method:r.toUpperCase(),headers:h.normalize().toJSON(),body:n,duplex:"half",credentials:v?d:void 0});let S=await fetch(m),k=md&&(l==="stream"||l==="response");if(md&&(a||k&&f)){let x={};["status","statusText","headers"].forEach(J=>{x[J]=S[J]});let O=I.toFiniteNumber(S.headers.get("content-length")),[A,M]=a&&hd(O,Ni(dd(a),!0))||[];S=new Response(fd(S.body,Mg,A,()=>{M&&M(),f&&f()}),x)}l=l||"text";let R=await xa[I.findKey(xa,l)||"text"](S,e);return!k&&f&&f(),await new Promise((x,O)=>{No(x,O,{data:R,headers:at.from(S.headers),status:S.status,statusText:S.statusText,config:e,request:m})})}catch(v){throw f&&f(),v&&v.name==="TypeError"&&/fetch/i.test(v.message)?Object.assign(new le("Network Error",le.ERR_NETWORK,e,m),{cause:v.cause||v}):le.from(v,v&&v.code,e,m)}});var gd={http:_a,xhr:Fg,fetch:jg};I.forEach(gd,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});var Vg=e=>`- ${e}`,__=e=>I.isFunction(e)||e===null||e===!1,Ta={getAdapter:e=>{e=I.isArray(e)?e:[e];let{length:t}=e,r,n,i={};for(let o=0;o<t;o++){r=e[o];let s;if(n=r,!__(r)&&(n=gd[(s=String(r)).toLowerCase()],n===void 0))throw new le(`Unknown adapter '${s}'`);if(n)break;i[s||"#"+o]=n}if(!n){let o=Object.entries(i).map(([a,c])=>`adapter ${a} `+(c===!1?"is not supported by the environment":"is not available in the build")),s=t?o.length>1?`since :
|
|
69
69
|
`+o.map(Vg).join(`
|
|
70
70
|
`):" "+Vg(o[0]):"as no adapter specified";throw new le("There is no suitable adapter to dispatch the request "+s,"ERR_NOT_SUPPORT")}return n},adapters:gd};function yd(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Ur(null,e)}function Ia(e){return yd(e),e.headers=at.from(e.headers),e.data=Lo.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),Ta.getAdapter(e.adapter||Li.adapter)(e).then(function(n){return yd(e),n.data=Lo.call(e,e.transformResponse,n),n.headers=at.from(n.headers),n},function(n){return Mo(n)||(yd(e),n&&n.response&&(n.response.data=Lo.call(e,e.transformResponse,n.response),n.response.headers=at.from(n.response.headers))),Promise.reject(n)})}var Ra="1.8.4";var Pa={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Pa[e]=function(n){return typeof n===e||"a"+(t<1?"n ":" ")+e}});var Hg={};Pa.transitional=function(t,r,n){function i(o,s){return"[Axios v"+Ra+"] Transitional option '"+o+"'"+s+(n?". "+n:"")}return(o,s,a)=>{if(t===!1)throw new le(i(s," has been removed"+(r?" in "+r:"")),le.ERR_DEPRECATED);return r&&!Hg[s]&&(Hg[s]=!0,console.warn(i(s," has been deprecated since v"+r+" and will be removed in the near future"))),t?t(o,s,a):!0}};Pa.spelling=function(t){return(r,n)=>(console.warn(`${n} is likely a misspelling of ${t}`),!0)};function w_(e,t,r){if(typeof e!="object")throw new le("options must be an object",le.ERR_BAD_OPTION_VALUE);let n=Object.keys(e),i=n.length;for(;i-- >0;){let o=n[i],s=t[o];if(s){let a=e[o],c=a===void 0||s(a,o,e);if(c!==!0)throw new le("option "+o+" must be "+c,le.ERR_BAD_OPTION_VALUE);continue}if(r!==!0)throw new le("Unknown option "+o,le.ERR_BAD_OPTION)}}var jo={assertOptions:w_,validators:Pa};var Fr=jo.validators,zi=class{constructor(t){this.defaults=t,this.interceptors={request:new rd,response:new rd}}async request(t,r){try{return await this._request(t,r)}catch(n){if(n instanceof Error){let i={};Error.captureStackTrace?Error.captureStackTrace(i):i=new Error;let o=i.stack?i.stack.replace(/^.+\n/,""):"";try{n.stack?o&&!String(n.stack).endsWith(o.replace(/^.+\n.+\n/,""))&&(n.stack+=`
|
|
71
|
-
`+o):n.stack=o}catch{}}throw n}}_request(t,r){typeof t=="string"?(r=r||{},r.url=t):r=t||{},r=vr(this.defaults,r);let{transitional:n,paramsSerializer:i,headers:o}=r;n!==void 0&&jo.assertOptions(n,{silentJSONParsing:Fr.transitional(Fr.boolean),forcedJSONParsing:Fr.transitional(Fr.boolean),clarifyTimeoutError:Fr.transitional(Fr.boolean)},!1),i!=null&&(I.isFunction(i)?r.paramsSerializer={serialize:i}:jo.assertOptions(i,{encode:Fr.function,serialize:Fr.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),jo.assertOptions(r,{baseUrl:Fr.spelling("baseURL"),withXsrfToken:Fr.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let s=o&&I.merge(o.common,o[r.method]);o&&I.forEach(["delete","get","head","post","put","patch","common"],m=>{delete o[m]}),r.headers=at.concat(s,o);let a=[],c=!0;this.interceptors.request.forEach(function(f){typeof f.runWhen=="function"&&f.runWhen(r)===!1||(c=c&&f.synchronous,a.unshift(f.fulfilled,f.rejected))});let l=[];this.interceptors.response.forEach(function(f){l.push(f.fulfilled,f.rejected)});let h,d=0,g;if(!c){let m=[Ia.bind(this),void 0];for(m.unshift.apply(m,a),m.push.apply(m,l),g=m.length,h=Promise.resolve(r);d<g;)h=h.then(m[d++],m[d++]);return h}g=a.length;let p=r;for(d=0;d<g;){let m=a[d++],f=a[d++];try{p=m(p)}catch(b){f.call(this,b);break}}try{h=Ia.call(this,p)}catch(m){return Promise.reject(m)}for(d=0,g=l.length;d<g;)h=h.then(l[d++],l[d++]);return h}getUri(t){t=vr(this.defaults,t);let r=zo(t.baseURL,t.url,t.allowAbsoluteUrls);return Uo(r,t.params,t.paramsSerializer)}};I.forEach(["delete","get","head","options"],function(t){zi.prototype[t]=function(r,n){return this.request(vr(n||{},{method:t,url:r,data:(n||{}).data}))}});I.forEach(["post","put","patch"],function(t){function r(n){return function(o,s,a){return this.request(vr(a||{},{method:t,headers:n?{"Content-Type":"multipart/form-data"}:{},url:o,data:s}))}}zi.prototype[t]=r(),zi.prototype[t+"Form"]=r(!0)});var Vo=zi;var bd=class e{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(o){r=o});let n=this;this.promise.then(i=>{if(!n._listeners)return;let o=n._listeners.length;for(;o-- >0;)n._listeners[o](i);n._listeners=null}),this.promise.then=i=>{let o,s=new Promise(a=>{n.subscribe(a),o=a}).then(i);return s.cancel=function(){n.unsubscribe(o)},s},t(function(o,s,a){n.reason||(n.reason=new Ur(o,s,a),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;let r=this._listeners.indexOf(t);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){let t=new AbortController,r=n=>{t.abort(n)};return this.subscribe(r),t.signal.unsubscribe=()=>this.unsubscribe(r),t.signal}static source(){let t;return{token:new e(function(i){t=i}),cancel:t}}},Wg=bd;function vd(e){return function(r){return e.apply(null,r)}}function _d(e){return I.isObject(e)&&e.isAxiosError===!0}var wd={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(wd).forEach(([e,t])=>{wd[t]=e});var $g=wd;function qg(e){let t=new Vo(e),r=Do(Vo.prototype.request,t);return I.extend(r,Vo.prototype,t,{allOwnKeys:!0}),I.extend(r,t,null,{allOwnKeys:!0}),r.create=function(i){return qg(vr(e,i))},r}var rt=qg(Li);rt.Axios=Vo;rt.CanceledError=Ur;rt.CancelToken=Wg;rt.isCancel=Mo;rt.VERSION=Ra;rt.toFormData=mn;rt.AxiosError=le;rt.Cancel=rt.CanceledError;rt.all=function(t){return Promise.all(t)};rt.spread=vd;rt.isAxiosError=_d;rt.mergeConfig=vr;rt.AxiosHeaders=at;rt.formToJSON=e=>ka(I.isHTMLForm(e)?new FormData(e):e);rt.getAdapter=Ta.getAdapter;rt.HttpStatusCode=$g;rt.default=rt;var Wt=rt;var{Axios:LC,AxiosError:MC,CanceledError:NC,isCancel:zC,CancelToken:jC,VERSION:VC,all:HC,Cancel:WC,isAxiosError:$C,spread:qC,toFormData:GC,AxiosHeaders:KC,HttpStatusCode:XC,formToJSON:JC,getAdapter:YC,mergeConfig:ZC}=Wt;var S_="https://proctoring-api-dev.easyproctor.tech/api",k_="https://proctoring-api-hml.easyproctor.tech/api",Gg="https://proctoring-api.easyproctor.tech/api",E_="https://easyproctor-realtime-api-dev.easyproctor.tech/api",C_="https://easyproctor-realtime-api-hml.easyproctor.tech/api",x_="https://easyproctor-realtime-api.easyproctor.tech/api",ir=class{constructor(t){this.options=t;this.baseUrl=this.selectBaseUrl(t.type,t.isRealtime),this.token=t.token}getBaseUrl(){return this.baseUrl}selectBaseUrl(t,r){return r?t==="dev"?E_:t==="homol"?C_:x_:t==="dev"?S_:t==="homol"?k_:Gg}setRealtime(t){this.baseUrl=this.selectBaseUrl(this.options.type,t)}getSocketUrl(){return this.baseUrl.replace("/api","/hub/sockethub")}async loginAuth(t,r){return await this.makeRequest({path:"/Auth",method:"POST",body:{emailOrCpf:t,key:r}})}async externalCameraRegister(t){return await this.makeRequest({path:"/ExternalCamera/register",method:"POST",body:t,jwt:this.token})}async externalCameraCheckTransmission(t){return await this.makeRequest({path:`/ExternalCamera/send-action/${t}`,method:"POST",body:{command:"Check_Transmission"},jwt:this.token})}async externalCameraStartTransmission(t,r){return await this.makeRequest({path:`/ExternalCamera/start-transmission/${t}`,method:"POST",body:{proctoringId:r},jwt:this.token})}async externalCameraStartSession(){return await this.makeRequest({path:"/ExternalCamera/start-session",method:"POST",body:{},jwt:this.token})}async goToExternalCameraPositionStep(t){return await this.makeRequest({path:`/ExternalCamera/go-to-position-step/${t}`,method:"POST",body:{},jwt:this.token})}async externalCameraFinish(t){return await this.makeRequest({path:`/ExternalCamera/finish/${t}`,method:"POST",body:{},jwt:this.token})}async confirmStart(t,r,n,i){return await this.makeRequest({path:`/proctoring/start/${t.examId}`,method:"POST",body:{clientId:t.clientId,proctoringType:r.proctoringType,latitude:n,longitude:i,captureScreen:r.captureScreen},jwt:t.token})}async getParamsConfig(t){return(await this.makeRequestAxios({path:"/Client/params",method:"GET",jwt:t.token}).catch(n=>{throw"N\xE3o foi poss\xEDvel realizar a requisi\xE7\xE3o, tente novamente mais tarde"})).data}async getSignedUrlImage(t,r){return(await this.makeRequestAxios({path:"/upload/signed-url-batch",method:"POST",jwt:t,body:r})).data}async getSignedUrl(t,r,n){return(await this.makeRequestAxios({path:"/upload/signed-url",method:"POST",jwt:t,body:{objectName:`${n}/${r.name}`,contentType:r.type}})).data}async initiateUpload(t,r,n){return(await this.makeRequestAxios({path:"/upload/initiate-upload",method:"POST",jwt:t,body:{objectName:r,contentType:n}})).data}async saveAlerts(t,r){await this.makeRequest({path:"/proctoring/save-alerts",method:"POST",jwt:t.token,body:{proctoringId:r.id,alerts:r.alerts}})}async finishAndSendUrls(t){return await this.makeRequest({path:`/proctoring/finish/${t.examId}`,method:"POST",body:{endDate:new Date().toISOString(),videoCameraUrl:"",audioCameraUrl:"",videoScreenUrl:""},jwt:t.token})}async log(t,r){let n;return r?.success!==null&&r?.success!==void 0?n=r.success?"4":"1":n="4",await this.makeRequest({path:"/Log",method:"POST",body:{entryType:n,eventName:t,message:r},jwt:this.token})}async signTerm(){return await this.makeRequest({path:"/User/sign-terms",method:"PATCH",body:{},jwt:this.token})}async signTermUrl(){return(await this.makeRequestAxios({path:"/User/sign-terms-url",method:"GET",jwt:this.token})).data}async startChallenge(t){return(await this.makeRequestAxios({path:"/Challenge/start",method:"POST",jwt:this.token,body:t})).data}async stopChallenge(t,r){return(await this.makeRequestAxios({path:`/Challenge/stop/${t}`,method:"POST",jwt:this.token,body:r})).data}async startRealtimeAlert(t){return(await this.makeRequestAxios({path:"/Realtime/start-warning",method:"POST",jwt:this.token,body:t})).data}async stopRealtimeAlert(t){return(await this.makeRequestAxios({path:"/Realtime/stop-warning",method:"POST",jwt:this.token,body:t})).data}async verifyFace(t,r,n){return(await this.makeRequestAxios({path:"/Realtime/verify-face",method:"POST",jwt:this.token,body:{proctoringId:t,base64:r,retry:n}})).data}async checkUpload(t,r,n){try{return(await this.makeRequestAxios({path:"/Upload/check",method:"POST",jwt:t,body:{objectName:r,contentType:n}})).data===!0}catch{return!1}}async getServerHour(t){return await this.makeRequest({path:"/Proctoring/server-hour",method:"GET",jwt:t})}async makeRequest(t){let{path:r,method:n,body:i,jwt:o}=t,s=await fetch(this.baseUrl+r,{method:n,body:i!=null?JSON.stringify(i):void 0,headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}});if(s.status>=400)throw"N\xE3o foi poss\xEDvel realizar a requisi\xE7\xE3o, tente novamente mais tarde";let a=s.headers.get("content-type");return(a?a.includes("application/json"):!1)?await s.json():null}async makeRequestAxios(t){let{path:r,method:n,body:i,jwt:o}=t,s=await Wt.request({url:this.baseUrl+r,method:n,headers:{Authorization:`Bearer ${o}`,"Access-Control-Allow-Origin":"*"},data:i});if(s.status>=400)throw"N\xE3o foi poss\xEDvel realizar a requisi\xE7\xE3o, tente novamente mais tarde";return s}async makeRequestPUT(t){let{url:r,method:n,body:i,jwt:o}=t,s=await fetch(r,{method:n,body:i!=null?JSON.stringify(i):void 0,headers:{Accept:"*/*","Accept-Encoding":"gzip, deflate, br",Connection:"keep-alive","aeg-event-type":"Notification","Content-Type":"application/json","Cache-Control":"no-cache","x-ms-blob-type":"BlockBlob"}});if(s.status>=400)throw"N\xE3o foi poss\xEDvel realizar a requisi\xE7\xE3o, tente novamente mais tarde";let a=s.headers.get("content-type");return(a?a.includes("application/json"):!1)?await s.json():null}};var Da=class{constructor(){this.baseUrl="https://localhost:5080"}async isAlive(){return(await this.makeRequestAxios({path:"/api/usb-device-manager/is-alive",method:"GET",jwt:this.token}).catch(r=>{throw"N\xE3o foi poss\xEDvel realizar a requisi\xE7\xE3o, tente novamente mais tarde"})).data}async isPluggedIn(){return(await this.makeRequestAxios({path:"/api/usb-device-manager/is-plugged-in",method:"GET",jwt:this.token}).catch(r=>{throw"N\xE3o foi poss\xEDvel realizar a requisi\xE7\xE3o, tente novamente mais tarde"})).data}async ConnectAndScan(){return(await this.makeRequestAxios({path:"/api/usb-device-manager/connect-and-scan",method:"GET",jwt:this.token}).catch(r=>{throw"N\xE3o foi poss\xEDvel realizar a requisi\xE7\xE3o, tente novamente mais tarde"})).data}async Devices({deviceType:t,rssiThreshold:r,packageRateThreshold:n}){let i=[];return t&&i.push(`deviceType=${t}`),r&&i.push(`rssiThreshold=${r}`),n&&i.push(`packageRateThreshold=${n}`),(await this.makeRequestAxios({path:`/api/usb-device-manager/devices?${i.join("&")}`,method:"GET",jwt:this.token}).catch(s=>{throw"N\xE3o foi poss\xEDvel realizar a requisi\xE7\xE3o, tente novamente mais tarde"})).data}async makeRequestAxios(t){let{path:r,method:n,body:i,jwt:o}=t,s=await Wt.request({url:this.baseUrl+r,method:n,headers:{Authorization:`Bearer ${o}`,"Access-Control-Allow-Origin":"*"},data:i});if(s.status>=400)throw"N\xE3o foi poss\xEDvel realizar a requisi\xE7\xE3o, tente novamente mais tarde";return s}};var Vn=class{constructor(){this.sessionDuration=0;this.state="Created",this.startedAt=new Date,this.alerts=[],this.recordings=[]}get hasSomethingToUpload(){for(let t of this.recordings)if(!t.upload)return!0;return!1}start(){this.state="Recording",this.startedAt=new Date(Date.now())}pause(){this.state="Paused"}resume(){this.state="Recording"}stop(){this.state="Ended",this.sessionDuration=Date.now()-this.startedAt.getTime()}setProctoringId(t){this.id=t}setEndConfirmed(){this.state="EndConfirmed"}setUploaded(){this.state="Uploaded"}setUploadConfirmed(){this.state="UploadConfirmed"}addAlert(t){this.alerts.push(t)}addRecording(t){this.recordings.push(t)}};var ji=class{constructor(t,r){this.backendService=new Da;this.scanInterval=5;this.options={};this.options=r,this.context=t,this.backend=new ir({type:t?.type||"prod",token:t.token,isRealtime:!1}),this.currentIsPlugged=!0}setProctoringId(t){this.proctoringId=t}async isPluggedIn(t=!1){try{let r=await this.backendService.isPluggedIn();if(this.proctoringId&&t)if(r)this.currentIsPlugged||this.options.onRealtimeAlertsCallback?.({type:"spycam",message:"Spycam disconnected",description:"Dispositivo de varredura conectado.",status:"OK"});else{let n=new Vn;n.setProctoringId(this.proctoringId),n.addAlert({begin:Date.now()-this.startTime.getTime(),end:0,alert:33,type:5}),await this.backend.saveAlerts(this.context,n),this.options.onRealtimeAlertsCallback?.({type:"spycam",message:"Spycam disconnected",description:"Nenhum dispositivo de varredura conectado.",status:"ALERT"})}return this.currentIsPlugged=r,this.currentIsPlugged}catch(r){throw r}}async isAlive(){try{return await this.backendService.isAlive()}catch(t){throw t}}connectAndScan(){return this.backendService.ConnectAndScan()}async devices({deviceType:t,rssiThreshold:r,packageRateThreshold:n}){let i=await this.backendService.Devices({deviceType:t,rssiThreshold:r,packageRateThreshold:n});if(i.length>0&&(this.options.onRealtimeAlertsCallback?.({type:"spycam",message:"Spycam detected",description:"Dispositivo espi\xE3o detectado.",data:i}),this.proctoringId)){let o=new Vn;o.setProctoringId(this.proctoringId),o.addAlert({begin:Date.now()-this.startTime.getTime(),end:0,alert:32,type:5}),await this.backend.saveAlerts(this.context,o)}return i}async startCheckSpyCam(t,{deviceType:r,rssiThreshold:n,packageRateThreshold:i}){this.scanInterval=t,this.startTime=new Date(Date.now()),await this.isPluggedIn(!0),this.checkSpyCam=setInterval(async()=>{await this.isPluggedIn(!0)&&await this.devices({deviceType:r,rssiThreshold:n,packageRateThreshold:i})},this.scanInterval*6e4)}stopCheckSpyCam(){clearInterval(this.checkSpyCam)}};var or={cameraId:void 0,microphoneId:void 0,allowMultipleMonitors:!1,allowOnlyFirstMonitor:!0,captureScreen:!0,noiseLimit:40,proctoringType:"VIDEO",insights:"",onBufferSizeError:!1,useGeolocation:!1,useSpyScan:!1,useExternalCamera:!1,useChallenge:!1,auto:!1};function Ba(e){return e.width&&e.height?{width:e.width,height:e.height,minWidth:e.minWidth,minHeight:e.minHeight}:{width:640,height:480}}var Kg={width:1280,height:720,minWidth:640,minHeight:480};function Hn(){let e=window.navigator.userAgent.split("SEB/");return e.length>1?e[1]:"1.0.0.0"}function Xg(){let e=navigator.userAgent,t;return e.match(/chrome|chromium|crios/i)?t="chrome":e.match(/firefox|fxios/i)?t="firefox":e.match(/safari/i)?t="safari":e.match(/opr\//i)?t="opera":e.match(/edg/i)?t="edge":t="No browser detection",t}function _r(){if("userAgentData"in navigator){let e=navigator.userAgentData,t=e.mobile||!1,r=e.platform||"";return t||/Android|iOS/i.test(r)}return/Android|iPhone|iPad|iPod/i.test(navigator.userAgent)}function Jg(){return Hn()!=="1.0.0.0"}var A_;function Oa(e){A_=e}function Ho(e,t,r=!1,n,i){let o,s,a,c;c=0;let l,h=0,d=0,g={mimeType:"video/webm",videoBitsPerSecond:25e4*(i?.quality||1),audioBitsPerSecond:64*1e3};console.log("recorderOptions",g),MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?g.mimeType="video/webm;codecs=vp9":console.warn("vp9 codec not supported. Using default mimeType without vp9.");function p(A,M){let J=A.getTracks();if(J.length==0)throw new Error("No tracks found");let E=J.find(y=>y.readyState!="live");if(E)throw new Error("Track not live: "+E.label);console.log("buildMediaRecorder tracks OK");let D=new MediaRecorder(A,M);return console.log("buildMediaRecorder mediaRecorder OK"),D.ondataavailable=y=>{c=c+y.data.size,y.data.size>0&&(i?.onChunkAvailable&&(i.onChunkAvailable(y.data,d),d++),t.push(y.data))},D}let m=p(e,g);async function f(A){return new Promise((M,J)=>{let E=!1;A.onstart=()=>{E=!0,console.log("recorder onstart"),l=new Date(Date.now()),M()},A.onerror=D=>{if(console.error("Recorder error event:",D),e.getTracks().forEach(y=>console.log(y.readyState)),"error"in D){let y=D.error;console.error("Error name:",y?.name),console.error("Error message:",y?.message),J(y||D)}else console.warn("Evento sem propriedade error"),J(D)};try{console.log("State antes do start:",A.state),d=0,i?.timeslice&&i?.timeslice>0?A.start(i.timeslice):A.start(1e4),c=0,l=new Date(Date.now())}catch(D){return console.error("Recorder erro ao chamar start event:",D),console.error("Erro real:",D,D?.error,D?.error?.name,D?.error?.message),console.error("Erro real 2:",D,D?.message,D?.name),e.getTracks().forEach(y=>console.log(y.readyState)),J(D)}setTimeout(()=>{E||(console.error("Timeout ao iniciar o recorder"),J(new Error("Timeout ao iniciar o recorder")))},5e3)})}async function b(){try{if(await f(m),m.state==="recording"){c=0;return}else console.log("Recorder n\xE3o est\xE1 em estado recording ap\xF3s start")}catch(A){throw console.error("Erro ao iniciar o recorder:",A),await new Promise(M=>setTimeout(M,300)),A}}function v(){return new Promise(A=>{m.state=="recording"?(console.log("stopRecording Recorder est\xE1 em estado recording, iniciando stop"),o=A,m.onstop=()=>{console.log("recorder onstop"),h=Date.now()-l.getTime()||0,console.log("duration no onstop",h),e.getTracks().forEach(M=>{M.stop()}),o&&o()},m.stop(),h=Date.now()-l.getTime()||0,console.log("duration imediatamente ap\xF3s mediaRecorder.stop()",h)):(console.log("stopRecording Recorder n\xE3o est\xE1 em estado recording"),A()),e.getTracks().forEach(M=>{M.stop()})})}function S(){return new Promise(A=>{m.state=="recording"&&m.pause(),A()})}function k(){return new Promise(A=>{m.state=="paused"&&m.resume(),A()})}function R(){return c}function x(){return l}function O(){return h}return{startRecording:b,stopRecording:v,pauseRecording:S,resumeRecording:k,recorderOptions:g,getBufferSize:R,getStartTime:x,getDuration:O}}var Ua,Yg=e=>(Ua=e,Ua),Pt={DEVICES_CHECKED:"devices_checked",START:"start",FINISH:"finish",ERROR:"error",UPLOAD:"upload",UPLOAD_FILE:"upload_file",DOWNLOAD_VIDEO:"download_video",BUFFER_SIZE:"buffer_size",ANOTHER_STREAM:"another_stream",CHANGE_DEVICE:"change_device",STOP_SHARING_SCREEN:"stop_sharing_screen",ERROR_RECORDER_RTC:"error_recorder_rtc",BROWSER_NOT_SUPPORTED:"browser_not_supported",SAVE_ON_SESSION:"save_on_session"},Dt=(e,t)=>Ua&&Ua.log(e,t),de={registerDevicesChecked:(e,t,r)=>Dt(Pt.DEVICES_CHECKED,{proctoringId:e,success:t,description:r}),registerStart:(e,t,r)=>Dt(Pt.START,{proctoringId:e,success:t,description:r}),registerFinish:(e,t,r)=>Dt(Pt.FINISH,{proctoringId:e,success:t,description:r}),registerError:(e,t)=>Dt(Pt.ERROR,{proctoringId:e,description:t}),registerBrowserNotSupported:(e,t)=>Dt(Pt.BROWSER_NOT_SUPPORTED,{proctoringId:e,description:t}),registerUpload:(e,t,r,n,i)=>Dt(Pt.UPLOAD,{proctoringId:e,success:t,description:r,serviceType:n,uploadTime:i}),registerUploadFile:(e,t,r)=>Dt(Pt.UPLOAD_FILE,{proctoringId:e,description:t,fileType:r}),registerChangeDevice:(e,t,r)=>Dt(Pt.CHANGE_DEVICE,{proctoringId:e,inOrOut:t,description:r}),registerStopSharingScreen:(e,t)=>Dt(Pt.STOP_SHARING_SCREEN,{proctoringId:e,description:t}),registerErrorRecorderRTC:(e,t)=>Dt(Pt.ERROR_RECORDER_RTC,{proctoringId:e,description:t}),registerDownloadFile:(e,t)=>Dt(Pt.DOWNLOAD_VIDEO,{proctoringId:e,description:t}),registerOnBufferSizeError:(e,t)=>Dt(Pt.BUFFER_SIZE,{proctoringId:e,description:t}),registerAnotherStream:(e,t)=>Dt(Pt.ANOTHER_STREAM,{proctoringId:e,description:t}),registerSaveOnSession:(e,t)=>Dt(Pt.SAVE_ON_SESSION,{proctoringId:e,description:t})};var Yr=class{constructor(t,r){this.backend=r;this.imageUrlPackage=[];this.imageBatchNum=0;this.contImages=0;this.proctoringId=t}async uploadPackage(t,r){let{file:n}=t;try{console.log("Upload service: uploadPackage");var i="";return await this.backend.getSignedUrl(r,n,this.proctoringId).then(o=>i=o).catch(o=>{throw o}),console.log("Upload service: uploadUrl",i),await Wt.request({url:i,method:"PUT",headers:{"Content-Type":n.type,"x-ms-blob-type":"BlockBlob"},data:n}).then(()=>!0).catch(o=>{throw o}),!0}catch(o){throw de.registerError(this.proctoringId,`Failed to upload package ${o}
|
|
71
|
+
`+o):n.stack=o}catch{}}throw n}}_request(t,r){typeof t=="string"?(r=r||{},r.url=t):r=t||{},r=vr(this.defaults,r);let{transitional:n,paramsSerializer:i,headers:o}=r;n!==void 0&&jo.assertOptions(n,{silentJSONParsing:Fr.transitional(Fr.boolean),forcedJSONParsing:Fr.transitional(Fr.boolean),clarifyTimeoutError:Fr.transitional(Fr.boolean)},!1),i!=null&&(I.isFunction(i)?r.paramsSerializer={serialize:i}:jo.assertOptions(i,{encode:Fr.function,serialize:Fr.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),jo.assertOptions(r,{baseUrl:Fr.spelling("baseURL"),withXsrfToken:Fr.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let s=o&&I.merge(o.common,o[r.method]);o&&I.forEach(["delete","get","head","post","put","patch","common"],m=>{delete o[m]}),r.headers=at.concat(s,o);let a=[],c=!0;this.interceptors.request.forEach(function(f){typeof f.runWhen=="function"&&f.runWhen(r)===!1||(c=c&&f.synchronous,a.unshift(f.fulfilled,f.rejected))});let l=[];this.interceptors.response.forEach(function(f){l.push(f.fulfilled,f.rejected)});let h,d=0,g;if(!c){let m=[Ia.bind(this),void 0];for(m.unshift.apply(m,a),m.push.apply(m,l),g=m.length,h=Promise.resolve(r);d<g;)h=h.then(m[d++],m[d++]);return h}g=a.length;let p=r;for(d=0;d<g;){let m=a[d++],f=a[d++];try{p=m(p)}catch(b){f.call(this,b);break}}try{h=Ia.call(this,p)}catch(m){return Promise.reject(m)}for(d=0,g=l.length;d<g;)h=h.then(l[d++],l[d++]);return h}getUri(t){t=vr(this.defaults,t);let r=zo(t.baseURL,t.url,t.allowAbsoluteUrls);return Uo(r,t.params,t.paramsSerializer)}};I.forEach(["delete","get","head","options"],function(t){zi.prototype[t]=function(r,n){return this.request(vr(n||{},{method:t,url:r,data:(n||{}).data}))}});I.forEach(["post","put","patch"],function(t){function r(n){return function(o,s,a){return this.request(vr(a||{},{method:t,headers:n?{"Content-Type":"multipart/form-data"}:{},url:o,data:s}))}}zi.prototype[t]=r(),zi.prototype[t+"Form"]=r(!0)});var Vo=zi;var bd=class e{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(o){r=o});let n=this;this.promise.then(i=>{if(!n._listeners)return;let o=n._listeners.length;for(;o-- >0;)n._listeners[o](i);n._listeners=null}),this.promise.then=i=>{let o,s=new Promise(a=>{n.subscribe(a),o=a}).then(i);return s.cancel=function(){n.unsubscribe(o)},s},t(function(o,s,a){n.reason||(n.reason=new Ur(o,s,a),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;let r=this._listeners.indexOf(t);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){let t=new AbortController,r=n=>{t.abort(n)};return this.subscribe(r),t.signal.unsubscribe=()=>this.unsubscribe(r),t.signal}static source(){let t;return{token:new e(function(i){t=i}),cancel:t}}},Wg=bd;function vd(e){return function(r){return e.apply(null,r)}}function _d(e){return I.isObject(e)&&e.isAxiosError===!0}var wd={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(wd).forEach(([e,t])=>{wd[t]=e});var $g=wd;function qg(e){let t=new Vo(e),r=Do(Vo.prototype.request,t);return I.extend(r,Vo.prototype,t,{allOwnKeys:!0}),I.extend(r,t,null,{allOwnKeys:!0}),r.create=function(i){return qg(vr(e,i))},r}var rt=qg(Li);rt.Axios=Vo;rt.CanceledError=Ur;rt.CancelToken=Wg;rt.isCancel=Mo;rt.VERSION=Ra;rt.toFormData=mn;rt.AxiosError=le;rt.Cancel=rt.CanceledError;rt.all=function(t){return Promise.all(t)};rt.spread=vd;rt.isAxiosError=_d;rt.mergeConfig=vr;rt.AxiosHeaders=at;rt.formToJSON=e=>ka(I.isHTMLForm(e)?new FormData(e):e);rt.getAdapter=Ta.getAdapter;rt.HttpStatusCode=$g;rt.default=rt;var Wt=rt;var{Axios:LC,AxiosError:MC,CanceledError:NC,isCancel:zC,CancelToken:jC,VERSION:VC,all:HC,Cancel:WC,isAxiosError:$C,spread:qC,toFormData:GC,AxiosHeaders:KC,HttpStatusCode:XC,formToJSON:JC,getAdapter:YC,mergeConfig:ZC}=Wt;var S_="https://proctoring-api-dev.easyproctor.tech/api",k_="https://proctoring-api-hml.easyproctor.tech/api",Gg="https://proctoring-api.easyproctor.tech/api",E_="https://easyproctor-realtime-api-dev.easyproctor.tech/api",C_="https://easyproctor-realtime-api-hml.easyproctor.tech/api",x_="https://easyproctor-realtime-api.easyproctor.tech/api",ir=class{constructor(t){this.options=t;this.baseUrl=this.selectBaseUrl(t.type,t.isRealtime),this.token=t.token}getBaseUrl(){return this.baseUrl}selectBaseUrl(t,r){return r?t==="dev"?E_:t==="homol"?C_:x_:t==="dev"?S_:t==="homol"?k_:Gg}setRealtime(t){this.baseUrl=this.selectBaseUrl(this.options.type,t)}getSocketUrl(){return this.baseUrl.replace("/api","/hub/sockethub")}async loginAuth(t,r){return await this.makeRequest({path:"/Auth",method:"POST",body:{emailOrCpf:t,key:r}})}async externalCameraRegister(t){return await this.makeRequest({path:"/ExternalCamera/register",method:"POST",body:t,jwt:this.token})}async externalCameraCheckTransmission(t){return await this.makeRequest({path:`/ExternalCamera/send-action/${t}`,method:"POST",body:{command:"Check_Transmission"},jwt:this.token})}async externalCameraStartTransmission(t,r){return await this.makeRequest({path:`/ExternalCamera/start-transmission/${t}`,method:"POST",body:{proctoringId:r},jwt:this.token})}async externalCameraStartSession(){return await this.makeRequest({path:"/ExternalCamera/start-session",method:"POST",body:{},jwt:this.token})}async goToExternalCameraPositionStep(t){return await this.makeRequest({path:`/ExternalCamera/go-to-position-step/${t}`,method:"POST",body:{},jwt:this.token})}async externalCameraFinish(t){return await this.makeRequest({path:`/ExternalCamera/finish/${t}`,method:"POST",body:{},jwt:this.token})}async confirmStart(t,r,n,i){return await this.makeRequest({path:`/proctoring/start/${t.examId}`,method:"POST",body:{clientId:t.clientId,proctoringType:r.proctoringType,latitude:n,longitude:i,captureScreen:r.captureScreen},jwt:t.token})}async getParamsConfig(t){return(await this.makeRequestAxios({path:"/Client/params",method:"GET",jwt:t.token}).catch(n=>{throw"N\xE3o foi poss\xEDvel realizar a requisi\xE7\xE3o, tente novamente mais tarde"})).data}async getSignedUrlImage(t,r){return(await this.makeRequestAxios({path:"/upload/signed-url-batch",method:"POST",jwt:t,body:r})).data}async getSignedUrl(t,r,n){return(await this.makeRequestAxios({path:"/upload/signed-url",method:"POST",jwt:t,body:{objectName:`${n}/${r.name}`,contentType:r.type}})).data}async initiateUpload(t,r,n){return(await this.makeRequestAxios({path:"/upload/initiate-upload",method:"POST",jwt:t,body:{objectName:r,contentType:n}})).data}async saveAlerts(t,r){await this.makeRequest({path:"/proctoring/save-alerts",method:"POST",jwt:t.token,body:{proctoringId:r.id,alerts:r.alerts}})}async finishAndSendUrls(t){return await this.makeRequest({path:`/proctoring/finish/${t.examId}`,method:"POST",body:{endDate:new Date().toISOString(),videoCameraUrl:"",audioCameraUrl:"",videoScreenUrl:""},jwt:t.token})}async log(t,r){let n;return r?.success!==null&&r?.success!==void 0?n=r.success?"4":"1":n="4",await this.makeRequest({path:"/Log",method:"POST",body:{entryType:n,eventName:t,message:r},jwt:this.token})}async signTerm(){return await this.makeRequest({path:"/User/sign-terms",method:"PATCH",body:{},jwt:this.token})}async signTermUrl(){return(await this.makeRequestAxios({path:"/User/sign-terms-url",method:"GET",jwt:this.token})).data}async startChallenge(t){return(await this.makeRequestAxios({path:"/Challenge/start",method:"POST",jwt:this.token,body:t})).data}async stopChallenge(t,r){return(await this.makeRequestAxios({path:`/Challenge/stop/${t}`,method:"POST",jwt:this.token,body:r})).data}async startRealtimeAlert(t){return(await this.makeRequestAxios({path:"/Realtime/start-warning",method:"POST",jwt:this.token,body:t})).data}async stopRealtimeAlert(t){return(await this.makeRequestAxios({path:"/Realtime/stop-warning",method:"POST",jwt:this.token,body:t})).data}async verifyFace(t,r,n){return(await this.makeRequestAxios({path:"/Realtime/verify-face",method:"POST",jwt:this.token,body:{proctoringId:t,base64:r,retry:n}})).data}async checkUpload(t,r,n){try{return(await this.makeRequestAxios({path:"/Upload/check",method:"POST",jwt:t,body:{objectName:r,contentType:n}})).data===!0}catch{return!1}}async getServerHour(t){return await this.makeRequest({path:"/Proctoring/server-hour",method:"GET",jwt:t})}async makeRequest(t){let{path:r,method:n,body:i,jwt:o}=t,s=await fetch(this.baseUrl+r,{method:n,body:i!=null?JSON.stringify(i):void 0,headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}});if(s.status>=400)throw"N\xE3o foi poss\xEDvel realizar a requisi\xE7\xE3o, tente novamente mais tarde";let a=s.headers.get("content-type");return(a?a.includes("application/json"):!1)?await s.json():null}async makeRequestAxios(t){let{path:r,method:n,body:i,jwt:o}=t,s=await Wt.request({url:this.baseUrl+r,method:n,headers:{Authorization:`Bearer ${o}`,"Access-Control-Allow-Origin":"*"},data:i});if(s.status>=400)throw"N\xE3o foi poss\xEDvel realizar a requisi\xE7\xE3o, tente novamente mais tarde";return s}async makeRequestPUT(t){let{url:r,method:n,body:i,jwt:o}=t,s=await fetch(r,{method:n,body:i!=null?JSON.stringify(i):void 0,headers:{Accept:"*/*","Accept-Encoding":"gzip, deflate, br",Connection:"keep-alive","aeg-event-type":"Notification","Content-Type":"application/json","Cache-Control":"no-cache","x-ms-blob-type":"BlockBlob"}});if(s.status>=400)throw"N\xE3o foi poss\xEDvel realizar a requisi\xE7\xE3o, tente novamente mais tarde";let a=s.headers.get("content-type");return(a?a.includes("application/json"):!1)?await s.json():null}};var Da=class{constructor(){this.baseUrl="https://localhost:5080"}async isAlive(){return(await this.makeRequestAxios({path:"/api/usb-device-manager/is-alive",method:"GET",jwt:this.token}).catch(r=>{throw"N\xE3o foi poss\xEDvel realizar a requisi\xE7\xE3o, tente novamente mais tarde"})).data}async isPluggedIn(){return(await this.makeRequestAxios({path:"/api/usb-device-manager/is-plugged-in",method:"GET",jwt:this.token}).catch(r=>{throw"N\xE3o foi poss\xEDvel realizar a requisi\xE7\xE3o, tente novamente mais tarde"})).data}async ConnectAndScan(){return(await this.makeRequestAxios({path:"/api/usb-device-manager/connect-and-scan",method:"GET",jwt:this.token}).catch(r=>{throw"N\xE3o foi poss\xEDvel realizar a requisi\xE7\xE3o, tente novamente mais tarde"})).data}async Devices({deviceType:t,rssiThreshold:r,packageRateThreshold:n}){let i=[];return t&&i.push(`deviceType=${t}`),r&&i.push(`rssiThreshold=${r}`),n&&i.push(`packageRateThreshold=${n}`),(await this.makeRequestAxios({path:`/api/usb-device-manager/devices?${i.join("&")}`,method:"GET",jwt:this.token}).catch(s=>{throw"N\xE3o foi poss\xEDvel realizar a requisi\xE7\xE3o, tente novamente mais tarde"})).data}async makeRequestAxios(t){let{path:r,method:n,body:i,jwt:o}=t,s=await Wt.request({url:this.baseUrl+r,method:n,headers:{Authorization:`Bearer ${o}`,"Access-Control-Allow-Origin":"*"},data:i});if(s.status>=400)throw"N\xE3o foi poss\xEDvel realizar a requisi\xE7\xE3o, tente novamente mais tarde";return s}};var Vn=class{constructor(){this.sessionDuration=0;this.state="Created",this.startedAt=new Date,this.alerts=[],this.recordings=[]}get hasSomethingToUpload(){for(let t of this.recordings)if(!t.upload)return!0;return!1}start(){this.state="Recording",this.startedAt=new Date(Date.now())}pause(){this.state="Paused"}resume(){this.state="Recording"}stop(){this.state="Ended",this.sessionDuration=Date.now()-this.startedAt.getTime()}setProctoringId(t){this.id=t}setEndConfirmed(){this.state="EndConfirmed"}setUploaded(){this.state="Uploaded"}setUploadConfirmed(){this.state="UploadConfirmed"}addAlert(t){this.alerts.push(t)}addRecording(t){this.recordings.push(t)}};var ji=class{constructor(t,r){this.backendService=new Da;this.scanInterval=5;this.options={};this.options=r,this.context=t,this.backend=new ir({type:t?.type||"prod",token:t.token,isRealtime:!1}),this.currentIsPlugged=!0}setProctoringId(t){this.proctoringId=t}async isPluggedIn(t=!1){try{let r=await this.backendService.isPluggedIn();if(this.proctoringId&&t)if(r)this.currentIsPlugged||this.options.onRealtimeAlertsCallback?.({type:"spycam",message:"Spycam disconnected",description:"Dispositivo de varredura conectado.",status:"OK"});else{let n=new Vn;n.setProctoringId(this.proctoringId),n.addAlert({begin:Date.now()-this.startTime.getTime(),end:0,alert:33,type:5}),await this.backend.saveAlerts(this.context,n),this.options.onRealtimeAlertsCallback?.({type:"spycam",message:"Spycam disconnected",description:"Nenhum dispositivo de varredura conectado.",status:"ALERT"})}return this.currentIsPlugged=r,this.currentIsPlugged}catch(r){throw r}}async isAlive(){try{return await this.backendService.isAlive()}catch(t){throw t}}connectAndScan(){return this.backendService.ConnectAndScan()}async devices({deviceType:t,rssiThreshold:r,packageRateThreshold:n}){let i=await this.backendService.Devices({deviceType:t,rssiThreshold:r,packageRateThreshold:n});if(i.length>0&&(this.options.onRealtimeAlertsCallback?.({type:"spycam",message:"Spycam detected",description:"Dispositivo espi\xE3o detectado.",data:i}),this.proctoringId)){let o=new Vn;o.setProctoringId(this.proctoringId),o.addAlert({begin:Date.now()-this.startTime.getTime(),end:0,alert:32,type:5}),await this.backend.saveAlerts(this.context,o)}return i}async startCheckSpyCam(t,{deviceType:r,rssiThreshold:n,packageRateThreshold:i}){this.scanInterval=t,this.startTime=new Date(Date.now()),await this.isPluggedIn(!0),this.checkSpyCam=setInterval(async()=>{await this.isPluggedIn(!0)&&await this.devices({deviceType:r,rssiThreshold:n,packageRateThreshold:i})},this.scanInterval*6e4)}stopCheckSpyCam(){clearInterval(this.checkSpyCam)}};var or={cameraId:void 0,microphoneId:void 0,allowMultipleMonitors:!1,allowOnlyFirstMonitor:!0,captureScreen:!0,noiseLimit:40,proctoringType:"VIDEO",insights:"",onBufferSizeError:!1,useGeolocation:!1,useSpyScan:!1,useExternalCamera:!1,useChallenge:!1,auto:!1};function Ba(e){return e.width&&e.height?{width:e.width,height:e.height,minWidth:e.minWidth,minHeight:e.minHeight}:{width:640,height:480}}var Kg={width:1280,height:720,minWidth:640,minHeight:480};function Hn(){let e=window.navigator.userAgent.split("SEB/");return e.length>1?e[1]:"1.0.0.0"}function Xg(){let e=navigator.userAgent,t;return e.match(/chrome|chromium|crios/i)?t="chrome":e.match(/firefox|fxios/i)?t="firefox":e.match(/safari/i)?t="safari":e.match(/opr\//i)?t="opera":e.match(/edg/i)?t="edge":t="No browser detection",t}function _r(){if("userAgentData"in navigator){let e=navigator.userAgentData,t=e.mobile||!1,r=e.platform||"";return t||/Android|iOS/i.test(r)}return/Android|iPhone|iPad|iPod/i.test(navigator.userAgent)}function Jg(){return Hn()!=="1.0.0.0"}var A_;function Oa(e){A_=e}function Ho(e,t,r=!1,n,i){let o,s,a,c;c=0;let l,h=0,d=0,g={mimeType:"video/webm",videoBitsPerSecond:25e4*(i?.quality||1),audioBitsPerSecond:64*1e3};console.log("recorderOptions",g),MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?g.mimeType="video/webm;codecs=vp9":console.warn("vp9 codec not supported. Using default mimeType without vp9.");function p(A,M){let J=A.getTracks();if(J.length==0)throw new Error("No tracks found");let E=J.find(y=>y.readyState!="live");if(E)throw new Error("Track not live: "+E.label);console.log("buildMediaRecorder tracks OK");let D=new MediaRecorder(A,M);return console.log("buildMediaRecorder mediaRecorder OK"),D.ondataavailable=y=>{c=c+y.data.size,y.data.size>0&&(i?.onChunkAvailable&&(i.onChunkAvailable(y.data,d),d++),t.push(y.data))},D}let m=p(e,g);async function f(A){return new Promise((M,J)=>{let E=!1;A.onstart=()=>{E=!0,console.log("recorder onstart"),l=new Date(Date.now()),M()},A.onerror=D=>{if(console.error("Recorder error event:",D),e.getTracks().forEach(y=>console.log(y.readyState)),"error"in D){let y=D.error;console.error("Error name:",y?.name),console.error("Error message:",y?.message),J(y||D)}else console.warn("Evento sem propriedade error"),J(D)};try{console.log("State antes do start:",A.state),d=0,i?.timeslice&&i?.timeslice>0?A.start(i.timeslice):A.start(1e4),c=0,l=new Date(Date.now())}catch(D){return console.error("Recorder erro ao chamar start event:",D),console.error("Erro real:",D,D?.error,D?.error?.name,D?.error?.message),console.error("Erro real 2:",D,D?.message,D?.name),e.getTracks().forEach(y=>console.log(y.readyState)),J(D)}setTimeout(()=>{E||(console.error("Timeout ao iniciar o recorder"),J(new Error("Timeout ao iniciar o recorder")))},1e4*(i?.timeoutMultiplierFactor||1))})}async function b(){try{if(await f(m),m.state==="recording"){c=0;return}else console.log("Recorder n\xE3o est\xE1 em estado recording ap\xF3s start")}catch(A){throw console.error("Erro ao iniciar o recorder:",A),await new Promise(M=>setTimeout(M,300)),A}}function v(){return new Promise(A=>{m.state=="recording"?(console.log("stopRecording Recorder est\xE1 em estado recording, iniciando stop"),o=A,m.onstop=()=>{console.log("recorder onstop"),h=Date.now()-l.getTime()||0,console.log("duration no onstop",h),e.getTracks().forEach(M=>{M.stop()}),o&&o()},m.stop(),h=Date.now()-l.getTime()||0,console.log("duration imediatamente ap\xF3s mediaRecorder.stop()",h)):(console.log("stopRecording Recorder n\xE3o est\xE1 em estado recording"),A()),e.getTracks().forEach(M=>{M.stop()})})}function S(){return new Promise(A=>{m.state=="recording"&&m.pause(),A()})}function k(){return new Promise(A=>{m.state=="paused"&&m.resume(),A()})}function R(){return c}function x(){return l}function O(){return h}return{startRecording:b,stopRecording:v,pauseRecording:S,resumeRecording:k,recorderOptions:g,getBufferSize:R,getStartTime:x,getDuration:O}}var Ua,Yg=e=>(Ua=e,Ua),Pt={DEVICES_CHECKED:"devices_checked",START:"start",FINISH:"finish",ERROR:"error",UPLOAD:"upload",UPLOAD_FILE:"upload_file",DOWNLOAD_VIDEO:"download_video",BUFFER_SIZE:"buffer_size",ANOTHER_STREAM:"another_stream",CHANGE_DEVICE:"change_device",STOP_SHARING_SCREEN:"stop_sharing_screen",ERROR_RECORDER_RTC:"error_recorder_rtc",BROWSER_NOT_SUPPORTED:"browser_not_supported",SAVE_ON_SESSION:"save_on_session"},Dt=(e,t)=>Ua&&Ua.log(e,t),de={registerDevicesChecked:(e,t,r)=>Dt(Pt.DEVICES_CHECKED,{proctoringId:e,success:t,description:r}),registerStart:(e,t,r)=>Dt(Pt.START,{proctoringId:e,success:t,description:r}),registerFinish:(e,t,r)=>Dt(Pt.FINISH,{proctoringId:e,success:t,description:r}),registerError:(e,t)=>Dt(Pt.ERROR,{proctoringId:e,description:t}),registerBrowserNotSupported:(e,t)=>Dt(Pt.BROWSER_NOT_SUPPORTED,{proctoringId:e,description:t}),registerUpload:(e,t,r,n,i)=>Dt(Pt.UPLOAD,{proctoringId:e,success:t,description:r,serviceType:n,uploadTime:i}),registerUploadFile:(e,t,r)=>Dt(Pt.UPLOAD_FILE,{proctoringId:e,description:t,fileType:r}),registerChangeDevice:(e,t,r)=>Dt(Pt.CHANGE_DEVICE,{proctoringId:e,inOrOut:t,description:r}),registerStopSharingScreen:(e,t)=>Dt(Pt.STOP_SHARING_SCREEN,{proctoringId:e,description:t}),registerErrorRecorderRTC:(e,t)=>Dt(Pt.ERROR_RECORDER_RTC,{proctoringId:e,description:t}),registerDownloadFile:(e,t)=>Dt(Pt.DOWNLOAD_VIDEO,{proctoringId:e,description:t}),registerOnBufferSizeError:(e,t)=>Dt(Pt.BUFFER_SIZE,{proctoringId:e,description:t}),registerAnotherStream:(e,t)=>Dt(Pt.ANOTHER_STREAM,{proctoringId:e,description:t}),registerSaveOnSession:(e,t)=>Dt(Pt.SAVE_ON_SESSION,{proctoringId:e,description:t})};var Yr=class{constructor(t,r){this.backend=r;this.imageUrlPackage=[];this.imageBatchNum=0;this.contImages=0;this.proctoringId=t}async uploadPackage(t,r){let{file:n}=t;try{console.log("Upload service: uploadPackage");var i="";return await this.backend.getSignedUrl(r,n,this.proctoringId).then(o=>i=o).catch(o=>{throw o}),console.log("Upload service: uploadUrl",i),await Wt.request({url:i,method:"PUT",headers:{"Content-Type":n.type,"x-ms-blob-type":"BlockBlob"},data:n}).then(()=>!0).catch(o=>{throw o}),!0}catch(o){throw de.registerError(this.proctoringId,`Failed to upload package ${o}
|
|
72
72
|
File name: ${n.name}
|
|
73
73
|
File type: ${n.type}
|
|
74
74
|
File size: ${n.size}`),o}}async uploadImages(t,r,n){let{file:i,onProgress:o}=t;try{let s=l=>{let h=l.loadedBytes/i.size*100;o&&o(Math.round(h))},a;if(this.imageBatchNum===this.contImages){let l=[];for(let d=this.imageBatchNum;d<this.imageBatchNum+60;d++){let g=`${this.proctoringId}/${this.proctoringId}_${d+1}.jpg`;(d+1)%n==0&&(g=`${this.proctoringId}/${this.proctoringId}_${d+1}_realtime.jpg`),l.push({objectName:g,contentType:"image/jpeg"})}(await this.backend.getSignedUrlImage(r,l)).map(d=>{this.imageUrlPackage.push(d)}),this.imageBatchNum+=60}let c=!1;return c=await Wt.request({url:this.imageUrlPackage[this.contImages],method:"PUT",headers:{"Content-Type":i.type,"x-ms-blob-type":"BlockBlob"},data:i,onUploadProgress:l=>{s({loadedBytes:l.loaded})}}).then(l=>l.status==200||l.status==201?(this.contImages++,!0):!1).catch(()=>!1).finally(()=>{}),{storage:"upload",url:a,uploaded:c}}catch{throw de.registerError(this.proctoringId,`Failed to upload to AWS
|
|
@@ -80,9 +80,9 @@ Minimum version required to store current data is: `+o+`.
|
|
|
80
80
|
File size: ${i.size}`),new Error("Failed to upload to AWS")}}};var Zg="not_shared_first_screen",Qg="not_shared_screen",Fa="multiple_monitors_detected",e0="proctoring_already_started",La="proctoring_not_started";var t0="another_stream_active",r0="stream_under_minimum_permitted",n0="browser_not_supported",i0="token_missing",o0="credentials_missing";var s0="spy_scan_api_not_found",Ed="safe_browser_api_not_found";var a0="external_camera_not_started";var Ma=class extends Bi{constructor(t,r,n="videoPreviewFrameDetection",i="liveViewFrameDetection"){super("ObjectDetector","https://storage.googleapis.com/mediapipe-models/object_detector/efficientdet_lite0/float16/1/efficientdet_lite0.tflite",t,r,n,i)}stopDetection(){super.stopDetection(),this.numPersonsSent>0&&this.handleOk("person_ok","person_detection_on_stream")}displayVideoDetections(t){for(let r of this.children)this.liveView.removeChild(r);this.children.splice(0);for(let r of t.detections){let n=window.innerWidth,i=window.innerHeight,o=this.video.offsetWidth,s=this.video.offsetHeight,a=o/n,c=s/i,l=o-r.boundingBox.width*a-r.boundingBox.originX*a,h=r.boundingBox.originY*c,d=(r.boundingBox.width-10)*a,g=r.boundingBox.height*c,p=document.createElement("p");p.innerText=r.categories[0].categoryName+" - with "+Math.round(parseFloat(r.categories[0].score)*100)+"% confidence.",p.style.right=l-20+"px",p.style.top=h+"px",p.style.width=d+"px";let m={zIndex:"2",position:"absolute",border:"1px dashed #fff"};Object.assign(p.style,{...m,margin:"0",fontSize:"9px",paddingBottom:"5px",paddingTop:"5px",color:"#fff",backgroundColor:"#007f8b"});let f=document.createElement("div");f.setAttribute("class","highlighter"),f.style.right=l-20+"px",f.style.top=h+"px",f.style.width=d+"px",f.style.height=g-20+"px",Object.assign(f.style,{...m,zIndex:"1",background:"rgba(0, 255, 0, 0.25)"}),this.liveView.appendChild(f),this.liveView.appendChild(p),this.children.push(f),this.children.push(p)}}verify(t){let r=t.detections.filter(i=>i.categories.some(o=>o.categoryName==="person")).length,n=t.detections.filter(i=>i.categories.some(o=>o.categoryName==="cell phone")).length;this.paramsConfig.videoBehaviourParameters?.detectPerson&&r!==this.numPersonsSent&&(r===0?(this.handleAlert("no_person_detected","person_detection_on_stream"),this.numPersonsSent=r):r>1?(this.handleAlert("multiple_persons_detected","person_detection_on_stream"),this.numPersonsSent=r):(this.handleOk("person_ok","person_detection_on_stream"),this.numPersonsSent=r)),this.paramsConfig.videoBehaviourParameters?.detectCellPhone&&n!==this.numCellphoneSent&&(n>0?(this.handleAlert("cellphone_detected","mobile_detection_on_stream"),this.numCellphoneSent=n):(this.handleOk("cellphone_ok","mobile_detection_on_stream"),this.numCellphoneSent=n))}};var Vi=class e{constructor(){this.db=null}static{this.DB_NAME="EasyProctorChunksDb"}static{this.DB_VERSION=3}static{this.STORE_NAME="chunks"}async connect(){return this.db?this.db:new Promise((t,r)=>{let n=window.indexedDB.open(e.DB_NAME,e.DB_VERSION);n.onerror=()=>{r(new Error("N\xE3o foi poss\xEDvel conectar ao IndexedDB para chunks."))},n.onupgradeneeded=()=>{let i=n.result;i.objectStoreNames.contains(e.STORE_NAME)&&i.deleteObjectStore(e.STORE_NAME);let o=i.createObjectStore(e.STORE_NAME,{keyPath:"id",autoIncrement:!0});o.createIndex("proctoringId","proctoringId",{unique:!1}),o.createIndex("uploaded","uploaded",{unique:!1}),o.createIndex("proctoringId_uploaded",["proctoringId","uploaded"],{unique:!1})},n.onsuccess=()=>{this.db=n.result,t(this.db)}})}async saveChunk(t){let r=await this.connect();return new Promise((n,i)=>{let a=r.transaction(e.STORE_NAME,"readwrite").objectStore(e.STORE_NAME).add(t);a.onsuccess=()=>{n(a.result)},a.onerror=()=>{i(new Error(`Erro ao salvar chunk no IndexedDB: ${a.error?.message}`))}})}async getPendingChunks(t){let r=await this.connect();return new Promise((n,i)=>{let a=r.transaction(e.STORE_NAME,"readonly").objectStore(e.STORE_NAME).index("proctoringId_uploaded"),c=IDBKeyRange.only([t,0]),l=a.getAll(c);l.onsuccess=()=>{let h=l.result.sort((d,g)=>d.chunkIndex-g.chunkIndex);n(h)},l.onerror=()=>{i(new Error(`Erro ao buscar chunks pendentes: ${l.error?.message}`))}})}async getAllChunks(t){let r=await this.connect();return new Promise((n,i)=>{let a=r.transaction(e.STORE_NAME,"readonly").objectStore(e.STORE_NAME).index("proctoringId"),c=IDBKeyRange.only(t),l=a.getAll(c);l.onsuccess=()=>{let h=l.result.sort((d,g)=>d.chunkIndex-g.chunkIndex);n(h)},l.onerror=()=>{i(new Error(`Erro ao buscar todos os chunks: ${l.error?.message}`))}})}async markAsUploaded(t){let r=await this.connect();return new Promise((n,i)=>{let s=r.transaction(e.STORE_NAME,"readwrite").objectStore(e.STORE_NAME),a=s.get(t);a.onsuccess=()=>{let c=a.result;if(!c){n();return}c.uploaded=1;let l=s.put(c);l.onsuccess=()=>n(),l.onerror=()=>i(new Error(`Erro ao marcar chunk como enviado: ${l.error?.message}`))},a.onerror=()=>i(new Error(`Erro ao buscar chunk para marcar: ${a.error?.message}`))})}async clearUploadedChunks(t){let r=await this.connect();return new Promise((n,i)=>{let a=r.transaction(e.STORE_NAME,"readwrite").objectStore(e.STORE_NAME).index("proctoringId_uploaded"),c=IDBKeyRange.only([t,1]),l=a.openCursor(c);l.onsuccess=()=>{let h=l.result;h?(h.delete(),h.continue()):n()},l.onerror=()=>i(new Error(`Erro ao limpar chunks enviados: ${l.error?.message}`))})}async clearAllChunks(t){let r=await this.connect();return new Promise((n,i)=>{let a=r.transaction(e.STORE_NAME,"readwrite").objectStore(e.STORE_NAME).index("proctoringId"),c=IDBKeyRange.only(t),l=a.openCursor(c);l.onsuccess=()=>{let h=l.result;h?(h.delete(),h.continue()):n()},l.onerror=()=>i(new Error(`Erro ao limpar todos os chunks: ${l.error?.message}`))})}async hasAnyPendingChunks(){let t=await this.connect();return new Promise((r,n)=>{let s=t.transaction(e.STORE_NAME,"readonly").objectStore(e.STORE_NAME).index("uploaded"),a=IDBKeyRange.only(0),c=s.count(a);c.onsuccess=()=>{r(c.result>0)},c.onerror=()=>n(new Error(`Erro ao verificar chunks pendentes: ${c.error?.message}`))})}async getPendingProctoringIds(){let t=await this.connect();return new Promise((r,n)=>{let s=t.transaction(e.STORE_NAME,"readonly").objectStore(e.STORE_NAME).index("uploaded"),a=IDBKeyRange.only(0),c=s.getAll(a);c.onsuccess=()=>{let l=c.result,h=[...new Set(l.map(d=>d.proctoringId))];r(h)},c.onerror=()=>n(new Error(`Erro ao buscar proctoringIds pendentes: ${c.error?.message}`))})}close(){this.db&&(this.db.close(),this.db=null)}};var I_={pollInterval:5e3,maxRetries:5,baseRetryDelay:2e3,cleanAfterUpload:!0},Na=class e{constructor(t,r,n,i,o){this.pollTimer=null;this.isProcessing=!1;this.isRunning=!1;this.retryCount=new Map;this.sessionUrl=null;this.currentOffset=0;this.totalBytesPurged=0;this.STORAGE_KEY_PREFIX="ep_upload_session_";this.GCS_CHUNK_SIZE=256*1024;this.proctoringId=t.trim(),this.token=r,this.backend=n,this.chunkStorage=i,this.config={...I_,...o},this.loadSessionState()}loadSessionState(){try{let t=localStorage.getItem(`${this.STORAGE_KEY_PREFIX}${this.proctoringId}`);if(t){let{sessionUrl:r,currentOffset:n,totalBytesPurged:i}=JSON.parse(t);this.sessionUrl=r,this.currentOffset=n,this.totalBytesPurged=i||0}}catch(t){console.warn("[BackgroundUpload] Erro ao carregar estado da sess\xE3o:",t)}}saveSessionState(){try{localStorage.setItem(`${this.STORAGE_KEY_PREFIX}${this.proctoringId}`,JSON.stringify({sessionUrl:this.sessionUrl,currentOffset:this.currentOffset,totalBytesPurged:this.totalBytesPurged}))}catch(t){console.warn("[BackgroundUpload] Erro ao salvar estado da sess\xE3o:",t)}}clearSessionState(){try{localStorage.removeItem(`${this.STORAGE_KEY_PREFIX}${this.proctoringId}`),this.sessionUrl=null,this.currentOffset=0,this.totalBytesPurged=0}catch(t){console.warn("[BackgroundUpload] Erro ao limpar estado da sess\xE3o:",t)}}start(){this.isRunning||(this.isRunning=!0,console.log(`[BackgroundUpload] Iniciando servi\xE7o para proctoringId: ${this.proctoringId}`),this.processQueue(),this.pollTimer=setInterval(()=>{this.processQueue(!1)},this.config.pollInterval))}stop(){this.isRunning=!1,this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null),console.log(`[BackgroundUpload] Servi\xE7o parado para proctoringId: ${this.proctoringId}`)}async flush(){console.log("[BackgroundUpload] Flush: enviando todos os chunks pendentes e finalizando...");let t=0;for(;this.isProcessing&&t<10;)await this.sleep(1e3),t++;let r=0,n=3;for(;r<n;)try{await this.processQueue(!0),console.log("[BackgroundUpload] Flush completado com sucesso.");return}catch(i){r++,console.error(`[BackgroundUpload] Erro no flush (tentativa ${r}/${n}):`,i),r<n&&await this.sleep(2e3)}throw new Error(`[BackgroundUpload] Falha ao finalizar upload ap\xF3s ${n} tentativas.`)}async syncOffset(){if(!this.sessionUrl)return 0;try{console.log("[BackgroundUpload] Sincronizando offset com GCS...");let t=await fetch(this.sessionUrl,{method:"PUT",headers:{"Content-Range":"bytes */*"}});if(console.log(`[BackgroundUpload] Status da sincroniza\xE7\xE3o (syncOffset): ${t.status}`),t.status===308){let r=t.headers.get("Range");if(r){let n=parseInt(r.split("-")[1],10);this.currentOffset=n+1,this.saveSessionState(),console.log(`[BackgroundUpload] Offset sincronizado: ${this.currentOffset}`)}else this.currentOffset=0}else t.ok||t.status===201?(console.log("[BackgroundUpload] Sincroniza\xE7\xE3o indicou upload JA FINALIZADO."),this.currentOffset=-1):console.warn(`[BackgroundUpload] Status inesperado na sincroniza\xE7\xE3o: ${t.status}`)}catch(t){console.warn("[BackgroundUpload] Erro ao sincronizar offset:",t)}return this.currentOffset}async processQueue(t=!1){if(!this.isProcessing){this.isProcessing=!0;try{if(this.sessionUrl&&(await this.syncOffset(),this.currentOffset===-1)){console.log("[BackgroundUpload] Sess\xE3o j\xE1 finalizada no servidor."),this.clearSessionState(),this.isProcessing=!1;return}let r=await this.chunkStorage.getAllChunks(this.proctoringId),n=r.filter(m=>m.uploaded===0);if(n.length===0&&!t){this.isProcessing=!1;return}console.log(`[BackgroundUpload] ${n.length} chunks pendentes encontrados. Modo final: ${t}`);let i=this.totalBytesPurged,o=r.map(m=>{let f=i,b=m.arrayBuffer.byteLength,v=f+b-1;return i+=b,{chunk:m,start:f,end:v}}),s=[],a=null,c=0,l=n[0].mimeType;for(let m of o){if(this.currentOffset>m.end)continue;let f=Math.max(0,this.currentOffset-m.start),b=m.chunk.arrayBuffer.slice(f);s.push(new Blob([b])),a=m.chunk.id,c=m.chunk.chunkIndex}if(s.length===0&&!t){this.isProcessing=!1;return}let h=new Blob(s,{type:l}),d=h.size,g;if(t)g=i;else if(d=Math.floor(h.size/this.GCS_CHUNK_SIZE)*this.GCS_CHUNK_SIZE,d===0){console.log("[BackgroundUpload] Dados insuficientes para atingir 256KB. Aguardando novo chunk..."),this.isProcessing=!1;return}let p=h.slice(0,d);try{await this.uploadData(p,l,c,g);for(let m of o)m.chunk.uploaded===0&&m.end<this.currentOffset&&(await this.chunkStorage.markAsUploaded(m.chunk.id),this.retryCount.delete(m.chunk.id),this.onChunkUploaded?.(m.chunk.id,m.chunk.chunkIndex),console.log(`[BackgroundUpload] Chunk ${m.chunk.chunkIndex} marcado como enviado.`));if(this.config.cleanAfterUpload){let f=o.filter(b=>b.chunk.uploaded===1||b.chunk.uploaded===0&&b.end<this.currentOffset).reduce((b,v)=>b+v.chunk.arrayBuffer.byteLength,0);await this.chunkStorage.clearUploadedChunks(this.proctoringId),f>0&&(this.totalBytesPurged+=f,this.saveSessionState(),console.log(`[BackgroundUpload] ${f} bytes limpos do armazenamento local. Total purgado: ${this.totalBytesPurged}`))}t&&this.clearSessionState()}catch(m){console.error("[BackgroundUpload] Falha no upload:",m),this.onUploadError?.(a||0,m)}}catch(r){console.error("[BackgroundUpload] Erro ao processar fila:",r)}finally{this.isProcessing=!1}}}async uploadData(t,r,n,i){let o=`EP_${this.proctoringId}_camera_0.webm`;if(this.sessionUrl)console.log(`[BackgroundUpload] Usando sess\xE3o GCS existente: ${this.sessionUrl}`);else{let g=await this.backend.initiateUpload(this.token,`${this.proctoringId}/${o}`,r),p=await fetch(g,{method:"POST",headers:{"x-goog-resumable":"start","Content-Type":r}});if(!p.ok)throw new Error(`Falha ao iniciar: ${p.status}`);if(this.sessionUrl=p.headers.get("Location"),!this.sessionUrl)throw new Error("Location header ausente");try{let f=new URL(this.sessionUrl).pathname.split("/"),b=f[1],v=decodeURIComponent(f.slice(2).join("/"));if(f.includes("b")&&f.includes("o")){let S=f.indexOf("b")+1,k=f.indexOf("o")+1;b=f[S],v=decodeURIComponent(f.slice(k).join("/"))}console.log(`[BackgroundUpload] Sess\xE3o Iniciada -> Bucket: ${b}, Objeto: ${v}`)}catch{console.log(`[BackgroundUpload] Sess\xE3o Iniciada. URL: ${this.sessionUrl}`)}this.currentOffset=0,this.saveSessionState()}let s=this.currentOffset,a=s+t.size-1,c=i!==void 0?i.toString():"*",l=t.size===0&&i!==void 0?`bytes */${c}`:`bytes ${s}-${a}/${c}`;console.log(`[BackgroundUpload] Enviando ${t.size>0?"dados":"finaliza\xE7\xE3o"}: ${l} (Size: ${t.size})`);let h=await fetch(this.sessionUrl,{method:"PUT",headers:{"Content-Range":l},body:t.size>0?t:null});if(console.log(`[BackgroundUpload] Resposta GCS (uploadData): ${h.status}`),h.status!==200&&h.status!==201&&h.status!==308){let g=await h.text();throw console.error(`[BackgroundUpload] Erro GCS: ${g}`),new Error(`Status HTTP inesperado: ${h.status}`)}let d=h.headers.get("Range");if(d){let g=parseInt(d.split("-")[1],10);this.currentOffset=g+1}else this.currentOffset+=t.size;this.saveSessionState(),de.registerUploadFile(this.proctoringId,`GCS Stream Upload
|
|
81
81
|
Size: ${t.size}
|
|
82
82
|
Range: ${s}-${a}
|
|
83
|
-
Last Index: ${n}`,"CameraChunk")}static async recoverPendingUploads(t,r){let n=new Vi,i=[];try{let o=await n.getPendingProctoringIds();if(o.length===0)return console.log("[BackgroundUpload] Nenhum chunk pendente encontrado para recupera\xE7\xE3o."),i;console.log(`[BackgroundUpload] Recupera\xE7\xE3o p\xF3s-crash: ${o.length} sess\xE3o(\xF5es) com chunks pendentes.`);for(let s of o)try{await new e(s,r,t,n,{cleanAfterUpload:!0}).flush(),i.push(s),console.log(`[BackgroundUpload] Chunks da sess\xE3o ${s} recuperados com sucesso.`)}catch(a){console.error(`[BackgroundUpload] Erro ao recuperar chunks da sess\xE3o ${s}:`,a)}}catch(o){console.error("[BackgroundUpload] Erro geral na recupera\xE7\xE3o:",o)}return i}sleep(t){return new Promise(r=>setTimeout(r,t))}};var p0=fl(l0()),h0=xd(),d0=h0.default||h0,Zr=class e{constructor(t,r,n,i,o){this.blobs=[];this.paramsConfig={audioBehaviourParameters:{recordingBitrate:128,noiseLimit:40},videoBehaviourParameters:{detectPerson:!1,detectFace:!1,detectCellPhone:!1,cameraVideoQuality:1}};this.options={cameraId:void 0,microphoneId:void 0,onBufferSizeError:!1,onBufferSizeErrorCallback:t=>{},proctoringType:"VIDEO",onChangeDevicesCallback:t=>{},onRealtimeAlertsCallback:t=>{}};this.videoOptions={width:640,height:480,minWidth:0,minHeight:0};this.blobsRTC=[];this.imageCount=0;this.filesToUpload=[];this.pendingPackages=[];this.animationFrameId=null;this.isCanvasLoopActive=!1;this.hardwareStream=null;this.internalClonedStream=null;this.videoElement=null;this.duration=0;this.stopped=!1;this.backgroundUpload=null;this.chunkIndex=0;this.pendingChunkSaves=[];this.boundVisibilityHandler=null;this.boundPageHideHandler=null;this.currentRetries=0;this.packageCount=0;this.failedUploads=0;this.options=t,this.videoOptions=r,this.backend=i,this.backendToken=o,n&&(this.paramsConfig=n)}static{this.CHUNK_TIMESLICE_MS=6e4}static{this.LS_SESSION_KEY="ep_proctoring_session"}get isChunkEnabled(){return!!this.proctoringId&&this.options.proctoringType==="REALTIME"&&!Jg()}setProctoringId(t){this.proctoringId=t,this.proctoringId&&this.backend&&(this.upload=new Yr(this.proctoringId,this.backend)),Oa(t),this.isChunkEnabled?(this.chunkStorage=new Vi,this.backend&&this.backendToken&&(this.backgroundUpload=new Na(this.proctoringId,this.backendToken,this.backend,this.chunkStorage,{pollInterval:5e3,maxRetries:5,cleanAfterUpload:!0})),this.persistSessionState("IN_PROGRESS"),console.log(`[CameraRecorder] Chunk recording ATIVO (type: ${this.options.proctoringType}, mobile: ${_r()})`)):console.log(`[CameraRecorder] Chunk recording INATIVO (type: ${this.options.proctoringType}) \u2014 modo cl\xE1ssico.`)}persistSessionState(t){try{let r={proctoringId:this.proctoringId,status:t,timestamp:Date.now()};localStorage.setItem(e.LS_SESSION_KEY,JSON.stringify(r))}catch(r){console.warn("[CameraRecorder] N\xE3o foi poss\xEDvel salvar estado no localStorage:",r)}}clearSessionState(){try{localStorage.removeItem(e.LS_SESSION_KEY)}catch(t){console.warn("[CameraRecorder] N\xE3o foi poss\xEDvel limpar estado do localStorage:",t)}}static checkForActiveSession(){try{let t=localStorage.getItem(e.LS_SESSION_KEY);if(!t)return null;let r=JSON.parse(t);return r.status==="IN_PROGRESS"?r:null}catch{return null}}setupLifecycleListeners(){this.boundVisibilityHandler=()=>this.handleVisibilityChange(),this.boundPageHideHandler=()=>this.handlePageHide(),document.addEventListener("visibilitychange",this.boundVisibilityHandler),window.addEventListener("pagehide",this.boundPageHideHandler)}removeLifecycleListeners(){this.boundVisibilityHandler&&(document.removeEventListener("visibilitychange",this.boundVisibilityHandler),this.boundVisibilityHandler=null),this.boundPageHideHandler&&(window.removeEventListener("pagehide",this.boundPageHideHandler),this.boundPageHideHandler=null)}handleVisibilityChange(){document.visibilityState==="hidden"?(console.log("[CameraRecorder] P\xE1gina ficou invis\xEDvel \u2014 sess\xE3o potencialmente interrompida."),this.persistSessionState("INTERRUPTED"),this.proctoringId&&de.registerError(this.proctoringId,"Visibility API: P\xE1gina ficou oculta (hidden). Poss\xEDvel troca de app ou minimiza\xE7\xE3o.")):document.visibilityState==="visible"&&(console.log("[CameraRecorder] P\xE1gina vis\xEDvel novamente \u2014 verificando estado da grava\xE7\xE3o."),this.persistSessionState("IN_PROGRESS"),this.proctoringId&&de.registerError(this.proctoringId,"Visibility API: P\xE1gina voltou a ficar vis\xEDvel. Usu\xE1rio retornou."),this.onVisibilityRestored?.())}handlePageHide(){console.log("[CameraRecorder] pagehide detectado \u2014 persistindo estado."),this.persistSessionState("INTERRUPTED"),this.proctoringId&&de.registerError(this.proctoringId,"Page Lifecycle: pagehide event detectado. P\xE1gina est\xE1 sendo descarregada.")}async initializeDetectors(){lg(),(this.paramsConfig.videoBehaviourParameters?.detectPerson||this.paramsConfig.videoBehaviourParameters?.detectCellPhone)&&(this.objectDetection=new Ma({onRealtimeAlertsCallback:t=>{t.begin=Date.now()-(this.getStartTime()?.getTime()||0),t.end=Date.now()-(this.getStartTime()?.getTime()||0),this.options.onRealtimeAlertsCallback(t)}},this.paramsConfig),await this.objectDetection.initializeDetector()),this.paramsConfig.videoBehaviourParameters?.detectFace&&(this.faceDetection=new Oi({onRealtimeAlertsCallback:t=>{t.begin=Date.now()-(this.getStartTime()?.getTime()||0),t.end=Date.now()-(this.getStartTime()?.getTime()||0),this.options.onRealtimeAlertsCallback(t)}},this.paramsConfig),await this.faceDetection.initializeDetector())}configImageCapture(){this.video=document.createElement("video"),this.canvas=document.createElement("canvas"),this.video.srcObject=this.cameraStream,this.video.play(),this.video.muted=!0,screen.orientation?.type.includes("portrait")&&_r()?(console.log("configurando canvas em portrait"),this.canvas.width=this.videoOptions.height/2,this.canvas.height=this.videoOptions.width/2):(this.canvas.width=this.videoOptions.width/2,this.canvas.height=this.videoOptions.height/2)}async bufferError(t){console.log("buffer error Camera Recorder params ");let r=this.paramsConfig.videoBehaviourParameters?.retryEnabled||!1,n=this.paramsConfig.videoBehaviourParameters?.maxRetries||3;r&&this.currentRetries<n?(await this.recordingStop(),await this.startRecording(),this.currentRetries++,this.options.onBufferSizeErrorCallback&&this.options.onBufferSizeErrorCallback(this.cameraStream)):this.options.onBufferSizeErrorCallback&&this.options.onBufferSizeErrorCallback()}async startStream(){let{cameraId:t,microphoneId:r,onBufferSizeErrorCallback:n}=this.options,i={audio:{deviceId:r},video:{deviceId:t,width:this.videoOptions.width,height:this.videoOptions.height,frameRate:15}};try{this.hardwareStream=await navigator.mediaDevices.getUserMedia(i)}catch(h){throw h.toString()=="NotReadableError: Could not start video source"?"N\xE3o foi poss\xEDvel conectar a camera, ela pode estar sendo utilizada por outro programa":h}this.cameraStream=this.hardwareStream;let s=this.cameraStream.getVideoTracks()[0].getSettings(),{width:a=0,height:c=0}=s;if(screen.orientation?.type.includes("portrait")&&_r()&&this.videoOptions.width==c&&this.videoOptions.height==a&&([a,c]=[c,a]),this.videoOptions.minWidth>a||this.videoOptions.minHeight>c)throw r0;if(this.videoOptions.width!==a||this.videoOptions.height!==c)throw de.registerAnotherStream(this.proctoringId,`Maybe have another stream active
|
|
83
|
+
Last Index: ${n}`,"CameraChunk")}static async recoverPendingUploads(t,r){let n=new Vi,i=[];try{let o=await n.getPendingProctoringIds();if(o.length===0)return console.log("[BackgroundUpload] Nenhum chunk pendente encontrado para recupera\xE7\xE3o."),i;console.log(`[BackgroundUpload] Recupera\xE7\xE3o p\xF3s-crash: ${o.length} sess\xE3o(\xF5es) com chunks pendentes.`);for(let s of o)try{await new e(s,r,t,n,{cleanAfterUpload:!0}).flush(),i.push(s),console.log(`[BackgroundUpload] Chunks da sess\xE3o ${s} recuperados com sucesso.`)}catch(a){console.error(`[BackgroundUpload] Erro ao recuperar chunks da sess\xE3o ${s}:`,a)}}catch(o){console.error("[BackgroundUpload] Erro geral na recupera\xE7\xE3o:",o)}return i}sleep(t){return new Promise(r=>setTimeout(r,t))}};var p0=fl(l0()),h0=xd(),d0=h0.default||h0,Zr=class e{constructor(t,r,n,i,o){this.blobs=[];this.paramsConfig={audioBehaviourParameters:{recordingBitrate:128,noiseLimit:40},videoBehaviourParameters:{detectPerson:!1,detectFace:!1,detectCellPhone:!1,cameraVideoQuality:1,timeoutMultiplierFactor:1}};this.options={cameraId:void 0,microphoneId:void 0,onBufferSizeError:!1,onBufferSizeErrorCallback:t=>{},proctoringType:"VIDEO",onChangeDevicesCallback:t=>{},onRealtimeAlertsCallback:t=>{}};this.videoOptions={width:640,height:480,minWidth:0,minHeight:0};this.blobsRTC=[];this.imageCount=0;this.filesToUpload=[];this.pendingPackages=[];this.animationFrameId=null;this.isCanvasLoopActive=!1;this.hardwareStream=null;this.internalClonedStream=null;this.videoElement=null;this.duration=0;this.stopped=!1;this.backgroundUpload=null;this.chunkIndex=0;this.pendingChunkSaves=[];this.boundVisibilityHandler=null;this.boundPageHideHandler=null;this.currentRetries=0;this.packageCount=0;this.failedUploads=0;this.options=t,this.videoOptions=r,this.backend=i,this.backendToken=o,n&&(this.paramsConfig=n)}static{this.CHUNK_TIMESLICE_MS=6e4}static{this.LS_SESSION_KEY="ep_proctoring_session"}get isChunkEnabled(){return!!this.proctoringId&&this.options.proctoringType==="REALTIME"&&!Jg()}setProctoringId(t){this.proctoringId=t,this.proctoringId&&this.backend&&(this.upload=new Yr(this.proctoringId,this.backend)),Oa(t),this.isChunkEnabled?(this.chunkStorage=new Vi,this.backend&&this.backendToken&&(this.backgroundUpload=new Na(this.proctoringId,this.backendToken,this.backend,this.chunkStorage,{pollInterval:5e3,maxRetries:5,cleanAfterUpload:!0})),this.persistSessionState("IN_PROGRESS"),console.log(`[CameraRecorder] Chunk recording ATIVO (type: ${this.options.proctoringType}, mobile: ${_r()})`)):console.log(`[CameraRecorder] Chunk recording INATIVO (type: ${this.options.proctoringType}) \u2014 modo cl\xE1ssico.`)}persistSessionState(t){try{let r={proctoringId:this.proctoringId,status:t,timestamp:Date.now()};localStorage.setItem(e.LS_SESSION_KEY,JSON.stringify(r))}catch(r){console.warn("[CameraRecorder] N\xE3o foi poss\xEDvel salvar estado no localStorage:",r)}}clearSessionState(){try{localStorage.removeItem(e.LS_SESSION_KEY)}catch(t){console.warn("[CameraRecorder] N\xE3o foi poss\xEDvel limpar estado do localStorage:",t)}}static checkForActiveSession(){try{let t=localStorage.getItem(e.LS_SESSION_KEY);if(!t)return null;let r=JSON.parse(t);return r.status==="IN_PROGRESS"?r:null}catch{return null}}setupLifecycleListeners(){this.boundVisibilityHandler=()=>this.handleVisibilityChange(),this.boundPageHideHandler=()=>this.handlePageHide(),document.addEventListener("visibilitychange",this.boundVisibilityHandler),window.addEventListener("pagehide",this.boundPageHideHandler)}removeLifecycleListeners(){this.boundVisibilityHandler&&(document.removeEventListener("visibilitychange",this.boundVisibilityHandler),this.boundVisibilityHandler=null),this.boundPageHideHandler&&(window.removeEventListener("pagehide",this.boundPageHideHandler),this.boundPageHideHandler=null)}handleVisibilityChange(){document.visibilityState==="hidden"?(console.log("[CameraRecorder] P\xE1gina ficou invis\xEDvel \u2014 sess\xE3o potencialmente interrompida."),this.persistSessionState("INTERRUPTED"),this.proctoringId&&de.registerError(this.proctoringId,"Visibility API: P\xE1gina ficou oculta (hidden). Poss\xEDvel troca de app ou minimiza\xE7\xE3o.")):document.visibilityState==="visible"&&(console.log("[CameraRecorder] P\xE1gina vis\xEDvel novamente \u2014 verificando estado da grava\xE7\xE3o."),this.persistSessionState("IN_PROGRESS"),this.proctoringId&&de.registerError(this.proctoringId,"Visibility API: P\xE1gina voltou a ficar vis\xEDvel. Usu\xE1rio retornou."),this.onVisibilityRestored?.())}handlePageHide(){console.log("[CameraRecorder] pagehide detectado \u2014 persistindo estado."),this.persistSessionState("INTERRUPTED"),this.proctoringId&&de.registerError(this.proctoringId,"Page Lifecycle: pagehide event detectado. P\xE1gina est\xE1 sendo descarregada.")}async initializeDetectors(){lg(),(this.paramsConfig.videoBehaviourParameters?.detectPerson||this.paramsConfig.videoBehaviourParameters?.detectCellPhone)&&(this.objectDetection=new Ma({onRealtimeAlertsCallback:t=>{t.begin=Date.now()-(this.getStartTime()?.getTime()||0),t.end=Date.now()-(this.getStartTime()?.getTime()||0),this.options.onRealtimeAlertsCallback(t)}},this.paramsConfig),await this.objectDetection.initializeDetector()),this.paramsConfig.videoBehaviourParameters?.detectFace&&(this.faceDetection=new Oi({onRealtimeAlertsCallback:t=>{t.begin=Date.now()-(this.getStartTime()?.getTime()||0),t.end=Date.now()-(this.getStartTime()?.getTime()||0),this.options.onRealtimeAlertsCallback(t)}},this.paramsConfig),await this.faceDetection.initializeDetector())}configImageCapture(){this.video=document.createElement("video"),this.canvas=document.createElement("canvas"),this.video.srcObject=this.cameraStream,this.video.play(),this.video.muted=!0,screen.orientation?.type.includes("portrait")&&_r()?(console.log("configurando canvas em portrait"),this.canvas.width=this.videoOptions.height/2,this.canvas.height=this.videoOptions.width/2):(this.canvas.width=this.videoOptions.width/2,this.canvas.height=this.videoOptions.height/2)}async bufferError(t){console.log("buffer error Camera Recorder params ");let r=this.paramsConfig.videoBehaviourParameters?.retryEnabled||!1,n=this.paramsConfig.videoBehaviourParameters?.maxRetries||3;r&&this.currentRetries<n?(await this.recordingStop(),await this.startRecording(),this.currentRetries++,this.options.onBufferSizeErrorCallback&&this.options.onBufferSizeErrorCallback(this.cameraStream)):this.options.onBufferSizeErrorCallback&&this.options.onBufferSizeErrorCallback()}async startStream(){let{cameraId:t,microphoneId:r,onBufferSizeErrorCallback:n}=this.options,i={audio:{deviceId:r},video:{deviceId:t,width:this.videoOptions.width,height:this.videoOptions.height,frameRate:15}};try{this.hardwareStream=await navigator.mediaDevices.getUserMedia(i)}catch(h){throw h.toString()=="NotReadableError: Could not start video source"?"N\xE3o foi poss\xEDvel conectar a camera, ela pode estar sendo utilizada por outro programa":h}this.cameraStream=this.hardwareStream;let s=this.cameraStream.getVideoTracks()[0].getSettings(),{width:a=0,height:c=0}=s;if(screen.orientation?.type.includes("portrait")&&_r()&&this.videoOptions.width==c&&this.videoOptions.height==a&&([a,c]=[c,a]),this.videoOptions.minWidth>a||this.videoOptions.minHeight>c)throw r0;if(this.videoOptions.width!==a||this.videoOptions.height!==c)throw de.registerAnotherStream(this.proctoringId,`Maybe have another stream active
|
|
84
84
|
Video Options: ${JSON.stringify(this.videoOptions,null,2)}
|
|
85
|
-
Setting: ${JSON.stringify(s,null,2)}`),t0}async stopStream(){this.cameraStream&&this.cameraStream.getTracks().forEach(t=>t.stop()),this.internalClonedStream&&(this.internalClonedStream.getTracks().forEach(t=>t.stop()),this.internalClonedStream=null),this.hardwareStream&&(this.hardwareStream.getTracks().forEach(t=>t.stop()),this.hardwareStream=null)}async waitForVideoFlow(){return new Promise(t=>{let r=()=>{if(this.videoElement&&this.videoElement?.readyState>=3)return t();requestAnimationFrame(r)};r()})}async attachAndWarmup(t){this.videoElement=document.createElement("video"),this.videoElement.srcObject=t,this.videoElement.muted=!0,await this.videoElement.play().catch(r=>{}),await new Promise(r=>{if(this.videoElement&&this.videoElement?.readyState>=1)return r();this.videoElement&&(this.videoElement.onloadedmetadata=()=>r())}),console.log("CameraRecorder checking metadata ok"),await this.waitForVideoFlow(),console.log("CameraRecorder waiting for video flow ok"),await new Promise(r=>setTimeout(r,300))}async startRecording(){await this.startStream(),await this.attachAndWarmup(this.cameraStream);let t=this.isChunkEnabled?{timeslice:e.CHUNK_TIMESLICE_MS,onChunkAvailable:(h,d)=>{this.handleNewChunk(h,d)},quality:this.paramsConfig.videoBehaviourParameters?.cameraVideoQuality}:{},{startRecording:r,stopRecording:n,pauseRecording:i,resumeRecording:o,recorderOptions:s,getBufferSize:a,getStartTime:c,getDuration:l}=Ho(this.cameraStream,this.blobs,this.options.onBufferSizeError,h=>this.bufferError(h),t);this.recordingStart=r,this.recordingStop=n,this.recordingPause=i,this.recordingResume=o,this.recorderOptions=s,this.getBufferSize=a,this.getStartTime=c,this.getDuration=l,this.chunkIndex=0,this.isChunkEnabled&&(this.backgroundUpload?.start(),this.setupLifecycleListeners());try{await new Promise(h=>setTimeout(h,500)),await this.recordingStart()}catch(h){console.log("Camera Recorder error",h),this.stopRecording();let d=this.paramsConfig.videoBehaviourParameters?.maxRetries||3;if(this.currentRetries<d)console.log("Camera Recorder retry",this.currentRetries),this.currentRetries++,await this.startRecording();else throw h}this.stopped=!1,(this.paramsConfig.videoBehaviourParameters?.detectPerson||this.paramsConfig.videoBehaviourParameters?.detectCellPhone||this.paramsConfig.videoBehaviourParameters?.detectFace)&&await this.initializeDetectors(),this.paramsConfig.videoBehaviourParameters?.detectFace&&await this.faceDetection.enableCam(this.cameraStream),(this.paramsConfig.videoBehaviourParameters?.detectPerson||this.paramsConfig.videoBehaviourParameters?.detectCellPhone)&&await this.objectDetection.enableCam(this.cameraStream),this.filesToUpload=[],this.pendingPackages=[],this.options.proctoringType=="REALTIME"&&await this.startRealtimeCapture(),this.packageCount=0,console.log("Camera Recorder started OK")}async stopRecording(){console.log("Camera Recorder stopRecording"),this.stopped=!0,this.isCanvasLoopActive=!1,this.faceDetection&&this.faceDetection.detecting&&this.faceDetection.stopDetection(),this.objectDetection&&this.objectDetection.detecting&&this.objectDetection.stopDetection(),clearInterval(this.imageInterval),clearInterval(this.sendFrameInterval),this.volumeMeter&&this.volumeMeter.stop(),this.intervalNoiseDetection&&clearInterval(this.intervalNoiseDetection),this.recordingStop&&await this.recordingStop(),this.duration=this.getDuration?this.getDuration():0,await new Promise(t=>setTimeout(t,200));try{this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.cameraStream&&this.cameraStream.getTracks().forEach(t=>t.stop()),this.internalClonedStream&&(this.internalClonedStream.getTracks().forEach(t=>t.stop()),this.internalClonedStream=null),this.hardwareStream&&(this.hardwareStream.getTracks().forEach(t=>t.stop()),this.hardwareStream=null),this.videoElement&&(this.videoElement?.remove(),this.videoElement=null),this.video&&this.video?.remove(),this.canvas&&this.canvas?.remove()}catch{console.error("Erro ao parar os streams de m\xEDdia.")}if(this.options.proctoringType=="REALTIME"&&this.upload&&this.backendToken&&(this.pendingPackages.push(this.filesToUpload.slice(0,this.filesToUpload.length)),await this.sendPackage(),await this.filesToUpload.splice(0,this.filesToUpload.length)),this.isChunkEnabled){if(this.backgroundUpload){try{this.pendingChunkSaves.length>0&&(console.log(`[CameraRecorder] Aguardando ${this.pendingChunkSaves.length} salvamentos de chunks pendentes...`),await Promise.all(this.pendingChunkSaves)),await this.backgroundUpload.flush()}catch(t){console.warn("[CameraRecorder] Erro ao fazer flush dos chunks:",t)}this.backgroundUpload.stop()}this.removeLifecycleListeners(),this.persistSessionState("FINISHED")}}async handleNewChunk(t,r){if(!this.proctoringId||!this.chunkStorage)return;let n=(async()=>{try{let i=await t.arrayBuffer();await this.chunkStorage.saveChunk({proctoringId:this.proctoringId,chunkIndex:this.chunkIndex,arrayBuffer:i,timestamp:Date.now(),uploaded:0,mimeType:this.recorderOptions?.mimeType||"video/webm"}),this.chunkIndex++,console.log(`[CameraRecorder] Chunk ${this.chunkIndex-1} salvo no IndexedDB.`)}catch(i){console.error("[CameraRecorder] Erro ao salvar chunk no IndexedDB:",i)}})();this.pendingChunkSaves.push(n),n.finally(()=>{this.pendingChunkSaves=this.pendingChunkSaves.filter(i=>i!==n)})}async pauseRecording(){await this.recordingPause()}async resumeRecording(){await this.recordingResume()}async getCurrentImageBase64(){return!this.video||!this.canvas?this.configImageCapture():this.video.srcObject!==this.cameraStream&&(this.video.srcObject=this.cameraStream,await this.video.play()),this.video.paused&&await this.video.play(),await new Promise(t=>{if(this.video.readyState>=2){t();return}let r=()=>{this.video.removeEventListener("loadedmetadata",r),setTimeout(()=>t(),50)};this.video.addEventListener("loadedmetadata",r),setTimeout(()=>{this.video.removeEventListener("loadedmetadata",r),t()},500)}),this.canvas.getContext("2d").drawImage(this.video,0,0,this.canvas.width,this.canvas.height),this.canvas.toDataURL("image/jpeg")}async captureFrame(){let t,r=this.paramsConfig.videoBehaviourParameters?.realtimePackageSize;this.canvas.getContext("2d").drawImage(this.video,0,0,this.canvas.width,this.canvas.height);let n=this.canvas.toDataURL("image/jpeg");if(this.proctoringId==null)return;r==this.imageCount&&(this.imageCount=0,this.pendingPackages.push(this.filesToUpload.slice(0,r)),this.sendPackage(),await this.filesToUpload.splice(0,r));let i=`${this.proctoringId}_${this.imageCount+1}.jpg`;t=await this.getFile(n,i,"image/jpeg"),t&&t.size>10&&r>0&&(this.filesToUpload.push(t),this.imageCount++)}async startRealtimeCapture(){this.configImageCapture(),this.imageCount=0,this.pendingPackages=[],await this.captureFrame(),this.imageInterval=setInterval(async()=>{await this.captureFrame()},this.paramsConfig.videoBehaviourParameters?.realtimeCaptureInterval*1e3)}async sendPackage(){let t=this.paramsConfig.videoBehaviourParameters?.realtimePackageSize,r=this.paramsConfig.videoBehaviourParameters?.realtimeCaptureInterval;if(this.upload&&this.backendToken&&this.pendingPackages.length>0){let n=[],i=0;for(let o of this.pendingPackages){let s=new p0.default;for(let h of o)s.file(h.name,h);let a=await s.generateAsync({type:"blob"}),c="realtime_package_"+t*r*this.packageCount+".zip",l=new File([a],c,{type:"application/zip"});try{await this.upload.uploadPackage({file:l},this.backendToken)==!0&&(this.packageCount++,this.failedUploads=0,n.push(i++))}catch{this.failedUploads++,this.failedUploads>=2&&this.options.onRealtimeAlertsCallback({status:"ALERT",description:"Realtime n\xE3o est\xE1 enviando pacotes",type:"error_upload_package",category:"error_upload_package",begin:0,end:0});break}}for(let o of n)await this.pendingPackages.splice(o,1)}}download(t){let r=URL.createObjectURL(t),n=document.createElement("a");document.body.appendChild(n),n.style.display="none",n.href=r,n.download=t.name,n.click(),window.URL.revokeObjectURL(r)}async saveOnSession(t){this.blobs!=null&&de.registerSaveOnSession(this.proctoringId,`Blobs Length: ${this.blobs.length} Buffer Size: ${this.getBufferSize()} ChunkEnabled: ${this.isChunkEnabled}`);let r=this.cameraStream.getVideoTracks()[0].getSettings(),n=this.cameraStream.getAudioTracks()[0].getSettings(),i=!1;if(this.isChunkEnabled&&this.backend&&this.backendToken&&this.proctoringId){let o=`EP_${this.proctoringId}_camera_0.webm`,s=`${this.proctoringId}/${o}`;i=await this.backend.checkUpload(this.backendToken,s,"video/webm"),this.chunkStorage&&await this.chunkStorage.clearAllChunks(t.id)}if(!i){let o=new Blob(this.blobs,{type:this.recorderOptions?.mimeType||"video/webm"}),s=o;if(typeof d0=="function")try{s=await d0(o,this.duration)}catch(a){console.warn("Erro ao corrigir a dura\xE7\xE3o do v\xEDdeo",a),s=o}else console.warn("fixWebmDuration n\xE3o dispon\xEDvel");t.addRecording({device:`Audio
|
|
85
|
+
Setting: ${JSON.stringify(s,null,2)}`),t0}async stopStream(){this.cameraStream&&this.cameraStream.getTracks().forEach(t=>t.stop()),this.internalClonedStream&&(this.internalClonedStream.getTracks().forEach(t=>t.stop()),this.internalClonedStream=null),this.hardwareStream&&(this.hardwareStream.getTracks().forEach(t=>t.stop()),this.hardwareStream=null)}async waitForVideoFlow(){return new Promise(t=>{let r=()=>{if(this.videoElement&&this.videoElement?.readyState>=3)return t();requestAnimationFrame(r)};r()})}async attachAndWarmup(t){this.videoElement=document.createElement("video"),this.videoElement.srcObject=t,this.videoElement.muted=!0,await this.videoElement.play().catch(r=>{}),await new Promise(r=>{if(this.videoElement&&this.videoElement?.readyState>=1)return r();this.videoElement&&(this.videoElement.onloadedmetadata=()=>r())}),console.log("CameraRecorder checking metadata ok"),await this.waitForVideoFlow(),console.log("CameraRecorder waiting for video flow ok"),await new Promise(r=>setTimeout(r,300))}async startRecording(){await this.startStream(),await this.attachAndWarmup(this.cameraStream);let t=this.isChunkEnabled?{timeslice:e.CHUNK_TIMESLICE_MS,onChunkAvailable:(h,d)=>{this.handleNewChunk(h,d)},quality:this.paramsConfig.videoBehaviourParameters?.cameraVideoQuality,timeoutMultiplierFactor:this.paramsConfig.videoBehaviourParameters?.timeoutMultiplierFactor||1}:{},{startRecording:r,stopRecording:n,pauseRecording:i,resumeRecording:o,recorderOptions:s,getBufferSize:a,getStartTime:c,getDuration:l}=Ho(this.cameraStream,this.blobs,this.options.onBufferSizeError,h=>this.bufferError(h),t);this.recordingStart=r,this.recordingStop=n,this.recordingPause=i,this.recordingResume=o,this.recorderOptions=s,this.getBufferSize=a,this.getStartTime=c,this.getDuration=l,this.chunkIndex=0,this.isChunkEnabled&&(this.backgroundUpload?.start(),this.setupLifecycleListeners());try{await new Promise(h=>setTimeout(h,500)),await this.recordingStart()}catch(h){console.log("Camera Recorder error",h),this.stopRecording();let d=this.paramsConfig.videoBehaviourParameters?.maxRetries||3;if(this.currentRetries<d)console.log("Camera Recorder retry",this.currentRetries),this.currentRetries++,await this.startRecording();else throw h}this.stopped=!1,(this.paramsConfig.videoBehaviourParameters?.detectPerson||this.paramsConfig.videoBehaviourParameters?.detectCellPhone||this.paramsConfig.videoBehaviourParameters?.detectFace)&&await this.initializeDetectors(),this.paramsConfig.videoBehaviourParameters?.detectFace&&await this.faceDetection.enableCam(this.cameraStream),(this.paramsConfig.videoBehaviourParameters?.detectPerson||this.paramsConfig.videoBehaviourParameters?.detectCellPhone)&&await this.objectDetection.enableCam(this.cameraStream),this.filesToUpload=[],this.pendingPackages=[],this.options.proctoringType=="REALTIME"&&await this.startRealtimeCapture(),this.packageCount=0,console.log("Camera Recorder started OK")}async stopRecording(){console.log("Camera Recorder stopRecording"),this.stopped=!0,this.isCanvasLoopActive=!1,this.faceDetection&&this.faceDetection.detecting&&this.faceDetection.stopDetection(),this.objectDetection&&this.objectDetection.detecting&&this.objectDetection.stopDetection(),clearInterval(this.imageInterval),clearInterval(this.sendFrameInterval),this.volumeMeter&&this.volumeMeter.stop(),this.intervalNoiseDetection&&clearInterval(this.intervalNoiseDetection),this.recordingStop&&await this.recordingStop(),this.duration=this.getDuration?this.getDuration():0,await new Promise(t=>setTimeout(t,200));try{this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.cameraStream&&this.cameraStream.getTracks().forEach(t=>t.stop()),this.internalClonedStream&&(this.internalClonedStream.getTracks().forEach(t=>t.stop()),this.internalClonedStream=null),this.hardwareStream&&(this.hardwareStream.getTracks().forEach(t=>t.stop()),this.hardwareStream=null),this.videoElement&&(this.videoElement?.remove(),this.videoElement=null),this.video&&this.video?.remove(),this.canvas&&this.canvas?.remove()}catch{console.error("Erro ao parar os streams de m\xEDdia.")}if(this.options.proctoringType=="REALTIME"&&this.upload&&this.backendToken&&(this.pendingPackages.push(this.filesToUpload.slice(0,this.filesToUpload.length)),await this.sendPackage(),await this.filesToUpload.splice(0,this.filesToUpload.length)),this.isChunkEnabled){if(this.backgroundUpload){try{this.pendingChunkSaves.length>0&&(console.log(`[CameraRecorder] Aguardando ${this.pendingChunkSaves.length} salvamentos de chunks pendentes...`),await Promise.all(this.pendingChunkSaves)),await this.backgroundUpload.flush()}catch(t){console.warn("[CameraRecorder] Erro ao fazer flush dos chunks:",t)}this.backgroundUpload.stop()}this.removeLifecycleListeners(),this.persistSessionState("FINISHED")}}async handleNewChunk(t,r){if(!this.proctoringId||!this.chunkStorage)return;let n=(async()=>{try{let i=await t.arrayBuffer();await this.chunkStorage.saveChunk({proctoringId:this.proctoringId,chunkIndex:this.chunkIndex,arrayBuffer:i,timestamp:Date.now(),uploaded:0,mimeType:this.recorderOptions?.mimeType||"video/webm"}),this.chunkIndex++,console.log(`[CameraRecorder] Chunk ${this.chunkIndex-1} salvo no IndexedDB.`)}catch(i){console.error("[CameraRecorder] Erro ao salvar chunk no IndexedDB:",i)}})();this.pendingChunkSaves.push(n),n.finally(()=>{this.pendingChunkSaves=this.pendingChunkSaves.filter(i=>i!==n)})}async pauseRecording(){await this.recordingPause()}async resumeRecording(){await this.recordingResume()}async getCurrentImageBase64(){return!this.video||!this.canvas?this.configImageCapture():this.video.srcObject!==this.cameraStream&&(this.video.srcObject=this.cameraStream,await this.video.play()),this.video.paused&&await this.video.play(),await new Promise(t=>{if(this.video.readyState>=2){t();return}let r=()=>{this.video.removeEventListener("loadedmetadata",r),setTimeout(()=>t(),50)};this.video.addEventListener("loadedmetadata",r),setTimeout(()=>{this.video.removeEventListener("loadedmetadata",r),t()},500)}),this.canvas.getContext("2d").drawImage(this.video,0,0,this.canvas.width,this.canvas.height),this.canvas.toDataURL("image/jpeg")}async captureFrame(){let t,r=this.paramsConfig.videoBehaviourParameters?.realtimePackageSize;this.canvas.getContext("2d").drawImage(this.video,0,0,this.canvas.width,this.canvas.height);let n=this.canvas.toDataURL("image/jpeg");if(this.proctoringId==null)return;r==this.imageCount&&(this.imageCount=0,this.pendingPackages.push(this.filesToUpload.slice(0,r)),this.sendPackage(),await this.filesToUpload.splice(0,r));let i=`${this.proctoringId}_${this.imageCount+1}.jpg`;t=await this.getFile(n,i,"image/jpeg"),t&&t.size>10&&r>0&&(this.filesToUpload.push(t),this.imageCount++)}async startRealtimeCapture(){this.configImageCapture(),this.imageCount=0,this.pendingPackages=[],await this.captureFrame(),this.imageInterval=setInterval(async()=>{await this.captureFrame()},this.paramsConfig.videoBehaviourParameters?.realtimeCaptureInterval*1e3)}async sendPackage(){let t=this.paramsConfig.videoBehaviourParameters?.realtimePackageSize,r=this.paramsConfig.videoBehaviourParameters?.realtimeCaptureInterval;if(this.upload&&this.backendToken&&this.pendingPackages.length>0){let n=[],i=0;for(let o of this.pendingPackages){let s=new p0.default;for(let h of o)s.file(h.name,h);let a=await s.generateAsync({type:"blob"}),c="realtime_package_"+t*r*this.packageCount+".zip",l=new File([a],c,{type:"application/zip"});try{await this.upload.uploadPackage({file:l},this.backendToken)==!0&&(this.packageCount++,this.failedUploads=0,n.push(i++))}catch{this.failedUploads++,this.failedUploads>=2&&this.options.onRealtimeAlertsCallback({status:"ALERT",description:"Realtime n\xE3o est\xE1 enviando pacotes",type:"error_upload_package",category:"error_upload_package",begin:0,end:0});break}}for(let o of n)await this.pendingPackages.splice(o,1)}}download(t){let r=URL.createObjectURL(t),n=document.createElement("a");document.body.appendChild(n),n.style.display="none",n.href=r,n.download=t.name,n.click(),window.URL.revokeObjectURL(r)}async saveOnSession(t){this.blobs!=null&&de.registerSaveOnSession(this.proctoringId,`Blobs Length: ${this.blobs.length} Buffer Size: ${this.getBufferSize()} ChunkEnabled: ${this.isChunkEnabled}`);let r=this.cameraStream.getVideoTracks()[0].getSettings(),n=this.cameraStream.getAudioTracks()[0].getSettings(),i=!1;if(this.isChunkEnabled&&this.backend&&this.backendToken&&this.proctoringId){let o=`EP_${this.proctoringId}_camera_0.webm`,s=`${this.proctoringId}/${o}`;i=await this.backend.checkUpload(this.backendToken,s,"video/webm"),this.chunkStorage&&await this.chunkStorage.clearAllChunks(t.id)}if(!i){let o=new Blob(this.blobs,{type:this.recorderOptions?.mimeType||"video/webm"}),s=o;if(typeof d0=="function")try{s=await d0(o,this.duration)}catch(a){console.warn("Erro ao corrigir a dura\xE7\xE3o do v\xEDdeo",a),s=o}else console.warn("fixWebmDuration n\xE3o dispon\xEDvel");t.addRecording({device:`Audio
|
|
86
86
|
Sample Rate: ${n.sampleRate}
|
|
87
87
|
Sample Size: ${n.sampleSize}
|
|
88
88
|
|