1
0
mirror of https://github.com/stonith404/pingvin-share.git synced 2024-10-02 09:30:10 +02:00

Merge branch 'development' into main

This commit is contained in:
Elias Schneider 2022-10-13 23:57:55 +02:00
commit c27c3dae9c
36 changed files with 6108 additions and 371 deletions

View File

@ -0,0 +1,21 @@
name: Backend system tests
on:
pull_request:
branches:
- main
jobs:
integration-tests:
runs-on: ubuntu-latest
container: node:18-alpine
steps:
- uses: actions/checkout@v2
with:
path: backend
- name: Install Dependencies
run: npm install
- name: Create .env file
run: mv .env.example .env
- name: Run Server and Test with Newman
run: npm run test:system

View File

@ -4,8 +4,8 @@ on:
push: push:
branches: main branches: main
paths: paths:
- 'frontend/**' - "frontend/**"
- 'backend/**' - "backend/**"
jobs: jobs:
build: build:
@ -23,4 +23,4 @@ jobs:
run: | run: |
docker buildx build --push \ docker buildx build --push \
--tag stonith404/pingvin-share:latest \ --tag stonith404/pingvin-share:latest \
--platform linux/amd64,linux/arm64 . --platform linux/amd64,linux/arm64,linux/arm/v7 .

View File

@ -1,18 +1,6 @@
{ {
"env": { "extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended"],
"browser": true, "parser": "@typescript-eslint/parser",
"es2021": true "plugins": ["@typescript-eslint"],
}, "root": true
"overrides": [
],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module"
},
"plugins": [
"@typescript-eslint"
],
"rules": {
}
} }

4331
backend/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -6,7 +6,8 @@
"dev": "dotenv -- nest start --watch", "dev": "dotenv -- nest start --watch",
"prod": "npx prisma migrate deploy && dotenv node dist/main", "prod": "npx prisma migrate deploy && dotenv node dist/main",
"lint": "eslint 'src/**/*.ts'", "lint": "eslint 'src/**/*.ts'",
"format": "prettier --write 'src/**/*.ts'" "format": "prettier --write 'src/**/*.ts'",
"test:system": "npx prisma migrate reset -f && pm2 start 'nest start' && sleep 5 && newman run ./test/system/newman-system-tests.json ; pm2 delete 0"
}, },
"dependencies": { "dependencies": {
"@nestjs/common": "^9.1.2", "@nestjs/common": "^9.1.2",
@ -21,6 +22,7 @@
"argon2": "^0.29.1", "argon2": "^0.29.1",
"class-transformer": "^0.5.1", "class-transformer": "^0.5.1",
"class-validator": "^0.13.2", "class-validator": "^0.13.2",
"content-disposition": "^0.5.4",
"mime-types": "^2.1.35", "mime-types": "^2.1.35",
"moment": "^2.29.4", "moment": "^2.29.4",
"multer": "^1.4.5-lts.1", "multer": "^1.4.5-lts.1",
@ -42,19 +44,21 @@
"@types/node": "^18.7.23", "@types/node": "^18.7.23",
"@types/passport-jwt": "^3.0.7", "@types/passport-jwt": "^3.0.7",
"@types/supertest": "^2.0.12", "@types/supertest": "^2.0.12",
"@typescript-eslint/eslint-plugin": "^5.39.0", "@typescript-eslint/eslint-plugin": "^5.40.0",
"@typescript-eslint/parser": "^5.39.0", "@typescript-eslint/parser": "^5.40.0",
"cross-env": "^7.0.3", "cross-env": "^7.0.3",
"dotenv-cli": "^6.0.0", "dotenv-cli": "^6.0.0",
"eslint": "^8.0.1", "eslint": "^8.25.0",
"eslint-config-prettier": "^8.3.0", "eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^4.0.0", "eslint-plugin-prettier": "^4.0.0",
"newman": "^5.3.2",
"pm2": "^5.2.2",
"prettier": "^2.7.1", "prettier": "^2.7.1",
"prisma": "^4.4.0", "prisma": "^4.4.0",
"source-map-support": "^0.5.21", "source-map-support": "^0.5.21",
"ts-loader": "^9.4.1", "ts-loader": "^9.4.1",
"ts-node": "^10.9.1", "ts-node": "^10.9.1",
"tsconfig-paths": "4.1.0", "tsconfig-paths": "4.1.0",
"typescript": "^4.3.5" "typescript": "^4.8.4"
} }
} }

View File

@ -0,0 +1,14 @@
-- RedefineTables
PRAGMA foreign_keys=OFF;
CREATE TABLE "new_RefreshToken" (
"token" TEXT NOT NULL PRIMARY KEY,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
"expiresAt" DATETIME NOT NULL,
"userId" TEXT NOT NULL,
CONSTRAINT "RefreshToken_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE CASCADE ON UPDATE CASCADE
);
INSERT INTO "new_RefreshToken" ("createdAt", "expiresAt", "token", "userId") SELECT "createdAt", "expiresAt", "token", "userId" FROM "RefreshToken";
DROP TABLE "RefreshToken";
ALTER TABLE "new_RefreshToken" RENAME TO "RefreshToken";
PRAGMA foreign_key_check;
PRAGMA foreign_keys=ON;

View File

@ -28,7 +28,7 @@ model RefreshToken {
expiresAt DateTime expiresAt DateTime
userId String userId String
user User @relation(fields: [userId], references: [id]) user User @relation(fields: [userId], references: [id], onDelete: Cascade)
} }
model Share { model Share {

View File

@ -27,6 +27,7 @@ export class AuthController {
} }
@Post("signIn") @Post("signIn")
@HttpCode(200)
signIn(@Body() dto: AuthSignInDTO) { signIn(@Body() dto: AuthSignInDTO) {
return this.authService.signIn(dto); return this.authService.signIn(dto);
} }

View File

@ -1,4 +1,3 @@
import { PickType } from "@nestjs/swagger";
import { UserDTO } from "src/user/dto/user.dto"; import { UserDTO } from "src/user/dto/user.dto";
export class AuthRegisterDTO extends UserDTO {} export class AuthRegisterDTO extends UserDTO {}

View File

@ -1,4 +1,4 @@
import { IsNotEmpty, IsString } from "class-validator"; import { IsNotEmpty } from "class-validator";
export class RefreshAccessTokenDTO { export class RefreshAccessTokenDTO {
@IsNotEmpty() @IsNotEmpty()

View File

@ -14,7 +14,7 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
}); });
} }
async validate(payload: any) { async validate(payload: { sub: string }) {
const user: User = await this.prisma.user.findUnique({ const user: User = await this.prisma.user.findUnique({
where: { id: payload.sub }, where: { id: payload.sub },
}); });

View File

@ -11,9 +11,6 @@ export class FileDTO {
@Expose() @Expose()
size: string; size: string;
@Expose()
url: boolean;
share: ShareDTO; share: ShareDTO;
from(partial: Partial<FileDTO>) { from(partial: Partial<FileDTO>) {

View File

@ -11,6 +11,7 @@ import {
UseInterceptors, UseInterceptors,
} from "@nestjs/common"; } from "@nestjs/common";
import { FileInterceptor } from "@nestjs/platform-express"; import { FileInterceptor } from "@nestjs/platform-express";
import * as contentDisposition from "content-disposition";
import { Response } from "express"; import { Response } from "express";
import { JwtGuard } from "src/auth/guard/jwt.guard"; import { JwtGuard } from "src/auth/guard/jwt.guard";
import { FileDownloadGuard } from "src/file/guard/fileDownload.guard"; import { FileDownloadGuard } from "src/file/guard/fileDownload.guard";
@ -41,6 +42,10 @@ export class FileController {
file: Express.Multer.File, file: Express.Multer.File,
@Param("shareId") shareId: string @Param("shareId") shareId: string
) { ) {
// Fixes file names with special characters
file.originalname = Buffer.from(file.originalname, "latin1").toString(
"utf8"
);
return new ShareDTO().from(await this.fileService.create(file, shareId)); return new ShareDTO().from(await this.fileService.create(file, shareId));
} }
@ -98,7 +103,7 @@ export class FileController {
res.set({ res.set({
"Content-Type": file.metaData.mimeType, "Content-Type": file.metaData.mimeType,
"Content-Length": file.metaData.size, "Content-Length": file.metaData.size,
"Content-Disposition": `attachment ; filename="${file.metaData.name}"`, "Content-Disposition": contentDisposition(file.metaData.name),
}); });
return new StreamableFile(file.file); return new StreamableFile(file.file);

View File

@ -1,7 +1,6 @@
import { Module } from "@nestjs/common"; import { Module } from "@nestjs/common";
import { JwtModule } from "@nestjs/jwt"; import { JwtModule } from "@nestjs/jwt";
import { ShareModule } from "src/share/share.module"; import { ShareModule } from "src/share/share.module";
import { ShareService } from "src/share/share.service";
import { FileController } from "./file.controller"; import { FileController } from "./file.controller";
import { FileService } from "./file.service"; import { FileService } from "./file.service";

View File

@ -100,12 +100,12 @@ export class FileService {
); );
} }
verifyFileDownloadToken(shareId: string, fileId: string, token: string) { verifyFileDownloadToken(shareId: string, token: string) {
try { try {
const claims = this.jwtService.verify(token, { const claims = this.jwtService.verify(token, {
secret: this.config.get("JWT_SECRET"), secret: this.config.get("JWT_SECRET"),
}); });
return claims.shareId == shareId && claims.fileId == fileId; return claims.shareId == shareId;
} catch { } catch {
return false; return false;
} }

View File

@ -1,23 +1,17 @@
import { CanActivate, ExecutionContext, Injectable } from "@nestjs/common"; import { CanActivate, ExecutionContext, Injectable } from "@nestjs/common";
import { Reflector } from "@nestjs/core";
import { Request } from "express"; import { Request } from "express";
import { FileService } from "src/file/file.service"; import { FileService } from "src/file/file.service";
import { PrismaService } from "src/prisma/prisma.service";
@Injectable() @Injectable()
export class FileDownloadGuard implements CanActivate { export class FileDownloadGuard implements CanActivate {
constructor( constructor(private fileService: FileService) {}
private reflector: Reflector,
private fileService: FileService,
private prisma: PrismaService
) {}
async canActivate(context: ExecutionContext) { async canActivate(context: ExecutionContext) {
const request: Request = context.switchToHttp().getRequest(); const request: Request = context.switchToHttp().getRequest();
const token = request.query.token as string; const token = request.query.token as string;
const { shareId, fileId } = request.params; const { shareId } = request.params;
return this.fileService.verifyFileDownloadToken(shareId, fileId, token); return this.fileService.verifyFileDownloadToken(shareId, token);
} }
} }

View File

@ -1,5 +1,5 @@
import { Type } from "class-transformer"; import { Type } from "class-transformer";
import { IsString, Matches, ValidateNested } from "class-validator"; import { IsString, Length, Matches, ValidateNested } from "class-validator";
import { ShareSecurityDTO } from "./shareSecurity.dto"; import { ShareSecurityDTO } from "./shareSecurity.dto";
export class CreateShareDTO { export class CreateShareDTO {
@ -7,6 +7,7 @@ export class CreateShareDTO {
@Matches("^[a-zA-Z0-9_-]*$", undefined, { @Matches("^[a-zA-Z0-9_-]*$", undefined, {
message: "ID only can contain letters, numbers, underscores and hyphens", message: "ID only can contain letters, numbers, underscores and hyphens",
}) })
@Length(3, 50)
id: string; id: string;
@IsString() @IsString()

View File

@ -1,6 +1,3 @@
import { IsNotEmpty } from "class-validator";
export class SharePasswordDto { export class SharePasswordDto {
@IsNotEmpty()
password: string; password: string;
} }

View File

@ -1,16 +1,16 @@
import { CanActivate, ExecutionContext, Injectable } from "@nestjs/common"; import {
import { Reflector } from "@nestjs/core"; CanActivate,
ExecutionContext,
Injectable,
NotFoundException,
} from "@nestjs/common";
import { User } from "@prisma/client"; import { User } from "@prisma/client";
import { Request } from "express"; import { Request } from "express";
import { ExtractJwt } from "passport-jwt";
import { PrismaService } from "src/prisma/prisma.service"; import { PrismaService } from "src/prisma/prisma.service";
import { ShareService } from "src/share/share.service";
@Injectable() @Injectable()
export class ShareOwnerGuard implements CanActivate { export class ShareOwnerGuard implements CanActivate {
constructor( constructor(private prisma: PrismaService) {}
private prisma: PrismaService
) {}
async canActivate(context: ExecutionContext) { async canActivate(context: ExecutionContext) {
const request: Request = context.switchToHttp().getRequest(); const request: Request = context.switchToHttp().getRequest();
@ -26,7 +26,7 @@ export class ShareOwnerGuard implements CanActivate {
include: { security: true }, include: { security: true },
}); });
if (!share) throw new NotFoundException("Share not found");
return share.creatorId == (request.user as User).id; return share.creatorId == (request.user as User).id;
} }

View File

@ -21,6 +21,7 @@ export class ShareSecurityGuard implements CanActivate {
async canActivate(context: ExecutionContext) { async canActivate(context: ExecutionContext) {
const request: Request = context.switchToHttp().getRequest(); const request: Request = context.switchToHttp().getRequest();
const shareToken = request.get("X-Share-Token");
const shareId = Object.prototype.hasOwnProperty.call( const shareId = Object.prototype.hasOwnProperty.call(
request.params, request.params,
"shareId" "shareId"
@ -36,19 +37,15 @@ export class ShareSecurityGuard implements CanActivate {
if (!share || moment().isAfter(share.expiration)) if (!share || moment().isAfter(share.expiration))
throw new NotFoundException("Share not found"); throw new NotFoundException("Share not found");
if (!share.security) return true; if (share.security?.password && !shareToken)
if (share.security.maxViews && share.security.maxViews <= share.views)
throw new ForbiddenException(
"Maximum views exceeded",
"share_max_views_exceeded"
);
if (
!this.shareService.verifyShareToken(shareId, request.get("X-Share-Token"))
)
throw new ForbiddenException( throw new ForbiddenException(
"This share is password protected", "This share is password protected",
"share_password_required"
);
if (!this.shareService.verifyShareToken(shareId, shareToken))
throw new ForbiddenException(
"Share token required",
"share_token_required" "share_token_required"
); );

View File

@ -0,0 +1,47 @@
import {
CanActivate,
ExecutionContext,
ForbiddenException,
Injectable,
NotFoundException,
} from "@nestjs/common";
import { Reflector } from "@nestjs/core";
import { Request } from "express";
import * as moment from "moment";
import { PrismaService } from "src/prisma/prisma.service";
import { ShareService } from "src/share/share.service";
@Injectable()
export class ShareTokenSecurity implements CanActivate {
constructor(
private reflector: Reflector,
private shareService: ShareService,
private prisma: PrismaService
) {}
async canActivate(context: ExecutionContext) {
const request: Request = context.switchToHttp().getRequest();
const shareId = Object.prototype.hasOwnProperty.call(
request.params,
"shareId"
)
? request.params.shareId
: request.params.id;
const share = await this.prisma.share.findUnique({
where: { id: shareId },
include: { security: true },
});
if (!share || moment().isAfter(share.expiration))
throw new NotFoundException("Share not found");
if (share.security?.maxViews && share.security.maxViews <= share.views)
throw new ForbiddenException(
"Maximum views exceeded",
"share_max_views_exceeded"
);
return true;
}
}

View File

@ -18,6 +18,7 @@ import { ShareMetaDataDTO } from "./dto/shareMetaData.dto";
import { SharePasswordDto } from "./dto/sharePassword.dto"; import { SharePasswordDto } from "./dto/sharePassword.dto";
import { ShareOwnerGuard } from "./guard/shareOwner.guard"; import { ShareOwnerGuard } from "./guard/shareOwner.guard";
import { ShareSecurityGuard } from "./guard/shareSecurity.guard"; import { ShareSecurityGuard } from "./guard/shareSecurity.guard";
import { ShareTokenSecurity } from "./guard/shareTokenSecurity.guard";
import { ShareService } from "./share.service"; import { ShareService } from "./share.service";
@Controller("shares") @Controller("shares")
@ -68,11 +69,10 @@ export class ShareController {
return this.shareService.isShareIdAvailable(id); return this.shareService.isShareIdAvailable(id);
} }
@Post(":id/password") @HttpCode(200)
async exchangeSharePasswordWithToken( @UseGuards(ShareTokenSecurity)
@Param("id") id: string, @Post(":id/token")
@Body() body: SharePasswordDto async getShareToken(@Param("id") id: string, @Body() body: SharePasswordDto) {
) { return this.shareService.getShareToken(id, body.password);
return this.shareService.exchangeSharePasswordWithToken(id, body.password);
} }
} }

View File

@ -76,6 +76,9 @@ export class ShareService {
} }
async complete(id: string) { async complete(id: string) {
if (await this.isShareCompleted(id))
throw new BadRequestException("Share already completed");
const moreThanOneFileInShare = const moreThanOneFileInShare =
(await this.prisma.file.findMany({ where: { shareId: id } })).length != 0; (await this.prisma.file.findMany({ where: { shareId: id } })).length != 0;
@ -101,7 +104,7 @@ export class ShareService {
} }
async get(id: string) { async get(id: string) {
let share: any = await this.prisma.share.findUnique({ const share : any = await this.prisma.share.findUnique({
where: { id }, where: { id },
include: { include: {
files: true, files: true,
@ -112,13 +115,6 @@ export class ShareService {
if (!share || !share.uploadLocked) if (!share || !share.uploadLocked)
throw new NotFoundException("Share not found"); throw new NotFoundException("Share not found");
share.files = share.files.map((file) => {
file["url"] = `http://localhost:8080/file/${file.id}`;
return file;
});
await this.increaseViewCount(share);
return share; return share;
} }
@ -160,27 +156,36 @@ export class ShareService {
}); });
} }
async exchangeSharePasswordWithToken(shareId: string, password: string) { async getShareToken(shareId: string, password: string) {
const sharePassword = ( const share = await this.prisma.share.findFirst({
await this.prisma.shareSecurity.findFirst({ where: { id: shareId },
where: { share: { id: shareId } }, include: {
}) security: true,
).password; },
});
if (!(await argon.verify(sharePassword, password))) if (
share?.security?.password &&
!(await argon.verify(share.security.password, password))
)
throw new ForbiddenException("Wrong password"); throw new ForbiddenException("Wrong password");
const token = this.generateShareToken(shareId); const token = await this.generateShareToken(shareId);
await this.increaseViewCount(share);
return { token }; return { token };
} }
generateShareToken(shareId: string) { async generateShareToken(shareId: string) {
const { expiration } = await this.prisma.share.findUnique({
where: { id: shareId },
});
console.log(moment(expiration).diff(new Date(), "seconds"));
return this.jwtService.sign( return this.jwtService.sign(
{ {
shareId, shareId,
}, },
{ {
expiresIn: "1h", expiresIn: moment(expiration).diff(new Date(), "seconds") + "s",
secret: this.config.get("JWT_SECRET"), secret: this.config.get("JWT_SECRET"),
} }
); );

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1 @@
This is a test filed used for uploading in the system test.

View File

@ -152,14 +152,12 @@ const NavBar = () => {
const { classes, cx } = useStyles(); const { classes, cx } = useStyles();
const items = ( const items = (
<> <>
{(user ? authenticatedLinks : unauthenticatedLinks).map((link) => { {(user ? authenticatedLinks : unauthenticatedLinks).map((link, i) => {
if (link.component) { if (link.component) {
return ( return (
<> <Box pl={5} py={15} key={i}>
<Box pl={5} py={15}> {link.component}
{link.component} </Box>
</Box>
</>
); );
} }
return ( return (

View File

@ -31,7 +31,7 @@ const CreateUploadModalBody = ({
.string() .string()
.required() .required()
.min(3) .min(3)
.max(100) .max(50)
.matches(new RegExp("^[a-zA-Z0-9_-]*$"), { .matches(new RegExp("^[a-zA-Z0-9_-]*$"), {
message: "Can only contain letters, numbers, underscores and hyphens", message: "Can only contain letters, numbers, underscores and hyphens",
}), }),

View File

@ -25,7 +25,7 @@ const DownloadAllButton = ({ shareId }: { shareId: string }) => {
setIsZipReady(share.isZipReady); setIsZipReady(share.isZipReady);
if (share.isZipReady) clearInterval(timer); if (share.isZipReady) clearInterval(timer);
}) })
.catch(() => {}); .catch(() => clearInterval(timer));
}, 5000); }, 5000);
return () => { return () => {
clearInterval(timer); clearInterval(timer);

View File

@ -1,15 +1,9 @@
import { import { Button, Center, createStyles, Group, Text } from "@mantine/core";
Button,
Center,
createStyles,
Group,
Text,
useMantineTheme,
} from "@mantine/core";
import { Dropzone as MantineDropzone } from "@mantine/dropzone"; import { Dropzone as MantineDropzone } from "@mantine/dropzone";
import getConfig from "next/config"; import getConfig from "next/config";
import { Dispatch, ForwardedRef, SetStateAction, useRef } from "react"; import { Dispatch, ForwardedRef, SetStateAction, useRef } from "react";
import { CloudUpload, Upload } from "tabler-icons-react"; import { CloudUpload, Upload } from "tabler-icons-react";
import { FileUpload } from "../../types/File.type";
import { byteStringToHumanSizeString } from "../../utils/math/byteStringToHumanSizeString.util"; import { byteStringToHumanSizeString } from "../../utils/math/byteStringToHumanSizeString.util";
import toast from "../../utils/toast.util"; import toast from "../../utils/toast.util";
@ -44,9 +38,8 @@ const Dropzone = ({
setFiles, setFiles,
}: { }: {
isUploading: boolean; isUploading: boolean;
setFiles: Dispatch<SetStateAction<File[]>>; setFiles: Dispatch<SetStateAction<FileUpload[]>>;
}) => { }) => {
const theme = useMantineTheme();
const { classes } = useStyles(); const { classes } = useStyles();
const openRef = useRef<() => void>(); const openRef = useRef<() => void>();
return ( return (
@ -62,7 +55,11 @@ const Dropzone = ({
if (files.length > 100) { if (files.length > 100) {
toast.error("You can't upload more than 100 files per share."); toast.error("You can't upload more than 100 files per share.");
} else { } else {
setFiles(files); const newFiles = files.map((file) => {
(file as FileUpload).uploadingProgress = 0;
return file as FileUpload;
});
setFiles(newFiles);
} }
}} }}
className={classes.dropzone} className={classes.dropzone}

View File

@ -1,8 +1,9 @@
import { ActionIcon, Loader, Table } from "@mantine/core"; import { ActionIcon, Table } from "@mantine/core";
import { Dispatch, SetStateAction } from "react"; import { Dispatch, SetStateAction } from "react";
import { CircleCheck, Trash } from "tabler-icons-react"; import { Trash } from "tabler-icons-react";
import { FileUpload } from "../../types/File.type"; import { FileUpload } from "../../types/File.type";
import { byteStringToHumanSizeString } from "../../utils/math/byteStringToHumanSizeString.util"; import { byteStringToHumanSizeString } from "../../utils/math/byteStringToHumanSizeString.util";
import UploadProgressIndicator from "./UploadProgressIndicator";
const FileList = ({ const FileList = ({
files, files,
@ -15,19 +16,12 @@ const FileList = ({
files.splice(index, 1); files.splice(index, 1);
setFiles([...files]); setFiles([...files]);
}; };
const rows = files.map((file, i) => ( const rows = files.map((file, i) => (
<tr key={i}> <tr key={i}>
<td>{file.name}</td> <td>{file.name}</td>
<td>{byteStringToHumanSizeString(file.size.toString())}</td> <td>{byteStringToHumanSizeString(file.size.toString())}</td>
<td> <td>
{file.uploadingState ? ( {file.uploadingProgress == 0 ? (
file.uploadingState != "finished" ? (
<Loader size={22} />
) : (
<CircleCheck color="green" size={22} />
)
) : (
<ActionIcon <ActionIcon
color="red" color="red"
variant="light" variant="light"
@ -36,6 +30,8 @@ const FileList = ({
> >
<Trash /> <Trash />
</ActionIcon> </ActionIcon>
) : (
<UploadProgressIndicator progress={file.uploadingProgress} />
)} )}
</td> </td>
</tr> </tr>

View File

@ -0,0 +1,20 @@
import { RingProgress } from "@mantine/core";
import { CircleCheck, CircleX } from "tabler-icons-react";
const UploadProgressIndicator = ({ progress }: { progress: number }) => {
if (progress > 0 && progress < 100) {
return (
<RingProgress
sections={[{ value: progress, color: "victoria" }]}
thickness={3}
size={25}
/>
);
} else if (progress == 100) {
return <CircleCheck color="green" size={22} />;
} else {
return <CircleX color="red" size={22} />;
}
};
export default UploadProgressIndicator;

View File

@ -14,9 +14,11 @@ import { useClipboard } from "@mantine/hooks";
import { useModals } from "@mantine/modals"; import { useModals } from "@mantine/modals";
import { NextLink } from "@mantine/next"; import { NextLink } from "@mantine/next";
import moment from "moment"; import moment from "moment";
import { useEffect, useState } from "react"; import { useRouter } from "next/router";
import { useState } from "react";
import { Link, Trash } from "tabler-icons-react"; import { Link, Trash } from "tabler-icons-react";
import Meta from "../../components/Meta"; import Meta from "../../components/Meta";
import useUser from "../../hooks/user.hook";
import shareService from "../../services/share.service"; import shareService from "../../services/share.service";
import { MyShare } from "../../types/share.type"; import { MyShare } from "../../types/share.type";
import toast from "../../utils/toast.util"; import toast from "../../utils/toast.util";
@ -24,100 +26,108 @@ import toast from "../../utils/toast.util";
const MyShares = () => { const MyShares = () => {
const modals = useModals(); const modals = useModals();
const clipboard = useClipboard(); const clipboard = useClipboard();
const router = useRouter();
const user = useUser();
const [shares, setShares] = useState<MyShare[]>(); const [shares, setShares] = useState<MyShare[]>();
useEffect(() => { // useEffect(() => {
shareService.getMyShares().then((shares) => setShares(shares)); // shareService.getMyShares().then((shares) => setShares(shares));
}, []); // }, []);
if (!shares) return <LoadingOverlay visible />; if (!user) {
return ( router.replace("/");
<> } else {
<Meta title="My shares" /> if (!shares) return <LoadingOverlay visible />;
<Title mb={30} order={3}> return (
My shares <>
</Title> <Meta title="My shares" />
{shares.length == 0 ? ( <Title mb={30} order={3}>
<Center style={{ height: "70vh" }}> My shares
<Stack align="center" spacing={10}> </Title>
<Title order={3}>It's empty here 👀</Title> {shares.length == 0 ? (
<Text>You don't have any shares.</Text> <Center style={{ height: "70vh" }}>
<Space h={5} /> <Stack align="center" spacing={10}>
<Button component={NextLink} href="/upload" variant="light"> <Title order={3}>It's empty here 👀</Title>
Create one <Text>You don't have any shares.</Text>
</Button> <Space h={5} />
</Stack> <Button component={NextLink} href="/upload" variant="light">
</Center> Create one
) : ( </Button>
<Table> </Stack>
<thead> </Center>
<tr> ) : (
<th>Name</th> <Table>
<th>Visitors</th> <thead>
<th>Expires at</th> <tr>
<th></th> <th>Name</th>
</tr> <th>Visitors</th>
</thead> <th>Expires at</th>
<tbody> <th></th>
{shares.map((share) => (
<tr key={share.id}>
<td>{share.id}</td>
<td>{share.views}</td>
<td>
{moment(share.expiration).format("MMMM DD YYYY, HH:mm")}
</td>
<td>
<Group position="right">
<ActionIcon
color="victoria"
variant="light"
size={25}
onClick={() => {
clipboard.copy(
`${window.location.origin}/share/${share.id}`
);
toast.success("Your link was copied to the keyboard.");
}}
>
<Link />
</ActionIcon>
<ActionIcon
color="red"
variant="light"
size={25}
onClick={() => {
modals.openConfirmModal({
title: `Delete share ${share.id}`,
children: (
<Text size="sm">
Do you really want to delete this share?
</Text>
),
confirmProps: {
color: "red",
},
labels: { confirm: "Confirm", cancel: "Cancel" },
onConfirm: () => {
shareService.remove(share.id);
setShares(
shares.filter((item) => item.id !== share.id)
);
},
});
}}
>
<Trash />
</ActionIcon>
</Group>
</td>
</tr> </tr>
))} </thead>
</tbody> <tbody>
</Table> {shares.map((share) => (
)} <tr key={share.id}>
</> <td>{share.id}</td>
); <td>{share.views}</td>
<td>
{moment(share.expiration).format("MMMM DD YYYY, HH:mm")}
</td>
<td>
<Group position="right">
<ActionIcon
color="victoria"
variant="light"
size={25}
onClick={() => {
clipboard.copy(
`${window.location.origin}/share/${share.id}`
);
toast.success(
"Your link was copied to the keyboard."
);
}}
>
<Link />
</ActionIcon>
<ActionIcon
color="red"
variant="light"
size={25}
onClick={() => {
modals.openConfirmModal({
title: `Delete share ${share.id}`,
children: (
<Text size="sm">
Do you really want to delete this share?
</Text>
),
confirmProps: {
color: "red",
},
labels: { confirm: "Confirm", cancel: "Cancel" },
onConfirm: () => {
shareService.remove(share.id);
setShares(
shares.filter((item) => item.id !== share.id)
);
},
});
}}
>
<Trash />
</ActionIcon>
</Group>
</td>
</tr>
))}
</tbody>
</Table>
)}
</>
);
}
}; };
export default MyShares; export default MyShares;

View File

@ -15,12 +15,21 @@ const Share = () => {
const shareId = router.query.shareId as string; const shareId = router.query.shareId as string;
const [fileList, setFileList] = useState<any[]>([]); const [fileList, setFileList] = useState<any[]>([]);
const submitPassword = async (password: string) => { const getShareToken = async (password?: string) => {
await shareService await shareService
.exchangeSharePasswordWithToken(shareId, password) .getShareToken(shareId, password)
.then(() => { .then(() => {
modals.closeAll(); modals.closeAll();
getFiles(); getFiles();
})
.catch((e) => {
if (e.response.data.error == "share_max_views_exceeded") {
showErrorModal(
modals,
"Visitor limit exceeded",
"The visitor limit from this share has been exceeded."
);
}
}); });
}; };
@ -38,14 +47,10 @@ const Share = () => {
"Not found", "Not found",
"This share can't be found. Please check your link." "This share can't be found. Please check your link."
); );
} else if (error == "share_password_required") {
showEnterPasswordModal(modals, getShareToken);
} else if (error == "share_token_required") { } else if (error == "share_token_required") {
showEnterPasswordModal(modals, submitPassword); getShareToken();
} else if (error == "share_max_views_exceeded") {
showErrorModal(
modals,
"Visitor limit exceeded",
"The visitor limit from this share has been exceeded."
);
} else if (error == "forbidden") { } else if (error == "forbidden") {
showErrorModal( showErrorModal(
modals, modals,
@ -69,9 +74,7 @@ const Share = () => {
description="Look what I've shared with you." description="Look what I've shared with you."
/> />
<Group position="right" mb="lg"> <Group position="right" mb="lg">
<DownloadAllButton <DownloadAllButton shareId={shareId} />
shareId={shareId}
/>
</Group> </Group>
<FileList <FileList
files={fileList} files={fileList}

View File

@ -28,39 +28,47 @@ const Upload = () => {
security: ShareSecurity security: ShareSecurity
) => { ) => {
setisUploading(true); setisUploading(true);
try { try {
files.forEach((file) => { setFiles((files) =>
file.uploadingState = "inProgress"; files.map((file) => {
}); file.uploadingProgress = 1;
setFiles([...files]); return file;
})
);
const share = await shareService.create(id, expiration, security); const share = await shareService.create(id, expiration, security);
for (let i = 0; i < files.length; i++) { for (let i = 0; i < files.length; i++) {
await shareService.uploadFile(share.id, files[i]); const progressCallBack = (bytesProgress: number) => {
setFiles((files) => {
return files.map((file, callbackIndex) => {
if (i == callbackIndex) {
file.uploadingProgress = Math.round(
(100 * bytesProgress) / files[i].size
);
}
return file;
});
});
};
files[i].uploadingState = "finished"; try {
setFiles([...files]); await shareService.uploadFile(share.id, files[i], progressCallBack);
if (!files.some((f) => f.uploadingState == "inProgress")) { } catch {
files[i].uploadingProgress = -1;
}
if (!files.some((f) => f.uploadingProgress != 100)) {
await shareService.completeShare(share.id); await shareService.completeShare(share.id);
setisUploading(false); setisUploading(false);
showCompletedUploadModal( showCompletedUploadModal(modals, share);
modals,
share
);
setFiles([]); setFiles([]);
} }
} }
} catch (e) { } catch (e) {
files.forEach((file) => {
file.uploadingState = undefined;
});
if (axios.isAxiosError(e)) { if (axios.isAxiosError(e)) {
toast.error(e.response?.data?.message ?? "An unkown error occured."); toast.error(e.response?.data?.message ?? "An unkown error occured.");
} else { } else {
toast.error("An unkown error occured."); toast.error("An unkown error occured.");
} }
setFiles([...files]);
setisUploading(false); setisUploading(false);
} }
}; };

View File

@ -44,9 +44,8 @@ const getMyShares = async (): Promise<MyShare[]> => {
return (await api.get("shares")).data; return (await api.get("shares")).data;
}; };
const exchangeSharePasswordWithToken = async (id: string, password: string) => { const getShareToken = async (id: string, password?: string) => {
const { token } = (await api.post(`/shares/${id}/password`, { password })) const { token } = (await api.post(`/shares/${id}/token`, { password })).data;
.data;
localStorage.setItem(`share_${id}_token`, token); localStorage.setItem(`share_${id}_token`, token);
}; };
@ -68,16 +67,26 @@ const downloadFile = async (shareId: string, fileId: string) => {
window.location.href = await getFileDownloadUrl(shareId, fileId); window.location.href = await getFileDownloadUrl(shareId, fileId);
}; };
const uploadFile = async (shareId: string, file: File) => { const uploadFile = async (
shareId: string,
file: File,
progressCallBack: (uploadingProgress: number) => void
) => {
var formData = new FormData(); var formData = new FormData();
formData.append("file", file); formData.append("file", file);
return (await api.post(`shares/${shareId}/files`, formData)).data;
return (
await api.post(`shares/${shareId}/files`, formData, {
onUploadProgress: (progressEvent) =>
progressCallBack(progressEvent.loaded),
})
).data;
}; };
export default { export default {
create, create,
completeShare, completeShare,
exchangeSharePasswordWithToken, getShareToken,
get, get,
remove, remove,
getMetaData, getMetaData,

View File

@ -1,2 +1 @@
export type FileUpload = File & { uploadingState?: UploadState }; export type FileUpload = File & { uploadingProgress: number };
export type UploadState = "finished" | "inProgress" | undefined;