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, 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";
22 export enum ProjectType {
27 export interface INativeProject {
31 export interface IProject {
36 remotePrjDef?: INativeProject | ISyncThingProject;
40 defaultSdkID?: string;
43 export interface IXDSAgentConfig {
48 export interface ILocalSTConfig {
55 export interface IConfig {
57 xdsAgent: IXDSAgentConfig;
58 xdsAgentZipUrl: string;
59 projectsRootDir: string;
61 localSThg: ILocalSTConfig;
65 export class ConfigService {
67 public conf: Observable<IConfig>;
69 private confSubject: BehaviorSubject<IConfig>;
70 private confStore: IConfig;
71 private AgentConnectObs = null;
72 private stConnectObs = null;
73 private xdsAgentZipUrl = "";
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,
84 this.confSubject = <BehaviorSubject<IConfig>>new BehaviorSubject(this.confStore);
85 this.conf = this.confSubject.asObservable();
87 // force to load projects
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;
100 xdsServerURL: this._window.location.origin + '/api/v1',
102 URL: 'http://localhost:8000',
110 URL: "http://localhost:8384",
111 retry: 10, // 10 seconds
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;
125 // Save config into cookie
127 // Notify subscribers
128 this.confSubject.next(Object.assign({}, this.confStore));
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);
137 // Setup connection with local XDS agent
138 if (this.AgentConnectObs) {
140 this.AgentConnectObs.unsubscribe();
142 this.AgentConnectObs = null;
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)
152 // Remove previous subscriber if existing
153 if (this.stConnectObs) {
155 this.stConnectObs.unsubscribe();
157 this.stConnectObs = null;
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;
171 // Rebuild projects definition from local and remote syncthing
172 this.confStore.projects = [];
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) {
183 type: ProjectType.SYNCTHING, // FIXME support other types
184 remotePrjDef: Object.assign({}, rPrj),
185 localPrjDef: Object.assign({}, lPrj[0]),
187 this.confStore.projects.push(pp);
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.');
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.";
201 this.alert.error(msg);
203 this.alert.error(error);
208 set syncToolURL(url: string) {
209 this.confStore.localSThg.URL = url;
213 set xdsAgentRetry(r: number) {
214 this.confStore.localSThg.retry = r;
215 this.confStore.xdsAgent.retry = r;
219 set xdsAgentUrl(url: string) {
220 this.confStore.xdsAgent.URL = url;
225 set projectsRootDir(p: string) {
226 if (p.charAt(0) === '~') {
227 p = this.confStore.localSThg.tilde + p.substring(1);
229 this.confStore.projectsRootDir = p;
233 getLabelRootName(): string {
234 let id = this.confStore.localSThg.ID;
235 if (!id || id === "") {
238 return id.slice(0, 15);
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);
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;
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];
260 if (this._getProjectIdx(prj.id) !== -1) {
261 this.alert.warning("Project already exist (id=" + prj.id + ")", true);
265 // TODO - support others project types
266 if (prj.type !== ProjectType.SYNCTHING) {
267 this.alert.error('Project type not supported yet (type: ' + prj.type + ')');
271 let sdkPrj: IXDSConfigProject = {
275 hostSyncThingID: this.confStore.localSThg.ID,
276 defaultSdkID: prj.defaultSdkID,
279 // Send config to XDS server
281 this.xdsServerSvr.addProject(sdkPrj)
282 .subscribe(resStRemotePrj => {
283 newPrj.remotePrjDef = resStRemotePrj;
285 // FIXME REWORK local ST config
286 // move logic to server side tunneling-back by WS
288 // Now setup local config
289 let stLocPrj: ISyncThingProject = {
293 remoteSyncThingID: resStRemotePrj.builderSThgID
296 // Set local Syncthing config
297 this.stSvr.addProject(stLocPrj)
298 .subscribe(resStLocalPrj => {
299 newPrj.localPrjDef = resStLocalPrj;
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));
307 this.alert.error("Configuration local ERROR: " + err);
311 this.alert.error("Configuration remote ERROR: " + err);
315 deleteProject(prj: IProject) {
316 let idx = this._getProjectIdx(prj.id);
318 throw new Error("Invalid project id (id=" + prj.id + ")");
320 this.xdsServerSvr.deleteProject(prj.id)
322 this.stSvr.deleteProject(prj.id)
324 this.confStore.projects.splice(idx, 1);
326 this.alert.error("Delete local ERROR: " + err);
329 this.alert.error("Delete remote ERROR: " + err);
333 private _getProjectIdx(id: string): number {
334 return this.confStore.projects.findIndex((item) => item.id === id);