2020-02-14 05:38:05 +07:00
|
|
|
import * as http from "http"
|
|
|
|
import { HttpCode, HttpError } from "../../common/http"
|
|
|
|
import { HttpProvider, HttpProviderOptions, HttpResponse, Route } from "../http"
|
|
|
|
import { ApiHttpProvider } from "./api"
|
|
|
|
|
|
|
|
/**
|
2020-03-03 01:43:02 +07:00
|
|
|
* App/fallback HTTP provider.
|
2020-02-14 05:38:05 +07:00
|
|
|
*/
|
2020-03-03 01:43:02 +07:00
|
|
|
export class AppHttpProvider extends HttpProvider {
|
|
|
|
public constructor(options: HttpProviderOptions, private readonly api: ApiHttpProvider) {
|
2020-02-14 05:38:05 +07:00
|
|
|
super(options)
|
|
|
|
}
|
|
|
|
|
2020-03-03 01:43:02 +07:00
|
|
|
public async handleRequest(route: Route, request: http.IncomingMessage): Promise<HttpResponse> {
|
|
|
|
if (!this.authenticated(request)) {
|
|
|
|
return { redirect: "/login", query: { to: route.fullPath } }
|
2020-02-14 05:38:05 +07:00
|
|
|
}
|
|
|
|
|
|
|
|
// Run an existing app, but if it doesn't exist go ahead and start it.
|
|
|
|
let app = this.api.getRunningApplication(route.base)
|
|
|
|
let sessionId = app && app.sessionId
|
|
|
|
if (!app) {
|
|
|
|
app = (await this.api.installedApplications()).find((a) => a.path === route.base)
|
2020-03-03 01:43:02 +07:00
|
|
|
if (app && app.exec) {
|
2020-02-14 05:38:05 +07:00
|
|
|
sessionId = await this.api.createSession(app)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (sessionId) {
|
2020-02-28 03:56:14 +07:00
|
|
|
return this.getAppRoot(route, (app && app.name) || "", sessionId)
|
2020-02-14 05:38:05 +07:00
|
|
|
}
|
|
|
|
|
2020-03-03 01:43:02 +07:00
|
|
|
throw new HttpError("Application not found", HttpCode.NotFound)
|
2020-02-14 05:38:05 +07:00
|
|
|
}
|
|
|
|
|
2020-02-28 03:56:14 +07:00
|
|
|
public async getAppRoot(route: Route, name: string, sessionId: string): Promise<HttpResponse> {
|
2020-02-14 05:38:05 +07:00
|
|
|
const response = await this.getUtf8Resource(this.rootPath, "src/browser/pages/app.html")
|
2020-02-28 03:56:14 +07:00
|
|
|
response.content = response.content.replace(/{{APP_NAME}}/, name)
|
|
|
|
return this.replaceTemplates(route, response, sessionId)
|
2020-02-14 05:38:05 +07:00
|
|
|
}
|
|
|
|
|
2020-03-03 01:43:02 +07:00
|
|
|
public async handleWebSocket(): Promise<true> {
|
|
|
|
throw new HttpError("Not found", HttpCode.NotFound)
|
2020-02-15 04:57:51 +07:00
|
|
|
}
|
2020-02-14 05:38:05 +07:00
|
|
|
}
|