feat: prettier run (#200)

* feat: prettier run

* fix: whatever that was

* chore: format more files

* chore: make format command better
This commit is contained in:
Jonathan 2022-10-19 22:43:01 -04:00 committed by GitHub
parent cb7dacd089
commit af0cd26ea0
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
165 changed files with 3635 additions and 10100 deletions

View file

@ -1,36 +1,18 @@
{
"extends": [
"next",
"next/core-web-vitals"
],
"extends": ["next", "next/core-web-vitals", "plugin:prettier/recommended"],
"rules": {
"indent": [
"error",
2,
{
"SwitchCase": 1
}
],
"linebreak-style": [
"error",
"unix"
],
"linebreak-style": ["error", "unix"],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"always"
],
"comma-dangle": [
"error",
"always-multiline"
],
"jsx-quotes": [
"error",
"prefer-single"
"single",
{
"avoidEscape": true
}
],
"semi": ["error", "always"],
"comma-dangle": ["error", "always-multiline"],
"jsx-quotes": ["error", "prefer-single"],
"indent": "off",
"react/prop-types": "off",
"react-hooks/rules-of-hooks": "off",
"react-hooks/exhaustive-deps": "off",

5
.prettierrc.json Normal file
View file

@ -0,0 +1,5 @@
{
"singleQuote": true,
"jsxSingleQuote": true,
"printWidth": 110
}

View file

@ -2,8 +2,8 @@ nodeLinker: node-modules
plugins:
- path: .yarn/plugins/@yarnpkg/plugin-interactive-tools.cjs
spec: "@yarnpkg/plugin-interactive-tools"
spec: '@yarnpkg/plugin-interactive-tools'
yarnPath: .yarn/releases/yarn-3.2.1.cjs
checksumBehavior: "update"
checksumBehavior: 'update'

View file

@ -1,18 +1,23 @@
# Contributing
## Bug reports
Create an issue on GitHub, please include the following (if one of them is not applicable to the issue then it's not needed):
* The steps to reproduce the bug
* Logs of Zipline
* The version of Zipline
* Your OS & Browser including server OS
* What you were expecting to see
- The steps to reproduce the bug
- Logs of Zipline
- The version of Zipline
- Your OS & Browser including server OS
- What you were expecting to see
## Feature requests
Create an issue on GitHub, please include the following:
* Breif explanation of the feature in the title (very breif please)
* How it would work (detailed, but optional)
- Breif explanation of the feature in the title (very breif please)
- How it would work (detailed, but optional)
## Pull Requests (contributions to the codebase)
Create a pull request on GitHub. If your PR does not pass the action checks, then please fix the errors. If your PR was submitted before a release, and I have pushed a new release, please make sure to update your PR to reflect any changes, usually this is handled by GitHub.
Please make sure your code also reflects the style of the rest of the code.

View file

@ -1,20 +1,21 @@
<div align="center">
<img src="https://raw.githubusercontent.com/diced/zipline/trunk/public/zipline_small.png"/>
A ShareX/file upload server that is easy to use, packed with features, and with an easy setup!
A ShareX/file upload server that is easy to use, packed with features, and with an easy setup!
![Stars](https://img.shields.io/github/stars/diced/zipline?logo=github&style=flat)
![Version](https://img.shields.io/github/package-json/v/diced/zipline?logo=git&logoColor=white&style=flat)
![GitHub last commit (branch)](https://img.shields.io/github/last-commit/diced/zipline/trunk?logo=git&logoColor=white&style=flat)
[![Discord](https://img.shields.io/discord/729771078196527176?color=%23777ed3&label=discord&logo=discord&logoColor=white&style=flat)](https://discord.gg/EAhCRfGxCF)
![Stars](https://img.shields.io/github/stars/diced/zipline?logo=github&style=flat)
![Version](https://img.shields.io/github/package-json/v/diced/zipline?logo=git&logoColor=white&style=flat)
![GitHub last commit (branch)](https://img.shields.io/github/last-commit/diced/zipline/trunk?logo=git&logoColor=white&style=flat)
[![Discord](https://img.shields.io/discord/729771078196527176?color=%23777ed3&label=discord&logo=discord&logoColor=white&style=flat)](https://discord.gg/EAhCRfGxCF)
![Build](https://img.shields.io/github/workflow/status/diced/zipline/Build?logo=github&style=flat)
[![Docker Image (trunk)](https://img.shields.io/github/workflow/status/diced/zipline/Push%20Docker%20Images?label=Docker%20%28trunk%29&logo=github&style=flat)](https://github.com/diced/zipline/pkgs/container/zipline/?tag=trunk)
[![Docker Image (release)](https://img.shields.io/github/workflow/status/diced/zipline/Push%20Release%20Docker%20Images?label=Docker%20%28release%29&logo=github&style=flat)](https://github.com/diced/zipline/pkgs/container/zipline/?tag=latest)
![Build](https://img.shields.io/github/workflow/status/diced/zipline/Build?logo=github&style=flat)
[![Docker Image (trunk)](https://img.shields.io/github/workflow/status/diced/zipline/Push%20Docker%20Images?label=Docker%20%28trunk%29&logo=github&style=flat)](https://github.com/diced/zipline/pkgs/container/zipline/?tag=trunk)
[![Docker Image (release)](https://img.shields.io/github/workflow/status/diced/zipline/Push%20Release%20Docker%20Images?label=Docker%20%28release%29&logo=github&style=flat)](https://github.com/diced/zipline/pkgs/container/zipline/?tag=latest)
</div>
## Features
- Configurable
- Fast
- Built with Next.js & React
@ -35,6 +36,7 @@
# Usage
## Install & run with Docker
This section requires [Docker](https://docs.docker.com/get-docker/) and [docker-compose](https://docs.docker.com/compose/install/).
```shell
@ -45,11 +47,14 @@ docker-compose up -d
```
### After installing
After installing, please edit the `docker-compose.yml` file and find the line that says `SECRET=changethis` and replace `changethis` with a random string.
Ways you could generate the string could be from a password managers generator, or you could just slam your keyboard and hope for the best.
## Building & running from source
This section requires [nodejs](https://nodejs.org), [yarn](https://yarnpkg.com/) or [npm](https://npmjs.com).
```shell
git clone https://github.com/diced/zipline
cd zipline
@ -63,6 +68,7 @@ yarn start
```
# NGINX Proxy
This section requires [NGINX](https://nginx.org/).
```nginx
@ -81,14 +87,17 @@ server {
```
# Website
The default port is `3000`, once you have accessed it you can see a login screen. The default credentials are "administrator" and "password". Once you login please immediately change the details to something more secure. You can do this by clicking on the top right corner where it says "administrator" with a gear icon and clicking Manage Account.
# ShareX (Windows)
This section requires [ShareX](https://www.getsharex.com/).
After navigating to Zipline, click on the top right corner where it says your username and click Manage Account. Scroll down to see "ShareX Config", select the one you would prefer using. After this you can import the .sxcu into sharex. [More information here](https://zipl.vercel.app/docs/guides/uploaders/sharex)
# Flameshot (Linux)
This section requires [Flameshot](https://www.flameshot.org/), [jq](https://stedolan.github.io/jq/), and [xsel](https://github.com/kfish/xsel).
You can either use the script below, or generate one directly from Zipline (just like how you can generate a ShareX config).
@ -104,17 +113,22 @@ curl -H "Content-Type: multipart/form-data" -H "authorization: $TOKEN" -F file=@
# Contributing
## Bug reports
Create an issue on GitHub, please include the following (if one of them is not applicable to the issue then it's not needed):
* The steps to reproduce the bug
* Logs of Zipline
* The version of Zipline
* Your OS & Browser including server OS
* What you were expecting to see
- The steps to reproduce the bug
- Logs of Zipline
- The version of Zipline
- Your OS & Browser including server OS
- What you were expecting to see
## Feature requests
Create an issue on GitHub, please include the following:
* Breif explanation of the feature in the title (very breif please)
* How it would work (detailed, but optional)
- Breif explanation of the feature in the title (very breif please)
- How it would work (detailed, but optional)
## Pull Requests (contributions to the codebase)
Create a pull request on GitHub. If your PR does not pass the action checks, then please fix the errors. If your PR was submitted before a release, and I have pushed a new release, please make sure to update your PR to reflect any changes, usually this is handled by GitHub.

View file

@ -9,4 +9,5 @@
| < 2 | :x: |
## Reporting a Vulnerability
Report a Vulnerability by issuing a bug report, with exact details with how the vulnerability happened, what "exploits" can happen, and possible fixes (optional). Vulnerability reports are treated with high priority and will be resolved most of the time quickly.

9678
mimes.json

File diff suppressed because it is too large Load diff

View file

@ -8,6 +8,7 @@
"build-ci": "cross-env ZIPLINE_DOCKER_BUILD=1 npm-run-all build:schema build:next",
"build:next": "next build",
"build:schema": "prisma generate --schema=prisma/schema.prisma",
"format": "prettier --write ./src/**/*.{ts,tsx} ./*.{md,js,json,yml}",
"migrate:dev": "prisma migrate dev --create-only",
"start": "tsx src/server",
"lint": "next lint",
@ -69,8 +70,10 @@
"esbuild": "^0.14.44",
"eslint": "^7.32.0",
"eslint-config-next": "12.1.6",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-prettier": "^4.2.1",
"npm-run-all": "^4.1.5",
"prettier": "^2.7.1",
"ts-node": "^10.8.1",
"tsx": "^3.8.0",
"typescript": "^4.7.3"

View file

@ -1,6 +1,5 @@
import { Card as MCard, Title } from '@mantine/core';
export default function Card({ name, children, ...other }) {
return (
<MCard p='md' shadow='sm' {...other}>

View file

@ -11,11 +11,5 @@ const useStyles = createStyles((theme, { size }: { size: MantineSize }) => ({
export default function CodeInput({ ...props }) {
const { classes } = useStyles({ size: 'md' }, { name: 'CodeInput' });
return (
<Textarea
classNames={{ input: classes.input }}
autoComplete='nope'
{...props}
/>
);
return <Textarea classNames={{ input: classes.input }} autoComplete='nope' {...props} />;
}

View file

@ -4,7 +4,19 @@ import { showNotification } from '@mantine/notifications';
import { relativeTime } from 'lib/utils/client';
import { useFileDelete, useFileFavorite } from 'lib/queries/files';
import { useState } from 'react';
import { CalendarIcon, ClockIcon, CopyIcon, CrossIcon, DeleteIcon, ExternalLinkIcon, FileIcon, HashIcon, ImageIcon, StarIcon, EyeIcon } from './icons';
import {
CalendarIcon,
ClockIcon,
CopyIcon,
CrossIcon,
DeleteIcon,
ExternalLinkIcon,
FileIcon,
HashIcon,
ImageIcon,
StarIcon,
EyeIcon,
} from './icons';
import MutedText from './MutedText';
import Type from './Type';
import Link from './Link';
@ -76,7 +88,9 @@ export default function File({ image, updateImages, disableMediaPreview }) {
};
const handleFavorite = async () => {
favoriteFile.mutate({ id: image.id, favorite: !image.favorite }, {
favoriteFile.mutate(
{ id: image.id, favorite: !image.favorite },
{
onSuccess: () => {
showNotification({
title: 'Image is now ' + (!image.favorite ? 'favorited' : 'unfavorited'),
@ -93,18 +107,14 @@ export default function File({ image, updateImages, disableMediaPreview }) {
icon: <CrossIcon />,
});
},
});
}
);
};
console.log(image);
return (
<>
<Modal
opened={open}
onClose={() => setOpen(false)}
title={<Title>{image.file}</Title>}
size='xl'
>
<Modal opened={open} onClose={() => setOpen(false)} title={<Title>{image.file}</Title>} size='xl'>
<LoadingOverlay visible={loading} />
<Stack>
<Type
@ -120,13 +130,19 @@ export default function File({ image, updateImages, disableMediaPreview }) {
<FileMeta Icon={FileIcon} title='Name' subtitle={image.file} />
<FileMeta Icon={ImageIcon} title='Type' subtitle={image.mimetype} />
<FileMeta Icon={EyeIcon} title='Views' subtitle={image.views} />
<FileMeta Icon={CalendarIcon} title='Uploaded at' subtitle={new Date(image.created_at).toLocaleString()} />
{image.expires_at && <FileMeta
<FileMeta
Icon={CalendarIcon}
title='Uploaded at'
subtitle={new Date(image.created_at).toLocaleString()}
/>
{image.expires_at && (
<FileMeta
Icon={ClockIcon}
title='Expires'
subtitle={relativeTime(new Date(image.expires_at))}
tooltip={new Date(image.expires_at).toLocaleString()}
/>}
/>
)}
<FileMeta Icon={HashIcon} title='ID' subtitle={image.id} />
</Stack>
</Stack>
@ -145,8 +161,20 @@ export default function File({ image, updateImages, disableMediaPreview }) {
<LoadingOverlay visible={loading} />
<Type
file={image}
sx={{ minHeight: 200, maxHeight: 320, fontSize: 70, width: '100%', cursor: 'pointer' }}
style={{ minHeight: 200, maxHeight: 320, fontSize: 70, width: '100%', cursor: 'pointer' }}
sx={{
minHeight: 200,
maxHeight: 320,
fontSize: 70,
width: '100%',
cursor: 'pointer',
}}
style={{
minHeight: 200,
maxHeight: 320,
fontSize: 70,
width: '100%',
cursor: 'pointer',
}}
src={image.url}
alt={image.file}
onClick={() => setOpen(true)}

View file

@ -1,4 +1,27 @@
import { AppShell, Box, Burger, Button, Divider, Header, MediaQuery, Navbar, NavLink, Paper, Popover, ScrollArea, Select, Stack, Text, Title, UnstyledButton, useMantineTheme, Group, Image, Tooltip, Badge } from '@mantine/core';
import {
AppShell,
Box,
Burger,
Button,
Divider,
Header,
MediaQuery,
Navbar,
NavLink,
Paper,
Popover,
ScrollArea,
Select,
Stack,
Text,
Title,
UnstyledButton,
useMantineTheme,
Group,
Image,
Tooltip,
Badge,
} from '@mantine/core';
import { useClipboard } from '@mantine/hooks';
import { useModals } from '@mantine/modals';
import { showNotification } from '@mantine/notifications';
@ -9,7 +32,24 @@ import { useRecoilState } from 'recoil';
import Link from 'next/link';
import { useRouter } from 'next/router';
import { useState } from 'react';
import { ExternalLinkIcon, ActivityIcon, CheckIcon, CopyIcon, CrossIcon, DeleteIcon, FileIcon, HomeIcon, LinkIcon, LogoutIcon, PencilIcon, SettingsIcon, TagIcon, TypeIcon, UploadIcon, UserIcon } from './icons';
import {
ExternalLinkIcon,
ActivityIcon,
CheckIcon,
CopyIcon,
CrossIcon,
DeleteIcon,
FileIcon,
HomeIcon,
LinkIcon,
LogoutIcon,
PencilIcon,
SettingsIcon,
TagIcon,
TypeIcon,
UploadIcon,
UserIcon,
} from './icons';
import { friendlyThemeName, themes } from './Theming';
function MenuItemLink(props) {
@ -23,7 +63,7 @@ function MenuItemLink(props) {
function MenuItem(props) {
return (
<UnstyledButton
sx={theme => ({
sx={(theme) => ({
display: 'block',
width: '100%',
padding: 5,
@ -47,14 +87,16 @@ function MenuItem(props) {
{...props}
>
<Group noWrap>
<Box sx={theme => ({
<Box
sx={(theme) => ({
marginRight: theme.spacing.xs / 4,
paddingLeft: theme.spacing.xs / 2,
'& *': {
display: 'block',
},
})}>
})}
>
{props.icon}
</Box>
<Text size='sm'>{props.children}</Text>
@ -101,13 +143,13 @@ const admin_items = [
icon: <UserIcon size={18} />,
text: 'Users',
link: '/dashboard/users',
if: props => true,
if: (props) => true,
},
{
icon: <TagIcon size={18} />,
text: 'Invites',
link: '/dashboard/invites',
if: props => props.invites,
if: (props) => props.invites,
},
];
@ -129,7 +171,7 @@ export default function Layout({ children, props }) {
const modals = useModals();
const clipboard = useClipboard();
const handleUpdateTheme = async value => {
const handleUpdateTheme = async (value) => {
const newUser = await useFetch('/api/user', 'PATCH', {
systemTheme: value || 'dark_blue',
});
@ -146,7 +188,8 @@ export default function Layout({ children, props }) {
});
};
const openResetToken = () => modals.openConfirmModal({
const openResetToken = () =>
modals.openConfirmModal({
title: 'Reset Token',
children: (
<Text size='sm'>
@ -167,7 +210,8 @@ export default function Layout({ children, props }) {
} else {
showNotification({
title: 'Token Reset',
message: 'Your token has been reset. You will need to update any uploaders to use this new token.',
message:
'Your token has been reset. You will need to update any uploaders to use this new token.',
color: 'green',
icon: <CheckIcon />,
});
@ -177,11 +221,13 @@ export default function Layout({ children, props }) {
},
});
const openCopyToken = () => modals.openConfirmModal({
const openCopyToken = () =>
modals.openConfirmModal({
title: 'Copy Token',
children: (
<Text size='sm'>
Make sure you don&apos;t share this token with anyone as they will be able to upload files on your behalf.
Make sure you don&apos;t share this token with anyone as they will be able to upload files on your
behalf.
</Text>
),
labels: { confirm: 'Copy', cancel: 'Cancel' },
@ -204,16 +250,8 @@ export default function Layout({ children, props }) {
navbarOffsetBreakpoint='sm'
fixed
navbar={
<Navbar
pt='sm'
hiddenBreakpoint='sm'
hidden={!opened}
width={{ sm: 200, lg: 230 }}
>
<Navbar.Section
grow
component={ScrollArea}
>
<Navbar pt='sm' hiddenBreakpoint='sm' hidden={!opened} width={{ sm: 200, lg: 230 }}>
<Navbar.Section grow component={ScrollArea}>
{items.map(({ icon, text, link }) => (
<Link href={link} key={text} passHref>
<NavLink
@ -230,9 +268,11 @@ export default function Layout({ children, props }) {
label='Administration'
icon={<SettingsIcon />}
childrenOffset={28}
defaultOpened={admin_items.map(x => x.link).includes(router.pathname)}
defaultOpened={admin_items.map((x) => x.link).includes(router.pathname)}
>
{admin_items.filter(x => x.if(props)).map(({ icon, text, link }) => (
{admin_items
.filter((x) => x.if(props))
.map(({ icon, text, link }) => (
<Link href={link} key={text} passHref>
<NavLink
component='a'
@ -247,7 +287,8 @@ export default function Layout({ children, props }) {
)}
</Navbar.Section>
<Navbar.Section>
{external_links.length ? external_links.map(({ label, link }, i) => (
{external_links.length
? external_links.map(({ label, link }, i) => (
<Link href={link} passHref key={i}>
<NavLink
label={label}
@ -257,7 +298,8 @@ export default function Layout({ children, props }) {
icon={<ExternalLinkIcon />}
/>
</Link>
)) : null}
))
: null}
</Navbar.Section>
{version.isSuccess ? (
<Navbar.Section>
@ -295,16 +337,12 @@ export default function Layout({ children, props }) {
</MediaQuery>
<Title ml='sm'>{title}</Title>
<Box sx={{ marginLeft: 'auto', marginRight: 0 }}>
<Popover
position='bottom-end'
opened={open}
onClose={() => setOpen(false)}
>
<Popover position='bottom-end' opened={open} onClose={() => setOpen(false)}>
<Popover.Target>
<Button
leftIcon={avatar ? <Image src={avatar} height={32} radius='md' /> : <SettingsIcon />}
onClick={() => setOpen((o) => !o)}
sx={t => ({
sx={(t) => ({
backgroundColor: 'inherit',
'&:hover': {
backgroundColor: t.other.hover,
@ -320,7 +358,8 @@ export default function Layout({ children, props }) {
<Popover.Dropdown p={4} mr='md' sx={{ minWidth: '200px' }}>
<Stack spacing={2}>
<Text sx={{
<Text
sx={{
color: theme.colorScheme === 'dark' ? theme.colors.dark[2] : theme.colors.gray[6],
fontWeight: 500,
fontSize: theme.fontSizes.sm,
@ -330,23 +369,48 @@ export default function Layout({ children, props }) {
>
{user.username}
</Text>
<MenuItemLink icon={<SettingsIcon />} href='/dashboard/manage'>Manage Account</MenuItemLink>
<MenuItem icon={<CopyIcon />} onClick={() => { setOpen(false); openCopyToken(); }}>Copy Token</MenuItem>
<MenuItem icon={<DeleteIcon />} onClick={() => { setOpen(false); openResetToken(); }} color='red'>Reset Token</MenuItem>
<MenuItemLink icon={<LogoutIcon />} href='/auth/logout' color='red'>Logout</MenuItemLink>
<MenuItemLink icon={<SettingsIcon />} href='/dashboard/manage'>
Manage Account
</MenuItemLink>
<MenuItem
icon={<CopyIcon />}
onClick={() => {
setOpen(false);
openCopyToken();
}}
>
Copy Token
</MenuItem>
<MenuItem
icon={<DeleteIcon />}
onClick={() => {
setOpen(false);
openResetToken();
}}
color='red'
>
Reset Token
</MenuItem>
<MenuItemLink icon={<LogoutIcon />} href='/auth/logout' color='red'>
Logout
</MenuItemLink>
<Divider
variant='solid'
my={theme.spacing.xs / 2}
sx={theme => ({
sx={(theme) => ({
width: '110%',
borderTopColor: theme.colorScheme === 'dark' ? theme.colors.dark[7] : theme.colors.gray[2],
borderTopColor:
theme.colorScheme === 'dark' ? theme.colors.dark[7] : theme.colors.gray[2],
margin: `${theme.spacing.xs / 2}px -4px`,
})}
/>
<MenuItem icon={<PencilIcon />}>
<Select
size='xs'
data={Object.keys(themes).map(t => ({ value: t, label: friendlyThemeName[t] }))}
data={Object.keys(themes).map((t) => ({
value: t,
label: friendlyThemeName[t],
}))}
value={systemTheme}
onChange={handleUpdateTheme}
/>
@ -363,7 +427,7 @@ export default function Layout({ children, props }) {
withBorder
p='md'
shadow='xs'
sx={t => ({
sx={(t) => ({
borderColor: t.colorScheme === 'dark' ? t.colors.dark[5] : t.colors.dark[0],
})}
>

View file

@ -1,5 +1,9 @@
import { Text } from '@mantine/core';
export default function MutedText({ children, ...props }) {
return <Text color='dimmed' size='xl' {...props}>{children}</Text>;
return (
<Text color='dimmed' size='xl' {...props}>
{children}
</Text>
);
}

View file

@ -6,12 +6,7 @@ import { CheckIcon, CrossIcon } from './icons';
function PasswordRequirement({ meets, label }: { meets: boolean; label: string }) {
return (
<Text
color={meets ? 'teal' : 'red'}
sx={{ display: 'flex', alignItems: 'center' }}
mt='sm'
size='sm'
>
<Text color={meets ? 'teal' : 'red'} sx={{ display: 'flex', alignItems: 'center' }} mt='sm' size='sm'>
{meets ? <CheckIcon /> : <CrossIcon />} <Box ml='md'>{label}</Box>
</Text>
);
@ -60,10 +55,7 @@ export default function PasswordStrength({ value, setValue, setStrength, ...prop
}}
>
<Popover.Target>
<div
onFocusCapture={() => setPopoverOpened(true)}
onBlurCapture={() => setPopoverOpened(false)}
>
<div onFocusCapture={() => setPopoverOpened(true)} onBlurCapture={() => setPopoverOpened(false)}>
<PasswordInput
label='Password'
description='A strong password should include letters in lower and uppercase, at least 1 number, at least 1 special symbol'

View file

@ -7,18 +7,16 @@ export function SmallTable({ rows, columns }) {
<Table highlightOnHover>
<thead>
<tr>
{columns.map(col => (
{columns.map((col) => (
<th key={randomId()}>{col.name}</th>
))}
</tr>
</thead>
<tbody>
{rows.map(row => (
{rows.map((row) => (
<tr key={randomId()}>
{columns.map(col => (
<td key={randomId()}>
{col.format ? col.format(row[col.id]) : row[col.id]}
</td>
{columns.map((col) => (
<td key={randomId()}>{col.format ? col.format(row[col.id]) : row[col.id]}</td>
))}
</tr>
))}

View file

@ -31,7 +31,7 @@ const useStyles = createStyles((theme) => ({
interface StatsGridProps {
stat: {
title: string;
icon: React.ReactNode,
icon: React.ReactNode;
value: string;
desc: string;
diff?: number;
@ -53,27 +53,14 @@ export default function StatCard({ stat }: StatsGridProps) {
<Group align='flex-end' spacing='xs' mt={25}>
<Text className={classes.value}>{stat.value}</Text>
{
typeof stat.diff == 'number' && (
{typeof stat.diff == 'number' && (
<>
<Text
color={stat.diff >= 0 ? 'teal' : 'red'}
size='sm'
weight={500}
className={classes.diff}
>
<Text color={stat.diff >= 0 ? 'teal' : 'red'} size='sm' weight={500} className={classes.diff}>
<span>{stat.diff === Infinity ? '∞' : stat.diff}%</span>
{
stat.diff >= 0 ? (
<ArrowUpRight size={16} />
) : (
<ArrowDownRight size={16} />
)
}
{stat.diff >= 0 ? <ArrowUpRight size={16} /> : <ArrowDownRight size={16} />}
</Text>
</>
)
}
)}
</Group>
<Text size='xs' color='dimmed' mt={7}>

View file

@ -20,7 +20,7 @@ import { useRecoilValue } from 'recoil';
import { userSelector } from 'lib/recoil/user';
export const themes = {
system: (colorScheme: 'dark' | 'light') => colorScheme === 'dark' ? dark_blue : light_blue,
system: (colorScheme: 'dark' | 'light') => (colorScheme === 'dark' ? dark_blue : light_blue),
dark_blue,
light_blue,
dark,
@ -34,17 +34,17 @@ export const themes = {
};
export const friendlyThemeName = {
'system': 'System Theme',
'dark_blue': 'Dark Blue',
'light_blue': 'Light Blue',
'dark': 'Very Dark',
'ayu_dark': 'Ayu Dark',
'ayu_mirage': 'Ayu Mirage',
'ayu_light': 'Ayu Light',
'nord': 'Nord',
'dracula': 'Dracula',
'matcha_dark_azul': 'Matcha Dark Azul',
'qogir_dark': 'Qogir Dark',
system: 'System Theme',
dark_blue: 'Dark Blue',
light_blue: 'Light Blue',
dark: 'Very Dark',
ayu_dark: 'Ayu Dark',
ayu_mirage: 'Ayu Mirage',
ayu_light: 'Ayu Light',
nord: 'Nord',
dracula: 'Dracula',
matcha_dark_azul: 'Matcha Dark Azul',
qogir_dark: 'Qogir Dark',
};
export default function ZiplineTheming({ Component, pageProps, ...props }) {
@ -69,14 +69,14 @@ export default function ZiplineTheming({ Component, pageProps, ...props }) {
...theme,
components: {
AppShell: {
styles: t => ({
styles: (t) => ({
root: {
backgroundColor: t.other.AppShell_backgroundColor,
},
}),
},
NavLink: {
styles: t => ({
styles: (t) => ({
icon: {
paddingLeft: t.spacing.sm,
},
@ -101,14 +101,14 @@ export default function ZiplineTheming({ Component, pageProps, ...props }) {
},
},
Card: {
styles: t => ({
styles: (t) => ({
root: {
backgroundColor: t.colorScheme === 'dark' ? t.colors.dark[6] : t.colors.gray[0],
},
}),
},
Image: {
styles: t => ({
styles: (t) => ({
placeholder: {
backgroundColor: t.colorScheme === 'dark' ? t.colors.dark[6] : t.colors.gray[0],
},

View file

@ -7,18 +7,23 @@ function Placeholder({ text, Icon, ...props }) {
if (props.disableResolve) props.src = null;
return (
<Image height={200} withPlaceholder placeholder={
<Image
height={200}
withPlaceholder
placeholder={
<Group>
<Icon size={48} />
<Text size='md'>{text}</Text>
</Group>
} {...props} />
}
{...props}
/>
);
}
export default function Type({ file, popup = false, disableMediaPreview, ...props }){
export default function Type({ file, popup = false, disableMediaPreview, ...props }) {
const type = (file.type || file.mimetype).split('/')[0];
const name = (file.name || file.file);
const name = file.name || file.file;
const media = /^(video|audio|image|text)/.test(type);
@ -36,18 +41,34 @@ export default function Type({ file, popup = false, disableMediaPreview, ...prop
}
if (media && disableMediaPreview) {
return <Placeholder Icon={FileIcon} text={`Click to view file (${name})`} disableResolve={true} {...props} />;
};
return (
<Placeholder Icon={FileIcon} text={`Click to view file (${name})`} disableResolve={true} {...props} />
);
}
return popup ? (media ? {
'video': <video width='100%' autoPlay controls {...props} />,
'image': <Image {...props} />,
'audio': <audio autoPlay controls {...props} style={{ width: '100%' }}/>,
'text': <Prism withLineNumbers language={name.split('.').pop()} {...props} style={{}} sx={{}}>{text}</Prism>,
}[type]: <Text>Can&apos;t preview {file.type || file.mimetype}</Text>) : (media ? {
'video': <Placeholder Icon={PlayIcon} text={`Click to view video (${name})`} {...props} />,
'image': <Image {...props} />,
'audio': <Placeholder Icon={AudioIcon} text={`Click to view audio (${name})`} {...props}/>,
'text': <Placeholder Icon={FileIcon} text={`Click to view text file (${name})`} {...props}/>,
}[type] : <Placeholder Icon={FileIcon} text={`Click to view file (${name})`} {...props}/>);
};
return popup ? (
media ? (
{
video: <video width='100%' autoPlay controls {...props} />,
image: <Image {...props} />,
audio: <audio autoPlay controls {...props} style={{ width: '100%' }} />,
text: (
<Prism withLineNumbers language={name.split('.').pop()} {...props} style={{}} sx={{}}>
{text}
</Prism>
),
}[type]
) : (
<Text>Can&apos;t preview {file.type || file.mimetype}</Text>
)
) : media ? (
{
video: <Placeholder Icon={PlayIcon} text={`Click to view video (${name})`} {...props} />,
image: <Image {...props} />,
audio: <Placeholder Icon={AudioIcon} text={`Click to view audio (${name})`} {...props} />,
text: <Placeholder Icon={FileIcon} text={`Click to view text file (${name})`} {...props} />,
}[type]
) : (
<Placeholder Icon={FileIcon} text={`Click to view file (${name})`} {...props} />
);
}

View file

@ -16,9 +16,7 @@ export default function Dropzone({ loading, onDrop, children }) {
</Text>
</Group>
<div style={{ pointerEvents: 'all' }}>
{children}
</div>
<div style={{ pointerEvents: 'all' }}>{children}</div>
</MantineDropzone>
);
}

View file

@ -46,9 +46,7 @@ export default function FileDropzone({ file }: { file: File }) {
</div>
}
>
<Badge size='lg'>
{file.name}
</Badge>
<Badge size='lg'>{file.name}</Badge>
</Tooltip>
);
}

View file

@ -3,5 +3,12 @@
import Image from 'next/image';
export default function DiscordIcon({ ...props }) {
return <Image src='https://assets-global.website-files.com/6257adef93867e50d84d30e2/62595384f934b806f37f4956_145dc557845548a36a82337912ca3ac5.svg' width={24} height={24} {...props} />;
return (
<Image
src='https://assets-global.website-files.com/6257adef93867e50d84d30e2/62595384f934b806f37f4956_145dc557845548a36a82337912ca3ac5.svg'
width={24}
height={24}
{...props}
/>
);
}

View file

@ -3,5 +3,12 @@
import Image from 'next/image';
export default function FlameshotIcon({ ...props }) {
return <Image src='https://raw.githubusercontent.com/flameshot-org/flameshot/master/data/img/app/flameshot.svg' width={24} height={24} {...props} />;
return (
<Image
src='https://raw.githubusercontent.com/flameshot-org/flameshot/master/data/img/app/flameshot.svg'
width={24}
height={24}
{...props}
/>
);
}

View file

@ -12,19 +12,19 @@ export default function RecentFiles({ disableMediaPreview }) {
<>
<Title>Recent Files</Title>
<SimpleGrid
cols={(recent.isSuccess && recent.data.length === 0) ? 1 : 4}
cols={recent.isSuccess && recent.data.length === 0 ? 1 : 4}
spacing='lg'
breakpoints={[
{ maxWidth: 'sm', cols: 1, spacing: 'sm' },
]}
breakpoints={[{ maxWidth: 'sm', cols: 1, spacing: 'sm' }]}
>
{
recent.isSuccess
? (
recent.data.length > 0
? (
recent.data.map(image => (
<File key={randomId()} image={image} updateImages={invalidateFiles} disableMediaPreview={disableMediaPreview} />
{recent.isSuccess ? (
recent.data.length > 0 ? (
recent.data.map((image) => (
<File
key={randomId()}
image={image}
updateImages={invalidateFiles}
disableMediaPreview={disableMediaPreview}
/>
))
) : (
<MantineCard shadow='md'>
@ -42,13 +42,12 @@ export default function RecentFiles({ disableMediaPreview }) {
</MantineCard>
)
) : (
[1, 2, 3, 4].map(x => (
[1, 2, 3, 4].map((x) => (
<div key={x}>
<Skeleton width='100%' height={220} sx={{ borderRadius: 1 }} />
</div>
))
)
}
)}
</SimpleGrid>
</>
);

View file

@ -18,44 +18,51 @@ export function StatCards() {
{ maxWidth: 'xs', cols: 1 },
]}
>
<StatCard stat={{
<StatCard
stat={{
title: 'UPLOADED FILES',
value: stats.isSuccess ? latest.data.count.toLocaleString() : '...',
desc: 'files have been uploaded',
icon: (
<FileIcon />
),
diff: stats.isSuccess && before?.data ? percentChange(before.data.count, latest.data.count) : undefined,
}}/>
icon: <FileIcon />,
diff:
stats.isSuccess && before?.data ? percentChange(before.data.count, latest.data.count) : undefined,
}}
/>
<StatCard stat={{
<StatCard
stat={{
title: 'STORAGE',
value: stats.isSuccess ? latest.data.size : '...',
desc: 'of storage used',
icon: (
<Database size={15} />
),
diff: stats.isSuccess && before?.data ? percentChange(before.data.size_num, latest.data.size_num) : undefined,
}}/>
icon: <Database size={15} />,
diff:
stats.isSuccess && before?.data
? percentChange(before.data.size_num, latest.data.size_num)
: undefined,
}}
/>
<StatCard stat={{
<StatCard
stat={{
title: 'VIEWS',
value: stats.isSuccess ? latest.data.views_count.toLocaleString() : '...',
desc: 'total page views',
icon: (
<Eye size={15} />
),
diff: stats.isSuccess && before?.data ? percentChange(before.data.views_count, latest.data.views_count) : undefined,
}}/>
icon: <Eye size={15} />,
diff:
stats.isSuccess && before?.data
? percentChange(before.data.views_count, latest.data.views_count)
: undefined,
}}
/>
<StatCard stat={{
<StatCard
stat={{
title: 'USERS',
value: stats.isSuccess ? latest.data.count_users.toLocaleString() : '...',
desc: 'total registered users',
icon: (
<Users size={15} />
),
}}/>
icon: <Users size={15} />,
}}
/>
</SimpleGrid>
);
}

View file

@ -29,7 +29,9 @@ export default function Dashboard({ disableMediaPreview }) {
};
const deleteImage = async ({ original }) => {
const res = await useFetch('/api/user/files', 'DELETE', { id: original.id });
const res = await useFetch('/api/user/files', 'DELETE', {
id: original.id,
});
if (!res.error) {
updateImages();
showNotification({
@ -46,7 +48,6 @@ export default function Dashboard({ disableMediaPreview }) {
icon: <CrossIcon />,
});
}
};
const copyImage = async ({ original }) => {
@ -65,7 +66,9 @@ export default function Dashboard({ disableMediaPreview }) {
return (
<div>
<Title>Welcome back, {user?.username}</Title>
<MutedText size='md'>You have <b>{images.isSuccess ? images.data.length : '...'}</b> files</MutedText>
<MutedText size='md'>
You have <b>{images.isSuccess ? images.data.length : '...'}</b> files
</MutedText>
<StatCards />
@ -73,7 +76,9 @@ export default function Dashboard({ disableMediaPreview }) {
<section>
<Title>Files</Title>
<MutedText size='md'>View your gallery <Link href='/dashboard/files'>here</Link>.</MutedText>
<MutedText size='md'>
View your gallery <Link href='/dashboard/files'>here</Link>.
</MutedText>
<DataGrid
data={images.data ?? []}
loading={images.isLoading}
@ -124,7 +129,6 @@ export default function Dashboard({ disableMediaPreview }) {
},
}}
empty={<></>}
columns={[
{
accessorKey: 'file',

View file

@ -29,35 +29,26 @@ export default function FilePagation({ disableMediaPreview }) {
return (
<>
<SimpleGrid
cols={3}
spacing='lg'
breakpoints={[
{ maxWidth: 'sm', cols: 1, spacing: 'sm' },
]}
>
{
(pages.isSuccess)
<SimpleGrid cols={3} spacing='lg' breakpoints={[{ maxWidth: 'sm', cols: 1, spacing: 'sm' }]}>
{pages.isSuccess
? pages.data.length
? (
pages.data[(page - 1) ?? 0].map(image => (
? pages.data[page - 1 ?? 0].map((image) => (
<div key={image.id}>
<File image={image} updateImages={() => pages.refetch()} disableMediaPreview={disableMediaPreview} />
<File
image={image}
updateImages={() => pages.refetch()}
disableMediaPreview={disableMediaPreview}
/>
</div>
))
) : (
null
)
: (
[1,2,3,4].map(x => (
: null
: [1, 2, 3, 4].map((x) => (
<div key={x}>
<Skeleton width='100%' height={220} sx={{ borderRadius: 1 }}/>
<Skeleton width='100%' height={220} sx={{ borderRadius: 1 }} />
</div>
))
)
}
))}
</SimpleGrid>
{(pages.isSuccess && pages.data.length) ? (
{pages.isSuccess && pages.data.length ? (
<Box
sx={{
display: 'flex',
@ -68,8 +59,12 @@ export default function FilePagation({ disableMediaPreview }) {
}}
>
<div></div>
<Pagination total={pages.data?.length ?? 0} page={page} onChange={setPage}/>
<Checkbox label='Show non-media files' checked={checked} onChange={(event) => setChecked(event.currentTarget.checked)} />
<Pagination total={pages.data?.length ?? 0} page={page} onChange={setPage} />
<Checkbox
label='Show non-media files'
checked={checked}
onChange={(event) => setChecked(event.currentTarget.checked)}
/>
</Box>
) : null}
</>

View file

@ -11,7 +11,7 @@ export default function Files({ disableMediaPreview }) {
const favoritePages = usePaginatedFiles({ favorite: 'media' });
const [favoritePage, setFavoritePage] = useState(1);
const updatePages = async favorite => {
const updatePages = async (favorite) => {
pages.refetch();
if (favorite) {
@ -24,31 +24,28 @@ export default function Files({ disableMediaPreview }) {
<Group mb='md'>
<Title>Files</Title>
<Link href='/dashboard/upload' passHref>
<ActionIcon component='a' variant='filled' color='primary'><PlusIcon/></ActionIcon>
<ActionIcon component='a' variant='filled' color='primary'>
<PlusIcon />
</ActionIcon>
</Link>
</Group>
{
(favoritePages.isSuccess && favoritePages.data.length)
? (
<Accordion
variant='contained'
mb='sm'
>
{favoritePages.isSuccess && favoritePages.data.length ? (
<Accordion variant='contained' mb='sm'>
<Accordion.Item value='favorite'>
<Accordion.Control>Favorite Files</Accordion.Control>
<Accordion.Panel>
<SimpleGrid
cols={3}
spacing='lg'
breakpoints={[
{ maxWidth: 'sm', cols: 1, spacing: 'sm' },
]}
>
{(favoritePages.isSuccess && favoritePages.data.length) ? favoritePages.data[(favoritePage - 1) ?? 0].map(image => (
<SimpleGrid cols={3} spacing='lg' breakpoints={[{ maxWidth: 'sm', cols: 1, spacing: 'sm' }]}>
{favoritePages.isSuccess && favoritePages.data.length
? favoritePages.data[favoritePage - 1 ?? 0].map((image) => (
<div key={image.id}>
<File image={image} updateImages={() => updatePages(true)} disableMediaPreview={disableMediaPreview} />
<File
image={image}
updateImages={() => updatePages(true)}
disableMediaPreview={disableMediaPreview}
/>
</div>
)) : null}
))
: null}
</SimpleGrid>
<Box
sx={{
@ -59,13 +56,16 @@ export default function Files({ disableMediaPreview }) {
paddingBottom: 3,
}}
>
<Pagination total={favoritePages.data.length} page={favoritePage} onChange={setFavoritePage} />
<Pagination
total={favoritePages.data.length}
page={favoritePage}
onChange={setFavoritePage}
/>
</Box>
</Accordion.Panel>
</Accordion.Item>
</Accordion>
) : null
}
) : null}
<FilePagation disableMediaPreview={disableMediaPreview} />
</>

View file

@ -1,4 +1,17 @@
import { ActionIcon, Avatar, Button, Card, Group, Modal, NumberInput, Select, SimpleGrid, Skeleton, Stack, Title } from '@mantine/core';
import {
ActionIcon,
Avatar,
Button,
Card,
Group,
Modal,
NumberInput,
Select,
SimpleGrid,
Skeleton,
Stack,
Title,
} from '@mantine/core';
import { useClipboard } from '@mantine/hooks';
import { useForm } from '@mantine/form';
import { useModals } from '@mantine/modals';
@ -9,17 +22,7 @@ import useFetch from 'hooks/useFetch';
import { useRouter } from 'next/router';
import { useEffect, useState } from 'react';
const expires = [
'30m',
'1h',
'6h',
'12h',
'1d',
'3d',
'5d',
'7d',
'never',
];
const expires = ['30m', '1h', '6h', '12h', '1d', '3d', '5d', '7d', 'never'];
function CreateInviteModal({ open, setOpen, updateInvites }) {
const form = useForm({
@ -29,10 +32,15 @@ function CreateInviteModal({ open, setOpen, updateInvites }) {
},
});
const onSubmit = async values => {
const onSubmit = async (values) => {
if (!expires.includes(values.expires)) return form.setFieldError('expires', 'Invalid expiration');
if (values.count < 1 || values.count > 100) return form.setFieldError('count', 'Must be between 1 and 100');
const expires_at = values.expires === 'never' ? null : new Date({
if (values.count < 1 || values.count > 100)
return form.setFieldError('count', 'Must be between 1 and 100');
const expires_at =
values.expires === 'never'
? null
: new Date(
{
'30m': Date.now() + 30 * 60 * 1000,
'1h': Date.now() + 60 * 60 * 1000,
'6h': Date.now() + 6 * 60 * 60 * 1000,
@ -40,7 +48,8 @@ function CreateInviteModal({ open, setOpen, updateInvites }) {
'1d': Date.now() + 24 * 60 * 60 * 1000,
'5d': Date.now() + 5 * 24 * 60 * 60 * 1000,
'7d': Date.now() + 7 * 24 * 60 * 60 * 1000,
}[values.expires]);
}[values.expires]
);
setOpen(false);
@ -69,12 +78,8 @@ function CreateInviteModal({ open, setOpen, updateInvites }) {
};
return (
<Modal
opened={open}
onClose={() => setOpen(false)}
title={<Title>Create Invite</Title>}
>
<form onSubmit={form.onSubmit(v => onSubmit(v))}>
<Modal opened={open} onClose={() => setOpen(false)} title={<Title>Create Invite</Title>}>
<form onSubmit={form.onSubmit((v) => onSubmit(v))}>
<Select
label='Expires'
id='expires'
@ -100,7 +105,7 @@ function CreateInviteModal({ open, setOpen, updateInvites }) {
min={1}
stepHoldDelay={200}
stepHoldInterval={100}
parser={(v:string) => Number(v.replace(/[^\d]/g, ''))}
parser={(v: string) => Number(v.replace(/[^\d]/g, ''))}
/>
<Group position='right' mt={22}>
@ -120,7 +125,8 @@ export default function Users() {
const [invites, setInvites] = useState([]);
const [open, setOpen] = useState(false);
const openDeleteModal = invite => modals.openConfirmModal({
const openDeleteModal = (invite) =>
modals.openConfirmModal({
title: `Delete ${invite.code}?`,
centered: true,
overlayBlur: 3,
@ -147,7 +153,7 @@ export default function Users() {
},
});
const handleCopy = async invite => {
const handleCopy = async (invite) => {
clipboard.copy(`${window.location.protocol}//${window.location.host}/invite/${invite.code}`);
showNotification({
title: 'Copied to clipboard',
@ -162,7 +168,7 @@ export default function Users() {
setInvites(us);
} else {
router.push('/dashboard');
};
}
};
useEffect(() => {
@ -174,24 +180,28 @@ export default function Users() {
<CreateInviteModal open={open} setOpen={setOpen} updateInvites={updateInvites} />
<Group mb='md'>
<Title>Invites</Title>
<ActionIcon variant='filled' color='primary' onClick={() => setOpen(true)}><PlusIcon /></ActionIcon>
<ActionIcon variant='filled' color='primary' onClick={() => setOpen(true)}>
<PlusIcon />
</ActionIcon>
</Group>
<SimpleGrid
cols={3}
spacing='lg'
breakpoints={[
{ maxWidth: 'sm', cols: 1, spacing: 'sm' },
]}
>
{invites.length ? invites.map(invite => (
<SimpleGrid cols={3} spacing='lg' breakpoints={[{ maxWidth: 'sm', cols: 1, spacing: 'sm' }]}>
{invites.length
? invites.map((invite) => (
<Card key={invite.id} sx={{ maxWidth: '100%' }}>
<Group position='apart'>
<Group position='left'>
<Avatar size='lg' color={invite.used ? 'dark' : 'primary'}>{invite.id}</Avatar>
<Avatar size='lg' color={invite.used ? 'dark' : 'primary'}>
{invite.id}
</Avatar>
<Stack spacing={0}>
<Title>{invite.code}{invite.used && <> (Used)</>}</Title>
<Title>
{invite.code}
{invite.used && <> (Used)</>}
</Title>
<MutedText size='sm'>Created: {new Date(invite.created_at).toLocaleString()}</MutedText>
<MutedText size='sm'>Expires: {invite.expires_at ? new Date(invite.expires_at).toLocaleString() : 'Never'}</MutedText>
<MutedText size='sm'>
Expires: {invite.expires_at ? new Date(invite.expires_at).toLocaleString() : 'Never'}
</MutedText>
</Stack>
</Group>
<Group position='right'>
@ -204,9 +214,8 @@ export default function Users() {
</Group>
</Group>
</Card>
)) : [1, 2, 3].map(x => (
<Skeleton key={x} width='100%' height={100} radius='sm' />
))}
))
: [1, 2, 3].map((x) => <Skeleton key={x} width='100%' height={100} radius='sm' />)}
</SimpleGrid>
</>
);

View file

@ -1,7 +1,7 @@
import { GeneratorModal } from './GeneratorModal';
export default function Flameshot({ user, open, setOpen }) {
const onSubmit = values => {
const onSubmit = (values) => {
const curl = [
'curl',
'-H',
@ -10,7 +10,12 @@ export default function Flameshot({ user, open, setOpen }) {
`"authorization: ${user?.token}"`,
'-F',
'file=@/tmp/ss.png',
`${window.location.protocol + '//' + window.location.hostname + (window.location.port ? ':' + window.location.port : '')}/api/upload`,
`${
window.location.protocol +
'//' +
window.location.hostname +
(window.location.port ? ':' + window.location.port : '')
}/api/upload`,
];
const extraHeaders = {};
@ -58,11 +63,13 @@ ${curl.join(' ')} | jq -r '.files[0]' | tr -d '\n' | xsel -ib;
pseudoElement.parentNode.removeChild(pseudoElement);
};
return <GeneratorModal
return (
<GeneratorModal
opened={open}
onClose={() => setOpen(false)}
title='Flameshot'
desc='To use this script, you need Flameshot, curl, jq, and xsel installed. This script is intended for use on Linux only.'
onSubmit={onSubmit}
/>;
/>
);
}

View file

@ -13,14 +13,9 @@ export function GeneratorModal({ opened, onClose, title, onSubmit, ...other }) {
});
return (
<Modal
opened={opened}
onClose={onClose}
title={<Title order={3}>{title}</Title>}
size='lg'
>
<Modal opened={opened} onClose={onClose} title={<Title order={3}>{title}</Title>} size='lg'>
{other.desc && <Text>{other.desc}</Text>}
<form onSubmit={form.onSubmit(values => onSubmit(values))}>
<form onSubmit={form.onSubmit((values) => onSubmit(values))}>
<Select
label='Select file name format'
data={[
@ -34,7 +29,7 @@ export function GeneratorModal({ opened, onClose, title, onSubmit, ...other }) {
/>
<NumberInput
label={'Image Compression (leave at 0 if you don\'t want to compress)'}
label={"Image Compression (leave at 0 if you don't want to compress)"}
max={100}
min={0}
mt='md'
@ -48,26 +43,15 @@ export function GeneratorModal({ opened, onClose, title, onSubmit, ...other }) {
id='zeroWidthSpace'
{...form.getInputProps('zeroWidthSpace', { type: 'checkbox' })}
/>
<Checkbox
label='Embed'
id='embed'
{...form.getInputProps('embed', { type: 'checkbox' })}
/>
<Checkbox label='Embed' id='embed' {...form.getInputProps('embed', { type: 'checkbox' })} />
</Group>
<Group grow>
<Button
mt='md'
onClick={form.reset}
>
<Button mt='md' onClick={form.reset}>
Reset
</Button>
<Button
mt='md'
rightIcon={<DownloadIcon />}
type='submit'
>
<Button mt='md' rightIcon={<DownloadIcon />} type='submit'>
Download
</Button>
</Group>

View file

@ -7,7 +7,12 @@ export default function ShareX({ user, open, setOpen }) {
Name: 'Zipline',
DestinationType: 'ImageUploader, TextUploader',
RequestMethod: 'POST',
RequestURL: `${window.location.protocol + '//' + window.location.hostname + (window.location.port ? ':' + window.location.port : '')}/api/upload`,
RequestURL: `${
window.location.protocol +
'//' +
window.location.hostname +
(window.location.port ? ':' + window.location.port : '')
}/api/upload`,
Headers: {
Authorization: user?.token,
},
@ -16,7 +21,7 @@ export default function ShareX({ user, open, setOpen }) {
FileFormName: 'file',
});
const onSubmit = values => {
const onSubmit = (values) => {
if (values.format !== 'RANDOM') {
config.Headers['Format'] = values.format;
setConfig(config);
@ -50,7 +55,10 @@ export default function ShareX({ user, open, setOpen }) {
}
const pseudoElement = document.createElement('a');
pseudoElement.setAttribute('href', 'data:application/json;charset=utf-8,' + encodeURIComponent(JSON.stringify(config, null, '\t')));
pseudoElement.setAttribute(
'href',
'data:application/json;charset=utf-8,' + encodeURIComponent(JSON.stringify(config, null, '\t'))
);
pseudoElement.setAttribute('download', 'zipline.sxcu');
pseudoElement.style.display = 'none';
document.body.appendChild(pseudoElement);
@ -58,10 +66,5 @@ export default function ShareX({ user, open, setOpen }) {
pseudoElement.parentNode.removeChild(pseudoElement);
};
return <GeneratorModal
opened={open}
onClose={() => setOpen(false)}
title='ShareX'
onSubmit={onSubmit}
/>;
return <GeneratorModal opened={open} onClose={() => setOpen(false)} title='ShareX' onSubmit={onSubmit} />;
}

View file

@ -1,9 +1,30 @@
import { Box, Button, Card, ColorInput, FileInput, Group, Image, PasswordInput, Space, Text, TextInput, Title, Tooltip } from '@mantine/core';
import {
Box,
Button,
Card,
ColorInput,
FileInput,
Group,
Image,
PasswordInput,
Space,
Text,
TextInput,
Title,
Tooltip,
} from '@mantine/core';
import { useForm } from '@mantine/form';
import { randomId, useInterval } from '@mantine/hooks';
import { useModals } from '@mantine/modals';
import { showNotification, updateNotification } from '@mantine/notifications';
import { CrossIcon, DeleteIcon, FlameshotIcon, RefreshIcon, SettingsIcon, ShareXIcon } from 'components/icons';
import {
CrossIcon,
DeleteIcon,
FlameshotIcon,
RefreshIcon,
SettingsIcon,
ShareXIcon,
} from 'components/icons';
import DownloadIcon from 'components/icons/DownloadIcon';
import Link from 'components/Link';
import MutedText from 'components/MutedText';
@ -17,7 +38,15 @@ import Flameshot from './Flameshot';
import ShareX from './ShareX';
function ExportDataTooltip({ children }) {
return <Tooltip position='top' color='' label='After clicking, if you have a lot of files the export can take a while to complete. A list of previous exports will be below to download.'>{children}</Tooltip>;
return (
<Tooltip
position='top'
color=''
label='After clicking, if you have a lot of files the export can take a while to complete. A list of previous exports will be below to download.'
>
{children}
</Tooltip>
);
}
export default function Manage() {
@ -70,7 +99,7 @@ export default function Manage() {
if (newUser.error) {
updateNotification({
id: 'update-user',
title: 'Couldn\'t save user',
title: "Couldn't save user",
message: newUser.error,
color: 'red',
icon: <CrossIcon />,
@ -96,14 +125,14 @@ export default function Manage() {
},
});
const onSubmit = async values => {
const onSubmit = async (values) => {
const cleanUsername = values.username.trim();
const cleanPassword = values.password.trim();
const cleanEmbedTitle = values.embedTitle.trim();
const cleanEmbedColor = values.embedColor.trim();
const cleanEmbedSiteName = values.embedSiteName.trim();
if (cleanUsername === '') return form.setFieldError('username', 'Username can\'t be nothing');
if (cleanUsername === '') return form.setFieldError('username', "Username can't be nothing");
showNotification({
id: 'update-user',
@ -119,7 +148,10 @@ export default function Manage() {
embedTitle: cleanEmbedTitle === '' ? null : cleanEmbedTitle,
embedColor: cleanEmbedColor === '' ? null : cleanEmbedColor,
embedSiteName: cleanEmbedSiteName === '' ? null : cleanEmbedSiteName,
domains: values.domains.split(/\s?,\s?/).map(x => x.trim()).filter(x => x !== ''),
domains: values.domains
.split(/\s?,\s?/)
.map((x) => x.trim())
.filter((x) => x !== ''),
};
const newUser = await useFetch('/api/user', 'PATCH', data);
@ -128,22 +160,26 @@ export default function Manage() {
if (newUser.invalidDomains) {
updateNotification({
id: 'update-user',
message: <>
<Text mt='xs'>The following domains are invalid:</Text>
{newUser.invalidDomains.map(err => (
message: (
<>
<Text color='gray' key={randomId()}>{err.domain}: {err.reason}</Text>
<Text mt='xs'>The following domains are invalid:</Text>
{newUser.invalidDomains.map((err) => (
<>
<Text color='gray' key={randomId()}>
{err.domain}: {err.reason}
</Text>
<Space h='md' />
</>
))}
</>,
</>
),
color: 'red',
icon: <CrossIcon />,
});
}
updateNotification({
id: 'update-user',
title: 'Couldn\'t save user',
title: "Couldn't save user",
message: newUser.error,
color: 'red',
icon: <CrossIcon />,
@ -164,7 +200,8 @@ export default function Manage() {
showNotification({
title: 'Export started...',
loading: true,
message: 'If you have a lot of files, the export may take a while. The list of exports will be updated every 30s.',
message:
'If you have a lot of files, the export may take a while. The list of exports will be updated every 30s.',
});
} else {
showNotification({
@ -179,11 +216,15 @@ export default function Manage() {
const getExports = async () => {
const res = await useFetch('/api/user/export');
setExports(res.exports.map(s => ({
setExports(
res.exports
.map((s) => ({
date: new Date(Number(s.name.split('_')[3].slice(0, -4))),
size: s.size,
full: s.name,
})).sort((a, b) => a.date.getTime() - b.date.getTime()));
}))
.sort((a, b) => a.date.getTime() - b.date.getTime())
);
};
const handleDelete = async () => {
@ -193,7 +234,7 @@ export default function Manage() {
if (!res.count) {
showNotification({
title: 'Couldn\'t delete files',
title: "Couldn't delete files",
message: res.error,
color: 'red',
icon: <CrossIcon />,
@ -208,7 +249,8 @@ export default function Manage() {
}
};
const openDeleteModal = () => modals.openConfirmModal({
const openDeleteModal = () =>
modals.openConfirmModal({
title: 'Are you sure you want to delete all of your files?',
closeOnConfirm: false,
labels: { confirm: 'Yes', cancel: 'No' },
@ -236,30 +278,49 @@ export default function Manage() {
return (
<>
<Title>Manage User</Title>
<MutedText size='md'>Want to use variables in embed text? Visit <Link href='https://zipline.diced.tech/docs/guides/variables'>the docs</Link> for variables</MutedText>
<MutedText size='md'>
Want to use variables in embed text? Visit{' '}
<Link href='https://zipline.diced.tech/docs/guides/variables'>the docs</Link> for variables
</MutedText>
<form onSubmit={form.onSubmit((v) => onSubmit(v))}>
<TextInput id='username' label='Username' {...form.getInputProps('username')} />
<PasswordInput id='password' label='Password' description='Leave blank to keep your old password' {...form.getInputProps('password')} />
<PasswordInput
id='password'
label='Password'
description='Leave blank to keep your old password'
{...form.getInputProps('password')}
/>
<TextInput id='embedTitle' label='Embed Title' {...form.getInputProps('embedTitle')} />
<ColorInput id='embedColor' label='Embed Color' {...form.getInputProps('embedColor')} />
<TextInput id='embedSiteName' label='Embed Site Name' {...form.getInputProps('embedSiteName')} />
<TextInput id='domains' label='Domains' description='A list of domains separated by commas. These domains will be used to randomly output a domain when uploading. This is optional.' placeholder='https://example.com, https://example2.com' {...form.getInputProps('domains')} />
<TextInput
id='domains'
label='Domains'
description='A list of domains separated by commas. These domains will be used to randomly output a domain when uploading. This is optional.'
placeholder='https://example.com, https://example2.com'
{...form.getInputProps('domains')}
/>
<Group position='right' mt='md'>
<Button
type='submit'
>Save User</Button>
<Button type='submit'>Save User</Button>
</Group>
</form>
<Box mb='md'>
<Title>Avatar</Title>
<FileInput placeholder='Click to upload a file' id='file' description='Add a custom avatar or leave blank for none' accept='image/png,image/jpeg,image/gif' value={file} onChange={handleAvatarChange} />
<FileInput
placeholder='Click to upload a file'
id='file'
description='Add a custom avatar or leave blank for none'
accept='image/png,image/jpeg,image/gif'
value={file}
onChange={handleAvatarChange}
/>
<Card mt='md'>
<Text>Preview:</Text>
<Button
leftIcon={fileDataURL ? <Image src={fileDataURL} height={32} radius='md' /> : <SettingsIcon />}
sx={t => ({
sx={(t) => ({
backgroundColor: '#00000000',
'&:hover': {
backgroundColor: t.other.hover,
@ -273,8 +334,16 @@ export default function Manage() {
</Card>
<Group position='right' mt='md'>
<Button onClick={() => { setFile(null); setFileDataURL(null); }} color='red'>Reset</Button>
<Button onClick={saveAvatar} >Save Avatar</Button>
<Button
onClick={() => {
setFile(null);
setFileDataURL(null);
}}
color='red'
>
Reset
</Button>
<Button onClick={saveAvatar}>Save Avatar</Button>
</Group>
</Box>
@ -284,9 +353,17 @@ export default function Manage() {
</Box>
<Group>
<Button onClick={openDeleteModal} rightIcon={<DeleteIcon />} color='red'>Delete All Data</Button>
<ExportDataTooltip><Button onClick={exportData} rightIcon={<DownloadIcon />}>Export Data</Button></ExportDataTooltip>
<Button onClick={getExports} rightIcon={<RefreshIcon />}>Refresh</Button>
<Button onClick={openDeleteModal} rightIcon={<DeleteIcon />} color='red'>
Delete All Data
</Button>
<ExportDataTooltip>
<Button onClick={exportData} rightIcon={<DownloadIcon />}>
Export Data
</Button>
</ExportDataTooltip>
<Button onClick={getExports} rightIcon={<RefreshIcon />}>
Refresh
</Button>
</Group>
<Card mt={22}>
{exports && exports.length ? (
@ -296,11 +373,16 @@ export default function Manage() {
{ id: 'date', name: 'Date' },
{ id: 'size', name: 'Size' },
]}
rows={exports ? exports.map((x, i) => ({
rows={
exports
? exports.map((x, i) => ({
name: <Link href={'/api/user/export?name=' + x.full}>Export {i + 1}</Link>,
date: x.date.toLocaleString(),
size: bytesToRead(x.size),
})) : []} />
}))
: []
}
/>
) : (
<Text>No exports yet</Text>
)}
@ -308,8 +390,12 @@ export default function Manage() {
<Title my='md'>Uploaders</Title>
<Group>
<Button size='xl' onClick={() => setShareXOpen(true)} rightIcon={<ShareXIcon />}>Generate ShareX Config</Button>
<Button size='xl' onClick={() => setFlameshotOpen(true)} rightIcon={<FlameshotIcon />}>Generate Flameshot Script</Button>
<Button size='xl' onClick={() => setShareXOpen(true)} rightIcon={<ShareXIcon />}>
Generate ShareX Config
</Button>
<Button size='xl' onClick={() => setFlameshotOpen(true)} rightIcon={<FlameshotIcon />}>
Generate Flameshot Script
</Button>
</Group>
<ShareX user={user} open={shareXOpen} setOpen={setShareXOpen} />

View file

@ -1,5 +1,16 @@
import { Box, Card, Grid, LoadingOverlay, MantineTheme, Title, useMantineTheme } from '@mantine/core';
import { ArcElement, CategoryScale, Chart as ChartJS, ChartData, ChartOptions, LinearScale, LineController, LineElement, PointElement, Tooltip } from 'chart.js';
import {
ArcElement,
CategoryScale,
Chart as ChartJS,
ChartData,
ChartOptions,
LinearScale,
LineController,
LineElement,
PointElement,
Tooltip,
} from 'chart.js';
import ChartDataLabels from 'chartjs-plugin-datalabels';
import ColorHash from 'color-hash';
import { bytesToRead } from 'lib/utils/client';
@ -49,13 +60,12 @@ const CHART_OPTIONS = (theme: MantineTheme): ChartOptions => ({
},
});
type LineChartData = ChartData<'line', number[], string>;
type ChartDataMemo = {
views: LineChartData,
uploads: LineChartData,
uploadTypes: ChartData<'pie', number[], string>,
storage: LineChartData,
views: LineChartData;
uploads: LineChartData;
uploadTypes: ChartData<'pie', number[], string>;
storage: LineChartData;
} | void;
export default function Graphs() {
@ -77,41 +87,49 @@ export default function Graphs() {
return {
views: {
labels,
datasets: [{
datasets: [
{
label: 'Views',
data: viewData,
borderColor: theme.colors.blue[6],
backgroundColor: theme.colors.blue[0],
}],
},
],
},
uploads: {
labels,
datasets: [{
datasets: [
{
label: 'Uploads',
data: uploadData,
borderColor: theme.colors.blue[6],
backgroundColor: theme.colors.blue[0],
}],
},
],
},
uploadTypes: {
labels: latest?.data.types_count.map((x) => x.mimetype),
datasets: [{
datasets: [
{
data: latest?.data.types_count.map((x) => x.count),
label: 'Upload Types',
backgroundColor: latest?.data.types_count.map((x) => hash.hex(x.mimetype)),
}],
},
],
},
storage: {
labels,
datasets: [{
datasets: [
{
label: 'Storage',
data: storageData,
borderColor: theme.colors.blue[6],
backgroundColor: theme.colors.blue[0],
}],
},
],
},
};
}, [historicalStats]);
@ -125,11 +143,9 @@ export default function Graphs() {
<Grid.Col md={12} lg={4}>
<Card>
<Title size='h4'>Upload Types</Title>
{
chartData && (
{chartData && (
<Pie
data={chartData.uploadTypes}
options={{
plugins: {
datalabels: {
@ -148,8 +164,7 @@ export default function Graphs() {
}}
style={{ maxHeight: '20vh' }}
/>
)
}
)}
</Card>
</Grid.Col>
@ -157,16 +172,14 @@ export default function Graphs() {
<Grid.Col md={12} lg={8}>
<Card>
<Title size='h4'>Total Views</Title>
{
chartData && (
{chartData && (
<Chart
type='line'
data={chartData.views}
options={chartOptions}
style={{ maxHeight: '20vh' }}
/>
)
}
)}
</Card>
</Grid.Col>
@ -174,16 +187,14 @@ export default function Graphs() {
<Grid.Col md={12} lg={6}>
<Card>
<Title size='h4'>Total Uploads</Title>
{
chartData && (
{chartData && (
<Chart
type='line'
data={chartData.uploads}
options={chartOptions}
style={{ maxHeight: '20vh' }}
/>
)
}
)}
</Card>
</Grid.Col>
@ -191,8 +202,7 @@ export default function Graphs() {
<Grid.Col md={12} lg={6}>
<Card>
<Title size='h4'>Storage Usage</Title>
{
chartData && (
{chartData && (
<Chart
type='line'
data={chartData.storage}
@ -226,8 +236,7 @@ export default function Graphs() {
}}
style={{ maxHeight: '20vh' }}
/>
)
}
)}
</Card>
</Grid.Col>
</Grid>

View file

@ -5,9 +5,7 @@ import { useStats } from 'lib/queries/stats';
export default function Types() {
const stats = useStats();
if(stats.isLoading) return (
<LoadingOverlay visible />
);
if (stats.isLoading) return <LoadingOverlay visible />;
const latest = stats.data[0];

View file

@ -13,7 +13,6 @@ export default function Stats() {
<Types />
<Graphs />
</div>
);
}

View file

@ -53,7 +53,7 @@ export default function Upload() {
useEffect(() => {
window.addEventListener('paste', (e: ClipboardEvent) => {
const item = Array.from(e.clipboardData.items).find(x => /^image/.test(x.type));
const item = Array.from(e.clipboardData.items).find((x) => /^image/.test(x.type));
const file = item.getAsFile();
setFiles([...files, file]);
showNotification({
@ -64,7 +64,11 @@ export default function Upload() {
});
const handleUpload = async () => {
const expires_at = expires === 'never' ? null : new Date({
const expires_at =
expires === 'never'
? null
: new Date(
{
'5min': Date.now() + 5 * 60 * 1000,
'10min': Date.now() + 10 * 60 * 1000,
'15min': Date.now() + 15 * 60 * 1000,
@ -92,7 +96,8 @@ export default function Upload() {
'6m': Date.now() + 6 * 30 * 24 * 60 * 60 * 1000,
'8m': Date.now() + 8 * 30 * 24 * 60 * 60 * 1000,
'1y': Date.now() + 365 * 24 * 60 * 60 * 1000,
}[expires]);
}[expires]
);
setProgress(0);
setLoading(true);
@ -108,13 +113,15 @@ export default function Upload() {
});
const req = new XMLHttpRequest();
req.upload.addEventListener('progress', e => {
req.upload.addEventListener('progress', (e) => {
if (e.lengthComputable) {
setProgress(Math.round(e.loaded / e.total * 100));
setProgress(Math.round((e.loaded / e.total) * 100));
}
});
req.addEventListener('load', e => {
req.addEventListener(
'load',
(e) => {
// @ts-ignore not sure why it thinks response doesnt exist, but it does.
const json = JSON.parse(e.target.response);
setLoading(false);
@ -123,7 +130,17 @@ export default function Upload() {
updateNotification({
id: 'upload',
title: 'Upload Successful',
message: <>Copied first file to clipboard! <br />{json.files.map(x => (<Link key={x} href={x}>{x}<br /></Link>))}</>,
message: (
<>
Copied first file to clipboard! <br />
{json.files.map((x) => (
<Link key={x} href={x}>
{x}
<br />
</Link>
))}
</>
),
color: 'green',
icon: <UploadIcon />,
});
@ -140,7 +157,9 @@ export default function Upload() {
});
}
setProgress(0);
}, false);
},
false
);
req.open('POST', '/api/upload');
req.setRequestHeader('Authorization', user.token);
@ -156,7 +175,9 @@ export default function Upload() {
<Dropzone loading={loading} onDrop={(f) => setFiles([...files, ...f])}>
<Group position='center' spacing='md'>
{files.map(file => (<FileDropzone key={randomId()} file={file} />))}
{files.map((file) => (
<FileDropzone key={randomId()} file={file} />
))}
</Group>
</Dropzone>
@ -167,7 +188,7 @@ export default function Upload() {
<Group position='right' mt='md'>
<Tooltip label='Add a password to your files (optional, leave blank for none)'>
<PasswordInput
style={{width: '252px'}}
style={{ width: '252px' }}
placeholder='Password'
value={password}
onChange={(e) => setPassword(e.currentTarget.value)}
@ -210,7 +231,9 @@ export default function Upload() {
]}
/>
</Tooltip>
<Button leftIcon={<UploadIcon />} onClick={handleUpload} disabled={files.length === 0 ? true : false}>Upload</Button>
<Button leftIcon={<UploadIcon />} onClick={handleUpload} disabled={files.length === 0 ? true : false}>
Upload
</Button>
</Group>
</>
);

View file

@ -26,7 +26,7 @@ export default function Upload() {
});
const req = new XMLHttpRequest();
req.addEventListener('load', e => {
req.addEventListener('load', (e) => {
// @ts-ignore not sure why it thinks response doesnt exist, but it does.
const json = JSON.parse(e.target.response);
@ -34,7 +34,17 @@ export default function Upload() {
updateNotification({
id: 'upload-text',
title: 'Upload Successful',
message: <>Copied first file to clipboard! <br />{json.files.map(x => (<Link key={x} href={x}>{x}<br /></Link>))}</>,
message: (
<>
Copied first file to clipboard! <br />
{json.files.map((x) => (
<Link key={x} href={x}>
{x}
<br />
</Link>
))}
</>
),
});
}
});
@ -53,20 +63,23 @@ export default function Upload() {
<>
<Title mb='md'>Upload Text</Title>
<CodeInput
value={value}
onChange={e => setValue(e.target.value)}
/>
<CodeInput value={value} onChange={(e) => setValue(e.target.value)} />
<Group position='right' mt='md'>
<Select
value={lang}
onChange={setLang}
dropdownPosition='top'
data={Object.keys(exts).map(x => ({ value: x, label: exts[x] }))}
data={Object.keys(exts).map((x) => ({ value: x, label: exts[x] }))}
icon={<TypeIcon />}
/>
<Button leftIcon={<UploadIcon />} onClick={handleUpload} disabled={value.trim().length === 0 ? true : false}>Upload</Button>
<Button
leftIcon={<UploadIcon />}
onClick={handleUpload}
disabled={value.trim().length === 0 ? true : false}
>
Upload
</Button>
</Group>
</>
);

View file

@ -5,13 +5,11 @@ import { CopyIcon, CrossIcon, DeleteIcon, ExternalLinkIcon } from 'components/ic
import TrashIcon from 'components/icons/TrashIcon';
import { URLResponse, useURLDelete } from 'lib/queries/url';
export default function URLCard({ url }: {
url: URLResponse
}) {
export default function URLCard({ url }: { url: URLResponse }) {
const clipboard = useClipboard();
const urlDelete = useURLDelete();
const copyURL = u => {
const copyURL = (u) => {
clipboard.copy(`${window.location.protocol}//${window.location.host}${u.url}`);
showNotification({
title: 'Copied to clipboard',
@ -20,7 +18,7 @@ export default function URLCard({ url }: {
});
};
const deleteURL = async u => {
const deleteURL = async (u) => {
urlDelete.mutate(u.id, {
onSuccess: () => {
showNotification({
@ -44,7 +42,7 @@ export default function URLCard({ url }: {
return (
<Card key={url.id} sx={{ maxWidth: '100%' }} shadow='sm'>
<LoadingOverlay visible={urlDelete.isLoading}/>
<LoadingOverlay visible={urlDelete.isLoading} />
<Group position='apart'>
<Group position='left'>

View file

@ -1,4 +1,15 @@
import { ActionIcon, Button, Group, Modal, SimpleGrid, Skeleton, TextInput, Title, Card, Center } from '@mantine/core';
import {
ActionIcon,
Button,
Group,
Modal,
SimpleGrid,
Skeleton,
TextInput,
Title,
Card,
Center,
} from '@mantine/core';
import { useForm } from '@mantine/form';
import { showNotification } from '@mantine/notifications';
import { CrossIcon, LinkIcon, PlusIcon } from 'components/icons';
@ -24,11 +35,11 @@ export default function Urls() {
},
});
const onSubmit = async values => {
const onSubmit = async (values) => {
const cleanURL = values.url.trim();
const cleanVanity = values.vanity.trim();
if (cleanURL === '') return form.setFieldError('url', 'URL can\'t be nothing');
if (cleanURL === '') return form.setFieldError('url', "URL can't be nothing");
try {
new URL(cleanURL);
@ -45,7 +56,7 @@ export default function Urls() {
const res = await fetch('/api/shorten', {
method: 'POST',
headers: {
'Authorization': user.token,
Authorization: user.token,
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
@ -77,11 +88,7 @@ export default function Urls() {
return (
<>
<Modal
opened={createOpen}
onClose={() => setCreateOpen(false)}
title={<Title>Shorten URL</Title>}
>
<Modal opened={createOpen} onClose={() => setCreateOpen(false)} title={<Title>Shorten URL</Title>}>
<form onSubmit={form.onSubmit((v) => onSubmit(v))}>
<TextInput id='url' label='URL' {...form.getInputProps('url')} />
<TextInput id='vanity' label='Vanity' {...form.getInputProps('vanity')} />
@ -95,11 +102,12 @@ export default function Urls() {
<Group mb='md'>
<Title>URLs</Title>
<ActionIcon variant='filled' color='primary' onClick={() => setCreateOpen(true)}><PlusIcon /></ActionIcon>
<ActionIcon variant='filled' color='primary' onClick={() => setCreateOpen(true)}>
<PlusIcon />
</ActionIcon>
</Group>
{
(urls.data && urls.data.length === 0) && (
{urls.data && urls.data.length === 0 && (
<Card shadow='md'>
<Center>
<Group>
@ -113,25 +121,12 @@ export default function Urls() {
</Group>
</Center>
</Card>
)
}
)}
<SimpleGrid
cols={4}
spacing='lg'
breakpoints={[
{ maxWidth: 'sm', cols: 1, spacing: 'sm' },
]}
>
{
(urls.isLoading || !urls.data) ?
[1, 2, 3, 4].map(x => (
<Skeleton key={x} width='100%' height={80} radius='sm' />
))
: urls.data.map(url => (
<URLCard key={url.id} url={url} />
))
}
<SimpleGrid cols={4} spacing='lg' breakpoints={[{ maxWidth: 'sm', cols: 1, spacing: 'sm' }]}>
{urls.isLoading || !urls.data
? [1, 2, 3, 4].map((x) => <Skeleton key={x} width='100%' height={80} radius='sm' />)
: urls.data.map((url) => <URLCard key={url.id} url={url} />)}
</SimpleGrid>
</>
);

View file

@ -13,11 +13,11 @@ export function CreateUserModal({ open, setOpen, updateUsers }) {
},
});
const onSubmit = async values => {
const onSubmit = async (values) => {
const cleanUsername = values.username.trim();
const cleanPassword = values.password.trim();
if (cleanUsername === '') return form.setFieldError('username', 'Username can\'t be nothing');
if (cleanPassword === '') return form.setFieldError('password', 'Password can\'t be nothing');
if (cleanUsername === '') return form.setFieldError('username', "Username can't be nothing");
if (cleanPassword === '') return form.setFieldError('password', "Password can't be nothing");
const data = {
username: cleanUsername,
@ -47,12 +47,8 @@ export function CreateUserModal({ open, setOpen, updateUsers }) {
};
return (
<Modal
opened={open}
onClose={() => setOpen(false)}
title={<Title>Create User</Title>}
>
<form onSubmit={form.onSubmit(v => onSubmit(v))}>
<Modal opened={open} onClose={() => setOpen(false)} title={<Title>Create User</Title>}>
<form onSubmit={form.onSubmit((v) => onSubmit(v))}>
<TextInput id='username' label='Username' {...form.getInputProps('username')} />
<TextInput id='password' label='Password' type='password' {...form.getInputProps('password')} />
<Switch mt={12} id='administrator' label='Administrator' {...form.getInputProps('administrator')} />

View file

@ -7,7 +7,8 @@ import useFetch from 'hooks/useFetch';
export function EditUserModal({ open, setOpen, updateUsers, user }) {
let form;
if (user) form = useForm({
if (user)
form = useForm({
initialValues: {
username: user?.username,
password: '',
@ -15,7 +16,7 @@ export function EditUserModal({ open, setOpen, updateUsers, user }) {
},
});
const onSubmit = async values => {
const onSubmit = async (values) => {
const cleanUsername = values.username.trim();
const cleanPassword = values.password.trim();
@ -28,7 +29,6 @@ export function EditUserModal({ open, setOpen, updateUsers, user }) {
if (cleanUsername !== '' && cleanUsername !== user.username) data.username = cleanUsername;
if (cleanPassword !== '') data.password = cleanPassword;
setOpen(false);
const res = await useFetch('/api/user/' + user.id, 'PATCH', data);
if (res.error) {
@ -51,13 +51,9 @@ export function EditUserModal({ open, setOpen, updateUsers, user }) {
};
return (
<Modal
opened={open}
onClose={() => setOpen(false)}
title={<Title>Edit User {user?.username}</Title>}
>
<Modal opened={open} onClose={() => setOpen(false)} title={<Title>Edit User {user?.username}</Title>}>
{user && (
<form onSubmit={form.onSubmit(v => onSubmit(v))}>
<form onSubmit={form.onSubmit((v) => onSubmit(v))}>
<TextInput id='username' label='Username' {...form.getInputProps('username')} />
<TextInput id='password' label='Password' type='password' {...form.getInputProps('password')} />
<Switch mt={12} id='administrator' label='Administrator' {...form.getInputProps('administrator')} />

View file

@ -45,7 +45,8 @@ export default function Users() {
};
// 2-step modal for deleting user if they want to delete their images too.
const openDeleteModal = user => modals.openConfirmModal({
const openDeleteModal = (user) =>
modals.openConfirmModal({
title: `Delete ${user.username}?`,
closeOnConfirm: false,
labels: { confirm: 'Yes', cancel: 'No' },
@ -73,7 +74,7 @@ export default function Users() {
setUsers(us);
} else {
router.push('/dashboard');
};
}
};
useEffect(() => {
@ -87,20 +88,25 @@ export default function Users() {
<Group mb='md'>
<Title>Users</Title>
<ActionIcon variant='filled' color='primary' onClick={() => setCreateOpen(true)}><PlusIcon /></ActionIcon>
<ActionIcon variant='filled' color='primary' onClick={() => setCreateOpen(true)}>
<PlusIcon />
</ActionIcon>
</Group>
<SimpleGrid
cols={3}
spacing='lg'
breakpoints={[
{ maxWidth: 'sm', cols: 1, spacing: 'sm' },
]}
>
{users.length ? users.filter(x => x.username !== user.username).map(user => (
<SimpleGrid cols={3} spacing='lg' breakpoints={[{ maxWidth: 'sm', cols: 1, spacing: 'sm' }]}>
{users.length
? users
.filter((x) => x.username !== user.username)
.map((user) => (
<Card key={user.id} sx={{ maxWidth: '100%' }}>
<Group position='apart'>
<Group position='left'>
<Avatar size='lg' color={user.administrator ? 'primary' : 'dark'} src={user.avatar ?? null}>{user.username[0]}</Avatar>
<Avatar
size='lg'
color={user.administrator ? 'primary' : 'dark'}
src={user.avatar ?? null}
>
{user.username[0]}
</Avatar>
<Stack spacing={0}>
<Title>{user.username}</Title>
<MutedText size='sm'>ID: {user.id}</MutedText>
@ -110,7 +116,13 @@ export default function Users() {
<Group position='right'>
{user.administrator ? null : (
<>
<ActionIcon aria-label='edit' onClick={() => {setEditOpen(true); setSelectedUser(user);}}>
<ActionIcon
aria-label='edit'
onClick={() => {
setEditOpen(true);
setSelectedUser(user);
}}
>
<PencilIcon />
</ActionIcon>
<ActionIcon aria-label='delete' onClick={() => openDeleteModal(user)}>
@ -118,13 +130,11 @@ export default function Users() {
</ActionIcon>
</>
)}
</Group>
</Group>
</Card>
)) : [1, 2, 3].map(x => (
<Skeleton key={x} width='100%' height={100} radius='sm' />
))}
))
: [1, 2, 3].map((x) => <Skeleton key={x} width='100%' height={100} radius='sm' />)}
</SimpleGrid>
</>
);

View file

@ -63,7 +63,6 @@ export default function readConfig() {
map('DATASOURCE_S3_REGION', 'string', 'datasource.s3.region'),
map('DATASOURCE_S3_USE_SSL', 'boolean', 'datasource.s3.use_ssl'),
map('DATASOURCE_SWIFT_USERNAME', 'string', 'datasource.swift.username'),
map('DATASOURCE_SWIFT_PASSWORD', 'string', 'datasource.swift.password'),
map('DATASOURCE_SWIFT_AUTH_ENDPOINT', 'string', 'datasource.swift.auth_endpoint'),
@ -152,7 +151,7 @@ export default function readConfig() {
default:
parsed = value;
break;
};
}
set(config, map.path, parsed);
}

View file

@ -3,9 +3,11 @@ import { CombinedError, s, ValidationError } from '@sapphire/shapeshift';
import { inspect } from 'util';
import Logger from 'lib/logger';
const discord_content = s.object({
const discord_content = s
.object({
content: s.string.nullish.default(null),
embed: s.object({
embed: s
.object({
title: s.string.nullish.default(null),
description: s.string.nullish.default(null),
footer: s.string.nullish.default(null),
@ -13,8 +15,10 @@ const discord_content = s.object({
thumbnail: s.boolean.default(false),
image: s.boolean.default(true),
timestamp: s.boolean.default(true),
}).default(null),
}).default(null);
})
.default(null),
})
.default(null);
const validator = s.object({
core: s.object({
@ -27,11 +31,14 @@ const validator = s.object({
stats_interval: s.number.default(1800),
invites_interval: s.number.default(1800),
}),
datasource: s.object({
datasource: s
.object({
type: s.enum('local', 's3', 'swift').default('local'),
local: s.object({
local: s
.object({
directory: s.string.default('./uploads'),
}).default({
})
.default({
directory: './uploads',
}),
s3: s.object({
@ -52,7 +59,8 @@ const validator = s.object({
domain_id: s.string.default('default'),
region_id: s.string.nullable,
}).optional,
}).default({
})
.default({
type: 'local',
local: {
directory: './uploads',
@ -65,7 +73,8 @@ const validator = s.object({
domain_id: 'default',
},
}),
uploader: s.object({
uploader: s
.object({
route: s.string.default('/u'),
embed_route: s.string.default('/a'),
length: s.number.default(6),
@ -73,7 +82,8 @@ const validator = s.object({
user_limit: s.number.default(104900000),
disabled_extensions: s.string.array.default([]),
format_date: s.string.default('YYYY-MM-DD_HH:mm:ss'),
}).default({
})
.default({
route: '/u',
embed_route: '/a',
length: 6,
@ -82,34 +92,44 @@ const validator = s.object({
disabled_extensions: [],
format_date: 'YYYY-MM-DD_HH:mm:ss',
}),
urls: s.object({
urls: s
.object({
route: s.string.default('/go'),
length: s.number.default(6),
}).default({
})
.default({
route: '/go',
length: 6,
}),
ratelimit: s.object({
ratelimit: s
.object({
user: s.number.default(0),
admin: s.number.default(0),
}).default({
})
.default({
user: 0,
admin: 0,
}),
website: s.object({
website: s
.object({
title: s.string.default('Zipline'),
show_files_per_user: s.boolean.default(true),
show_version: s.boolean.default(true),
disable_media_preview: s.boolean.default(false),
external_links: s.array(s.object({
external_links: s
.array(
s.object({
label: s.string,
link: s.string,
})).default([
})
)
.default([
{ label: 'Zipline', link: 'https://github.com/diced/zipline' },
{ label: 'Documentation', link: 'https://zipline.diced.tech/' },
]),
}).default({
})
.default({
title: 'Zipline',
show_files_per_user: true,
show_version: true,
@ -123,21 +143,27 @@ const validator = s.object({
discord: s.object({
url: s.string,
username: s.string.default('Zipline'),
avatar_url: s.string.default('https://raw.githubusercontent.com/diced/zipline/9b60147e112ec5b70170500b85c75ea621f41d03/public/zipline.png'),
avatar_url: s.string.default(
'https://raw.githubusercontent.com/diced/zipline/9b60147e112ec5b70170500b85c75ea621f41d03/public/zipline.png'
),
upload: discord_content,
shorten: discord_content,
}),
oauth: s.object({
oauth: s
.object({
github_client_id: s.string.nullable.default(null),
github_client_secret: s.string.nullable.default(null),
discord_client_id: s.string.nullable.default(null),
discord_client_secret: s.string.nullable.default(null),
}).nullish.default(null),
features: s.object({
})
.nullish.default(null),
features: s
.object({
invites: s.boolean.default(true),
oauth_registration: s.boolean.default(false),
}).default({ invites: true, oauth_registration: false }),
})
.default({ invites: true, oauth_registration: false }),
});
export default function validate(config): Config {
@ -150,10 +176,8 @@ export default function validate(config): Config {
errors.push('datasource.s3.access_key_id is a required field');
if (!validated.datasource.s3.secret_access_key)
errors.push('datasource.s3.secret_access_key is a required field');
if (!validated.datasource.s3.bucket)
errors.push('datasource.s3.bucket is a required field');
if (!validated.datasource.s3.endpoint)
errors.push('datasource.s3.endpoint is a required field');
if (!validated.datasource.s3.bucket) errors.push('datasource.s3.bucket is a required field');
if (!validated.datasource.s3.endpoint) errors.push('datasource.s3.endpoint is a required field');
if (errors.length) throw { errors };
break;
}

View file

@ -7,9 +7,7 @@ export class S3 extends Datasource {
public name: string = 'S3';
public s3: Client;
public constructor(
public config: ConfigS3Datasource,
) {
public constructor(public config: ConfigS3Datasource) {
super();
this.s3 = new Client({
endPoint: config.endpoint,
@ -55,8 +53,8 @@ export class S3 extends Datasource {
const objects = this.s3.listObjectsV2(this.config.bucket, '', true);
let size = 0;
objects.on('data', item => size += item.size);
objects.on('end', err => {
objects.on('data', (item) => (size += item.size));
objects.on('end', (err) => {
if (err) rej(err);
else res(size);
});

View file

@ -44,9 +44,7 @@ class SwiftContainer {
const endpoint = catalogEntry.endpoints.find(
(x: any) =>
x.interface === (this.options.credentials.interface || 'public') &&
(this.options.credentials.region_id
? x.region_id == this.options.credentials.region_id
: true)
(this.options.credentials.region_id ? x.region_id == this.options.credentials.region_id : true)
);
return endpoint ? endpoint.url : null;
@ -94,7 +92,8 @@ class SwiftContainer {
}
});
if (error || !json || !headers || json.error) throw new Error('Could not retrieve credentials from OpenStack, check your config file');
if (error || !json || !headers || json.error)
throw new Error('Could not retrieve credentials from OpenStack, check your config file');
const catalog = json.token.catalog;
// many Swift clouds use ceph radosgw to provide swift
@ -124,10 +123,15 @@ class SwiftContainer {
public async listObjects(query?: string): Promise<SwiftObject[]> {
const auth = await this.authenticate();
return await fetch(`${auth.swiftURL}/${this.options.credentials.container}${query ? `${query.startsWith('?') ? '' : '?'}${query}` : ''}`, {
return await fetch(
`${auth.swiftURL}/${this.options.credentials.container}${
query ? `${query.startsWith('?') ? '' : '?'}${query}` : ''
}`,
{
method: 'GET',
headers: this.generateHeaders(auth.token),
}).then((e) => e.json());
}
).then((e) => e.json());
}
public async uploadObject(name: string, data: Buffer): Promise<any> {

View file

@ -15,7 +15,8 @@ function parse(str: string, args: Args) {
.replace(/{user\.name}/gi, args[0].username)
.replace(/{link}/gi, args[3]);
if (args[1]) str = str
if (args[1])
str = str
.replace(/{file\.id}/gi, args[1].id.toString())
.replace(/{file\.mime}/gi, args[1].mimetype)
.replace(/{file\.file}/gi, args[1].file)
@ -23,7 +24,8 @@ function parse(str: string, args: Args) {
.replace(/{file\.created_at.time_string}/gi, args[1].created_at.toLocaleTimeString())
.replace(/{file\.created_at.date_string}/gi, args[1].created_at.toLocaleDateString());
if (args[2]) str = str
if (args[2])
str = str
.replace(/{url\.id}/gi, args[2].id.toString())
.replace(/{url\.vanity}/gi, args[2].vanity ? args[2].vanity : 'none')
.replace(/{url\.destination}/gi, args[2].destination)
@ -34,10 +36,14 @@ function parse(str: string, args: Args) {
return str;
}
export function parseContent(content: ConfigDiscordContent, args: Args): ConfigDiscordContent & { url: string } {
export function parseContent(
content: ConfigDiscordContent,
args: Args
): ConfigDiscordContent & { url: string } {
return {
content: parse(content.content, args),
embed: content.embed ? {
embed: content.embed
? {
title: parse(content.embed.title, args),
description: parse(content.embed.description, args),
footer: parse(content.embed.footer, args),
@ -45,7 +51,8 @@ export function parseContent(content: ConfigDiscordContent, args: Args): ConfigD
thumbnail: content.embed.thumbnail,
timestamp: content.embed.timestamp,
image: content.embed.image,
} : null,
}
: null,
url: args[3],
};
}
@ -60,22 +67,34 @@ export async function sendUpload(user: User, image: Image, host: string) {
username: config.discord.username,
avatar_url: config.discord.avatar_url,
content: parsed.content ?? null,
embeds: parsed.embed ? [{
embeds: parsed.embed
? [
{
title: parsed.embed.title ?? null,
description: parsed.embed.description ?? null,
url: parsed.url ?? null,
timestamp: parsed.embed.timestamp ? image.created_at.toISOString() : null,
color: parsed.embed.color ?? null,
footer: parsed.embed.footer ? {
footer: parsed.embed.footer
? {
text: parsed.embed.footer,
} : null,
thumbnail: isImage && parsed.embed.thumbnail ? {
}
: null,
thumbnail:
isImage && parsed.embed.thumbnail
? {
url: parsed.url,
} : null,
image: isImage && parsed.embed.image ? {
}
: null,
image:
isImage && parsed.embed.image
? {
url: parsed.url,
} : null,
}] : null,
}
: null,
},
]
: null,
};
const res = await fetch(config.discord.url, {
@ -88,7 +107,9 @@ export async function sendUpload(user: User, image: Image, host: string) {
if (!res.ok) {
const text = await res.text();
Logger.get('discord').error(`Failed to send upload notification to discord: ${res.status} ${res.statusText}`);
Logger.get('discord').error(
`Failed to send upload notification to discord: ${res.status} ${res.statusText}`
);
Logger.get('discord').error(`Received response: ${text}`);
}
@ -104,16 +125,22 @@ export async function sendShorten(user: User, url: Url, host: string) {
username: config.discord.username,
avatar_url: config.discord.avatar_url,
content: parsed.content ?? null,
embeds: parsed.embed ? [{
embeds: parsed.embed
? [
{
title: parsed.embed.title ?? null,
description: parsed.embed.description ?? null,
url: parsed.url ?? null,
timestamp: parsed.embed.timestamp ? url.created_at.toISOString() : null,
color: parsed.embed.color ?? null,
footer: parsed.embed.footer ? {
footer: parsed.embed.footer
? {
text: parsed.embed.footer,
} : null,
}] : null,
}
: null,
},
]
: null,
};
const res = await fetch(config.discord.url, {
@ -125,7 +152,9 @@ export async function sendShorten(user: User, url: Url, host: string) {
});
if (!res.ok) {
Logger.get('discord').error(`Failed to send url shorten notification to discord: ${res.status} ${res.statusText}`);
Logger.get('discord').error(
`Failed to send url shorten notification to discord: ${res.status} ${res.statusText}`
);
}
return;

View file

@ -1,45 +1,45 @@
// https://github.com/toptal/haste-server/blob/master/static/application.js#L167-L174
// Popular extension map
const exts = {
'md': 'Markdown',
'css': 'CSS',
'js': 'JavaScript',
'json': 'JSON',
'html': 'HTML',
'ts': 'TypeScript',
'java': 'Java',
'py': 'Python',
'rb': 'Ruby',
'sh': 'Shell',
'php': 'PHP',
'pl': 'Perl',
'sql': 'SQL',
'xml': 'XML',
'yml': 'YAML',
'yaml': 'YAML',
'c': 'C',
'cpp': 'C++',
'cs': 'C#',
'go': 'Go',
'h': 'C/C++ Header',
'txt': 'Text',
'dockerfile': 'Dockerfile',
'toml': 'TOML',
'ini': 'INI',
'bat': 'Batch File',
'tex': 'TeX',
'r': 'R',
'lua': 'Lua',
'ps1': 'PowerShell',
'rst': 'reStructuredText',
'rs': 'Rust',
'swift': 'Swift',
'scss': 'SCSS',
'less': 'LESS',
'scala': 'Scala',
'kotlin': 'Kotlin',
'vb': 'Visual Basic',
'vim': 'Vim Script',
md: 'Markdown',
css: 'CSS',
js: 'JavaScript',
json: 'JSON',
html: 'HTML',
ts: 'TypeScript',
java: 'Java',
py: 'Python',
rb: 'Ruby',
sh: 'Shell',
php: 'PHP',
pl: 'Perl',
sql: 'SQL',
xml: 'XML',
yml: 'YAML',
yaml: 'YAML',
c: 'C',
cpp: 'C++',
cs: 'C#',
go: 'Go',
h: 'C/C++ Header',
txt: 'Text',
dockerfile: 'Dockerfile',
toml: 'TOML',
ini: 'INI',
bat: 'Batch File',
tex: 'TeX',
r: 'R',
lua: 'Lua',
ps1: 'PowerShell',
rst: 'reStructuredText',
rs: 'Rust',
swift: 'Swift',
scss: 'SCSS',
less: 'LESS',
scala: 'Scala',
kotlin: 'Kotlin',
vb: 'Visual Basic',
vim: 'Vim Script',
};
export default exts;

View file

@ -1,4 +1,8 @@
export default async function useFetch(url: string, method: 'GET' | 'POST' | 'PATCH' | 'DELETE' = 'GET', body: Record<string, any> = null) {
export default async function useFetch(
url: string,
method: 'GET' | 'POST' | 'PATCH' | 'DELETE' = 'GET',
body: Record<string, any> = null
) {
const headers = {};
if (body) headers['content-type'] = 'application/json';

View file

@ -10,8 +10,7 @@ export default class Logger {
public name: string;
static get(clas: any) {
if (typeof clas !== 'function')
if (typeof clas !== 'string') throw new Error('not string/function');
if (typeof clas !== 'function') if (typeof clas !== 'string') throw new Error('not string/function');
const name = clas.name ?? clas;
@ -28,11 +27,7 @@ export default class Logger {
error(...args: any[]) {
console.log(
this.formatMessage(
LoggerLevel.ERROR,
this.name,
args.map((error) => error.stack ?? error).join(' ')
)
this.formatMessage(LoggerLevel.ERROR, this.name, args.map((error) => error.stack ?? error).join(' '))
);
}

View file

@ -3,18 +3,20 @@ import { discord_auth, github_auth } from 'lib/oauth';
import { notNull } from 'lib/util';
import { GetServerSideProps } from 'next';
export const getServerSideProps: GetServerSideProps = async ctx => {
export const getServerSideProps: GetServerSideProps = async (ctx) => {
// this entire thing will also probably change before the stable release
const ghEnabled = notNull(config.oauth?.github_client_id, config.oauth?.github_client_secret);
const discEnabled = notNull(config.oauth?.discord_client_id, config.oauth?.discord_client_secret);
const oauth_providers = [];
if (ghEnabled) oauth_providers.push({
if (ghEnabled)
oauth_providers.push({
name: 'GitHub',
url: '/api/auth/oauth/github',
});
if (discEnabled) oauth_providers.push({
if (discEnabled)
oauth_providers.push({
name: 'Discord',
url: '/api/auth/oauth/discord',
});

View file

@ -21,7 +21,7 @@ export type NextApiReq = NextApiRequest & {
getCookie: (name: string) => string | null;
cleanCookie: (name: string) => void;
files?: NextApiFile[];
}
};
export type NextApiRes = NextApiResponse & {
error: (message: string) => void;
@ -30,31 +30,41 @@ export type NextApiRes = NextApiResponse & {
json: (json: Record<string, any>, status?: number) => void;
ratelimited: (remaining: number) => void;
setCookie: (name: string, value: unknown, options: CookieSerializeOptions) => void;
}
};
export const withZipline = (handler: (req: NextApiRequest, res: NextApiResponse) => unknown) => (req: NextApiReq, res: NextApiRes) => {
export const withZipline =
(handler: (req: NextApiRequest, res: NextApiResponse) => unknown) => (req: NextApiReq, res: NextApiRes) => {
res.setHeader('Content-Type', 'application/json');
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Content-Allow-Methods', 'GET,HEAD,POST,OPTIONS');
res.setHeader('Access-Control-Max-Age', '86400');
res.error = (message: string) => {
res.json({
res.json(
{
error: message,
}, 500);
},
500
);
};
res.forbid = (message: string, extra: any = {}) => {
res.json({
res.json(
{
error: '403: ' + message,
...extra,
}, 403);
},
403
);
};
res.bad = (message: string) => {
res.json({
res.json(
{
error: '401: ' + message,
}, 401);
},
401
);
};
res.ratelimited = (remaining: number) => {
@ -79,11 +89,14 @@ export const withZipline = (handler: (req: NextApiRequest, res: NextApiResponse)
return unsigned ? unsigned : null;
};
req.cleanCookie = (name: string) => {
res.setHeader('Set-Cookie', serialize(name, '', {
res.setHeader(
'Set-Cookie',
serialize(name, '', {
path: '/',
expires: new Date(1),
maxAge: undefined,
}));
})
);
};
req.user = async () => {
@ -107,10 +120,11 @@ export const withZipline = (handler: (req: NextApiRequest, res: NextApiResponse)
}
};
res.setCookie = (name: string, value: unknown, options?: CookieSerializeOptions) => setCookie(res, name, value, options || {});
res.setCookie = (name: string, value: unknown, options?: CookieSerializeOptions) =>
setCookie(res, name, value, options || {});
return handler(req, res);
};
};
export const setCookie = (
res: NextApiResponse,
@ -118,7 +132,6 @@ export const setCookie = (
value: unknown,
options: CookieSerializeOptions = {}
) => {
if ('maxAge' in options) {
options.expires = new Date(Date.now() + options.maxAge * 1000);
options.maxAge /= 1000;

View file

@ -1,11 +1,11 @@
import { readFile } from 'fs/promises';
export type Mimes = [string, string[]][]
export type Mimes = [string, string[]][];
export async function guess(extension: string): Promise<string> {
const mimes: Mimes = JSON.parse(await readFile('./mimes.json', 'utf8'));
const mime = mimes.find(x => x[0] === extension);
const mime = mimes.find((x) => x[0] === extension);
if (!mime) return 'application/octet-stream';
return mime[1][0];

View file

@ -1,9 +1,10 @@
export const github_auth = {
oauth_url: (clientId: string) => `https://github.com/login/oauth/authorize?client_id=${clientId}&scope=user`,
oauth_url: (clientId: string) =>
`https://github.com/login/oauth/authorize?client_id=${clientId}&scope=user`,
oauth_user: async (access_token: string) => {
const res = await fetch('https://api.github.com/user', {
headers: {
'Authorization': `Bearer ${access_token}`,
Authorization: `Bearer ${access_token}`,
},
});
if (!res.ok) return null;
@ -13,11 +14,14 @@ export const github_auth = {
};
export const discord_auth = {
oauth_url: (clientId: string, origin: string) => `https://discord.com/api/oauth2/authorize?client_id=${clientId}&redirect_uri=${encodeURIComponent(`${origin}/api/auth/oauth/discord`)}&response_type=code&scope=identify`,
oauth_url: (clientId: string, origin: string) =>
`https://discord.com/api/oauth2/authorize?client_id=${clientId}&redirect_uri=${encodeURIComponent(
`${origin}/api/auth/oauth/discord`
)}&response_type=code&scope=identify`,
oauth_user: async (access_token: string) => {
const res = await fetch('https://discord.com/api/users/@me', {
headers: {
'Authorization': `Bearer ${access_token}`,
Authorization: `Bearer ${access_token}`,
},
});
if (!res.ok) return null;

View file

@ -2,6 +2,6 @@ import { PrismaClient } from '@prisma/client';
if (!global.prisma) {
if (!process.env.ZIPLINE_DOCKER_BUILD) global.prisma = new PrismaClient();
};
}
export default global.prisma;

View file

@ -9,7 +9,7 @@ export type UserFilesResponse = {
id: string;
favorite: boolean;
url: string;
}
};
export const useFiles = (query: { [key: string]: string } = {}) => {
const queryBuilder = new URLSearchParams(query);
@ -17,11 +17,11 @@ export const useFiles = (query: { [key: string]: string } = {}) => {
return useQuery<UserFilesResponse[]>(['files', queryString], async () => {
return fetch('/api/user/files?' + queryString)
.then(res => res.json() as Promise<UserFilesResponse[]>)
.then(data =>
.then((res) => res.json() as Promise<UserFilesResponse[]>)
.then((data) =>
query.paged === 'true'
? data
: data.map(x => ({
: data.map((x) => ({
...x,
created_at: new Date(x.created_at).toLocaleString(),
}))
@ -31,57 +31,65 @@ export const useFiles = (query: { [key: string]: string } = {}) => {
export const usePaginatedFiles = (query: { [key: string]: string } = {}) => {
query['paged'] = 'true';
const data = useFiles(query) as ReturnType<typeof useQuery> & { data: UserFilesResponse[][] };
const data = useFiles(query) as ReturnType<typeof useQuery> & {
data: UserFilesResponse[][];
};
return data;
};
export const useRecent = (filter?: string) => {
return useQuery<UserFilesResponse[]>(['recent', filter], async () => {
return fetch(`/api/user/recent?filter=${encodeURIComponent(filter)}`)
.then(res => res.json())
.then(data => data.map(x => ({
.then((res) => res.json())
.then((data) =>
data.map((x) => ({
...x,
created_at: new Date(x.created_at).toLocaleString(),
})));
}))
);
});
};
export function useFileDelete() {
// '/api/user/files', 'DELETE', { id: image.id }
return useMutation(async (id: string) => {
return useMutation(
async (id: string) => {
return fetch('/api/user/files', {
method: 'DELETE',
body: JSON.stringify({ id }),
headers: {
'content-type': 'application/json',
},
}).then(res => res.json());
}, {
}).then((res) => res.json());
},
{
onSuccess: () => {
queryClient.refetchQueries(['files']);
},
});
}
);
}
export function useFileFavorite() {
// /api/user/files', 'PATCH', { id: image.id, favorite: !image.favorite }
return useMutation(async (data: { id: string, favorite: boolean }) => {
return useMutation(
async (data: { id: string; favorite: boolean }) => {
return fetch('/api/user/files', {
method: 'PATCH',
body: JSON.stringify(data),
headers: {
'content-type': 'application/json',
},
}).then(res => res.json());
}, {
}).then((res) => res.json());
},
{
onSuccess: () => {
queryClient.refetchQueries(['files']);
},
});
}
);
}
export function invalidateFiles() {
return queryClient.invalidateQueries(
['files', 'recent', 'stats']
);
return queryClient.invalidateQueries(['files', 'recent', 'stats']);
}

View file

@ -16,14 +16,17 @@ export type Stats = {
size_num: number;
types_count: StatsTypesCount[];
views_count: number;
}
}
};
};
export const useStats = (amount = 2) => {
return useQuery<Stats[]>(['stats', amount], async () => {
return fetch('/api/stats?amount=' + amount)
.then(res => res.json());
}, {
return useQuery<Stats[]>(
['stats', amount],
async () => {
return fetch('/api/stats?amount=' + amount).then((res) => res.json());
},
{
staleTime: 1000 * 60 * 5, // 5 minutes
});
}
);
};

View file

@ -7,17 +7,17 @@ export type URLResponse = {
id: string;
url: string;
vanity: string;
}
};
export function useURLs() {
return useQuery<URLResponse[]>(['urls'], async () => {
return fetch('/api/user/urls')
.then(res => res.json());
return fetch('/api/user/urls').then((res) => res.json());
});
}
export function useURLDelete() {
return useMutation(async (id: string) => {
return useMutation(
async (id: string) => {
// '/api/user/urls', 'DELETE', { id: u.id }
return fetch('/api/user/urls', {
method: 'DELETE',
@ -25,11 +25,15 @@ export function useURLDelete() {
headers: {
'content-type': 'application/json',
},
}).then(res => res.json());
}, {
}).then((res) => res.json());
},
{
onSuccess: (data, variables) => {
const dataWithoutDeleted = queryClient.getQueryData<URLResponse[]>(['urls'])?.filter(u => u.id !== variables);
const dataWithoutDeleted = queryClient
.getQueryData<URLResponse[]>(['urls'])
?.filter((u) => u.id !== variables);
queryClient.setQueryData(['urls'], dataWithoutDeleted);
},
});
}
);
}

View file

@ -1,9 +1,13 @@
import { useQuery } from '@tanstack/react-query';
export const useVersion = () => {
return useQuery<{ local: string, upstream: string }>(['version'], async () => {
return fetch('/api/version').then(res => res.json());
}, {
return useQuery<{ local: string; upstream: string }>(
['version'],
async () => {
return fetch('/api/version').then((res) => res.json());
},
{
staleTime: Infinity,
});
}
);
};

View file

@ -26,10 +26,7 @@ export function createToken() {
}
export function sign(value: string, secret: string): string {
const signed = value + ':' + createHmac('sha256', secret)
.update(value)
.digest('base64')
.replace(/=+$/, '');
const signed = value + ':' + createHmac('sha256', secret).update(value).digest('base64').replace(/=+$/, '');
return signed;
}
@ -59,7 +56,7 @@ export function chunk<T>(arr: T[], size: number): Array<T[]> {
let i = 0;
while (i < L) {
result.push(arr.slice(i, i += size));
result.push(arr.slice(i, (i += size)));
}
return result;
@ -93,7 +90,11 @@ export function randomInvis(length: number) {
// some parts from https://github.com/tycrek/ass/blob/master/generators/lengthGen.js
const invisibleCharset = ['\u200B', '\u2060', '\u200C', '\u200D'];
return [...randomBytes(length)].map((byte) => invisibleCharset[Number(byte) % invisibleCharset.length]).join('').slice(1).concat(invisibleCharset[0]);
return [...randomBytes(length)]
.map((byte) => invisibleCharset[Number(byte) % invisibleCharset.length])
.join('')
.slice(1)
.concat(invisibleCharset[0]);
}
export function createInvisImage(length: number, imageId: number) {

View file

@ -46,7 +46,10 @@ export function relativeTime(to: Date, from: Date = new Date()) {
for (const unit in units) {
if (time > units[unit]) {
return rtf.format(Math.floor(Math.round(time.getTime() / units[unit])), unit as Intl.RelativeTimeFormatUnit || 'second');
return rtf.format(
Math.floor(Math.round(time.getTime() / units[unit])),
(unit as Intl.RelativeTimeFormatUnit) || 'second'
);
}
}
}

View file

@ -15,9 +15,11 @@ export default function FourOhFour() {
}}
spacing='sm'
>
<Title sx={{ fontSize: 220, fontWeight: 900, lineHeight: .8 }}>404</Title>
<Title sx={{ fontSize: 220, fontWeight: 900, lineHeight: 0.8 }}>404</Title>
<MutedText sx={{ fontSize: 40, fontWeight: 500 }}>This page does not exist!</MutedText>
<Button component={Link} href='/dashboard'>Head to the Dashboard</Button>
<Button component={Link} href='/dashboard'>
Head to the Dashboard
</Button>
</Stack>
);
}

View file

@ -15,9 +15,11 @@ export default function FiveHundred() {
}}
spacing='sm'
>
<Title sx={{ fontSize: 220, fontWeight: 900, lineHeight: .8 }}>500</Title>
<Title sx={{ fontSize: 220, fontWeight: 900, lineHeight: 0.8 }}>500</Title>
<MutedText sx={{ fontSize: 40, fontWeight: 500 }}>Internal Server Error</MutedText>
<Button component={Link} href='/dashboard'>Head to the Dashboard</Button>
<Button component={Link} href='/dashboard'>
Head to the Dashboard
</Button>
</Stack>
);
}

View file

@ -30,19 +30,21 @@ export default function EmbeddedImage({ image, user, pass }) {
};
const updateImage = async (url?: string) => {
const imageEl = document.getElementById('image_content') as HTMLImageElement;
const img = new Image();
img.addEventListener('load', function () {
if (this.naturalWidth > innerWidth) imageEl.width = Math.floor(this.naturalWidth * Math.min((innerHeight / this.naturalHeight), (innerWidth / this.naturalWidth)));
if (this.naturalWidth > innerWidth)
imageEl.width = Math.floor(
this.naturalWidth * Math.min(innerHeight / this.naturalHeight, innerWidth / this.naturalWidth)
);
else imageEl.width = this.naturalWidth;
});
img.src = url || dataURL('/r');
if (url) {
imageEl.src = url;
};
}
};
useEffect(() => {
@ -58,7 +60,9 @@ export default function EmbeddedImage({ image, user, pass }) {
<Head>
{image.embed && (
<>
{user.embedSiteName && <meta property='og:site_name' content={parse(user.embedSiteName, image, user)} />}
{user.embedSiteName && (
<meta property='og:site_name' content={parse(user.embedSiteName, image, user)} />
)}
{user.embedTitle && <meta property='og:title' content={parse(user.embedTitle, image, user)} />}
<meta property='theme-color' content={user.embedColor} />
</>
@ -99,7 +103,13 @@ export default function EmbeddedImage({ image, user, pass }) {
closeOnClickOutside={false}
overlayBlur={3}
>
<PasswordInput label='Password' placeholder='Password' error={error} value={password} onChange={e => setPassword(e.target.value)} />
<PasswordInput
label='Password'
placeholder='Password'
error={error}
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<Button fullWidth onClick={() => check()} mt='md'>
Submit
</Button>
@ -117,12 +127,7 @@ export default function EmbeddedImage({ image, user, pass }) {
)}
{image.mimetype.startsWith('video') && (
<video
src={dataURL('/r')}
controls={true}
autoPlay={true}
id='image_content'
/>
<video src={dataURL('/r')} controls={true} autoPlay={true} id='image_content' />
)}
</Box>
</>
@ -139,11 +144,7 @@ export const getServerSideProps: GetServerSideProps = async (context) => {
if (route === config.urls.route.substring(1)) {
const url = await prisma.url.findFirst({
where: {
OR: [
{ id },
{ vanity: id },
{ invisible: { invis: id } },
],
OR: [{ id }, { vanity: id }, { invisible: { invis: id } }],
},
select: {
destination: true,
@ -157,14 +158,10 @@ export const getServerSideProps: GetServerSideProps = async (context) => {
destination: url.destination,
},
};
} else if (uploader_route === '' ? /(^[^\\.]+\.[^\\.]+)/.test(route) : route === uploader_route) {
const image = await prisma.image.findFirst({
where: {
OR: [
{ file: id },
{ invisible: { invis: id } },
],
OR: [{ file: id }, { invisible: { invis: id } }],
},
select: {
mimetype: true,
@ -196,7 +193,8 @@ export const getServerSideProps: GetServerSideProps = async (context) => {
image.created_at = image.created_at.toString();
const prismRender = Object.keys(exts).includes(image.file.split('.').pop());
if (prismRender) return {
if (prismRender)
return {
redirect: {
destination: `/code/${image.file}`,
permanent: true,
@ -225,4 +223,3 @@ export const getServerSideProps: GetServerSideProps = async (context) => {
return { notFound: true };
}
};

View file

@ -11,9 +11,7 @@ export default function MyApp({ Component, pageProps }) {
<Head>
<meta name='viewport' content='minimum-scale=1, initial-scale=1, width=device-width' />
</Head>
<QueryClientProvider
client={queryClient}
>
<QueryClientProvider client={queryClient}>
<ZiplineTheming Component={Component} pageProps={pageProps} />
</QueryClientProvider>
</RecoilRoot>

View file

@ -11,7 +11,10 @@ class MyDocument extends Document {
return (
<Html lang='en'>
<Head>
<link rel='stylesheet' href='https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap' />
<link
rel='stylesheet'
href='https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap'
/>
</Head>
<body>
<Main />

View file

@ -15,9 +15,11 @@ export default function Error({ statusCode }) {
}}
spacing='sm'
>
<Title sx={{ fontSize: 220, fontWeight: 900, lineHeight: .8 }}>{statusCode}</Title>
<Title sx={{ fontSize: 220, fontWeight: 900, lineHeight: 0.8 }}>{statusCode}</Title>
<MutedText sx={{ fontSize: 40, fontWeight: 500 }}>Something went wrong...</MutedText>
<Button component={Link} href='/dashboard'>Head to the Dashboard</Button>
<Button component={Link} href='/dashboard'>
Head to the Dashboard
</Button>
</Stack>
);
}

View file

@ -8,7 +8,11 @@ async function handler(req: NextApiReq, res: NextApiRes) {
if (req.method === 'POST' && req.body && req.body.code) {
if (!config.features.invites) return res.forbid('invites are disabled');
const { code, username, password } = req.body as { code: string; username: string, password: string };
const { code, username, password } = req.body as {
code: string;
username: string;
password: string;
};
const invite = await prisma.invite.findUnique({
where: { code },
});
@ -49,7 +53,11 @@ async function handler(req: NextApiReq, res: NextApiRes) {
if (req.method !== 'POST') return res.status(405).end();
const { username, password, administrator } = req.body as { username: string, password: string, administrator: boolean };
const { username, password, administrator } = req.body as {
username: string;
password: string;
administrator: boolean;
};
if (!username) return res.bad('no username');
if (!password) return res.bad('no auth');

View file

@ -12,7 +12,10 @@ async function handler(req: NextApiReq, res: NextApiRes) {
if (!user.administrator) return res.forbid('you arent an administrator');
if (req.method === 'POST') {
const { expires_at, count } = req.body as { expires_at: string, count: number };
const { expires_at, count } = req.body as {
expires_at: string;
count: number;
};
const expiry = expires_at ? new Date(expires_at) : null;
if (expiry) {
@ -31,9 +34,13 @@ async function handler(req: NextApiReq, res: NextApiRes) {
});
}
await prisma.invite.createMany({data});
await prisma.invite.createMany({ data });
Logger.get('invite').info(`${user.username} (${user.id}) created ${data.length} invites with codes ${data.map(invite => invite.code).join(', ')}`);
Logger.get('invite').info(
`${user.username} (${user.id}) created ${data.length} invites with codes ${data
.map((invite) => invite.code)
.join(', ')}`
);
return res.json(data);
} else {

View file

@ -5,7 +5,10 @@ import Logger from 'lib/logger';
async function handler(req: NextApiReq, res: NextApiRes) {
if (req.method !== 'POST') return res.status(405).end();
const { username, password } = req.body as { username: string, password: string };
const { username, password } = req.body as {
username: string;
password: string;
};
const users = await prisma.user.findMany();
if (users.length === 0) {
@ -32,7 +35,11 @@ async function handler(req: NextApiReq, res: NextApiRes) {
const valid = await checkPassword(password, user.password);
if (!valid) return res.forbid('Wrong password');
res.setCookie('user', user.id, { sameSite: true, expires: new Date(Date.now() + (6.048e+8 * 2)), path: '/' });
res.setCookie('user', user.id, {
sameSite: true,
expires: new Date(Date.now() + 6.048e8 * 2),
path: '/',
});
Logger.get('user').info(`User ${user.username} (${user.id}) logged in`);

View file

@ -14,7 +14,13 @@ async function handler(req: NextApiReq, res: NextApiRes) {
}
const { code } = req.query as { code: string };
if (!code) return res.redirect(discord_auth.oauth_url(config.oauth.discord_client_id, `${config.core.https ? 'https' : 'http'}://${req.headers.host}`));
if (!code)
return res.redirect(
discord_auth.oauth_url(
config.oauth.discord_client_id,
`${config.core.https ? 'https' : 'http'}://${req.headers.host}`
)
);
const resp = await fetch('https://discord.com/api/oauth2/token', {
method: 'POST',
@ -38,7 +44,9 @@ async function handler(req: NextApiReq, res: NextApiRes) {
const userJson = await discord_auth.oauth_user(json.access_token);
if (!userJson) return res.error('invalid user request');
const avatar = userJson.avatar ? `https://cdn.discordapp.com/avatars/${userJson.id}/${userJson.avatar}.png` : `https://cdn.discordapp.com/embed/avatars/${userJson.discriminator % 5}.png`;
const avatar = userJson.avatar
? `https://cdn.discordapp.com/avatars/${userJson.id}/${userJson.avatar}.png`
: `https://cdn.discordapp.com/embed/avatars/${userJson.discriminator % 5}.png`;
const avatarBase64 = await getBase64URLFromURL(avatar);
const existing = await prisma.user.findFirst({
@ -58,7 +66,11 @@ async function handler(req: NextApiReq, res: NextApiRes) {
});
req.cleanCookie('user');
res.setCookie('user', existing.id, { sameSite: true, expires: new Date(Date.now() + (6.048e+8 * 2)), path: '/' });
res.setCookie('user', existing.id, {
sameSite: true,
expires: new Date(Date.now() + 6.048e8 * 2),
path: '/',
});
Logger.get('user').info(`User ${existing.username} (${existing.id}) logged in via oauth(discord)`);
return res.redirect('/dashboard');
@ -79,7 +91,11 @@ async function handler(req: NextApiReq, res: NextApiRes) {
Logger.get('user').info(`Created user ${user.username} via oauth(discord)`);
req.cleanCookie('user');
res.setCookie('user', user.id, { sameSite: true, expires: new Date(Date.now() + (6.048e+8 * 2)), path: '/' });
res.setCookie('user', user.id, {
sameSite: true,
expires: new Date(Date.now() + 6.048e8 * 2),
path: '/',
});
Logger.get('user').info(`User ${user.username} (${user.id}) logged in via oauth(discord)`);
return res.redirect('/dashboard');

View file

@ -21,7 +21,7 @@ async function handler(req: NextApiReq, res: NextApiRes) {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify({
client_id: config.oauth.github_client_id,
@ -58,7 +58,11 @@ async function handler(req: NextApiReq, res: NextApiRes) {
});
req.cleanCookie('user');
res.setCookie('user', existing.id, { sameSite: true, expires: new Date(Date.now() + (6.048e+8 * 2)), path: '/' });
res.setCookie('user', existing.id, {
sameSite: true,
expires: new Date(Date.now() + 6.048e8 * 2),
path: '/',
});
Logger.get('user').info(`User ${existing.username} (${existing.id}) logged in via oauth(github)`);
return res.redirect('/dashboard');
@ -79,7 +83,11 @@ async function handler(req: NextApiReq, res: NextApiRes) {
Logger.get('user').info(`Created user ${user.username} via oauth(github)`);
req.cleanCookie('user');
res.setCookie('user', user.id, { sameSite: true, expires: new Date(Date.now() + (6.048e+8 * 2)), path: '/' });
res.setCookie('user', user.id, {
sameSite: true,
expires: new Date(Date.now() + 6.048e8 * 2),
path: '/',
});
Logger.get('user').info(`User ${user.username} (${user.id}) logged in via oauth(github)`);
return res.redirect('/dashboard');

View file

@ -44,13 +44,25 @@ async function handler(req: NextApiReq, res: NextApiRes) {
if (req.headers.zws) invis = await createInvisURL(zconfig.urls.length, url.id);
Logger.get('url').info(`User ${user.username} (${user.id}) shortenned a url ${url.destination} (${url.id})`);
Logger.get('url').info(
`User ${user.username} (${user.id}) shortenned a url ${url.destination} (${url.id})`
);
if (config.discord?.shorten) {
await sendShorten(user, url, `${zconfig.core.https ? 'https' : 'http'}://${req.headers.host}${zconfig.urls.route}/${req.body.vanity ? req.body.vanity : invis ? invis.invis : url.id}`);
await sendShorten(
user,
url,
`${zconfig.core.https ? 'https' : 'http'}://${req.headers.host}${zconfig.urls.route}/${
req.body.vanity ? req.body.vanity : invis ? invis.invis : url.id
}`
);
}
return res.json({ url: `${zconfig.core.https ? 'https' : 'http'}://${req.headers.host}${zconfig.urls.route}/${req.body.vanity ? req.body.vanity : invis ? invis.invis : url.id}` });
return res.json({
url: `${zconfig.core.https ? 'https' : 'http'}://${req.headers.host}${zconfig.urls.route}/${
req.body.vanity ? req.body.vanity : invis ? invis.invis : url.id
}`,
});
}
export default withZipline(handler);

View file

@ -8,7 +8,7 @@ async function handler(req: NextApiReq, res: NextApiRes) {
if (!user) return res.forbid('not logged in');
let amount = typeof req.query.amount === 'string' ? parseInt(req.query.amount) : 2;
if(isNaN(amount)) return res.bad('invalid amount');
if (isNaN(amount)) return res.bad('invalid amount');
// get stats per day

View file

@ -46,7 +46,7 @@ async function handler(req: NextApiReq, res: NextApiRes) {
if (!req.files) return res.error('no files');
if (req.files && req.files.length === 0) return res.error('no files');
const response: { files: string[], expires_at?: Date } = { files: [] };
const response: { files: string[]; expires_at?: Date } = { files: [] };
const expires_at = req.headers['expires-at'] as string;
let expiry: Date;
@ -62,15 +62,18 @@ async function handler(req: NextApiReq, res: NextApiRes) {
const rawFormat = ((req.headers.format || '') as string).toUpperCase() || 'RANDOM';
const format: ImageFormat = Object.keys(ImageFormat).includes(rawFormat) && ImageFormat[rawFormat];
const imageCompressionPercent = req.headers['image-compression-percent'] ? Number(req.headers['image-compression-percent']) : null;
const imageCompressionPercent = req.headers['image-compression-percent']
? Number(req.headers['image-compression-percent'])
: null;
for (let i = 0; i !== req.files.length; ++i) {
const file = req.files[i];
if (file.size > zconfig.uploader[user.administrator ? 'admin_limit' : 'user_limit']) return res.error(`file[${i}] size too big`);
if (file.size > zconfig.uploader[user.administrator ? 'admin_limit' : 'user_limit'])
return res.error(`file[${i}] size too big`);
const ext = file.originalname.split('.').pop();
if (zconfig.uploader.disabled_extensions.includes(ext)) return res.error('disabled extension recieved: ' + ext);
if (zconfig.uploader.disabled_extensions.includes(ext))
return res.error('disabled extension recieved: ' + ext);
let fileName: string;
switch (format) {
@ -101,7 +104,7 @@ async function handler(req: NextApiReq, res: NextApiRes) {
const image = await prisma.image.create({
data: {
file: `${fileName}.${compressionUsed ? 'jpg' : ext}`,
mimetype: req.headers.uploadtext ? 'text/plain' : (compressionUsed ? 'image/jpeg' : file.mimetype),
mimetype: req.headers.uploadtext ? 'text/plain' : compressionUsed ? 'image/jpeg' : file.mimetype,
userId: user.id,
embed: !!req.headers.embed,
format,
@ -115,21 +118,37 @@ async function handler(req: NextApiReq, res: NextApiRes) {
if (compressionUsed) {
const buffer = await sharp(file.buffer).jpeg({ quality: imageCompressionPercent }).toBuffer();
await datasource.save(image.file, buffer);
Logger.get('image').info(`User ${user.username} (${user.id}) compressed image from ${file.buffer.length} -> ${buffer.length} bytes`);
Logger.get('image').info(
`User ${user.username} (${user.id}) compressed image from ${file.buffer.length} -> ${buffer.length} bytes`
);
} else {
await datasource.save(image.file, file.buffer);
}
Logger.get('image').info(`User ${user.username} (${user.id}) uploaded an image ${image.file} (${image.id})`);
Logger.get('image').info(
`User ${user.username} (${user.id}) uploaded an image ${image.file} (${image.id})`
);
if (user.domains.length) {
const domain = user.domains[Math.floor(Math.random() * user.domains.length)];
response.files.push(`${domain}${zconfig.uploader.route === '/' ? '' : zconfig.uploader.route}/${invis ? invis.invis : image.file}`);
response.files.push(
`${domain}${zconfig.uploader.route === '/' ? '' : zconfig.uploader.route}/${
invis ? invis.invis : image.file
}`
);
} else {
response.files.push(`${zconfig.core.https ? 'https' : 'http'}://${req.headers.host}${zconfig.uploader.route === '/' ? '' : zconfig.uploader.route}/${invis ? invis.invis : image.file}`);
response.files.push(
`${zconfig.core.https ? 'https' : 'http'}://${req.headers.host}${
zconfig.uploader.route === '/' ? '' : zconfig.uploader.route
}/${invis ? invis.invis : image.file}`
);
}
if (zconfig.discord?.upload) {
await sendUpload(user, image, `${zconfig.core.https ? 'https' : 'http'}://${req.headers.host}/r/${invis ? invis.invis : image.file}`);
await sendUpload(
user,
image,
`${zconfig.core.https ? 'https' : 'http'}://${req.headers.host}/r/${invis ? invis.invis : image.file}`
);
}
}
@ -139,7 +158,7 @@ async function handler(req: NextApiReq, res: NextApiRes) {
id: user.id,
},
data: {
ratelimit: new Date(Date.now() + (zconfig.ratelimit.admin * 1000)),
ratelimit: new Date(Date.now() + zconfig.ratelimit.admin * 1000),
},
});
} else if (!user.administrator && zconfig.ratelimit.user > 0) {
@ -149,7 +168,7 @@ async function handler(req: NextApiReq, res: NextApiRes) {
id: user.id,
},
data: {
ratelimit: new Date(Date.now() + (zconfig.ratelimit.user * 1000)),
ratelimit: new Date(Date.now() + zconfig.ratelimit.user * 1000),
},
});
}
@ -170,7 +189,7 @@ function run(middleware: any) {
export default async function handlers(req, res) {
return withZipline(handler)(req, res);
};
}
export const config = {
api: {

View file

@ -65,33 +65,39 @@ async function handler(req: NextApiReq, res: NextApiRes) {
});
}
if (req.body.avatar) await prisma.user.update({
if (req.body.avatar)
await prisma.user.update({
where: { id: target.id },
data: { avatar: req.body.avatar },
});
if (req.body.embedTitle) await prisma.user.update({
if (req.body.embedTitle)
await prisma.user.update({
where: { id: target.id },
data: { embedTitle: req.body.embedTitle },
});
if (req.body.embedColor) await prisma.user.update({
if (req.body.embedColor)
await prisma.user.update({
where: { id: target.id },
data: { embedColor: req.body.embedColor },
});
if (req.body.embedSiteName) await prisma.user.update({
if (req.body.embedSiteName)
await prisma.user.update({
where: { id: target.id },
data: { embedSiteName: req.body.embedSiteName },
});
if (req.body.systemTheme) await prisma.user.update({
if (req.body.systemTheme)
await prisma.user.update({
where: { id: target.id },
data: { systemTheme: req.body.systemTheme },
});
if (req.body.domains) {
if (!req.body.domains) await prisma.user.update({
if (!req.body.domains)
await prisma.user.update({
where: { id: target.id },
data: { domains: [] },
});
@ -138,7 +144,9 @@ async function handler(req: NextApiReq, res: NextApiRes) {
},
});
Logger.get('user').info(`User ${user.username} (${user.id}) updated ${target.username} (${newUser.username}) (${newUser.id})`);
Logger.get('user').info(
`User ${user.username} (${user.id}) updated ${target.username} (${newUser.username}) (${newUser.id})`
);
return res.json(newUser);
}

View file

@ -51,7 +51,7 @@ async function handler(req: NextApiReq, res: NextApiRes) {
} else {
Object.defineProperty(stream, 'ondata', {
get: () => ondataPatched,
set: cb => ondata = cb,
set: (cb) => (ondata = cb),
});
}
@ -68,14 +68,14 @@ async function handler(req: NextApiReq, res: NextApiRes) {
});
};
zip.ondata = async (err, data, final) => {
if (!err) {
write_stream.write(data);
if (final) {
write_stream.close();
Logger.get('user').info(`Export for ${user.username} (${user.id}) has completed and is available at ${export_name}`);
Logger.get('user').info(
`Export for ${user.username} (${user.id}) has completed and is available at ${export_name}`
);
}
} else {
write_stream.close();
@ -91,14 +91,14 @@ async function handler(req: NextApiReq, res: NextApiRes) {
if (stream) {
const def = new ZipPassThrough(file.file);
zip.add(def);
onBackpressure(def, stream, shouldApplyBackpressure => {
onBackpressure(def, stream, (shouldApplyBackpressure) => {
if (shouldApplyBackpressure) {
stream.pause();
} else if (stream.isPaused()) {
stream.resume();
}
});
stream.on('data', c => def.push(c));
stream.on('data', (c) => def.push(c));
stream.on('end', () => def.push(new Uint8Array(0), true));
}
}
@ -121,7 +121,7 @@ async function handler(req: NextApiReq, res: NextApiRes) {
stream.pipe(res);
} else {
const files = await readdir(tmpdir());
const exp = files.filter(f => f.startsWith('zipline_export_'));
const exp = files.filter((f) => f.startsWith('zipline_export_'));
const exports = [];
for (let i = 0; i !== exp.length; ++i) {
const name = exp[i];

View file

@ -39,7 +39,9 @@ async function handler(req: NextApiReq, res: NextApiRes) {
await datasource.delete(image.file);
Logger.get('image').info(`User ${user.username} (${user.id}) deleted an image ${image.file} (${image.id})`);
Logger.get('image').info(
`User ${user.username} (${user.id}) deleted an image ${image.file} (${image.id})`
);
delete image.password;
return res.json(image);
@ -49,7 +51,8 @@ async function handler(req: NextApiReq, res: NextApiRes) {
let image;
if (req.body.favorite !== null) image = await prisma.image.update({
if (req.body.favorite !== null)
image = await prisma.image.update({
where: { id: req.body.id },
data: {
favorite: req.body.favorite,
@ -78,10 +81,10 @@ async function handler(req: NextApiReq, res: NextApiRes) {
},
});
// @ts-ignore
images.map(image => image.url = `/r/${image.file}`);
if (req.query.filter && req.query.filter === 'media') images = images.filter(x => /^(video|audio|image|text)/.test(x.mimetype));
images.map((image) => (image.url = `/r/${image.file}`));
if (req.query.filter && req.query.filter === 'media')
images = images.filter((x) => /^(video|audio|image|text)/.test(x.mimetype));
return res.json(req.query.paged ? chunk(images, 16) : images);
}

View file

@ -17,19 +17,28 @@ async function handler(req: NextApiReq, res: NextApiRes) {
req.cleanCookie('user');
Logger.get('user').info(`User ${user.username} (${user.id}) logged out (oauth token expired)`);
return res.json({ error: 'oauth token expired', redirect_uri: github_auth.oauth_url(config.oauth.github_client_id) });
return res.json({
error: 'oauth token expired',
redirect_uri: github_auth.oauth_url(config.oauth.github_client_id),
});
}
} else if (user.oauthProvider === 'discord') {
const resp = await fetch('https://discord.com/api/users/@me', {
headers: {
'Authorization': `Bearer ${user.oauthAccessToken}`,
Authorization: `Bearer ${user.oauthAccessToken}`,
},
});
if (!resp.ok) {
req.cleanCookie('user');
Logger.get('user').info(`User ${user.username} (${user.id}) logged out (oauth token expired)`);
return res.json({ error: 'oauth token expired', redirect_uri: discord_auth.oauth_url(config.oauth.discord_client_id, `${config.core.https ? 'https' : 'http'}://${req.headers.host}`) });
return res.json({
error: 'oauth token expired',
redirect_uri: discord_auth.oauth_url(
config.oauth.discord_client_id,
`${config.core.https ? 'https' : 'http'}://${req.headers.host}`
),
});
}
}
}
@ -58,33 +67,39 @@ async function handler(req: NextApiReq, res: NextApiRes) {
});
}
if (req.body.avatar) await prisma.user.update({
if (req.body.avatar)
await prisma.user.update({
where: { id: user.id },
data: { avatar: req.body.avatar },
});
if (req.body.embedTitle) await prisma.user.update({
if (req.body.embedTitle)
await prisma.user.update({
where: { id: user.id },
data: { embedTitle: req.body.embedTitle },
});
if (req.body.embedColor) await prisma.user.update({
if (req.body.embedColor)
await prisma.user.update({
where: { id: user.id },
data: { embedColor: req.body.embedColor },
});
if (req.body.embedSiteName) await prisma.user.update({
if (req.body.embedSiteName)
await prisma.user.update({
where: { id: user.id },
data: { embedSiteName: req.body.embedSiteName },
});
if (req.body.systemTheme) await prisma.user.update({
if (req.body.systemTheme)
await prisma.user.update({
where: { id: user.id },
data: { systemTheme: req.body.systemTheme },
});
if (req.body.domains) {
if (!req.body.domains) await prisma.user.update({
if (!req.body.domains)
await prisma.user.update({
where: { id: user.id },
data: { domains: [] },
});

View file

@ -7,7 +7,7 @@ async function handler(req: NextApiReq, res: NextApiRes) {
const take = Number(req.query.take ?? 4);
if (take > 50) return res.error('take can\'t be more than 50');
if (take > 50) return res.error("take can't be more than 50");
let images = await prisma.image.findMany({
take,
@ -27,8 +27,9 @@ async function handler(req: NextApiReq, res: NextApiRes) {
});
// @ts-ignore
images.map(image => image.url = `/r/${image.file}`);
if (req.query.filter && req.query.filter === 'media') images = images.filter(x => /^(video|audio|image)/.test(x.mimetype));
images.map((image) => (image.url = `/r/${image.file}`));
if (req.query.filter && req.query.filter === 'media')
images = images.filter((x) => /^(video|audio|image)/.test(x.mimetype));
return res.json(images);
}

View file

@ -33,7 +33,7 @@ async function handler(req: NextApiReq, res: NextApiRes) {
});
// @ts-ignore
urls.map(url => url.url = `${config.urls.route}/${url.vanity ?? url.id}`);
urls.map((url) => (url.url = `${config.urls.route}/${url.vanity ?? url.id}`));
return res.json(urls);
}
}

View file

@ -21,17 +21,17 @@ async function handler(req: NextApiReq, res: NextApiRes) {
const user = await req.user();
if (!user) return res.forbid('not logged in');
if (!user.administrator) return res.forbid('you aren\'t an administrator');
if (!user.administrator) return res.forbid("you aren't an administrator");
if (req.method === 'DELETE') {
if (req.body.id === user.id) return res.forbid('you can\'t delete your own account');
if (req.body.id === user.id) return res.forbid("you can't delete your own account");
const deleteUser = await prisma.user.findFirst({
where: {
id: req.body.id,
},
});
if (!deleteUser) return res.forbid('user doesn\'t exist');
if (!deleteUser) return res.forbid("user doesn't exist");
if (req.body.delete_images) {
const files = await prisma.image.findMany({
@ -49,7 +49,9 @@ async function handler(req: NextApiReq, res: NextApiRes) {
userId: deleteUser.id,
},
});
Logger.get('image').info(`User ${user.username} (${user.id}) deleted ${count} files of user ${deleteUser.username} (${deleteUser.id})`);
Logger.get('image').info(
`User ${user.username} (${user.id}) deleted ${count} files of user ${deleteUser.username} (${deleteUser.id})`
);
}
await prisma.user.delete({

View file

@ -2,7 +2,6 @@ import { readFile } from 'fs/promises';
import config from 'lib/config';
import { NextApiReq, NextApiRes, withZipline } from 'middleware/withZipline';
async function handler(req: NextApiReq, res: NextApiRes) {
const user = await req.user();
if (!user) return res.forbid('not logged in');

View file

@ -29,14 +29,15 @@ export default function Login({ title, oauth_registration, oauth_providers: unpa
},
});
const onSubmit = async values => {
const onSubmit = async (values) => {
const username = values.username.trim();
const password = values.password.trim();
if (username === '') return form.setFieldError('username', 'Username can\'t be nothing');
if (username === '') return form.setFieldError('username', "Username can't be nothing");
const res = await useFetch('/api/auth/login', 'POST', {
username, password,
username,
password,
});
if (res.error) {
@ -47,7 +48,7 @@ export default function Login({ title, oauth_registration, oauth_providers: unpa
form.setFieldError('password', 'Invalid password');
}
} else {
await router.push(router.query.url as string || '/dashboard');
await router.push((router.query.url as string) || '/dashboard');
}
};
@ -70,14 +71,18 @@ export default function Login({ title, oauth_registration, oauth_providers: unpa
<TextInput size='lg' id='username' label='Username' {...form.getInputProps('username')} />
<PasswordInput size='lg' id='password' label='Password' {...form.getInputProps('password')} />
<Button size='lg' type='submit' fullWidth mt={12}>Login</Button>
<Button size='lg' type='submit' fullWidth mt={12}>
Login
</Button>
</form>
{oauth_registration && (
<>
<Divider label='or' labelPosition='center' my={8} />
{oauth_providers.map(({ url, name, Icon }, i) => (
<Link key={i} href={url} passHref>
<Button size='lg' fullWidth leftIcon={<Icon />} component='a' my={8}>Login in with {name}</Button>
<Button size='lg' fullWidth leftIcon={<Icon />} component='a' my={8}>
Login in with {name}
</Button>
</Link>
))}
</>

View file

@ -23,9 +23,7 @@ export default function Logout() {
})();
}, []);
return (
<LoadingOverlay visible={true} />
);
return <LoadingOverlay visible={true} />;
}
Logout.title = 'Zipline - Logout';

View file

@ -23,7 +23,7 @@ export default function Login({ title, oauth_registration, oauth_providers: unpa
if (!oauth_registration) {
router.push('/auth/login');
return null;
};
}
useEffect(() => {
(async () => {
@ -46,7 +46,9 @@ export default function Login({ title, oauth_registration, oauth_providers: unpa
</Link>
{oauth_providers.map(({ url, name, Icon }, i) => (
<Link key={i} href={url} passHref>
<Button size='lg' fullWidth mt={12} leftIcon={<Icon />} component='a'>Sign in with {name}</Button>
<Button size='lg' fullWidth mt={12} leftIcon={<Icon />} component='a'>
Sign in with {name}
</Button>
</Link>
))}
</div>

View file

@ -4,17 +4,15 @@ import { streamToString } from 'lib/utils/streams';
import { GetServerSideProps } from 'next';
type CodeProps = {
code: string,
id: string,
}
code: string;
id: string;
};
// Code component
export default function Code(
{ code, id }: CodeProps
) {
export default function Code({ code, id }: CodeProps) {
return (
<Prism
sx={t => ({ height: '100vh', backgroundColor: t.colors.dark[8] })}
sx={(t) => ({ height: '100vh', backgroundColor: t.colors.dark[8] })}
withLineNumbers
language={exts[id.split('.').pop()]?.toLowerCase()}
>
@ -30,14 +28,12 @@ export const getServerSideProps: GetServerSideProps<CodeProps> = async (context)
const { default: datasource } = await import('lib/datasource');
const data = await datasource.get(context.params.id as string);
if (!data) return {
if (!data)
return {
notFound: true,
};
context.res.setHeader(
'Cache-Control',
'public, max-age=2628000, stale-while-revalidate=86400'
);
context.res.setHeader('Cache-Control', 'public, max-age=2628000, stale-while-revalidate=86400');
return {
props: {

View file

@ -17,9 +17,7 @@ export default function FilesPage(props) {
<title>{props.title} - Files</title>
</Head>
<Layout
props={props}
>
<Layout props={props}>
<Files disableMediaPreview={props.disable_media_preview} />
</Layout>
</>

View file

@ -16,9 +16,7 @@ export default function DashboardPage(props) {
<Head>
<title>{props.title}</title>
</Head>
<Layout
props={props}
>
<Layout props={props}>
<Dashboard disableMediaPreview={props.disable_media_preview} />
</Layout>
</>

View file

@ -14,7 +14,7 @@ export default function InvitesPage(props) {
router.push('/dashboard');
}, []);
return null;
};
}
const { loading } = useLogin();
@ -25,9 +25,7 @@ export default function InvitesPage(props) {
<Head>
<title>{props.title} - Invites</title>
</Head>
<Layout
props={props}
>
<Layout props={props}>
<Invites />
</Layout>
</>

View file

@ -16,9 +16,7 @@ export default function ManagePage(props) {
<Head>
<title>{props.title} - Manage User</title>
</Head>
<Layout
props={props}
>
<Layout props={props}>
<Manage />
</Layout>
</>

View file

@ -16,9 +16,7 @@ export default function StatsPage(props) {
<Head>
<title>{props.title} - Stats</title>
</Head>
<Layout
props={props}
>
<Layout props={props}>
<Stats />
</Layout>
</>

View file

@ -16,10 +16,8 @@ export default function UploadTextPage(props) {
<Head>
<title>{props.title} - Upload Text</title>
</Head>
<Layout
props={props}
>
<UploadText/>
<Layout props={props}>
<UploadText />
</Layout>
</>
);

View file

@ -16,9 +16,7 @@ export default function UploadPage(props) {
<Head>
<title>{props.title} - Upload</title>
</Head>
<Layout
props={props}
>
<Layout props={props}>
<Upload />
</Layout>
</>

View file

@ -16,9 +16,7 @@ export default function UrlsPage(props) {
<Head>
<title>{props.title} - URLs</title>
</Head>
<Layout
props={props}
>
<Layout props={props}>
<Urls />
</Layout>
</>

View file

@ -16,9 +16,7 @@ export default function UsersPage(props) {
<Head>
<title>{props.title} - Users</title>
</Head>
<Layout
props={props}
>
<Layout props={props}>
<Users />
</Layout>
</>

View file

@ -51,7 +51,11 @@ export default function Invite({ code, title }) {
};
const createUser = async () => {
const res = await useFetch('/api/auth/create', 'POST', { code, username, password });
const res = await useFetch('/api/auth/create', 'POST', {
code,
username,
password,
});
if (res.error) {
showNotification({
title: 'Error while creating user',
@ -70,22 +74,24 @@ export default function Invite({ code, title }) {
setUser(null);
await useFetch('/api/auth/logout');
await useFetch('/api/auth/login', 'POST', {
username, password,
username,
password,
});
router.push('/dashboard');
}
};
return (
<>
<Head>
<title>{title} - Invite ({code})</title>
<title>
{title} - Invite ({code})
</title>
</Head>
<Center sx={{ height: '100vh' }}>
<Box
sx={t => ({
sx={(t) => ({
backgroundColor: t.colors.dark[6],
borderRadius: t.radius.sm,
})}
@ -101,14 +107,20 @@ export default function Invite({ code, title }) {
onBlur={() => checkUsername()}
/>
<Group position='center' mt='xl'>
<Button disabled={usernameError !== '' || username == ''} onClick={nextStep}>Continue</Button>
<Button disabled={usernameError !== '' || username == ''} onClick={nextStep}>
Continue
</Button>
</Group>
</Stepper.Step>
<Stepper.Step label='Choose a password' allowStepSelect={active > 1 && usernameError === ''}>
<PasswordStrength value={password} setValue={setPassword} setStrength={setStrength} />
<Group position='center' mt='xl'>
<Button variant='default' onClick={prevStep}>Back</Button>
<Button disabled={strength !== 100} onClick={nextStep}>Continue</Button>
<Button variant='default' onClick={prevStep}>
Back
</Button>
<Button disabled={strength !== 100} onClick={nextStep}>
Continue
</Button>
</Group>
</Stepper.Step>
<Stepper.Step label='Verify your password' allowStepSelect={active > 2}>
@ -120,13 +132,19 @@ export default function Invite({ code, title }) {
onBlur={() => checkPassword()}
/>
<Group position='center' mt='xl'>
<Button variant='default' onClick={prevStep}>Back</Button>
<Button disabled={verifyPasswordError !== '' || verifyPassword == ''} onClick={nextStep}>Continue</Button>
<Button variant='default' onClick={prevStep}>
Back
</Button>
<Button disabled={verifyPasswordError !== '' || verifyPassword == ''} onClick={nextStep}>
Continue
</Button>
</Group>
</Stepper.Step>
<Stepper.Completed>
<Group position='center' mt='xl'>
<Button variant='default' onClick={() => setActive(0)}>Go back</Button>
<Button variant='default' onClick={() => setActive(0)}>
Go back
</Button>
<Button onClick={() => createUser()}>Finish setup</Button>
</Group>
</Stepper.Completed>
@ -137,8 +155,9 @@ export default function Invite({ code, title }) {
);
}
export const getServerSideProps: GetServerSideProps = async context => {
if (!config.features.invites) return {
export const getServerSideProps: GetServerSideProps = async (context) => {
if (!config.features.invites)
return {
notFound: true,
};

View file

@ -23,13 +23,17 @@ async function start() {
// annoy user if they didnt change secret from default "changethis"
if (config.core.secret === 'changethis') {
logger.error('Secret is not set!');
logger.error('Running Zipline as is, without a randomized secret is not recommended and leaves your instance at risk!');
logger.error(
'Running Zipline as is, without a randomized secret is not recommended and leaves your instance at risk!'
);
logger.error('Please change your secret in the config file or environment variables.');
logger.error('The config file is located at `config.toml`, or if using docker-compose you can change the variables in the `docker-compose.yml` file.');
logger.error(
'The config file is located at `config.toml`, or if using docker-compose you can change the variables in the `docker-compose.yml` file.'
);
logger.error('It is recomended to use a secret that is alphanumeric and randomized.');
logger.error('A way you can generate this is through a password manager you may have.');
process.exit(1);
};
}
process.env.DATABASE_URL = config.core.database_url;
await migrations();
@ -55,15 +59,15 @@ async function start() {
},
});
router.on('GET', config.uploader.route === '/' ? '/:id(^[^\\.]+\\.[^\\.]+)' : `${config.uploader.route}/:id`, async (req, res, params) => {
router.on(
'GET',
config.uploader.route === '/' ? '/:id(^[^\\.]+\\.[^\\.]+)' : `${config.uploader.route}/:id`,
async (req, res, params) => {
if (params.id === '') return nextServer.render404(req, res as ServerResponse);
const image = await prisma.image.findFirst({
where: {
OR: [
{ file: params.id },
{ invisible: { invis: decodeURI(params.id) } },
],
OR: [{ file: params.id }, { invisible: { invis: decodeURI(params.id) } }],
},
});
@ -73,17 +77,15 @@ async function start() {
else if (image.embed) await handle(req, res);
else await fileDb(req, res, nextServer, prisma, handle, image);
}
});
}
);
router.on('GET', '/r/:id', async (req, res, params) => {
if (params.id === '') return nextServer.render404(req, res as ServerResponse);
const image = await prisma.image.findFirst({
where: {
OR: [
{ file: params.id },
{ invisible: { invis: decodeURI(params.id) } },
],
OR: [{ file: params.id }, { invisible: { invis: decodeURI(params.id) } }],
},
});
@ -127,12 +129,7 @@ async function start() {
}, config.core.invites_interval * 1000);
}
async function rawFile(
req: IncomingMessage,
res: OutgoingMessage,
nextServer: NextServer,
id: string,
) {
async function rawFile(req: IncomingMessage, res: OutgoingMessage, nextServer: NextServer, id: string) {
const data = await datasource.get(id);
if (!data) return nextServer.render404(req, res as ServerResponse);
const mimetype = await guess(extname(id));
@ -151,7 +148,7 @@ async function rawFileDb(
res: OutgoingMessage,
nextServer: NextServer,
prisma: PrismaClient,
image: Image,
image: Image
) {
if (image.expires_at && image.expires_at < new Date()) {
Logger.get('server').info(`${image.file} expired`);
@ -185,7 +182,7 @@ async function fileDb(
nextServer: NextServer,
prisma: PrismaClient,
handle: RequestHandler,
image: Image,
image: Image
) {
if (image.expires_at && image.expires_at < new Date()) {
await datasource.delete(image.file);

View file

@ -48,7 +48,6 @@ export function bytesToRead(bytes: number) {
return `${bytes.toFixed(1)} ${units[num]}`;
}
export async function getStats(prisma: PrismaClient, datasource: Datasource) {
const size = await datasource.fullSize();
const byUser = await prisma.image.groupBy({
@ -88,7 +87,11 @@ export async function getStats(prisma: PrismaClient, datasource: Datasource) {
},
});
const types_count = [];
for (let i = 0, L = typesCount.length; i !== L; ++i) types_count.push({ mimetype: typesCount[i].mimetype, count: typesCount[i]._count.mimetype });
for (let i = 0, L = typesCount.length; i !== L; ++i)
types_count.push({
mimetype: typesCount[i].mimetype,
count: typesCount[i]._count.mimetype,
});
return {
size: bytesToRead(size),
@ -96,7 +99,7 @@ export async function getStats(prisma: PrismaClient, datasource: Datasource) {
count,
count_by_user: count_by_user.sort((a, b) => b.count - a.count),
count_users,
views_count: (viewsCount[0]?._sum?.views ?? 0),
views_count: viewsCount[0]?._sum?.views ?? 0,
types_count: types_count.sort((a, b) => b.count - a.count),
};
}

View file

@ -1,11 +1,7 @@
{
"compilerOptions": {
"target": "esnext",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
@ -20,18 +16,10 @@
"noEmit": true,
"baseUrl": "src",
"paths": {
"components/*": [
"components/*"
],
"hooks/*": [
"lib/hooks/*"
],
"middleware/*": [
"lib/middleware/*"
],
"lib/*": [
"lib/*"
]
"components/*": ["components/*"],
"hooks/*": ["lib/hooks/*"],
"middleware/*": ["lib/middleware/*"],
"lib/*": ["lib/*"]
},
"incremental": true
},
@ -44,10 +32,5 @@
"**/**/*.tsx",
"prisma/seed.ts"
],
"exclude": [
"node_modules",
"dist",
".yarn",
".next",
]
"exclude": ["node_modules", "dist", ".yarn", ".next"]
}

Some files were not shown because too many files have changed in this diff Show more