Static: extract view file

This commit is contained in:
Jurgis Sakalauskas
2022-12-06 10:40:58 +02:00
parent 9f85c11d2e
commit d20295326f
5 changed files with 94 additions and 43 deletions
+1 -1
View File
@@ -6,7 +6,7 @@ A rewrite attempt from "vanilla" node.js into framework based (Nest.js).
## License ## License
No licence (Nest is MIT) No licence
## Below are left from nest readme ## Below are left from nest readme
+13
View File
@@ -0,0 +1,13 @@
export default class FileDto {
constructor(
readonly name: string,
readonly size: number,
readonly date: Date,
readonly isDirectory: boolean,
) {
this.name = name;
this.size = size;
this.date = date;
this.isDirectory = isDirectory;
}
}
+61
View File
@@ -0,0 +1,61 @@
import FileDto from '../Dto/file.dto';
export default class IndexView {
public render(relPath: string, files: Array<FileDto>): string {
return this.buildHtml(relPath, files);
}
private buildHtml(relPath: string, files: Array<FileDto>): string {
const longestFileLength = this.getLongestFileLength(files);
let result: string;
const resultHtmlStart = `
<html lang="en">
<head><title>Index of ${relPath} </title></head>
<body>
<h1>Index of ${relPath}</h1>
<hr><pre>`;
result = `<a href="../">../</a>`;
for (const file of files) {
result += this.getFileLink(file, longestFileLength);
}
const resultHtmlEnd = `</pre><hr></body></html>`;
return resultHtmlStart + result + resultHtmlEnd;
}
private getFileLink(file: FileDto, longestFileLength: number) {
const arrDate: Array<string> = file.date.toUTCString().split(' ');
const strDate: string =
' '.repeat(longestFileLength - file.name.length) +
`${arrDate[1]}-${arrDate[2]}-${arrDate[3]} ${arrDate[4]}`;
if (file.isDirectory) {
const strSize = ' '.repeat(19) + '-';
return (
'\n' + `<a href="${file.name}/">${file.name}/</a>${strDate + strSize}`
);
}
let strSize = file.size.toString();
strSize = ' '.repeat(20 - strSize.length) + strSize;
return (
'\n' + `<a href="${file.name}">${file.name}</a> ${strDate + strSize}`
);
}
private getLongestFileLength(files: Array<FileDto>) {
let longestFileLength = 0;
for (const file of files) {
longestFileLength =
longestFileLength < file.name.length
? file.name.length
: longestFileLength;
}
longestFileLength += 10;
return longestFileLength;
}
}
+5 -3
View File
@@ -1,6 +1,7 @@
import { Controller, Get, Next, Req, Res } from '@nestjs/common'; import { Controller, Get, Next, Req, Res } from '@nestjs/common';
import { NextFunction, Request, Response } from 'express'; import { NextFunction, Request, Response } from 'express';
import { StaticService } from './static.service'; import { StaticService } from './static.service';
import IndexView from './View/index.view';
@Controller('*') @Controller('*')
export class StaticController { export class StaticController {
@@ -11,11 +12,12 @@ export class StaticController {
@Res() response: Response, @Res() response: Response,
@Next() next: NextFunction, @Next() next: NextFunction,
) { ) {
const dirIndexHtml = await this.staticService.provideDirIndex(request.url); const dirIndex = await this.staticService.provideDirIndex(request.url);
if (dirIndexHtml === null) { if (dirIndex === null) {
return next(); return next();
} }
const view = new IndexView();
return response.status(200).send(dirIndexHtml); return response.status(200).send(view.render(request.url, dirIndex));
} }
} }
+14 -39
View File
@@ -6,10 +6,11 @@ import {
import { readdir, stat } from 'fs/promises'; import { readdir, stat } from 'fs/promises';
import { Stats } from 'fs'; import { Stats } from 'fs';
import { join } from 'path'; import { join } from 'path';
import FileDto from './Dto/file.dto';
@Injectable() @Injectable()
export class StaticService { export class StaticService {
async provideDirIndex(relPath: string): Promise<string> { async provideDirIndex(relPath: string): Promise<Array<FileDto>> {
if (relPath.indexOf('..') > -1) { if (relPath.indexOf('..') > -1) {
throw new UnauthorizedException( throw new UnauthorizedException(
'You are not authorized to visit ' + relPath, 'You are not authorized to visit ' + relPath,
@@ -28,35 +29,17 @@ export class StaticService {
return null; return null;
} }
return this.readDirectory(path, relPath); return this.readDirectory(path);
} }
private async readDirectory(path: string, relPath: string) { private async readDirectory(path: string): Promise<Array<FileDto>> {
let files = await readdir(path); let files = await readdir(path);
let longestFileLength = 0;
files = files.filter((fileName: string) => { files = files.filter((fileName: string) => {
const fileIncluded = fileName[0] !== '.'; return fileName[0] !== '.';
longestFileLength =
fileIncluded && longestFileLength < fileName.length
? fileName.length
: longestFileLength;
return fileIncluded;
}); });
longestFileLength += 10; const filesDtos: Array<FileDto> = [];
let result: string;
const resultHtmlStart = `
<html lang="en">
<head><title>Index of ${relPath} </title></head>
<body>
<h1>Index of ${relPath}</h1>
<hr><pre>`;
result = `<a href="../">../</a>`;
for (const file of files) { for (const file of files) {
const stats: Stats | false = await stat(join(path, file)).catch( const stats: Stats | false = await stat(join(path, file)).catch(
() => false, () => false,
@@ -65,24 +48,16 @@ export class StaticService {
if (stats === false) { if (stats === false) {
continue; continue;
} }
const arrDate: Array<string> = stats.birthtime.toUTCString().split(' '); const fileDto = new FileDto(
const strDate: string = file,
' '.repeat(longestFileLength - file.length) + stats.size,
`${arrDate[1]}-${arrDate[2]}-${arrDate[3]} ${arrDate[4]}`; stats.birthtime,
stats.isDirectory(),
);
if (stats.isDirectory()) { filesDtos.push(fileDto);
const strSize = ' '.repeat(19) + '-';
result += '\n' + `<a href="${file}/">${file}/</a>${strDate + strSize}`;
continue;
}
let strSize = stats.size.toString();
strSize = ' '.repeat(20 - strSize.length) + strSize;
result += '\n' + `<a href="${file}">${file}</a> ${strDate + strSize}`;
} }
const resultHtmlEnd = `</pre><hr></body></html>`; return filesDtos;
return resultHtmlStart + result + resultHtmlEnd;
} }
} }