0.0.6 • Published 2 years ago

nhn-cd-sdk v0.0.6

Weekly downloads
-
License
MIT
Repository
-
Last release
2 years ago

NHN Proctor SDK

Installing

Using npm:

$ npm install nhn-cd-sdk

Using jsDelivr CDN:

<script src="https://cdn.jsdelivr.net/npm/nhn-cd-sdk@{{VERSION}}/dist/nhn-cd-sdk.js"></script>

Using unpkg CDN:

<script src="https://unpkg.com/nhn-cd-sdk@{{VERSION}}/dist/nhn-cd-sdk.js"></script>

Usage

import usage:

import { Launcher, Collector, Communicator } from 'nhn-cd-sdk';

const config = {
  /* ... */
};
const collector = new Collector(config);

CDN usage:

const config = {
  /* ... */
};
const collector = new window.nhnCDSDK.Collector(config);

Run example

Using npm script:

$ npm i
$ npm run example

Using example file:

Copy the code from the examples folder to your local project at jsdelivr or unpkg. Then change the code below in the html file as follows.

<!-- 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

const launcher = new Launcher('https://...', { option1: 'value' });

instance methods

launcher#setServiceUrl(serviceUrl: String)

  • 서비스 URL 설정 또는 기존의 서비스 URL 값을 변경

launcher#setUriParams(uriParameters: Object)

  • 옵션 설정 또는 기존의 옵션 값을 변경

launcher#launch()

  • Proctor 실행

Communicator

  • 시험 시작, 시험 종료 제어

Get an Communicator instance

Example

const communicator = new window.nhnCDSDK.Communicator();

instance methods

communicator#initialize(config: Object)

  • NHN Proctor 사용자 정보 초기화

Example

communicator.initialize({
  appKey: '{{APP_KEY}}',
  examNo: '{{EXAM_NO}}',
  userId: '{{USER_ID}}'
});

communicator#communicate(event,properties)

  • NHN Proctor 이벤트 전달

Example

event = '{{EVENT_NAME}}'; // or 'beginTest' or 'endTest'
properties = {
  key: '{{VALUE}}'
};

communicator#beginTest()

  • 시험 시작

communicator#endTest()

  • 시험 종료

Collector

  • Collector API 제공

Get an Collector instance

Example

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;
    });
  }
};
propertytypedescriptionoptional
userInfoString사용자 정보O
userInfo.appKeyString통합 AppKey 또는 서비스 AppKeyO
userInfo.examNoString시험 번호O
userInfo.userIdString사용자 ID(수험생 번호)O
deviceTypeString장비 구분(pc: PC, mo: Mobile )O
webAuthJSONWebAuth 인증 데이터O
webAuth.userIdString사용자 ID(수험생 번호)O
webAuth.tokenString고객사에서 발급한 WebAuth 인증 토큰O
webAuth.viaString기타 정보X
apiBaseUrlStringapi base urlO
retryCountNumberapi 요청 실패시 재요청 횟수O
authRenewCountNumber인증 갱신 실패시 재요청 횟수O
authRenewBeforeCallbackFunctionWebAuth 인증 데이터를 갱신시키기 위한 콜백 함수Promise를 반환해야 한다.반환된 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

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)

  • 요청에 대한 성공, 실패 구독 등록
collector.on('api:success', (response) => {
  console.log('요청 결과 : ', response);
});
collector.on('api:fail', ({ resultCode, resultMessage }) => {
  console.log(`응답 데이터 에러 : ${resultCode} ${resultMessage}`);
});

collector#revokeAccessToken()

  • 발급 받은 Token을 취소(강제 만료 시키기 위한) API

Example

collector#revokeAccessToken()

collector#fetchFaceDetect(bodyData: {image: { url: string, bytes: Array<Uint8Array> }})

  • 얼굴 인식 API 요청

Request Body

이름타입설명필수 여부
image.urlString이미지의 URLimage.url, image.bytes 중 반드시 1개만 있어야 한다.선택적 필수
image.bytesBlobbase64로 인코딩된 이미지 바이트image.url, image.bytes 중 반드시 1개만 존재해야 한다.선택적 필수

Example

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

이름타입설명필수 여부
camLocationString카메라 위치 정보(side(측면), front(정면))O
reqTimelong요청 시간(timestamp 10자리)(초 단위까지)O

Request Body

이름타입설명필수 여부
fileBinary이미지 파일이미지 권장 사항side (Size : 640 x 360, 확장자 : jpg, jpeg)front (Size : 640 x 480, 확장자 : jpg, jpeg)O

Example

// 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

이름타입설명필수 여부
reqTimelong요청 시간(timestamp 10자리)(초 단위까지)O

Request Body

이름타입설명필수 여부
fileBinary음성 파일(지원 형식 .wav, .wave, .webm)(권장 16bit, 16,000 sampling rate, mono channel)O

Example

// 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

이름타입설명필수 여부
fileBinary이미지 파일권장 사항 (Size : 640 x 480, 확장자 : jpg, jpeg)O

Example

// 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

이름타입설명필수 여부
fileBinary이미지 파일권장 사항 (Size : 640 x 360, 확장자 : jpg, jpeg)O

Example

// request body
const formData = new FormData();
formData.append('file', new File([imageBlob], 'cam-snapshot.jpg', { type: 'image/jpeg' }));
// 측면 카메라 사전 검증 API
collector.preCheckSideCamera(formData);