/
crowdin.ts
620 lines (569 loc) · 19.3 KB
/
crowdin.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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
/* eslint-disable @typescript-eslint/ban-ts-ignore */
import Crowdin, { ReportsModel, SourceFilesModel, TranslationsModel, WebhooksModel } from '@crowdin/crowdin-api-client';
import axios from 'axios';
interface UpdateOrCreateFileArgs {
client: Crowdin;
projectId: number;
name: string;
title?: string;
type?: SourceFilesModel.FileType;
directoryId?: number;
data: any;
file?: SourceFilesModel.File;
}
function isUpdateOrCreateFileArgs(arg: Crowdin | UpdateOrCreateFileArgs): arg is UpdateOrCreateFileArgs {
//@ts-ignore
return arg.client && arg.projectId;
}
/**
*
* @param client crowdin client instance
* @param projectId crowdin project id
* @param name file name
* @param title file title
* @param type file type
* @param directoryId directory id
* @param data file data
* @param file file object
* @returns id of newly created or existing file id
*/
export async function updateOrCreateFile(
client: Crowdin,
projectId: number,
name: string,
title: string,
type: SourceFilesModel.FileType,
directoryId: number,
data: any,
file?: SourceFilesModel.File,
): Promise<number>;
export async function updateOrCreateFile(args: UpdateOrCreateFileArgs): Promise<number>;
export async function updateOrCreateFile(
clientOrArgs: Crowdin | UpdateOrCreateFileArgs,
projectId?: number,
name?: string,
title?: string,
type?: SourceFilesModel.FileType,
directoryId?: number,
data?: any,
file?: SourceFilesModel.File,
): Promise<number> {
let options: UpdateOrCreateFileArgs;
if (isUpdateOrCreateFileArgs(clientOrArgs)) {
options = clientOrArgs;
} else {
//@ts-ignore
options = { client: clientOrArgs, projectId, name, title, type, directoryId, data, file };
}
const storageFile = await options.client.uploadStorageApi.addStorage(options.name, options.data);
if (options.file) {
await options.client.sourceFilesApi.updateOrRestoreFile(options.projectId, options.file.id, {
storageId: storageFile.data.id,
});
if (options.title && options.title !== options.file.title) {
await options.client.sourceFilesApi.editFile(options.projectId, options.file.id, [
{
value: options.title,
op: 'replace',
path: '/title',
},
]);
}
//@ts-ignore
return options.file.id;
} else {
const newFile = await options.client.sourceFilesApi.createFile(options.projectId, {
storageId: storageFile.data.id,
name: options.name,
title: options.title,
type: options.type,
directoryId: options.directoryId,
});
return newFile.data.id;
}
}
interface GetFolderArgs {
directories: SourceFilesModel.Directory[];
client: Crowdin;
projectId: number;
directoryName: string;
parentDirectory?: SourceFilesModel.Directory;
}
function isGetFolderArgs(arg: GetFolderArgs | SourceFilesModel.Directory[]): arg is GetFolderArgs {
return !Array.isArray(arg);
}
/**
*
* @param directories all directories
* @param crowdinClient crowdin client instance
* @param projectId project id
* @param directoryName directory name to find
* @param parentDirectory parent directory
* @returns found folder (or undefined in case if directory for given name does not exists) and files under it
*/
export async function getFolder(
directories: SourceFilesModel.Directory[],
crowdinClient: Crowdin,
projectId: number,
directoryName: string,
parentDirectory?: SourceFilesModel.Directory,
): Promise<{ folder?: SourceFilesModel.Directory; files: SourceFilesModel.File[] }>;
export async function getFolder(
args: GetFolderArgs,
): Promise<{ folder?: SourceFilesModel.Directory; files: SourceFilesModel.File[] }>;
export async function getFolder(
directoriesOrArgs: SourceFilesModel.Directory[] | GetFolderArgs,
crowdinClient?: Crowdin,
projectId?: number,
directoryName?: string,
parentDirectory?: SourceFilesModel.Directory,
): Promise<{ folder?: SourceFilesModel.Directory; files: SourceFilesModel.File[] }> {
let args: GetFolderArgs;
if (isGetFolderArgs(directoriesOrArgs)) {
args = directoriesOrArgs;
} else {
//@ts-ignore
args = { directories: directoriesOrArgs, client: crowdinClient, projectId, directoryName, parentDirectory };
}
const folder = args.directories.find(
d =>
d.name === args.directoryName &&
((!args.parentDirectory && !d.directoryId) || d.directoryId === args.parentDirectory?.id),
);
let files: SourceFilesModel.File[] = [];
if (folder) {
files = (
await args.client.sourceFilesApi.withFetchAll().listProjectFiles(args.projectId, { directoryId: folder.id })
).data.map(e => e.data);
}
return { folder, files };
}
interface GetOrCreateFolderArgs {
directories: SourceFilesModel.Directory[];
client: Crowdin;
projectId: number;
directoryName: string;
parentDirectory?: SourceFilesModel.Directory;
}
function isGetOrCreateFolderArgs(
args: GetOrCreateFolderArgs | SourceFilesModel.Directory[],
): args is GetOrCreateFolderArgs {
return !Array.isArray(args);
}
/**
*
* @param directories all directories
* @param crowdinClient crowdin client instance
* @param projectId project id
* @param directoryName directory name to find
* @param parentDirectory parent directory
* @returns found or created folder and files under it
*/
export async function getOrCreateFolder(
directories: SourceFilesModel.Directory[],
crowdinClient: Crowdin,
projectId: number,
directoryName: string,
parentDirectory?: SourceFilesModel.Directory,
): Promise<{ folder: SourceFilesModel.Directory; files: SourceFilesModel.File[]; created: boolean }>;
export async function getOrCreateFolder(
args: GetFolderArgs,
): Promise<{ folder: SourceFilesModel.Directory; files: SourceFilesModel.File[]; created: boolean }>;
export async function getOrCreateFolder(
directoriesOrArgs: SourceFilesModel.Directory[] | GetOrCreateFolderArgs,
crowdinClient?: Crowdin,
projectId?: number,
directoryName?: string,
parentDirectory?: SourceFilesModel.Directory,
): Promise<{ folder: SourceFilesModel.Directory; files: SourceFilesModel.File[]; created: boolean }> {
let args: GetOrCreateFolderArgs;
if (isGetOrCreateFolderArgs(directoriesOrArgs)) {
args = directoriesOrArgs;
} else {
//@ts-ignore
args = { directories: directoriesOrArgs, client: crowdinClient, projectId, directoryName, parentDirectory };
}
let { folder, files } = await getFolder(args);
let created = false;
if (!folder) {
created = true;
folder = (
await args.client.sourceFilesApi.createDirectory(args.projectId, {
name: args.directoryName,
directoryId: args.parentDirectory ? args.parentDirectory.id : undefined,
})
).data;
files = (
await args.client.sourceFilesApi.withFetchAll().listProjectFiles(args.projectId, { directoryId: folder.id })
).data.map(e => e.data);
}
return { folder, files, created };
}
interface UploadTranslationsArgs {
client: Crowdin;
projectId: number;
fileId: number;
language: string;
fileName: string;
fileContent: any;
request?: Omit<TranslationsModel.UploadTranslationRequest, 'fileId' | 'storageId'>;
}
function isUploadTranslationsArgs(args: UploadTranslationsArgs | Crowdin): args is UploadTranslationsArgs {
//@ts-ignore
return args.client && args.projectId;
}
/**
*
* @param crowdinClient crowdin client instance
* @param projectId project id
* @param fileId file id
* @param language language id
* @param fileName file name for upload storage request
* @param fileContent file content
* @param request extra request fields for upload translation request
* @returns upload translation response
*/
export async function uploadTranslations(
crowdinClient: Crowdin,
projectId: number,
fileId: number,
language: string,
fileName: string,
fileContent: any,
request?: Omit<TranslationsModel.UploadTranslationRequest, 'fileId' | 'storageId'>,
): Promise<TranslationsModel.UploadTranslationResponse>;
export async function uploadTranslations(
args: UploadTranslationsArgs,
): Promise<TranslationsModel.UploadTranslationResponse>;
export async function uploadTranslations(
crowdinClientOrArgs: Crowdin | UploadTranslationsArgs,
projectId?: number,
fileId?: number,
language?: string,
fileName?: string,
fileContent?: any,
request?: Omit<TranslationsModel.UploadTranslationRequest, 'fileId' | 'storageId'>,
): Promise<TranslationsModel.UploadTranslationResponse> {
let args: UploadTranslationsArgs;
if (isUploadTranslationsArgs(crowdinClientOrArgs)) {
args = crowdinClientOrArgs;
} else {
//@ts-ignore
args = { client: crowdinClientOrArgs, projectId, fileId, fileContent, fileName, language, request };
}
const storage = await args.client.uploadStorageApi.addStorage(args.fileName, args.fileContent);
return (
await args.client.translationsApi.uploadTranslation(args.projectId, args.language, {
fileId: args.fileId,
storageId: storage.data.id,
...(args.request || {}),
})
).data;
}
interface UpdateSourceFilesArgs {
client: Crowdin;
projectId: number;
directory: string;
fileEntities: FileEntity[];
parentDirectory?: SourceFilesModel.Directory;
}
function isUpdateSourceFilesArgs(args: UpdateSourceFilesArgs | Crowdin): args is UpdateSourceFilesArgs {
//@ts-ignore
return args.client && args.projectId;
}
/**
*
* @param crowdinClient crowdin client instance
* @param projectId project id
* @param directory directory name where files are located
* @param fileEntities files information
* @param parentDirectory parent directory
*/
export async function updateSourceFiles(
crowdinClient: Crowdin,
projectId: number,
directory: string,
fileEntities: FileEntity[],
parentDirectory?: SourceFilesModel.Directory,
): Promise<void>;
export async function updateSourceFiles(args: UpdateSourceFilesArgs): Promise<void>;
export async function updateSourceFiles(
crowdinClientOrArgs: Crowdin | UpdateSourceFilesArgs,
projectId?: number,
directory?: string,
fileEntities?: FileEntity[],
parentDirectory?: SourceFilesModel.Directory,
): Promise<void> {
let args: UpdateSourceFilesArgs;
if (isUpdateSourceFilesArgs(crowdinClientOrArgs)) {
args = crowdinClientOrArgs;
} else {
//@ts-ignore
args = { client: crowdinClientOrArgs, projectId, directory, fileEntities, parentDirectory };
}
const directories = await args.client.sourceFilesApi.withFetchAll().listProjectDirectories(args.projectId);
const { folder, files } = await getOrCreateFolder({
directories: directories.data.map(d => d.data),
client: args.client,
projectId: args.projectId,
directoryName: args.directory,
parentDirectory: args.parentDirectory,
});
await Promise.all(
args.fileEntities.map(
async fileEntity =>
await updateOrCreateFile({
client: args.client,
projectId: args.projectId,
name: fileEntity.name,
title: fileEntity.title,
type: fileEntity.type,
directoryId: folder.id,
data: fileEntity.data,
file: files.find(f => f.name === fileEntity.name),
}),
),
);
}
interface HandleTranslationsArgs {
client: Crowdin;
projectId: number;
directory: string;
request: TranslationsRequest;
parentDirectory?: SourceFilesModel.Directory;
handleFn: (translations: any, language: string, file: SourceFilesModel.File) => Promise<void>;
}
function isHandleTranslationsArgs(args: HandleTranslationsArgs | Crowdin): args is HandleTranslationsArgs {
//@ts-ignore
return args.client && args.projectId;
}
/**
*
* @param crowdinClient crowdin client instance
* @param projectId projecy id
* @param directory directory name where source files are located
* @param request request if file files and languages info
* @param handleFn function that will be invoked for each translation file
* @param parentDirectory parent directory
*/
export async function handleTranslations(
crowdinClient: Crowdin,
projectId: number,
directory: string,
request: TranslationsRequest,
handleFn: (translations: any, language: string, file: SourceFilesModel.File) => Promise<void>,
parentDirectory?: SourceFilesModel.Directory,
): Promise<void>;
export async function handleTranslations(args: HandleTranslationsArgs): Promise<void>;
export async function handleTranslations(
crowdinClientOrArgs: Crowdin | HandleTranslationsArgs,
projectId?: number,
directory?: string,
request?: TranslationsRequest,
handleFn?: (translations: any, language: string, file: SourceFilesModel.File) => Promise<void>,
parentDirectory?: SourceFilesModel.Directory,
): Promise<void> {
let args: HandleTranslationsArgs;
if (isHandleTranslationsArgs(crowdinClientOrArgs)) {
args = crowdinClientOrArgs;
} else {
//@ts-ignore
args = { client: crowdinClientOrArgs, projectId, directory, handleFn, request, parentDirectory };
}
const directories = await args.client.sourceFilesApi.withFetchAll().listProjectDirectories(args.projectId);
const { files } = await getFolder({
directories: directories.data.map(d => d.data),
client: args.client,
projectId: args.projectId,
directoryName: args.directory,
parentDirectory: args.parentDirectory,
});
for (const [fileId, targetLanguages] of Object.entries(args.request)) {
const file = files.find(f => f.id === parseInt(fileId));
if (!file) {
continue;
}
await Promise.all(
targetLanguages.map(async languageCode => {
const translationsLink = await args.client.translationsApi.buildProjectFileTranslation(
args.projectId,
file.id,
{
targetLanguageId: languageCode,
},
);
if (!translationsLink) {
return;
}
const response = await axios.get(translationsLink.data.url);
await args.handleFn(response.data, languageCode, file);
}),
);
}
}
interface CreateOrUpdateWebhookArgs {
client: Crowdin;
projectId: number;
url: string;
events: WebhooksModel.Event[];
payload: any;
name: string;
requestType?: WebhooksModel.RequestType;
batchingEnabled?: boolean;
headers?: Record<string, string>;
contentType?: WebhooksModel.ContentType;
webhookId?: number;
webhookMatch?: (webhook: WebhooksModel.Webhook) => boolean;
}
/**
* Function to update or create webhook
*
* @returns updated or created webhook id
*/
export async function createOrUpdateWebhook(args: CreateOrUpdateWebhookArgs): Promise<number> {
const {
client,
projectId,
events,
name,
url,
payload,
requestType = 'POST',
batchingEnabled = true,
headers,
contentType,
webhookId,
webhookMatch,
} = args;
let id = webhookId;
if (webhookMatch) {
const webhooks = await client.webhooksApi.withFetchAll().listWebhooks(projectId);
const webhook = webhooks.data.find(e => webhookMatch(e.data));
if (webhook) {
id = webhook.data.id;
}
}
if (id) {
await client.webhooksApi.editWebhook(projectId, id, [
{
value: events,
op: 'replace',
path: '/events',
},
{
value: payload,
op: 'replace',
path: '/payload',
},
{
value: url,
op: 'replace',
path: '/url',
},
]);
return id;
} else {
const newWebhook = await client.webhooksApi.addWebhook(projectId, {
name,
url,
events,
requestType,
payload,
batchingEnabled,
headers,
contentType,
});
return newWebhook.data.id;
}
}
export class PaymentRequiredError extends Error {
public subscribeLink: string;
public initializedAt: string;
constructor(subscribeLink: string, initializedAt: string) {
super('Payment required');
this.subscribeLink = subscribeLink;
this.initializedAt = initializedAt;
//@ts-ignore
this.code = 402;
}
}
/**
*
* @param param0.appIdentifier method request
* @param param0.token bearer token
* @param param0.organization crowdin organization
*/
export async function getSubscription({
appIdentifier,
token,
organization,
baseUrl,
}: SubscriptionRequest): Promise<Subscription> {
let requestUrl;
if (baseUrl) {
requestUrl = `${baseUrl}/api/v2/applications/${appIdentifier}/subscription`;
} else if (!!organization) {
requestUrl = `https://${organization}.api.crowdin.com/api/v2/applications/${appIdentifier}/subscription`;
} else {
requestUrl = `https://crowdin.com/api/v2/applications/${appIdentifier}/subscription`;
}
try {
const response = await axios.get<Subscription>(requestUrl, {
headers: {
Authorization: `Bearer ${token}`,
},
});
return response.data;
} catch (e) {
//@ts-ignore
if (e.response) {
//@ts-ignore
if (e.response.status === 402) {
//@ts-ignore
throw new PaymentRequiredError(e.response.data?.subscribeLink, e.response.data?.initializedAt);
//@ts-ignore
} else if (e.response.data?.error?.message) {
//@ts-ignore
throw new Error(e.response.data.error.message);
}
}
throw e;
}
}
export async function generateReport({
client,
projectId,
request,
}: {
client: Crowdin;
projectId: number;
request: ReportsModel.GenerateReportRequest;
}): Promise<any | undefined> {
const report = await client.reportsApi.generateReport(projectId, request);
while (true) {
const status = await client.reportsApi.checkReportStatus(projectId, report.data.identifier);
if (status.data.status === 'finished') {
const downloadRes = await client.reportsApi.downloadReport(projectId, report.data.identifier);
const reportBlob = await axios.get(downloadRes.data.url);
return reportBlob.data;
}
}
}
export interface FileEntity {
name: string;
title: string;
type: SourceFilesModel.FileType;
data: any;
}
export interface TranslationsRequest {
[fileId: string]: string[];
}
export interface SubscriptionRequest {
token: string;
organization?: string;
appIdentifier: string;
baseUrl?: string;
}
export interface Subscription {
expires: string;
}