UNPKG

nhn-cd-sdk

Version:

NHN Cheating Detection SDK

402 lines (284 loc) 13.4 kB
# NHN Proctor SDK # Installing Using npm: ```shell $ npm install nhn-cd-sdk ``` Using jsDelivr CDN: ```html <script src="https://cdn.jsdelivr.net/npm/nhn-cd-sdk@{{VERSION}}/dist/nhn-cd-sdk.js"></script> ``` Using unpkg CDN: ```html <script src="https://unpkg.com/nhn-cd-sdk@{{VERSION}}/dist/nhn-cd-sdk.js"></script> ``` # Usage `import` usage: ```js import { Launcher, Collector, Communicator } from 'nhn-cd-sdk'; const config = { /* ... */ }; const collector = new Collector(config); ``` `CDN` usage: ```js const config = { /* ... */ }; const collector = new window.nhnCDSDK.Collector(config); ``` # Run example Using npm script: ```shell $ npm i $ npm run example ``` Using example file: Copy the code from the `examples` folder to your local project at [jsdelivr](https://cdn.jsdelivr.net/npm/nhn-cd-sdk@latest/examples/) or [unpkg](https://unpkg.com/browse/nhn-cd-sdk@latest/examples/). Then change the code below in the html file as follows. ```html <!-- before --> <script src="/dist/nhn-cd-sdk.js"></script> <!-- after --> <!-- using jsdelivr --> <script src="https://cdn.jsdelivr.net/npm/nhn-cd-sdk@{{VERSION}}/dist/nhn-cd-sdk.js"></script> <!-- using unpkg --> <script src="https://unpkg.com/nhn-cd-sdk@{{VERSION}}/dist/nhn-cd-sdk.js"></script> ``` # Launcher URI Scheme를 사용한 Proctor 앱 실행 ## Creating an Launcher instance ### new Launcher([serviceUrl[,uriParameters]]) - serviceUrl - Custom URI Scheme을 통해 이동하는 고객사의 서비스 URL.(URL encoding 후 전달) - uriParameters - URI Scheme을 통해 기능 수행 시 추가로 전달할 정보를 정의 #### Example ```js const launcher = new Launcher('https://...', { option1: 'value' }); ``` ## instance methods ### launcher#setServiceUrl(serviceUrl: String) - 서비스 URL 설정 또는 기존의 서비스 URL 값을 변경 ### launcher#setUriParams(uriParameters: Object) - 옵션 설정 또는 기존의 옵션 값을 변경 ### launcher#launch() - Proctor 실행 <br/> # Communicator - 시험 시작, 시험 종료 제어 ## Get an Communicator instance ### Example ```js const communicator = new window.nhnCDSDK.Communicator(); ``` ## instance methods ### communicator#initialize(config: Object) - NHN Proctor 사용자 정보 초기화 ### Example ```js communicator.initialize({ appKey: '{{APP_KEY}}', examNo: '{{EXAM_NO}}', userId: '{{USER_ID}}' }); ``` ### communicator#communicate(event[,properties]) - NHN Proctor 이벤트 전달 ### Example ```js event = '{{EVENT_NAME}}'; // or 'beginTest' or 'endTest' properties = { key: '{{VALUE}}' }; ``` ### communicator#beginTest() - 시험 시작 ### communicator#endTest() - 시험 종료 # Collector - Collector API 제공 ## Get an Collector instance ### Example ```js const collector = new window.nhnCDSDK.Collector(config); const config = { userInfo: { appKey: '{{APP_KEY}}', // 통합 AppKey 또는 서비스 AppKey examNo: '{{EXAM_NO}}', // 시험 번호 userId: '{{USER_ID}}' // 사용자 아이디 }, deviceType: 'pc', webAuth: { userId: '{{WEB_AUTH_USER_ID}}', // 사용자 ID(수험생 번호) token: '{{WEB_AUTH_TOKEN}}', // 고객사에서 발급한 WebAuth 인증 토큰 via: '{{WEB_AUTH_VIA}}' // 기타 정보 }, retryCount: '{{RETRY_COUNT}}', authRenewCount: '{{AUTH_RENEW_COUNT', authRenewBeforeCallback: (webAuth) => { // use your token api. const tokenAPI = () => { return new Promise((resolve) => { setTimeout(() => { resolve({ token: '{{NEW_WEB_AUTH_TOKEN}}', userId: '{{NEW_WEB_AUTH_USER_ID}}', via: 'NEW_WEB_AUTH_VIA' }); }, 500); }); }; return tokenAPI().then((newWebAuth) => { webAuth.token = newWebAuth.token; webAuth.userId = newWebAuth.userId; webAuth.via = newWebAuth.via; }); } }; ``` | property | type | description | optional | | :---------------------: | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | :------: | | userInfo | String | 사용자 정보 | O | | userInfo.appKey | String | 통합 AppKey 또는 서비스 AppKey | O | | userInfo.examNo | String | 시험 번호 | O | | userInfo.userId | String | 사용자 ID(수험생 번호) | O | | deviceType | String | 장비 구분(pc: PC, mo: Mobile ) | O | | webAuth | JSON | WebAuth 인증 데이터 | O | | webAuth.userId | String | 사용자 ID(수험생 번호) | O | | webAuth.token | String | 고객사에서 발급한 WebAuth 인증 토큰 | O | | webAuth.via | String | 기타 정보 | X | | apiBaseUrl | String | api base url | O | | retryCount | Number | api 요청 실패시 재요청 횟수 | O | | authRenewCount | Number | 인증 갱신 실패시 재요청 횟수 | O | | authRenewBeforeCallback | Function | WebAuth 인증 데이터를 갱신시키기 위한 콜백 함수<br />Promise를 반환해야 한다.<br />반환된 Promise는 새로운 인증에 필요한 `webAuth` 정보를 반환해한다. | O | ## instance methods ### collector#getApiBaseUrl(): - api base url 반환 ### collector#setApiBaseUrl(apiBaseUrl: string) - api base url 변경 ### collector#updateUserInfo(newUserInfo: Object) - 사용자 정보 갱신 - 3개의 항목(appKey, examNo, userId) 중 최소 1개 이상의 key-value 쌍을 전달 ### Example ```js collector.updateUserInfo({ appKey: '{{UPDATE_NEW_APP_KEY}}', // 통합 AppKey 또는 서비스 AppKey examNo: '{{UPDATE_NEW_EXAM_NO}}', // 시험 번호 userId: '{{UPDATE_NEW_USER_ID}}' // 사용자 아이디 }); ``` ### collector#setRetryCount(count: Number) - API 요청 실패 시 재요청 횟수 변경 ### collector#setAuthRenewCount(count: Number) - 인증 갱신 실패 시 재요청 횟수 변경 ### collector#setAuthRenewBeforeCallback(callback: Function) - WebAuth 인증 데이터를 갱신시키기 위한 콜백 함수 - Promise를 반환한다. - 일부 WebAuth 값을 반환하면 반환된 필드가 갱신된다. ### on(event: String, listener: Function) - 요청에 대한 성공, 실패 구독 등록 ```js collector.on('api:success', (response) => { console.log('요청 결과 : ', response); }); collector.on('api:fail', ({ resultCode, resultMessage }) => { console.log(`응답 데이터 에러 : ${resultCode} ${resultMessage}`); }); ``` ### collector#revokeAccessToken() - 발급 받은 Token을 취소(강제 만료 시키기 위한) API #### Example ```js collector#revokeAccessToken() ``` ### collector#fetchFaceDetect(bodyData: {image: { url: string, bytes: Array&lt;Uint8Array&gt; }}) - 얼굴 인식 API 요청 #### [Request Body] | 이름 | 타입 | 설명 | 필수 여부 | | ----------- | ------ | ------------------------------------------------------------------------------------------ | ----------- | | image.url | String | 이미지의 URL<br />image.url, image.bytes 중 반드시 1개만 있어야 한다. | 선택적 필수 | | image.bytes | Blob | base64로 인코딩된 이미지 바이트<br />image.url, image.bytes 중 반드시 1개만 존재해야 한다. | 선택적 필수 | #### Example ```js const input = document.querySelector('#uid_face_detect_input'); const [file] = input.files; file.arrayBuffer().then((buffer) => { const data = { image: { bytes: Array.from(new Uint8Array(buffer)) } }; // 얼굴 인식 API 요청 collector.fetchFaceDetect(data); }); ``` ### collector#fetchBehaviorDetect(bodyData: {file:FormData}, queryParams: { camLocation: string, reqTime: number }) - 행동 감지 요청 API #### [URL Parameter] | 이름 | 타입 | 설명 | 필수 여부 | | ----------- | ------ | ----------------------------------------- | --------- | | camLocation | String | 카메라 위치 정보(side(측면), front(정면)) | O | | reqTime | long | 요청 시간(timestamp 10자리)(초 단위까지) | O | #### [Request Body] | 이름 | 타입 | 설명 | 필수 여부 | | ---- | ------ | ------------------------------------------------------------------------------------------------------------------------------ | --------- | | file | Binary | 이미지 파일<br>이미지 권장 사항<br>side (Size : 640 x 360, 확장자 : jpg, jpeg)<br>front (Size : 640 x 480, 확장자 : jpg, jpeg) | O | #### Example ```js // request body const formData = new FormData(); formData.append('file', new File([imageBlob], 'cam-snapshot.jpg', { type: 'image/jpeg' })); // request params const query = { reqTime: Math.floor(Date.now() / 1000), camLocation: 'front' }; // 행동 감지 요청 API collector.fetchBehaviorDetect(formData, query); ``` ### collector#fetchVoiceDetect(data: {file: BinaryData}, queryParams: { reqTime: number }) - 음성 감지 요청 API #### [URL Parameter] | 이름 | 타입 | 설명 | 필수 여부 | | ------- | ---- | ---------------------------------------- | --------- | | reqTime | long | 요청 시간(timestamp 10자리)(초 단위까지) | O | #### [Request Body] | 이름 | 타입 | 설명 | 필수 여부 | | ---- | ------ | ----------------------------------------------------------------------------------------------- | --------- | | file | Binary | 음성 파일<br>(지원 형식 .wav, .wave, .webm)<br>(권장 16bit, 16,000 sampling rate, mono channel) | O | #### Example ```js // request body const formData = new FormData(); formData.append('file', new File([imageBlob], 'cam-snapshot.jpg', { type: 'image/jpeg' })); // request params const query = { reqTime: Math.floor(Date.now() / 1000) }; // 음성 감지 요청 API collector.fetchVoiceDetect(formData, query); ``` ### collector#registerBehaviorReg(bodyData: {file:FormData}) - 가운데 시선 정보 등록 API ### [Request Body] | 이름 | 타입 | 설명 | 필수 여부 | | ---- | ------ | --------------------------------------------------------------- | --------- | | file | Binary | 이미지 파일<br>권장 사항 (Size : 640 x 480, 확장자 : jpg, jpeg) | O | #### Example ```js // request body const formData = new FormData(); formData.append('file', new File([imageBlob], 'cam-snapshot.jpg', { type: 'image/jpeg' })); // 가운데 시선 정보 등록 API collector.registerBehaviorReg(formData); ``` ### collector#preCheckSideCamera(bodyData: {file:FormData}) - 측면 카메라 사전 검증 API ### [Request Body] | 이름 | 타입 | 설명 | 필수 여부 | | ---- | ------ | --------------------------------------------------------------- | --------- | | file | Binary | 이미지 파일<br>권장 사항 (Size : 640 x 360, 확장자 : jpg, jpeg) | O | #### Example ```js // request body const formData = new FormData(); formData.append('file', new File([imageBlob], 'cam-snapshot.jpg', { type: 'image/jpeg' })); // 측면 카메라 사전 검증 API collector.preCheckSideCamera(formData); ```