a04ac130a507a06795cc1c9210abc8667975bfdb
[src/xds/xds-server.git] / webapp / src / app / common / config.service.ts
1 import { Injectable, OnInit } from '@angular/core';
2 import { Http, Headers, RequestOptionsArgs, Response } from '@angular/http';
3 import { Location } from '@angular/common';
4 import { CookieService } from 'ngx-cookie';
5 import { Observable } from 'rxjs/Observable';
6 import { Subscriber } from 'rxjs/Subscriber';
7 import { BehaviorSubject } from 'rxjs/BehaviorSubject';
8
9 // Import RxJs required methods
10 import 'rxjs/add/operator/map';
11 import 'rxjs/add/operator/catch';
12 import 'rxjs/add/observable/throw';
13 import 'rxjs/add/operator/mergeMap';
14
15
16 import { XDSServerService, IXDSConfigProject } from "../common/xdsserver.service";
17 import { XDSAgentService } from "../common/xdsagent.service";
18 import { SyncthingService, ISyncThingProject, ISyncThingStatus } from "../common/syncthing.service";
19 import { AlertService, IAlert } from "../common/alert.service";
20 import { UtilsService } from "../common/utils.service";
21
22 export enum ProjectType {
23     NATIVE = 1,
24     SYNCTHING = 2
25 }
26
27 export interface INativeProject {
28     // TODO
29 }
30
31 export interface IProject {
32     id?: string;
33     label: string;
34     path: string;
35     type: ProjectType;
36     remotePrjDef?: INativeProject | ISyncThingProject;
37     localPrjDef?: any;
38     isExpanded?: boolean;
39     visible?: boolean;
40     defaultSdkID?: string;
41 }
42
43 export interface IXDSAgentConfig {
44     URL: string;
45     retry: number;
46 }
47
48 export interface ILocalSTConfig {
49     ID: string;
50     URL: string;
51     retry: number;
52     tilde: string;
53 }
54
55 export interface IConfig {
56     xdsServerURL: string;
57     xdsAgent: IXDSAgentConfig;
58     xdsAgentZipUrl: string;
59     projectsRootDir: string;
60     projects: IProject[];
61     localSThg: ILocalSTConfig;
62 }
63
64 @Injectable()
65 export class ConfigService {
66
67     public conf: Observable<IConfig>;
68
69     private confSubject: BehaviorSubject<IConfig>;
70     private confStore: IConfig;
71     private AgentConnectObs = null;
72     private stConnectObs = null;
73     private xdsAgentZipUrl = "";
74
75     constructor(private _window: Window,
76         private cookie: CookieService,
77         private xdsServerSvr: XDSServerService,
78         private xdsAgentSvr: XDSAgentService,
79         private stSvr: SyncthingService,
80         private alert: AlertService,
81         private utils: UtilsService,
82     ) {
83         this.load();
84         this.confSubject = <BehaviorSubject<IConfig>>new BehaviorSubject(this.confStore);
85         this.conf = this.confSubject.asObservable();
86
87         // force to load projects
88         this.loadProjects();
89     }
90
91     // Load config
92     load() {
93         // Try to retrieve previous config from cookie
94         let cookConf = this.cookie.getObject("xds-config");
95         if (cookConf != null) {
96             this.confStore = <IConfig>cookConf;
97         } else {
98             // Set default config
99             this.confStore = {
100                 xdsServerURL: this._window.location.origin + '/api/v1',
101                 xdsAgent: {
102                     URL: 'http://localhost:8000',
103                     retry: 10,
104                 },
105                 xdsAgentZipUrl: "",
106                 projectsRootDir: "",
107                 projects: [],
108                 localSThg: {
109                     ID: null,
110                     URL: "http://localhost:8384",
111                     retry: 10,    // 10 seconds
112                     tilde: "",
113                 }
114             };
115         }
116
117         // Update XDS Agent tarball url
118         this.xdsServerSvr.getXdsAgentInfo().subscribe(nfo => {
119             let os = this.utils.getOSName(true);
120             let zurl = nfo.tarballs.filter(elem => elem.os === os);
121             this.confStore.xdsAgentZipUrl = zurl && zurl[0].fileUrl;
122         });
123     }
124
125     // Save config into cookie
126     save() {
127         // Notify subscribers
128         this.confSubject.next(Object.assign({}, this.confStore));
129
130         // Don't save projects in cookies (too big!)
131         let cfg = this.confStore;
132         delete (cfg.projects);
133         this.cookie.putObject("xds-config", cfg);
134     }
135
136     loadProjects() {
137         // Setup connection with local XDS agent
138         if (this.AgentConnectObs) {
139             try {
140                 this.AgentConnectObs.unsubscribe();
141             } catch (err) { }
142             this.AgentConnectObs = null;
143         }
144
145         let cfg = this.confStore.xdsAgent;
146         this.AgentConnectObs = this.xdsAgentSvr.connect(cfg.retry, cfg.URL)
147             .subscribe((sts) => {
148                 console.log("Agent sts", sts);
149             }, error => this.alert.error(error)
150             );
151
152         // Remove previous subscriber if existing
153         if (this.stConnectObs) {
154             try {
155                 this.stConnectObs.unsubscribe();
156             } catch (err) { }
157             this.stConnectObs = null;
158         }
159
160         // FIXME: move this code and all logic about syncthing inside XDS Agent
161         // Setup connection with local SyncThing
162         let retry = this.confStore.localSThg.retry;
163         let url = this.confStore.localSThg.URL;
164         this.stConnectObs = this.stSvr.connect(retry, url).subscribe((sts) => {
165             this.confStore.localSThg.ID = sts.ID;
166             this.confStore.localSThg.tilde = sts.tilde;
167             if (this.confStore.projectsRootDir === "") {
168                 this.confStore.projectsRootDir = sts.tilde;
169             }
170
171             // Rebuild projects definition from local and remote syncthing
172             this.confStore.projects = [];
173
174             this.xdsServerSvr.getProjects().subscribe(remotePrj => {
175                 this.stSvr.getProjects().subscribe(localPrj => {
176                     remotePrj.forEach(rPrj => {
177                         let lPrj = localPrj.filter(item => item.id === rPrj.id);
178                         if (lPrj.length > 0) {
179                             let pp: IProject = {
180                                 id: rPrj.id,
181                                 label: rPrj.label,
182                                 path: rPrj.path,
183                                 type: ProjectType.SYNCTHING,    // FIXME support other types
184                                 remotePrjDef: Object.assign({}, rPrj),
185                                 localPrjDef: Object.assign({}, lPrj[0]),
186                             };
187                             this.confStore.projects.push(pp);
188                         }
189                     });
190                     this.confSubject.next(Object.assign({}, this.confStore));
191                 }), error => this.alert.error('Could not load initial state of local projects.');
192             }), error => this.alert.error('Could not load initial state of remote projects.');
193
194         }, error => {
195             if (error.indexOf("Syncthing local daemon not responding") !== -1) {
196                 let msg = "<span><strong>" + error + "<br></strong>";
197                 msg += "You may need to download and execute XDS-Agent.<br>";
198                 msg += "<a class=\"fa fa-download\" href=\"" + this.confStore.xdsAgentZipUrl + "\" target=\"_blank\"></a>";
199                 msg += " Download XDS-Agent tarball.";
200                 msg += "</span>";
201                 this.alert.error(msg);
202             } else {
203                 this.alert.error(error);
204             }
205         });
206     }
207
208     set syncToolURL(url: string) {
209         this.confStore.localSThg.URL = url;
210         this.save();
211     }
212
213     set xdsAgentRetry(r: number) {
214         this.confStore.localSThg.retry = r;
215         this.confStore.xdsAgent.retry = r;
216         this.save();
217     }
218
219     set xdsAgentUrl(url: string) {
220         this.confStore.xdsAgent.URL = url;
221         this.save();
222     }
223
224
225     set projectsRootDir(p: string) {
226         if (p.charAt(0) === '~') {
227             p = this.confStore.localSThg.tilde + p.substring(1);
228         }
229         this.confStore.projectsRootDir = p;
230         this.save();
231     }
232
233     getLabelRootName(): string {
234         let id = this.confStore.localSThg.ID;
235         if (!id || id === "") {
236             return null;
237         }
238         return id.slice(0, 15);
239     }
240
241     addProject(prj: IProject) {
242         // Substitute tilde with to user home path
243         prj.path = prj.path.trim();
244         if (prj.path.charAt(0) === '~') {
245             prj.path = this.confStore.localSThg.tilde + prj.path.substring(1);
246
247             // Must be a full path (on Linux or Windows)
248         } else if (!((prj.path.charAt(0) === '/') ||
249             (prj.path.charAt(1) === ':' && (prj.path.charAt(2) === '\\' || prj.path.charAt(2) === '/')))) {
250             prj.path = this.confStore.projectsRootDir + '/' + prj.path;
251         }
252
253         if (prj.id == null) {
254             // FIXME - must be done on server side
255             let prefix = this.getLabelRootName() || new Date().toISOString();
256             let splath = prj.path.split('/');
257             prj.id = prefix + "_" + splath[splath.length - 1];
258         }
259
260         if (this._getProjectIdx(prj.id) !== -1) {
261             this.alert.warning("Project already exist (id=" + prj.id + ")", true);
262             return;
263         }
264
265         // TODO - support others project types
266         if (prj.type !== ProjectType.SYNCTHING) {
267             this.alert.error('Project type not supported yet (type: ' + prj.type + ')');
268             return;
269         }
270
271         let sdkPrj: IXDSConfigProject = {
272             id: prj.id,
273             label: prj.label,
274             path: prj.path,
275             hostSyncThingID: this.confStore.localSThg.ID,
276             defaultSdkID: prj.defaultSdkID,
277         };
278
279         // Send config to XDS server
280         let newPrj = prj;
281         this.xdsServerSvr.addProject(sdkPrj)
282             .subscribe(resStRemotePrj => {
283                 newPrj.remotePrjDef = resStRemotePrj;
284
285                 // FIXME REWORK local ST config
286                 //  move logic to server side tunneling-back by WS
287
288                 // Now setup local config
289                 let stLocPrj: ISyncThingProject = {
290                     id: sdkPrj.id,
291                     label: sdkPrj.label,
292                     path: sdkPrj.path,
293                     remoteSyncThingID: resStRemotePrj.builderSThgID
294                 };
295
296                 // Set local Syncthing config
297                 this.stSvr.addProject(stLocPrj)
298                     .subscribe(resStLocalPrj => {
299                         newPrj.localPrjDef = resStLocalPrj;
300
301                         // FIXME: maybe reduce subject to only .project
302                         //this.confSubject.next(Object.assign({}, this.confStore).project);
303                         this.confStore.projects.push(Object.assign({}, newPrj));
304                         this.confSubject.next(Object.assign({}, this.confStore));
305                     },
306                     err => {
307                         this.alert.error("Configuration local ERROR: " + err);
308                     });
309             },
310             err => {
311                 this.alert.error("Configuration remote ERROR: " + err);
312             });
313     }
314
315     deleteProject(prj: IProject) {
316         let idx = this._getProjectIdx(prj.id);
317         if (idx === -1) {
318             throw new Error("Invalid project id (id=" + prj.id + ")");
319         }
320         this.xdsServerSvr.deleteProject(prj.id)
321             .subscribe(res => {
322                 this.stSvr.deleteProject(prj.id)
323                     .subscribe(res => {
324                         this.confStore.projects.splice(idx, 1);
325                     }, err => {
326                         this.alert.error("Delete local ERROR: " + err);
327                     });
328             }, err => {
329                 this.alert.error("Delete remote ERROR: " + err);
330             });
331     }
332
333     private _getProjectIdx(id: string): number {
334         return this.confStore.projects.findIndex((item) => item.id === id);
335     }
336
337 }