forked from ToolJet/ToolJet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutil.service.ts
More file actions
224 lines (193 loc) · 7.61 KB
/
util.service.ts
File metadata and controls
224 lines (193 loc) · 7.61 KB
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
import { dbTransactionWrap } from '@helpers/database.helper';
import { CreatePluginDto, UpdatePluginDto } from './dto';
import { EntityManager } from 'typeorm';
import { FilesRepository } from '@modules/files/repository';
import { ConfigService } from '@nestjs/config';
import { InternalServerErrorException } from '@nestjs/common';
import { Plugin } from '@entities/plugin.entity';
import { encode } from 'js-base64';
import { File } from 'src/entities/file.entity';
import * as jszip from 'jszip';
import * as fs from 'fs';
import { CreateFileDto, UpdateFileDto } from '@modules/files/dto';
import { IPluginsUtilService } from './interfaces/IUtilService';
import { Injectable } from '@nestjs/common';
const jszipInstance = new jszip();
@Injectable()
export class PluginsUtilService implements IPluginsUtilService {
constructor(protected readonly filesRepository: FilesRepository, protected readonly configService: ConfigService) {}
async create(
createPluginDto: CreatePluginDto,
version: string,
files: {
index: ArrayBuffer;
operations: ArrayBuffer;
icon: ArrayBuffer;
manifest: ArrayBuffer;
}
) {
return await dbTransactionWrap(async (manager: EntityManager) => {
const queryRunner = manager.connection.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
try {
const uploadedFiles: { index?: File; operations?: File; icon?: File; manifest?: File } = {};
await Promise.all(
Object.keys(files).map(async (key) => {
return await dbTransactionWrap(async (manager: EntityManager) => {
const file = files[key];
const fileDto = new CreateFileDto();
fileDto.data = encode(file);
fileDto.filename = key;
uploadedFiles[key] = await this.filesRepository.createOne(fileDto, manager);
});
})
);
const plugin = new Plugin();
plugin.pluginId = createPluginDto.id;
plugin.name = createPluginDto.name;
plugin.repo = createPluginDto.repo || '';
plugin.version = version || createPluginDto.version;
plugin.description = createPluginDto.description;
plugin.indexFileId = uploadedFiles.index.id;
plugin.operationsFileId = uploadedFiles.operations.id;
plugin.iconFileId = uploadedFiles.icon.id;
plugin.manifestFileId = uploadedFiles.manifest.id;
return await manager.save(plugin);
} catch (error) {
await queryRunner.rollbackTransaction();
throw new InternalServerErrorException(error);
} finally {
await queryRunner.release();
}
});
}
fetchPluginFiles(id: string, repo: string) {
if (repo && repo.length > 0) {
return this.fetchPluginFilesFromRepo(repo);
}
return this.fetchPluginFilesFromS3(id);
}
async fetchPluginFilesFromRepo(repo: string) {
const releaseResponse = await fetch(`https://api.github.com/repos/${repo}/releases/latest`);
const latestRelease = await releaseResponse.json();
const [zipballResponse, indexResponse] = await Promise.all([
fetch(`${latestRelease.zipball_url}`),
fetch(`${latestRelease.assets[0].browser_download_url}`),
]);
const zipball = await zipballResponse.arrayBuffer();
const index = await indexResponse.arrayBuffer();
const result = await jszipInstance.loadAsync(zipball);
let manifestFileKey: string;
let iconFileKey: string;
let operationsFileKey: string;
Object.keys(result.files).forEach(async (key) => {
if (key.includes('manifest.json')) {
manifestFileKey = key;
} else if (key.includes('icon.svg')) {
iconFileKey = key;
} else if (key.includes('operations.json')) {
operationsFileKey = key;
}
});
const [manifestFile, iconFile, operations] = await Promise.all([
result.files[manifestFileKey].async('arraybuffer'),
result.files[iconFileKey].async('arraybuffer'),
result.files[operationsFileKey].async('arraybuffer'),
]);
const version = latestRelease.name.replace('v', '');
return [index, operations, iconFile, manifestFile, version];
}
private async fetchPluginFilesFromS3(id: string) {
if (process.env.NODE_ENV === 'production') {
const host = this.configService.get<string>(
'TOOLJET_MARKETPLACE_URL',
'https://tooljet-plugins-production.s3.us-east-2.amazonaws.com'
);
const promises = await Promise.all([
fetch(`${host}/marketplace-assets/${id}/dist/index.js`),
fetch(`${host}/marketplace-assets/${id}/lib/operations.json`),
fetch(`${host}/marketplace-assets/${id}/lib/icon.svg`),
fetch(`${host}/marketplace-assets/${id}/lib/manifest.json`),
]);
const files = promises.map(async (promise) => {
if (!promise.ok) throw new InternalServerErrorException();
const arrayBuffer = await promise.arrayBuffer();
const textDecoder = new TextDecoder();
return textDecoder.decode(arrayBuffer);
});
const [indexFile, operationsFile, iconFile, manifestFile] = await Promise.all(files);
return [indexFile, operationsFile, iconFile, manifestFile];
}
async function readFile(filePath) {
return new Promise((resolve, reject) => {
const readStream = fs.createReadStream(filePath, { encoding: 'utf8' });
let fileContent = '';
readStream.on('data', (chunk) => {
fileContent += chunk;
});
readStream.on('error', (err) => {
reject(err);
});
readStream.on('end', () => {
resolve(fileContent);
});
});
}
const [indexFile, operationsFile, iconFile, manifestFile] = await Promise.all([
readFile(`../marketplace/plugins/${id}/dist/index.js`),
readFile(`../marketplace/plugins/${id}/lib/operations.json`),
readFile(`../marketplace/plugins/${id}/lib/icon.svg`),
readFile(`../marketplace/plugins/${id}/lib/manifest.json`),
]);
return [indexFile, operationsFile, iconFile, manifestFile];
}
async upgrade(
id: string,
updatePluginDto: UpdatePluginDto,
version: string,
files: {
index: ArrayBuffer;
operations: ArrayBuffer;
icon: ArrayBuffer;
manifest: ArrayBuffer;
}
) {
return await dbTransactionWrap(async (manager: EntityManager) => {
const queryRunner = manager.connection.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
try {
const currentPlugin = await manager.findOne(Plugin, {
where: { id },
});
const uploadedFiles: { index?: File; operations?: File; icon?: File; manifest?: File } = {};
await Promise.all(
Object.keys(files).map(async (key) => {
return await dbTransactionWrap(async (manager: EntityManager) => {
const file = files[key];
const fileDto = new UpdateFileDto();
fileDto.data = encode(file);
fileDto.filename = key;
uploadedFiles[key] = await this.filesRepository.updateOne(
currentPlugin[`${key}FileId`],
fileDto,
manager
);
});
})
);
const plugin = new Plugin();
plugin.id = currentPlugin.id;
plugin.repo = updatePluginDto.repo || '';
plugin.version = version ?? updatePluginDto.version;
return manager.save(plugin);
} catch (error) {
await queryRunner.rollbackTransaction();
throw new InternalServerErrorException(error);
} finally {
await queryRunner.release();
}
});
}
}