Auto detect XDS-Agent tarballs and fix URL.
[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.confStore.xdsAgentZipUrl = "";
119         this.xdsServerSvr.getXdsAgentInfo().subscribe(nfo => {
120             let os = this.utils.getOSName(true);
121             let zurl = nfo.tarballs.filter(elem => elem.os === os);
122             if (zurl && zurl.length) {
123                 this.confStore.xdsAgentZipUrl = zurl[0].fileUrl;
124                 this.confSubject.next(Object.assign({}, this.confStore));
125             }
126         });
127     }
128
129     // Save config into cookie
130     save() {
131         // Notify subscribers
132         this.confSubject.next(Object.assign({}, this.confStore));
133
134         // Don't save projects in cookies (too big!)
135         let cfg = Object.assign({}, this.confStore);
136         delete (cfg.projects);
137         this.cookie.putObject("xds-config", cfg);
138     }
139
140     loadProjects() {
141         // Setup connection with local XDS agent
142         if (this.AgentConnectObs) {
143             try {
144                 this.AgentConnectObs.unsubscribe();
145             } catch (err) { }
146             this.AgentConnectObs = null;
147         }
148
149         let cfg = this.confStore.xdsAgent;
150         this.AgentConnectObs = this.xdsAgentSvr.connect(cfg.retry, cfg.URL)
151             .subscribe((sts) => {
152                 //console.log("Agent sts", sts);
153             }, error => this.alert.error(error)
154             );
155
156         // Remove previous subscriber if existing
157         if (this.stConnectObs) {
158             try {
159                 this.stConnectObs.unsubscribe();
160             } catch (err) { }
161             this.stConnectObs = null;
162         }
163
164         // FIXME: move this code and all logic about syncthing inside XDS Agent
165         // Setup connection with local SyncThing
166         let retry = this.confStore.localSThg.retry;
167         let url = this.confStore.localSThg.URL;
168         this.stConnectObs = this.stSvr.connect(retry, url).subscribe((sts) => {
169             this.confStore.localSThg.ID = sts.ID;
170             this.confStore.localSThg.tilde = sts.tilde;
171             if (this.confStore.projectsRootDir === "") {
172                 this.confStore.projectsRootDir = sts.tilde;
173             }
174
175             // Rebuild projects definition from local and remote syncthing
176             this.confStore.projects = [];
177
178             this.xdsServerSvr.getProjects().subscribe(remotePrj => {
179                 this.stSvr.getProjects().subscribe(localPrj => {
180                     remotePrj.forEach(rPrj => {
181                         let lPrj = localPrj.filter(item => item.id === rPrj.id);
182                         if (lPrj.length > 0) {
183                             let pp: IProject = {
184                                 id: rPrj.id,
185                                 label: rPrj.label,
186                                 path: rPrj.path,
187                                 type: ProjectType.SYNCTHING,    // FIXME support other types
188                                 remotePrjDef: Object.assign({}, rPrj),
189                                 localPrjDef: Object.assign({}, lPrj[0]),
190                             };
191                             this.confStore.projects.push(pp);
192                         }
193                     });
194                     this.confSubject.next(Object.assign({}, this.confStore));
195                 }), error => this.alert.error('Could not load initial state of local projects.');
196             }), error => this.alert.error('Could not load initial state of remote projects.');
197
198         }, error => {
199             if (error.indexOf("Syncthing local daemon not responding") !== -1) {
200                 let msg = "<span><strong>" + error + "<br></strong>";
201                 msg += "You may need to download and execute XDS-Agent.<br>";
202                 if (this.confStore.xdsAgentZipUrl !== "") {
203                     msg += "<a class=\"fa fa-download\" href=\"" + this.confStore.xdsAgentZipUrl + "\" target=\"_blank\"></a>";
204                     msg += " Download XDS-Agent tarball.";
205                 }
206                 msg += "</span>";
207                 this.alert.error(msg);
208             } else {
209                 this.alert.error(error);
210             }
211         });
212     }
213
214     set syncToolURL(url: string) {
215         this.confStore.localSThg.URL = url;
216         this.save();
217     }
218
219     set xdsAgentRetry(r: number) {
220         this.confStore.localSThg.retry = r;
221         this.confStore.xdsAgent.retry = r;
222         this.save();
223     }
224
225     set xdsAgentUrl(url: string) {
226         this.confStore.xdsAgent.URL = url;
227         this.save();
228     }
229
230
231     set projectsRootDir(p: string) {
232         if (p.charAt(0) === '~') {
233             p = this.confStore.localSThg.tilde + p.substring(1);
234         }
235         this.confStore.projectsRootDir = p;
236         this.save();
237     }
238
239     getLabelRootName(): string {
240         let id = this.confStore.localSThg.ID;
241         if (!id || id === "") {
242             return null;
243         }
244         return id.slice(0, 15);
245     }
246
247     addProject(prj: IProject) {
248         // Substitute tilde with to user home path
249         prj.path = prj.path.trim();
250         if (prj.path.charAt(0) === '~') {
251             prj.path = this.confStore.localSThg.tilde + prj.path.substring(1);
252
253             // Must be a full path (on Linux or Windows)
254         } else if (!((prj.path.charAt(0) === '/') ||
255             (prj.path.charAt(1) === ':' && (prj.path.charAt(2) === '\\' || prj.path.charAt(2) === '/')))) {
256             prj.path = this.confStore.projectsRootDir + '/' + prj.path;
257         }
258
259         if (prj.id == null) {
260             // FIXME - must be done on server side
261             let prefix = this.getLabelRootName() || new Date().toISOString();
262             let splath = prj.path.split('/');
263             prj.id = prefix + "_" + splath[splath.length - 1];
264         }
265
266         if (this._getProjectIdx(prj.id) !== -1) {
267             this.alert.warning("Project already exist (id=" + prj.id + ")", true);
268             return;
269         }
270
271         // TODO - support others project types
272         if (prj.type !== ProjectType.SYNCTHING) {
273             this.alert.error('Project type not supported yet (type: ' + prj.type + ')');
274             return;
275         }
276
277         let sdkPrj: IXDSConfigProject = {
278             id: prj.id,
279             label: prj.label,
280             path: prj.path,
281             hostSyncThingID: this.confStore.localSThg.ID,
282             defaultSdkID: prj.defaultSdkID,
283         };
284
285         // Send config to XDS server
286         let newPrj = prj;
287         this.xdsServerSvr.addProject(sdkPrj)
288             .subscribe(resStRemotePrj => {
289                 newPrj.remotePrjDef = resStRemotePrj;
290
291                 // FIXME REWORK local ST config
292                 //  move logic to server side tunneling-back by WS
293
294                 // Now setup local config
295                 let stLocPrj: ISyncThingProject = {
296                     id: sdkPrj.id,
297                     label: sdkPrj.label,
298                     path: sdkPrj.path,
299                     remoteSyncThingID: resStRemotePrj.builderSThgID
300                 };
301
302                 // Set local Syncthing config
303                 this.stSvr.addProject(stLocPrj)
304                     .subscribe(resStLocalPrj => {
305                         newPrj.localPrjDef = resStLocalPrj;
306
307                         // FIXME: maybe reduce subject to only .project
308                         //this.confSubject.next(Object.assign({}, this.confStore).project);
309                         this.confStore.projects.push(Object.assign({}, newPrj));
310                         this.confSubject.next(Object.assign({}, this.confStore));
311                     },
312                     err => {
313                         this.alert.error("Configuration local ERROR: " + err);
314                     });
315             },
316             err => {
317                 this.alert.error("Configuration remote ERROR: " + err);
318             });
319     }
320
321     deleteProject(prj: IProject) {
322         let idx = this._getProjectIdx(prj.id);
323         if (idx === -1) {
324             throw new Error("Invalid project id (id=" + prj.id + ")");
325         }
326         this.xdsServerSvr.deleteProject(prj.id)
327             .subscribe(res => {
328                 this.stSvr.deleteProject(prj.id)
329                     .subscribe(res => {
330                         this.confStore.projects.splice(idx, 1);
331                     }, err => {
332                         this.alert.error("Delete local ERROR: " + err);
333                     });
334             }, err => {
335                 this.alert.error("Delete remote ERROR: " + err);
336             });
337     }
338
339     private _getProjectIdx(id: string): number {
340         return this.confStore.projects.findIndex((item) => item.id === id);
341     }
342
343 }