77 */
88
99const QueryString = require ( 'querystring' )
10-
1110const RequestPromise = require ( 'request-promise' )
11+ const socketClient = require ( 'socket.io-client' )
12+
13+ const { createAuthorizationQuery, setAuthorization } = require ( './auth' )
1214
13- const Auth = require ( './auth' )
15+ const {
16+ API_HOST ,
17+ WEB_HOST ,
18+ HTTP_DEFAULT_OPTIONS ,
19+ SOCKET_HOST ,
20+ REND_FINISHED_STATE ,
21+ REND_NOT_FINISHED_STATE
22+ } = require ( './config' )
1423
15- const { API_HOST , WEB_HOST , HTTP_DEFAULT_OPTIONS } = require ( './config ' )
24+ const { SocketConnectionError } = require ( './util/error ' )
1625
1726class Api {
1827 /**
@@ -80,7 +89,6 @@ class Api {
8089 */
8190 unauthorizedRequest ( options ) {
8291 const _options = Object . assign ( { } , HTTP_DEFAULT_OPTIONS , options )
83-
8492 Api . prepareRequest ( _options )
8593
8694 return Api . request ( _options )
@@ -93,9 +101,8 @@ class Api {
93101 */
94102 authorizedRequest ( options ) {
95103 const _options = Object . assign ( { } , HTTP_DEFAULT_OPTIONS , options )
96-
97104 Api . prepareRequest ( _options )
98- Auth . setAuthorization ( _options , this . signKey , this . clientId )
105+ setAuthorization ( _options , this . signKey , this . clientId )
99106
100107 return Api . request ( _options )
101108 }
@@ -107,11 +114,40 @@ class Api {
107114 */
108115 webRequest ( options ) {
109116 const _options = Object . assign ( { } , HTTP_DEFAULT_OPTIONS , options )
110-
111117 Api . appendURI ( _options , WEB_HOST )
112118
113119 return RequestPromise ( _options )
114120 }
121+
122+ /**
123+ * @param {Function } callback - The callback function for handling render status result.
124+ * @return {unsubscribe }
125+ */
126+ socketConnection ( callback ) {
127+ const renderStatus = socketClient ( SOCKET_HOST , {
128+ query : createAuthorizationQuery ( this . clientId , this . signKey )
129+ } )
130+
131+ renderStatus . on ( 'error' , ( error ) => callback ( new SocketConnectionError ( error ) ) )
132+ renderStatus . on ( 'event' , ( status ) => {
133+ if ( status . state === 'rended' ) {
134+ renderStatus . close ( )
135+ return callback ( null , REND_FINISHED_STATE )
136+ } else {
137+ // if `status.state` is not `rended` but percent is 100, then show rend not finished state
138+ return callback ( null , Math . min ( REND_NOT_FINISHED_STATE , status . percent ) )
139+ }
140+ } )
141+
142+ // if socket is still open, then force close manually.
143+ const unsubscribe = ( ) => {
144+ if ( renderStatus ) {
145+ renderStatus . close ( )
146+ }
147+ }
148+
149+ return unsubscribe
150+ }
115151}
116152
117153module . exports = new Api ( )
0 commit comments