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';
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';
16 import { XDSServerService, IXDSFolderConfig } from "../services/xdsserver.service";
17 import { XDSAgentService } from "../services/xdsagent.service";
18 import { SyncthingService, ISyncThingProject, ISyncThingStatus } from "../services/syncthing.service";
19 import { AlertService, IAlert } from "../services/alert.service";
20 import { UtilsService } from "../services/utils.service";
22 export enum ProjectType {
27 export var ProjectTypes = [
28 { value: ProjectType.NATIVE_PATHMAP, display: "Path mapping" },
29 { value: ProjectType.SYNCTHING, display: "Cloud Sync" }
32 export interface IProject {
40 serverPrjDef?: IXDSFolderConfig;
43 defaultSdkID?: string;
46 export interface IXDSAgentConfig {
51 export interface ILocalSTConfig {
58 export interface IxdsAgentPackage {
65 export interface IConfig {
67 xdsAgent: IXDSAgentConfig;
68 xdsAgentPackages: IxdsAgentPackage[];
69 projectsRootDir: string;
71 localSThg: ILocalSTConfig;
75 export class ConfigService {
77 public conf: Observable<IConfig>;
79 private confSubject: BehaviorSubject<IConfig>;
80 private confStore: IConfig;
81 private AgentConnectObs = null;
82 private stConnectObs = null;
84 constructor(private _window: Window,
85 private cookie: CookieService,
86 private xdsServerSvr: XDSServerService,
87 private xdsAgentSvr: XDSAgentService,
88 private stSvr: SyncthingService,
89 private alert: AlertService,
90 private utils: UtilsService,
93 this.confSubject = <BehaviorSubject<IConfig>>new BehaviorSubject(this.confStore);
94 this.conf = this.confSubject.asObservable();
96 // force to load projects
102 // Try to retrieve previous config from cookie
103 let cookConf = this.cookie.getObject("xds-config");
104 if (cookConf != null) {
105 this.confStore = <IConfig>cookConf;
107 // Set default config
109 xdsServerURL: this._window.location.origin + '/api/v1',
111 URL: 'http://localhost:8000',
114 xdsAgentPackages: [],
119 URL: "http://localhost:8384",
120 retry: 10, // 10 seconds
126 // Update XDS Agent tarball url
127 this.xdsServerSvr.getXdsAgentInfo().subscribe(nfo => {
128 this.confStore.xdsAgentPackages = [];
129 nfo.tarballs && nfo.tarballs.forEach(el =>
130 this.confStore.xdsAgentPackages.push({
137 this.confSubject.next(Object.assign({}, this.confStore));
140 // Update Project data
141 this.xdsServerSvr.FolderStateChange$.subscribe(prj => {
142 let i = this._getProjectIdx(prj.id);
144 // XXX for now, only isInSync and status may change
145 this.confStore.projects[i].isInSync = prj.isInSync;
146 this.confStore.projects[i].status = prj.status;
147 this.confSubject.next(Object.assign({}, this.confStore));
152 // Save config into cookie
154 // Notify subscribers
155 this.confSubject.next(Object.assign({}, this.confStore));
157 // Don't save projects in cookies (too big!)
158 let cfg = Object.assign({}, this.confStore);
159 delete (cfg.projects);
160 this.cookie.putObject("xds-config", cfg);
164 // Setup connection with local XDS agent
165 if (this.AgentConnectObs) {
167 this.AgentConnectObs.unsubscribe();
169 this.AgentConnectObs = null;
172 let cfg = this.confStore.xdsAgent;
173 this.AgentConnectObs = this.xdsAgentSvr.connect(cfg.retry, cfg.URL)
174 .subscribe((sts) => {
175 //console.log("Agent sts", sts);
176 // FIXME: load projects from local XDS Agent and
177 // not directly from local syncthing
178 this._loadProjectFromLocalST();
181 if (error.indexOf("XDS local Agent not responding") !== -1) {
182 let msg = "<span><strong>" + error + "<br></strong>";
183 msg += "You may need to download and execute XDS-Agent.<br>";
185 let os = this.utils.getOSName(true);
186 let zurl = this.confStore.xdsAgentPackages && this.confStore.xdsAgentPackages.filter(elem => elem.os === os);
187 if (zurl && zurl.length) {
188 msg += " Download XDS-Agent tarball for " + zurl[0].os + " host OS ";
189 msg += "<a class=\"fa fa-download\" href=\"" + zurl[0].url + "\" target=\"_blank\"></a>";
192 this.alert.error(msg);
194 this.alert.error(error);
199 private _loadProjectFromLocalST() {
200 // Remove previous subscriber if existing
201 if (this.stConnectObs) {
203 this.stConnectObs.unsubscribe();
205 this.stConnectObs = null;
208 // FIXME: move this code and all logic about syncthing inside XDS Agent
209 // Setup connection with local SyncThing
210 let retry = this.confStore.localSThg.retry;
211 let url = this.confStore.localSThg.URL;
212 this.stConnectObs = this.stSvr.connect(retry, url).subscribe((sts) => {
213 this.confStore.localSThg.ID = sts.ID;
214 this.confStore.localSThg.tilde = sts.tilde;
215 if (this.confStore.projectsRootDir === "") {
216 this.confStore.projectsRootDir = sts.tilde;
219 // Rebuild projects definition from local and remote syncthing
220 this.confStore.projects = [];
222 this.xdsServerSvr.getProjects().subscribe(remotePrj => {
223 this.stSvr.getProjects().subscribe(localPrj => {
224 remotePrj.forEach(rPrj => {
225 let lPrj = localPrj.filter(item => item.id === rPrj.id);
226 if (lPrj.length > 0 || rPrj.type === ProjectType.NATIVE_PATHMAP) {
227 this._addProject(rPrj, true);
230 this.confSubject.next(Object.assign({}, this.confStore));
231 }), error => this.alert.error('Could not load initial state of local projects.');
232 }), error => this.alert.error('Could not load initial state of remote projects.');
235 if (error.indexOf("Syncthing local daemon not responding") !== -1) {
236 let msg = "<span><strong>" + error + "<br></strong>";
237 msg += "Please check that local XDS-Agent is running.<br>";
239 this.alert.error(msg);
241 this.alert.error(error);
246 set syncToolURL(url: string) {
247 this.confStore.localSThg.URL = url;
251 set xdsAgentRetry(r: number) {
252 this.confStore.localSThg.retry = r;
253 this.confStore.xdsAgent.retry = r;
257 set xdsAgentUrl(url: string) {
258 this.confStore.xdsAgent.URL = url;
263 set projectsRootDir(p: string) {
264 if (p.charAt(0) === '~') {
265 p = this.confStore.localSThg.tilde + p.substring(1);
267 this.confStore.projectsRootDir = p;
271 getLabelRootName(): string {
272 let id = this.confStore.localSThg.ID;
273 if (!id || id === "") {
276 return id.slice(0, 15);
279 addProject(prj: IProject): Observable<IProject> {
280 // Substitute tilde with to user home path
281 let pathCli = prj.pathClient.trim();
282 if (pathCli.charAt(0) === '~') {
283 pathCli = this.confStore.localSThg.tilde + pathCli.substring(1);
285 // Must be a full path (on Linux or Windows)
286 } else if (!((pathCli.charAt(0) === '/') ||
287 (pathCli.charAt(1) === ':' && (pathCli.charAt(2) === '\\' || pathCli.charAt(2) === '/')))) {
288 pathCli = this.confStore.projectsRootDir + '/' + pathCli;
291 let xdsPrj: IXDSFolderConfig = {
293 label: prj.label || "",
296 defaultSdkID: prj.defaultSdkID,
298 serverPath: prj.pathServer,
301 syncThingID: this.confStore.localSThg.ID,
304 // Send config to XDS server
306 return this.xdsServerSvr.addProject(xdsPrj)
307 .flatMap(resStRemotePrj => {
308 xdsPrj = resStRemotePrj;
309 if (xdsPrj.type === ProjectType.SYNCTHING) {
310 // FIXME REWORK local ST config
311 // move logic to server side tunneling-back by WS
312 let stData = xdsPrj.dataCloudSync;
314 // Now setup local config
315 let stLocPrj: ISyncThingProject = {
319 serverSyncThingID: stData.builderSThgID
322 // Set local Syncthing config
323 return this.stSvr.addProject(stLocPrj);
326 return Observable.of(null);
329 .map(resStLocalPrj => {
330 this._addProject(xdsPrj);
335 deleteProject(prj: IProject): Observable<IProject> {
336 let idx = this._getProjectIdx(prj.id);
339 throw new Error("Invalid project id (id=" + prj.id + ")");
341 return this.xdsServerSvr.deleteProject(prj.id)
343 if (prj.type === ProjectType.SYNCTHING) {
344 return this.stSvr.deleteProject(prj.id);
346 return Observable.of(null);
349 this.confStore.projects.splice(idx, 1);
354 syncProject(prj: IProject): Observable<string> {
355 let idx = this._getProjectIdx(prj.id);
357 throw new Error("Invalid project id (id=" + prj.id + ")");
359 return this.xdsServerSvr.syncProject(prj.id);
362 private _getProjectIdx(id: string): number {
363 return this.confStore.projects.findIndex((item) => item.id === id);
366 private _addProject(rPrj: IXDSFolderConfig, noNext?: boolean) {
368 // Convert XDSFolderConfig to IProject
372 pathClient: rPrj.path,
373 pathServer: rPrj.dataPathMap.serverPath,
376 isInSync: rPrj.isInSync,
377 defaultSdkID: rPrj.defaultSdkID,
378 serverPrjDef: Object.assign({}, rPrj), // do a copy
382 this.confStore.projects.push(pp);
384 // sort project array
385 this.confStore.projects.sort((a, b) => {
386 if (a.label < b.label) {
389 if (a.label > b.label) {
395 // FIXME: maybe reduce subject to only .project
396 //this.confSubject.next(Object.assign({}, this.confStore).project);
398 this.confSubject.next(Object.assign({}, this.confStore));