feat: remove appwrite and add nextjs backend

This commit is contained in:
Elias Schneider
2022-10-09 22:30:32 +02:00
parent 7728351158
commit 4bab33ad8a
153 changed files with 13400 additions and 2811 deletions

View File

@@ -0,0 +1,15 @@
import { Anchor, Center, Footer as MFooter, Text } from "@mantine/core";
const Footer = () => {
return (
<MFooter height="auto" p={10}>
<Center>
<Text size="xs" color="dimmed">
Made with 🖤 by <Anchor size="xs" href="https://eliasschneider.com" target="_blank">Elias Schneider</Anchor>
</Text>
</Center>
</MFooter>
);
};
export default Footer;

View File

@@ -0,0 +1,27 @@
import Head from "next/head";
const Meta = ({
title,
description,
}: {
title: string;
description?: string;
}) => {
return (
<Head>
{/* TODO: Doesn't work because script get only executed on client side */}
<title>{title} - Pingvin Share</title>
<meta name="og:title" content={`${title} - Pingvin Share`} />
<meta
name="og:description"
content={
description ?? "An open-source and self-hosted sharing platform."
}
/>
<meta name="twitter:title" content={`${title} - Pingvin Share`} />
<meta name="twitter:description" content={description} />
</Head>
);
};
export default Meta;

View File

@@ -0,0 +1,95 @@
import {
Anchor,
Button,
Container,
Paper,
PasswordInput,
Text,
TextInput,
Title,
} from "@mantine/core";
import { useForm, yupResolver } from "@mantine/form";
import getConfig from "next/config";
import * as yup from "yup";
import authService from "../../services/auth.service";
import toast from "../../utils/toast.util";
const { publicRuntimeConfig } = getConfig();
const AuthForm = ({ mode }: { mode: "signUp" | "signIn" }) => {
const validationSchema = yup.object().shape({
email: yup.string().email().required(),
password: yup.string().min(8).required(),
});
const form = useForm({
initialValues: {
email: "",
password: "",
},
schema: yupResolver(validationSchema),
});
const signIn = (email: string, password: string) => {
authService
.signIn(email, password)
.then(() => window.location.replace("/upload"))
.catch((e) => toast.error(e.response.data.message));
};
const signUp = (email: string, password: string) => {
authService
.signUp(email, password)
.then(() => signIn(email, password))
.catch((e) => toast.error(e.response.data.message));
};
return (
<Container size={420} my={40}>
<Title
align="center"
sx={(theme) => ({
fontFamily: `Greycliff CF, ${theme.fontFamily}`,
fontWeight: 900,
})}
>
{mode == "signUp" ? "Sign up" : "Welcome back"}
</Title>
{publicRuntimeConfig.ALLOW_REGISTRATION == "true" && (
<Text color="dimmed" size="sm" align="center" mt={5}>
{mode == "signUp"
? "You have an account already?"
: "You don't have an account yet?"}{" "}
<Anchor href={mode == "signUp" ? "signIn" : "signUp"} size="sm">
{mode == "signUp" ? "Sign in" : "Sign up"}
</Anchor>
</Text>
)}
<Paper withBorder shadow="md" p={30} mt={30} radius="md">
<form
onSubmit={form.onSubmit((values) =>
mode == "signIn"
? signIn(values.email, values.password)
: signUp(values.email, values.password)
)}
>
<TextInput
label="Email"
placeholder="you@email.com"
{...form.getInputProps("email")}
/>
<PasswordInput
label="Password"
placeholder="Your password"
mt="md"
{...form.getInputProps("password")}
/>
<Button fullWidth mt="xl" type="submit">
{mode == "signUp" ? "Let's get started" : "Sign in"}
</Button>
</form>
</Paper>
</Container>
);
};
export default AuthForm;

View File

@@ -0,0 +1,41 @@
import {
ColorScheme,
ColorSchemeProvider,
MantineProvider,
} from "@mantine/core";
import { ModalsProvider } from "@mantine/modals";
import { setCookies } from "cookies-next";
import { Dispatch, ReactNode, SetStateAction } from "react";
import mantineTheme from "../../styles/mantine.style";
const ThemeProvider = ({
children,
colorScheme,
setColorScheme,
}: {
children: ReactNode;
colorScheme: ColorScheme;
setColorScheme: Dispatch<SetStateAction<ColorScheme>>;
}) => {
const toggleColorScheme = (value?: ColorScheme) => {
const nextColorScheme =
value || (colorScheme === "dark" ? "light" : "dark");
setColorScheme(nextColorScheme);
setCookies("mantine-color-scheme", nextColorScheme, {
maxAge: 60 * 60 * 24 * 30,
});
};
return (
<MantineProvider theme={{ colorScheme, ...mantineTheme }} withGlobalStyles>
<ColorSchemeProvider
colorScheme={colorScheme}
toggleColorScheme={toggleColorScheme}
>
<ModalsProvider>{children}</ModalsProvider>
</ColorSchemeProvider>
</MantineProvider>
);
};
export default ThemeProvider;

View File

@@ -0,0 +1,47 @@
import { ActionIcon, Avatar, Menu } from "@mantine/core";
import { NextLink } from "@mantine/next";
import { DoorExit, Link, Moon } from "tabler-icons-react";
import authService from "../../services/auth.service";
import ToggleThemeButton from "./ToggleThemeButton";
const ActionAvatar = () => {
return (
<Menu
control={
<ActionIcon>
<Avatar size={28} radius="xl" />
</ActionIcon>
}
>
<Menu.Label>My account</Menu.Label>
<Menu.Item
component={NextLink}
href="/account/shares"
icon={<Link size={14} />}
>
Shares
</Menu.Item>
{/* <Menu.Item
component={NextLink}
href="/account/shares"
icon={<Settings size={14} />}
>
Settings
</Menu.Item> */}
<Menu.Item
onClick={async () => {
await authService.signOut();
}}
icon={<DoorExit size={14} />}
>
Sign out
</Menu.Item>
<Menu.Label>Settings</Menu.Label>
<Menu.Item icon={<Moon size={14} />}>
<ToggleThemeButton />
</Menu.Item>
</Menu>
);
};
export default ActionAvatar;

View File

@@ -0,0 +1,131 @@
import {
Burger,
Container,
Group,
Header as MantineHeader,
Paper,
Text,
Transition,
} from "@mantine/core";
import { useBooleanToggle } from "@mantine/hooks";
import { NextLink } from "@mantine/next";
import getConfig from "next/config";
import Image from "next/image";
import { ReactNode, useEffect, useState } from "react";
import useUser from "../../hooks/user.hook";
import headerStyle from "../../styles/header.style";
import ActionAvatar from "./ActionAvatar";
const { publicRuntimeConfig } = getConfig();
type Link = {
link?: string;
label?: string;
component?: ReactNode;
action?: () => Promise<void>;
};
const Header = () => {
const [opened, toggleOpened] = useBooleanToggle(false);
const [active, setActive] = useState<string>();
const user = useUser();
const { classes, cx } = headerStyle();
const authenticatedLinks: Link[] = [
{
link: "/upload",
label: "Upload",
},
{
component: <ActionAvatar />,
},
];
const unauthenticatedLinks: Link[] | undefined = [
{
link: "/auth/signIn",
label: "Sign in",
},
];
if (publicRuntimeConfig.SHOW_HOME_PAGE == "true")
unauthenticatedLinks.unshift({
link: "/",
label: "Home",
});
if (publicRuntimeConfig.ALLOW_REGISTRATION == "true")
unauthenticatedLinks.push({
link: "/auth/signUp",
label: "Sign up",
});
const links = user ? authenticatedLinks : unauthenticatedLinks;
const items = links.map((link, i) => {
if (link.component) {
return (
<Container key={i} pl={5} py={15}>
{link.component}
</Container>
);
}
if (link) {
// eslint-disable-next-line react-hooks/rules-of-hooks
useEffect(() => {
if (window.location.pathname == link.link) {
setActive(link.link);
}
}, []);
return (
<NextLink
key={link.label}
href={link.link ?? ""}
onClick={link.action}
className={cx(classes.link, {
[classes.linkActive]: link.link && active === link.link,
})}
>
{link.label}
</NextLink>
);
}
});
return (
<MantineHeader height={60} mb={20} className={classes.root}>
<Container className={classes.header}>
<NextLink href="/">
<Group>
<Image
src="/img/logo.svg"
alt="Pinvgin Share Logo"
height={40}
width={40}
/>
<Text weight={600}>Pingvin Share</Text>
</Group>
</NextLink>
<Group spacing={5} className={classes.links}>
{items}
</Group>
<Burger
opened={opened}
onClick={() => toggleOpened()}
className={classes.burger}
size="sm"
/>
<Transition transition="pop-top-right" duration={200} mounted={opened}>
{(styles) => (
<Paper className={classes.dropdown} withBorder style={styles}>
{items}
</Paper>
)}
</Transition>
</Container>
</MantineHeader>
);
};
export default Header;

View File

@@ -0,0 +1,19 @@
import { Switch, useMantineColorScheme } from "@mantine/core";
const ToggleThemeButton = () => {
const { colorScheme, toggleColorScheme } = useMantineColorScheme();
return (
<Switch
size="sm"
checked={colorScheme == "dark"}
onClick={(v) =>
toggleColorScheme(v.currentTarget.checked ? "dark" : "light")
}
onLabel="ON"
offLabel="OFF"
/>
);
};
export default ToggleThemeButton;

View File

@@ -0,0 +1,146 @@
import {
Accordion,
Button,
Col,
Grid,
Group,
NumberInput,
PasswordInput,
Select,
Text,
TextInput,
} from "@mantine/core";
import { useForm, yupResolver } from "@mantine/form";
import { useModals } from "@mantine/modals";
import * as yup from "yup";
import shareService from "../../services/share.service";
import { ShareSecurity } from "../../types/share.type";
const CreateUploadModalBody = ({
uploadCallback,
}: {
uploadCallback: (
id: string,
expiration: string,
security: ShareSecurity
) => void;
}) => {
const modals = useModals();
const validationSchema = yup.object().shape({
link: yup
.string()
.required()
.min(3)
.max(100)
.matches(new RegExp("^[a-zA-Z0-9_-]*$"), {
message: "Can only contain letters, numbers, underscores and hyphens",
}),
password: yup.string().min(3).max(30),
maxViews: yup.number().min(1),
});
const form = useForm({
initialValues: {
link: "",
password: undefined,
maxViews: undefined,
expiration: "1-day",
},
schema: yupResolver(validationSchema),
});
return (
<form
onSubmit={form.onSubmit(async (values) => {
if (!(await shareService.isShareIdAvailable(values.link))) {
form.setFieldError("link", "This link is already in use");
} else {
uploadCallback(values.link, values.expiration, {
password: values.password,
maxViews: values.maxViews,
});
modals.closeAll();
}
})}
>
<Group direction="column" grow>
<Grid align={form.errors.link ? "center" : "flex-end"}>
<Col xs={9}>
<TextInput
variant="filled"
label="Link"
placeholder="myAwesomeShare"
{...form.getInputProps("link")}
/>
</Col>
<Col xs={3}>
<Button
variant="outline"
onClick={() =>
form.setFieldValue(
"link",
Buffer.from(Math.random().toString(), "utf8")
.toString("base64")
.substr(10, 7)
)
}
>
Generate
</Button>
</Col>
</Grid>
<Text
size="xs"
sx={(theme) => ({
color: theme.colors.gray[6],
})}
>
{window.location.origin}/share/
{form.values.link == "" ? "myAwesomeShare" : form.values.link}
</Text>
<Select
label="Expiration"
{...form.getInputProps("expiration")}
data={[
{
value: "10-minutes",
label: "10 Minutes",
},
{ value: "1-hour", label: "1 Hour" },
{ value: "1-day", label: "1 Day" },
{ value: "1-week".toString(), label: "1 Week" },
{ value: "1-month", label: "1 Month" },
]}
/>
<Accordion>
<Accordion.Item
label="Security options"
sx={{ borderBottom: "none" }}
>
<Group direction="column" grow>
<PasswordInput
variant="filled"
placeholder="No password"
label="Password protection"
{...form.getInputProps("password")}
/>
<NumberInput
min={1}
type="number"
variant="filled"
placeholder="No limit"
label="Maximal views"
{...form.getInputProps("maxViews")}
/>
</Group>
</Accordion.Item>
</Accordion>
<Button type="submit">Share</Button>
</Group>
</form>
);
};
export default CreateUploadModalBody;

View File

@@ -0,0 +1,53 @@
import { Button, Tooltip } from "@mantine/core";
import { useEffect, useState } from "react";
import shareService from "../../services/share.service";
const DownloadAllButton = ({ shareId }: { shareId: string }) => {
const [isZipReady, setIsZipReady] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const downloadAll = async () => {
setIsLoading(true);
await shareService
.downloadFile(shareId, "zip")
.then(() => setIsLoading(false));
};
useEffect(() => {
shareService
.getMetaData(shareId)
.then((share) => setIsZipReady(share.isZipReady))
.catch(() => {});
const timer = setInterval(() => {
shareService.getMetaData(shareId).then((share) => {
setIsZipReady(share.isZipReady);
if (share.isZipReady) clearInterval(timer);
}).catch(() => {});
}, 5000);
return () => {
clearInterval(timer);
};
}, []);
if (!isZipReady)
return (
<Tooltip
wrapLines
position="bottom"
width={220}
withArrow
label="The share is preparing. This can take a few minutes."
>
<Button variant="outline" onClick={downloadAll} disabled>
Download all
</Button>
</Tooltip>
);
return (
<Button variant="outline" loading={isLoading} onClick={downloadAll}>
Download all
</Button>
);
};
export default DownloadAllButton;

View File

@@ -0,0 +1,88 @@
import { ActionIcon, Loader, Skeleton, Table } from "@mantine/core";
import { useRouter } from "next/router";
import { CircleCheck, Download } from "tabler-icons-react";
import shareService from "../../services/share.service";
import { byteStringToHumanSizeString } from "../../utils/math/byteStringToHumanSizeString.util";
const FileList = ({
files,
shareId,
isLoading,
}: {
files: any[];
shareId: string;
isLoading: boolean;
}) => {
const router = useRouter();
const skeletonRows = [...Array(5)].map((c, i) => (
<tr key={i}>
<td>
<Skeleton height={30} width={30} />
</td>
<td>
<Skeleton height={14} />
</td>
<td>
<Skeleton height={14} />
</td>
<td>
<Skeleton height={25} width={25} />
</td>
</tr>
));
const rows = files.map((file) => (
<tr key={file.name}>
<td>
{/* <Image
width={30}
height={30}
alt={file.name}
objectFit="cover"
style={{ borderRadius: 3 }}
src={`data:image/png;base64,${new Buffer(file.preview).toString(
"base64"
)}`}
></Image> */}
</td>
<td>{file.name}</td>
<td>{byteStringToHumanSizeString(file.size)}</td>
<td>
{file.uploadingState ? (
file.uploadingState != "finished" ? (
<Loader size={22} />
) : (
<CircleCheck color="green" size={22} />
)
) : (
<ActionIcon
size={25}
onClick={async () => {
await shareService.downloadFile(shareId, file.id);
}}
>
<Download />
</ActionIcon>
)}
</td>
</tr>
));
return (
<Table>
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Size</th>
<th></th>
</tr>
</thead>
<tbody>{isLoading ? skeletonRows : rows}</tbody>
</Table>
);
};
export default FileList;

View File

@@ -0,0 +1,58 @@
import { Button, Group, PasswordInput, Text, Title } from "@mantine/core";
import { ModalsContextProps } from "@mantine/modals/lib/context";
import { useState } from "react";
const showEnterPasswordModal = (
modals: ModalsContextProps,
submitCallback: any
) => {
return modals.openModal({
closeOnClickOutside: false,
withCloseButton: false,
closeOnEscape: false,
title: (
<>
<Title order={4}>Password required</Title>
<Text size="sm">
This access this share please enter the password for the share.
</Text>
</>
),
children: <Body submitCallback={submitCallback} />,
});
};
const Body = ({ submitCallback }: { submitCallback: any }) => {
const [password, setPassword] = useState("");
const [passwordWrong, setPasswordWrong] = useState(false);
return (
<>
<Group grow direction="column">
<PasswordInput
variant="filled"
placeholder="Password"
error={passwordWrong && "Wrong password"}
onFocus={() => setPasswordWrong(false)}
onChange={(e) => setPassword(e.target.value)}
value={password}
/>
<Button
onClick={() =>
submitCallback(password)
.then((res: any) => res)
.catch((e: any) => {
const error = e.response.data.message;
if (error == "Wrong password") {
setPasswordWrong(true);
}
})
}
>
Submit
</Button>
</Group>
</>
);
};
export default showEnterPasswordModal;

View File

@@ -0,0 +1,41 @@
import { Button, Group, Text, Title } from "@mantine/core";
import { useModals } from "@mantine/modals";
import { ModalsContextProps } from "@mantine/modals/lib/context";
import { useRouter } from "next/router";
const showErrorModal = (
modals: ModalsContextProps,
title: string,
text: string
) => {
return modals.openModal({
closeOnClickOutside: false,
withCloseButton: false,
closeOnEscape: false,
title: <Title order={4}>{title}</Title>,
children: <Body text={text} />,
});
};
const Body = ({ text }: { text: string }) => {
const modals = useModals();
const router = useRouter();
return (
<>
<Group grow direction="column">
<Text size="sm">{text}</Text>
<Button
onClick={() => {
modals.closeAll();
router.back();
}}
>
Go back
</Button>
</Group>
</>
);
};
export default showErrorModal;

View File

@@ -0,0 +1,115 @@
import {
Button,
Center,
createStyles,
Group,
MantineTheme,
Text,
useMantineTheme,
} from "@mantine/core";
import { Dropzone as MantineDropzone, DropzoneStatus } from "@mantine/dropzone";
import getConfig from "next/config";
import React, { Dispatch, ForwardedRef, SetStateAction, useRef } from "react";
import { CloudUpload, Upload } from "tabler-icons-react";
import toast from "../../utils/toast.util";
const { publicRuntimeConfig } = getConfig()
const useStyles = createStyles((theme) => ({
wrapper: {
position: "relative",
marginBottom: 30,
},
dropzone: {
borderWidth: 1,
paddingBottom: 50,
},
icon: {
color:
theme.colorScheme === "dark"
? theme.colors.dark[3]
: theme.colors.gray[4],
},
control: {
position: "absolute",
bottom: -20,
},
}));
function getActiveColor(status: DropzoneStatus, theme: MantineTheme) {
return status.accepted
? theme.colors[theme.primaryColor][6]
: theme.colorScheme === "dark"
? theme.colors.dark[2]
: theme.black;
}
const Dropzone = ({
isUploading,
setFiles,
}: {
isUploading: boolean;
setFiles: Dispatch<SetStateAction<File[]>>;
}) => {
const theme = useMantineTheme();
const { classes } = useStyles();
const openRef = useRef<() => void>();
return (
<div className={classes.wrapper}>
<MantineDropzone
maxSize={parseInt(publicRuntimeConfig.MAX_FILE_SIZE!)}
onReject={(e) => {
toast.error(e[0].errors[0].message);
}}
disabled={isUploading}
openRef={openRef as ForwardedRef<() => void>}
onDrop={(files) => {
if (files.length > 100) {
toast.error("You can't upload more than 100 files per share.");
} else {
setFiles(files);
}
}}
className={classes.dropzone}
radius="md"
>
{(status) => (
<div style={{ pointerEvents: "none" }}>
<Group position="center">
<CloudUpload size={50} color={getActiveColor(status, theme)} />
</Group>
<Text
align="center"
weight={700}
size="lg"
mt="xl"
sx={{ color: getActiveColor(status, theme) }}
>
{status.accepted ? "Drop files here" : "Upload files"}
</Text>
<Text align="center" size="sm" mt="xs" color="dimmed">
Drag and drop your files or use the upload button to start your
share.
</Text>
</div>
)}
</MantineDropzone>
<Center>
<Button
className={classes.control}
variant="light"
size="sm"
radius="xl"
disabled={isUploading}
onClick={() => openRef.current && openRef.current()}
>
{<Upload />}
</Button>
</Center>
</div>
);
};
export default Dropzone;

View File

@@ -0,0 +1,60 @@
import { ActionIcon, Loader, Table } from "@mantine/core";
import { Dispatch, SetStateAction } from "react";
import { CircleCheck, Trash } from "tabler-icons-react";
import { FileUpload } from "../../types/File.type";
import { byteStringToHumanSizeString } from "../../utils/math/byteStringToHumanSizeString.util";
const FileList = ({
files,
setFiles,
}: {
files: FileUpload[];
setFiles: Dispatch<SetStateAction<FileUpload[]>>;
}) => {
const remove = (index: number) => {
files.splice(index, 1);
setFiles([...files]);
};
const rows = files.map((file, i) => (
<tr key={i}>
<td>{file.name}</td>
<td>{file.type}</td>
<td>{byteStringToHumanSizeString(file.size.toString())}</td>
<td>
{file.uploadingState ? (
file.uploadingState != "finished" ? (
<Loader size={22} />
) : (
<CircleCheck color="green" size={22} />
)
) : (
<ActionIcon
color="red"
variant="light"
size={25}
onClick={() => remove(i)}
>
<Trash />
</ActionIcon>
)}
</td>
</tr>
));
return (
<Table>
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Size</th>
<th></th>
</tr>
</thead>
<tbody>{rows}</tbody>
</Table>
);
};
export default FileList;

View File

@@ -0,0 +1,77 @@
import {
ActionIcon,
Button,
Group,
Text,
TextInput,
Title,
} from "@mantine/core";
import { useClipboard } from "@mantine/hooks";
import { useModals } from "@mantine/modals";
import { ModalsContextProps } from "@mantine/modals/lib/context";
import moment from "moment";
import { useRouter } from "next/router";
import { Copy } from "tabler-icons-react";
import { Share } from "../../types/share.type";
import toast from "../../utils/toast.util";
const showCompletedUploadModal = (
modals: ModalsContextProps,
share: Share,
) => {
return modals.openModal({
closeOnClickOutside: false,
withCloseButton: false,
closeOnEscape: false,
title: (
<Group grow direction="column" spacing={0}>
<Title order={4}>Share ready</Title>
</Group>
),
children: <Body share={share} />,
});
};
const Body = ({ share }: { share: Share }) => {
const clipboard = useClipboard({ timeout: 500 });
const modals = useModals();
const router = useRouter();
const link = `${window.location.origin}/share/${share.id}`;
return (
<Group grow direction="column">
<TextInput
variant="filled"
value={link}
rightSection={
<ActionIcon
onClick={() => {
clipboard.copy(link);
toast.success("Your link was copied to the keyboard.");
}}
>
<Copy />
</ActionIcon>
}
/>
<Text
size="xs"
sx={(theme) => ({
color: theme.colors.gray[6],
})}
>
Your share expires at {moment(share.expiration).format("LLL")}
</Text>
<Button
onClick={() => {
modals.closeAll();
router.push("/upload");
}}
>
Done
</Button>
</Group>
);
};
export default showCompletedUploadModal;

View File

@@ -0,0 +1,22 @@
import { Title } from "@mantine/core";
import { ModalsContextProps } from "@mantine/modals/lib/context";
import { ShareSecurity } from "../../types/share.type";
import CreateUploadModalBody from "../share/CreateUploadModalBody";
const showCreateUploadModal = (
modals: ModalsContextProps,
uploadCallback: (
id: string,
expiration: string,
security: ShareSecurity,
) => void
) => {
return modals.openModal({
title: <Title order={4}>Share</Title>,
children: (
<CreateUploadModalBody uploadCallback={uploadCallback} />
),
});
};
export default showCreateUploadModal;