mirror of
https://github.com/sakaljurgis/kodi-api-server.git
synced 2026-07-08 20:37:41 +00:00
add initial frame, kodi api module, static serve module, settings, etc.
This commit is contained in:
@@ -0,0 +1,16 @@
|
||||
import { NestMiddleware } from '@nestjs/common';
|
||||
import { NextFunction } from 'express';
|
||||
import { Request, Response } from 'express';
|
||||
import { join } from 'path';
|
||||
|
||||
export class KodiApiUrlRewriteMiddleware implements NestMiddleware {
|
||||
async use(req: Request, res: Response, next: NextFunction) {
|
||||
let path: string;
|
||||
if (req.query && req.query.path) {
|
||||
path = req.query.path as string;
|
||||
}
|
||||
req.url = join('/api/', path);
|
||||
|
||||
next();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Controller, Get, Req } from '@nestjs/common';
|
||||
import RequestRangeBytes from 'src/RequestRange/request-range-bytes.class';
|
||||
import { RequestRange } from 'src/RequestRange/request-range.decorator';
|
||||
import { Request } from 'express';
|
||||
|
||||
@Controller('api')
|
||||
export class KodiApiController {
|
||||
@Get('*')
|
||||
getMainMenu(
|
||||
@RequestRange() requestedRange: RequestRangeBytes,
|
||||
@Req() request: Request,
|
||||
) {
|
||||
return {
|
||||
range: requestedRange,
|
||||
path: request.url,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import {
|
||||
MiddlewareConsumer,
|
||||
Module,
|
||||
NestModule,
|
||||
RequestMethod,
|
||||
} from '@nestjs/common';
|
||||
import { KodiApiController } from './kodi-api.controller';
|
||||
import { KodiApiUrlRewriteMiddleware } from './UrlRewrite/url-rewrite.middleware';
|
||||
|
||||
@Module({
|
||||
controllers: [KodiApiController],
|
||||
providers: [],
|
||||
})
|
||||
export class KodiApiModule implements NestModule {
|
||||
configure(consumer: MiddlewareConsumer) {
|
||||
consumer
|
||||
.apply(KodiApiUrlRewriteMiddleware)
|
||||
.forRoutes({ path: '/api*', method: RequestMethod.ALL });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
export default class RequestRangeBytes {
|
||||
readonly end: number | null;
|
||||
readonly start: number | null;
|
||||
|
||||
constructor(start: number | null, end: number | null) {
|
||||
this.start = start;
|
||||
this.end = end;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
|
||||
import RequestRangeBytes from './request-range-bytes.class';
|
||||
|
||||
export const RequestRange = createParamDecorator(
|
||||
(data: string, ctx: ExecutionContext): RequestRangeBytes | null => {
|
||||
const request = ctx.switchToHttp().getRequest().headers;
|
||||
|
||||
const range = request['range'];
|
||||
if (!range) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const array = range.split(/bytes=([0-9]*)-([0-9]*)/);
|
||||
|
||||
let start = parseInt(array[1]);
|
||||
let end = parseInt(array[2]);
|
||||
|
||||
//both isNaN? -> incorrect request header, response with everything we have
|
||||
start = isNaN(start) ? null : start; //isNaN? -> only num of end bytes requested
|
||||
end = isNaN(end) ? null : end; //isNaN? -> everything from start to the end requested
|
||||
|
||||
return new RequestRangeBytes(start, end);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,13 @@
|
||||
import { NestMiddleware } from '@nestjs/common';
|
||||
import { NextFunction } from 'express';
|
||||
import { Request, Response } from 'express';
|
||||
|
||||
//we dont care about query params for static response
|
||||
export class RemoveQueryUrlRewriteMiddleware implements NestMiddleware {
|
||||
async use(req: Request, res: Response, next: NextFunction) {
|
||||
const urlArray = req.url.split('?');
|
||||
req.url = urlArray[0];
|
||||
|
||||
next();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Next,
|
||||
NotFoundException,
|
||||
Req,
|
||||
Res,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { NextFunction, Request, Response } from 'express';
|
||||
import { readdir, stat } from 'fs/promises';
|
||||
import { join } from 'path';
|
||||
|
||||
@Controller('*')
|
||||
export class StaticController {
|
||||
@Get()
|
||||
async main(
|
||||
@Req() request: Request,
|
||||
@Res() response: Response,
|
||||
@Next() next: NextFunction,
|
||||
) {
|
||||
const relPath = request.url;
|
||||
//relPath = relPath.split('%2E').join('.');
|
||||
//relPath = relPath.split('%2e').join('.');
|
||||
|
||||
if (relPath.indexOf('..') > -1) {
|
||||
throw new UnauthorizedException(
|
||||
'You are not authorized to visit ' + request.url,
|
||||
);
|
||||
}
|
||||
|
||||
const path = join(__dirname, process.env.STATIC_SERVE_FOLDER, relPath);
|
||||
|
||||
const stats: any = await stat(path).catch(() => false);
|
||||
|
||||
if (stats === false) {
|
||||
throw new NotFoundException('Path not found: ' + relPath);
|
||||
}
|
||||
|
||||
if (stats.isDirectory()) {
|
||||
response.status(200).send(await readDirectory(path, relPath));
|
||||
//.send(JSON.stringify(await readDirectory(path, relPath), null, ' '));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
return next();
|
||||
}
|
||||
}
|
||||
|
||||
async function readDirectory(path: string, relPath: string) {
|
||||
let files = await readdir(path);
|
||||
let longestFileLenght = 0;
|
||||
|
||||
files = files.filter((fileName: string) => {
|
||||
const fileIncluded = fileName[0] !== '.';
|
||||
longestFileLenght = fileIncluded ? fileName.length : longestFileLenght;
|
||||
|
||||
return fileIncluded;
|
||||
});
|
||||
|
||||
let result: string;
|
||||
|
||||
if (files.length == 0) {
|
||||
//strPath = strPath.replace(strRootDir, "")
|
||||
result = "<html>\n"
|
||||
result = result + "<head><title>Index of " + relPath + "</title></head>\n"
|
||||
result = result + '<body bgcolor="white">\n'
|
||||
result = result + '<h1>Index of ' + relPath + '</h1><hr><pre><a href="../">../</a>'
|
||||
result = result + "\n</pre><hr></body>"
|
||||
result = result + "</html>"
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// function getFilesInDirHtml(strPath, callback) {
|
||||
// readdir
|
||||
|
||||
// fs.readdir(strPath, function (err, arrItemsAll) {
|
||||
|
||||
// if (err) { callback(err, null) }
|
||||
|
||||
// var arrItemsNotHidden = []
|
||||
// var numLength = 0
|
||||
|
||||
// if (!arrItemsAll) arrItemsAll = []
|
||||
|
||||
// //remove hidden (with dot in front)
|
||||
// //find longest item length
|
||||
// arrItemsAll.forEach(function (strItem) {
|
||||
|
||||
// if (strItem[0] != ".") {
|
||||
|
||||
// arrItemsNotHidden[arrItemsNotHidden.length] = strItem
|
||||
// if (strItem.length > numLength) { numLength = strItem.length }
|
||||
|
||||
// }
|
||||
|
||||
// });
|
||||
|
||||
// numLength = numLength + 10
|
||||
|
||||
// var arrRows = []
|
||||
// arrItemsNotHidden.sort()
|
||||
|
||||
// if (arrItemsNotHidden.length == 0) {
|
||||
// strPath = strPath.replace(strRootDir, "")
|
||||
// var result = "<html>\n"
|
||||
// result = result + "<head><title>Index of " + strPath + "</title></head>\n"
|
||||
// result = result + '<body bgcolor="white">\n'
|
||||
// result = result + '<h1>Index of ' + strPath + '</h1><hr><pre><a href="../">../</a>'
|
||||
// result = result + "\n</pre><hr></body>"
|
||||
// result = result + "</html>"
|
||||
// callback(null, result)
|
||||
// }
|
||||
|
||||
// arrItemsNotHidden.forEach(function (strItem) {
|
||||
|
||||
// fs.stat(strPath + strItem, function (err, stats) {
|
||||
|
||||
// if (err) {
|
||||
// arrRows[arrRows.length] = "error"
|
||||
// return
|
||||
// }
|
||||
|
||||
// var strRow = ""
|
||||
// var strSize = ""
|
||||
// var strDate = ""
|
||||
// var strName = ""
|
||||
|
||||
// //get size and name and date
|
||||
// if (!stats.isDirectory()) {
|
||||
|
||||
// strSize = stats.size.toString()
|
||||
// strSize = space(20 - strSize.length) + strSize
|
||||
|
||||
// //add name
|
||||
// strName = strItem
|
||||
// //get date
|
||||
// var arrDate = stats.birthtime.toUTCString().split(" ")
|
||||
// strDate = space(numLength - strItem.length) + arrDate[1] + "-" + arrDate[2] + "-" + arrDate[3] + " " + arrDate[4]
|
||||
// //strDate = space(numLength - strItem.length) + stats.birthtime.toISOString()
|
||||
|
||||
// } else {
|
||||
// strSize = space(19) + "-"
|
||||
// //add name
|
||||
// strName = strItem + "/"
|
||||
// //get date
|
||||
// var arrDate = stats.birthtime.toUTCString().split(" ")
|
||||
// strDate = space(numLength - strItem.length - 1) + arrDate[1] + "-" + arrDate[2] + "-" + arrDate[3] + " " + arrDate[4]
|
||||
// //strDate = space(numLength - strItem.length - 1) + stats.birthtime.toISOString()
|
||||
// }
|
||||
|
||||
// //combine row
|
||||
// //<a href="Animation/">Animation/</a> 28-Apr-2018 20:56 -
|
||||
// strRow = '<a href="' + strName + '">' + strName + '</a>' + strDate + strSize
|
||||
|
||||
// //strRow = strName + strDate + strSize
|
||||
// arrRows[arrRows.length] = strRow
|
||||
|
||||
// //check if all done, call callback
|
||||
// if (arrRows.length == arrItemsNotHidden.length) {
|
||||
// //callback(null, result)
|
||||
// arrRows.sort()
|
||||
// strPath = strPath.replace(strRootDir, "");
|
||||
// var result = '<html>\n';
|
||||
// result =
|
||||
// result + '<head><title>Index of ' + strPath + '</title></head>\n';
|
||||
// result = result + '<body bgcolor="white">\n'
|
||||
// result =
|
||||
// result +
|
||||
// '<h1>Index of ' +
|
||||
// strPath +
|
||||
// '</h1><hr><pre><a href="../">../</a>\n';
|
||||
// result = result + arrRows.join('\n');
|
||||
// result = result + '\n</pre><hr></body>';
|
||||
// result = result + '</html>';
|
||||
// callback(null, result);
|
||||
// }
|
||||
// });
|
||||
// });
|
||||
// });
|
||||
// }
|
||||
@@ -0,0 +1,27 @@
|
||||
import {
|
||||
MiddlewareConsumer,
|
||||
Module,
|
||||
NestModule,
|
||||
RequestMethod,
|
||||
} from '@nestjs/common';
|
||||
import { ServeStaticModule } from '@nestjs/serve-static';
|
||||
import { join } from 'path';
|
||||
import { StaticController } from './static.controller';
|
||||
import { RemoveQueryUrlRewriteMiddleware } from './UrlRewrite/url-rewrite.middleware';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ServeStaticModule.forRoot({
|
||||
rootPath: join(__dirname, '../../../static'),
|
||||
}),
|
||||
],
|
||||
controllers: [StaticController],
|
||||
providers: [],
|
||||
})
|
||||
export class StaticModule implements NestModule {
|
||||
configure(consumer: MiddlewareConsumer) {
|
||||
consumer
|
||||
.apply(RemoveQueryUrlRewriteMiddleware)
|
||||
.forRoutes({ path: '/*', method: RequestMethod.ALL });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { AppController } from './app.controller';
|
||||
import { AppService } from './app.service';
|
||||
|
||||
describe('AppController', () => {
|
||||
let appController: AppController;
|
||||
|
||||
beforeEach(async () => {
|
||||
const app: TestingModule = await Test.createTestingModule({
|
||||
controllers: [AppController],
|
||||
providers: [AppService],
|
||||
}).compile();
|
||||
|
||||
appController = app.get<AppController>(AppController);
|
||||
});
|
||||
|
||||
describe('root', () => {
|
||||
it('should return "Hello World!"', () => {
|
||||
expect(appController.getHello()).toBe('Hello World!');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import { Controller, Get } from '@nestjs/common';
|
||||
import { AppService } from './app.service';
|
||||
import { RequestRange } from './RequestRange/request-range.decorator';
|
||||
import RequestRangeBytes from './RequestRange/request-range-bytes.class';
|
||||
|
||||
@Controller()
|
||||
export class AppController {
|
||||
constructor(private readonly appService: AppService) {}
|
||||
@Get('api')
|
||||
getElse(@RequestRange() requestedRange: RequestRangeBytes) {
|
||||
return {
|
||||
range: requestedRange,
|
||||
};
|
||||
}
|
||||
|
||||
@Get('*')
|
||||
getHello(): string {
|
||||
return this.appService.getHello();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import {
|
||||
//MiddlewareConsumer,
|
||||
Module,
|
||||
//NestModule,
|
||||
//RequestMethod,
|
||||
} from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
//import { AppService } from './app.service';
|
||||
//import { KodiApiController } from './KodiApi/kodi-api.controller';
|
||||
//import { StaticController } from './Static/static.controller';
|
||||
//import { KodiApiUrlRewriteMiddleware } from './KodiApi/UrlRewrite/url-rewrite.middleware';
|
||||
import { KodiApiModule } from './KodiApi/kodi-api.module';
|
||||
import { StaticModule } from './Static/static.module';
|
||||
|
||||
@Module({
|
||||
imports: [ConfigModule.forRoot(), KodiApiModule, StaticModule],
|
||||
controllers: [],
|
||||
providers: [],
|
||||
})
|
||||
export class AppModule {}
|
||||
// export class AppModule implements NestModule {
|
||||
// configure(consumer: MiddlewareConsumer) {
|
||||
// consumer
|
||||
// .apply(KodiApiUrlRewriteMiddleware)
|
||||
// .forRoutes({ path: '/api*', method: RequestMethod.ALL });
|
||||
// }
|
||||
// }
|
||||
@@ -0,0 +1,8 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
@Injectable()
|
||||
export class AppService {
|
||||
getHello(): string {
|
||||
return 'Hello World!';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { AppModule } from './app.module';
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create(AppModule);
|
||||
await app.listen(process.env.PORT ? parseInt(process.env.PORT) : 3000);
|
||||
}
|
||||
bootstrap();
|
||||
Reference in New Issue
Block a user