-
Notifications
You must be signed in to change notification settings - Fork 63
/
Copy pathserversManagementView.ts
458 lines (376 loc) · 15.3 KB
/
serversManagementView.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
import * as nls from 'vscode-nls';
const localize = nls.loadMessageBundle();
import * as vscode from 'vscode';
import * as path from 'path';
import { ServerManagement, Context, ServerView, ServiceView, EnvironmentView } from './serverManagement';
import { IniManagement } from './iniManagement';
import IDictionary from './utils/IDictionary';
import IEnvironment from './utils/IEnvironment';
import { advplCompile } from './advplCompile';
export class ServerManagementView {
private _provider: ServerProvider;
private get Config(): vscode.WorkspaceConfiguration {
return vscode.workspace.getConfiguration("advpl");
}
private get EnvironmentsConfig(): Array<IEnvironment> {
return this.Config.get<Array<IEnvironment>>("environments");
}
private get Dictionary(): Array<IDictionary> {
return this.Config.get<Array<IDictionary>>("dictionary");
}
constructor() {
// Grava a instancia do Server Provider para registrar
this._provider = new ServerProvider();
// Registra o comando de conexão ao ambiente
vscode.commands.registerCommand("advpl.serversManagement.connect", (element) => this.connect(element));
// Registra o comando para obter e configurar todos os ambientes do INIs
vscode.commands.registerCommand("advpl.serversManagement.getAllEnvironments", (element) => this.getAllEnvironments(element));
// Registra o comando para renomear os ambientes/servidores ou serviços
vscode.commands.registerCommand("advpl.serversManagement.rename", (element) => this.rename(element));
// Registra o comando para Desfragmentar o Ambiente
vscode.commands.registerCommand("advpl.serversManagement.Defrag", (element) => this.defrag(element));
// Registra o comando para retornar os arquivos presentes no Ambiente
vscode.commands.registerCommand("advpl.serversManagement.getRpoInfos", (element) => this.getRpoInfos(element));
// Registra o comando para retornar as funções dos arquivos arquivos presentes no Ambiente
vscode.commands.registerCommand("advpl.serversManagement.getRpoFunctions", (element) => this.getRpoFunctions(element));
// Registra o comando para desabilitar o Ambiente
vscode.commands.registerCommand("advpl.serversManagement.DeleteEnvironment", (element) => this.delete(element));
// Registra o comando para alterar a senha do Ambiente
vscode.commands.registerCommand("advpl.serversManagement.CipherPassword", (element) => this.cipherPassword(element));
}
get provider() {
return this._provider;
}
public connect(element: Dependency) {
let updObj = vscode.workspace.getConfiguration("advpl");
// Atualiza a configuração de ambiente selecionado
updObj.update("selectedEnvironment", element.label).then(() => {
vscode.window.showInformationMessage(localize('src.ServerManagementView.environmentText', 'Environment ') + element.label + localize('src.ServerManagementView.environmentSelectedText', ' selection was successful.'));
});
}
public getAllEnvironments(element: Dependency) {
let serverManagement = new ServerManagement(false);
let ini = new IniManagement();
if (element.context !== Context.ServiceConnected) {
vscode.window.showErrorMessage(localize('src.ServerManagementView.CONTEXTVALID', "This option can only be used for a Service type item."));
return;
}
vscode.window.withProgress({
location: vscode.ProgressLocation.Window,
title: localize('src.ServerManagementView.CARREGANDO', "Loading environments..."),
cancellable: false
}, (progress, token) => {
token.onCancellationRequested(() => {
console.log("User canceled the long running operation");
});
return new Promise(resolve => {
// Busca o conteúdo do INI
ini.GetIniContent().then(() => {
// Busca todos os ambientes
ini.GetEnvironments();
ini.Environments.map(
env => {
let service = <ServiceView>element.subject;
// Verifica se o ambiente já está configurado
if (!service.environments.find(_env => _env.environment.toUpperCase() === env.Environment.toUpperCase())) {
// Adiciona nas configurações os ambientes do INI
serverManagement.AddEnvironment(
{
environment: env.Environment,
name: env.Environment,
server: service.parent.serverIP,
port: service.servicePort,
serverVersion: service.serverVersion,
passwordCipher: service.passwordCipher,
includeList: service.includeList,
user: service.user,
smartClientPath: service.smartClientPath,
enable: true
}
);
}
}
);
resolve();
});
});
});
}
rename(element: Dependency): any {
let config = this.Config;
let dictionary = this.Dictionary;
let environments = this.EnvironmentsConfig;
let oldLabel = element.label;
let options: vscode.InputBoxOptions = {
prompt: localize('src.ServerManagementView.RENAME', "Rename"),
placeHolder: localize('src.ServerManagementView.INFORMELABEL', "Enter the Label to change."),
value: oldLabel,
validateInput: function (newLabel: string) {
// Não permite label vazio
if (!newLabel) {
return localize('src.ServerManagementView.INFORMELABEL', "Enter the Label to change.");
}
// Verifica se o Label já foi utilizado no dicionário de Servidores/Serviços
if (dictionary.find(dic => dic.label.toUpperCase().trim() === newLabel.toUpperCase().trim())) {
return localize('src.ServerManagementView.LABELINUSE', "This Label is already in use.");
}
// Valida se o nome para o ambiente já foi utilizado
if (environments.find(env => retEnv(env).toUpperCase().trim() === newLabel.toUpperCase().trim())) {
return localize('src.ServerManagementView.NAMEINUSE', "This Label is already being used in an environment.");
}
/**
* Verifica se no ambiente está informado o atributo nome,
* trata desta forma para evitar erros caso essa propriedade
* seja null.
*/
function retEnv(env: IEnvironment) {
if (env.name)
return env.name;
else
return env.environment;
}
return "";
}
}
// Mostra um input para o usuário informar o novo label
vscode.window.showInputBox(options).then(newLabel => {
// Altera somente quando o Label for prenchido
if (newLabel) {
// Caso seja um elemento do nível servidor
if (element.subject instanceof ServerView) {
let obj = <ServerView>element.subject;
let dictionaryPos = dictionary.findIndex(dic => dic.name === obj.serverIP);
if (dictionaryPos > -1) {
dictionary[dictionaryPos].label = newLabel;
} else {
dictionary.push({
"label": newLabel,
"name": obj.serverIP
});
}
// Atualiza o dicionário de elementos
config.update('dictionary', dictionary);
} else if (element.subject instanceof ServiceView) {
let obj = <ServiceView>element.subject;
let dictionaryPos = dictionary.findIndex(dic => validParent(dic) && dic.name === obj.servicePort.toString());
/**
* Valida o atributo parent dessa forma para evitar erros
* caso essa propriedade seja null.
*/
function validParent(dic: IDictionary) {
if (dic.parent)
return dic.parent.trim() === obj.parent.serverIP.trim();
else
return true;
}
if (dictionaryPos > -1) {
dictionary[dictionaryPos].label = newLabel;
} else {
dictionary.push({
"label": newLabel,
"name": obj.servicePort.toString(),
"parent": obj.parent.serverIP
});
}
// Atualiza o dicionário de elementos
config.update('dictionary', dictionary);
} else if (element.subject instanceof EnvironmentView) {
let obj = <EnvironmentView>element.subject;
// Busca o ambiente relacionado ao serviço + servidor
environments.find(
env => env.environment === obj.environment &&
env.port === obj.parent.servicePort &&
env.server === obj.parent.parent.serverIP
).name = newLabel;
// Atualiza a configuração de ambientes
config.update('environments', environments);
// Caso o sujeito já esteja conectado, conecta novamente.
if (obj.isConnected) {
// Cria um novo elemento, para utilizá-lo para conectar no ambiente
let newElement = new Dependency(newLabel,
element.description,
element.tooltip,
element.collapsibleState,
element.context,
element.isConnected,
element.owner,
element.subject);
this.connect(newElement);
}
}
}
});
}
defrag(element: Dependency): any {
vscode.commands.executeCommand("advpl.monitor.defragRpo");
}
getRpoInfos(element: Dependency): any {
vscode.commands.executeCommand("advpl.monitor.getRpoInfos");
}
getRpoFunctions(element: Dependency): any {
vscode.commands.executeCommand("advpl.monitor.getRpoFunctions");
}
cipherPassword(element: Dependency): any {
const compile = new advplCompile();
let options: vscode.InputBoxOptions = {
prompt: localize('src.advplCompile.passwordQueryText', 'Type in the password:'),
password: true
}
var password = vscode.window.showInputBox(options).then(newPass => {
let environments = this.EnvironmentsConfig;
let config = this.Config;
let obj = <EnvironmentView>element.subject;
if (newPass != undefined) {
compile.runCipherPassword(newPass, cipher => {
cipher = cipher.replace(/\r?\n?/g, '');
// Busca o ambiente relacionado ao serviço + servidor
environments.find(
env => env.environment === obj.environment &&
env.port === obj.parent.servicePort &&
env.server === obj.parent.parent.serverIP
).passwordCipher = cipher; // Altera a senha deste ambiente
// Atualiza a configuração de ambientes
config.update('environments', environments).then(() => {
let message = localize('src.ServerManagementView.passwordChangedSuccess', 'Environment password %ENV_NAME% successfully changed.');
vscode.window.showInformationMessage(message.replace("%ENV_NAME%", obj.environmentLabel));
});
});
}
});
}
delete(element: Dependency): any {
let config = this.Config;
let environments = this.EnvironmentsConfig;
vscode.window.showQuickPick([
localize('src.ServerManagementView.yesText', 'Yes'),
localize('src.ServerManagementView.noText', 'No')
]).then(option => {
// Confirma se o usuário realmente deseja DELETAR o ambiente
if (option === localize('src.ServerManagementView.yesText', 'Yes')) {
if (element.subject instanceof EnvironmentView) {
let obj = <EnvironmentView>element.subject;
// Busca o ambiente relacionado ao serviço + servidor
environments = environments.filter(
env => !(env.environment === obj.environment &&
env.port === obj.parent.servicePort &&
env.server === obj.parent.parent.serverIP)
);
// Atualiza a configuração de ambientes
config.update('environments', environments).then(() => {
vscode.window.showInformationMessage(localize('src.ServerManagementView.environmentText', "Environment ") + element.label + localize('src.ServerManagementView.DELETED', " deleted"));
});
}
}
});
}
}
export class ServerProvider implements vscode.TreeDataProvider<Dependency> {
private _onDidChangeTreeData: vscode.EventEmitter<Dependency | undefined> = new vscode.EventEmitter<Dependency | undefined>();
readonly onDidChangeTreeData: vscode.Event<Dependency | undefined> = this._onDidChangeTreeData.event;
refresh(): void {
this._onDidChangeTreeData.fire(undefined);
}
getTreeItem(element: Dependency): Dependency {
return element;
}
getChildren(element?: Dependency): Thenable<Dependency[]> {
if (element) {
return Promise.resolve(this.getEnvironments(element, element.context));
} else {
return Promise.resolve(this.getEnvironments());
}
}
private getEnvironments(childElement?: Dependency, context?: Context): Dependency[] {
let environments = Array<Dependency>();
let servers = new ServerManagement(true).servers;
let objectParent;
const toDep = (label, description, tooltip, isConnected, context: Context, owner: string, subject: Object): Dependency => {
if (context === Context.Environment || context === Context.EnvironmentConnected) {
return new Dependency(label, description, tooltip, vscode.TreeItemCollapsibleState.None, context, isConnected, owner, subject);
} else {
return new Dependency(label, description, tooltip, vscode.TreeItemCollapsibleState.Expanded, context, isConnected, owner, subject);
}
};
// Caso não tenha sido repassado nenhum elemento, o item é o primeiro Pai
if (childElement) {
if (childElement.context == Context.Server || childElement.context == Context.ServerConnected) {
objectParent = <ServerView>servers.find(server => server.serverName === childElement.label);
objectParent.services.map(
service => environments.push(
toDep(
service.serviceName,
service.servicePort,
service.serviceName.toUpperCase().trim() == service.servicePort.toUpperCase().trim() ? service.serviceName : service.serviceName + " • " + service.servicePort,
service.isConnected,
service.isConnected ? Context.ServiceConnected : Context.Service,
childElement.label,
service
)
)
);
}
else if (childElement.context == Context.Service || childElement.context == Context.ServiceConnected) {
objectParent = <ServiceView>servers.find(
server => server.serverName === childElement.owner
).services.find(
service => service.serviceName === childElement.label
);
objectParent.environments.map(
environment => environments.push(
toDep(
environment.environmentLabel,
environment.environment,
environment.environmentLabel.toUpperCase().trim() == environment.environment.toUpperCase().trim() ? environment.environmentLabel : environment.environmentLabel + " • " + environment.environment,
environment.isConnected,
environment.isConnected ? Context.EnvironmentConnected : Context.Environment,
childElement.label,
environment
)
)
);
}
} else {
servers.map(
server => environments.push(
toDep(server.serverName,
server.serverIP,
server.serverName.toUpperCase().trim() == server.serverIP.toUpperCase().trim() ? server.serverName : server.serverName + " • " + server.serverIP,
server.isConnected,
server.isConnected ? Context.ServerConnected : Context.Server,
"",
server
)
)
);
}
return environments;
}
}
export class Dependency extends vscode.TreeItem {
constructor(
public readonly label: string,
public readonly description: string,
public readonly tooltip: string,
public readonly collapsibleState: vscode.TreeItemCollapsibleState,
public readonly context?: Context,
public readonly isConnected?: boolean,
public readonly owner?: string,
public readonly subject?: Object
) {
super(label, collapsibleState);
}
get contextValue(): string {
return Context[this.context];
}
iconPath = {
light: path.join(__filename, '..', '..', '..', 'images', 'light', this.getIcon()),
dark: path.join(__filename, '..', '..', '..', 'images', 'dark', this.getIcon())
};
private getIcon(): string {
if (this.context === Context.Environment || this.context === Context.EnvironmentConnected) {
return this.isConnected ? "server_green.svg" : "server.svg";
} else {
return this.isConnected ? "dependency_green.svg" : "dependency.svg";
}
}
}