Compare commits

...

47 Commits

Author SHA1 Message Date
af72cb6799 Version 1.1.0 2022-03-07 19:14:37 +01:00
47f0a45cb1 install dependencies 2022-03-07 19:09:37 +01:00
0a0a8a8952 Merge remote-tracking branch 'boilerplate/develop' into develop
# Conflicts:
#	package.json
2022-03-07 19:07:15 +01:00
a5b7cf9268 upgrade dependencies 2022-03-07 19:04:29 +01:00
3062960a4b fix(front/file-uploader): properly disable forms when uploading files to avoid interrupting a file upload
fixes #9
2022-03-07 17:24:15 +01:00
f54438e9dd chore(front/NavMenu): move Auth Tokens link to new Account dropdown from swaf 2022-03-06 18:34:55 +01:00
848c952073 fix(back/AuthTokenController): fix auth tokens pagination size 2022-03-06 18:34:03 +01:00
e3f7b5e7c7 feat(front/auth-token): make token revoke action button mode to gain space 2022-03-06 18:33:41 +01:00
8ddcd50c35 feat(front/auth-token): use better icon for new token generation button 2022-03-06 18:33:36 +01:00
8d13bd0c8d chore(back/AuthToken): update to new AuthProof use method from swaf 2022-03-06 16:39:27 +01:00
c54a201e98 chore(front): convert auth-tokens to svelte 2022-03-06 13:17:02 +01:00
3abd692ce3 feat(front): improve about page, remove redundant link from nav menu 2022-03-06 12:24:50 +01:00
eaac5f3ace chore(front): remove old asset files 2022-03-05 10:13:12 +01:00
5cb13c221d feat(front/url-shrinker): update url-shrinker icon to shrink 2022-03-05 10:12:49 +01:00
7c65f1b6ae chore(front/url-shrinker): convert url-shrinker to svelte 2022-03-05 10:12:26 +01:00
c025aa2539 chore(front/file-uploader): remove unnecessary css, container, update col-grow class names 2022-03-05 10:11:19 +01:00
1b5e088d74 chore(front/global css): remove old scss files and add new and updated _vars.scss 2022-03-05 09:08:53 +01:00
53c7423115 fix(front/file-uploader): remove unnecessary data-table-container usage 2022-03-05 09:08:14 +01:00
c2182dbbca chore(back/scripts): move linux scripts to new assets folder 2022-03-05 09:06:58 +01:00
27f760d503 feat(front/file-uploader): make copy button in file list work again 2022-03-02 11:37:02 +01:00
a8f82564a5 feat(front/file-uploader): display human readable time in file list 2022-03-02 11:22:29 +01:00
9807158bb9 feat(front/file-uploader): improve file list table density and looks 2022-03-02 11:16:37 +01:00
11fccbfc0d fix sass->scss asset dir name 2022-03-02 11:11:57 +01:00
15441a0941 feat(front/FileUpload): display errors and allow retrying or canceling the upload 2022-03-02 11:10:58 +01:00
7ad0eac6db feat(front/file-uploader): reduce page height changes/unnecessary visual changes, improve ux 2022-03-02 11:09:55 +01:00
c906827fe1 fix(front/file-uploader): do not add failed uploads to finished uploads list 2022-03-02 11:07:27 +01:00
5477c858ef fix(front/file-uploader): prevent starting upload if another upload is running 2022-03-02 11:06:53 +01:00
79fb4e28c8 chore(front/file-uploader): convert file-uploader view to svelte 2022-03-02 10:26:48 +01:00
e94b98aee0 Merge remote-tracking branch 'origin/develop' into develop 2022-03-01 10:50:35 +01:00
47156c9a77 Remove feather icons in favor of lucide icons (included with swaf) 2022-03-01 10:50:14 +01:00
79d23a4604 swaf upgrade: convert views to svelte 2022-02-19 10:17:21 +01:00
5571737d93 swaf upgrade: fix eslint 2022-02-19 09:30:51 +01:00
377c073cd2 swaf upgrade: move views to new assets folder 2022-02-18 20:46:50 +01:00
b1ba6b9106 swaf upgrade: make code compile 2022-02-18 20:46:34 +01:00
69b234d95c upgrade dependencies 2022-02-18 20:35:36 +01:00
17c7674c3e Merge remote-tracking branch 'boilerplate/develop' into develop
# Conflicts:
#	assets/config.json
#	assets/sass/_vars.scss
#	assets/sass/app.scss
#	assets/sass/layout.scss
#	assets/ts/copyable_text.ts
#	package.json
#	src/App.ts
#	tsconfig.json
#	views/about.njk
#	views/layouts/base.njk
2022-02-18 20:32:46 +01:00
5f5275ceb1 upgrade dependencies 2021-12-24 15:20:28 +01:00
eb0364a2f7 Fix eslint and fix linting issues 2021-11-21 17:52:56 +01:00
f2f34dd00f Update eslint config with swaf 2021-11-21 17:44:12 +01:00
8c1230d501 Remove reference to deleted tsconfig.frontend.json from eslint config 2021-11-21 17:41:48 +01:00
6002ad5290 Remove webpack and unused dependencies 2021-11-21 17:07:31 +01:00
257a407faf Remove unused old assets 2021-11-21 16:58:59 +01:00
569a50e43a Upgrade swaf and dependencies 2021-11-20 19:54:59 +01:00
938e8b4ebb Add imagemin-webp 2021-06-07 11:24:52 +02:00
7e260ebde2 Upgrade dependencies, replace img-loader with image-minimizer-webpack-plugin 2021-06-07 11:21:43 +02:00
efbc895ba3 Bump @types/node 2021-04-30 11:55:59 +02:00
2cb5b6f8f9 Replace node-sass with sass 2021-04-30 11:55:59 +02:00
76 changed files with 4345 additions and 6917 deletions

135
.eslintrc.cjs Normal file
View File

@ -0,0 +1,135 @@
module.exports = {
root: true,
parser: '@typescript-eslint/parser',
plugins: [
'svelte3',
'@typescript-eslint',
'import',
'simple-import-sort',
],
parserOptions: {
tsconfigRootDir: __dirname,
project: [
'./tsconfig.test.json',
'./src/tsconfig.json',
'./src/common/tsconfig.json',
'./src/assets/ts/tsconfig.eslint.json',
'./src/assets/views/tsconfig.json',
]
},
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
],
rules: {
indent: [
'error',
4,
{
SwitchCase: 1
}
],
'no-trailing-spaces': 'error',
'max-len': [
'error',
{
code: 120,
ignoreTemplateLiterals: true,
ignoreRegExpLiterals: true
}
],
semi: 'off',
'@typescript-eslint/semi': [
'error'
],
'no-extra-semi': 'error',
'eol-last': 'error',
'comma-dangle': 'off',
'simple-import-sort/imports': 'error',
'no-extra-parens': 'off',
'no-nested-ternary': 'error',
'no-return-await': 'off',
'no-useless-return': 'error',
'no-useless-constructor': 'off',
'import/extensions': ['error', 'ignorePackages'],
'@typescript-eslint/comma-dangle': [
'error',
{
arrays: 'always-multiline',
objects: 'always-multiline',
imports: 'always-multiline',
exports: 'always-multiline',
functions: 'always-multiline',
enums: 'always-multiline',
generics: 'always-multiline',
tuples: 'always-multiline'
}
],
'@typescript-eslint/no-extra-parens': [
'error'
],
'@typescript-eslint/no-inferrable-types': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'error',
'@typescript-eslint/no-unnecessary-condition': 'error',
'@typescript-eslint/no-unused-vars': [
'error',
{
argsIgnorePattern: '^_'
}
],
'@typescript-eslint/no-non-null-assertion': 'error',
'@typescript-eslint/no-useless-constructor': [
'error'
],
'@typescript-eslint/return-await': [
'error',
'always'
],
'@typescript-eslint/explicit-member-accessibility': [
'error',
{
accessibility: 'explicit'
}
],
'@typescript-eslint/no-floating-promises': 'error',
},
ignorePatterns: [
'.eslintrc.js',
'rollup.config.js',
'jest.config.js',
'dist/**/*',
'config/**/*',
'intermediates/**/*',
'public/**/*',
'scripts/**/*',
'src/frontend/register_svelte/register_svelte.js',
],
overrides: [
{
files: [
'test/**/*'
],
rules: {
'max-len': [
'error',
{
code: 120,
ignoreTemplateLiterals: true,
ignoreRegExpLiterals: true,
ignoreStrings: true
}
]
}
},
{
files: ['*.svelte'],
processor: 'svelte3/svelte3'
}
],
settings: {
'svelte3/typescript': require('typescript'),
'svelte3/ignore-styles': function (attributes) {
return !!(attributes['lang'] && attributes['lang'] !== 'css');
}
},
}

View File

@ -1,115 +0,0 @@
{
"root": true,
"parser": "@typescript-eslint/parser",
"plugins": [
"@typescript-eslint"
],
"parserOptions": {
"project": [
"./tsconfig.json",
"./tsconfig.test.json",
"./tsconfig.frontend.json"
]
},
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended"
],
"rules": {
"indent": [
"error",
4,
{
"SwitchCase": 1
}
],
"no-trailing-spaces": "error",
"max-len": [
"error",
{
"code": 120,
"ignoreStrings": true,
"ignoreTemplateLiterals": true,
"ignoreRegExpLiterals": true
}
],
"semi": "off",
"@typescript-eslint/semi": [
"error"
],
"no-extra-semi": "error",
"eol-last": "error",
"comma-dangle": "off",
"@typescript-eslint/comma-dangle": [
"error",
{
"arrays": "always-multiline",
"objects": "always-multiline",
"imports": "always-multiline",
"exports": "always-multiline",
"functions": "always-multiline",
"enums": "always-multiline",
"generics": "always-multiline",
"tuples": "always-multiline"
}
],
"no-extra-parens": "off",
"@typescript-eslint/no-extra-parens": [
"error"
],
"no-nested-ternary": "error",
"@typescript-eslint/no-inferrable-types": "off",
"@typescript-eslint/explicit-module-boundary-types": "error",
"@typescript-eslint/no-unnecessary-condition": "error",
"@typescript-eslint/no-unused-vars": [
"error",
{
"argsIgnorePattern": "^_"
}
],
"@typescript-eslint/no-non-null-assertion": "error",
"no-useless-return": "error",
"no-useless-constructor": "off",
"@typescript-eslint/no-useless-constructor": [
"error"
],
"no-return-await": "off",
"@typescript-eslint/return-await": [
"error",
"always"
],
"@typescript-eslint/explicit-member-accessibility": [
"error",
{
"accessibility": "explicit"
}
],
"@typescript-eslint/no-floating-promises": "error"
},
"ignorePatterns": [
"jest.config.js",
"scripts/**/*",
"webpack.config.js",
"dist/**/*",
"public/**/*",
"config/**/*"
],
"overrides": [
{
"files": [
"test/**/*"
],
"rules": {
"max-len": [
"error",
{
"code": 120,
"ignoreTemplateLiterals": true,
"ignoreRegExpLiterals": true,
"ignoreStrings": true
}
]
}
}
]
}

3
.gitignore vendored
View File

@ -8,3 +8,6 @@ storage/uploads
config/local.* config/local.*
src/package.json src/package.json
intermediates/
dist/

View File

@ -1,12 +0,0 @@
{
"bundles": {
"app": "ts/app.ts",
"fm": "ts/fm.ts",
"url-shrinker": "ts/url-shrinker.ts",
"layout": "sass/layout.scss",
"error": "sass/error.scss",
"logo": "img/logo.svg",
"logo_png": "img/logox128.png",
"logo_png_xxl": "img/logox1024.png"
}
}

View File

@ -1,81 +0,0 @@
/* vietnamese */
@font-face {
font-family: 'Nunito Sans';
font-style: normal;
font-weight: 300;
font-display: swap;
src: local('Nunito Sans Light'), local('NunitoSans-Light'), url(https://fonts.gstatic.com/s/nunitosans/v5/pe03MImSLYBIv1o4X1M8cc8WAc5iU1EQVg.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Nunito Sans';
font-style: normal;
font-weight: 300;
font-display: swap;
src: local('Nunito Sans Light'), local('NunitoSans-Light'), url(https://fonts.gstatic.com/s/nunitosans/v5/pe03MImSLYBIv1o4X1M8cc8WAc5jU1EQVg.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Nunito Sans';
font-style: normal;
font-weight: 300;
font-display: swap;
src: local('Nunito Sans Light'), local('NunitoSans-Light'), url(https://fonts.gstatic.com/s/nunitosans/v5/pe03MImSLYBIv1o4X1M8cc8WAc5tU1E.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* vietnamese */
@font-face {
font-family: 'Nunito Sans';
font-style: normal;
font-weight: 400;
font-display: swap;
src: local('Nunito Sans Regular'), local('NunitoSans-Regular'), url(https://fonts.gstatic.com/s/nunitosans/v5/pe0qMImSLYBIv1o4X1M8cceyI9tScg.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Nunito Sans';
font-style: normal;
font-weight: 400;
font-display: swap;
src: local('Nunito Sans Regular'), local('NunitoSans-Regular'), url(https://fonts.gstatic.com/s/nunitosans/v5/pe0qMImSLYBIv1o4X1M8ccezI9tScg.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Nunito Sans';
font-style: normal;
font-weight: 400;
font-display: swap;
src: local('Nunito Sans Regular'), local('NunitoSans-Regular'), url(https://fonts.gstatic.com/s/nunitosans/v5/pe0qMImSLYBIv1o4X1M8cce9I9s.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* vietnamese */
@font-face {
font-family: 'Nunito Sans';
font-style: normal;
font-weight: 700;
font-display: swap;
src: local('Nunito Sans Bold'), local('NunitoSans-Bold'), url(https://fonts.gstatic.com/s/nunitosans/v5/pe03MImSLYBIv1o4X1M8cc8GBs5iU1EQVg.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Nunito Sans';
font-style: normal;
font-weight: 700;
font-display: swap;
src: local('Nunito Sans Bold'), local('NunitoSans-Bold'), url(https://fonts.gstatic.com/s/nunitosans/v5/pe03MImSLYBIv1o4X1M8cc8GBs5jU1EQVg.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Nunito Sans';
font-style: normal;
font-weight: 700;
font-display: swap;
src: local('Nunito Sans Bold'), local('NunitoSans-Bold'), url(https://fonts.gstatic.com/s/nunitosans/v5/pe03MImSLYBIv1o4X1M8cc8GBs5tU1E.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}

View File

@ -1,33 +0,0 @@
$primary: darken(#242b33, 2%);
$primaryForeground: #f0f0f0;
$secondary: lighten(#842cff, 10%);
$secondaryForeground: $primaryForeground;
$backgroundColor: darken($primary, 4%);
$defaultTextColor: #ffffff;
$headerBackground: transparent;
$headerContainer: true;
$footerBackground: transparent;
$panelBackground: darken($backgroundColor, 3.2%);
$inputBackground: darken($panelBackground, 4%);
$info: #4499ff;
$infoText: darken($info, 42%);
$infoColor: desaturate($infoText, 50%);
$success: #55ff55;
$successText: darken($success, 45%);
$successColor: desaturate($successText, 50%);
$warning: #ffcc00;
$warningText: darken($warning, 30%);
$warningColor: desaturate($warningText, 50%);
$error: #ff0000;
$errorText: darken($error, 30%);
$errorColor: desaturate($errorText, 50%);
// Responsivity
$mobileThreshold: 850px;
$desktopThreshold: 940px;

View File

@ -1,18 +0,0 @@
@import "layout";
@import "fm";
.file-upload-table {
@media (max-width: 550px) {
> thead > tr > th:nth-child(3),
> tbody > tr > td:nth-child(3) {
display: none;
}
}
@media (max-width: 785px) {
> thead > tr > th:nth-child(4),
> tbody > tr > td:nth-child(4) {
display: none;
}
}
}

View File

@ -1,90 +0,0 @@
@import "layout";
header, footer {
margin: 0;
padding: 0;
height: 0;
}
main {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
.messages {
margin-bottom: 32px;
}
.error-code {
font-size: 36px;
}
.error-message {
font-size: 32px;
}
.error-instructions {
margin-top: 32px;
font-size: 20px;
}
nav {
margin-top: 32px;
}
&::before {
content: "Oops";
position: absolute;
z-index: -1;
font-size: #{'min(50vh, 40vw)'};
opacity: 0.025;
}
}
.contact {
text-align: center;
padding: 8px;
}
.logo {
position: absolute;
top: 0;
left: 0;
width: 100%;
margin-top: 24px;
text-align: center;
a {
position: relative;
padding: 16px;
color: $defaultTextColor;
&:hover {
color: #fff;
&::before {
opacity: 0.2;
}
}
&::before {
content: "";
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
background-image: url(../img/logo.svg);
background-repeat: no-repeat;
background-position: center;
background-size: 64px;
opacity: 0.075;
filter: contrast(0);
}
}
}

View File

@ -1,11 +0,0 @@
@import "vars";
#file-upload {
padding: 8px;
background: $infoColor;
border-radius: 5px;
.name, .status {
text-align: center;
}
}

View File

@ -1,977 +0,0 @@
@import "vars";
@import 'fonts';
@import "responsivity_tools";
* {
box-sizing: border-box;
}
html, body {
height: 100%;
}
body {
display: flex;
flex-direction: column;
margin: 0;
font-family: "Nunito Sans", sans-serif;
font-size: 16px;
color: $defaultTextColor;
background-color: $backgroundColor;
}
@mixin tip {
position: relative;
.tip {
visibility: hidden;
position: absolute;
z-index: 10000;
pointer-events: none;
display: block;
width: max-content;
height: 30px;
padding: 4px 8px;
line-height: 22px;
top: calc(100% + 8px);
left: 50%;
transform: translateX(-50%);
text-align: center;
font-size: 18px;
color: $defaultTextColor;
opacity: 0;
transition: opacity ease-out 100ms, visibility step-end 150ms;
transition-delay: 0ms;
background-color: #000;
border-radius: 5px;
text-transform: initial;
font-weight: initial;
&.top {
top: auto;
bottom: calc(100% + 8px);
}
}
&:hover, &:active {
.tip {
visibility: visible;
opacity: 1;
transition: opacity ease-out 100ms;
transition-delay: 150ms;
}
}
}
body > header {
z-index: 50;
display: flex;
flex-direction: row-reverse;
justify-content: space-between;
align-items: center;
$headerHeight: 64px;
height: $headerHeight;
line-height: $headerHeight;
background: $headerBackground;
@if $headerContainer {
@include container;
}
@media (max-width: $mobileThreshold) {
padding: 0;
}
.logo {
display: flex;
flex-direction: row;
align-items: center;
padding: 0 16px 0 8px;
font-size: 24px;
color: $defaultTextColor;
&:hover {
color: lighten($defaultTextColor, 10%);
}
img {
width: initial;
height: calc(#{$headerHeight} - 16px);
margin-right: 8px;
flex-shrink: 0;
}
}
nav {
> ul {
position: fixed;
z-index: -1;
top: 0;
left: 0;
height: 100%;
transform: translateX(-100%);
transition: transform ease-out 150ms;
display: flex;
flex-direction: column;
margin: 0;
padding: $headerHeight 8px 8px;
font-size: 20px;
background: $panelBackground;
li {
position: relative;
list-style: none;
margin-top: 8px;
a, button {
position: relative;
margin: 0;
display: flex;
flex-direction: row;
align-items: center;
height: auto;
padding: 8px;
border-radius: 3px;
&:hover, &:active {
&:not(button) {
background-color: rgba(255, 255, 255, 0.07);
}
}
.feather {
--icon-size: 16px;
}
.tip {
position: static;
visibility: visible;
opacity: 1;
display: block;
height: auto;
margin-left: 8px;
padding: 0 0 0 4px;
transform: none;
font-size: 16px;
line-height: 16px;
color: inherit;
text-transform: uppercase;
font-weight: inherit;
background: transparent;
}
&:hover {
.tip {
visibility: visible;
opacity: 1;
transition: opacity ease-out 100ms;
transition-delay: 150ms;
}
}
}
button {
margin: 0;
height: 32px;
.feather {
margin-right: 0;
}
}
form {
display: flex;
justify-content: center;
align-items: center;
padding: 0;
}
&.auth-user {
img {
width: 48px;
height: 48px;
border-radius: 3px;
margin-right: 8px;
}
}
.dropdown {
position: initial;
display: block;
padding-left: 0;
}
}
> li:not(:first-child) {
border-top: 1px solid transparentize($defaultTextColor, 0.8);
padding-top: 8px;
}
&.open {
transform: translateX(0%);
box-shadow: 0 0 5px darken($panelBackground, 20%);
}
}
#menu-button {
position: fixed;
top: 0;
left: 0;
display: block;
margin: 0;
padding: 0 16px;
line-height: $headerHeight;
cursor: pointer;
background: transparent;
border-radius: 0;
.feather {
--icon-size: 28px;
margin: 0 8px;
}
}
hr {
border: 0;
border-bottom: 1px solid $defaultTextColor;
opacity: 0.2;
}
}
@media (min-width: $mobileThreshold) {
flex-direction: row;
nav {
#menu-button {
display: none;
}
ul {
position: static;
flex-direction: row;
transform: none;
padding: 0;
background: transparent;
li {
margin-top: 0;
margin-left: 8px;
&:last-child {
a, button, .button {
.tip {
left: unset;
right: 4px;
transform: none;
}
}
}
.dropdown {
position: absolute;
z-index: -1;
top: 100%;
right: 0;
display: none;
padding: 8px;
white-space: nowrap;
background: $panelBackground;
border-radius: 0 0 3px 3px;
box-shadow: 0 2px 2px transparentize(darken($panelBackground, 20%), 0.75);
border-top: 4px solid lighten($panelBackground, 5%);
li {
margin-left: 0;
&:not(:first-child) {
margin-top: 8px;
}
}
}
&:hover .dropdown {
display: block;
}
}
> li:not(:first-child) {
border-top: 0;
padding-top: 0;
}
}
}
}
}
body > footer {
padding: 8px;
margin-top: 8px;
text-align: center;
background-color: $footerBackground;
}
main {
flex: 1;
padding: 8px 0;
button, .button {
@include tip;
}
}
h1 {
text-align: center;
font-size: 32px;
& + p {
text-align: center;
font-size: 20px;
}
}
h1, h2 {
font-weight: 100;
}
h3, h4 {
font-weight: 300;
}
section > h2, .panel > h2 {
display: flex;
flex-direction: row;
align-items: center;
position: relative;
text-align: center;
margin-top: 4px;
font-size: 24px;
line-height: 1;
.feather {
margin: 0 16px 0 0;
opacity: 0.1;
}
&::after {
content: "";
flex: 1;
margin: 0 16px;
height: 0;
border-bottom: 1px solid $defaultTextColor;
opacity: 0.1;
}
}
section > hr, .panel > hr {
border: 0;
border-bottom: 1px solid $defaultTextColor;
opacity: 0.2;
margin: 8px 32px;
}
a {
color: $secondary;
text-decoration: none;
&:hover {
color: lighten($secondary, 30%);
}
.feather.feather-external-link {
--icon-size: 16px;
margin-left: 4px;
margin-top: -3px;
}
}
form {
padding: 8px 16px;
text-align: center;
.form-field:not(.hidden) {
display: flex;
flex-direction: column;
margin: 16px auto;
.control {
position: relative;
background: $inputBackground;
border-radius: 5px;
}
.feather.icon {
position: absolute;
top: 50%;
right: 8px;
transform: translateY(-50%);
z-index: 0;
--icon-size: 24px;
opacity: 0.75;
}
label {
position: absolute;
left: 8px;
top: 20px;
user-select: none;
font-size: 16px;
opacity: 0.75;
transition-property: top, font-size;
transition-duration: 150ms;
transition-timing-function: ease-out;
cursor: text;
}
[disabled] {
opacity: 0.5;
& ~ label {
opacity: 0.5;
cursor: default;
}
}
input, select, textarea, .input-group {
z-index: 1;
border: 0;
color: $defaultTextColor;
background: transparent;
font-size: 16px;
&:focus, &:not([value=""]), &[type="file"] {
~ label {
top: 8px;
font-size: 14px;
}
}
}
input, select, textarea, .form-display {
display: block;
padding: 32px 8px 8px 8px;
width: 100%;
height: 60px;
}
select {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
&::-ms-expand {
display: none;
}
& + .feather {
position: absolute;
pointer-events: none;
right: 8px;
top: 30px;
transition: transform 150ms ease-out;
}
// Temporary
&:focus + .feather {
transform: rotateX(180deg);
}
}
textarea {
resize: vertical;
min-height: 100px;
font-family: inherit;
}
input[type=color] {
height: calc(32px + 8px + 32px);
}
&.inline {
display: flex;
flex-direction: row;
.control {
display: flex;
flex-direction: row;
align-items: center;
flex-grow: 1;
input[type=checkbox] {
width: min-content;
height: min-content;
margin: 8px;
text-align: left;
& ~ label {
position: static;
flex-grow: 1;
display: inline;
padding: 8px;
font-size: 16px;
text-align: left;
}
}
}
}
.input-group {
display: flex;
flex-grow: 1;
flex-direction: row;
div {
position: relative;
flex: 1;
input {
width: 100%;
border: 0;
background: transparent;
}
}
}
}
.inline-fields {
display: flex;
flex-direction: row;
align-items: start;
margin: 16px auto;
.form-field {
flex: 1;
margin: 0;
}
> :not(.form-field) {
padding: 32px 8px 8px 8px;
}
+ {
.error, .hint {
margin-top: -16px;
margin-bottom: 16px;
}
}
}
.form-field, .inline-fields + {
.error, .hint {
padding: 2px;
text-align: left;
font-size: 14px;
.feather {
--icon-size: 14px;
}
}
.error {
color: $error;
}
}
}
button, .button {
display: inline-flex;
margin: 8px;
padding: 12px 16px;
border: 0;
border-radius: 5px;
cursor: pointer;
text-transform: uppercase;
font-size: 16px;
font-weight: bolder;
line-height: 16px;
.feather {
--icon-size: 16px;
margin-right: 8px;
}
.feather.last {
margin-right: 0;
margin-left: 8px;
}
&, &.primary {
color: $primaryForeground;
background-color: darken($secondary, 10%);
&:hover {
background-color: $secondary;
}
}
&.info {
background-color: $infoColor;
}
&.success {
background-color: $successColor;
}
&.warning {
background-color: $warningColor;
&:hover {
background-color: lighten($warningColor, 10%);
}
}
&.error, &.danger {
background-color: $errorColor;
&:hover {
background-color: lighten($errorColor, 10%);
}
}
&.transparent {
background-color: transparent;
}
&:hover {
color: $primaryForeground;
}
}
// ---
// --- Tables
// ---
td.actions {
> * {
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
form {
padding: 0;
display: inline;
}
button, .button {
margin: 0;
padding: 8px;
.feather {
margin-right: 0;
}
}
> *:not(:first-child) {
margin-left: 8px;
}
}
}
.data-table {
width: 100%;
text-align: left;
border-collapse: collapse;
th, td {
padding: 8px;
}
th {
border-bottom: 1px solid #39434a;
white-space: nowrap;
}
tr:nth-child(even) {
background-color: rgba(255, 255, 255, 0.03);
}
tr:hover {
background-color: rgba(255, 255, 255, 0.09);
}
thead tr:hover {
background-color: transparent;
}
th.shrink-col {
width: 0;
}
}
// ---
// --- Breadcrumb widget
// ---
.breadcrumb {
list-style: none;
display: flex;
flex-direction: row;
margin: 0;
padding: 8px;
> *:not(:first-child)::before {
content: '';
padding: 0 8px;
}
}
// ---
// --- Layout helpers
// ---
.center {
text-align: center;
}
.panel {
position: relative;
margin: 16px 0 48px;
padding: 8px;
background-color: $panelBackground;
border-radius: 5px;
p {
margin: 16px 8px;
}
> .feather:first-child {
position: absolute;
--icon-size: 24px;
opacity: 0.1;
top: 8px;
left: 8px;
}
}
.sub-panel {
margin: 32px 0;
padding: 1px 16px;
border: 2px solid lighten($panelBackground, 4%);
border-radius: 5px;
form > & {
margin: 32px -18px;
}
}
// ---
// --- Feather
// ---
.feather {
display: inline-flex;
justify-content: center;
align-items: center;
flex-shrink: 0;
width: var(--icon-size);
height: var(--icon-size);
--icon-size: 16px;
font-size: var(--icon-size);
stroke: currentColor;
stroke-width: 2;
stroke-linecap: square;
stroke-linejoin: miter;
fill: none;
vertical-align: middle;
h1 > &, h2 > &, h3 > & {
--icon-size: 24px;
}
}
// ---
// --- Helper classes
// ---
.message {
display: flex;
flex-direction: row;
align-items: center;
padding: 8px 16px;
border-radius: 5px;
.feather {
--icon-size: 24px;
margin-right: 8px;
}
&:not(&-discreet) {
background-color: rgba(255, 255, 255, 0.33);
&[data-type=info], &[data-type=question] {
background-color: $infoColor;
}
&[data-type=success] {
background-color: $successColor;
}
&[data-type=warning] {
background-color: $warningColor;
}
&[data-type=error] {
background-color: $errorColor;
}
}
&-discreet {
color: mix($panelBackground, #fff, 35%);
.feather {
--icon-size: 20px;
}
}
}
.messages .message:not(:last-child) {
margin-bottom: 8px;
}
.container > .messages:first-child {
margin-top: 16px;
}
.copyable-text {
display: flex;
flex-direction: row;
margin: 8px;
background-color: darken($backgroundColor, 2%);
border-radius: 5px;
overflow: hidden;
.title {
padding: 8px;
}
.content {
width: 0;
flex-grow: 1;
overflow: hidden;
white-space: nowrap;
padding: 8px;
}
.copy-button {
margin: 0;
padding: 0;
border-radius: 0;
.feather {
--icon-size: 20px;
margin: 8px;
}
}
}
.hidden {
display: none;
}
.progress-bar {
position: relative;
display: block;
margin: 8px;
padding: 4px;
background: #fff1;
border-radius: 5px;
overflow: hidden;
text-align: center;
.content {
position: relative;
}
&::before {
content: "";
display: block;
position: absolute;
left: 0;
top: 0;
width: var(--progress);
height: 100%;
transition: width ease-out 150ms;
background: $secondary;
}
}
.table-col-grow {
width: 100%;
}
.table-col-grow-cell {
> * {
display: flex;
flex-direction: row;
> * {
width: 0;
flex-grow: 1;
white-space: nowrap;
text-overflow: ellipsis;
}
* {
overflow: hidden;
text-overflow: ellipsis;
}
}
}
.pagination {
ul {
display: flex;
flex-direction: row;
list-style: none;
padding: 8px;
justify-content: center;
li {
a, &.active, &.ellipsis {
display: block;
min-width: 40px;
height: 40px;
padding: 4px;
line-height: 32px;
text-align:center;
&:hover:not(.active):not(.ellipsis) {
background-color: #fff5;
}
}
}
}
}

View File

@ -1,19 +0,0 @@
@import "vars";
@mixin container {
width: 100%;
padding: 0 8px;
@media (min-width: $mobileThreshold) {
margin: 0 auto;
padding: 0 16px;
}
@media (min-width: $desktopThreshold) {
width: $desktopThreshold;
}
}
.container {
@include container;
}

View File

@ -1,39 +0,0 @@
export default class PersistentWebsocket {
private webSocket?: WebSocket;
public constructor(
protected readonly url: string,
private readonly handler: MessageHandler,
protected readonly reconnectOnClose: boolean = true,
) {
}
public run(): void {
const _webSocket = this.webSocket = new WebSocket(this.url);
this.webSocket.addEventListener('open', () => {
console.debug('Websocket connected');
});
this.webSocket.addEventListener('message', (e) => {
this.handler(_webSocket, e);
});
this.webSocket.addEventListener('error', (e) => {
console.error('Websocket error', e);
});
this.webSocket.addEventListener('close', (e) => {
this.webSocket = undefined;
console.debug('Websocket closed', e.code, e.reason);
if (this.reconnectOnClose) {
setTimeout(() => this.run(), 1000);
}
});
}
public send(data: string): void {
if (!this.webSocket) throw new Error('WebSocket not connected');
this.webSocket.send(data);
}
}
export type MessageHandler = (webSocket: WebSocket, e: MessageEvent) => void;

View File

@ -1,10 +0,0 @@
import './external_links';
import './message_icons';
import './forms';
import './copyable_text';
import './tooltips-and-dropdowns';
import './main_menu';
import './font-awesome';
// css
import '../sass/app.scss';

View File

@ -1,23 +0,0 @@
document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('.copyable-text').forEach(el => {
const contentEl = el.querySelector('.content');
const selection = window.getSelection();
if (contentEl && selection) {
contentEl.addEventListener('click', () => {
selection.selectAllChildren(contentEl);
});
el.querySelector('.copy-button')?.addEventListener('click', () => {
selection.selectAllChildren(contentEl);
document.execCommand('copy');
});
}
});
document.querySelectorAll<HTMLElement>('.copy-button[data-content]').forEach(el => {
el.addEventListener('click', () => {
navigator.clipboard.writeText(`${el.dataset.content}`)
.then(() => console.log('copy success'))
.catch(console.error);
});
});
});

View File

@ -1,11 +0,0 @@
import feather from "feather-icons";
document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('a[target="_blank"]').forEach(el => {
if (!el.classList.contains('no-icon')) {
el.innerHTML += `<i data-feather="external-link"></i>`;
}
});
feather.replace();
});

View File

@ -1,193 +0,0 @@
import {applyFormMessages} from "./forms";
document.addEventListener('DOMContentLoaded', () => {
const form = document.querySelector<HTMLFormElement>('#upload-form');
if (!form) return;
const upload = document.getElementById('file-upload');
const uploadLink = document.querySelector<HTMLLinkElement>('#file-upload-link');
const uploadField = document.querySelector<HTMLInputElement>('#field-upload');
const neverExpireCheckbox = document.querySelector<HTMLInputElement>('#field-never_expire');
const expireAfterDaysField = document.querySelector<HTMLInputElement>('#field-expire_after_days');
const autogenUrlCheckbox = document.querySelector<HTMLInputElement>('#field-autogen_url');
const slugField = document.querySelector<HTMLInputElement>('#field-slug');
if (expireAfterDaysField && neverExpireCheckbox) {
const updateExpireAfterDaysField = () => {
expireAfterDaysField.disabled = neverExpireCheckbox.checked;
const parent = expireAfterDaysField.parentElement?.parentElement;
if (parent) {
if (neverExpireCheckbox.checked) {
parent.classList.add('hidden');
} else {
parent.classList.remove('hidden');
}
}
};
neverExpireCheckbox.addEventListener('change', updateExpireAfterDaysField);
updateExpireAfterDaysField();
}
if (slugField && autogenUrlCheckbox) {
const updateSlugField = () => {
slugField.disabled = autogenUrlCheckbox.checked;
const parent = slugField.parentElement?.parentElement;
if (parent) {
if (autogenUrlCheckbox.checked) {
parent.classList.add('hidden');
} else {
parent.classList.remove('hidden');
}
}
};
autogenUrlCheckbox.addEventListener('change', updateSlugField);
updateSlugField();
}
let uploadForm: UploadForm | undefined;
form.addEventListener('submit', e => {
e.preventDefault();
if (upload && uploadLink && uploadField && uploadField.files && (!uploadForm || uploadForm.isFinished())) {
uploadForm = new UploadForm(form, upload, uploadLink, uploadField.files[0].name);
uploadForm.updateView();
uploadForm.start();
}
});
});
const units = ['K', 'M', 'G', 'T'];
class UploadForm {
private finished: boolean = false;
private readonly progressBar: HTMLElement | null;
private readonly progressBarContent: HTMLElement | null;
private readonly status: HTMLElement | null;
private speed: HTMLElement | null;
private xferSpeed: number[] = [];
private lastTransferTime: number | null = null;
private lastLoaded: number = 0;
private xhr: XMLHttpRequest;
public constructor(
private form: HTMLFormElement,
private upload: HTMLElement,
private uploadLink: HTMLLinkElement,
private fileName: string,
) {
this.progressBar = this.upload.querySelector('.progress-bar');
this.progressBarContent = this.progressBar?.querySelector('.content') || null;
this.status = this.upload.querySelector('.status');
this.speed = this.status?.querySelector('.speed') || null;
if (!this.progressBar)
throw new Error('Invalid html');
this.xhr = new XMLHttpRequest();
this.xhr.responseType = 'json';
this.xhr.upload.addEventListener('progress', e => {
if (this.progressBar && this.progressBarContent) {
if (e.lengthComputable) {
this.progressBar.classList.remove('undefined');
const percent = (e.loaded / e.total * 100).toFixed(2) + '%';
this.progressBar.style.setProperty('--progress', `${percent}`);
this.progressBarContent.innerText = percent;
this.updateSpeed(e.loaded);
} else {
this.progressBar.classList.add('undefined');
}
}
});
this.xhr.upload.addEventListener('loadstart', () => {
this.status?.classList.remove('hidden');
});
this.xhr.addEventListener('load', () => {
this.finished = true;
const response = this.xhr.response;
console.log('done', response);
if (response.status === 'error') {
if (response.messages) {
this.restoreView();
applyFormMessages(this.form, response.messages);
}
} else if (response.url) {
if (this.status) {
this.status.innerHTML = 'Done!';
}
const uploadLinkContent = this.uploadLink.querySelector<HTMLElement>('.content');
if (uploadLinkContent) {
uploadLinkContent.innerText = response.url;
}
this.uploadLink.classList.remove('hidden');
} else {
window.location.reload();
}
});
this.xhr.addEventListener('error', (e) => {
this.finished = true;
console.error('error', e);
if (this.status) {
this.status.innerHTML = 'Error; upload was interrupted.';
}
});
}
public isFinished(): boolean {
return this.finished;
}
public updateView(): void {
const uploadName = this.upload.querySelector<HTMLElement>('.name');
if (uploadName) {
uploadName.innerText = this.fileName;
}
this.form.classList.add('hidden');
this.upload.classList.remove('hidden');
if (this.status) {
this.status.innerHTML = `Uploading @ <span class="speed">--</span>`;
this.speed = this.status.querySelector('.speed');
}
}
public restoreView(): void {
if (this.status) {
this.status.classList.add('hidden');
}
this.upload.classList.add('hidden');
this.form.classList.remove('hidden');
}
public start(): void {
const formData = new FormData(this.form);
this.xhr.open('POST', this.form.action);
this.xhr.send(formData);
}
public updateSpeed(loaded: number): void {
const time = new Date().getTime();
if (this.lastTransferTime) {
this.xferSpeed.push((loaded - this.lastLoaded) / (time - this.lastTransferTime));
if (this.xferSpeed.length > 100) this.xferSpeed = this.xferSpeed.slice(1);
let speed = this.xferSpeed.reduce((v, c) => v + c) / this.xferSpeed.length;
let unit = 0;
while (speed >= 1000 && unit < units.length - 1) {
speed /= 1000;
unit++;
}
if (this.speed) {
this.speed.innerText = speed.toFixed(2) + units[unit] + 'Bps';
}
}
this.lastTransferTime = time;
this.lastLoaded = loaded;
}
}

View File

@ -1,4 +0,0 @@
import '../../node_modules/@fortawesome/fontawesome-free/scss/fontawesome.scss';
import '../../node_modules/@fortawesome/fontawesome-free/scss/regular.scss';
import '../../node_modules/@fortawesome/fontawesome-free/scss/solid.scss';
import '../../node_modules/@fortawesome/fontawesome-free/scss/brands.scss';

View File

@ -1,43 +0,0 @@
/*
* For labels to update their state (css selectors based on the value attribute)
*/
import {ValidationError} from "swaf/db/Validator";
export function updateInputs(): void {
document.querySelectorAll<HTMLInputElement | HTMLTextAreaElement>('input, textarea').forEach(el => {
if (!el.dataset.inputSetup) {
el.dataset.inputSetup = 'true';
if (el.type !== 'checkbox') {
el.setAttribute('value', el.value);
el.addEventListener('change', () => {
el.setAttribute('value', el.value);
});
}
}
});
}
document.addEventListener('DOMContentLoaded', () => {
updateInputs();
});
export function applyFormMessages(
formElement: HTMLFormElement,
messages: { [p: string]: ValidationError<unknown> },
): void {
for (const fieldName of Object.keys(messages)) {
const field = formElement.querySelector('#field-' + fieldName);
if (!field) continue;
let parent = field.parentElement;
while (parent && !parent.classList.contains('form-field')) parent = parent.parentElement;
let err = field.querySelector('.error');
if (!err) {
err = document.createElement('div');
err.classList.add('error');
parent?.insertBefore(err, parent.querySelector('.hint') || parent);
}
err.innerHTML = `<i data-feather="x-circle"></i> ${messages[fieldName].message}`;
}
}

View File

@ -1,21 +0,0 @@
document.addEventListener('DOMContentLoaded', () => {
const menuButton = document.getElementById('menu-button');
const mainMenu = document.getElementById('main-menu');
if (menuButton) {
menuButton.addEventListener('click', (e) => {
e.stopPropagation();
mainMenu?.classList.toggle('open');
});
}
if (mainMenu) {
mainMenu.addEventListener('click', (e) => {
e.stopPropagation();
});
document.addEventListener('click', () => {
mainMenu.classList.remove('open');
});
}
});

View File

@ -1,26 +0,0 @@
import feather from "feather-icons";
document.addEventListener('DOMContentLoaded', () => {
const messageTypeToIcon: { [p: string]: string } = {
info: 'info',
success: 'check',
warning: 'alert-triangle',
error: 'x-circle',
question: 'help-circle',
};
document.querySelectorAll<HTMLElement>('.message').forEach(el => {
const icon = el.querySelector('.icon');
const type = el.dataset['type'];
if (!icon || !type) return;
if (!messageTypeToIcon[type]) throw new Error(`No icon for type ${type}`);
const svgContainer = document.createElement('div');
svgContainer.innerHTML = feather.icons[messageTypeToIcon[type]].toSvg();
if (svgContainer.firstChild) el.insertBefore(svgContainer.firstChild, icon);
icon.remove();
});
feather.replace();
});

View File

@ -1,31 +0,0 @@
export function updateTooltips(): void {
console.debug('Updating tooltips');
const elements = document.querySelectorAll<HTMLElement>('.tip, .dropdown');
// Calculate max potential displacement
let max = 0;
elements.forEach(el => {
const box = el.getBoundingClientRect();
if (max < box.height) max = box.height;
});
// Prevent displacement
elements.forEach(el => {
if (!el.dataset.tooltipSetup) {
el.dataset.tooltipSetup = 'true';
const box = el.getBoundingClientRect();
if (box.bottom >= document.body.clientHeight - (max + 32)) {
el.classList.add('top');
}
}
});
}
document.addEventListener('DOMContentLoaded', () => {
window.addEventListener('popstate', () => {
updateTooltips();
});
window.requestAnimationFrame(() => {
updateTooltips();
});
});

View File

@ -1,24 +0,0 @@
document.addEventListener('DOMContentLoaded', () => {
const form = document.getElementById('url-shrink-form');
if (!form) return;
const autogenUrlCheckbox = document.querySelector<HTMLInputElement>('#field-autogen_url');
const slugField = document.querySelector<HTMLInputElement>('#field-slug');
if (slugField && autogenUrlCheckbox) {
const updateSlugField = () => {
slugField.disabled = autogenUrlCheckbox.checked;
const parent = slugField.parentElement?.parentElement;
if (parent) {
if (autogenUrlCheckbox.checked) {
parent.classList.add('hidden');
} else {
parent.classList.remove('hidden');
}
}
};
autogenUrlCheckbox.addEventListener('change', updateSlugField);
updateSlugField();
}
});

View File

@ -1,6 +1,6 @@
{ {
"name": "ily.li", "name": "ily.li",
"version": "1.0.3", "version": "1.1.0",
"description": "Self-hosted file pusher", "description": "Self-hosted file pusher",
"repository": "https://eternae.ink/ashpie/ily.li", "repository": "https://eternae.ink/ashpie/ily.li",
"author": "Alice Gaudon <alice@gaudon.pro>", "author": "Alice Gaudon <alice@gaudon.pro>",
@ -10,58 +10,50 @@
"test": "jest --verbose --runInBand", "test": "jest --verbose --runInBand",
"clean": "node scripts/clean.js", "clean": "node scripts/clean.js",
"prepare-sources": "node scripts/prepare-sources.js", "prepare-sources": "node scripts/prepare-sources.js",
"compile": "yarn clean && tsc", "compile": "yarn clean && yarn prepare-sources && tsc --build",
"build": "yarn prepare-sources && yarn compile && webpack --mode production", "build": "yarn compile && node . pre-compile-views && node scripts/dist.js",
"dev": "yarn prepare-sources && concurrently -k -n \"Typescript,Node,Webpack,Maildev\" -p \"[{name}]\" -c \"blue,green,red,yellow\" \"tsc --watch\" \"nodemon\" \"webpack --watch --mode development\" \"maildev\"", "build-production": "NODE_ENV=production yarn build",
"start": "yarn build && node", "dev": "yarn compile && concurrently -k -n \"Maildev,Typescript,ViewPreCompile,Node\" -p \"[{name}]\" -c \"yellow,blue,red,green\" \"maildev\" \"tsc --build --watch --preserveWatchOutput\" \"nodemon -i public -i intermediates -- pre-compile-views --watch\" \"nodemon -i public -i intermediates\"",
"lint": "eslint ." "lint": "eslint .",
"start": "yarn build-production && node ."
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "^7.9.0", "@tsconfig/svelte": "^3.0.0",
"@babel/preset-env": "^7.9.5", "@types/config": "^0.0.41",
"@fortawesome/fontawesome-free": "^5.14.0",
"@types/config": "^0.0.38",
"@types/express": "^4.17.6", "@types/express": "^4.17.6",
"@types/express-session": "^1.17.0", "@types/express-session": "^1.17.0",
"@types/feather-icons": "^4.7.0", "@types/formidable": "^2.0.0",
"@types/formidable": "^1.0.31", "@types/jest": "^27.0.3",
"@types/jest": "^26.0.4",
"@types/mysql": "^2.15.15", "@types/mysql": "^2.15.15",
"@types/node": "^14.6.3", "@types/node": "^17.0.4",
"@types/nodemailer": "^6.4.0", "@types/nodemailer": "^6.4.0",
"@types/nunjucks": "^3.1.3", "@types/nunjucks": "^3.1.3",
"@types/ws": "^7.2.6", "@types/ws": "^8.2.0",
"@typescript-eslint/eslint-plugin": "^4.3.0", "@typescript-eslint/eslint-plugin": "^5.4.0",
"@typescript-eslint/parser": "^4.3.0", "@typescript-eslint/parser": "^5.4.0",
"babel-loader": "^8.1.0", "concurrently": "^7.0.0",
"concurrently": "^6.0.0", "eslint": "^8.3.0",
"css-loader": "^5.0.0", "eslint-plugin-import": "^2.25.3",
"eslint": "^7.10.0", "eslint-plugin-simple-import-sort": "^7.0.0",
"feather-icons": "^4.28.0", "eslint-plugin-svelte3": "^3.2.1",
"file-loader": "^6.0.0",
"imagemin": "^7.0.0",
"imagemin-gifsicle": "^7.0.0", "imagemin-gifsicle": "^7.0.0",
"imagemin-mozjpeg": "^9.0.0", "imagemin-mozjpeg": "^10.0.0",
"imagemin-pngquant": "^9.0.0", "imagemin-pngquant": "^9.0.2",
"imagemin-svgo": "^9.0.0", "imagemin-svgo": "^10.0.0",
"img-loader": "^3.0.1", "imagemin-webp": "^7.0.0",
"jest": "^26.1.0", "jest": "^27.0.4",
"maildev": "^1.1.0", "maildev": "^1.1.0",
"mini-css-extract-plugin": "^1.2.1",
"node-sass": "^5.0.0",
"nodemon": "^2.0.3", "nodemon": "^2.0.3",
"sass-loader": "^11.0.1", "sass": "^1.32.12",
"terser-webpack-plugin": "^5.0.3", "svelte": "^3.44.2",
"ts-jest": "^26.1.1", "svgo": "^2.3.0",
"ts-loader": "^9.1.0", "ts-jest": "^27.0.3",
"typescript": "^4.0.2", "typescript": "^4.0.2"
"webpack": "^5.3.2",
"webpack-cli": "^4.1.0"
}, },
"dependencies": { "dependencies": {
"config": "^3.3.1", "config": "^3.3.1",
"express": "^4.17.1", "express": "^4.17.1",
"formidable": "^1.2.2", "formidable": "^2.0.1",
"swaf": "^0.23.0" "swaf": "^0.25.1"
} }
} }

22
scripts/_functions.js Normal file
View File

@ -0,0 +1,22 @@
const fs = require('fs');
const path = require('path');
function copyRecursively(file, destination) {
const target = path.join(destination, path.basename(file));
if (fs.statSync(file).isDirectory()) {
console.log('mkdir', target);
fs.mkdirSync(target, {recursive: true});
fs.readdirSync(file).forEach(f => {
copyRecursively(path.join(file, f), target);
});
} else {
console.log('> cp ', target);
fs.copyFileSync(file, target);
}
}
module.exports = {
copyRecursively,
};

View File

@ -1,7 +1,9 @@
const fs = require('fs'); const fs = require('fs');
[ [
'intermediates',
'dist', 'dist',
'public',
].forEach(file => { ].forEach(file => {
if (fs.existsSync(file)) { if (fs.existsSync(file)) {
console.log('Cleaning', file, '...'); console.log('Cleaning', file, '...');

22
scripts/dist.js Normal file
View File

@ -0,0 +1,22 @@
const fs = require('fs');
const path = require('path');
const {copyRecursively} = require('./_functions.js');
[
'yarn.lock',
'README.md',
'config/',
].forEach(file => {
copyRecursively(file, 'dist');
});
fs.mkdirSync('dist/types', {recursive: true});
fs.readdirSync('src/types').forEach(file => {
copyRecursively(path.join('src/types', file), 'dist/types');
});
fs.readdirSync('src/assets').forEach(file => {
copyRecursively(path.join('src/assets', file), 'dist/assets');
});

View File

@ -1,4 +1,28 @@
const fs = require('fs'); const fs = require('fs');
const path = require('path'); const path = require('path');
fs.copyFileSync('package.json', path.join('src', 'package.json')); // These folders must exist for nodemon not to loop indefinitely.
[
'public',
'dist',
'intermediates',
'intermediates/assets',
].forEach(dir => {
if (!fs.existsSync(dir)) fs.mkdirSync(dir);
});
// Symlink to build/common
const commonLocalSymlink = path.resolve('intermediates/common-local');
if (!fs.existsSync(commonLocalSymlink)) {
const target = path.resolve('dist/common-local');
fs.symlinkSync(target, commonLocalSymlink);
}
const commonSymlink = path.resolve('intermediates/common');
if (!fs.existsSync(commonSymlink)) {
const target = path.resolve('node_modules/swaf/common');
fs.symlinkSync(target, commonSymlink);
}
// Copy package.json
fs.copyFileSync('package.json', 'dist/package.json');

View File

@ -1,57 +1,65 @@
import Application from "swaf/Application"; import Application from "swaf/Application";
import Migration, {MigrationType} from "swaf/db/Migration"; import AccountController from "swaf/auth/AccountController";
import CreateMigrationsTable from "swaf/migrations/CreateMigrationsTable"; import AuthComponent from "swaf/auth/AuthComponent";
import AuthController from "swaf/auth/AuthController";
import AddUsedToMagicLinksMigration from "swaf/auth/magic_link/AddUsedToMagicLinksMigration";
import CreateMagicLinksTableMigration from "swaf/auth/magic_link/CreateMagicLinksTableMigration";
import MagicLinkAuthMethod from "swaf/auth/magic_link/MagicLinkAuthMethod";
import MagicLinkController from "swaf/auth/magic_link/MagicLinkController";
import MagicLinkWebSocketListener from "swaf/auth/magic_link/MagicLinkWebSocketListener";
import MakeMagicLinksSessionNotUniqueMigration from "swaf/auth/magic_link/MakeMagicLinksSessionNotUniqueMigration";
import AddApprovedFieldToUsersTableMigration from "swaf/auth/migrations/AddApprovedFieldToUsersTableMigration";
import CreateUsersAndUserEmailsTableMigration from "swaf/auth/migrations/CreateUsersAndUserEmailsTableMigration";
import AddPasswordToUsersMigration from "swaf/auth/password/AddPasswordToUsersMigration";
import PasswordAuthMethod from "swaf/auth/password/PasswordAuthMethod";
import AutoUpdateComponent from "swaf/components/AutoUpdateComponent";
import CsrfProtectionComponent from "swaf/components/CsrfProtectionComponent";
import ExpressAppComponent from "swaf/components/ExpressAppComponent"; import ExpressAppComponent from "swaf/components/ExpressAppComponent";
import NunjucksComponent from "swaf/components/NunjucksComponent"; import FormHelperComponent from "swaf/components/FormHelperComponent";
import MysqlComponent from "swaf/components/MysqlComponent"; import FrontendToolsComponent from "swaf/components/FrontendToolsComponent";
import LogRequestsComponent from "swaf/components/LogRequestsComponent"; import LogRequestsComponent from "swaf/components/LogRequestsComponent";
import MailComponent from "swaf/components/MailComponent";
import MaintenanceComponent from "swaf/components/MaintenanceComponent";
import MysqlComponent from "swaf/components/MysqlComponent";
import PreviousUrlComponent from "swaf/components/PreviousUrlComponent";
import RedisComponent from "swaf/components/RedisComponent"; import RedisComponent from "swaf/components/RedisComponent";
import ServeStaticDirectoryComponent from "swaf/components/ServeStaticDirectoryComponent"; import ServeStaticDirectoryComponent from "swaf/components/ServeStaticDirectoryComponent";
import MaintenanceComponent from "swaf/components/MaintenanceComponent";
import MailComponent from "swaf/components/MailComponent";
import SessionComponent from "swaf/components/SessionComponent"; import SessionComponent from "swaf/components/SessionComponent";
import FormHelperComponent from "swaf/components/FormHelperComponent";
import CsrfProtectionComponent from "swaf/components/CsrfProtectionComponent";
import WebSocketServerComponent from "swaf/components/WebSocketServerComponent"; import WebSocketServerComponent from "swaf/components/WebSocketServerComponent";
import AboutController from "./controllers/AboutController"; import Migration, {MigrationType} from "swaf/db/Migration";
import AutoUpdateComponent from "swaf/components/AutoUpdateComponent"; import AssetCompiler from "swaf/frontend/AssetCompiler";
import MagicLinkWebSocketListener from "swaf/auth/magic_link/MagicLinkWebSocketListener"; import CopyAssetPreCompiler from "swaf/frontend/CopyAssetPreCompiler";
import FileController from "./controllers/FileController"; import MailViewEngine from "swaf/frontend/MailViewEngine";
import CreateAuthTokensTable from "./migrations/CreateAuthTokensTable"; import NunjucksViewEngine from "swaf/frontend/NunjucksViewEngine";
import AuthComponent from "swaf/auth/AuthComponent"; import ScssAssetPreCompiler from "swaf/frontend/ScssAssetPreCompiler";
import CreateFilesTable from "./migrations/CreateFilesTable"; import SvelteViewEngine from "swaf/frontend/SvelteViewEngine";
import IncreaseFilesSizeField from "./migrations/IncreaseFilesSizeField"; import TypeScriptPreCompiler from "swaf/frontend/TypeScriptPreCompiler";
import CreateUrlRedirectsTable from "./migrations/CreateUrlRedirectsTable";
import AuthTokenController from "./controllers/AuthTokenController";
import URLRedirectController from "./controllers/URLRedirectController";
import LinkController from "./controllers/LinkController";
import BackendController from "swaf/helpers/BackendController"; import BackendController from "swaf/helpers/BackendController";
import DummyMigration from "swaf/migrations/DummyMigration";
import DropLegacyLogsTable from "swaf/migrations/DropLegacyLogsTable";
import CreateUsersAndUserEmailsTableMigration from "swaf/auth/migrations/CreateUsersAndUserEmailsTableMigration";
import CreateMagicLinksTableMigration from "swaf/auth/magic_link/CreateMagicLinksTableMigration";
import AddApprovedFieldToUsersTableMigration from "swaf/auth/migrations/AddApprovedFieldToUsersTableMigration";
import PreviousUrlComponent from "swaf/components/PreviousUrlComponent";
import MagicLinkAuthMethod from "swaf/auth/magic_link/MagicLinkAuthMethod";
import {MAGIC_LINK_MAIL} from "swaf/Mails";
import PasswordAuthMethod from "swaf/auth/password/PasswordAuthMethod";
import MailController from "swaf/mail/MailController"; import MailController from "swaf/mail/MailController";
import AccountController from "swaf/auth/AccountController"; import {MAGIC_LINK_MAIL} from "swaf/Mails";
import AuthController from "swaf/auth/AuthController"; import CreateMigrationsTable from "swaf/migrations/CreateMigrationsTable";
import MagicLinkController from "swaf/auth/magic_link/MagicLinkController"; import DropLegacyLogsTable from "swaf/migrations/DropLegacyLogsTable";
import AddUsedToMagicLinksMigration from "swaf/auth/magic_link/AddUsedToMagicLinksMigration"; import DummyMigration from "swaf/migrations/DummyMigration";
import MakeMagicLinksSessionNotUniqueMigration from "swaf/auth/magic_link/MakeMagicLinksSessionNotUniqueMigration";
import AddPasswordToUsersMigration from "swaf/auth/password/AddPasswordToUsersMigration"; import AboutController from "./controllers/AboutController.js";
import DeleteOldFilesJobComponent from "./DeleteOldFilesJobComponent"; import AuthTokenController from "./controllers/AuthTokenController.js";
import packageJson = require('./package.json'); import FileController from "./controllers/FileController.js";
import ReplaceTtlWithExpiresAtFilesTable from "./migrations/ReplaceTtlWithExpiresAtFilesTable"; import LinkController from "./controllers/LinkController.js";
import URLRedirectController from "./controllers/URLRedirectController.js";
import DeleteOldFilesJobComponent from "./DeleteOldFilesJobComponent.js";
import CreateAuthTokensTable from "./migrations/CreateAuthTokensTable.js";
import CreateFilesTable from "./migrations/CreateFilesTable.js";
import CreateUrlRedirectsTable from "./migrations/CreateUrlRedirectsTable.js";
import IncreaseFilesSizeField from "./migrations/IncreaseFilesSizeField.js";
import ReplaceTtlWithExpiresAtFilesTable from "./migrations/ReplaceTtlWithExpiresAtFilesTable.js";
export default class App extends Application { export default class App extends Application {
public constructor( public constructor(
version: string,
private readonly addr: string, private readonly addr: string,
private readonly port: number, private readonly port: number,
) { ) {
super(packageJson.version); super(version);
} }
protected getMigrations(): MigrationType<Migration>[] { protected getMigrations(): MigrationType<Migration>[] {
@ -91,18 +99,27 @@ export default class App extends Application {
this.use(new ServeStaticDirectoryComponent('node_modules/feather-icons/dist', '/icons')); this.use(new ServeStaticDirectoryComponent('node_modules/feather-icons/dist', '/icons'));
// Dynamic views and routes // Dynamic views and routes
this.use(new NunjucksComponent()); const intermediateDirectory = 'intermediates/assets';
const assetCompiler = new AssetCompiler(intermediateDirectory, 'public');
const additionalViewPaths = ['test/assets'];
this.use(new FrontendToolsComponent(
assetCompiler,
new CopyAssetPreCompiler(intermediateDirectory, '', 'json', additionalViewPaths, false),
new ScssAssetPreCompiler(intermediateDirectory, assetCompiler.targetDir, 'scss', additionalViewPaths),
new CopyAssetPreCompiler(intermediateDirectory, 'img', 'svg', additionalViewPaths, true),
new TypeScriptPreCompiler(intermediateDirectory, additionalViewPaths),
new SvelteViewEngine(intermediateDirectory, ...additionalViewPaths),
new NunjucksViewEngine(intermediateDirectory, ...additionalViewPaths),
));
this.use(new PreviousUrlComponent()); this.use(new PreviousUrlComponent());
// Maintenance // Maintenance
this.use(new MaintenanceComponent(this, () => { this.use(new MaintenanceComponent());
return this.as(RedisComponent).canServe() && this.as(MysqlComponent).canServe();
}));
this.use(new AutoUpdateComponent()); this.use(new AutoUpdateComponent());
// Services // Services
this.use(new MysqlComponent()); this.use(new MysqlComponent());
this.use(new MailComponent()); this.use(new MailComponent(new MailViewEngine(intermediateDirectory, ...additionalViewPaths)));
// Session // Session
this.use(new RedisComponent()); this.use(new RedisComponent());
@ -116,7 +133,7 @@ export default class App extends Application {
this.use(new CsrfProtectionComponent()); this.use(new CsrfProtectionComponent());
// WebSocket server // WebSocket server
this.use(new WebSocketServerComponent(this, this.as(ExpressAppComponent), this.as(RedisComponent))); this.use(new WebSocketServerComponent());
// Jobs // Jobs

View File

@ -1,10 +1,11 @@
import ApplicationComponent from "swaf/ApplicationComponent";
import FileModel from "./models/FileModel";
import {logger} from "swaf/Logger";
import config from "config"; import config from "config";
import {WhereTest} from "swaf/db/ModelQuery"; import ApplicationComponent from "swaf/ApplicationComponent";
import MysqlComponent from "swaf/components/MysqlComponent"; import MysqlComponent from "swaf/components/MysqlComponent";
import FileController from "./controllers/FileController"; import {WhereTest} from "swaf/db/ModelQuery";
import {logger} from "swaf/Logger";
import FileController from "./controllers/FileController.js";
import FileModel from "./models/FileModel.js";
import Timeout = NodeJS.Timeout; import Timeout = NodeJS.Timeout;
export default class DeleteOldFilesJobComponent extends ApplicationComponent { export default class DeleteOldFilesJobComponent extends ApplicationComponent {
@ -12,7 +13,7 @@ export default class DeleteOldFilesJobComponent extends ApplicationComponent {
private readonly interval: number = config.get<number>('delete_old_files_interval'); private readonly interval: number = config.get<number>('delete_old_files_interval');
public async start(): Promise<void> { public async start(): Promise<void> {
if (this.getApp().as(MysqlComponent).canServe()) { if (this.getApp().as(MysqlComponent).isReady()) {
await this.run(); await this.run();
} }
@ -33,7 +34,7 @@ export default class DeleteOldFilesJobComponent extends ApplicationComponent {
} }
this.timeout = setInterval(() => { this.timeout = setInterval(() => {
if (this.getApp().as(MysqlComponent).canServe()) { if (this.getApp().as(MysqlComponent).isReady()) {
this.run().catch(err => logger.error(err)); this.run().catch(err => logger.error(err));
} }
}, this.interval); }, this.interval);

View File

@ -1,7 +1,8 @@
import config from "config"; import config from "config";
import FileModel from "./models/FileModel";
import {ServerError} from "swaf/HttpError";
import {nanoid} from "nanoid"; import {nanoid} from "nanoid";
import {ServerError} from "swaf/HttpError";
import FileModel from "./models/FileModel.js";
export default async function generateSlug(tries: number): Promise<string> { export default async function generateSlug(tries: number): Promise<string> {
let i = 0; let i = 0;

View File

Before

Width:  |  Height:  |  Size: 2.3 KiB

After

Width:  |  Height:  |  Size: 2.3 KiB

View File

Before

Width:  |  Height:  |  Size: 37 KiB

After

Width:  |  Height:  |  Size: 37 KiB

View File

Before

Width:  |  Height:  |  Size: 3.8 KiB

After

Width:  |  Height:  |  Size: 3.8 KiB

3
src/assets/package.json Normal file
View File

@ -0,0 +1,3 @@
{
"type": "commonjs"
}

117
src/assets/scss/_vars.scss Normal file
View File

@ -0,0 +1,117 @@
//
// --- Color palette ---
//
$onLight: #222;
$onDark: #eee;
// Primary
$primary: darken(#842cff, 17.5%);
$primaryLight: lighten($primary, 10%);
$onPrimary: $onDark;
$primaryOnBackground: $primary;
$primaryLightOnBackground: $primaryLight;
$primaryOnSurface: $primary;
$primaryLightOnSurface: $primaryLight;
$primaryDarkMode: $primary;
$primaryLightDarkMode: lighten($primaryDarkMode, 23%);
$onPrimaryDarkMode: $onDark;
$primaryOnBackgroundDarkMode: lighten($primaryDarkMode, 20%);
$primaryLightOnBackgroundDarkMode: $primaryLightDarkMode;
$primaryOnSurfaceDarkMode: lighten($primaryDarkMode, 29%);
$primaryLightOnSurfaceDarkMode: lighten($primaryOnSurfaceDarkMode, 15%);
// Secondary
$secondary: #f21170;
$onSecondary: $onLight;
$secondaryDarkMode: $secondary;
$onSecondaryDarkMode: $onSecondary;
// Background
$backgroundBase: #eee;
$background: mix($backgroundBase, $primary, 98%);
$onBackground: $onLight;
$backgroundBaseDarkMode: #222;
$backgroundDarkMode: mix($backgroundBaseDarkMode, $primaryDarkMode, 98%);
$onBackgroundDarkMode: $onDark;
// Surface
$surface: lighten($background, 6%);
$onSurface: $onLight;
$surfaceDarkMode: darken($backgroundDarkMode, 4.5%);
$onSurfaceDarkMode: $onDark;
// Subsurface
$subsurface: darken($surface, 3%);
$onSubsurface: $onLight;
$subsurfaceDarkMode: darken($surfaceDarkMode, 3%);
$onSubsurfaceDarkMode: $onDark;
// Input
$input: darken($surface, 5%);
$onInput: $onLight;
$inputDarkMode: darken($surfaceDarkMode, 5%);
$onInputDarkMode: $onDark;
//
// --- Layout ---
//
$header: $surface;
$headerDarkMode: $surfaceDarkMode;
$headerContainer: true;
$headerHeight: 72px;
$footer: transparent;
//
// --- State palette ---
//
$info: #4499ff;
$onInfo: darken($info, 50%);
$infoOnBackground: darken($info, 20%);
$infoOnSurface: darken($info, 20%);
$infoDarkMode: darken($info, 40%);
$onInfoDarkMode: lighten($info, 20%);
$infoOnBackgroundDarkMode: $info;
$infoOnSurfaceDarkMode: $info;
$success: #55ff55;
$onSuccess: darken($success, 45%);
$successOnBackground: darken($success, 45%);
$successOnSurface: darken($success, 45%);
$successDarkMode: darken($success, 45%);
$onSuccessDarkMode: lighten($success, 20%);
$successOnBackgroundDarkMode: $success;
$successOnSurfaceDarkMode: $success;
$warning: #ffcc00;
$onWarning: darken($warning, 30%);
$warningOnBackground: darken($warning, 25%);
$warningOnSurface: darken($warning, 25%);
$warningDarkMode: darken($warning, 30%);
$onWarningDarkMode: lighten($warning, 20%);
$warningOnBackgroundDarkMode: $warning;
$warningOnSurfaceDarkMode: $warning;
$error: #ff0000;
$onError: darken($error, 40%);
$errorOnBackground: darken($error, 10%);
$errorOnSurface: darken($error, 10%);
$errorDarkMode: darken($error, 30%);
$onErrorDarkMode: lighten($error, 20%);
$errorOnBackgroundDarkMode: lighten($error, 15%);
$errorOnSurfaceDarkMode: lighten($error, 3%);
//
// --- Responsivity ---
//
$mobileThreshold: 850px;
$desktopThreshold: 940px;

View File

@ -0,0 +1,6 @@
{
"extends": "./tsconfig.json",
"include": [
"./**/*"
]
}

View File

@ -0,0 +1,27 @@
{
"extends": "../../../tsconfig.json",
"compilerOptions": {
"target": "ESNext",
"module": "CommonJS",
"baseUrl": "../../../intermediates/assets",
"rootDir": "../../../intermediates/assets/ts-source",
"sourceRoot": "../../../intermediates/assets/ts-source",
"outDir": "../../../intermediates/assets/ts",
"declaration": false,
"typeRoots": [],
"resolveJsonModule": false,
"lib": [
"es2020",
"DOM"
]
},
"include": [
"../../../intermediates/assets/ts-source/**/*"
],
"references": [
{
"path": "../../common"
}
]
}

View File

@ -0,0 +1,25 @@
<script>
import BaseTemplate from "./templates/BaseTemplate.svelte";
import {locals} from "../ts/stores";
import Icon from "./utils/Icon.svelte";
</script>
<BaseTemplate title="{$locals.app.name} - About us"
description="Simple, self-hosted file hosting and link shrinking solution. Power lies in simplicity."
noH1>
<h1>Self-hosting files</h1>
<div class="container">
<section class="panel">
<h2>What is ily.li?</h2>
<p>ily.li is a simple, self-hosted file sharing/hosting and link shrinking platform. It is based on <a href="https://eternae.ink/ashpie/swaf" target="_blank">swaf</a>.</p>
<nav>
<ul>
<li>
<a href="https://eternae.ink/ashpie/ily.li" target="_blank"><Icon name="code"/> Repository</a>
</li>
</ul>
</nav>
</section>
</div>
</BaseTemplate>

View File

@ -1,22 +1,31 @@
{% extends 'layouts/base.njk' %} <script lang="ts">
import {locals} from "../ts/stores.js";
import {route} from "../../common/Routing.js";
import {Time} from "../../common/Time.js";
import BaseTemplate from "./templates/BaseTemplate.svelte";
import Form from "./utils/Form.svelte";
import Icon from "./utils/Icon.svelte";
import CopyableText from "./components/CopyableText.svelte";
import Pagination from "./components/Pagination.svelte";
</script>
{% set title = app.name + ' - Auth tokens' %} <BaseTemplate title="{$locals.app.name} - Auth tokens" description="Upload files directly from your desktop." noH1>
<h1>Auth tokens</h1>
{% block body %}
<div class="container">
<section class="panel"> <section class="panel">
<h2><i data-feather="key"></i> Auth tokens</h2> <h2>
<form action="{{ route('generate-token') }}" method="POST"> <Icon name="key"/>
{{ macros.csrf(getCsrfToken) }} Auth tokens
</h2>
<Form action="{route('generate-token')}" submitText="Generate a new token" submitIcon="file-plus"/>
<button type="submit"><i data-feather="plus"></i> Generate a new token</button> <Pagination pagination={$locals.pagination} routeName="auth-tokens" contextSize={3}/>
</form>
<table class="data-table"> <table class="data-table">
<thead> <thead>
<tr> <tr>
<th>#</th> <th>#</th>
<th class="table-col-grow">Secret</th> <th class="col-grow">Secret</th>
<th>Created at</th> <th>Created at</th>
<th>Last used at</th> <th>Last used at</th>
<th>Actions</th> <th>Actions</th>
@ -24,40 +33,52 @@
</thead> </thead>
<tbody> <tbody>
{% for token in auth_tokens %} {#each $locals.auth_tokens as token}
<tr> <tr>
<td>{{ token.id }}</td> <td>{token.id}</td>
<td> <td>
<div class="copyable-text"> <CopyableText content="{token.secret}"/>
<div class="content">{{ token.secret }}</div> </td>
<button class="copy-button"><i data-feather="copy"></i></button> <td>
</div> <time datetime="{token.created_at}" title="{token.created_at}">
{Time.humanizeTimeSince(new Date(token.created_at), true)} ago
</time>
</td>
<td>
{#if token.used_at}
<time datetime="{token.used_at}" title="{token.used_at}">
{Time.humanizeTimeSince(new Date(token.used_at), true)} ago
</time>
{:else}
Never
{/if}
</td> </td>
<td>{{ token.created_at.toISOString() }}</td>
<td>{{ token.used_at.toISOString() }}</td>
<td class="actions"> <td class="actions">
<form action="{{ route('revoke-token', token.id) }}" method="POST"> <Form action="{route('revoke-token', token.id)}" submitText="Revoke" submitIcon="trash"
<button class="button danger"><i data-feather="trash"></i> <span class="tip">Revoke</span></button> submitClass="danger" button/>
{{ macros.csrf(getCsrfToken) }}
</form>
</td> </td>
</tr> </tr>
{% endfor %} {/each}
</tbody> </tbody>
</table> </table>
<Pagination pagination={$locals.pagination} routeName="auth-tokens" contextSize={3}/>
</section> </section>
<section class="panel"> <section class="panel">
<h2><i data-feather="tool"></i> Setup a desktop utility</h2> <h2>
<Icon name="wrench"/>
Setup a desktop utility
</h2>
<p>There may be a desktop client at some point. For now, if you're an advanced user, you can setup <p>There may be a desktop client at some point. For now, if you're an advanced user, you can setup
scripts/macros.</p> scripts/macros.</p>
<hr> <hr>
<section> <section>
<h3>First alternative: sh script (native on linux)</h3> <h3>First alternative: sh script (native on linux)</h3>
<p>If you have the sh shell on your machine (i.e. you are on linux, git bash on windows...) and curl, you can <p>If you have the sh shell on your machine (i.e. you are on linux, git bash on windows...) and curl, you
download and use these scripts:</p> can download and use these scripts:</p>
<table class="data-table"> <table class="data-table">
<thead> <thead>
<tr> <tr>
@ -68,11 +89,11 @@
<tbody> <tbody>
<tr> <tr>
<td>upload_file.sh</td> <td>upload_file.sh</td>
<td><a href="{{ route('file-linux-script') }}">Download</a></td> <td><a href="{route('file-linux-script')}">Download</a></td>
</tr> </tr>
<tr> <tr>
<td>shrink_url.sh</td> <td>shrink_url.sh</td>
<td><a href="{{ route('url-linux-script') }}">Download</a></td> <td><a href="{route('url-linux-script')}">Download</a></td>
</tr> </tr>
</tbody> </tbody>
</table> </table>
@ -134,7 +155,7 @@
<td>url_domain</td> <td>url_domain</td>
<td>Choose domain name</td> <td>Choose domain name</td>
<td>No</td> <td>No</td>
<td>{{ allowed_domains.join('|') }}</td> <td>{$locals.allowed_domains.join('|')}</td>
</tr> </tr>
<tr> <tr>
@ -156,12 +177,11 @@
<td>url_domain</td> <td>url_domain</td>
<td>Choose domain name</td> <td>Choose domain name</td>
<td>No</td> <td>No</td>
<td>{{ allowed_domains.join('|') }}</td> <td>{$locals.allowed_domains.join('|')}</td>
</tr> </tr>
</tbody> </tbody>
</table> </table>
<p>For examples with curl, please download and review the scripts above.</p> <p>For examples with curl, please download and review the scripts above.</p>
</section> </section>
</section> </section>
</div> </BaseTemplate>
{% endblock %}

View File

@ -0,0 +1,223 @@
<script lang="ts">
import {onMount} from "svelte";
import Icon from "../utils/Icon.svelte"
export let file: File;
export let form: HTMLFormElement;
export let fileFieldName: string = 'file';
export let autostart: boolean = false;
export let inProgress: boolean = false;
let xhr: XMLHttpRequest | undefined;
let xferSpeed: number[] = [];
let lastTransferTime: number | null = null;
let lastLoaded: number = 0;
let speed: string | undefined;
export let progress: string = '';
export let error: string | undefined = undefined;
export let finalUrl: string | undefined = undefined;
$: file && autoStart();
const units = ['K', 'M', 'G', 'T'];
export async function run(): Promise<void> {
inProgress = true;
try {
await new Promise<void>((resolve, reject) => {
reset();
prepareXhrRequest(resolve, reject);
if (!xhr) throw new Error('Failed to initialize xhr');
sendXhrRequest(xhr);
});
} catch (e) {
error = e;
return onError(e);
} finally {
inProgress = false;
}
onEnd(file.name, finalUrl);
}
function retry() {
run().catch(onError);
}
function cancel() {
onEnd(file.name, null);
}
function reset() {
resetResult();
initSpeedTracker();
initProgressTracker();
initErrorTracker();
}
function resetResult() {
finalUrl = undefined;
}
function initSpeedTracker() {
xferSpeed = [];
lastTransferTime = null;
lastLoaded = 0;
speed = '--';
}
function initProgressTracker() {
progress = '';
}
function initErrorTracker() {
error = undefined;
}
function prepareXhrRequest(
resolve: (value?: PromiseLike<void>) => void,
reject: (err: string | ProgressEvent<XMLHttpRequestEventTarget> | undefined) => void,
) {
xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.upload.addEventListener('progress', e => {
if (e.lengthComputable) {
progress = (e.loaded / e.total * 100).toFixed(2) + '%';
updateSpeed(e.loaded);
} else {
progress = '';
}
});
xhr.addEventListener('load', () => {
const response = xhr.response;
if (response) {
console.log('done', response);
if (response.status === 'error') {
if (response.messages) {
// TODO: display errors // applyFormMessages(this.form, response.messages);
const messages = response.messages;
const formattedError = Object.keys(messages).map(field => `${field}: ${messages[field].name}, ${messages[field].message}`).join(';');
return reject(formattedError);
}
} else if (response.url) {
finalUrl = response.url;
return resolve();
}
reject('Malformed response from server.');
}
});
xhr.addEventListener('error', (e) => {
reject(e);
});
}
function sendXhrRequest(xhr: XMLHttpRequest) {
const formData = new FormData(form);
formData.set(fileFieldName, file);
xhr.open('POST', form.action);
xhr.send(formData);
}
function updateSpeed(loaded: number): void {
const time = new Date().getTime();
if (lastTransferTime) {
xferSpeed.push((loaded - lastLoaded) / (time - lastTransferTime));
if (xferSpeed.length > 100) xferSpeed = xferSpeed.slice(1);
let rawSpeed = xferSpeed.reduce((v, c) => v + c) / xferSpeed.length;
let unit = 0;
while (rawSpeed >= 1000 && unit < units.length - 1) {
rawSpeed /= 1000;
unit++;
}
speed = rawSpeed.toFixed(2) + units[unit] + 'Bps';
}
lastTransferTime = time;
lastLoaded = loaded;
}
onMount(() => {
autoStart();
});
function autoStart() {
if (autostart && !inProgress) {
run().catch(onError);
}
}
export let onEnd = function (name: string, finalUrl: string) {
}
export let onError = function (err) {
}
</script>
<style lang="scss">
@import "../../scss/vars";
.file-upload {
padding: 8px;
color: var(--on-subsurface);
background: var(--subsurface);
border-radius: 5px;
.name, .status {
text-align: center;
}
&.error {
color: var(--on-error);
background-color: var(--error);
}
}
.progress-bar {
position: relative;
display: block;
margin: 8px;
padding: 4px;
background: #fff1;
border-radius: 5px;
overflow: hidden;
text-align: center;
.content {
position: relative;
}
&::before {
content: "";
display: block;
position: absolute;
left: 0;
top: 0;
width: var(--progress);
height: 100%;
transition: width ease-out 150ms;
background: var(--primary);
}
}
</style>
<div class="file-upload" class:error={!!error}>
<div class="name">{file?.name}</div>
<div class="progress-bar" style="--progress: {progress};"><span class="content">{progress}</span></div>
<div class="status">
{#if error}
Error: {error}
<button on:click={retry}><Icon name="repeat"/> Retry</button>
<button on:click={cancel}><Icon name="slash"/> Cancel</button>
{:else}
Uploading @ {speed}
{/if}
</div>
</div>

View File

@ -0,0 +1,217 @@
<script lang="ts">
import {locals} from "../ts/stores.js";
import {route} from "../../common/Routing";
import BaseTemplate from "./templates/BaseTemplate.svelte";
import Form from "./utils/Form.svelte";
import Field from "./utils/Field.svelte";
import CopyableText from "./components/CopyableText.svelte";
import Pagination from "./components/Pagination.svelte";
import Message from "./components/Message.svelte";
import Icon from "./utils/Icon.svelte"
import FileUpload from "./components/FileUpload.svelte";
import {Time} from "../../common/Time.js";
let neverExpire: string;
let autogenUrl: string;
let uploadForm: HTMLFormElement;
let selectedFiles: FileList | undefined;
let nextFileIndex = 0;
let uploading: boolean = false;
let currentFile: File | undefined;
let finishedFileUploads: { name: string, finalUrl: string }[] = [];
function uploadFiles(e) {
e.preventDefault();
uploadForm = this;
if (selectedFiles && !uploading) {
processNextUpload();
}
}
async function processNextUpload() {
if (nextFileIndex > selectedFiles.length - 1) {
nextFileIndex = 0;
selectedFiles = undefined;
uploading = false;
return;
}
uploading = true;
currentFile = selectedFiles[nextFileIndex++];
}
function onUploadEnd(fileName, finalUrl) {
if (finalUrl) {
finishedFileUploads = [...finishedFileUploads, {name: fileName, finalUrl: finalUrl}];
}
processNextUpload();
}
</script>
<style lang="scss">
.file-upload-table {
@media (max-width: 550px) {
> thead > tr > th:nth-child(3),
> tbody > tr > td:nth-child(3) {
display: none;
}
}
@media (max-width: 785px) {
> thead > tr > th:nth-child(4),
> tbody > tr > td:nth-child(4) {
display: none;
}
}
td, th {
padding: 4px;
}
}
.new-files {
h3 {
text-align: center;
:global(.icon) {
color: var(--success);
}
}
hr {
margin: 24px;
border: 0;
border-top: 1px solid var(--on-subsurface);
opacity: 0.25;
}
}
</style>
<BaseTemplate title="{$locals.app.name} - Upload file" description="File upload web interface." noH1>
<h1>Upload files</h1>
<section class="panel">
<h2>
<Icon name="upload"/>
Upload files
</h2>
<p>You are responsible for the files that you upload.</p>
<Form action={route('post-file-frontend')} withFiles
submitText="Upload" submitIcon="upload" submitDisabled={uploading}
onSubmit={uploadFiles}>
<Field type="file" name="upload" placeholder="Choose wisely" icon="file"
hint="The maximum upload size is {$locals.max_upload_size} MiB"
multiple required
bind:fileList={selectedFiles}/>
<Field type="checkbox" name="never_expire" placeholder="Never delete this file"
icon="infinity"
bind:value={neverExpire}/>
{#if !neverExpire}
<Field type="number" name="expire_after_days" icon="clock"
placeholder="How many days to delete this file after"
initialValue={30} max="1825"/>
{/if}
{#if !selectedFiles || selectedFiles.length <= 1}
<Field type="checkbox" name="autogen_url" placeholder="Generate url automatically"
icon="zap"
bind:value={autogenUrl} initialValue={true}/>
{#if !autogenUrl}
<Field type="text" name="slug" placeholder="Custom url slug" icon="link"
hint="Example: beautiful_image.jpg sets url to https://{$locals.default_domain}/beautiful_image.jpg"/>
{/if}
{:else}
<Message type="info" discreet sticky
content="When upload multiple files, URLs will be generated automatically."/>
{/if}
</Form>
{#if uploading}
<FileUpload file={currentFile} form={uploadForm} fileFieldName="upload"
onEnd={onUploadEnd} autostart/>
{/if}
{#if finishedFileUploads.length > 0}
<section class="sub-panel new-files">
<hr>
<h3>
<Icon name="file-check"/>
Newly uploaded files
</h3>
{#each finishedFileUploads as fileUpload}
<CopyableText title="{fileUpload.name}" content="{fileUpload.finalUrl}"/>
{/each}
</section>
{/if}
{#if $locals.flash.url}
<CopyableText title="URL" content={$locals.flash.url}/>
{/if}
</section>
<section class="panel">
<h2>
<Icon name="folder"/>
File list
</h2>
<Pagination pagination={$locals.pagination} routeName="file-uploader" contextSize={3}/>
<table class="data-table file-upload-table">
<thead>
<tr>
<th>#</th>
<th class="col-grow">Name</th>
<th>Size</th>
<th>Expires in</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{#each $locals.files as file}
<tr>
<td>{file.id}</td>
<td class="col-grow-cell"><a href="{file.url}">
<pre>{file.real_name}</pre>
</a></td>
<td>{(file.size / (1024 * 1024)).toFixed(2)}MB</td>
<td>
{#if file.expires_at}
<time datetime="{file.expires_at}" title="{file.expires_at}">
{Time.humanizeTimeTo(new Date(file.expires_at))}
</time>
{:else}
Never
{/if}
</td>
<td class="actions">
{#if file.shouldBeDeleted}
Pending deletion
{:else}
<CopyableText content="{file.url}" buttonMode/>
<Form action={route('delete-file-frontend', file.slug)} button
submitIcon="trash" submitText="delete" submitClass="danger" submitDisabled={uploading}
confirm="Are you sure you want to delete file {file.real_name}?"/>
{/if}
</td>
</tr>
{:else}
<tr>
<td colspan="5" class="center">You haven't uploaded any file yet.</td>
</tr>
{/each}
</tbody>
</table>
<Pagination pagination={$locals.pagination} routeName="file-uploader" contextSize={3}/>
</section>
</BaseTemplate>

View File

@ -0,0 +1,7 @@
<script>
import NavMenuItem from "../../components/NavMenuItem.svelte";
import {route} from "../../../../common/Routing.js";
</script>
<NavMenuItem href={route('auth-tokens')} icon="key" text="Auth tokens" />
<hr>

View File

@ -0,0 +1,10 @@
<script>
import {locals} from "../../../ts/stores.js";
import NavMenuItem from "../../components/NavMenuItem.svelte";
import {route} from "../../../../common/Routing";
</script>
{#if $locals.user}
<NavMenuItem href={route('file-uploader')} icon="upload" text="Upload" />
<NavMenuItem href={route('url-shrinker')} icon="shrink" text="Shrink URL" />
{/if}

View File

@ -0,0 +1,15 @@
{
"extends": "@tsconfig/svelte/tsconfig.json",
"compilerOptions": {
"outDir": "public/js",
"rootDir": "../../../intermediates/assets",
},
"include": [
"src/assets/ts/**/*"
],
"references": [
{
"path": "../../common"
}
]
}

View File

@ -0,0 +1,83 @@
<script lang="ts">
import {locals} from "../ts/stores.js";
import {route} from "../../common/Routing";
import BaseTemplate from "./templates/BaseTemplate.svelte";
import Icon from "./utils/Icon.svelte"
import Form from "./utils/Form.svelte";
import Field from "./utils/Field.svelte";
import CopyableText from "./components/CopyableText.svelte";
import Pagination from "./components/Pagination.svelte";
let autogenUrl;
</script>
<BaseTemplate title="{$locals.app.name} - Shrink URL" description="Make your URLs shorter." noH1>
<h1>Shrink URLs</h1>
<section class="panel">
<h2>
<Icon name="shrink"/>
Shrink a URL
</h2>
<p>For security reasons, shrinked URLs cannot be deleted.</p>
<Form action="{route('shrink-url')}" submitText="Shrink URL" submitIcon="shrink">
<Field type="text" name="target_url" placeholder="Target URL" icon="link"
hint="Only valid URLs starting with http:// or https://" required/>
<Field type="checkbox" name="autogen_url" placeholder="Generate url automatically"
icon="zap"
bind:value={autogenUrl} initialValue={true}/>
{#if !autogenUrl}
<Field type="text" name="slug" placeholder="Custom url slug" icon="link"
hint="Example: beautiful_image.jpg sets url to https://{$locals.default_domain}/beautiful_image.jpg"/>
{/if}
</Form>
{#if $locals.flash.url}
<CopyableText title="URL" content={$locals.flash.url}/>
{/if}
</section>
<section class="panel">
<h2>
<Icon name="link"/>
URL list
</h2>
<Pagination pagination={$locals.pagination} routeName="url-shrinker" contextSize={3}/>
<table class="data-table">
<thead>
<tr>
<th>#</th>
<th class="col-grow">Target</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{#each $locals.urls as url}
<tr>
<td>{url.id}</td>
<td class="col-grow-cell">
<a href="{url.url}">
<pre>{url.target_url}</pre>
</a>
</td>
<td class="actions">
<CopyableText content="{url.url}" buttonMode/>
</td>
</tr>
{:else}
<tr>
<td colspan="3" class="center">You haven't shrunk any url yet.</td>
</tr>
{/each}
</tbody>
</table>
<Pagination pagination={$locals.pagination} routeName="url-shrinker" contextSize={3}/>
</section>
</BaseTemplate>

1
src/common/dummy.ts Normal file
View File

@ -0,0 +1 @@
console.log('common code between back and front');

3
src/common/package.json Normal file
View File

@ -0,0 +1,3 @@
{
"type": "commonjs"
}

20
src/common/tsconfig.json Normal file
View File

@ -0,0 +1,20 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"composite": true,
"module": "CommonJS",
"baseUrl": "../../dist/common-local",
"rootDir": "./",
"sourceRoot": "./",
"outDir": "../../dist/common-local",
"typeRoots": [
"src/types"
],
},
"include": [
"./**/*"
]
}

View File

@ -1,5 +1,5 @@
import Controller from "swaf/Controller";
import {Request, Response} from "express"; import {Request, Response} from "express";
import Controller from "swaf/Controller";
export default class AboutController extends Controller { export default class AboutController extends Controller {
public routes(): void { public routes(): void {

View File

@ -1,13 +1,15 @@
import Controller from "swaf/Controller";
import {RequireAuthMiddleware} from "swaf/auth/AuthComponent";
import {Request, Response} from "express";
import AuthToken from "../models/AuthToken";
import {BadRequestError, ForbiddenHttpError, NotFoundHttpError} from "swaf/HttpError";
import config from "config"; import config from "config";
import {Request, Response} from "express";
import {RequireAuthMiddleware} from "swaf/auth/AuthComponent";
import {route} from "swaf/common/Routing";
import Controller from "swaf/Controller";
import {BadRequestError, ForbiddenHttpError, NotFoundHttpError} from "swaf/HttpError";
import AuthToken from "../models/AuthToken.js";
export default class AuthTokenController extends Controller { export default class AuthTokenController extends Controller {
public routes(): void { public routes(): void {
this.get('/auth-tokens', this.getAuthTokens, 'auth-tokens', RequireAuthMiddleware); this.get('/auth-tokens/:page?', this.getAuthTokens, 'auth-tokens', RequireAuthMiddleware);
this.post('/gen-auth-token', this.postGenAuthToken, 'generate-token', RequireAuthMiddleware); this.post('/gen-auth-token', this.postGenAuthToken, 'generate-token', RequireAuthMiddleware);
this.post('/revoke-auth-token/:id', this.postRevokeAuthToken, 'revoke-token', RequireAuthMiddleware); this.post('/revoke-auth-token/:id', this.postRevokeAuthToken, 'revoke-token', RequireAuthMiddleware);
} }
@ -15,10 +17,16 @@ export default class AuthTokenController extends Controller {
public async getAuthTokens(req: Request, res: Response): Promise<void> { public async getAuthTokens(req: Request, res: Response): Promise<void> {
const allowedDomains = config.get<string[]>('allowed_url_domains'); const allowedDomains = config.get<string[]>('allowed_url_domains');
const user = req.as(RequireAuthMiddleware).getUser(); const user = req.as(RequireAuthMiddleware).getUser();
const authTokens = await AuthToken.paginateForUser(req, 25, user.getOrFail('id'));
res.render('auth-tokens', { res.render('auth-tokens', {
allowed_domains: allowedDomains, allowed_domains: allowedDomains,
default_domain: allowedDomains[config.get<number>('default_url_domain_for_files')], default_domain: allowedDomains[config.get<number>('default_url_domain_for_files')],
auth_tokens: await AuthToken.select().where('user_id', user.id).get(), auth_tokens: authTokens.map(token => ({
...token,
created_at: token.created_at?.toISOString(),
used_at: token.used_at?.toISOString(),
})),
pagination: authTokens.pagination?.serialize(),
}); });
} }
@ -30,7 +38,7 @@ export default class AuthTokenController extends Controller {
}); });
await authToken.save(); await authToken.save();
req.flash('success', 'Successfully created auth token.'); req.flash('success', 'Successfully created auth token.');
res.redirect(req.getPreviousUrl() || Controller.route('file-uploader')); res.redirect(req.getPreviousUrl() || route('file-uploader'));
} }
protected async postRevokeAuthToken(req: Request, res: Response): Promise<void> { protected async postRevokeAuthToken(req: Request, res: Response): Promise<void> {
@ -46,6 +54,6 @@ export default class AuthTokenController extends Controller {
await authToken.delete(); await authToken.delete();
req.flash('success', 'Successfully deleted auth token.'); req.flash('success', 'Successfully deleted auth token.');
res.redirect(req.getPreviousUrl() || Controller.route('file-uploader')); res.redirect(req.getPreviousUrl() || route('file-uploader'));
} }
} }

View File

@ -1,37 +1,50 @@
import Controller from "swaf/Controller";
import {RequireAuthMiddleware, RequireRequestAuthMiddleware} from "swaf/auth/AuthComponent";
import {NextFunction, Request, Response} from "express";
import {BadRequestError, ForbiddenHttpError, ServerError} from "swaf/HttpError";
import FileModel from "../models/FileModel";
import config from "config"; import config from "config";
import {NextFunction, Request, Response} from "express";
import formidable from "formidable";
import * as fs from "fs"; import * as fs from "fs";
import Formidable from "formidable"; import path from "path";
import generateSlug from "../SlugGenerator"; import {RequireAuthMiddleware, RequireRequestAuthMiddleware} from "swaf/auth/AuthComponent";
import {logger} from "swaf/Logger"; import {route} from "swaf/common/Routing";
import Controller from "swaf/Controller";
import FileUploadMiddleware from "swaf/FileUploadMiddleware"; import FileUploadMiddleware from "swaf/FileUploadMiddleware";
import {BadRequestError, ForbiddenHttpError, ServerError} from "swaf/HttpError";
import {logger} from "swaf/Logger";
import FileModel from "../models/FileModel.js";
import generateSlug from "../SlugGenerator.js";
export default class FileController extends Controller { export default class FileController extends Controller {
public routes(): void { public routes(): void {
this.get('/files/:page([0-9]+)?', this.getFileUploader, 'file-uploader', RequireAuthMiddleware); this.get('/files/:page([0-9]+)?', this.getFileUploader, 'file-uploader',
RequireAuthMiddleware);
this.get('/files/upload-script', this.downloadLinuxScript, 'file-linux-script'); this.get('/files/upload-script', this.downloadLinuxScript, 'file-linux-script');
this.post('/files/upload', this.postFileFrontend, 'post-file-frontend', RequireAuthMiddleware, FileUploadFormMiddleware); this.post('/files/upload', this.postFileFrontend, 'post-file-frontend',
this.post('/files/delete/:slug', FileController.deleteFileRoute, 'delete-file-frontend', RequireAuthMiddleware); RequireAuthMiddleware, FileUploadFormMiddleware);
this.post('/files/delete/:slug', FileController.deleteFileRoute, 'delete-file-frontend',
RequireAuthMiddleware);
} }
protected async getFileUploader(req: Request, res: Response): Promise<void> { protected async getFileUploader(req: Request, res: Response): Promise<void> {
const allowedDomains = config.get<string[]>('allowed_url_domains'); const allowedDomains = config.get<string[]>('allowed_url_domains');
const user = req.as(RequireAuthMiddleware).getUser(); const user = req.as(RequireAuthMiddleware).getUser();
const files = await FileModel.paginateForUser(req, 25, user.getOrFail('id'));
res.render('file-uploader', { res.render('file-uploader', {
max_upload_size: config.get<string>('max_upload_size'), max_upload_size: config.get<string>('max_upload_size'),
allowed_domains: allowedDomains, allowed_domains: allowedDomains,
default_domain: allowedDomains[config.get<number>('default_url_domain_for_files')], default_domain: allowedDomains[config.get<number>('default_url_domain_for_files')],
files: await FileModel.paginateForUser(req, 25, user.getOrFail('id')), files: files.map(file => ({
...file,
shouldBeDeleted: file.shouldBeDeleted(),
url: file.getURL(),
expires_at: file.expires_at?.toISOString(),
})),
pagination: files.pagination?.serialize(),
}); });
} }
protected async downloadLinuxScript(req: Request, res: Response): Promise<void> { protected async downloadLinuxScript(req: Request, res: Response): Promise<void> {
res.download('assets/files/upload_file.sh', 'upload_file.sh'); res.download(path.resolve(__dirname, '..', 'assets/files/upload_file.sh'), 'upload_file.sh');
} }
protected async postFileFrontend(req: Request, res: Response): Promise<void> { protected async postFileFrontend(req: Request, res: Response): Promise<void> {
@ -58,7 +71,11 @@ export default class FileController extends Controller {
const upload = req.files['upload']; const upload = req.files['upload'];
if (Array.isArray(upload)) { if (Array.isArray(upload)) {
throw new BadRequestError('Uploading multiple files at once is unsupported.', 'Please only upload one file at a time.', req.url); throw new BadRequestError(
'Uploading multiple files at once is unsupported.',
'Please only upload one file at a time.',
req.url,
);
} }
// TTL // TTL
@ -72,7 +89,7 @@ export default class FileController extends Controller {
const file = FileModel.create({ const file = FileModel.create({
user_id: user.id, user_id: user.id,
slug: slug, slug: slug,
real_name: upload.name, real_name: upload.originalFilename,
storage_type: 'local', storage_type: 'local',
storage_path: 'storage/uploads/' + slug, storage_path: 'storage/uploads/' + slug,
size: upload.size, size: upload.size,
@ -80,9 +97,10 @@ export default class FileController extends Controller {
}); });
await file.save(); await file.save();
fs.renameSync(upload.path, file.getOrFail('storage_path')); fs.renameSync(upload.filepath, file.getOrFail('storage_path'));
const domain = req.body.url_domain || config.get<string[]>('allowed_url_domains')[config.get<number>('default_url_domain_for_files')]; const domain = req.body.url_domain ||
config.get<string[]>('allowed_url_domains')[config.get<number>('default_url_domain_for_files')];
res.format({ res.format({
json: () => res.json({ json: () => res.json({
url: file.getURL(domain), url: file.getURL(domain),
@ -91,7 +109,7 @@ export default class FileController extends Controller {
html: () => { html: () => {
req.flash('success', 'Upload success!'); req.flash('success', 'Upload success!');
req.flash('url', file.getURL(domain)); req.flash('url', file.getURL(domain));
res.redirect(Controller.route('file-uploader')); res.redirect(route('file-uploader'));
}, },
}); });
} }
@ -126,7 +144,7 @@ export default class FileController extends Controller {
text: () => res.send('success'), text: () => res.send('success'),
html: () => { html: () => {
req.flash('success', 'Successfully deleted file.'); req.flash('success', 'Successfully deleted file.');
res.redirect(Controller.route('file-uploader')); res.redirect(route('file-uploader'));
}, },
}); });
} }
@ -143,11 +161,11 @@ export class FileUploadFormMiddleware extends FileUploadMiddleware {
return 'upload'; return 'upload';
} }
protected makeForm(): Formidable { protected getFormidableOptions(): formidable.Options {
return new Formidable({ return {
uploadDir: 'storage/tmp', uploadDir: 'storage/tmp',
maxFileSize: config.get<number>('max_upload_size') * 1024 * 1024, maxFileSize: config.get<number>('max_upload_size') * 1024 * 1024,
}); };
} }
} }

View File

@ -1,5 +1,6 @@
import Controller from "swaf/Controller";
import {Request, Response} from "express"; import {Request, Response} from "express";
import {route} from "swaf/common/Routing";
import Controller from "swaf/Controller";
export default class HomeController extends Controller { export default class HomeController extends Controller {
public routes(): void { public routes(): void {
@ -20,6 +21,6 @@ export default class HomeController extends Controller {
* This is to test and assert that swaf extended types are available * This is to test and assert that swaf extended types are available
*/ */
protected async goBack(req: Request, res: Response): Promise<void> { protected async goBack(req: Request, res: Response): Promise<void> {
res.redirect(req.getPreviousUrl() || Controller.route('home')); res.redirect(req.getPreviousUrl() || route('home'));
} }
} }

View File

@ -1,17 +1,18 @@
import Controller from "swaf/Controller";
import {NextFunction, Request, Response} from "express";
import {BadRequestError, NotFoundHttpError, ServerError} from "swaf/HttpError";
import config from "config"; import config from "config";
import {RequireRequestAuthMiddleware} from "swaf/auth/AuthComponent"; import {NextFunction, Request, Response} from "express";
import URLRedirect from "../models/URLRedirect";
import URLRedirectController from "./URLRedirectController";
import FileModel from "../models/FileModel";
import generateSlug from "../SlugGenerator";
import FileController, {FileUploadFormMiddleware} from "./FileController";
import * as fs from "fs"; import * as fs from "fs";
import {encodeRFC5987ValueChars} from "../Utils"; import {RequireRequestAuthMiddleware} from "swaf/auth/AuthComponent";
import {promisify} from "util"; import Controller from "swaf/Controller";
import {BadRequestError, NotFoundHttpError, ServerError} from "swaf/HttpError";
import {logger} from "swaf/Logger"; import {logger} from "swaf/Logger";
import {promisify} from "util";
import FileModel from "../models/FileModel.js";
import URLRedirect from "../models/URLRedirect.js";
import generateSlug from "../SlugGenerator.js";
import {encodeRFC5987ValueChars} from "../Utils.js";
import FileController, {FileUploadFormMiddleware} from "./FileController.js";
import URLRedirectController from "./URLRedirectController.js";
export default class LinkController extends Controller { export default class LinkController extends Controller {
public routes(): void { public routes(): void {
@ -75,7 +76,13 @@ export default class LinkController extends Controller {
protected async putFile(req: Request, res: Response, next: NextFunction): Promise<void> { protected async putFile(req: Request, res: Response, next: NextFunction): Promise<void> {
if (req.body.type !== 'file') return next(); if (req.body.type !== 'file') return next();
const slug = req.params.slug; const slug = req.params.slug;
if (!slug) throw new BadRequestError('Cannot put without a slug.', 'Either provide a slug or use POST method instead.', req.url); if (!slug) {
throw new BadRequestError(
'Cannot put without a slug.',
'Either provide a slug or use POST method instead.',
req.url,
);
}
await FileController.handleFileUpload(slug, req, res, true); await FileController.handleFileUpload(slug, req, res, true);
} }

View File

@ -1,9 +1,12 @@
import Controller from "swaf/Controller";
import {NextFunction, Request, Response} from "express";
import URLRedirect from "../models/URLRedirect";
import {RequireAuthMiddleware, RequireRequestAuthMiddleware} from "swaf/auth/AuthComponent";
import generateSlug from "../SlugGenerator";
import config from "config"; import config from "config";
import {NextFunction, Request, Response} from "express";
import path from "path";
import {RequireAuthMiddleware, RequireRequestAuthMiddleware} from "swaf/auth/AuthComponent";
import {route} from "swaf/common/Routing";
import Controller from "swaf/Controller";
import URLRedirect from "../models/URLRedirect.js";
import generateSlug from "../SlugGenerator.js";
export default class URLRedirectController extends Controller { export default class URLRedirectController extends Controller {
public routes(): void { public routes(): void {
@ -15,15 +18,20 @@ export default class URLRedirectController extends Controller {
protected async getUrlShrinker(req: Request, res: Response): Promise<void> { protected async getUrlShrinker(req: Request, res: Response): Promise<void> {
const user = req.as(RequireAuthMiddleware).getUser(); const user = req.as(RequireAuthMiddleware).getUser();
const allowedDomains = config.get<string[]>('allowed_url_domains'); const allowedDomains = config.get<string[]>('allowed_url_domains');
const urls = await URLRedirect.paginateForUser(req, 25, user.getOrFail('id'));
res.render('url-shrinker', { res.render('url-shrinker', {
allowed_domains: allowedDomains, allowed_domains: allowedDomains,
default_domain: allowedDomains[config.get<number>('default_url_domain_for_urls')], default_domain: allowedDomains[config.get<number>('default_url_domain_for_urls')],
urls: await URLRedirect.paginateForUser(req, 25, user.getOrFail('id')), urls: urls.map(url => ({
...url,
url: url.getURL(),
})),
pagination: urls.pagination?.serialize(),
}); });
} }
protected async downloadLinuxScript(req: Request, res: Response): Promise<void> { protected async downloadLinuxScript(req: Request, res: Response): Promise<void> {
res.download('assets/files/shrink_url.sh', 'shrink_url.sh'); res.download(path.resolve(__dirname, '..', 'assets/files/shrink_url.sh'), 'shrink_url.sh');
} }
protected async addUrlFrontend(req: Request, res: Response, next: NextFunction): Promise<void> { protected async addUrlFrontend(req: Request, res: Response, next: NextFunction): Promise<void> {
@ -57,7 +65,8 @@ export default class URLRedirectController extends Controller {
await urlRedirect.save(); await urlRedirect.save();
const domain = req.body.url_domain || config.get<string[]>('allowed_url_domains')[config.get<number>('default_url_domain_for_urls')]; const domain = req.body.url_domain ||
config.get<string[]>('allowed_url_domains')[config.get<number>('default_url_domain_for_urls')];
res.format({ res.format({
json: () => res.json({ json: () => res.json({
url: urlRedirect.getURL(domain), url: urlRedirect.getURL(domain),
@ -66,7 +75,7 @@ export default class URLRedirectController extends Controller {
html: () => { html: () => {
req.flash('success', 'URL shrunk successfully!'); req.flash('success', 'URL shrunk successfully!');
req.flash('url', urlRedirect.getURL(domain)); req.flash('url', urlRedirect.getURL(domain));
res.redirect(Controller.route('url-shrinker')); res.redirect(route('url-shrinker'));
}, },
}); });
} }

View File

@ -6,14 +6,22 @@ process.env['NODE_CONFIG_DIR'] =
+ delimiter + delimiter
+ (process.env['NODE_CONFIG_DIR'] || __dirname + '/../config/'); + (process.env['NODE_CONFIG_DIR'] || __dirname + '/../config/');
import {logger} from "swaf/Logger";
import App from "./App";
import config from "config"; import config from "config";
import {promises as fs} from "fs";
import {logger} from "swaf/Logger";
import App from "./App.js";
(async () => { (async () => {
logger.debug('Config path:', process.env['NODE_CONFIG_DIR']); logger.debug('Config path:', process.env['NODE_CONFIG_DIR']);
const app = new App(config.get<string>('listen_addr'), config.get<number>('port')); const packageJson = JSON.parse((await fs.readFile('package.json')).toString());
const app = new App(
packageJson.version,
config.get<string>('app.listen_addr'),
config.get<number>('app.port'),
);
await app.start(); await app.start();
})().catch(err => { })().catch(err => {
logger.error(err); logger.error(err);

View File

@ -1,6 +1,7 @@
import Migration from "swaf/db/Migration"; import Migration from "swaf/db/Migration";
import ModelFactory from "swaf/db/ModelFactory"; import ModelFactory from "swaf/db/ModelFactory";
import AuthToken from "../models/AuthToken";
import AuthToken from "../models/AuthToken.js";
export default class CreateAuthTokensTable extends Migration { export default class CreateAuthTokensTable extends Migration {
public async install(): Promise<void> { public async install(): Promise<void> {

View File

@ -1,6 +1,7 @@
import Migration from "swaf/db/Migration"; import Migration from "swaf/db/Migration";
import ModelFactory from "swaf/db/ModelFactory"; import ModelFactory from "swaf/db/ModelFactory";
import FileModel from "../models/FileModel";
import FileModel from "../models/FileModel.js";
export default class CreateFilesTable extends Migration { export default class CreateFilesTable extends Migration {
public async install(): Promise<void> { public async install(): Promise<void> {

View File

@ -1,6 +1,7 @@
import Migration from "swaf/db/Migration"; import Migration from "swaf/db/Migration";
import ModelFactory from "swaf/db/ModelFactory"; import ModelFactory from "swaf/db/ModelFactory";
import URLRedirect from "../models/URLRedirect";
import URLRedirect from "../models/URLRedirect.js";
export default class CreateUrlRedirectsTable extends Migration { export default class CreateUrlRedirectsTable extends Migration {
public async install(): Promise<void> { public async install(): Promise<void> {

View File

@ -1,5 +1,6 @@
import Migration from "swaf/db/Migration"; import Migration from "swaf/db/Migration";
import FileModel from "../models/FileModel";
import FileModel from "../models/FileModel.js";
export default class ReplaceTtlWithExpiresAtFilesTable extends Migration { export default class ReplaceTtlWithExpiresAtFilesTable extends Migration {
public async install(): Promise<void> { public async install(): Promise<void> {

View File

@ -1,14 +1,26 @@
import Model from "swaf/db/Model"; import {Request} from "express";
import {nanoid} from "nanoid";
import AuthProof from "swaf/auth/AuthProof"; import AuthProof from "swaf/auth/AuthProof";
import User from "swaf/auth/models/User"; import User from "swaf/auth/models/User";
import {nanoid} from "nanoid"; import Model from "swaf/db/Model";
import {ModelQueryResult} from "swaf/db/ModelQuery";
export default class AuthToken extends Model implements AuthProof<User> { export default class AuthToken extends Model implements AuthProof<User> {
public static async paginateForUser(
req: Request,
perPage: number,
user_id: number,
): Promise<ModelQueryResult<AuthToken>> {
req.params.sortBy = 'created_at';
req.params.sortDirection = 'DESC';
return await this.paginate(req, perPage, this.select().where('user_id', user_id));
}
public id?: number = undefined; public id?: number = undefined;
protected readonly user_id?: number = undefined; protected readonly user_id?: number = undefined;
private secret?: string = undefined; private secret?: string = undefined;
protected created_at?: Date = undefined; public created_at?: Date = undefined;
protected used_at?: Date = undefined; public used_at?: Date = undefined;
protected readonly ttl?: number = undefined; protected readonly ttl?: number = undefined;
protected init(): void { protected init(): void {
@ -23,8 +35,9 @@ export default class AuthToken extends Model implements AuthProof<User> {
} }
} }
public use(): void { public async use(): Promise<void> {
this.used_at = new Date(); this.used_at = new Date();
await this.save();
} }
public canDelete(user_id: number): boolean { public canDelete(user_id: number): boolean {

View File

@ -1,9 +1,11 @@
import Model from "swaf/db/Model";
import Controller from "swaf/Controller";
import config from "config"; import config from "config";
import User from "swaf/auth/models/User";
import {Request} from "express"; import {Request} from "express";
import URLRedirect from "./URLRedirect"; import User from "swaf/auth/models/User";
import {route} from "swaf/common/Routing";
import Model from "swaf/db/Model";
import {ModelQueryResult} from "swaf/db/ModelQuery";
import URLRedirect from "./URLRedirect.js";
export default class FileModel extends Model { export default class FileModel extends Model {
public static get table(): string { public static get table(): string {
@ -14,7 +16,7 @@ export default class FileModel extends Model {
return await this.select().where('slug', slug).first(); return await this.select().where('slug', slug).first();
} }
public static async paginateForUser(req: Request, perPage: number, user_id: number): Promise<FileModel[]> { public static async paginateForUser(req: Request, perPage: number, user_id: number): Promise<ModelQueryResult<FileModel>> {
req.params.sortBy = 'created_at'; req.params.sortBy = 'created_at';
req.params.sortDirection = 'DESC'; req.params.sortDirection = 'DESC';
return await this.paginate(req, perPage, this.select().where('user_id', user_id)); return await this.paginate(req, perPage, this.select().where('user_id', user_id));
@ -47,7 +49,7 @@ export default class FileModel extends Model {
} }
public getURL(domain: string = config.get<string>('public_url')): string { public getURL(domain: string = config.get<string>('public_url')): string {
return (/^https?:\/\//.test(domain) ? '' : 'https://') + domain + Controller.route('get-file', { return (/^https?:\/\//.test(domain) ? '' : 'https://') + domain + route('get-file', {
slug: this.getOrFail('slug'), slug: this.getOrFail('slug'),
}); });
} }

View File

@ -1,9 +1,11 @@
import Model from "swaf/db/Model";
import User from "swaf/auth/models/User";
import FileModel from "./FileModel";
import {Request} from "express";
import config from "config"; import config from "config";
import Controller from "swaf/Controller"; import {Request} from "express";
import User from "swaf/auth/models/User";
import {route} from "swaf/common/Routing";
import Model from "swaf/db/Model";
import {ModelQueryResult} from "swaf/db/ModelQuery";
import FileModel from "./FileModel.js";
export default class URLRedirect extends Model { export default class URLRedirect extends Model {
public static get table(): string { public static get table(): string {
@ -14,7 +16,11 @@ export default class URLRedirect extends Model {
return await this.select().where('slug', slug).first(); return await this.select().where('slug', slug).first();
} }
public static async paginateForUser(req: Request, perPage: number, user_id: number): Promise<URLRedirect[]> { public static async paginateForUser(
req: Request,
perPage: number,
user_id: number,
): Promise<ModelQueryResult<URLRedirect>> {
req.params.sortBy = 'created_at'; req.params.sortBy = 'created_at';
req.params.sortDirection = 'DESC'; req.params.sortDirection = 'DESC';
return await this.paginate(req, perPage, this.select().where('user_id', user_id)); return await this.paginate(req, perPage, this.select().where('user_id', user_id));
@ -35,7 +41,7 @@ export default class URLRedirect extends Model {
} }
public getURL(domain: string = config.get<string>('public_url')): string { public getURL(domain: string = config.get<string>('public_url')): string {
return (/^https?:\/\//.test(domain) ? '' : 'https://') + domain + Controller.route('get-url', { return (/^https?:\/\//.test(domain) ? '' : 'https://') + domain + route('get-url', {
slug: this.getOrFail('slug'), slug: this.getOrFail('slug'),
}); });
} }

30
src/tsconfig.json Normal file
View File

@ -0,0 +1,30 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"composite": true,
"module": "CommonJS",
"baseUrl": "../dist",
"rootDir": "./",
"sourceRoot": "./",
"outDir": "../dist",
"typeRoots": [
"src/types"
]
},
"include": [
"./**/*",
"../node_modules/swaf/types"
],
"exclude": [
"./assets/**/*",
"./common/**/*"
],
"references": [
{
"path": "./common"
}
]
}

0
src/types/.gitkeep Normal file
View File

View File

@ -1,19 +0,0 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "public/js",
"rootDir": "./assets",
"target": "ES6",
"strict": true,
"lib": [
"es2020",
"DOM"
],
"typeRoots": [
"./node_modules/@types"
]
},
"include": [
"assets/ts/**/*"
]
}

View File

@ -1,23 +1,43 @@
{ {
"compilerOptions": { "compilerOptions": {
"module": "CommonJS", "target": "ESNext",
"esModuleInterop": true, "module": "ESNext",
"outDir": "dist", "declaration": true,
"rootDir": "./src", "stripInternal": true,
"target": "ES6",
"strict": true, "strict": true,
"allowSyntheticDefaultImports": true,
"strictNullChecks": true,
"moduleResolution": "Node",
"esModuleInterop": true,
"baseUrl": "dist",
"inlineSourceMap": true,
"inlineSources": true,
"outDir": "dist",
"typeRoots": [
"node_modules/@types",
"src/types"
],
"lib": [ "lib": [
"es2020", "es2020",
"DOM" "dom"
],
"typeRoots": [
"./node_modules/@types"
], ],
"resolveJsonModule": true, "resolveJsonModule": true,
"skipLibCheck": true "skipLibCheck": true,
"allowJs": true
}, },
"include": [ "include": [],
"src/**/*", "references": [
"node_modules/swaf/types" {
"path": "src",
},
{
"path": "src/assets/ts",
},
{
"path": "src/assets/views",
}
] ]
} }

View File

@ -11,4 +11,4 @@
"src/types/**/*", "src/types/**/*",
"test/**/*" "test/**/*"
] ]
} }

View File

@ -1,14 +0,0 @@
{% extends 'layouts/base.njk' %}
{% set title = app.name + ' - About us' %}
{% block body %}
<h1>Self-hosting files</h1>
<div class="container">
<section class="panel">
<h2>Details</h2>
<p class="center">Powered by swaf</p>
</section>
</div>
{% endblock %}

View File

@ -1,104 +0,0 @@
{% extends 'layouts/base.njk' %}
{% set title = app.name + ' - Upload file' %}
{% block scripts %}
<script src="/js/fm.js"></script>
{% endblock %}
{% block body %}
<h1>Upload files</h1>
<p>You are responsible for the files that you upload.</p>
<div class="container">
<section class="panel">
<h2><i data-feather="upload"></i> Upload a file</h2>
<form action="{{ route('post-file-frontend') }}" method="POST" enctype="multipart/form-data"
id="upload-form">
{{ macros.field(_locals, 'file', 'upload', '', 'Choose wisely', 'The maximum upload size is ' + max_upload_size + 'MiB', validation_attributes='required') }}
{{ macros.field(_locals, 'checkbox', 'never_expire', '', 'Never delete this file') }}
{{ macros.field(_locals, 'number', 'expire_after_days', '30', 'How many days to delete this file after', null, validation_attributes='max="1825"') }}
{{ macros.field(_locals, 'checkbox', 'autogen_url', '', 'Generate url automatically', null, validation_attributes='checked') }}
{{ macros.field(_locals, 'text', 'slug', '', 'Custom url slug', 'Example: beautiful_image.jpg sets url to https://'+default_domain+'/beautiful_image.jpg', validation_attributes='disabled') }}
{{ macros.csrf(getCsrfToken) }}
<button type="submit"><i data-feather="upload"></i> Upload</button>
</form>
<div id="file-upload" class="hidden">
<div class="name">photo.jpg</div>
<div class="progress-bar" style="--progress: 50%;"><span class="content">50%</span></div>
<div class="status hidden"></div>
</div>
<div id="file-upload-link" class="hidden copyable-text">
<div class="title">URL</div>
<div class="content"></div>
<button class="copy-button"><i data-feather="copy"></i></button>
</div>
{% set url = flash('url') %}
{% if url | length %}
<div class="copyable-text">
<div class="title">URL</div>
<div class="content">{{ url }}</div>
<button class="copy-button"><i data-feather="copy"></i></button>
</div>
{% endif %}
</section>
<section class="panel">
<h2><i data-feather="folder"></i> File list</h2>
{{ macros.paginate(files.pagination, 'file-uploader', 3) }}
<table class="data-table file-upload-table">
<thead>
<tr>
<th>#</th>
<th class="table-col-grow">Name</th>
<th>Size</th>
<th>Expires at</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for file in files %}
<tr>
<td>{{ file.id }}</td>
<td class="table-col-grow-cell"><a href="{{ file.getURL() }}"><pre>{{ file.real_name }}</pre></a></td>
<td>{{ (file.size / (1024 * 1024)).toFixed(2) }}MB</td>
<td>{% if file.expires_at %}{{ file.expires_at.toISOString() }}{% else %}Never{% endif %}</td>
<td class="actions">
<div>
{% if file.shouldBeDeleted() %}
Pending deletion
{% else %}
<button class="copy-button" data-content="{{ file.getURL() }}"><i data-feather="copy"></i> <span class="tip">Copy URL</span></button>
<form action="{{ route('delete-file-frontend', file.slug) }}" method="post">
{{ macros.csrf(getCsrfToken) }}
<button class="button danger" onclick="return confirm('Are you sure you want to delete file {{ file.real_name }}?');"><i data-feather="trash"></i> <span class="tip">Delete</span></button>
</form>
{% endif %}
</div>
</td>
</tr>
{% else %}
<tr>
<td colspan="5" class="center">You haven't uploaded any file yet.</td>
</tr>
{% endfor %}
</tbody>
</table>
{{ macros.paginate(files.pagination, 'file-uploader', 3) }}
</section>
</div>
{% endblock %}

View File

@ -1,63 +0,0 @@
{% extends 'layouts/barebone.njk' %}
{% import 'macros.njk' as macros %}
{% block _stylesheets %}
{{ super() }}
<link rel="stylesheet" href="/css/app.css">
{% block stylesheets %}{% endblock %}
{% endblock %}
{% block _scripts %}
{{ super() }}
{% block scripts %}{% endblock %}
{% endblock %}
{% block header %}
<a href="/" class="logo"><img src="/img/logo.svg" alt="Logo"> {{ app.name }}</a>
<nav>
<button id="menu-button"><i data-feather="menu"></i></button>
<ul id="main-menu">
<li><a href="{{ route('about') }}"><i data-feather="info"></i> <span class="tip">About</span></a></li>
{% if user %}
<li><a href="{{ route('file-uploader') }}"><i data-feather="upload"></i> <span class="tip">Upload file</span></a></li>
<li><a href="{{ route('url-shrinker') }}"><i data-feather="crosshair"></i> <span class="tip">Shrink URL</span></a></li>
{% if user.is_admin %}
<li><a href="{{ route('backend') }}"><i data-feather="settings"></i> <span class="tip">Backend</span></a></li>
{% endif %}
<li><a href="{{ route('account') }}"><i data-feather="user"></i> <span class="tip">{{ user.name | default('Account') }}</span></a>
<ul class="dropdown">
<li><a href="{{ route('auth-tokens') }}"><i data-feather="key"></i> <span class="tip">Auth tokens</span></a></li>
<li>
<hr>
<form action="{{ route('logout') }}?{{ querystring.stringify({redirect_uri: '/'}) }}" method="POST">
<button><i data-feather="log-out"></i> <span class="tip">Logout</span></button>
{{ macros.csrf(getCsrfToken) }}
</form>
</li>
</ul>
</li>
{% else %}
<li><a href="{{ route('auth') }}"><i data-feather="user"></i> <span class="tip">Login / Register</span></a></li>
{% endif %}
</ul>
</nav>
{% endblock %}
{% block _body %}
<div class="container">
{{ macros.messages(flash) }}
</div>
<main>
{% if h1 %}
<h1>{{ h1 }}</h1>
{% endif %}
{% if subtitle %}
<p>{{ subtitle }}</p>
{% endif %}
{% block body %}{% endblock %}
</main>
{% endblock %}
{% block footer %}{{ app.name }} v{{ app_version }} - all rights reserved.{% endblock %}

View File

@ -1,75 +0,0 @@
{% extends 'layouts/base.njk' %}
{% set title = app.name + ' - Shrink URL' %}
{% block scripts %}
<script src="/js/url-shrinker.js"></script>
{% endblock %}
{% block body %}
<h1>Shrink URLs</h1>
<p>For security reasons, shrinked URLs cannot be deleted.</p>
<div class="container">
<section class="panel">
<h2><i data-feather="crosshair"></i> Shrink a URL</h2>
<form action="{{ route('shrink-url') }}" method="POST" id="url-shrink-form">
{{ macros.field(_locals, 'text', 'target_url', '', 'Target URL', 'Only valid URLs starting with http:// or https://', validation_attributes='required') }}
{{ macros.field(_locals, 'checkbox', 'autogen_url', '', 'Generate url automatically', null, validation_attributes='checked') }}
{{ macros.field(_locals, 'text', 'slug', '', 'Custom url slug', 'Example: bear sets url to https://'+default_domain+'/bear', validation_attributes='disabled') }}
{{ macros.csrf(getCsrfToken) }}
<button type="submit"><i data-feather="link"></i> Shrink URL</button>
</form>
{% set url = flash('url') %}
{% if url | length %}
<div class="copyable-text">
<div class="title">URL</div>
<div class="content">{{ url }}</div>
<button class="copy-button"><i data-feather="copy"></i></button>
</div>
{% endif %}
</section>
<section class="panel">
<h2><i data-feather="link"></i> URL list</h2>
{{ macros.paginate(urls.pagination, 'url-shrinker', 3) }}
<table class="data-table">
<thead>
<tr>
<th>#</th>
<th class="table-col-grow">Target</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for url in urls %}
<tr>
<td>{{ url.id }}</td>
<td class="table-col-grow-cell"><a href="{{ url.getURL() }}"><pre>{{ url.target_url }}</pre></a></td>
<td class="actions">
<div>
<button class="copy-button" data-content="{{ url.getURL() }}"><i data-feather="copy"></i> <span class="tip">Copy URL</span></button>
</div>
</td>
</tr>
{% else %}
<tr>
<td colspan="3" class="center">You haven't shrunk any url yet.</td>
</tr>
{% endfor %}
</tbody>
</table>
{{ macros.paginate(urls.pagination, 'url-shrinker', 3) }}
</section>
</div>
{% endblock %}

View File

@ -1,100 +0,0 @@
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const dev = process.env.NODE_ENV === 'development';
const userConfig = require('./assets/config.json');
for (const b in userConfig.bundles) {
if (userConfig.bundles.hasOwnProperty(b)) {
userConfig.bundles[b] = `./assets/${userConfig.bundles[b]}`;
}
}
const config = {
entry: userConfig.bundles,
output: {
path: path.resolve(__dirname, 'public/js'),
filename: '[name].js'
},
devtool: dev ? 'eval-source-map' : undefined,
module: {
rules: [
{
test: /\.js$/i,
use: [
{
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env'],
}
}
]
},
{
test: /\.s[ac]ss$/i,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: '/',
}
},
'css-loader',
'sass-loader',
]
},
{
test: /\.(woff2?|eot|ttf|otf)$/i,
use: 'file-loader?name=../fonts/[name].[ext]',
},
{
test: /\.tsx?$/i,
use: {
loader: 'ts-loader',
options: {
configFile: 'tsconfig.frontend.json',
}
},
exclude: '/node_modules/'
},
{
test: /\.(png|jpe?g|gif|svg)$/i,
use: [
'file-loader?name=../img/[name].[ext]',
{
loader: 'img-loader',
options: {
enabled: !dev,
plugins: [
require('imagemin-gifsicle')({}),
require('imagemin-mozjpeg')({}),
require('imagemin-pngquant')({}),
require('imagemin-svgo')({}),
]
}
}
]
}
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
plugins: [
new MiniCssExtractPlugin({
filename: '../css/[name].css',
}),
]
};
if (!dev) {
config.optimization = {
minimize: true,
minimizer: [
new TerserPlugin(),
]
};
}
module.exports = config;

7542
yarn.lock

File diff suppressed because it is too large Load Diff