import {Injectable} from "@angular/core"; | |
import {Httpd} from "@ionic-native/httpd"; | |
import {File} from '@ionic-native/file'; | |
import {Platform} from 'ionic-angular'; | |
import {Subscription} from "rxjs/Subscription"; | |
@Injectable() | |
export class IosHttpdService { | |
private readonly serverPort: number = 1210; | |
private platformIsReady: boolean = false; | |
private platformListener: boolean = false; | |
private serverSubscription: Subscription = null; | |
private serverUrl: string = null; | |
constructor(private httpd: Httpd, private file: File, private platform: Platform) { | |
} | |
platformReadyNow(): Promise<boolean> { | |
return new Promise<boolean>((resolve, reject) => { | |
if (this.platform.is('ios')) { | |
this.platformIsReady = true; | |
} | |
resolve(this.platformIsReady); | |
}); | |
} | |
stopAndResumeListener() { | |
if (!this.platformListener) { | |
this.platformListener = true; | |
this.platform.resume.subscribe(() => { | |
this.startServerIfNotRunning(); | |
}); | |
this.platform.pause.subscribe(() => { | |
if (this.serverSubscription !== null) { | |
this.serverSubscription.unsubscribe(); | |
this.serverUrl = null; | |
} | |
}); | |
} | |
} | |
startServer() { | |
this.serverSubscription = this.httpd.startServer({ | |
www_root: this.file.applicationStorageDirectory.replace('file://', '') + '/Library/files/', | |
port: this.serverPort, | |
localhost_only: true | |
}).subscribe((serverUrl) => { | |
this.serverUrl = serverUrl; | |
this.stopAndResumeListener(); | |
}); | |
} | |
startServerIfNotRunning() { | |
if (this.platformIsReady) { | |
this.httpd.getLocalPath().then((path) => { | |
if (path.length < 1) { | |
this.startServer(); | |
} | |
}); | |
} | |
} | |
getServerUrl() { | |
if (this.serverUrl !== null) { | |
return this.serverUrl; | |
} else { // if for any reason we don't get this URL | |
return `http://127.0.0.1:${this.serverPort}/`; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment