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 var ProjectStatus = {
33 ErrorConfig: "ErrorConfig",
40 export interface IProject {
49 serverPrjDef?: IXDSFolderConfig;
52 defaultSdkID?: string;
55 export interface IXDSAgentConfig {
60 export interface ILocalSTConfig {
67 export interface IxdsAgentPackage {
74 export interface IConfig {
76 xdsAgent: IXDSAgentConfig;
77 xdsAgentPackages: IxdsAgentPackage[];
78 projectsRootDir: string;
80 localSThg: ILocalSTConfig;
84 export class ConfigService {
86 public conf: Observable<IConfig>;
88 private confSubject: BehaviorSubject<IConfig>;
89 private confStore: IConfig;
90 private AgentConnectObs = null;
91 private stConnectObs = null;
93 constructor(private _window: Window,
94 private cookie: CookieService,
95 private xdsServerSvr: XDSServerService,
96 private xdsAgentSvr: XDSAgentService,
97 private stSvr: SyncthingService,
98 private alert: AlertService,
99 private utils: UtilsService,
102 this.confSubject = <BehaviorSubject<IConfig>>new BehaviorSubject(this.confStore);
103 this.conf = this.confSubject.asObservable();
105 // force to load projects
111 // Try to retrieve previous config from cookie
112 let cookConf = this.cookie.getObject("xds-config");
113 if (cookConf != null) {
114 this.confStore = <IConfig>cookConf;
116 // Set default config
118 xdsServerURL: this._window.location.origin + '/api/v1',
120 URL: 'http://localhost:8010',
123 xdsAgentPackages: [],
128 URL: "http://localhost:8384",
129 retry: 10, // 10 seconds
135 // Update XDS Agent tarball url
136 this.xdsServerSvr.getXdsAgentInfo().subscribe(nfo => {
137 this.confStore.xdsAgentPackages = [];
138 nfo.tarballs && nfo.tarballs.forEach(el =>
139 this.confStore.xdsAgentPackages.push({
146 this.confSubject.next(Object.assign({}, this.confStore));
149 // Update Project data
150 this.xdsServerSvr.FolderStateChange$.subscribe(prj => {
151 let i = this._getProjectIdx(prj.id);
153 // XXX for now, only isInSync and status may change
154 this.confStore.projects[i].isInSync = prj.isInSync;
155 this.confStore.projects[i].status = prj.status;
156 this.confStore.projects[i].isUsable = this._isUsableProject(prj);
157 this.confSubject.next(Object.assign({}, this.confStore));
162 // Save config into cookie
164 // Notify subscribers
165 this.confSubject.next(Object.assign({}, this.confStore));
167 // Don't save projects in cookies (too big!)
168 let cfg = Object.assign({}, this.confStore);
169 delete (cfg.projects);
170 this.cookie.putObject("xds-config", cfg);
174 // Setup connection with local XDS agent
175 if (this.AgentConnectObs) {
177 this.AgentConnectObs.unsubscribe();
179 this.AgentConnectObs = null;
182 let cfg = this.confStore.xdsAgent;
183 this.AgentConnectObs = this.xdsAgentSvr.connect(cfg.retry, cfg.URL)
184 .subscribe((sts) => {
185 //console.log("Agent sts", sts);
186 // FIXME: load projects from local XDS Agent and
187 // not directly from local syncthing
188 this._loadProjectFromLocalST();
191 if (error.indexOf("XDS local Agent not responding") !== -1) {
192 let url_OS_Linux = "https://en.opensuse.org/LinuxAutomotive#Installation_AGL_XDS";
193 let url_OS_Other = "https://github.com/iotbzh/xds-agent#how-to-install-on-other-platform";
194 let msg = `<span><strong>` + error + `<br></strong>
195 You may need to install and execute XDS-Agent: <br>
196 On Linux machine <a href="` + url_OS_Linux + `" target="_blank"><span
197 class="fa fa-external-link"></span></a>
199 On Windows machine <a href="` + url_OS_Other + `" target="_blank"><span
200 class="fa fa-external-link"></span></a>
202 On MacOS machine <a href="` + url_OS_Other + `" target="_blank"><span
203 class="fa fa-external-link"></span></a>
205 this.alert.error(msg);
207 this.alert.error(error);
212 private _loadProjectFromLocalST() {
213 // Remove previous subscriber if existing
214 if (this.stConnectObs) {
216 this.stConnectObs.unsubscribe();
218 this.stConnectObs = null;
221 // FIXME: move this code and all logic about syncthing inside XDS Agent
222 // Setup connection with local SyncThing
223 let retry = this.confStore.localSThg.retry;
224 let url = this.confStore.localSThg.URL;
225 this.stConnectObs = this.stSvr.connect(retry, url).subscribe((sts) => {
226 this.confStore.localSThg.ID = sts.ID;
227 this.confStore.localSThg.tilde = sts.tilde;
228 if (this.confStore.projectsRootDir === "") {
229 this.confStore.projectsRootDir = sts.tilde;
232 // Rebuild projects definition from local and remote syncthing
233 this.confStore.projects = [];
235 this.xdsServerSvr.getProjects().subscribe(remotePrj => {
236 this.stSvr.getProjects().subscribe(localPrj => {
237 remotePrj.forEach(rPrj => {
238 let lPrj = localPrj.filter(item => item.id === rPrj.id);
239 if (lPrj.length > 0 || rPrj.type === ProjectType.NATIVE_PATHMAP) {
240 this._addProject(rPrj, true);
243 this.confSubject.next(Object.assign({}, this.confStore));
244 }), error => this.alert.error('Could not load initial state of local projects.');
245 }), error => this.alert.error('Could not load initial state of remote projects.');
248 if (error.indexOf("Syncthing local daemon not responding") !== -1) {
249 let msg = "<span><strong>" + error + "<br></strong>";
250 msg += "Please check that local XDS-Agent is running.<br>";
252 this.alert.error(msg);
254 this.alert.error(error);
259 set syncToolURL(url: string) {
260 this.confStore.localSThg.URL = url;
264 set xdsAgentRetry(r: number) {
265 this.confStore.localSThg.retry = r;
266 this.confStore.xdsAgent.retry = r;
270 set xdsAgentUrl(url: string) {
271 this.confStore.xdsAgent.URL = url;
276 set projectsRootDir(p: string) {
277 if (p.charAt(0) === '~') {
278 p = this.confStore.localSThg.tilde + p.substring(1);
280 this.confStore.projectsRootDir = p;
284 getLabelRootName(): string {
285 let id = this.confStore.localSThg.ID;
286 if (!id || id === "") {
289 return id.slice(0, 15);
292 addProject(prj: IProject): Observable<IProject> {
293 // Substitute tilde with to user home path
294 let pathCli = prj.pathClient.trim();
295 if (pathCli.charAt(0) === '~') {
296 pathCli = this.confStore.localSThg.tilde + pathCli.substring(1);
298 // Must be a full path (on Linux or Windows)
299 } else if (!((pathCli.charAt(0) === '/') ||
300 (pathCli.charAt(1) === ':' && (pathCli.charAt(2) === '\\' || pathCli.charAt(2) === '/')))) {
301 pathCli = this.confStore.projectsRootDir + '/' + pathCli;
304 let xdsPrj: IXDSFolderConfig = {
306 label: prj.label || "",
309 defaultSdkID: prj.defaultSdkID,
311 serverPath: prj.pathServer,
314 syncThingID: this.confStore.localSThg.ID,
317 // Send config to XDS server
319 return this.xdsServerSvr.addProject(xdsPrj)
320 .flatMap(resStRemotePrj => {
321 xdsPrj = resStRemotePrj;
322 if (xdsPrj.type === ProjectType.SYNCTHING) {
323 // FIXME REWORK local ST config
324 // move logic to server side tunneling-back by WS
325 let stData = xdsPrj.dataCloudSync;
327 // Now setup local config
328 let stLocPrj: ISyncThingProject = {
332 serverSyncThingID: stData.builderSThgID
335 // Set local Syncthing config
336 return this.stSvr.addProject(stLocPrj);
339 return Observable.of(null);
342 .map(resStLocalPrj => {
343 this._addProject(xdsPrj);
348 deleteProject(prj: IProject): Observable<IProject> {
349 let idx = this._getProjectIdx(prj.id);
352 throw new Error("Invalid project id (id=" + prj.id + ")");
354 return this.xdsServerSvr.deleteProject(prj.id)
356 if (prj.type === ProjectType.SYNCTHING) {
357 return this.stSvr.deleteProject(prj.id);
359 return Observable.of(null);
362 this.confStore.projects.splice(idx, 1);
367 syncProject(prj: IProject): Observable<string> {
368 let idx = this._getProjectIdx(prj.id);
370 throw new Error("Invalid project id (id=" + prj.id + ")");
372 return this.xdsServerSvr.syncProject(prj.id);
375 private _isUsableProject(p) {
376 return p && p.isInSync &&
377 (p.status === ProjectStatus.Enable) &&
378 (p.status !== ProjectStatus.Syncing);
381 private _getProjectIdx(id: string): number {
382 return this.confStore.projects.findIndex((item) => item.id === id);
385 private _addProject(rPrj: IXDSFolderConfig, noNext?: boolean) {
387 // Convert XDSFolderConfig to IProject
391 pathClient: rPrj.path,
392 pathServer: rPrj.dataPathMap.serverPath,
395 isInSync: rPrj.isInSync,
396 isUsable: this._isUsableProject(rPrj),
397 defaultSdkID: rPrj.defaultSdkID,
398 serverPrjDef: Object.assign({}, rPrj), // do a copy
402 this.confStore.projects.push(pp);
404 // sort project array
405 this.confStore.projects.sort((a, b) => {
406 if (a.label < b.label) {
409 if (a.label > b.label) {
415 // FIXME: maybe reduce subject to only .project
416 //this.confSubject.next(Object.assign({}, this.confStore).project);
418 this.confSubject.next(Object.assign({}, this.confStore));