easyproctor-hml 2.5.25 → 2.5.27

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/esm/index.js CHANGED
@@ -12333,10 +12333,16 @@ function recorder(stream, buffer, videoOptions, onBufferSizeError = false, onBuf
12333
12333
  }
12334
12334
  console.log("startRecording", timeSlice);
12335
12335
  try {
12336
- mediaRecorder.start(timeSlice);
12337
12336
  mediaRecorder.onstart = () => {
12338
12337
  console.log("Grava\xE7\xE3o iniciada com sucesso!");
12339
12338
  };
12339
+ mediaRecorder.onerror = (e3) => {
12340
+ console.error("Erro no MediaRecorder:", e3);
12341
+ };
12342
+ console.log("mediaRecorder.state", mediaRecorder.state);
12343
+ console.log(stream.active);
12344
+ console.log(stream.getTracks().map((t3) => t3.readyState));
12345
+ mediaRecorder.start(timeSlice);
12340
12346
  } catch (e3) {
12341
12347
  console.error("Falha ao iniciar:", e3);
12342
12348
  }
@@ -12703,6 +12709,7 @@ var VolumeMeter = class {
12703
12709
  if (this.animationFrameId !== null) {
12704
12710
  cancelAnimationFrame(this.animationFrameId);
12705
12711
  }
12712
+ this.audioContext.close();
12706
12713
  this.microphone.disconnect();
12707
12714
  this.analyser.disconnect();
12708
12715
  }
@@ -12986,6 +12993,7 @@ Setting: ${JSON.stringify(settings, null, 2)}`
12986
12993
  console.log("startRecording Camera Recorder finished");
12987
12994
  }
12988
12995
  async stopRecording() {
12996
+ console.log("Stopping Camera Recorder...");
12989
12997
  this.isCanvasLoopActive = false;
12990
12998
  this.recordingStop && await this.recordingStop();
12991
12999
  try {
@@ -22074,9 +22082,11 @@ var Proctoring = class {
22074
22082
  setDeviceCheckData(data) {
22075
22083
  this.deviceData = data;
22076
22084
  }
22077
- createRecorders(options = getDefaultProctoringOptions) {
22078
- var _a2, _b;
22085
+ async createRecorders(options = getDefaultProctoringOptions) {
22086
+ var _a2, _b, _c2;
22079
22087
  this.onChangeDevices();
22088
+ console.log("Creating Recorders...");
22089
+ await ((_a2 = this.recorder) == null ? void 0 : _a2.stopAll());
22080
22090
  const cameraRecorder = new CameraRecorder(
22081
22091
  {
22082
22092
  cameraId: this.sessionOptions.cameraId,
@@ -22101,8 +22111,8 @@ var Proctoring = class {
22101
22111
  this.context.token
22102
22112
  );
22103
22113
  const screenRecorder = this.sessionOptions.captureScreen ? new ScreenRecorder({
22104
- allowOnlyFirstMonitor: (_a2 = this.sessionOptions.allowOnlyFirstMonitor) != null ? _a2 : true,
22105
- allowMultipleMonitors: (_b = this.sessionOptions.allowMultipleMonitors) != null ? _b : true,
22114
+ allowOnlyFirstMonitor: (_b = this.sessionOptions.allowOnlyFirstMonitor) != null ? _b : true,
22115
+ allowMultipleMonitors: (_c2 = this.sessionOptions.allowMultipleMonitors) != null ? _c2 : true,
22106
22116
  screenRecorderOptions: this.sessionOptions.screenRecorderOptions,
22107
22117
  onStopSharingScreenCallback: () => this.onStopSharingScreenCallback(),
22108
22118
  onBufferSizeError: this.sessionOptions.onBufferSizeError,
@@ -22173,7 +22183,7 @@ var Proctoring = class {
22173
22183
  await this.repository.clear();
22174
22184
  }
22175
22185
  this.proctoringSession = new ProctoringSession();
22176
- this.allRecorders = this.createRecorders(this.sessionOptions);
22186
+ this.allRecorders = await this.createRecorders(this.sessionOptions);
22177
22187
  const startResponse = await this.backend.confirmStart(
22178
22188
  {
22179
22189
  clientId: this.context.clientId,
package/index.js CHANGED
@@ -30430,10 +30430,16 @@ function recorder(stream4, buffer, videoOptions, onBufferSizeError = false, onBu
30430
30430
  }
30431
30431
  console.log("startRecording", timeSlice);
30432
30432
  try {
30433
- mediaRecorder.start(timeSlice);
30434
30433
  mediaRecorder.onstart = () => {
30435
30434
  console.log("Grava\xE7\xE3o iniciada com sucesso!");
30436
30435
  };
30436
+ mediaRecorder.onerror = (e3) => {
30437
+ console.error("Erro no MediaRecorder:", e3);
30438
+ };
30439
+ console.log("mediaRecorder.state", mediaRecorder.state);
30440
+ console.log(stream4.active);
30441
+ console.log(stream4.getTracks().map((t3) => t3.readyState));
30442
+ mediaRecorder.start(timeSlice);
30437
30443
  } catch (e3) {
30438
30444
  console.error("Falha ao iniciar:", e3);
30439
30445
  }
@@ -30800,6 +30806,7 @@ var VolumeMeter = class {
30800
30806
  if (this.animationFrameId !== null) {
30801
30807
  cancelAnimationFrame(this.animationFrameId);
30802
30808
  }
30809
+ this.audioContext.close();
30803
30810
  this.microphone.disconnect();
30804
30811
  this.analyser.disconnect();
30805
30812
  }
@@ -31083,6 +31090,7 @@ Setting: ${JSON.stringify(settings, null, 2)}`
31083
31090
  console.log("startRecording Camera Recorder finished");
31084
31091
  }
31085
31092
  async stopRecording() {
31093
+ console.log("Stopping Camera Recorder...");
31086
31094
  this.isCanvasLoopActive = false;
31087
31095
  this.recordingStop && await this.recordingStop();
31088
31096
  try {
@@ -37323,9 +37331,11 @@ var Proctoring = class {
37323
37331
  setDeviceCheckData(data) {
37324
37332
  this.deviceData = data;
37325
37333
  }
37326
- createRecorders(options = getDefaultProctoringOptions) {
37327
- var _a2, _b;
37334
+ async createRecorders(options = getDefaultProctoringOptions) {
37335
+ var _a2, _b, _c2;
37328
37336
  this.onChangeDevices();
37337
+ console.log("Creating Recorders...");
37338
+ await ((_a2 = this.recorder) == null ? void 0 : _a2.stopAll());
37329
37339
  const cameraRecorder = new CameraRecorder(
37330
37340
  {
37331
37341
  cameraId: this.sessionOptions.cameraId,
@@ -37350,8 +37360,8 @@ var Proctoring = class {
37350
37360
  this.context.token
37351
37361
  );
37352
37362
  const screenRecorder = this.sessionOptions.captureScreen ? new ScreenRecorder({
37353
- allowOnlyFirstMonitor: (_a2 = this.sessionOptions.allowOnlyFirstMonitor) != null ? _a2 : true,
37354
- allowMultipleMonitors: (_b = this.sessionOptions.allowMultipleMonitors) != null ? _b : true,
37363
+ allowOnlyFirstMonitor: (_b = this.sessionOptions.allowOnlyFirstMonitor) != null ? _b : true,
37364
+ allowMultipleMonitors: (_c2 = this.sessionOptions.allowMultipleMonitors) != null ? _c2 : true,
37355
37365
  screenRecorderOptions: this.sessionOptions.screenRecorderOptions,
37356
37366
  onStopSharingScreenCallback: () => this.onStopSharingScreenCallback(),
37357
37367
  onBufferSizeError: this.sessionOptions.onBufferSizeError,
@@ -37422,7 +37432,7 @@ var Proctoring = class {
37422
37432
  await this.repository.clear();
37423
37433
  }
37424
37434
  this.proctoringSession = new ProctoringSession();
37425
- this.allRecorders = this.createRecorders(this.sessionOptions);
37435
+ this.allRecorders = await this.createRecorders(this.sessionOptions);
37426
37436
  const startResponse = await this.backend.confirmStart(
37427
37437
  {
37428
37438
  clientId: this.context.clientId,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "easyproctor-hml",
3
- "version": "2.5.25",
3
+ "version": "2.5.27",
4
4
  "description": "Modulo web de gravação do EasyProctor",
5
5
  "main": "./index.js",
6
6
  "module": "./esm/index.js",
@@ -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[Ag]=this[Ag]={accessors:{}}).accessors,i=this.prototype;function o(s){let a=Lo(s);n[a]||(Qv(i,s),n[a]=!0)}return T.isArray(t)?t.forEach(o):o(t),this}};Ni.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);T.reduceDescriptors(Ni.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(n){this[r]=n}}});T.freezeMethods(Ni);var at=Ni;function Fo(e,t){let r=this||Ui,n=t||r,i=at.from(n.headers),o=n.data;return T.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 Tg(e,t,r){le.call(this,e??"canceled",le.ERR_CANCELED,t,r),this.name="CanceledError"}T.inherits(Tg,le,{__CANCEL__:!0});var Br=Tg;function Uo(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 ad(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function e_(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,m=0;for(;d!==i;)m+=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(m*1e3/p):void 0}}var Ig=e_;function t_(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 Rg=t_;var zi=(e,t,r=3)=>{let n=0,i=Ig(50,250);return Rg(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)},cd=(e,t)=>{let r=e!=null;return[n=>t[0]({lengthComputable:r,total:e,loaded:n}),t[1]]},ld=e=>(...t)=>T.asap(()=>e(...t));var Pg=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 Dg=je.hasStandardBrowserEnv?{write(e,t,r,n,i,o){let s=[e+"="+encodeURIComponent(t)];T.isNumber(r)&&s.push("expires="+new Date(r).toGMTString()),T.isString(n)&&s.push("path="+n),T.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 hd(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function dd(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function No(e,t,r){let n=!hd(t);return e&&(n||r==!1)?dd(e,t):t}var Og=e=>e instanceof at?{...e}:e;function br(e,t){t=t||{};let r={};function n(l,h,d,m){return T.isPlainObject(l)&&T.isPlainObject(h)?T.merge.call({caseless:m},l,h):T.isPlainObject(h)?T.merge({},h):T.isArray(h)?h.slice():h}function i(l,h,d,m){if(T.isUndefined(h)){if(!T.isUndefined(l))return n(void 0,l,d,m)}else return n(l,h,d,m)}function o(l,h){if(!T.isUndefined(h))return n(void 0,h)}function s(l,h){if(T.isUndefined(h)){if(!T.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(Og(l),Og(h),d,!0)};return T.forEach(Object.keys(Object.assign({},e,t)),function(h){let d=c[h]||i,m=d(e[h],t[h],h);T.isUndefined(m)&&d!==a||(r[h]=m)}),r}var Ca=e=>{let t=br({},e),{data:r,withXSRFToken:n,xsrfHeaderName:i,xsrfCookieName:o,headers:s,auth:a}=t;t.headers=s=at.from(s),t.url=Bo(No(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(T.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&&T.isFunction(n)&&(n=n(t)),n||n!==!1&&Pg(t.url))){let l=i&&o&&Dg.read(o);l&&s.set(i,l)}return t};var r_=typeof XMLHttpRequest<"u",Bg=r_&&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,m,p,g;function f(){p&&p(),g&&g(),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 _(){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};Uo(function(P){r(P),f()},function(P){n(P),f()},x),b=null}"onloadend"in b?b.onloadend=_:b.onreadystatechange=function(){!b||b.readyState!==4||b.status===0&&!(b.responseURL&&b.responseURL.indexOf("file:")===0)||setTimeout(_)},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 I=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded",x=i.transitional||Sa;i.timeoutErrorMessage&&(I=i.timeoutErrorMessage),n(new le(I,x.clarifyTimeoutError?le.ETIMEDOUT:le.ECONNABORTED,e,b)),b=null},o===void 0&&s.setContentType(null),"setRequestHeader"in b&&T.forEach(s.toJSON(),function(I,x){b.setRequestHeader(x,I)}),T.isUndefined(i.withCredentials)||(b.withCredentials=!!i.withCredentials),a&&a!=="json"&&(b.responseType=i.responseType),l&&([m,g]=zi(l,!0),b.addEventListener("progress",m)),c&&b.upload&&([d,p]=zi(c),b.upload.addEventListener("progress",d),b.upload.addEventListener("loadend",p)),(i.cancelToken||i.signal)&&(h=k=>{b&&(n(!k||k.type?new Br(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=ad(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 n_=(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 Br(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=()=>T.asap(a),c}},Lg=n_;var i_=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},o_=async function*(e,t){for await(let r of s_(e))yield*i_(r,t)},s_=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()}},ud=(e,t,r,n)=>{let i=o_(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 m=o+=d;r(m)}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",Mg=Aa&&typeof ReadableStream=="function",a_=Aa&&(typeof TextEncoder=="function"?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),Ug=(e,...t)=>{try{return!!e(...t)}catch{return!1}},c_=Mg&&Ug(()=>{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}),Fg=64*1024,fd=Mg&&Ug(()=>T.isReadableStream(new Response("").body)),xa={stream:fd&&(e=>e.body)};Aa&&(e=>{["text","arrayBuffer","blob","formData","stream"].forEach(t=>{!xa[t]&&(xa[t]=T.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 l_=async e=>{if(e==null)return 0;if(T.isBlob(e))return e.size;if(T.isSpecCompliantForm(e))return(await new Request(je.origin,{method:"POST",body:e}).arrayBuffer()).byteLength;if(T.isArrayBufferView(e)||T.isArrayBuffer(e))return e.byteLength;if(T.isURLSearchParams(e)&&(e=e+""),T.isString(e))return(await a_(e)).byteLength},h_=async(e,t)=>{let r=T.toFiniteNumber(e.getContentLength());return r??l_(t)},Ng=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:m}=Ca(e);l=l?(l+"").toLowerCase():"text";let p=Lg([i,o&&o.toAbortSignal()],s),g,f=p&&p.unsubscribe&&(()=>{p.unsubscribe()}),b;try{if(c&&c_&&r!=="get"&&r!=="head"&&(b=await h_(h,n))!==0){let x=new Request(t,{method:"POST",body:n,duplex:"half"}),O;if(T.isFormData(n)&&(O=x.headers.get("content-type"))&&h.setContentType(O),x.body){let[P,z]=cd(b,zi(ld(c)));n=ud(x.body,Fg,P,z)}}T.isString(d)||(d=d?"include":"omit");let _="credentials"in Request.prototype;g=new Request(t,{...m,signal:p,method:r.toUpperCase(),headers:h.normalize().toJSON(),body:n,duplex:"half",credentials:_?d:void 0});let S=await fetch(g),k=fd&&(l==="stream"||l==="response");if(fd&&(a||k&&f)){let x={};["status","statusText","headers"].forEach(Z=>{x[Z]=S[Z]});let O=T.toFiniteNumber(S.headers.get("content-length")),[P,z]=a&&cd(O,zi(ld(a),!0))||[];S=new Response(ud(S.body,Fg,P,()=>{z&&z(),f&&f()}),x)}l=l||"text";let I=await xa[T.findKey(xa,l)||"text"](S,e);return!k&&f&&f(),await new Promise((x,O)=>{Uo(x,O,{data:I,headers:at.from(S.headers),status:S.status,statusText:S.statusText,config:e,request:g})})}catch(_){throw f&&f(),_&&_.name==="TypeError"&&/fetch/i.test(_.message)?Object.assign(new le("Network Error",le.ERR_NETWORK,e,g),{cause:_.cause||_}):le.from(_,_&&_.code,e,g)}});var pd={http:_a,xhr:Bg,fetch:Ng};T.forEach(pd,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});var zg=e=>`- ${e}`,d_=e=>T.isFunction(e)||e===null||e===!1,Ta={getAdapter:e=>{e=T.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,!d_(r)&&(n=pd[(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(zg).join(`
70
70
  `):" "+zg(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:pd};function md(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Br(null,e)}function Ia(e){return md(e),e.headers=at.from(e.headers),e.data=Fo.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),Ta.getAdapter(e.adapter||Ui.adapter)(e).then(function(n){return md(e),n.data=Fo.call(e,e.transformResponse,n),n.headers=at.from(n.headers),n},function(n){return Mo(n)||(md(e),n&&n.response&&(n.response.data=Fo.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 jg={};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&&!jg[s]&&(jg[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 u_(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 zo={assertOptions:u_,validators:Pa};var Lr=zo.validators,ji=class{constructor(t){this.defaults=t,this.interceptors={request:new ed,response:new ed}}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=br(this.defaults,r);let{transitional:n,paramsSerializer:i,headers:o}=r;n!==void 0&&zo.assertOptions(n,{silentJSONParsing:Lr.transitional(Lr.boolean),forcedJSONParsing:Lr.transitional(Lr.boolean),clarifyTimeoutError:Lr.transitional(Lr.boolean)},!1),i!=null&&(T.isFunction(i)?r.paramsSerializer={serialize:i}:zo.assertOptions(i,{encode:Lr.function,serialize:Lr.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),zo.assertOptions(r,{baseUrl:Lr.spelling("baseURL"),withXsrfToken:Lr.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let s=o&&T.merge(o.common,o[r.method]);o&&T.forEach(["delete","get","head","post","put","patch","common"],g=>{delete o[g]}),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,m;if(!c){let g=[Ia.bind(this),void 0];for(g.unshift.apply(g,a),g.push.apply(g,l),m=g.length,h=Promise.resolve(r);d<m;)h=h.then(g[d++],g[d++]);return h}m=a.length;let p=r;for(d=0;d<m;){let g=a[d++],f=a[d++];try{p=g(p)}catch(b){f.call(this,b);break}}try{h=Ia.call(this,p)}catch(g){return Promise.reject(g)}for(d=0,m=l.length;d<m;)h=h.then(l[d++],l[d++]);return h}getUri(t){t=br(this.defaults,t);let r=No(t.baseURL,t.url,t.allowAbsoluteUrls);return Bo(r,t.params,t.paramsSerializer)}};T.forEach(["delete","get","head","options"],function(t){ji.prototype[t]=function(r,n){return this.request(br(n||{},{method:t,url:r,data:(n||{}).data}))}});T.forEach(["post","put","patch"],function(t){function r(n){return function(o,s,a){return this.request(br(a||{},{method:t,headers:n?{"Content-Type":"multipart/form-data"}:{},url:o,data:s}))}}ji.prototype[t]=r(),ji.prototype[t+"Form"]=r(!0)});var jo=ji;var gd=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 Br(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}}},Vg=gd;function yd(e){return function(r){return e.apply(null,r)}}function bd(e){return T.isObject(e)&&e.isAxiosError===!0}var vd={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(vd).forEach(([e,t])=>{vd[t]=e});var Hg=vd;function Wg(e){let t=new jo(e),r=Po(jo.prototype.request,t);return T.extend(r,jo.prototype,t,{allOwnKeys:!0}),T.extend(r,t,null,{allOwnKeys:!0}),r.create=function(i){return Wg(br(e,i))},r}var rt=Wg(Ui);rt.Axios=jo;rt.CanceledError=Br;rt.CancelToken=Vg;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=yd;rt.isAxiosError=bd;rt.mergeConfig=br;rt.AxiosHeaders=at;rt.formToJSON=e=>ka(T.isHTMLForm(e)?new FormData(e):e);rt.getAdapter=Ta.getAdapter;rt.HttpStatusCode=Hg;rt.default=rt;var vr=rt;var{Axios:kC,AxiosError:EC,CanceledError:CC,isCancel:xC,CancelToken:AC,VERSION:TC,all:IC,Cancel:RC,isAxiosError:PC,spread:DC,toFormData:OC,AxiosHeaders:BC,HttpStatusCode:LC,formToJSON:FC,getAdapter:MC,mergeConfig:UC}=vr;var f_="https://proctoring-api-dev.easyproctor.tech/api",p_="https://proctoring-api-hml.easyproctor.tech/api",$g="https://proctoring-api.easyproctor.tech/api",nr=class{constructor(t){this.options=t;this.baseUrl=this.selectBaseUrl(t.type),this.token=t.token}selectBaseUrl(t){return t==="dev"?f_:t==="homol"?p_:$g}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 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 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 vr.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 vr.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 Hn=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 Vi=class{constructor(t,r){this.backendService=new Da;this.scanInterval=5;this.options={};this.options=r,this.context=t,this.backend=new nr({type:t?.type||"prod",token:t.token}),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 Hn;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 Hn;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 ir={cameraId:void 0,microphoneId:void 0,allowMultipleMonitors:!1,allowOnlyFirstMonitor:!0,captureScreen:!0,noiseLimit:40,proctoringType:"IMAGE",insights:"",onBufferSizeError:!1,useGeolocation:!1,useSpyScan:!1,useExternalCamera:!1,useChallenge:!1,screenRecorderOptions:{width:1280,height:720}};function Oa(e){return e.width&&e.height?{width:e.width,height:e.height,minWidth:e.minWidth,minHeight:e.minHeight,timeSlice:e.timeSlice,videoBitsPerSecond:e.videoBitsPerSecond,mimeType:e.mimeType}:{width:640,height:480}}var Gg={width:1280,height:720,minWidth:640,minHeight:480};function qg(){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 Fr(){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)}var Ba,Kg=e=>(Ba=e,Ba),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)=>Ba&&Ba.log(e,t),ue={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 Vo;function La(e){Vo=e}function Wn(e,t,r,n=!1,i,o=!1){let s,a=!1,c,l,h;h=0;let d={mimeType:"video/webm",videoBitsPerSecond:128e3,audioBitsPerSecond:64*1e3};MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?d.mimeType="video/webm;codecs=vp9":console.warn("vp9 codec not supported. Using default mimeType without vp9."),r?.mimeType&&(d.mimeType=r?.mimeType),r?.videoBitsPerSecond!=null&&(d.videoBitsPerSecond=r?.videoBitsPerSecond),o&&(d={mimeType:"audio/webm",audioBitsPerSecond:64*1e3}),console.log("recorderOptions bitsPerSecond",d.videoBitsPerSecond);let m=new MediaRecorder(e,d);m.ondataavailable=S=>{if(h=h+S.data.size,console.log("video tracks length > 0",e.getVideoTracks().length>0),e.getVideoTracks().length>0){let k=e.getVideoTracks()[0];console.log(k.readyState),console.log(k.enabled)}S.data.size>0&&t.push(S.data),a?(o&&m.state=="inactive"&&(t=[new Blob(t,{type:"audio/webm"})]),s&&s()):((l&&S.data.size===l.data.size||S.data.size===0)&&(Vo&&l&&S.data.size===l.data.size&&ue.registerOnBufferSizeError(Vo,`onBufferSizeError: Recorder size freezed: ${S.data.size} Mb`),Vo&&S.data.size===0&&ue.registerOnBufferSizeError(Vo,"onBufferSizeError: Recorder size equal 0 Mb"),console.log("onbuffer size error"+S.data.size),i&&i()),l=S)};function p(){return new Promise(S=>{s=S;var k=1e4;r?.timeSlice!=null&&(k=r?.timeSlice),console.log("startRecording",k);try{m.start(k),m.onstart=()=>{console.log("Grava\xE7\xE3o iniciada com sucesso!")}}catch(I){console.error("Falha ao iniciar:",I)}h=0,a=!1})}function g(){return new Promise(S=>{m.state=="recording"?(s=S,m.stop(),a=!0,e.getTracks().forEach(k=>{k.stop()})):S()})}function f(){return new Promise(S=>{m.state=="recording"&&m.pause(),S()})}function b(){return new Promise(S=>{m.state=="paused"&&m.resume(),S()})}function _(){return h}return{startRecording:p,stopRecording:g,pauseRecording:f,resumeRecording:b,recorderOptions:d,getBufferSize:_}}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,onProgress:i}=t;try{let o=c=>{let l=c.loadedBytes/n.size*100;i&&i(Math.round(l))},s=await this.backend.getSignedUrl(r,n,this.proctoringId),a=await vr.request({url:s,method:"PUT",headers:{"Content-Type":n.type,"x-ms-blob-type":"BlockBlob"},data:n,onUploadProgress:c=>{o({loadedBytes:c.loaded})}}).then(()=>!0).catch(()=>!1);return{storage:"upload",url:s,uploaded:a}}catch{throw ue.registerError(this.proctoringId,`Failed to upload to AWS
71
+ `+o):n.stack=o}catch{}}throw n}}_request(t,r){typeof t=="string"?(r=r||{},r.url=t):r=t||{},r=br(this.defaults,r);let{transitional:n,paramsSerializer:i,headers:o}=r;n!==void 0&&zo.assertOptions(n,{silentJSONParsing:Lr.transitional(Lr.boolean),forcedJSONParsing:Lr.transitional(Lr.boolean),clarifyTimeoutError:Lr.transitional(Lr.boolean)},!1),i!=null&&(T.isFunction(i)?r.paramsSerializer={serialize:i}:zo.assertOptions(i,{encode:Lr.function,serialize:Lr.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),zo.assertOptions(r,{baseUrl:Lr.spelling("baseURL"),withXsrfToken:Lr.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let s=o&&T.merge(o.common,o[r.method]);o&&T.forEach(["delete","get","head","post","put","patch","common"],g=>{delete o[g]}),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,m;if(!c){let g=[Ia.bind(this),void 0];for(g.unshift.apply(g,a),g.push.apply(g,l),m=g.length,h=Promise.resolve(r);d<m;)h=h.then(g[d++],g[d++]);return h}m=a.length;let p=r;for(d=0;d<m;){let g=a[d++],f=a[d++];try{p=g(p)}catch(b){f.call(this,b);break}}try{h=Ia.call(this,p)}catch(g){return Promise.reject(g)}for(d=0,m=l.length;d<m;)h=h.then(l[d++],l[d++]);return h}getUri(t){t=br(this.defaults,t);let r=No(t.baseURL,t.url,t.allowAbsoluteUrls);return Bo(r,t.params,t.paramsSerializer)}};T.forEach(["delete","get","head","options"],function(t){ji.prototype[t]=function(r,n){return this.request(br(n||{},{method:t,url:r,data:(n||{}).data}))}});T.forEach(["post","put","patch"],function(t){function r(n){return function(o,s,a){return this.request(br(a||{},{method:t,headers:n?{"Content-Type":"multipart/form-data"}:{},url:o,data:s}))}}ji.prototype[t]=r(),ji.prototype[t+"Form"]=r(!0)});var jo=ji;var gd=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 Br(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}}},Vg=gd;function yd(e){return function(r){return e.apply(null,r)}}function bd(e){return T.isObject(e)&&e.isAxiosError===!0}var vd={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(vd).forEach(([e,t])=>{vd[t]=e});var Hg=vd;function Wg(e){let t=new jo(e),r=Po(jo.prototype.request,t);return T.extend(r,jo.prototype,t,{allOwnKeys:!0}),T.extend(r,t,null,{allOwnKeys:!0}),r.create=function(i){return Wg(br(e,i))},r}var rt=Wg(Ui);rt.Axios=jo;rt.CanceledError=Br;rt.CancelToken=Vg;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=yd;rt.isAxiosError=bd;rt.mergeConfig=br;rt.AxiosHeaders=at;rt.formToJSON=e=>ka(T.isHTMLForm(e)?new FormData(e):e);rt.getAdapter=Ta.getAdapter;rt.HttpStatusCode=Hg;rt.default=rt;var vr=rt;var{Axios:kC,AxiosError:EC,CanceledError:CC,isCancel:xC,CancelToken:AC,VERSION:TC,all:IC,Cancel:RC,isAxiosError:PC,spread:DC,toFormData:OC,AxiosHeaders:BC,HttpStatusCode:LC,formToJSON:FC,getAdapter:MC,mergeConfig:UC}=vr;var f_="https://proctoring-api-dev.easyproctor.tech/api",p_="https://proctoring-api-hml.easyproctor.tech/api",$g="https://proctoring-api.easyproctor.tech/api",nr=class{constructor(t){this.options=t;this.baseUrl=this.selectBaseUrl(t.type),this.token=t.token}selectBaseUrl(t){return t==="dev"?f_:t==="homol"?p_:$g}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 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 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 vr.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 vr.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 Hn=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 Vi=class{constructor(t,r){this.backendService=new Da;this.scanInterval=5;this.options={};this.options=r,this.context=t,this.backend=new nr({type:t?.type||"prod",token:t.token}),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 Hn;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 Hn;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 ir={cameraId:void 0,microphoneId:void 0,allowMultipleMonitors:!1,allowOnlyFirstMonitor:!0,captureScreen:!0,noiseLimit:40,proctoringType:"IMAGE",insights:"",onBufferSizeError:!1,useGeolocation:!1,useSpyScan:!1,useExternalCamera:!1,useChallenge:!1,screenRecorderOptions:{width:1280,height:720}};function Oa(e){return e.width&&e.height?{width:e.width,height:e.height,minWidth:e.minWidth,minHeight:e.minHeight,timeSlice:e.timeSlice,videoBitsPerSecond:e.videoBitsPerSecond,mimeType:e.mimeType}:{width:640,height:480}}var Gg={width:1280,height:720,minWidth:640,minHeight:480};function qg(){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 Fr(){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)}var Ba,Kg=e=>(Ba=e,Ba),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)=>Ba&&Ba.log(e,t),ue={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 Vo;function La(e){Vo=e}function Wn(e,t,r,n=!1,i,o=!1){let s,a=!1,c,l,h;h=0;let d={mimeType:"video/webm",videoBitsPerSecond:128e3,audioBitsPerSecond:64*1e3};MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?d.mimeType="video/webm;codecs=vp9":console.warn("vp9 codec not supported. Using default mimeType without vp9."),r?.mimeType&&(d.mimeType=r?.mimeType),r?.videoBitsPerSecond!=null&&(d.videoBitsPerSecond=r?.videoBitsPerSecond),o&&(d={mimeType:"audio/webm",audioBitsPerSecond:64*1e3}),console.log("recorderOptions bitsPerSecond",d.videoBitsPerSecond);let m=new MediaRecorder(e,d);m.ondataavailable=S=>{if(h=h+S.data.size,console.log("video tracks length > 0",e.getVideoTracks().length>0),e.getVideoTracks().length>0){let k=e.getVideoTracks()[0];console.log(k.readyState),console.log(k.enabled)}S.data.size>0&&t.push(S.data),a?(o&&m.state=="inactive"&&(t=[new Blob(t,{type:"audio/webm"})]),s&&s()):((l&&S.data.size===l.data.size||S.data.size===0)&&(Vo&&l&&S.data.size===l.data.size&&ue.registerOnBufferSizeError(Vo,`onBufferSizeError: Recorder size freezed: ${S.data.size} Mb`),Vo&&S.data.size===0&&ue.registerOnBufferSizeError(Vo,"onBufferSizeError: Recorder size equal 0 Mb"),console.log("onbuffer size error"+S.data.size),i&&i()),l=S)};function p(){return new Promise(S=>{s=S;var k=1e4;r?.timeSlice!=null&&(k=r?.timeSlice),console.log("startRecording",k);try{m.onstart=()=>{console.log("Grava\xE7\xE3o iniciada com sucesso!")},m.onerror=I=>{console.error("Erro no MediaRecorder:",I)},console.log("mediaRecorder.state",m.state),console.log(e.active),console.log(e.getTracks().map(I=>I.readyState)),m.start(k)}catch(I){console.error("Falha ao iniciar:",I)}h=0,a=!1})}function g(){return new Promise(S=>{m.state=="recording"?(s=S,m.stop(),a=!0,e.getTracks().forEach(k=>{k.stop()})):S()})}function f(){return new Promise(S=>{m.state=="recording"&&m.pause(),S()})}function b(){return new Promise(S=>{m.state=="paused"&&m.resume(),S()})}function _(){return h}return{startRecording:p,stopRecording:g,pauseRecording:f,resumeRecording:b,recorderOptions:d,getBufferSize:_}}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,onProgress:i}=t;try{let o=c=>{let l=c.loadedBytes/n.size*100;i&&i(Math.round(l))},s=await this.backend.getSignedUrl(r,n,this.proctoringId),a=await vr.request({url:s,method:"PUT",headers:{"Content-Type":n.type,"x-ms-blob-type":"BlockBlob"},data:n,onUploadProgress:c=>{o({loadedBytes:c.loaded})}}).then(()=>!0).catch(()=>!1);return{storage:"upload",url:s,uploaded:a}}catch{throw ue.registerError(this.proctoringId,`Failed to upload to AWS
72
72
  File name: ${n.name}
73
73
  File type: ${n.type}
74
74
  File size: ${n.size}`),new Error("Failed to upload to AWS")}}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 m=`${this.proctoringId}/${this.proctoringId}_${d+1}.jpg`;(d+1)%n==0&&(m=`${this.proctoringId}/${this.proctoringId}_${d+1}_realtime.jpg`),l.push({objectName:m,contentType:"image/jpeg"})}(await this.backend.getSignedUrlImage(r,l)).map(d=>{this.imageUrlPackage.push(d)}),this.imageBatchNum+=60}let c=!1;return c=await vr.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 ue.registerError(this.proctoringId,`Failed to upload to AWS
@@ -77,11 +77,11 @@ Minimum version required to store current data is: `+o+`.
77
77
  File size: ${i.size}`),new Error("Failed to upload to AWS")}}async upload(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(n){if(this.imageBatchNum===this.contImages){let l=[];for(let d=this.imageBatchNum;d<this.imageBatchNum+20;d++)l.push({objectName:`${this.proctoringId}/${this.proctoringId}_${d+1}.jpg`,contentType:"image/jpeg"});(await this.backend.getSignedUrlImage(r,l)).map(d=>{this.imageUrlPackage.push(d)}),this.imageBatchNum+=20}}else a=await this.backend.getSignedUrl(r,i,this.proctoringId);let c=!1;return n?c=await vr.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(()=>!0).catch(()=>!1).finally(()=>{this.contImages++}):c=await vr.request({url:a,method:"PUT",headers:{"Content-Type":i.type,"x-ms-blob-type":"BlockBlob"},data:i,onUploadProgress:l=>{s({loadedBytes:l.loaded})}}).then(()=>!0).catch(()=>!1),{storage:"upload",url:a,uploaded:c}}catch{throw ue.registerError(this.proctoringId,`Failed to upload to AWS
78
78
  File name: ${i.name}
79
79
  File type: ${i.type}
80
- File size: ${i.size}`),new Error("Failed to upload to AWS")}}};var Xg="not_shared_first_screen",Jg="not_shared_screen",Fa="multiple_monitors_detected",Yg="proctoring_already_started",Ma="proctoring_not_started";var Sd="another_stream_active",kd="stream_under_minimum_permitted",Zg="browser_not_supported",Qg="token_missing",e0="credentials_missing";var t0="spy_scan_api_not_found";var r0="external_camera_not_started";var Ua=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,m=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 g={zIndex:"2",position:"absolute",border:"1px dashed #fff"};Object.assign(p.style,{...g,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=m-20+"px",Object.assign(f.style,{...g,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 gn=class{constructor(t){this.volume=null;this.animationFrameId=null;this.stream=t}async start(t={}){return new Promise((r,n)=>{try{this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.microphone=this.audioContext.createMediaStreamSource(this.stream),this.analyser.smoothingTimeConstant=.8,this.analyser.fftSize=1024,this.microphone.connect(this.analyser);let i=()=>{let o=new Uint8Array(this.analyser.frequencyBinCount);this.analyser.getByteFrequencyData(o);let a=o.reduce((c,l)=>c+l,0)/o.length;this.setVolume(a),t.setVolume&&t.setVolume(a),this.animationFrameId=requestAnimationFrame(i)};this.animationFrameId=requestAnimationFrame(i),r(!0)}catch(i){this.stop(),n(`Error: ${i}`)}})}stop(){this.animationFrameId!==null&&cancelAnimationFrame(this.animationFrameId),this.microphone.disconnect(),this.analyser.disconnect()}getVolume(){return this.volume}setVolume(t){this.volume=t}};var s0=ul(i0()),Zr=class{constructor(t,r,n,i,o){this.blobs=[];this.paramsConfig={audioBehaviourParameters:{recordingBitrate:128,noiseLimit:40},imageBehaviourParameters:{useUploadImage:!0,uploadInterval:20,saveVideo:!0},videoBehaviourParameters:{detectPerson:!1,detectFace:!1,detectCellPhone:!1}};this.options={cameraId:void 0,microphoneId:void 0,onBufferSizeError:!1,onBufferSizeErrorCallback:t=>{},proctoringType:"IMAGE",onChangeDevicesCallback:t=>{},onRealtimeAlertsCallback:t=>{}};this.videoOptions={width:640,height:480,minWidth:0,minHeight:0};this.blobsRTC=[];this.imageCount=0;this.filesToUpload=[];this.animationFrameId=null;this.isCanvasLoopActive=!1;this.hardwareStream=null;this.internalClonedStream=null;this.currentRetries=0;this.packageCount=0;this.noiseWait=20;this.options=t,this.videoOptions=r,this.backend=i,this.backendToken=o,n&&(this.paramsConfig=n)}setProctoringId(t){this.proctoringId=t,this.proctoringId&&this.backend&&(this.upload=new Yr(this.proctoringId,this.backend)),La(t)}async initializeDetectors(){ag(),(this.paramsConfig.videoBehaviourParameters?.detectPerson||this.paramsConfig.videoBehaviourParameters?.detectCellPhone)&&(this.objectDetection=new Ua({onRealtimeAlertsCallback:t=>this.options.onRealtimeAlertsCallback(t)},this.paramsConfig),await this.objectDetection.initializeDetector()),this.paramsConfig.videoBehaviourParameters?.detectFace&&(this.faceDetection=new Li({onRealtimeAlertsCallback:t=>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")&&Fr()?(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 "+this.paramsConfig.videoBehaviourParameters);let r=this.paramsConfig.videoBehaviourParameters?.retryEnabled||!1,n=this.paramsConfig.videoBehaviourParameters?.maxRetries||3;r&&this.currentRetries<n?(console.log("buffer error Camera Recorder retry"),await this.recordingStop(),await this.startRecording({retry:!0}),this.currentRetries++,this.options.onBufferSizeErrorCallback&&this.options.onBufferSizeErrorCallback(this.cameraStream)):this.options.onBufferSizeErrorCallback&&this.options.onBufferSizeErrorCallback()}async startStream(t){let{cameraId:r,microphoneId:n,onBufferSizeErrorCallback:i}=this.options,o={audio:{deviceId:n},video:{deviceId:r,width:this.videoOptions.width,height:this.videoOptions.height,frameRate:15}};try{this.hardwareStream=await navigator.mediaDevices.getUserMedia(o)}catch(d){throw d.toString()=="NotReadableError: Could not start video source"?"N\xE3o foi poss\xEDvel conectar a camera, ela pode estar sendo utilizada por outro programa":d}this.cameraStream=this.hardwareStream;let a=this.cameraStream.getVideoTracks()[0].getSettings(),{width:c=0,height:l=0}=a;if(screen.orientation?.type.includes("portrait")&&Fr()&&this.videoOptions.width==l&&this.videoOptions.height==c&&([c,l]=[l,c]),this.videoOptions.minWidth>c||this.videoOptions.minHeight>l)throw kd;if(this.videoOptions.width!==c||this.videoOptions.height!==l)throw ue.registerAnotherStream(this.proctoringId,`Maybe have another stream active
80
+ File size: ${i.size}`),new Error("Failed to upload to AWS")}}};var Xg="not_shared_first_screen",Jg="not_shared_screen",Fa="multiple_monitors_detected",Yg="proctoring_already_started",Ma="proctoring_not_started";var Sd="another_stream_active",kd="stream_under_minimum_permitted",Zg="browser_not_supported",Qg="token_missing",e0="credentials_missing";var t0="spy_scan_api_not_found";var r0="external_camera_not_started";var Ua=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,m=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 g={zIndex:"2",position:"absolute",border:"1px dashed #fff"};Object.assign(p.style,{...g,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=m-20+"px",Object.assign(f.style,{...g,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 gn=class{constructor(t){this.volume=null;this.animationFrameId=null;this.stream=t}async start(t={}){return new Promise((r,n)=>{try{this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.microphone=this.audioContext.createMediaStreamSource(this.stream),this.analyser.smoothingTimeConstant=.8,this.analyser.fftSize=1024,this.microphone.connect(this.analyser);let i=()=>{let o=new Uint8Array(this.analyser.frequencyBinCount);this.analyser.getByteFrequencyData(o);let a=o.reduce((c,l)=>c+l,0)/o.length;this.setVolume(a),t.setVolume&&t.setVolume(a),this.animationFrameId=requestAnimationFrame(i)};this.animationFrameId=requestAnimationFrame(i),r(!0)}catch(i){this.stop(),n(`Error: ${i}`)}})}stop(){this.animationFrameId!==null&&cancelAnimationFrame(this.animationFrameId),this.audioContext.close(),this.microphone.disconnect(),this.analyser.disconnect()}getVolume(){return this.volume}setVolume(t){this.volume=t}};var s0=ul(i0()),Zr=class{constructor(t,r,n,i,o){this.blobs=[];this.paramsConfig={audioBehaviourParameters:{recordingBitrate:128,noiseLimit:40},imageBehaviourParameters:{useUploadImage:!0,uploadInterval:20,saveVideo:!0},videoBehaviourParameters:{detectPerson:!1,detectFace:!1,detectCellPhone:!1}};this.options={cameraId:void 0,microphoneId:void 0,onBufferSizeError:!1,onBufferSizeErrorCallback:t=>{},proctoringType:"IMAGE",onChangeDevicesCallback:t=>{},onRealtimeAlertsCallback:t=>{}};this.videoOptions={width:640,height:480,minWidth:0,minHeight:0};this.blobsRTC=[];this.imageCount=0;this.filesToUpload=[];this.animationFrameId=null;this.isCanvasLoopActive=!1;this.hardwareStream=null;this.internalClonedStream=null;this.currentRetries=0;this.packageCount=0;this.noiseWait=20;this.options=t,this.videoOptions=r,this.backend=i,this.backendToken=o,n&&(this.paramsConfig=n)}setProctoringId(t){this.proctoringId=t,this.proctoringId&&this.backend&&(this.upload=new Yr(this.proctoringId,this.backend)),La(t)}async initializeDetectors(){ag(),(this.paramsConfig.videoBehaviourParameters?.detectPerson||this.paramsConfig.videoBehaviourParameters?.detectCellPhone)&&(this.objectDetection=new Ua({onRealtimeAlertsCallback:t=>this.options.onRealtimeAlertsCallback(t)},this.paramsConfig),await this.objectDetection.initializeDetector()),this.paramsConfig.videoBehaviourParameters?.detectFace&&(this.faceDetection=new Li({onRealtimeAlertsCallback:t=>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")&&Fr()?(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 "+this.paramsConfig.videoBehaviourParameters);let r=this.paramsConfig.videoBehaviourParameters?.retryEnabled||!1,n=this.paramsConfig.videoBehaviourParameters?.maxRetries||3;r&&this.currentRetries<n?(console.log("buffer error Camera Recorder retry"),await this.recordingStop(),await this.startRecording({retry:!0}),this.currentRetries++,this.options.onBufferSizeErrorCallback&&this.options.onBufferSizeErrorCallback(this.cameraStream)):this.options.onBufferSizeErrorCallback&&this.options.onBufferSizeErrorCallback()}async startStream(t){let{cameraId:r,microphoneId:n,onBufferSizeErrorCallback:i}=this.options,o={audio:{deviceId:n},video:{deviceId:r,width:this.videoOptions.width,height:this.videoOptions.height,frameRate:15}};try{this.hardwareStream=await navigator.mediaDevices.getUserMedia(o)}catch(d){throw d.toString()=="NotReadableError: Could not start video source"?"N\xE3o foi poss\xEDvel conectar a camera, ela pode estar sendo utilizada por outro programa":d}this.cameraStream=this.hardwareStream;let a=this.cameraStream.getVideoTracks()[0].getSettings(),{width:c=0,height:l=0}=a;if(screen.orientation?.type.includes("portrait")&&Fr()&&this.videoOptions.width==l&&this.videoOptions.height==c&&([c,l]=[l,c]),this.videoOptions.minWidth>c||this.videoOptions.minHeight>l)throw kd;if(this.videoOptions.width!==c||this.videoOptions.height!==l)throw ue.registerAnotherStream(this.proctoringId,`Maybe have another stream active
81
81
  Video Options: ${JSON.stringify(this.videoOptions,null,2)}
82
82
  Setting: ${JSON.stringify(a,null,2)}`),Sd}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 startRecording(t){console.log("startRecording Camera Recorder"),(this.paramsConfig.videoBehaviourParameters?.detectPerson||this.paramsConfig.videoBehaviourParameters?.detectCellPhone||this.paramsConfig.videoBehaviourParameters?.detectFace)&&!t?.retry&&(console.log("startRecording Camera Recorder initializeDetectors"),await this.initializeDetectors());let{cameraId:r,microphoneId:n,onBufferSizeErrorCallback:i}=this.options,o={audio:{deviceId:n},video:{deviceId:r,width:this.videoOptions.width,height:this.videoOptions.height,frameRate:15}};try{this.hardwareStream=await navigator.mediaDevices.getUserMedia(o)}catch(_){throw console.log("startRecording Camera Recorder error",_),_.toString()=="NotReadableError: Could not start video source"?"N\xE3o foi poss\xEDvel conectar a camera, ela pode estar sendo utilizada por outro programa":_}this.cameraStream=this.hardwareStream;let a=this.cameraStream.getVideoTracks()[0].getSettings(),{width:c=0,height:l=0}=a,{startRecording:h,stopRecording:d,pauseRecording:m,resumeRecording:p,recorderOptions:g,getBufferSize:f}=Wn(this.cameraStream,this.blobs,this.videoOptions,this.options.onBufferSizeError,_=>this.bufferError(_),!1);if(this.recordingStart=h,this.recordingStop=d,this.recordingPause=m,this.recordingResume=p,this.recorderOptions=g,this.getBufferSize=f,console.log("startRecording Camera Recorder recordingStart"),this.recordingStart(),screen.orientation?.type.includes("portrait")&&Fr()&&this.videoOptions.width==l&&this.videoOptions.height==c&&([c,l]=[l,c]),this.videoOptions.minWidth>c||this.videoOptions.minHeight>l)throw kd;if(this.videoOptions.width!==c||this.videoOptions.height!==l)throw ue.registerAnotherStream(this.proctoringId,`Maybe have another stream active
83
83
  Video Options: ${JSON.stringify(this.videoOptions,null,2)}
84
- Setting: ${JSON.stringify(a,null,2)}`),Sd;this.paramsConfig.imageBehaviourParameters?.useUploadImage&&this.options.proctoringType=="IMAGE"&&this.photoShotsCycle(),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.options.proctoringType=="REALTIME"&&this.captureFrame(),this.packageCount=0,console.log("startRecording Camera Recorder finished")}async stopRecording(){this.isCanvasLoopActive=!1,this.recordingStop&&await this.recordingStop();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)}catch{console.error("Erro ao parar os streams de m\xEDdia.")}this.faceDetection&&this.faceDetection.detecting&&this.faceDetection.stopDetection(),this.objectDetection&&this.objectDetection.detecting&&this.objectDetection.stopDetection(),clearInterval(this.imageInterval),clearInterval(this.sendFrameInterval),this.options.proctoringType=="REALTIME"&&this.upload&&this.backendToken&&(await this.sendPackage(this.filesToUpload),await this.filesToUpload.splice(0,this.filesToUpload.length)),this.volumeMeter&&this.volumeMeter.stop(),this.intervalNoiseDetection&&clearInterval(this.intervalNoiseDetection)}async pauseRecording(){await this.recordingPause()}async resumeRecording(){await this.recordingResume()}photoShotsCycle(){let t;this.configImageCapture(),this.imageInterval=setInterval(async()=>{this.canvas.getContext("2d").drawImage(this.video,0,0,this.videoOptions.width,this.videoOptions.height);let r=this.canvas.toDataURL("image/jpeg");t=await this.getFile(r,`${this.proctoringId}_${this.imageCount+1}.jpg`,"image/jpeg"),t&&this.upload&&this.backendToken&&(this.upload.upload({file:t},this.backendToken,!0),this.imageCount++)},this.paramsConfig.imageBehaviourParameters.uploadInterval*1e3)}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")}captureFrame(){let t;this.configImageCapture();let r=this.paramsConfig.videoBehaviourParameters?.realtimePackageSize;this.imageCount=0,this.imageInterval=setInterval(async()=>{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;if(r==this.imageCount){this.imageCount=0;let o=[...this.filesToUpload];this.sendPackage(o),await this.filesToUpload.splice(0,this.filesToUpload.length)}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++)},this.paramsConfig.videoBehaviourParameters?.realtimeCaptureInterval*1e3)}async sendPackage(t){let r=!1,n=0,i=this.paramsConfig.videoBehaviourParameters?.realtimePackageSize,o=this.paramsConfig.videoBehaviourParameters?.realtimeCaptureInterval+1;if(this.upload&&this.backendToken&&!r&&this.filesToUpload.length>0){n=0,r=!0;let s=new s0.default;for(let d of t)s.file(d.name,d);let a=await s.generateAsync({type:"blob"}),c="realtime_package_"+i*o*this.packageCount+".zip",l=new File([a],c,{type:"application/zip"});(await this.upload.uploadPackage({file:l},this.backendToken)).uploaded==!0?this.packageCount++:console.log("erro no upload do pacote"),r=!1}else if(r&&(n++,n==3)){n=0;let s=this.videoOptions.width/2,a=this.videoOptions.height/2;s<320&&(s=320),a<180&&(a=180),this.canvas.width=s,this.canvas.height=a}}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&&ue.registerSaveOnSession(this.proctoringId,`Blobs Length: ${this.blobs.length} Buffer Size: ${this.getBufferSize()} `);let r=this.cameraStream.getVideoTracks()[0].getSettings(),n=this.cameraStream.getAudioTracks()[0].getSettings();(this.options.proctoringType=="VIDEO"||this.options.proctoringType=="REALTIME"||this.options.proctoringType=="IMAGE"&&this.paramsConfig.imageBehaviourParameters?.saveVideo)&&t.addRecording({device:`Audio
84
+ Setting: ${JSON.stringify(a,null,2)}`),Sd;this.paramsConfig.imageBehaviourParameters?.useUploadImage&&this.options.proctoringType=="IMAGE"&&this.photoShotsCycle(),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.options.proctoringType=="REALTIME"&&this.captureFrame(),this.packageCount=0,console.log("startRecording Camera Recorder finished")}async stopRecording(){console.log("Stopping Camera Recorder..."),this.isCanvasLoopActive=!1,this.recordingStop&&await this.recordingStop();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)}catch{console.error("Erro ao parar os streams de m\xEDdia.")}this.faceDetection&&this.faceDetection.detecting&&this.faceDetection.stopDetection(),this.objectDetection&&this.objectDetection.detecting&&this.objectDetection.stopDetection(),clearInterval(this.imageInterval),clearInterval(this.sendFrameInterval),this.options.proctoringType=="REALTIME"&&this.upload&&this.backendToken&&(await this.sendPackage(this.filesToUpload),await this.filesToUpload.splice(0,this.filesToUpload.length)),this.volumeMeter&&this.volumeMeter.stop(),this.intervalNoiseDetection&&clearInterval(this.intervalNoiseDetection)}async pauseRecording(){await this.recordingPause()}async resumeRecording(){await this.recordingResume()}photoShotsCycle(){let t;this.configImageCapture(),this.imageInterval=setInterval(async()=>{this.canvas.getContext("2d").drawImage(this.video,0,0,this.videoOptions.width,this.videoOptions.height);let r=this.canvas.toDataURL("image/jpeg");t=await this.getFile(r,`${this.proctoringId}_${this.imageCount+1}.jpg`,"image/jpeg"),t&&this.upload&&this.backendToken&&(this.upload.upload({file:t},this.backendToken,!0),this.imageCount++)},this.paramsConfig.imageBehaviourParameters.uploadInterval*1e3)}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")}captureFrame(){let t;this.configImageCapture();let r=this.paramsConfig.videoBehaviourParameters?.realtimePackageSize;this.imageCount=0,this.imageInterval=setInterval(async()=>{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;if(r==this.imageCount){this.imageCount=0;let o=[...this.filesToUpload];this.sendPackage(o),await this.filesToUpload.splice(0,this.filesToUpload.length)}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++)},this.paramsConfig.videoBehaviourParameters?.realtimeCaptureInterval*1e3)}async sendPackage(t){let r=!1,n=0,i=this.paramsConfig.videoBehaviourParameters?.realtimePackageSize,o=this.paramsConfig.videoBehaviourParameters?.realtimeCaptureInterval+1;if(this.upload&&this.backendToken&&!r&&this.filesToUpload.length>0){n=0,r=!0;let s=new s0.default;for(let d of t)s.file(d.name,d);let a=await s.generateAsync({type:"blob"}),c="realtime_package_"+i*o*this.packageCount+".zip",l=new File([a],c,{type:"application/zip"});(await this.upload.uploadPackage({file:l},this.backendToken)).uploaded==!0?this.packageCount++:console.log("erro no upload do pacote"),r=!1}else if(r&&(n++,n==3)){n=0;let s=this.videoOptions.width/2,a=this.videoOptions.height/2;s<320&&(s=320),a<180&&(a=180),this.canvas.width=s,this.canvas.height=a}}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&&ue.registerSaveOnSession(this.proctoringId,`Blobs Length: ${this.blobs.length} Buffer Size: ${this.getBufferSize()} `);let r=this.cameraStream.getVideoTracks()[0].getSettings(),n=this.cameraStream.getAudioTracks()[0].getSettings();(this.options.proctoringType=="VIDEO"||this.options.proctoringType=="REALTIME"||this.options.proctoringType=="IMAGE"&&this.paramsConfig.imageBehaviourParameters?.saveVideo)&&t.addRecording({device:`Audio
85
85
  Sample Rate: ${n.sampleRate}
86
86
  Sample Size: ${n.sampleSize}
87
87
 
@@ -502,7 +502,7 @@ registerProcessor("audio-processor", AudioProcessor);
502
502
  <circle cx="10" cy="10" r="9" stroke="#16A34A" stroke-width="2" fill="none"/>
503
503
  <path d="M6 10L9 13L14 7" stroke="#16A34A" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
504
504
  </svg>
505
- `,this.applyStyles(_,{display:"inline-flex",alignItems:"center",justifyContent:"center",width:"20px",height:"20px",flexShrink:"0"});let S=document.createElement("span");S.innerText=f,b.appendChild(_),b.appendChild(S),c.appendChild(b)}),s.appendChild(c);let h=document.createElement("button");h.innerText="Capturar foto",h.id="position-capture-button",this.applyStyles(h,{marginTop:"10px",padding:"12px 24px",fontSize:"14px",fontWeight:"bold",color:"white",backgroundColor:"#16A34A",border:"none",borderRadius:"6px",cursor:"pointer",transition:"background-color 0.2s",alignSelf:"flex-start"}),h.onclick=()=>{if(this.connection){let f=document.getElementById("photo-message");f&&(f.innerText="N\xE3o saia da posi\xE7\xE3o atual, estamos validando o ambiente..."),n.style.display="none",this.takePicture(!0,()=>{}),h.disabled=!0,this.applyStyles(h,{backgroundColor:"#9CA3AF",cursor:"not-allowed"})}},s.appendChild(h),i.appendChild(s),t.appendChild(i);let d=document.createElement("div");this.applyStyles(d,{marginTop:"10px",fontSize:"13px",color:"#666"});let m=document.createElement("span");m.innerText="Dica: ",m.style.fontWeight="bold";let p=document.createElement("span");p.innerText="mantenha o celular est\xE1vel durante todo o processo.",d.appendChild(m),d.appendChild(p),t.appendChild(d);let g=document.getElementById("external-camera-continue");g.disabled=!0,this.applyStyles(g,{color:"#ccc",cursor:"not-allowed"})}renderImageStep(t){t.innerHTML="";let r=document.createElement("img");r.src="data:image/jpeg;base64,"+this.capturePhotoUrl,this.applyStyles(r,{maxWidth:"100%",maxHeight:"300px",borderRadius:"8px"}),t.appendChild(r);let n=document.createElement("photo-message");n.id="photo-message",n.innerText="Verifica\xE7\xE3o finalizada com sucesso.",this.applyStyles(n,{textAlign:"center",color:"#555",marginTop:"20px"}),t.appendChild(n);let i=document.getElementById("external-camera-continue");i.disabled=!1,i.innerText="Concluir",this.applyStyles(i,{width:"100%",height:"70px",backgroundColor:"#FFF",border:"none",color:"rgba(0, 0, 0, .7)",fontWeight:"bold",borderRadius:"0 0 10px 0",cursor:"pointer",borderLeft:"2px solid rgba(0, 0, 0, .1)"}),i.onclick=()=>{this.closeCheckExternalCamera(),this.resolvePromise({result:!0})}}nextState(){this.renderCurrentStep()}async initializeWebSocketConnection(){let t=this.backend.getSocketUrl();this.connection=new as().withUrl(t,{accessTokenFactory:()=>this.context.token,transport:Ve.WebSockets,withCredentials:!1,skipNegotiation:!0}).withAutomaticReconnect().configureLogging(L.Information).build(),this.connection.on("ReceiveMessage",(r,n)=>{if(console.log("sessionId: ",r),console.log("Message: ",n),r!==this.externalSessionId){console.warn("Sess\xE3o diferente!");return}try{let o=_y[n];console.log("Mensagem -> ",o),this.handleWebSocketMessage(o)}catch(i){console.error("Erro ao processar mensagem do WebSocket:",i)}}),this.connection.on("ReceiveAction",(r,n)=>{if(console.log("sessionId: ",r),console.log("Message: ",n),r!==this.externalSessionId){console.warn("Sess\xE3o diferente!");return}try{this.handleWebSocketAction(n)}catch(i){console.error("Erro ao processar mensagem do WebSocket:",i)}});try{await this.connection.start(),console.log("Conectado ao Hub SignalR com sucesso!")}catch(r){throw console.error("Falha ao conectar ou entrar no grupo do SignalR: ",r),new Error("N\xE3o foi poss\xEDvel conectar ao servi\xE7o em tempo real.")}}handleWebSocketAction(t){let r=document.getElementById("position-capture-button"),n=document.getElementById("photo-message"),i=document.getElementById("photo-error-banner");switch(t.command){case"Capture_Error":r&&(this.applyStyles(r,{marginTop:"30px",padding:"12px 20px",fontSize:"16px",fontWeight:"bold",color:"white",backgroundColor:"#16A34A",border:"none",borderRadius:"8px",cursor:"pointer",transition:"background-color 0.2s"}),r.disabled=!1),n&&(n.innerText=""+t.message),i&&(i.style.display="flex"),this.waitingPositionValidation==!0&&this.onTakePictureCallback({photo:this.capturePhotoUrl,errorMessage:t.message,success:!1});break;case"CapturePhoto":this.capturePhotoUrl=""+t.message;let o=document.getElementById("photo-icon-container");if(o&&this.capturePhotoUrl&&this.capturePhotoUrl.trim()!==""){let s=document.getElementById("img-photo");s||(o.innerHTML="",s=document.createElement("img"),s.id="img-photo",this.applyStyles(s,{width:"100%",height:"100%",objectFit:"contain",objectPosition:"center",borderRadius:"8px",display:"block"}),o.appendChild(s));let a=this.capturePhotoUrl.startsWith("data:")?this.capturePhotoUrl:"data:image/jpeg;base64,"+this.capturePhotoUrl;s.src=a,s.onload=()=>{console.log("Image loaded successfully in icon container")},s.onerror=c=>{console.error("Error loading image:",c)}}this.waitingPositionValidation==!1&&this.onTakePictureCallback({photo:this.capturePhotoUrl});break;case"Check_Transmission":t.message=="Transmission_OK"&&(this.transmissionOk=!0);break;case"Cancel":this.closeCheckExternalCamera();break;case"EnvironmentAlert":this.onRealtimeAlertsCallback({status:"ALERT",description:t.message,type:"environment_alert"});break}}handleWebSocketMessage(t){switch(this.currentStep=t,t){case 1:this.currentStep===1&&(this.nextState(),this.onQrCodeReadedCallback(!0));break;case 2:this.nextState(),this.waitingPositionValidation==!0&&this.onTakePictureCallback({photo:this.capturePhotoUrl,success:!0});break;case 3:this.closeCheckExternalCamera();break;case 9:console.error("Erro recebido do processo de c\xE2mera externa."),this.closeCheckExternalCamera(),this.resolvePromise({result:!1});break}}async disconnectWebSocket(){if(this.connection)try{await this.connection.stop(),console.log("Desconectado do SignalR.")}catch(t){console.error("Erro ao desconectar do SignalR:",t)}finally{this.connection=null}}closeCheckExternalCamera(){e.isModalOpen=!1,this.disconnectWebSocket(),document.querySelector("#externalCameraCheck")?.remove()}applyStyles(t,r){for(let n in r)t.style[n]=r[n]}};var cl=class{constructor(t){this.context=t;this.deviceData=null;this.sessionStartTime=0;this.paramsConfig={audioBehaviourParameters:{recordingBitrate:128,noiseLimit:40},imageBehaviourParameters:{useUploadImage:!0,uploadInterval:20,saveVideo:!0},videoBehaviourParameters:{detectFace:!1,detectPerson:!1,detectCellPhone:!1,detectNoise:!1,detectSpeech:!1,realtimePackageSize:10,realtimeCaptureInterval:2}};this.proctoringId="";this.insights=void 0;this.state="Stop";this.serviceType="Upload";this.onStopSharingScreenCallback=()=>{};this.onLostFocusCallback=()=>{};this.onLostFocusAlertRecorderCallback=t=>{};this.onFocusCallback=()=>{};this.onFocusAlertRecorderCallback=t=>{};this.onChangeDevicesCallback=t=>{};this.onRealtimeAlertsCallback=t=>{};this.onBufferSizeErrorCallback=t=>{};this.backend=new nr({type:t.type||"prod",token:t.token}),this.repository=new rs("EasyProctorDb","exams2"),this.repositoryDevices=new rs("EasyProctorDbDevices","devices"),this.context.credentials?.cpf&&(this.auth=new Ic(this.context.credentials.cpf,this.backend)),this.appChecker=new al(this.context,r=>this.onRealtimeAlertsCallback(r))}setOnStopSharingScreenCallback(t){this.onStopSharingScreenCallback=async()=>{ue.registerStopSharingScreen(this.proctoringId,"Stop sharing screen"),this.allRecorders?.alertRecorder?.addAlert({alert:34,type:3}),this.allRecorders?.screenRecorder?.stopRecording(),t()}}setOnLostFocusAlertRecorderCallback(){this.onLostFocusAlertRecorderCallback=async t=>{this.onLostFocusCallback&&this.onLostFocusCallback(),this.sessionOptions.proctoringType==="REALTIME"&&await this.onRealtimeAlertsCallback({type:"lost_focus",category:"lost_focus",description:"Perda de foco no exame",begin:t.begin,end:t.end,alert:25,status:"ALERT"})}}setOnFocusAlertRecorderCallback(){this.onFocusAlertRecorderCallback=async t=>{this.onFocusCallback&&this.onFocusCallback(),this.sessionOptions.proctoringType==="REALTIME"&&await this.onRealtimeAlertsCallback({type:"focus",category:"focus",description:"Retorno de foco no exame",begin:t.begin,end:t.end,alert:25,status:"OK"})}}async setOnLostFocusCallback(t){this.onLostFocusCallback=async()=>await t(),this.setOnLostFocusAlertRecorderCallback()}async setOnFocusCallback(t){this.onFocusCallback=async()=>await t(),this.setOnFocusAlertRecorderCallback()}async onChangeDevices(t={}){new Ha(this.repositoryDevices,this.proctoringId,this.sessionOptions,this.allRecorders).startRecording(t),this.onChangeDevicesCallback=n=>t.status&&t.status(n)}convertRealtimeCategoryToAlertCategory(t){switch(t){case"no_face_detected":return 1;case"multiple_faces_detected":return 2;case"multiple_persons_detected":return 28;case"no_person_detected":return 29;case"lost_focus":return 25;case"focus":return 25;default:return null}}convertRealtimeTypeToWarningType(t){switch(t){case"face_detection_on_stream":return 0;case"person_detection_on_stream":return 1;case"lost_focus":return 2;case"focus":return 2;default:return null}}async stopRealtimeAlert(t){let n=async i=>{if(!(i>3))try{var o=await this.backend.stopRealtimeAlert({proctoringId:this.proctoringId,begin:t.begin,end:t.end,warningCategoryEnum:this.convertRealtimeTypeToWarningType(t.type),alertImageBase64:await this.allRecorders.cameraRecorder.getCurrentImageBase64(),retry:i<2});return console.log("response stopRealtimeAlert",o),o}catch(s){return console.log("error stopRealtimeAlert",s),n(i+1)}};await n(1)}async onRealtimeAlerts(t={}){this.setOnLostFocusAlertRecorderCallback(),this.setOnFocusAlertRecorderCallback(),this.onRealtimeAlertsCallback=async r=>{t.data&&t.data(r),this.sessionOptions.proctoringType==="REALTIME"&&(r.type==="face_detection_on_stream"||r.type==="person_detection_on_stream"||r.type==="lost_focus"||r.type==="focus")&&(r.status==="ALERT"?await this.backend.startRealtimeAlert({proctoringId:this.proctoringId,begin:r.begin,end:r.end,alert:this.convertRealtimeCategoryToAlertCategory(r.category)}):r.status==="OK"&&await this.stopRealtimeAlert(r))}}setOnBufferSizeErrorCallback(t){this.onBufferSizeErrorCallback=r=>t(r)}setDeviceCheckData(t){this.deviceData=t}createRecorders(t=ir){this.onChangeDevices();let r=new Zr({cameraId:this.sessionOptions.cameraId,microphoneId:this.sessionOptions.microphoneId,onBufferSizeError:this.sessionOptions.onBufferSizeError,onBufferSizeErrorCallback:a=>this.onBufferSizeErrorCallback(a),proctoringType:this.sessionOptions.proctoringType,onChangeDevicesCallback:a=>this.onChangeDevicesCallback(a),onRealtimeAlertsCallback:a=>this.onRealtimeAlertsCallback(a)},{width:this.videoOptions.width,height:this.videoOptions.height,minWidth:this.videoOptions.minWidth,minHeight:this.videoOptions.minHeight,timeSlice:this.videoOptions.timeSlice,videoBitsPerSecond:this.videoOptions.videoBitsPerSecond,mimeType:this.videoOptions.mimeType},this.paramsConfig,this.backend,this.context.token),n=this.sessionOptions.captureScreen?new Tc({allowOnlyFirstMonitor:this.sessionOptions.allowOnlyFirstMonitor??!0,allowMultipleMonitors:this.sessionOptions.allowMultipleMonitors??!0,screenRecorderOptions:this.sessionOptions.screenRecorderOptions,onStopSharingScreenCallback:()=>this.onStopSharingScreenCallback(),onBufferSizeError:this.sessionOptions.onBufferSizeError,onBufferSizeErrorCallback:()=>this.onBufferSizeErrorCallback()}):void 0,i=new $a({onFocusCallback:a=>this.onFocusAlertRecorderCallback(a),onLostFocusCallback:a=>this.onLostFocusAlertRecorderCallback(a),onRealtimeAlertCallback:a=>this.onRealtimeAlertsCallback(a)},t),o=new Ac(t,this.proctoringSession,this.paramsConfig,r,a=>this.onRealtimeAlertsCallback(a),this.backend,this.context.token),s=[r,n,i].filter(Boolean);return s.push(o),this.recorder=new Wa(this.proctoringSession,s),{cameraRecorder:r,screenRecorder:n,alertRecorder:i,noiseRecorder:o}}async login(){if(!this.context.credentials?.cpf)throw e0;this.context.token=await this.auth.login()}async start(t=ir,r={}){try{if(this.context.token===void 0)throw Qg;t.useChallenge&&(this.extensionEasycatcher=new Va),this.extension=new ja,this.extension.addEventListener();let n=this.backend.selectBaseUrl(this.context.type),i=await ur();await this.repositoryDevices.save({...i,id:"devices"}),this.sessionOptions={...ir,...t},this.videoOptions=Oa(r),await this.initConfig(t.useGeolocation),await this.verifyBrowser(),this.sessionOptions.captureScreen&&await this.verifyMultipleMonitors(this.sessionOptions);try{t?.useSpyScan&&await this.spyCam.isAlive()}catch{throw t0}if(this.state!="Stop")throw Yg;this.state="Starting",await this.repository.hasSessions()&&await this.repository.clear(),this.proctoringSession=new Hn,this.allRecorders=this.createRecorders(this.sessionOptions);let o=await this.backend.confirmStart({clientId:this.context.clientId,examId:this.context.examId,token:this.context.token},this.sessionOptions,this.geolocation?this.geolocation.coords.latitude:void 0,this.geolocation?this.geolocation.coords.longitude:void 0);this.proctoringId=o.id,ue.registerDevicesChecked(this.proctoringId,!!this.deviceData,`Devices checked: ${JSON.stringify(this.deviceData)} | Devices List: ${JSON.stringify(i)}`);try{t?.useExternalCamera&&await this.appChecker.startTransmission(this.proctoringId)}catch{throw r0}this.sessionStartTime=Date.now(),this.allRecorders.cameraRecorder.setProctoringId(this.proctoringId),this.allRecorders.noiseRecorder.setProctoringId(this.proctoringId),this.proctoringSession.setProctoringId(this.proctoringId),await this.recorder.startAll(),t?.useSpyScan&&(this.spyCam.setProctoringId(this.proctoringId),this.spyCam.startCheckSpyCam(this.paramsConfig.spyScanInterval??5,{deviceType:3})),await this.repository.save(this.proctoringSession);let s={};for(let l in navigator)s[l]=navigator[l];ue.registerStart(this.proctoringId,!0,`Version: ${ns()}
505
+ `,this.applyStyles(_,{display:"inline-flex",alignItems:"center",justifyContent:"center",width:"20px",height:"20px",flexShrink:"0"});let S=document.createElement("span");S.innerText=f,b.appendChild(_),b.appendChild(S),c.appendChild(b)}),s.appendChild(c);let h=document.createElement("button");h.innerText="Capturar foto",h.id="position-capture-button",this.applyStyles(h,{marginTop:"10px",padding:"12px 24px",fontSize:"14px",fontWeight:"bold",color:"white",backgroundColor:"#16A34A",border:"none",borderRadius:"6px",cursor:"pointer",transition:"background-color 0.2s",alignSelf:"flex-start"}),h.onclick=()=>{if(this.connection){let f=document.getElementById("photo-message");f&&(f.innerText="N\xE3o saia da posi\xE7\xE3o atual, estamos validando o ambiente..."),n.style.display="none",this.takePicture(!0,()=>{}),h.disabled=!0,this.applyStyles(h,{backgroundColor:"#9CA3AF",cursor:"not-allowed"})}},s.appendChild(h),i.appendChild(s),t.appendChild(i);let d=document.createElement("div");this.applyStyles(d,{marginTop:"10px",fontSize:"13px",color:"#666"});let m=document.createElement("span");m.innerText="Dica: ",m.style.fontWeight="bold";let p=document.createElement("span");p.innerText="mantenha o celular est\xE1vel durante todo o processo.",d.appendChild(m),d.appendChild(p),t.appendChild(d);let g=document.getElementById("external-camera-continue");g.disabled=!0,this.applyStyles(g,{color:"#ccc",cursor:"not-allowed"})}renderImageStep(t){t.innerHTML="";let r=document.createElement("img");r.src="data:image/jpeg;base64,"+this.capturePhotoUrl,this.applyStyles(r,{maxWidth:"100%",maxHeight:"300px",borderRadius:"8px"}),t.appendChild(r);let n=document.createElement("photo-message");n.id="photo-message",n.innerText="Verifica\xE7\xE3o finalizada com sucesso.",this.applyStyles(n,{textAlign:"center",color:"#555",marginTop:"20px"}),t.appendChild(n);let i=document.getElementById("external-camera-continue");i.disabled=!1,i.innerText="Concluir",this.applyStyles(i,{width:"100%",height:"70px",backgroundColor:"#FFF",border:"none",color:"rgba(0, 0, 0, .7)",fontWeight:"bold",borderRadius:"0 0 10px 0",cursor:"pointer",borderLeft:"2px solid rgba(0, 0, 0, .1)"}),i.onclick=()=>{this.closeCheckExternalCamera(),this.resolvePromise({result:!0})}}nextState(){this.renderCurrentStep()}async initializeWebSocketConnection(){let t=this.backend.getSocketUrl();this.connection=new as().withUrl(t,{accessTokenFactory:()=>this.context.token,transport:Ve.WebSockets,withCredentials:!1,skipNegotiation:!0}).withAutomaticReconnect().configureLogging(L.Information).build(),this.connection.on("ReceiveMessage",(r,n)=>{if(console.log("sessionId: ",r),console.log("Message: ",n),r!==this.externalSessionId){console.warn("Sess\xE3o diferente!");return}try{let o=_y[n];console.log("Mensagem -> ",o),this.handleWebSocketMessage(o)}catch(i){console.error("Erro ao processar mensagem do WebSocket:",i)}}),this.connection.on("ReceiveAction",(r,n)=>{if(console.log("sessionId: ",r),console.log("Message: ",n),r!==this.externalSessionId){console.warn("Sess\xE3o diferente!");return}try{this.handleWebSocketAction(n)}catch(i){console.error("Erro ao processar mensagem do WebSocket:",i)}});try{await this.connection.start(),console.log("Conectado ao Hub SignalR com sucesso!")}catch(r){throw console.error("Falha ao conectar ou entrar no grupo do SignalR: ",r),new Error("N\xE3o foi poss\xEDvel conectar ao servi\xE7o em tempo real.")}}handleWebSocketAction(t){let r=document.getElementById("position-capture-button"),n=document.getElementById("photo-message"),i=document.getElementById("photo-error-banner");switch(t.command){case"Capture_Error":r&&(this.applyStyles(r,{marginTop:"30px",padding:"12px 20px",fontSize:"16px",fontWeight:"bold",color:"white",backgroundColor:"#16A34A",border:"none",borderRadius:"8px",cursor:"pointer",transition:"background-color 0.2s"}),r.disabled=!1),n&&(n.innerText=""+t.message),i&&(i.style.display="flex"),this.waitingPositionValidation==!0&&this.onTakePictureCallback({photo:this.capturePhotoUrl,errorMessage:t.message,success:!1});break;case"CapturePhoto":this.capturePhotoUrl=""+t.message;let o=document.getElementById("photo-icon-container");if(o&&this.capturePhotoUrl&&this.capturePhotoUrl.trim()!==""){let s=document.getElementById("img-photo");s||(o.innerHTML="",s=document.createElement("img"),s.id="img-photo",this.applyStyles(s,{width:"100%",height:"100%",objectFit:"contain",objectPosition:"center",borderRadius:"8px",display:"block"}),o.appendChild(s));let a=this.capturePhotoUrl.startsWith("data:")?this.capturePhotoUrl:"data:image/jpeg;base64,"+this.capturePhotoUrl;s.src=a,s.onload=()=>{console.log("Image loaded successfully in icon container")},s.onerror=c=>{console.error("Error loading image:",c)}}this.waitingPositionValidation==!1&&this.onTakePictureCallback({photo:this.capturePhotoUrl});break;case"Check_Transmission":t.message=="Transmission_OK"&&(this.transmissionOk=!0);break;case"Cancel":this.closeCheckExternalCamera();break;case"EnvironmentAlert":this.onRealtimeAlertsCallback({status:"ALERT",description:t.message,type:"environment_alert"});break}}handleWebSocketMessage(t){switch(this.currentStep=t,t){case 1:this.currentStep===1&&(this.nextState(),this.onQrCodeReadedCallback(!0));break;case 2:this.nextState(),this.waitingPositionValidation==!0&&this.onTakePictureCallback({photo:this.capturePhotoUrl,success:!0});break;case 3:this.closeCheckExternalCamera();break;case 9:console.error("Erro recebido do processo de c\xE2mera externa."),this.closeCheckExternalCamera(),this.resolvePromise({result:!1});break}}async disconnectWebSocket(){if(this.connection)try{await this.connection.stop(),console.log("Desconectado do SignalR.")}catch(t){console.error("Erro ao desconectar do SignalR:",t)}finally{this.connection=null}}closeCheckExternalCamera(){e.isModalOpen=!1,this.disconnectWebSocket(),document.querySelector("#externalCameraCheck")?.remove()}applyStyles(t,r){for(let n in r)t.style[n]=r[n]}};var cl=class{constructor(t){this.context=t;this.deviceData=null;this.sessionStartTime=0;this.paramsConfig={audioBehaviourParameters:{recordingBitrate:128,noiseLimit:40},imageBehaviourParameters:{useUploadImage:!0,uploadInterval:20,saveVideo:!0},videoBehaviourParameters:{detectFace:!1,detectPerson:!1,detectCellPhone:!1,detectNoise:!1,detectSpeech:!1,realtimePackageSize:10,realtimeCaptureInterval:2}};this.proctoringId="";this.insights=void 0;this.state="Stop";this.serviceType="Upload";this.onStopSharingScreenCallback=()=>{};this.onLostFocusCallback=()=>{};this.onLostFocusAlertRecorderCallback=t=>{};this.onFocusCallback=()=>{};this.onFocusAlertRecorderCallback=t=>{};this.onChangeDevicesCallback=t=>{};this.onRealtimeAlertsCallback=t=>{};this.onBufferSizeErrorCallback=t=>{};this.backend=new nr({type:t.type||"prod",token:t.token}),this.repository=new rs("EasyProctorDb","exams2"),this.repositoryDevices=new rs("EasyProctorDbDevices","devices"),this.context.credentials?.cpf&&(this.auth=new Ic(this.context.credentials.cpf,this.backend)),this.appChecker=new al(this.context,r=>this.onRealtimeAlertsCallback(r))}setOnStopSharingScreenCallback(t){this.onStopSharingScreenCallback=async()=>{ue.registerStopSharingScreen(this.proctoringId,"Stop sharing screen"),this.allRecorders?.alertRecorder?.addAlert({alert:34,type:3}),this.allRecorders?.screenRecorder?.stopRecording(),t()}}setOnLostFocusAlertRecorderCallback(){this.onLostFocusAlertRecorderCallback=async t=>{this.onLostFocusCallback&&this.onLostFocusCallback(),this.sessionOptions.proctoringType==="REALTIME"&&await this.onRealtimeAlertsCallback({type:"lost_focus",category:"lost_focus",description:"Perda de foco no exame",begin:t.begin,end:t.end,alert:25,status:"ALERT"})}}setOnFocusAlertRecorderCallback(){this.onFocusAlertRecorderCallback=async t=>{this.onFocusCallback&&this.onFocusCallback(),this.sessionOptions.proctoringType==="REALTIME"&&await this.onRealtimeAlertsCallback({type:"focus",category:"focus",description:"Retorno de foco no exame",begin:t.begin,end:t.end,alert:25,status:"OK"})}}async setOnLostFocusCallback(t){this.onLostFocusCallback=async()=>await t(),this.setOnLostFocusAlertRecorderCallback()}async setOnFocusCallback(t){this.onFocusCallback=async()=>await t(),this.setOnFocusAlertRecorderCallback()}async onChangeDevices(t={}){new Ha(this.repositoryDevices,this.proctoringId,this.sessionOptions,this.allRecorders).startRecording(t),this.onChangeDevicesCallback=n=>t.status&&t.status(n)}convertRealtimeCategoryToAlertCategory(t){switch(t){case"no_face_detected":return 1;case"multiple_faces_detected":return 2;case"multiple_persons_detected":return 28;case"no_person_detected":return 29;case"lost_focus":return 25;case"focus":return 25;default:return null}}convertRealtimeTypeToWarningType(t){switch(t){case"face_detection_on_stream":return 0;case"person_detection_on_stream":return 1;case"lost_focus":return 2;case"focus":return 2;default:return null}}async stopRealtimeAlert(t){let n=async i=>{if(!(i>3))try{var o=await this.backend.stopRealtimeAlert({proctoringId:this.proctoringId,begin:t.begin,end:t.end,warningCategoryEnum:this.convertRealtimeTypeToWarningType(t.type),alertImageBase64:await this.allRecorders.cameraRecorder.getCurrentImageBase64(),retry:i<2});return console.log("response stopRealtimeAlert",o),o}catch(s){return console.log("error stopRealtimeAlert",s),n(i+1)}};await n(1)}async onRealtimeAlerts(t={}){this.setOnLostFocusAlertRecorderCallback(),this.setOnFocusAlertRecorderCallback(),this.onRealtimeAlertsCallback=async r=>{t.data&&t.data(r),this.sessionOptions.proctoringType==="REALTIME"&&(r.type==="face_detection_on_stream"||r.type==="person_detection_on_stream"||r.type==="lost_focus"||r.type==="focus")&&(r.status==="ALERT"?await this.backend.startRealtimeAlert({proctoringId:this.proctoringId,begin:r.begin,end:r.end,alert:this.convertRealtimeCategoryToAlertCategory(r.category)}):r.status==="OK"&&await this.stopRealtimeAlert(r))}}setOnBufferSizeErrorCallback(t){this.onBufferSizeErrorCallback=r=>t(r)}setDeviceCheckData(t){this.deviceData=t}async createRecorders(t=ir){this.onChangeDevices(),console.log("Creating Recorders..."),await this.recorder?.stopAll();let r=new Zr({cameraId:this.sessionOptions.cameraId,microphoneId:this.sessionOptions.microphoneId,onBufferSizeError:this.sessionOptions.onBufferSizeError,onBufferSizeErrorCallback:a=>this.onBufferSizeErrorCallback(a),proctoringType:this.sessionOptions.proctoringType,onChangeDevicesCallback:a=>this.onChangeDevicesCallback(a),onRealtimeAlertsCallback:a=>this.onRealtimeAlertsCallback(a)},{width:this.videoOptions.width,height:this.videoOptions.height,minWidth:this.videoOptions.minWidth,minHeight:this.videoOptions.minHeight,timeSlice:this.videoOptions.timeSlice,videoBitsPerSecond:this.videoOptions.videoBitsPerSecond,mimeType:this.videoOptions.mimeType},this.paramsConfig,this.backend,this.context.token),n=this.sessionOptions.captureScreen?new Tc({allowOnlyFirstMonitor:this.sessionOptions.allowOnlyFirstMonitor??!0,allowMultipleMonitors:this.sessionOptions.allowMultipleMonitors??!0,screenRecorderOptions:this.sessionOptions.screenRecorderOptions,onStopSharingScreenCallback:()=>this.onStopSharingScreenCallback(),onBufferSizeError:this.sessionOptions.onBufferSizeError,onBufferSizeErrorCallback:()=>this.onBufferSizeErrorCallback()}):void 0,i=new $a({onFocusCallback:a=>this.onFocusAlertRecorderCallback(a),onLostFocusCallback:a=>this.onLostFocusAlertRecorderCallback(a),onRealtimeAlertCallback:a=>this.onRealtimeAlertsCallback(a)},t),o=new Ac(t,this.proctoringSession,this.paramsConfig,r,a=>this.onRealtimeAlertsCallback(a),this.backend,this.context.token),s=[r,n,i].filter(Boolean);return s.push(o),this.recorder=new Wa(this.proctoringSession,s),{cameraRecorder:r,screenRecorder:n,alertRecorder:i,noiseRecorder:o}}async login(){if(!this.context.credentials?.cpf)throw e0;this.context.token=await this.auth.login()}async start(t=ir,r={}){try{if(this.context.token===void 0)throw Qg;t.useChallenge&&(this.extensionEasycatcher=new Va),this.extension=new ja,this.extension.addEventListener();let n=this.backend.selectBaseUrl(this.context.type),i=await ur();await this.repositoryDevices.save({...i,id:"devices"}),this.sessionOptions={...ir,...t},this.videoOptions=Oa(r),await this.initConfig(t.useGeolocation),await this.verifyBrowser(),this.sessionOptions.captureScreen&&await this.verifyMultipleMonitors(this.sessionOptions);try{t?.useSpyScan&&await this.spyCam.isAlive()}catch{throw t0}if(this.state!="Stop")throw Yg;this.state="Starting",await this.repository.hasSessions()&&await this.repository.clear(),this.proctoringSession=new Hn,this.allRecorders=await this.createRecorders(this.sessionOptions);let o=await this.backend.confirmStart({clientId:this.context.clientId,examId:this.context.examId,token:this.context.token},this.sessionOptions,this.geolocation?this.geolocation.coords.latitude:void 0,this.geolocation?this.geolocation.coords.longitude:void 0);this.proctoringId=o.id,ue.registerDevicesChecked(this.proctoringId,!!this.deviceData,`Devices checked: ${JSON.stringify(this.deviceData)} | Devices List: ${JSON.stringify(i)}`);try{t?.useExternalCamera&&await this.appChecker.startTransmission(this.proctoringId)}catch{throw r0}this.sessionStartTime=Date.now(),this.allRecorders.cameraRecorder.setProctoringId(this.proctoringId),this.allRecorders.noiseRecorder.setProctoringId(this.proctoringId),this.proctoringSession.setProctoringId(this.proctoringId),await this.recorder.startAll(),t?.useSpyScan&&(this.spyCam.setProctoringId(this.proctoringId),this.spyCam.startCheckSpyCam(this.paramsConfig.spyScanInterval??5,{deviceType:3})),await this.repository.save(this.proctoringSession);let s={};for(let l in navigator)s[l]=navigator[l];ue.registerStart(this.proctoringId,!0,`Version: ${ns()}
506
506
  Navigator: ${JSON.stringify(s)}`),o.cameraStream=this.allRecorders.cameraRecorder.cameraStream,this.allRecorders.screenRecorder&&(o.screenStream=this.allRecorders.screenRecorder.screenStream),this.state="Recording";let a=0,c=!1;return this.verifyFirstFaceInterval=setInterval(async()=>{if(this.sessionOptions.proctoringType==="REALTIME"){if(c)return;c=!0,a++;try{var l=await this.backend.verifyFace(this.proctoringId,await this.allRecorders.cameraRecorder.getCurrentImageBase64(),!(a>5));c=!1,clearInterval(this.verifyFirstFaceInterval)}catch{c=!1;return}}},1500),o}catch(n){throw console.log(n),await this.cancel(),this.proctoringId&&ue.registerStart(this.proctoringId,!1,`Token: ${this.context.token}
507
507
  Version: ${ns()}
508
508
  Navigator: ${navigator}