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.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));
129 // Save config into cookie
131 // Notify subscribers
132 this.confSubject.next(Object.assign({}, this.confStore));
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);
141 // Setup connection with local XDS agent
142 if (this.AgentConnectObs) {
144 this.AgentConnectObs.unsubscribe();
146 this.AgentConnectObs = null;
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)
156 // Remove previous subscriber if existing
157 if (this.stConnectObs) {
159 this.stConnectObs.unsubscribe();
161 this.stConnectObs = null;
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;
175 // Rebuild projects definition from local and remote syncthing
176 this.confStore.projects = [];
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) {
187 type: ProjectType.SYNCTHING, // FIXME support other types
188 remotePrjDef: Object.assign({}, rPrj),
189 localPrjDef: Object.assign({}, lPrj[0]),
191 this.confStore.projects.push(pp);
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.');
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.";
207 this.alert.error(msg);
209 this.alert.error(error);
214 set syncToolURL(url: string) {
215 this.confStore.localSThg.URL = url;
219 set xdsAgentRetry(r: number) {
220 this.confStore.localSThg.retry = r;
221 this.confStore.xdsAgent.retry = r;
225 set xdsAgentUrl(url: string) {
226 this.confStore.xdsAgent.URL = url;
231 set projectsRootDir(p: string) {
232 if (p.charAt(0) === '~') {
233 p = this.confStore.localSThg.tilde + p.substring(1);
235 this.confStore.projectsRootDir = p;
239 getLabelRootName(): string {
240 let id = this.confStore.localSThg.ID;
241 if (!id || id === "") {
244 return id.slice(0, 15);
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);
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;
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];
266 if (this._getProjectIdx(prj.id) !== -1) {
267 this.alert.warning("Project already exist (id=" + prj.id + ")", true);
271 // TODO - support others project types
272 if (prj.type !== ProjectType.SYNCTHING) {
273 this.alert.error('Project type not supported yet (type: ' + prj.type + ')');
277 let sdkPrj: IXDSConfigProject = {
281 hostSyncThingID: this.confStore.localSThg.ID,
282 defaultSdkID: prj.defaultSdkID,
285 // Send config to XDS server
287 this.xdsServerSvr.addProject(sdkPrj)
288 .subscribe(resStRemotePrj => {
289 newPrj.remotePrjDef = resStRemotePrj;
291 // FIXME REWORK local ST config
292 // move logic to server side tunneling-back by WS
294 // Now setup local config
295 let stLocPrj: ISyncThingProject = {
299 remoteSyncThingID: resStRemotePrj.builderSThgID
302 // Set local Syncthing config
303 this.stSvr.addProject(stLocPrj)
304 .subscribe(resStLocalPrj => {
305 newPrj.localPrjDef = resStLocalPrj;
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));
313 this.alert.error("Configuration local ERROR: " + err);
317 this.alert.error("Configuration remote ERROR: " + err);
321 deleteProject(prj: IProject) {
322 let idx = this._getProjectIdx(prj.id);
324 throw new Error("Invalid project id (id=" + prj.id + ")");
326 this.xdsServerSvr.deleteProject(prj.id)
328 this.stSvr.deleteProject(prj.id)
330 this.confStore.projects.splice(idx, 1);
332 this.alert.error("Delete local ERROR: " + err);
335 this.alert.error("Delete remote ERROR: " + err);
339 private _getProjectIdx(id: string): number {
340 return this.confStore.projects.findIndex((item) => item.id === id);