/
digital-factory.ts
390 lines (328 loc) · 12.8 KB
/
digital-factory.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
import { createHash, randomBytes } from 'crypto';
import {
createServer, IncomingMessage, Server, ServerResponse,
} from 'http';
import fetch from 'node-fetch';
import * as fs from 'fs';
import * as path from 'path';
import * as env from 'dotenv';
import { print, prettyJSON } from './print';
const DEFAULT_CLOUD_ACCOUNT_API_ROOT = 'https://account.ultimaker.com';
const OAUTH_SERVER_URL = DEFAULT_CLOUD_ACCOUNT_API_ROOT;
const API_ROOT_URL = 'https://api.ultimaker.com';
const CALLBACK_SERVER_PORT = 32118;
env.config({ path: '../config.env' });
const { CLIENT_ID } = process.env;
const { SCOPES } = process.env;
export interface TokenResponse {
access_token: string;
expires_in: number;
refresh_token: string;
scope: string;
token_type: string;
}
export class DigitalFactoryDemo {
private _callbackServer: Server = null;
private _state: string = null;
private _pkceVerifier: string = null;
private _tokenPair: TokenResponse = null;
private _tokenTimestampMs = 0;
private _token_url: string = null;
private _authorizationUrl = `${OAUTH_SERVER_URL}/authorize`;
private _redirectUri: string = null;
private _signInCompleteResolve: () => void = null;
signIn(): Promise<void> {
this._callbackServer = createServer(this._handleRequest.bind(this));
this._callbackServer.listen(CALLBACK_SERVER_PORT);
this._token_url = `${OAUTH_SERVER_URL}/token`;
this._redirectUri = `http://localhost:${CALLBACK_SERVER_PORT}/callback`;
this._state = this._generateState();
this._pkceVerifier = this._generatePKCEVerifier();
const query = new URLSearchParams({
client_id: CLIENT_ID,
redirect_uri: this._redirectUri,
scope: SCOPES,
state: this._state,
response_type: 'code',
code_challenge: this._generatePKCEChallenge(this._pkceVerifier),
code_challenge_method: 'S512',
});
const signInUrl = `${this._authorizationUrl}?${query}`;
print('Open the following URL in your browser and log in to Ultimaker Digital Factory:');
print('');
print(` ${signInUrl}`);
print('');
return new Promise<void>((resolve, reject) => {
this._signInCompleteResolve = resolve;
process.on('SIGINT', reject);
});
}
private async _handleRequest(req: IncomingMessage, res: ServerResponse): Promise<void> {
if (!req.url) {
return;
}
if (!this._pkceVerifier) {
return;
}
const url = new URL(`http://localhost:${CALLBACK_SERVER_PORT}${req.url}`);
const code = url.searchParams.get('code');
if (!code) {
return;
}
const state = url.searchParams.get('state');
if (!state || state !== this._state) {
return;
}
this._tokenPair = await this._requestAccessToken(code, this._pkceVerifier);
this._tokenTimestampMs = Date.now();
print(`Access token: ${prettyJSON(this._tokenPair.access_token)}`);
print(`Expires in: ${this._tokenPair.expires_in}s`);
res.writeHead(200);
res.end('Sign in finished, you can now close this window.');
// reset everything
this._callbackServer && this._callbackServer.close(); // eslint-disable-line no-unused-expressions
this._callbackServer = null;
this._state = null;
this._pkceVerifier = null;
this._signInCompleteResolve();
}
private async _requestAccessToken(code: string, pkceVerifier: string): Promise<TokenResponse> {
const tokenResponse = await fetch(this._token_url, {
method: 'POST',
body: new URLSearchParams({
client_id: CLIENT_ID,
redirect_uri: this._redirectUri,
grant_type: 'authorization_code',
scope: SCOPES,
code,
code_verifier: pkceVerifier,
}),
});
return tokenResponse.json();
}
private _generateState(): string {
return randomBytes(16).toString('base64');
}
private _generatePKCEVerifier(): string {
return randomBytes(32).toString('base64');
}
private _generatePKCEChallenge(verifier: string): string {
return createHash('sha512').update(verifier).digest().toString('base64');
}
private _getRequestHeaders(): {[key: string]: string} {
return {
Authorization: `Bearer ${this._tokenPair.access_token}`,
};
}
private async _checkTokenExpiration(): Promise<any> {
if (!this._tokenNeedsRefresh()) {
return;
}
print('Trying to refresh the token');
this._tokenPair = await this._requestTokenRefresh();
this._tokenTimestampMs = Date.now();
print(`New access token: ${prettyJSON(this._tokenPair.access_token)}`);
print(`Expires in: ${this._tokenPair.expires_in}s`);
}
private async _requestTokenRefresh(): Promise<TokenResponse> {
const tokenResponse = await fetch(this._token_url, {
method: 'POST',
body: new URLSearchParams({
client_id: CLIENT_ID,
grant_type: 'refresh_token',
refresh_token: this._tokenPair.refresh_token,
scope: SCOPES,
}),
});
return tokenResponse.json();
}
private _tokenNeedsRefresh(): boolean {
// Refresh 30s before the token expires.
return Date.now() > (this._tokenTimestampMs + 1000 * (this._tokenPair.expires_in - 30));
}
async httpGetDigitalFactory(url: string): Promise<any> {
const response = await fetch(url, {
method: 'GET',
headers: this._getRequestHeaders(),
});
return response.json();
}
async httpPutDigitalFactory(url: string, body: any, additional_headers: any = {}): Promise<any> {
const headers = {
'Content-Type': 'application/json',
...additional_headers,
...this._getRequestHeaders(),
};
const response = await fetch(url, {
method: 'PUT',
headers,
body: prettyJSON(body),
});
return response.json();
}
async httpPostDigitalFactory(url: string, body: any = {}, additional_headers: any = {}): Promise<any> {
const headers = {
'Content-Type': 'application/json',
...additional_headers,
...this._getRequestHeaders(),
};
const response = await fetch(url, {
method: 'POST',
headers,
body: prettyJSON(body),
});
return response.json();
}
async createProject(name: string): Promise<any> {
await this._checkTokenExpiration();
const response = await this.httpPutDigitalFactory(
`${API_ROOT_URL}/cura/v1/projects`,
{
data: {
display_name: name,
},
},
);
return response.data;
}
async uploadFileToProject(libraryProjectId: string, filePath: string): Promise<any> {
const filename = path.posix.basename(filePath);
const fileContents = fs.readFileSync(filePath);
const contentLength = fileContents.byteLength;
const mimeType = 'application/x-ufp';
await this._checkTokenExpiration();
const jobUploadResponse = await this.httpPutDigitalFactory(`${API_ROOT_URL}/cura/v1/jobs/upload`, {
data: {
job_name: filename,
content_type: mimeType,
file_size: contentLength,
library_project_id: libraryProjectId,
},
});
const uploadUrl = jobUploadResponse.data.upload_url;
print(`upload url: ${uploadUrl}`);
await fetch(uploadUrl, {
method: 'PUT',
headers: { 'Content-Type': mimeType },
body: fileContents,
});
return jobUploadResponse.data;
}
async addCommentToProject(projectId: string, comment: string): Promise<void> {
await this._checkTokenExpiration();
const response = await this.httpPutDigitalFactory(
`${API_ROOT_URL}/cura/v1/projects/${projectId}/comments`,
{
data: {
body: comment,
},
},
);
return response.data;
}
async submitPrintJob(jobId: string, clusterId: string): Promise<any> {
await this._checkTokenExpiration();
const response = await this.httpPostDigitalFactory(
`${API_ROOT_URL}/connect/v1/clusters/${clusterId}/print/${jobId}`,
{ data: {} },
);
return response.data;
}
async getRunningPrintJobs(): Promise<any> {
const query = new URLSearchParams({
limit: '20',
status: 'in_progress',
});
await this._checkTokenExpiration();
const response = await this.httpGetDigitalFactory(`${API_ROOT_URL}/connect/v1/print_jobs?${query}`);
return response.data;
}
async getClusters(): Promise<Cluster[]> {
await this._checkTokenExpiration();
const response = await this.httpGetDigitalFactory(`${API_ROOT_URL}/connect/v1/clusters`);
return response.data;
}
async searchProjects(): Promise<any> {
const query = new URLSearchParams({
limit: '24',
page: '1',
search: 'demo',
shared: 'false',
});
await this._checkTokenExpiration();
const response = await this.httpGetDigitalFactory(`${API_ROOT_URL}/cura/v1/projects?${query}`);
return response.data;
}
async generateReport(clusterIds: string[]): Promise<string> {
await this._checkTokenExpiration();
print('Requesting report generation');
const today = new Date();
const sevenDaysAgoMs = Date.now() - 24 * 60 * 60 * 7 * 1000;
const sevenDaysAgo = new Date(sevenDaysAgoMs);
const response = <{ data: ReportStatus }> await this.httpPutDigitalFactory(`${API_ROOT_URL}/report/v1/reports`,
{
data: {
cluster_ids: clusterIds,
start_date: sevenDaysAgo.toISOString(),
end_date: today.toISOString(),
report_type: 'print_jobs',
},
});
let status: ReportStatus = response.data;
const reportID = status.report_id;
while (status.status === 'pending' || status.status === 'processing') {
print('Waiting one second');
await new Promise((resolve) => setTimeout(resolve, 1000));
print('Checking the status of the report');
const statusResponse = <{ data: ReportStatus }> await this.httpGetDigitalFactory(`${API_ROOT_URL}/report/v1/reports/${reportID}`);
status = statusResponse.data;
}
if (status.status !== 'success') {
print('Something went wrong while generating the report.', status);
return null;
}
return status.download_url;
}
async getWebcamImage(clusterId: string, clusterPrinterId: string): Promise<string> {
await this._checkTokenExpiration();
print('Requesting webcam image');
const response = <{data: WebcamActionStatusResponse}> await this.httpPostDigitalFactory(`${API_ROOT_URL}/connect/v1/clusters/${clusterId}/printers/${clusterPrinterId}/action/get_webcam_snapshot`,
{ data: {} });
const actionId = response.data.action_id;
let status = response.data;
while (status.status === 'pending' || status.status === 'sent') {
print('Waiting one second');
await new Promise((resolve) => setTimeout(resolve, 1000));
print('Checking the status of the webcam image');
const statusResponse = <{data: WebcamActionStatusResponse}> await this.httpGetDigitalFactory(`${API_ROOT_URL}/connect/v1/clusters/${clusterId}/action_status/${actionId}`);
status = statusResponse.data;
}
if (status.status !== 'success') {
print('Something went wrong while fetching the webcam image.', status);
return null;
}
return status.status_details.value.image_url;
}
}
interface ReportStatus {
download_url?: string;
report_id: string;
status: 'pending' | 'processing' | 'success' | 'failed' | 'unknown';
}
interface WebcamActionStatusResponse {
action_id: string;
status: 'success' | 'failed' | 'pending' | 'sent' | 'unknown';
status_details: {
type: string;
value: {
image_url: string
}};
}
// A minimal Cluster definition
interface Cluster {
cluster_id: string;
is_online: boolean;
host_printer: {
uuid: string;
};
}