Skip to content

Commit

Permalink
Merge pull request #9 from takejohn/feature/8-astro-page
Browse files Browse the repository at this point in the history
Astroを使って高速化 (#8)
  • Loading branch information
ringo360 authored Apr 2, 2024
2 parents 7ad0250 + ab8e298 commit f173c9e
Show file tree
Hide file tree
Showing 24 changed files with 7,333 additions and 266 deletions.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ So I made this repo. You can use as Simple&Lightweight File Server or Fast&Light
2. install package (`$npm i` or `$yarn install`)
> If you wanna use yarn, you need install yarn. (`$npm i -g yarn`)
3. edit `config.json` (copy `config.json.example` as `config.json`)
4. run server (`$node cdn` or `$pm2 start cdn.js`)
4. build with `$yarn build`
5. run server (`$yarn start` or `$pm2 start yarn -- start`)

Done! default port is 8080. you can view page on `http://localhost:8080`.

Expand Down
100 changes: 45 additions & 55 deletions Routes/api/index.js
Original file line number Diff line number Diff line change
@@ -1,80 +1,56 @@
const fs = require("fs");
const path = require("path");
const express = require("express");
import fs from "fs/promises";
import path from "path";
import express from "express";
let router = express.Router();
const config = require("../../config.js");
const filesDir = path.resolve(__dirname, "../../", config.filesDir);
const prvDir = path.resolve(__dirname, "../../", config.prvDir);
const passport = require('passport');
const passportHttp = require('passport-http');
const fileUpload = require("express-fileupload");
const ipRangeCheck = require("ip-range-check");
import { config, getDirectoryEntries } from "@packages/common";
const filesDir = path.resolve(import.meta.dirname, "../../", config.filesDir);
const prvDir = path.resolve(import.meta.dirname, "../../", config.prvDir);
import passport from 'passport';
import passportHttp from 'passport-http';
import fileUpload from "express-fileupload";
import ipRangeCheck from "ip-range-check";

router.use(fileUpload({

}));
router.use((req, res, next) => {
next();
})

function formatFileSize(bytes) {
const kilobyte = 1024;
const megabyte = kilobyte * 1024;
const gigabyte = megabyte * 1024;
router.use('/', fileUpload());

if (bytes < kilobyte) {
return bytes + ' bytes';
} else if (bytes < megabyte) {
return (bytes / kilobyte).toFixed(2) + ' KB';
} else if (bytes < gigabyte) {
return (bytes / megabyte).toFixed(2) + ' MB';
} else {
return (bytes / gigabyte).toFixed(2) + ' GB';
}
}

router.use((req, res, next) => {
router.use(async (req, res, next) => {
if (req.method != "GET") return next();
if (req.path.startsWith("/api/files")) return next();
let folderPath = path.join(filesDir, decodeURIComponent(req.path).slice(1).split("/").slice(1).join("/"));
try {
let stat = fs.statSync(folderPath)
if (!stat.isDirectory()) throw new Error();
res.json(fs.readdirSync(folderPath).map(file => {
let filePath = path.join(folderPath, file);
let stat = fs.statSync(filePath);
return {
directory: stat.isDirectory(),
file: stat.isFile(),
name: file,
size: stat.size,
sizeStr: formatFileSize(stat.size)
}
}));
res.json(await getDirectoryEntries(decodeURIComponent(req.path).slice(1).split("/").slice(1).join("/")));
} catch (e) {
res.sendStatus(404);
}
})

/**
* @param {fileUpload.UploadedFile} file
* @param {string} uploadDir
*/
function uploadFile(file, uploadDir) {
return new Promise((resolve, reject) => {
return new Promise(async (resolve, reject) => {
let filePath = path.join(uploadDir, file.name);
let extName = path.extname(file.name);
let baseName = path.basename(file.name, extName);
let files = fs.readdirSync(uploadDir);
let files = await fs.readdir(uploadDir);
let newFileName = file.name;
let count = 1;
while (files.includes(newFileName)) {
newFileName = `${baseName}_${count}${extName}`;
count++;
}
filePath = path.join(uploadDir, newFileName);
let stream = fs.createWriteStream(filePath);
stream.write(file.data);
stream.end();
stream.on('finish', () => {
try {
await fs.writeFile(filePath, file.data);
resolve({
path: filePath
});
});
stream.on('error', () => reject());
} catch {
reject();
}
})
}

Expand All @@ -100,11 +76,23 @@ function str2bool(str) {
}
}

async function directoryExists(uploadDir) {
console.log(uploadDir);
try {
await fs.stat(uploadDir);
return true;
} catch {
return false;
}
}

router.post("/upload-discord", async (req, res) => {
let file = req.files.file;
if (!file) return res.status(400);
let uploadDir = str2bool(req.query["private"]) ? prvDir : filesDir;
if (!fs.existsSync(uploadDir)) return res.sendStatus(404);
if (!await directoryExists(uploadDir)) {
return res.sendStatus(404);
}
let check = ipRangeCheck(req.ip, [
"127.0.0.1/8",//ループバックアドレス
"::1/128",//ループバックアドレス(IPv6)
Expand All @@ -131,10 +119,12 @@ router.post("/upload-discord", async (req, res) => {

router.post("/upload", passport.authenticate('basic', { session: false }), async (req, res) => {
if (!req.query.path) return res.status(400);
let file = req.files.file;
let file = req.files?.file;
if (!file) return res.status(400);
let uploadDir = path.join(filesDir, decodeURIComponent(req.query.path));
if (!fs.existsSync(uploadDir)) return res.sendStatus(404);
if (!await directoryExists(uploadDir)) {
return res.sendStatus(404);
}
try {
let result = await uploadFile(file, uploadDir)
res.status(200).send({
Expand All @@ -146,4 +136,4 @@ router.post("/upload", passport.authenticate('basic', { session: false }), async
})


module.exports = router
export default router
34 changes: 15 additions & 19 deletions Routes/index.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,26 @@
const fs = require("fs");
const path = require("path");
const express = require("express");
const swaggerUi = require("swagger-ui-express");
const YAML = require("yaml");
import fs from "fs";
import path from "path";
import express from "express";
import swaggerUi from "swagger-ui-express";
import YAML from "yaml";
const router = express.Router();
const config = require("../config.js");
const send = require("send");
const filesDir = path.resolve(__dirname, "../", config.filesDir);
import { config } from "@packages/common";
import apiRouter from "./api/index.js";
import { handler as astroHandler } from "@packages/astro";
import send from "send";

const swaggerDoc = YAML.parse(fs.readFileSync(path.join(__dirname, "../", "docs", "openapi.yml"), "utf8"));
const swaggerDoc = YAML.parse(fs.readFileSync(path.join(import.meta.dirname, "../", "docs", "openapi.yml"), "utf8"));
router.use("/api-doc", swaggerUi.serve, swaggerUi.setup(swaggerDoc));

router.use("/api", require("./api"))
router.use("/api", apiRouter);

router.get('/webupload', function (req, res) {
res.status(200).send('HELLO')
})

router.use(express.static(path.join(__dirname, "../", "files")))
router.use(express.static(path.resolve(import.meta.dirname, "../", config.filesDir)));

router.use("/static", express.static(path.join(__dirname, "../", "html")))
router.use("/", express.static(path.join(import.meta.dirname, "../", "packages", "astro", "dist", "client")));
router.use(astroHandler);


router.use((req, res, next) => {
if (req.method != "GET") return next();
res.send(fs.readFileSync(path.join(__dirname, "../", "html", "index.html"), "utf8"))
})

module.exports = router
export default router
29 changes: 14 additions & 15 deletions cdn.js
Original file line number Diff line number Diff line change
@@ -1,42 +1,41 @@
const express = require("express");
const path = require("path");
const fs = require("fs");
import express from "express";
import path from "path";
import fs from "fs/promises";
const app = express();
const config = require("./config.js");
import { config } from "@packages/common";
import router from "./Routes/index.js";

app.set('trust proxy', 'uniquelocal')
app.use((req, res, next) => {
app.use(async (req, res, next) => {
const now = new Date();
const clientIP = config.useXffHeader ? req.headers['x-forwarded-for'] : req.ip; // クライアントのIPを取得
const requestInfo = `${req.method} ${decodeURIComponent(req.originalUrl)}`; // リクエストのメソッドとURL
const userAgent = req.headers['user-agent'];
console.log(userAgent)
console.log(`[${now.toLocaleString()}] - Client IP: ${clientIP}, Request: ${requestInfo}`);
let logPath = path.join(__dirname, "access.log");
if (!fs.existsSync(logPath))
fs.writeFileSync(logPath, "CDN Access log\n");
fs.appendFileSync(logPath, `[${now.toLocaleString()}] - Client IP: ${clientIP}, Request: ${requestInfo}, UA: ${userAgent}\n`)
let logPath = path.join(import.meta.dirname, "access.log");
await fs.appendFile(logPath, `[${now.toLocaleString()}] - Client IP: ${clientIP}, Request: ${requestInfo}, UA: ${userAgent}\n`)

next();
});

app.get("/private/:filename", (req, res) => {
app.get("/private/:filename", async (req, res) => {
const filename = req.params.filename;
const filePath = path.resolve(__dirname, 'private', filename);
const filePath = path.resolve(import.meta.dirname, 'private', filename);

// ファイルが存在するかを確認
if (fs.existsSync(filePath)) {
if (await fs.access(filePath, fs.constants.R_OK)) {
res.sendFile(filePath, { root: '/' });
} else {
// ファイルが存在しない場合、404エラーを送信
res.status(404).sendFile(path.join(__dirname, 'assets', '404.png'));
res.status(404).sendFile(path.join(import.meta.dirname, 'assets', '404.png'));
}
});

app.use("/", require("./Routes"))
app.use("/", router)

app.use((req, res, next) => {
res.status(404).sendFile(path.join(__dirname, 'assets', '404.png'));
res.status(404).sendFile(path.join(import.meta.dirname, 'assets', '404.png'));
});

app.use((err, req, res, next) => {
Expand Down
22 changes: 0 additions & 22 deletions html/index.html

This file was deleted.

76 changes: 0 additions & 76 deletions html/index.js

This file was deleted.

Loading

0 comments on commit f173c9e

Please sign in to comment.