add initial frame, kodi api module, static serve module, settings, etc.

This commit is contained in:
Jurgis Sakalauskas
2022-12-05 09:59:18 +02:00
parent 40e9244e31
commit 1ad27b4e8f
24 changed files with 15285 additions and 0 deletions
+3
View File
@@ -0,0 +1,3 @@
PORT=3000
STATIC_SERVE_FOLDER="../../../static"
LOG_FILE_REQUESTS="../../static/static_log.txt"
+25
View File
@@ -0,0 +1,25 @@
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
tsconfigRootDir : __dirname,
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
],
root: true,
env: {
node: true,
jest: true,
},
ignorePatterns: ['.eslintrc.js'],
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-explicit-any': 'off',
},
};
+36
View File
@@ -0,0 +1,36 @@
# compiled output
/dist
/node_modules
# Logs
logs
*.log
npm-debug.log*
pnpm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# OS
.DS_Store
# Tests
/coverage
/.nyc_output
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
.vscode
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
+4
View File
@@ -0,0 +1,4 @@
{
"singleQuote": true,
"trailingComma": "all"
}
+5
View File
@@ -0,0 +1,5 @@
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src"
}
+14685
View File
File diff suppressed because it is too large Load Diff
+73
View File
@@ -0,0 +1,73 @@
{
"name": "kodi-api-server",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"prebuild": "rimraf dist",
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"@nestjs/common": "^9.0.0",
"@nestjs/config": "^2.2.0",
"@nestjs/core": "^9.0.0",
"@nestjs/platform-express": "^9.0.0",
"@nestjs/serve-static": "^3.0.0",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^7.2.0"
},
"devDependencies": {
"@nestjs/cli": "^9.0.0",
"@nestjs/schematics": "^9.0.0",
"@nestjs/testing": "^9.0.0",
"@types/express": "^4.17.13",
"@types/jest": "28.1.8",
"@types/node": "^16.0.0",
"@types/supertest": "^2.0.11",
"@typescript-eslint/eslint-plugin": "^5.0.0",
"@typescript-eslint/parser": "^5.0.0",
"eslint": "^8.0.1",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^4.0.0",
"jest": "28.1.3",
"prettier": "^2.3.2",
"source-map-support": "^0.5.20",
"supertest": "^6.1.3",
"ts-jest": "28.0.8",
"ts-loader": "^9.2.3",
"ts-node": "^10.0.0",
"tsconfig-paths": "4.1.0",
"typescript": "^4.7.4"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}
@@ -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();
}
}
+18
View File
@@ -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,
};
}
}
+20
View File
@@ -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();
}
}
+184
View File
@@ -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);
// }
// });
// });
// });
// }
+27
View File
@@ -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 });
}
}
+22
View File
@@ -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!');
});
});
});
+20
View File
@@ -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();
}
}
+27
View File
@@ -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 });
// }
// }
+8
View File
@@ -0,0 +1,8 @@
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}
+8
View File
@@ -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();
+24
View File
@@ -0,0 +1,24 @@
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import { AppModule } from './../src/app.module';
describe('AppController (e2e)', () => {
let app: INestApplication;
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
it('/ (GET)', () => {
return request(app.getHttpServer())
.get('/')
.expect(200)
.expect('Hello World!');
});
});
+9
View File
@@ -0,0 +1,9 @@
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
}
}
+4
View File
@@ -0,0 +1,4 @@
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}
+21
View File
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "es2017",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": false,
"noImplicitAny": false,
"strictBindCallApply": false,
"forceConsistentCasingInFileNames": false,
"noFallthroughCasesInSwitch": false
}
}