Skip to content

Commit

Permalink
Merge pull request #20 from TeamSekai/feature/offset
Browse files Browse the repository at this point in the history
offsetを指定可能に
  • Loading branch information
ringo360 committed Jun 15, 2024
2 parents efc659f + 28c3318 commit 0118308
Show file tree
Hide file tree
Showing 3 changed files with 145 additions and 114 deletions.
243 changes: 130 additions & 113 deletions Routes/api/index.js
Original file line number Diff line number Diff line change
@@ -1,139 +1,156 @@
import fs from "fs/promises";
import path from "path";
import express from "express";
import fs from 'fs/promises';
import path from 'path';
import express from 'express';
import cors from 'cors';
let router = express.Router();
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 { 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";
import fileUpload from 'express-fileupload';
import ipRangeCheck from 'ip-range-check';

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

router.use('/', fileUpload());

router.use(cors());

router.use(async (req, res, next) => {
if (req.method != "GET") return next();
if (req.path.startsWith("/api/files")) return next();
try {
res.json(await getDirectoryEntries(decodeURIComponent(req.path).slice(1).split("/").slice(1).join("/")));
} catch (e) {
res.sendStatus(404);
}
})
if (req.method != 'GET') return next();
if (req.path.startsWith('/api/files')) return next();
const offset = Number(req.query.offset);
try {
let files = await getDirectoryEntries(
decodeURIComponent(req.path).slice(1).split('/').slice(1).join('/')
);
if (!isNaN(offset)) {
files = files.slice(offset, offset + 10);
}
res.json(files);
} catch (e) {
console.log(e);
res.sendStatus(404);
}
});

/**
* @param {fileUpload.UploadedFile} file
* @param {string} uploadDir
* @param {fileUpload.UploadedFile} file
* @param {string} uploadDir
*/
function uploadFile(file, uploadDir) {
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 = 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);
try {
await fs.writeFile(filePath, file.data);
resolve({
path: filePath
});
} catch {
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 = 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);
try {
await fs.writeFile(filePath, file.data);
resolve({
path: filePath,
});
} catch {
reject();
}
});
}

passport.use(new passportHttp.BasicStrategy(
function (username, password, done) {
if (username == config.uploadUserName && password == config.uploadPassword) {
return done(null, true);
} else {
return done(null, false);
}
}
));
passport.use(
new passportHttp.BasicStrategy(function (username, password, done) {
if (
username == config.uploadUserName &&
password == config.uploadPassword
) {
return done(null, true);
} else {
return done(null, false);
}
})
);

function str2bool(str) {
if (typeof str != 'string') {
return Boolean(str);
}
try {
var obj = JSON.parse(str.toLowerCase());
return obj == true;
} catch (e) {
return str != '';
}
if (typeof str != 'string') {
return Boolean(str);
}
try {
var obj = JSON.parse(str.toLowerCase());
return obj == true;
} catch (e) {
return str != '';
}
}

async function directoryExists(uploadDir) {
console.log(uploadDir);
try {
await fs.stat(uploadDir);
return true;
} catch {
return false;
}
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 (!await directoryExists(uploadDir)) {
return res.sendStatus(404);
}
let check = ipRangeCheck(req.ip, [
"127.0.0.1/8",//ループバックアドレス
"::1/128",//ループバックアドレス(IPv6)
"10.0.0.0/8",//プライベートIP
"172.16.0.0/12",//プライベートIP
"192.168.0.0/16",//プライベートIP
"fc00::/7",//プライベートIP(IPv6)
...config.trustedIPs
]);
if (!check) return res.sendStatus(403);
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 (!(await directoryExists(uploadDir))) {
return res.sendStatus(404);
}
let check = ipRangeCheck(req.ip, [
'127.0.0.1/8', //ループバックアドレス
'::1/128', //ループバックアドレス(IPv6)
'10.0.0.0/8', //プライベートIP
'172.16.0.0/12', //プライベートIP
'192.168.0.0/16', //プライベートIP
'fc00::/7', //プライベートIP(IPv6)
...config.trustedIPs,
]);
if (!check) return res.sendStatus(403);

try {
let result = await uploadFile(file, uploadDir)
res.status(200).send({
fileName: path.basename(result.path)
});
} catch {
res.status(500).send({
success: false,
error: "Failed to Upload"
});
}
try {
let result = await uploadFile(file, uploadDir);
res.status(200).send({
fileName: path.basename(result.path),
});
} catch {
res.status(500).send({
success: false,
error: 'Failed to Upload',
});
}
});

router.post("/upload", passport.authenticate('basic', { session: false }), async (req, res) => {
if (!req.query.path) return res.status(400);
let file = req.files?.file;
if (!file) return res.status(400);
let uploadDir = path.join(filesDir, decodeURIComponent(req.query.path));
if (!await directoryExists(uploadDir)) {
return res.sendStatus(404);
}
try {
let result = await uploadFile(file, uploadDir)
res.status(200).send({
fileName: path.basename(result.path)
});
} catch {
res.sendStatus(500);
}
})

router.post(
'/upload',
passport.authenticate('basic', { session: false }),
async (req, res) => {
if (!req.query.path) return res.status(400);
let file = req.files?.file;
if (!file) return res.status(400);
let uploadDir = path.join(filesDir, decodeURIComponent(req.query.path));
if (!(await directoryExists(uploadDir))) {
return res.sendStatus(404);
}
try {
let result = await uploadFile(file, uploadDir);
res.status(200).send({
fileName: path.basename(result.path),
});
} catch {
res.sendStatus(500);
}
}
);

export default router
export default router;
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"@packages/astro": "*",
"@packages/common": "*",
"axios": "^1.5.1",
"cors": "^2.8.5",
"express": "^4.18.2",
"express-fileupload": "^1.5.0",
"form-data": "^4.0.0",
Expand Down
15 changes: 14 additions & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1403,6 +1403,14 @@ cookie@0.6.0, cookie@^0.6.0:
resolved "https://registry.npmjs.org/cookie/-/cookie-0.6.0.tgz"
integrity sha512-U71cyTamuh1CRNCfpGY6to28lxvNwPG4Guz/EVjgf3Jmzv0vlDp1atT9eS5dDjMYHucpHbWns6Lwf3BKz6svdw==

cors@^2.8.5:
version "2.8.5"
resolved "https://registry.yarnpkg.com/cors/-/cors-2.8.5.tgz#eac11da51592dd86b9f06f6e7ac293b3df875d29"
integrity sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==
dependencies:
object-assign "^4"
vary "^1"

cross-spawn@^7.0.3:
version "7.0.3"
resolved "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz"
Expand Down Expand Up @@ -2947,6 +2955,11 @@ npm-run-path@^5.1.0:
dependencies:
path-key "^4.0.0"

object-assign@^4:
version "4.1.1"
resolved "https://registry.yarnpkg.com/object-assign/-/object-assign-4.1.1.tgz#2109adc7965887cfc05cbbd442cac8bfbb360863"
integrity sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==

object-inspect@^1.13.1:
version "1.13.1"
resolved "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.1.tgz"
Expand Down Expand Up @@ -4063,7 +4076,7 @@ utils-merge@1.0.1, utils-merge@^1.0.1:
resolved "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz"
integrity sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==

vary@~1.1.2:
vary@^1, vary@~1.1.2:
version "1.1.2"
resolved "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz"
integrity sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==
Expand Down

0 comments on commit 0118308

Please sign in to comment.