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,64 @@
import React from "react";
import {
createStyles,
Title,
Text,
Button,
Container,
Group,
} from "@mantine/core";
import Meta from "../components/Meta";
import { NextLink } from "@mantine/next";
const useStyles = createStyles((theme) => ({
root: {
paddingTop: 80,
paddingBottom: 80,
},
label: {
textAlign: "center",
fontWeight: 900,
fontSize: 220,
lineHeight: 1,
marginBottom: theme.spacing.xl * 1.5,
color: theme.colors.gray[2],
[theme.fn.smallerThan("sm")]: {
fontSize: 120,
},
},
description: {
maxWidth: 500,
margin: "auto",
marginBottom: theme.spacing.xl * 1.5,
},
}));
const ErrorNotFound = () => {
const { classes } = useStyles();
return (
<>
<Meta title="Not found" />
<Container className={classes.root}>
<div className={classes.label}>404</div>
<Title align="center" order={3}>
Oops this page doesn't exist.
</Title>
<Text
color="dimmed"
align="center"
className={classes.description}
></Text>
<Group position="center">
<Button component={NextLink} href="/" variant="light">
Bring me back
</Button>
</Group>
</Container>
</>
);
};
export default ErrorNotFound;

View File

@@ -0,0 +1,86 @@
import {
ColorScheme,
Container,
LoadingOverlay,
MantineProvider,
Stack,
} from "@mantine/core";
import { ModalsProvider } from "@mantine/modals";
import { NotificationsProvider } from "@mantine/notifications";
import { getCookie } from "cookies-next";
import { GetServerSidePropsContext } from "next";
import type { AppProps } from "next/app";
import getConfig from "next/config";
import { useEffect, useState } from "react";
import Footer from "../components/Footer";
import ThemeProvider from "../components/mantine/ThemeProvider";
import Header from "../components/navBar/NavBar";
import { UserContext } from "../hooks/user.hook";
import authService from "../services/auth.service";
import userService from "../services/user.service";
import GlobalStyle from "../styles/global.style";
import globalStyle from "../styles/mantine.style";
import { CurrentUser } from "../types/user.type";
import { GlobalLoadingContext } from "../utils/loading.util";
const { publicRuntimeConfig } = getConfig()
function App(
props: AppProps & { colorScheme: ColorScheme; environmentVariables: any }
) {
const { Component, pageProps } = props;
const [colorScheme, setColorScheme] = useState<ColorScheme>(
props.colorScheme
);
const [isLoading, setIsLoading] = useState(true);
const [user, setUser] = useState<CurrentUser | null>(null);
const getInitalData = async () => {
console.log(publicRuntimeConfig)
setIsLoading(true);
setUser(await userService.getCurrentUser());
setIsLoading(false);
};
useEffect(() => {
setInterval(async () => await authService.refreshAccessToken(), 30 * 1000);
getInitalData();
}, []);
return (
<MantineProvider withGlobalStyles withNormalizeCSS theme={globalStyle}>
<ThemeProvider colorScheme={colorScheme} setColorScheme={setColorScheme}>
<GlobalStyle />
<NotificationsProvider>
<ModalsProvider>
<GlobalLoadingContext.Provider value={{ isLoading, setIsLoading }}>
{isLoading ? (
<LoadingOverlay visible overlayOpacity={1} />
) : (
<UserContext.Provider value={user}>
<LoadingOverlay visible={isLoading} overlayOpacity={1} />
<Stack justify="space-between" sx={{ minHeight: "100vh" }}>
<div>
<Header />
<Container>
<Component {...pageProps} />
</Container>
</div>
<Footer />
</Stack>
</UserContext.Provider>
)}
</GlobalLoadingContext.Provider>
</ModalsProvider>
</NotificationsProvider>
</ThemeProvider>
</MantineProvider>
);
}
export default App;
App.getInitialProps = ({ ctx }: { ctx: GetServerSidePropsContext }) => {
return {
colorScheme: getCookie("mantine-color-scheme", ctx) || "light",
};
};

View File

@@ -0,0 +1,29 @@
import { createGetInitialProps } from "@mantine/next";
import Document, { Head, Html, Main, NextScript } from "next/document";
const getInitialProps = createGetInitialProps();
export default class _Document extends Document {
static getInitialProps = getInitialProps;
render() {
return (
<Html>
<Head>
<link rel="manifest" href="/manifest.json" />
<link rel="apple-touch-icon" href="/icons/icon-white-128x128.png" />
<meta property="og:image" content="/img/opengraph-default.png" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:image" content="/img/opengraph-default.png" />
<meta name="robots" content="noindex" />
<meta name="theme-color" content="#46509e" />
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}

View File

@@ -0,0 +1,122 @@
import {
ActionIcon,
Button,
Center,
Group,
LoadingOverlay,
Space,
Table,
Text,
Title,
} from "@mantine/core";
import { useClipboard } from "@mantine/hooks";
import { useModals } from "@mantine/modals";
import { NextLink } from "@mantine/next";
import moment from "moment";
import { useEffect, useState } from "react";
import { Link, Trash } from "tabler-icons-react";
import Meta from "../../components/Meta";
import shareService from "../../services/share.service";
import { MyShare } from "../../types/share.type";
import toast from "../../utils/toast.util";
const MyShares = () => {
const modals = useModals();
const clipboard = useClipboard();
const [shares, setShares] = useState<MyShare[]>();
useEffect(() => {
shareService.getMyShares().then((shares) => setShares(shares));
}, []);
if (!shares) return <LoadingOverlay visible />;
return (
<>
<Meta title="My shares" />
<Title mb={30} order={3}>
My shares
</Title>
{shares.length == 0 ? (
<Center style={{ height: "70vh" }}>
<Group direction="column" align="center" spacing={10}>
<Title order={3}>It's empty here 👀</Title>
<Text>You don't have any shares.</Text>
<Space h={5} />
<Button component={NextLink} href="/upload" variant="light">
Create one
</Button>
</Group>
</Center>
) : (
<Table>
<thead>
<tr>
<th>Name</th>
<th>Visitors</th>
<th>Expires at</th>
<th></th>
</tr>
</thead>
<tbody>
{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;

View File

@@ -0,0 +1,19 @@
import { NextApiRequest, NextApiResponse } from "next";
import httpProxyMiddleware from "next-http-proxy-middleware";
import getConfig from "next/config";
const { publicRuntimeConfig } = getConfig();
export const config = {
api: {
bodyParser: false,
externalResolver: true,
},
};
// This function can be marked `async` if using `await` inside
export default (req: NextApiRequest, res: NextApiResponse) =>
httpProxyMiddleware(req, res, {
// You can use the `http-proxy` option
target: publicRuntimeConfig.BACKEND_URL,
});

View File

@@ -0,0 +1,20 @@
import { useRouter } from "next/router";
import AuthForm from "../../components/auth/AuthForm";
import Meta from "../../components/Meta";
import useUser from "../../hooks/user.hook";
const SignIn = () => {
const user = useUser();
const router = useRouter();
if (user) {
router.replace("/");
} else {
return (
<>
<Meta title="Sign In" />
<AuthForm mode="signIn" />
</>
);
}
};
export default SignIn;

View File

@@ -0,0 +1,22 @@
import { useRouter } from "next/router";
import AuthForm from "../../components/auth/AuthForm";
import Meta from "../../components/Meta";
import useUser from "../../hooks/user.hook";
const SignUp = () => {
const user = useUser();
const router = useRouter();
if (user) {
router.replace("/");
} else if (process.env.NEXT_PUBLIC_DISABLE_REGISTRATION) {
router.replace("/auth/signIn");
} else {
return (
<>
<Meta title="Sign Up" />
<AuthForm mode="signUp" />
</>
);
}
};
export default SignUp;

View File

@@ -0,0 +1,157 @@
import {
Button,
Container,
createStyles,
Group,
List,
Text,
ThemeIcon,
Title,
} from "@mantine/core";
import { NextLink } from "@mantine/next";
import getConfig from "next/config";
import Image from "next/image";
import { useRouter } from "next/router";
import { Check } from "tabler-icons-react";
import Meta from "../components/Meta";
import useUser from "../hooks/user.hook";
const { publicRuntimeConfig } = getConfig()
const useStyles = createStyles((theme) => ({
inner: {
display: "flex",
justifyContent: "space-between",
paddingTop: theme.spacing.xl * 4,
paddingBottom: theme.spacing.xl * 4,
},
content: {
maxWidth: 480,
marginRight: theme.spacing.xl * 3,
[theme.fn.smallerThan("md")]: {
maxWidth: "100%",
marginRight: 0,
},
},
title: {
color: theme.colorScheme === "dark" ? theme.white : theme.black,
fontSize: 44,
lineHeight: 1.2,
fontWeight: 900,
[theme.fn.smallerThan("xs")]: {
fontSize: 28,
},
},
control: {
[theme.fn.smallerThan("xs")]: {
flex: 1,
},
},
image: {
[theme.fn.smallerThan("md")]: {
display: "none",
},
},
highlight: {
position: "relative",
backgroundColor:
theme.colorScheme === "dark"
? theme.fn.rgba(theme.colors[theme.primaryColor][6], 0.55)
: theme.colors[theme.primaryColor][0],
borderRadius: theme.radius.sm,
padding: "4px 12px",
},
}));
export default function Home() {
const user = useUser();
const { classes } = useStyles();
const router = useRouter();
if (user) {
router.replace("/upload");
} else if (publicRuntimeConfig.SHOW_HOME_PAGE == "false") {
router.replace("/auth/signIn");
} else {
return (
<>
<Meta title="Home" />
<Container>
<div className={classes.inner}>
<div className={classes.content}>
<Title className={classes.title}>
A <span className={classes.highlight}>self-hosted</span> <br />{" "}
file sharing platform.
</Title>
<Text color="dimmed" mt="md">
Do you really want to give your personal files in the hand of
third parties like WeTransfer?
</Text>
<List
mt={30}
spacing="sm"
size="sm"
icon={
<ThemeIcon size={20} radius="xl">
<Check size={12} />
</ThemeIcon>
}
>
<List.Item>
<b>Self-Hosted</b> - Host Pingvin Share on your own machine.
</List.Item>
<List.Item>
<b>Privacy</b> - Your files are your files and should never
get into the hands of third parties.
</List.Item>
<List.Item>
<b>No annoying file size limit</b> - Upload as big files as
you want. Only your hard drive will be your limit.
</List.Item>
</List>
<Group mt={30}>
<Button
component={NextLink}
href="/auth/signUp"
radius="xl"
size="md"
className={classes.control}
>
Get started
</Button>
<Button
component={NextLink}
href="https://github.com/stonith404/pingvin-share"
target="_blank"
variant="default"
radius="xl"
size="md"
className={classes.control}
>
Source code
</Button>
</Group>
</div>
<Group className={classes.image} align="center">
<Image
src="/img/logo.svg"
alt="Pingvin Share Logo"
width={200}
height={200}
/>
</Group>
</div>
</Container>
</>
);
}
}

View File

@@ -0,0 +1,85 @@
import { Group } from "@mantine/core";
import { useModals } from "@mantine/modals";
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import Meta from "../../components/Meta";
import DownloadAllButton from "../../components/share/DownloadAllButton";
import FileList from "../../components/share/FileList";
import showEnterPasswordModal from "../../components/share/showEnterPasswordModal";
import showErrorModal from "../../components/share/showErrorModal";
import shareService from "../../services/share.service";
const Share = () => {
const router = useRouter();
const modals = useModals();
const shareId = router.query.shareId as string;
const [fileList, setFileList] = useState<any[]>([]);
const submitPassword = async (password: string) => {
await shareService
.exchangeSharePasswordWithToken(shareId, password)
.then(() => {
modals.closeAll();
getFiles();
});
};
const getFiles = async () => {
shareService
.get(shareId)
.then((share) => {
setFileList(share.files);
})
.catch((e) => {
const { error } = e.response.data;
if (e.response.status == 404) {
showErrorModal(
modals,
"Not found",
"This share can't be found. Please check your link."
);
} else if (error == "share_token_required") {
showEnterPasswordModal(modals, submitPassword);
} 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") {
showErrorModal(
modals,
"Forbidden",
"You're not allowed to see this share. Are you logged in with the correct account?"
);
} else {
showErrorModal(modals, "Error", "An unknown error occurred.");
}
});
};
useEffect(() => {
getFiles();
}, []);
return (
<>
<Meta
title={`Share ${shareId}`}
description="Look what I've shared with you."
/>
<Group position="right" mb="lg">
<DownloadAllButton
shareId={shareId}
/>
</Group>
<FileList
files={fileList}
shareId={shareId}
isLoading={fileList.length == 0}
/>
</>
);
};
export default Share;

View File

@@ -0,0 +1,81 @@
import { Button, Group } from "@mantine/core";
import { useModals } from "@mantine/modals";
import { useRouter } from "next/router";
import { useState } from "react";
import Meta from "../components/Meta";
import Dropzone from "../components/upload/Dropzone";
import FileList from "../components/upload/FileList";
import showCompletedUploadModal from "../components/upload/showCompletedUploadModal";
import showCreateUploadModal from "../components/upload/showCreateUploadModal";
import useUser from "../hooks/user.hook";
import shareService from "../services/share.service";
import { FileUpload } from "../types/File.type";
import { ShareSecurity } from "../types/share.type";
const Upload = () => {
const router = useRouter();
const modals = useModals();
const user = useUser();
const [files, setFiles] = useState<FileUpload[]>([]);
const [isUploading, setisUploading] = useState(false);
const uploadFiles = async (
id: string,
expiration: string,
security: ShareSecurity
) => {
setisUploading(true);
try {
files.forEach((file) => {
file.uploadingState = "inProgress";
});
setFiles([...files]);
const share = await shareService.create(id, expiration, security);
for (let i = 0; i < files.length; i++) {
await shareService.uploadFile(share.id, files[i]);
files[i].uploadingState = "finished";
setFiles([...files]);
if (!files.some((f) => f.uploadingState == "inProgress")) {
await shareService.completeShare(share.id);
setisUploading(false);
showCompletedUploadModal(
modals,
share
);
setFiles([]);
}
}
} catch {
files.forEach((file) => {
file.uploadingState = undefined;
});
setFiles([...files]);
setisUploading(false);
}
};
if (!user) {
router.replace("/");
} else {
return (
<>
<Meta title="Upload" />
<Group position="right" mb={20}>
<Button
loading={isUploading}
disabled={files.length <= 0}
onClick={() => showCreateUploadModal(modals, uploadFiles)}
>
Share
</Button>
</Group>
<Dropzone setFiles={setFiles} isUploading={isUploading} />
{files.length > 0 && <FileList files={files} setFiles={setFiles} />}
</>
);
}
};
export default Upload;

View File

@@ -0,0 +1,6 @@
// TODO: Add user account
const Account = () => {
return <div></div>;
};
export default Account;