initial commit

This commit is contained in:
Elias Schneider
2022-04-25 15:15:17 +02:00
commit 61be87b72a
72 changed files with 11502 additions and 0 deletions

67
src/pages/_app.tsx Normal file
View File

@@ -0,0 +1,67 @@
import {
ColorScheme,
Container,
LoadingOverlay,
MantineProvider,
} 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 { useEffect, useState } from "react";
import "../../styles/globals.css";
import ThemeProvider from "../components/mantine/ThemeProvider";
import Header from "../components/navBar/NavBar";
import globalStyle from "../styles/global.style";
import authUtil, { IsSignedInContext } from "../utils/auth.util";
import { GlobalLoadingContext } from "../utils/loading.util";
function App(props: AppProps & { colorScheme: ColorScheme }) {
const { Component, pageProps } = props;
const [colorScheme, setColorScheme] = useState<ColorScheme>(
props.colorScheme
);
const [isLoading, setIsLoading] = useState(true);
const [isSignedIn, setIsSignedIn] = useState(false);
const checkIfSignedIn = async () => {
setIsLoading(true);
setIsSignedIn(await authUtil.isSignedIn());
setIsLoading(false);
};
useEffect(() => {
checkIfSignedIn();
}, []);
return (
<MantineProvider withGlobalStyles withNormalizeCSS theme={globalStyle}>
<ThemeProvider colorScheme={colorScheme} setColorScheme={setColorScheme}>
<NotificationsProvider>
<ModalsProvider>
<GlobalLoadingContext.Provider value={{ isLoading, setIsLoading }}>
{isLoading ? (
<LoadingOverlay visible overlayOpacity={1} />
) : (
<IsSignedInContext.Provider value={isSignedIn}>
<LoadingOverlay visible={isLoading} overlayOpacity={1} />
<Header />
<Container>
<Component {...pageProps} />
</Container>
</IsSignedInContext.Provider>
)}
</GlobalLoadingContext.Provider>
</ModalsProvider>
</NotificationsProvider>
</ThemeProvider>
</MantineProvider>
);
}
export default App;
App.getInitialProps = ({ ctx }: { ctx: GetServerSidePropsContext }) => ({
colorScheme: getCookie("mantine-color-scheme", ctx) || "light",
});

8
src/pages/_document.tsx Normal file
View File

@@ -0,0 +1,8 @@
import Document from "next/document";
import { createGetInitialProps } from "@mantine/next";
const getInitialProps = createGetInitialProps();
export default class _Document extends Document {
static getInitialProps = getInitialProps;
}

View File

@@ -0,0 +1,44 @@
import type { NextApiRequest, NextApiResponse } from "next";
import {
SecurityDocument,
ShareDocument,
} from "../../../../types/Appwrite.type";
import awServer from "../../../../utils/appwriteServer.util";
import { hashPassword } from "../../../../utils/shares/security.util";
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const shareId = req.query.shareId as string;
let hashedPassword;
try {
hashedPassword = await checkPassword(shareId, req.body.password);
} catch (e) {
return res.status(403).json({ message: e });
}
if (hashedPassword)
res.setHeader(
"Set-Cookie",
`${shareId}-password=${hashedPassword}; Path=/api/share/${shareId}; max-age=3600; HttpOnly`
);
res.send(200);
};
export const checkPassword = async (shareId: string, password?: string) => {
let hashedPassword;
const shareDocument = await awServer.database.getDocument<ShareDocument>(
"shares",
shareId
);
await awServer.database
.getDocument<SecurityDocument>("shareSecurity", shareDocument.securityID)
.then((securityDocument) => {
if (securityDocument.password) {
hashedPassword = hashPassword(password as string, shareId);
if (hashedPassword !== securityDocument.password) {
throw "wrong_password";
}
}
});
return hashedPassword;
};
export default handler;

View File

@@ -0,0 +1,64 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { ShareDocument } from "../../../../types/Appwrite.type";
import { AppwriteFileWithPreview } from "../../../../types/File.type";
import awServer from "../../../../utils/appwriteServer.util";
import { checkSecurity } from "../../../../utils/shares/security.util";
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const shareId = req.query.shareId as string;
const fileList: AppwriteFileWithPreview[] = [];
const hashedPassword = req.cookies[`${shareId}-password`];
if (!(await shareExists(shareId)))
return res.status(404).json({ message: "not_found" });
try {
await checkSecurity(shareId, hashedPassword);
} catch (e) {
return res.status(403).json({ message: e });
}
addVisitorCount(shareId);
const fileListWithoutPreview = (await awServer.storage.listFiles(shareId))
.files;
for (const file of fileListWithoutPreview) {
const filePreview = await awServer.storage.getFilePreview(
shareId,
file.$id
);
fileList.push({ ...file, preview: filePreview });
}
if (hashedPassword)
res.setHeader(
"Set-Cookie",
`${shareId}-password=${hashedPassword}; Path=/share/${shareId}; max-age=3600; HttpOnly`
);
res.status(200).json(fileList);
};
const shareExists = async (shareId: string) => {
try {
const shareDocument = await awServer.database.getDocument<ShareDocument>(
"shares",
shareId
);
return shareDocument.enabled && shareDocument.expiresAt > Date.now();
} catch (e) {
return false;
}
};
const addVisitorCount = async (shareId: string) => {
const currentDocument = await awServer.database.getDocument<ShareDocument>(
"shares",
shareId
);
currentDocument.visitorCount++;
awServer.database.updateDocument("shares", shareId, currentDocument);
};
export default handler;

15
src/pages/auth/signIn.tsx Normal file
View File

@@ -0,0 +1,15 @@
import { useRouter } from "next/router";
import React, { useContext } from "react";
import AuthForm from "../../components/auth/AuthForm";
import { IsSignedInContext } from "../../utils/auth.util";
const SignIn = () => {
const isSignedIn = useContext(IsSignedInContext);
const router = useRouter();
if (isSignedIn) {
router.replace("/");
} else {
return <AuthForm mode="signIn" />;
}
};
export default SignIn;

15
src/pages/auth/signUp.tsx Normal file
View File

@@ -0,0 +1,15 @@
import { useRouter } from "next/router";
import React, { useContext } from "react";
import AuthForm from "../../components/auth/AuthForm";
import { IsSignedInContext } from "../../utils/auth.util";
const SignUp = () => {
const isSignedIn = useContext(IsSignedInContext);
const router = useRouter();
if (isSignedIn) {
router.replace("/");
} else {
return <AuthForm mode="signUp" />;
}
};
export default SignUp;

151
src/pages/index.tsx Normal file
View File

@@ -0,0 +1,151 @@
import {
Button,
Container,
createStyles,
Group,
List,
Text,
ThemeIcon,
Title,
} from "@mantine/core";
import { NextLink } from "@mantine/next";
import { useRouter } from "next/router";
import React, { useContext } from "react";
import { Check } from "tabler-icons-react";
import { IsSignedInContext } from "../utils/auth.util";
import Image from "next/image";
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,
fontFamily: `Greycliff CF, ${theme.fontFamily}`,
fontSize: 44,
lineHeight: 1.2,
fontWeight: 900,
[theme.fn.smallerThan("xs")]: {
fontSize: 28,
},
},
control: {
[theme.fn.smallerThan("xs")]: {
flex: 1,
},
},
image: {
flex: 1,
[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 isSignedIn = useContext(IsSignedInContext);
const { classes } = useStyles();
const router = useRouter();
if (isSignedIn) {
router.replace("/upload");
} else {
return (
<div>
<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>
<Image
src="/logo.svg"
alt="Pingvin Share Logo"
width={200}
height={200}
className={classes.image}
/>
</div>
</Container>
</div>
);
}
}

View File

@@ -0,0 +1,54 @@
import { useModals } from "@mantine/modals";
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import FileList from "../../components/share/FileList";
import showEnterPasswordModal from "../../components/share/showEnterPasswordModal";
import showShareNotFoundModal from "../../components/share/showShareNotFoundModal";
import showVisitorLimitExceededModal from "../../components/share/showVisitorLimitExceededModal";
import shareService from "../../services/share.service";
import { AppwriteFileWithPreview } from "../../types/File.type";
const Share = () => {
const router = useRouter();
const modals = useModals();
const shareId = router.query.shareId as string;
const [shareList, setShareList] = useState<AppwriteFileWithPreview[]>([]);
const submitPassword = async (password: string) => {
await shareService.authenticateWithPassword(shareId, password).then(() => {
modals.closeAll();
getFiles();
});
};
const getFiles = (password?: string) =>
shareService
.get(shareId, password)
.then((files) => setShareList(files))
.catch((e) => {
const error = e.response.data.message;
if (e.response.status == 404) {
showShareNotFoundModal(modals);
} else if (error == "password_required") {
showEnterPasswordModal(modals, submitPassword);
} else if (error == "visitor_limit_exceeded") {
showVisitorLimitExceededModal(modals);
}
});
useEffect(() => {
getFiles();
}, []);
return (
<div>
<FileList
files={shareList}
shareId={shareId}
isLoading={shareList.length == 0}
/>
</div>
);
};
export default Share;

103
src/pages/upload.tsx Normal file
View File

@@ -0,0 +1,103 @@
import { Button, Group, Menu } from "@mantine/core";
import { useModals } from "@mantine/modals";
import { useRouter } from "next/router";
import { useContext, useState } from "react";
import { Link, Mail } from "tabler-icons-react";
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 { FileUpload } from "../types/File.type";
import aw from "../utils/appwrite.util";
import { IsSignedInContext } from "../utils/auth.util";
import toast from "../utils/toast.util";
const Upload = () => {
const router = useRouter();
const modals = useModals();
const isSignedIn = useContext(IsSignedInContext);
const [files, setFiles] = useState<FileUpload[]>([]);
const [isUploading, setisUploading] = useState(false);
const uploadFiles = async (
id: string,
expiration: number,
security: { password?: string; maxVisitors?: number }
) => {
setisUploading(true);
const bucketId = JSON.parse(
(
await aw.functions.createExecution(
"createShare",
JSON.stringify({ id, security, expiration }),
false
)
).stdout
).id;
for (let i = 0; i < files.length; i++) {
files[i].uploadingState = "inProgress";
setFiles([...files]);
aw.storage.createFile(bucketId, "unique()", files[i]).then(
async () => {
files[i].uploadingState = "finished";
setFiles([...files]);
if (!files.some((f) => f.uploadingState == "inProgress")) {
await aw.functions.createExecution(
"finishShare",
JSON.stringify({ id }),
false
),
setisUploading(false);
showCompletedUploadModal(
modals,
`${window.location.origin}/share/${bucketId}`,
new Date(Date.now()).toLocaleString()
);
}
},
(error) => {
files[i].uploadingState = undefined;
toast.error(error.message);
setisUploading(false);
}
);
}
};
if (!isSignedIn) {
router.replace("/");
} else {
return (
<>
<Group position="right" mb={20}>
<div>
<Menu
control={
<Button loading={isUploading} disabled={files.length <= 0}>
Share
</Button>
}
transition="pop-top-right"
placement="end"
size="lg"
>
<Menu.Item
icon={<Link size={16} />}
onClick={() => showCreateUploadModal(modals, uploadFiles)}
>
Share with link
</Menu.Item>
<Menu.Item disabled icon={<Mail size={16} />}>
Share with email
</Menu.Item>
</Menu>
</div>
</Group>
<Dropzone setFiles={setFiles} isUploading={isUploading} />
{files.length > 0 && <FileList files={files} setFiles={setFiles} />}
</>
);
}
};
export default Upload;

View File

@@ -0,0 +1,5 @@
const Account = () => {
return <div></div>;
};
export default Account;