Compare commits

..

116 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
3b833e013b Version 1.0.3 2021-04-22 20:15:51 +02:00
d5aa2c70db File upload list: hide size and expires at columns on mobile 2021-04-22 20:14:53 +02:00
4573846c7b Prevent shrunk url list from overflowing 2021-04-22 20:05:24 +02:00
75650bf23f Restore default table cell behavior for actions and table-col-grow-cell 2021-04-22 20:04:48 +02:00
53c5763909 Add user confirmation dialog on delete file button 2021-04-22 19:48:55 +02:00
51da9f4c7c Prevent upload list from overflowing and add standalone copy text button 2021-04-22 19:25:20 +02:00
3e5f245121 Put checkboxes before their field in file upload and url shrink forms 2021-04-22 18:35:36 +02:00
30960e42c5 Add default text row in file upload list and shrunk url list 2021-04-22 18:34:53 +02:00
03989be9ab Upgrade dependencies 2021-04-22 18:25:43 +02:00
bc5fda7d16 Merge branch 'boilerplate' into develop 2021-04-22 14:24:20 +02:00
f5d135d331 Merge branch 'develop' 2021-04-22 14:21:08 +02:00
82439366ba Fix imagemin peer dependency of img-loader 2021-04-22 14:06:53 +02:00
162f884103 Upgrade dependencies 2021-04-22 12:34:20 +02:00
00bb24cf2e Update repository url 2021-04-22 12:30:40 +02:00
459c83b47d Version 1.0.2 2021-03-30 17:27:19 +02:00
349a8b65de Fix file uploading not working (ttl doesn't exist anymore) 2021-03-30 17:27:04 +02:00
8555a35970 Version 1.0.1 2021-03-30 17:03:24 +02:00
9ef3a07f5f Merge branch 'boilerplate' into develop 2021-03-30 17:01:59 +02:00
4bcee79e8a Merge branch 'develop' 2021-03-30 16:56:44 +02:00
d223c9c77f Update config to new swaf version 2021-03-30 16:56:35 +02:00
0b07ff68d9 Remove forgotten debug log 2021-03-30 16:46:41 +02:00
e2c1d17f75 Version 1.0.0 2021-03-30 16:36:14 +02:00
1dcbb6b414 Add old file deletion daily job 2021-03-30 16:31:23 +02:00
c8d7c664e2 files: replace ttl with expires_at 2021-03-30 16:22:46 +02:00
faa728aacb layout.scss: allow .form-field to be hidden with .hidden 2021-03-30 14:36:06 +02:00
33947012e4 urls and files: hide custom slug field when generating automatically 2021-03-30 14:32:40 +02:00
1e00834324 File uploader: change subtitle to a better disclaimer 2021-03-30 14:30:46 +02:00
fe60a611b6 layout.scss: allow .form-field to be hidden with .hidden 2021-03-30 14:27:03 +02:00
6e92eb2740 Simplify menu auth-tokens display text 2021-03-30 14:12:42 +02:00
84b0ed9d88 Merge branch 'boilerplate' into develop 2021-03-30 12:46:05 +02:00
00b1f25804 Merge branch 'develop' 2021-03-30 12:45:12 +02:00
12f82f0f3d package.json: use NodeJS scripts instead of unix commands 2021-03-30 12:44:09 +02:00
ceaa0769bc Upgrade dependencies 2021-03-30 12:39:40 +02:00
0f83dd7ad6 layout.scss: add pagination default style 2021-03-30 12:34:24 +02:00
f853be6fb9 layout.scss: add pagination default style 2021-03-30 12:32:41 +02:00
0de960a168 urls & files: set page size to 25, add page nav and sort by create desc 2021-03-30 12:32:21 +02:00
0dfae21005 Move auth tokens to dedicated page 2021-03-30 12:19:56 +02:00
a5729af3c1 Merge file/url creating form and manager 2021-03-30 12:19:56 +02:00
a2a9d20994 Remove old domain gris.li from default production config 2021-03-30 12:19:56 +02:00
42c705ac6b Upgrade dependencies 2021-03-30 12:19:53 +02:00
ecd18cabe2 Version 0.6.0 2021-01-26 14:38:52 +01:00
959e5ca276 Remove duplicate definition of .copyable-text and improve table layout 2021-01-26 14:30:46 +01:00
7d6242861e frontend: make use of new width space and use more icons 2021-01-26 14:29:29 +01:00
8b42d83edf Remove duplicate definition of .copyable-text and improve table layout 2021-01-26 14:28:53 +01:00
a8954fbf22 Update config parameter base_url -> public_url 2021-01-26 14:27:55 +01:00
42c49974ea frontend: reorganize menu with dropdowns 2021-01-26 14:27:26 +01:00
4b7d33d9d3 Merge branch 'boilerplate' into develop 2021-01-26 13:38:21 +01:00
1cdd118806 Merge branch 'develop' 2021-01-26 13:37:58 +01:00
145d8df70a css: move menu .tip visibility to layout.scss 2021-01-26 13:37:41 +01:00
6723cdb1ee Merge branch 'boilerplate' into develop 2021-01-26 13:18:11 +01:00
2726fd16cc Merge branch 'develop' 2021-01-26 13:17:51 +01:00
8612b0f33a css: move lighter theme to layout.scss and make header css mobile first 2021-01-26 13:00:38 +01:00
bda464ab16 css: move a hover color and td.actions improvements to layout.scss 2021-01-26 13:00:23 +01:00
e7165edafd Add hover color on warning buttons 2021-01-26 11:43:42 +01:00
16394c0d4c Set icon size for titles 2021-01-26 11:43:13 +01:00
d2a67a12ee Fix subpanel leaking out of their container 2021-01-26 11:42:24 +01:00
1043690a5d Add bigger container max-width for desktop view 2021-01-26 11:38:26 +01:00
d6f4d612fe Update to swaf 0.23.4 2021-01-25 17:56:56 +01:00
c6b4c2dfe3 Install and upgrade dependencies 2021-01-25 13:28:45 +01:00
f5ccab3b34 Merge remote-tracking branch 'boilerplate/master' into develop 2021-01-25 13:26:58 +01:00
46168c0e90 Merge branch 'develop' 2021-01-25 13:20:25 +01:00
5eaebd5d12 Upgrade dependencies and bump swaf to ^0.23.0 2021-01-25 13:18:49 +01:00
ff1f3d6f19 .gitignore: add config/local.* 2021-01-25 11:55:41 +01:00
2290170569 Add maildev as a dev dependency 2021-01-25 11:45:00 +01:00
9f3a541c3e Add maildev as a dev dependency 2021-01-25 11:44:22 +01:00
93ac2f151d Version 0.5.5 2020-11-27 15:29:13 +01:00
892cf26628 Fix api authentication 2020-11-27 15:28:28 +01:00
13abf62368 Add FixUserMainEmailRelation migration 2020-11-27 15:12:00 +01:00
44b32401a7 Merge branch 'develop' 2020-07-16 09:25:10 +02:00
82 changed files with 5844 additions and 7910 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,114 +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",
"webpack.config.js",
"dist/**/*",
"public/**/*",
"config/**/*"
],
"overrides": [
{
"files": [
"test/**/*"
],
"rules": {
"max-len": [
"error",
{
"code": 120,
"ignoreTemplateLiterals": true,
"ignoreRegExpLiterals": true,
"ignoreStrings": true
}
]
}
}
]
}

8
.gitignore vendored
View File

@ -4,4 +4,10 @@ public
dist
yarn-error.log
storage/tmp
storage/uploads
storage/uploads
config/local.*
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,31 +0,0 @@
$primary: darken(#242b33, 2%);
$primaryForeground: #f0f0f0;
$secondary: lighten(#842cff, 10%);
$secondaryForeground: $primaryForeground;
$backgroundColor: darken($primary, 4%);
$defaultTextColor: #ffffff;
$headerBackground: darken($primary, 7.5%);
$footerBackground: lighten($headerBackground, 1%);
$panelBackground: lighten($headerBackground, 1%);
$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: 632px;

View File

@ -1,2 +0,0 @@
@import "layout";
@import "fm";

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,871 +0,0 @@
@import "vars";
@import 'fonts';
* {
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;
justify-content: space-between;
$headerHeight: 64px;
height: $headerHeight;
line-height: $headerHeight;
background-color: $headerBackground;
.logo {
display: flex;
flex-direction: row;
padding: 0 24px 0 16px;
font-size: 32px;
color: $defaultTextColor;
&:hover {
color: lighten($defaultTextColor, 10%);
}
img {
width: $headerHeight;
height: $headerHeight;
margin-right: 16px;
}
}
nav {
ul {
display: flex;
flex-direction: row;
margin: 0;
padding: 0;
font-size: 20px;
li {
position: relative;
list-style: none;
a, button {
position: relative;
height: 64px;
margin: 0;
padding: 0 24px;
display: flex;
flex-direction: row;
align-items: center;
&:hover, &:active {
&:not(button) {
background-color: rgba(255, 255, 255, 0.07);
}
}
.feather {
--icon-size: 24px;
}
}
button {
margin: 8px;
padding: 24px;
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: absolute;
z-index: -1;
top: 100%;
right: 0;
white-space: nowrap;
background: $headerBackground;
border-radius: 0 0 3px 3px;
a {
padding: 0 8px;
}
}
&:hover .dropdown {
display: block;
}
}
}
#menu-button {
display: none;
}
}
@media (max-width: $mobileThreshold) {
flex-direction: row-reverse;
.logo {
padding: 0 16px 0 8px;
font-size: 24px;
img {
margin-right: 8px;
}
}
nav {
#menu-button {
display: block;
margin: 0;
padding: 0 16px;
line-height: $headerHeight;
cursor: pointer;
background: transparent;
border-radius: 0;
.feather {
--icon-size: 28px;
margin: 0 8px;
}
}
> ul {
flex-direction: column;
position: absolute;
z-index: 10;
left: 0;
transform: translateX(-100%);
transition: transform ease-out 150ms;
background-color: $headerBackground;
&.open {
transform: translateX(0%);
}
li {
a, button {
.tip {
display: block;
margin-left: 8px;
text-transform: inherit;
font-weight: inherit;
}
}
.dropdown {
position: initial;
display: block;
padding-left: 32px;
}
}
}
}
}
@media (min-width: $mobileThreshold) {
nav ul li {
a, button, .button {
@include tip;
}
&:last-child {
a, button, .button {
.tip {
left: unset;
right: 4px;
transform: none;
}
}
}
}
}
}
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, 10%);
}
.feather.feather-external-link {
--icon-size: 16px;
margin-left: 4px;
margin-top: -3px;
}
}
form {
padding: 8px 16px;
text-align: center;
.form-field {
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;
}
&.error, &.danger {
background-color: $errorColor;
&:hover {
background-color: lighten($errorColor, 10%);
}
}
&.transparent {
background-color: transparent;
}
&:hover {
color: $primaryForeground;
}
}
.data-table {
width: 100%;
text-align: left;
border-collapse: collapse;
th, td {
padding: 8px;
}
th {
border-bottom: 1px solid #39434a;
}
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 {
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;
}
@mixin container {
width: $mobileThreshold;
padding: 0 16px;
@media (min-width: $mobileThreshold) {
margin: 0 auto;
}
@media (max-width: $mobileThreshold) {
width: 100%;
padding: 0 8px;
}
}
.container {
@include container;
}
.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 -18px;
padding: 1px 16px;
border: 2px solid lighten($panelBackground, 4%);
border-radius: 5px;
}
// ---
// --- 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;
}
// ---
// --- 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 {
overflow: hidden;
white-space: nowrap;
padding: 8px;
}
.copy-button {
margin: 0;
padding: 0;
border-radius: 0;
.feather {
--icon-size: 20px;
margin: 8px;
}
}
}
.copyable-text {
display: flex;
flex-direction: row;
margin: 8px;
background-color: darken($backgroundColor, 2%);
border-radius: 5px;
overflow: hidden;
.title {
padding: 8px;
}
.content {
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;
}
}

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,15 +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');
});
}
});
});

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,171 +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?.addEventListener('change', () => {
expireAfterDaysField.disabled = neverExpireCheckbox.checked;
});
}
if (slugField) {
autogenUrlCheckbox?.addEventListener('change', () => {
slugField.disabled = autogenUrlCheckbox.checked;
});
}
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,13 +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?.addEventListener('change', () => {
slugField.disabled = autogenUrlCheckbox.checked;
});
}
});

View File

@ -1,57 +1,66 @@
{
app: {
name: 'ily.li',
contact_email: 'contact@ily.li',
},
log_level: "DEV",
db_log_level: "ERROR",
public_url: "http://localhost:4899",
public_websocket_url: "ws://localhost:4899",
port: 4899,
mysql: {
connectionLimit: 10,
host: "localhost",
user: "root",
password: "",
database: "ilyli",
create_database_automatically: false,
},
redis: {
host: "127.0.0.1",
port: 6379,
prefix: 'ilyli',
},
session: {
cookie: {
secure: false,
},
},
mail: {
host: "127.0.0.1",
port: "1025",
secure: false,
username: "",
password: "",
allow_invalid_tls: true,
from: 'contact@ily.li',
from_name: 'ily.li',
},
view: {
cache: false,
},
magic_link: {
validity_period: 20,
},
newlyGeneratedSlugSize: 3,
default_file_ttl: 30, // 30 seconds
max_upload_size: 16, // MB
max_hotlink_size: 1, // MB
approval_mode: false,
domain: 'localhost',
allowed_url_domains: [
'localhost:4899',
'127.0.0.1:4899',
],
default_url_domain_for_files: 0,
default_url_domain_for_urls: 1,
app: {
name: 'ily.li',
contact_email: 'contact@ily.li',
},
log_level: "DEV",
db_log_level: "ERROR",
public_url: "http://localhost:4899",
public_websocket_url: "ws://localhost:4899",
port: 4899,
mysql: {
connectionLimit: 10,
host: "localhost",
user: "root",
password: "",
database: "ilyli",
create_database_automatically: false,
},
redis: {
host: "127.0.0.1",
port: 6379,
prefix: 'ilyli',
},
session: {
cookie: {
secure: false,
},
},
mail: {
host: "127.0.0.1",
port: "1025",
secure: false,
username: "",
password: "",
allow_invalid_tls: true,
from: 'contact@ily.li',
from_name: 'ily.li',
},
view: {
cache: false,
},
magic_link: {
validity_period: 20,
},
auth: {
approval_mode: false,
// 30 days
name_change_wait_period: 2592000000,
},
newlyGeneratedSlugSize: 3,
// 30 seconds
default_file_ttl: 30,
// MB
max_upload_size: 16,
// MB
max_hotlink_size: 1,
domain: 'localhost',
allowed_url_domains: [
'localhost:4899',
'127.0.0.1:4899',
],
default_url_domain_for_files: 0,
default_url_domain_for_urls: 1,
// 1 hour in ms
delete_old_files_interval: 3600000,
}

View File

@ -1,30 +1,36 @@
{
log_level: "DEBUG",
db_log_level: "ERROR",
public_url: 'https://ily.li',
public_websocket_url: 'wss://ily.li',
session: {
cookie: {
secure: true
},
},
mail: {
secure: true,
allow_invalid_tls: false
},
magic_link: {
validity_period: 900,
},
newlyGeneratedSlugSize: 5,
default_file_ttl: 2592000, // 30 days
max_upload_size: 8192, // MB
max_hotlink_size: 128, // MB
approval_mode: true,
domain: 'ily.li',
allowed_url_domains: [
'ily.li',
'gris.li',
],
default_url_domain_for_files: 0,
default_url_domain_for_urls: 1,
log_level: "DEBUG",
db_log_level: "ERROR",
public_url: 'https://ily.li',
public_websocket_url: 'wss://ily.li',
session: {
cookie: {
secure: true
},
},
mail: {
secure: true,
allow_invalid_tls: false
},
magic_link: {
validity_period: 900,
},
newlyGeneratedSlugSize: 5,
// 30 days
default_file_ttl: 2592000,
// MB
max_upload_size: 8192,
// MB
max_hotlink_size: 128,
auth: {
approval_mode: true,
},
domain: 'ily.li',
allowed_url_domains: [
'ily.li',
],
default_url_domain_for_files: 0,
default_url_domain_for_urls: 0,
// 1 day in ms
delete_old_files_interval: 86400000
}

View File

@ -1,66 +1,59 @@
{
"name": "ily.li",
"version": "0.5.4",
"version": "1.1.0",
"description": "Self-hosted file pusher",
"repository": "https://eternae.ink/arisu/ily.li",
"repository": "https://eternae.ink/ashpie/ily.li",
"author": "Alice Gaudon <alice@gaudon.pro>",
"license": "GPL-3.0-only",
"main": "dist/src/main.js",
"main": "dist/main.js",
"scripts": {
"dist-webpack": "webpack --mode production",
"clean": "(test ! -d dist || rm -r dist)",
"compile": "yarn clean && tsc",
"build": "yarn compile && yarn dist-webpack",
"lint": "eslint . --ext .js,.jsx,.ts,.tsx",
"dev": "concurrently -k -n \"Typescript,Node,Webpack,Maildev\" -p \"[{name}]\" -c \"blue,green,red,yellow\" \"tsc --watch\" \"nodemon\" \"webpack --watch --mode development\" \"maildev\"",
"start": "yarn build && node dist/src/main.js",
"test": "jest --verbose --runInBand"
"test": "jest --verbose --runInBand",
"clean": "node scripts/clean.js",
"prepare-sources": "node scripts/prepare-sources.js",
"compile": "yarn clean && yarn prepare-sources && tsc --build",
"build": "yarn compile && node . pre-compile-views && node scripts/dist.js",
"build-production": "NODE_ENV=production yarn build",
"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 .",
"start": "yarn build-production && node ."
},
"devDependencies": {
"@babel/core": "^7.9.0",
"@babel/preset-env": "^7.9.5",
"@fortawesome/fontawesome-free": "^5.14.0",
"@types/config": "^0.0.36",
"@tsconfig/svelte": "^3.0.0",
"@types/config": "^0.0.41",
"@types/express": "^4.17.6",
"@types/express-session": "^1.17.0",
"@types/feather-icons": "^4.7.0",
"@types/formidable": "^1.0.31",
"@types/jest": "^26.0.4",
"@types/formidable": "^2.0.0",
"@types/jest": "^27.0.3",
"@types/mysql": "^2.15.15",
"@types/node": "^14.6.3",
"@types/node": "^17.0.4",
"@types/nodemailer": "^6.4.0",
"@types/nunjucks": "^3.1.3",
"@types/ws": "^7.2.6",
"@typescript-eslint/eslint-plugin": "^4.3.0",
"@typescript-eslint/parser": "^4.3.0",
"babel-loader": "^8.1.0",
"concurrently": "^5.1.0",
"css-loader": "^5.0.0",
"eslint": "^7.10.0",
"feather-icons": "^4.28.0",
"file-loader": "^6.0.0",
"imagemin": "^7.0.1",
"@types/ws": "^8.2.0",
"@typescript-eslint/eslint-plugin": "^5.4.0",
"@typescript-eslint/parser": "^5.4.0",
"concurrently": "^7.0.0",
"eslint": "^8.3.0",
"eslint-plugin-import": "^2.25.3",
"eslint-plugin-simple-import-sort": "^7.0.0",
"eslint-plugin-svelte3": "^3.2.1",
"imagemin-gifsicle": "^7.0.0",
"imagemin-mozjpeg": "^9.0.0",
"imagemin-pngquant": "^9.0.0",
"imagemin-svgo": "^8.0.0",
"img-loader": "^3.0.1",
"jest": "^26.1.0",
"mini-css-extract-plugin": "^1.2.1",
"node-sass": "^5.0.0",
"imagemin-mozjpeg": "^10.0.0",
"imagemin-pngquant": "^9.0.2",
"imagemin-svgo": "^10.0.0",
"imagemin-webp": "^7.0.0",
"jest": "^27.0.4",
"maildev": "^1.1.0",
"nodemon": "^2.0.3",
"sass-loader": "^10.0.1",
"terser-webpack-plugin": "^5.0.3",
"ts-jest": "^26.1.1",
"ts-loader": "^8.0.4",
"typescript": "^4.0.2",
"webpack": "^5.3.2",
"webpack-cli": "^4.1.0"
"sass": "^1.32.12",
"svelte": "^3.44.2",
"svgo": "^2.3.0",
"ts-jest": "^27.0.3",
"typescript": "^4.0.2"
},
"dependencies": {
"config": "^3.3.1",
"express": "^4.17.1",
"formidable": "^1.2.2",
"swaf": "^0.22.5"
"formidable": "^2.0.1",
"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,
};

12
scripts/clean.js Normal file
View File

@ -0,0 +1,12 @@
const fs = require('fs');
[
'intermediates',
'dist',
'public',
].forEach(file => {
if (fs.existsSync(file)) {
console.log('Cleaning', file, '...');
fs.rmSync(file, {recursive: true});
}
});

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

@ -0,0 +1,28 @@
const fs = require('fs');
const path = require('path');
// 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,68 +1,85 @@
import Application from "swaf/Application";
import Migration, {MigrationType} from "swaf/db/Migration";
import CreateMigrationsTable from "swaf/migrations/CreateMigrationsTable";
import AccountController from "swaf/auth/AccountController";
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 NunjucksComponent from "swaf/components/NunjucksComponent";
import MysqlComponent from "swaf/components/MysqlComponent";
import FormHelperComponent from "swaf/components/FormHelperComponent";
import FrontendToolsComponent from "swaf/components/FrontendToolsComponent";
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 ServeStaticDirectoryComponent from "swaf/components/ServeStaticDirectoryComponent";
import MaintenanceComponent from "swaf/components/MaintenanceComponent";
import MailComponent from "swaf/components/MailComponent";
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 AboutController from "./controllers/AboutController";
import AutoUpdateComponent from "swaf/components/AutoUpdateComponent";
import AuthController from "./controllers/AuthController";
import MagicLinkWebSocketListener from "swaf/auth/magic_link/MagicLinkWebSocketListener";
import MagicLinkController from "./controllers/MagicLinkController";
import MailController from "swaf/auth/MailController";
import FileController from "./controllers/FileController";
import CreateUsersAndUserEmailsTable from "swaf/auth/migrations/CreateUsersAndUserEmailsTable";
import CreateMagicLinksTable from "swaf/auth/migrations/CreateMagicLinksTable";
import CreateAuthTokensTable from "./migrations/CreateAuthTokensTable";
import AuthComponent from "swaf/auth/AuthComponent";
import AuthGuard from "swaf/auth/AuthGuard";
import MagicLink from "swaf/auth/models/MagicLink";
import AuthToken from "./models/AuthToken";
import {MagicLinkActionType} from "./controllers/MagicLinkActionType";
import {Request} from "express";
import CreateFilesTable from "./migrations/CreateFilesTable";
import IncreaseFilesSizeField from "./migrations/IncreaseFilesSizeField";
import AddApprovedFieldToUsersTable from "swaf/auth/migrations/AddApprovedFieldToUsersTable";
import CreateUrlRedirectsTable from "./migrations/CreateUrlRedirectsTable";
import AuthTokenController from "./controllers/AuthTokenController";
import URLRedirectController from "./controllers/URLRedirectController";
import LinkController from "./controllers/LinkController";
import Migration, {MigrationType} from "swaf/db/Migration";
import AssetCompiler from "swaf/frontend/AssetCompiler";
import CopyAssetPreCompiler from "swaf/frontend/CopyAssetPreCompiler";
import MailViewEngine from "swaf/frontend/MailViewEngine";
import NunjucksViewEngine from "swaf/frontend/NunjucksViewEngine";
import ScssAssetPreCompiler from "swaf/frontend/ScssAssetPreCompiler";
import SvelteViewEngine from "swaf/frontend/SvelteViewEngine";
import TypeScriptPreCompiler from "swaf/frontend/TypeScriptPreCompiler";
import BackendController from "swaf/helpers/BackendController";
import RedirectBackComponent from "swaf/components/RedirectBackComponent";
import DummyMigration from "swaf/migrations/DummyMigration";
import MailController from "swaf/mail/MailController";
import {MAGIC_LINK_MAIL} from "swaf/Mails";
import CreateMigrationsTable from "swaf/migrations/CreateMigrationsTable";
import DropLegacyLogsTable from "swaf/migrations/DropLegacyLogsTable";
import {Session} from "express-session";
import packageJson = require('../package.json');
import DummyMigration from "swaf/migrations/DummyMigration";
import AboutController from "./controllers/AboutController.js";
import AuthTokenController from "./controllers/AuthTokenController.js";
import FileController from "./controllers/FileController.js";
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 {
public constructor(
version: string,
private readonly addr: string,
private readonly port: number,
) {
super(packageJson.version);
super(version);
}
protected getMigrations(): MigrationType<Migration>[] {
return [
CreateMigrationsTable,
DummyMigration,
CreateUsersAndUserEmailsTable,
CreateMagicLinksTable,
CreateUsersAndUserEmailsTableMigration,
CreateMagicLinksTableMigration,
CreateAuthTokensTable,
CreateFilesTable,
IncreaseFilesSizeField,
AddApprovedFieldToUsersTable,
AddApprovedFieldToUsersTableMigration,
CreateUrlRedirectsTable,
DropLegacyLogsTable,
DummyMigration,
AddUsedToMagicLinksMigration,
MakeMagicLinksSessionNotUniqueMigration,
AddPasswordToUsersMigration,
DummyMigration,
ReplaceTtlWithExpiresAtFilesTable,
];
}
@ -73,13 +90,8 @@ export default class App extends Application {
}
private registerComponents() {
const redisComponent = new RedisComponent();
const mysqlComponent = new MysqlComponent();
const expressAppComponent = new ExpressAppComponent(this.addr, this.port);
this.use(expressAppComponent);
// Base
this.use(new ExpressAppComponent(this.addr, this.port));
this.use(new LogRequestsComponent());
// Static files
@ -87,44 +99,32 @@ export default class App extends Application {
this.use(new ServeStaticDirectoryComponent('node_modules/feather-icons/dist', '/icons'));
// Dynamic views and routes
this.use(new NunjucksComponent());
this.use(new RedirectBackComponent());
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());
// Maintenance
this.use(new MaintenanceComponent(this, () => {
return redisComponent.canServe() && mysqlComponent.canServe();
}));
this.use(new MaintenanceComponent());
this.use(new AutoUpdateComponent());
// Services
this.use(mysqlComponent);
this.use(new MailComponent());
this.use(new MysqlComponent());
this.use(new MailComponent(new MailViewEngine(intermediateDirectory, ...additionalViewPaths)));
// Session
this.use(redisComponent);
this.use(new SessionComponent(redisComponent));
this.use(new AuthComponent(new class extends AuthGuard<MagicLink | AuthToken> {
public async getProofForSession(session: Session): Promise<MagicLink | AuthToken | null> {
return await MagicLink.bySessionId(
session.id,
[MagicLinkActionType.LOGIN, MagicLinkActionType.REGISTER],
);
}
public async getProofForRequest(req: Request): Promise<MagicLink | AuthToken | null> {
const authorization = req.header('Authorization');
if (authorization) {
const token = await AuthToken.select().where('secret', authorization).first();
if (token) {
token.use();
await token.save();
}
return token;
}
return await super.getProofForRequest(req);
}
}(this)));
this.use(new RedisComponent());
this.use(new SessionComponent(this.as(RedisComponent)));
this.use(new AuthComponent(this, new MagicLinkAuthMethod(this, MAGIC_LINK_MAIL), new PasswordAuthMethod(this)));
// Utils
this.use(new FormHelperComponent());
@ -133,7 +133,11 @@ export default class App extends Application {
this.use(new CsrfProtectionComponent());
// WebSocket server
this.use(new WebSocketServerComponent(this, expressAppComponent, redisComponent));
this.use(new WebSocketServerComponent());
// Jobs
this.use(new DeleteOldFilesJobComponent());
}
private registerWebSocketListeners() {
@ -145,12 +149,13 @@ export default class App extends Application {
this.use(new LinkController());
// Priority
this.use(new MailController());
this.use(new AuthController());
this.use(new MagicLinkController(this.as<MagicLinkWebSocketListener<this>>(MagicLinkWebSocketListener)));
this.use(new BackendController());
// Core functionality
this.use(new MailController());
// Core
this.use(new AccountController());
this.use(new BackendController());
// Other functionality
this.use(new AuthTokenController());

View File

@ -0,0 +1,63 @@
import config from "config";
import ApplicationComponent from "swaf/ApplicationComponent";
import MysqlComponent from "swaf/components/MysqlComponent";
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;
export default class DeleteOldFilesJobComponent extends ApplicationComponent {
private timeout?: Timeout;
private readonly interval: number = config.get<number>('delete_old_files_interval');
public async start(): Promise<void> {
if (this.getApp().as(MysqlComponent).isReady()) {
await this.run();
}
this.schedule();
}
public async stop(): Promise<void> {
if (this.timeout) {
clearInterval(this.timeout);
this.timeout = undefined;
}
}
private schedule(): void {
if (this.timeout) {
clearInterval(this.timeout);
this.timeout = undefined;
}
this.timeout = setInterval(() => {
if (this.getApp().as(MysqlComponent).isReady()) {
this.run().catch(err => logger.error(err));
}
}, this.interval);
logger.info(`Scheduled old file deletion job every ${this.interval}ms`);
}
private async run(): Promise<void> {
const filesToDelete = await FileModel.select()
.where('expires_at', new Date(), WhereTest.LE)
.get();
if (filesToDelete.length > 0) {
logger.info('Deleting old files...');
} else {
logger.info('No old file to delete.');
return;
}
for (const file of filesToDelete) {
logger.info(`Deleting ${file.id}`);
if (!file.shouldBeDeleted()) throw new Error('File should not be deleted.');
await FileController.deleteFile(file);
}
}
}

View File

@ -1,13 +1,13 @@
import {cryptoRandomDictionary} from "swaf/Utils";
import config from "config";
import FileModel from "./models/FileModel";
import {nanoid} from "nanoid";
import {ServerError} from "swaf/HttpError";
const SLUG_DICTIONARY = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
import FileModel from "./models/FileModel.js";
export default async function generateSlug(tries: number): Promise<string> {
let i = 0;
do {
const slug = cryptoRandomDictionary(config.get<number>('newlyGeneratedSlugSize'), SLUG_DICTIONARY);
const slug = nanoid(config.get<number>('newlyGeneratedSlugSize'));
if (!await FileModel.getBySlug(slug)) {
return slug;
}

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,29 +1,99 @@
<div class="container">
<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>
<BaseTemplate title="{$locals.app.name} - Auth tokens" description="Upload files directly from your desktop." noH1>
<h1>Auth tokens</h1>
<section class="panel">
<h2>Setup a desktop utility</h2>
<h2>
<Icon name="key"/>
Auth tokens
</h2>
<Form action="{route('generate-token')}" submitText="Generate a new token" submitIcon="file-plus"/>
<Pagination pagination={$locals.pagination} routeName="auth-tokens" contextSize={3}/>
<table class="data-table">
<thead>
<tr>
<th>#</th>
<th class="col-grow">Secret</th>
<th>Created at</th>
<th>Last used at</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{#each $locals.auth_tokens as token}
<tr>
<td>{token.id}</td>
<td>
<CopyableText content="{token.secret}"/>
</td>
<td>
<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 class="actions">
<Form action="{route('revoke-token', token.id)}" submitText="Revoke" submitIcon="trash"
submitClass="danger" button/>
</td>
</tr>
{/each}
</tbody>
</table>
<Pagination pagination={$locals.pagination} routeName="auth-tokens" contextSize={3}/>
</section>
<section class="panel">
<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
scripts/macros.</p>
<hr>
<section>
<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
download and use these scripts:</p>
<p>If you have the sh shell on your machine (i.e. you are on linux, git bash on windows...) and curl, you
can download and use these scripts:</p>
<table class="data-table">
<thead>
<tr>
<th>Name</th>
<th class="table-col-grow">Name</th>
<th>Download link</th>
</tr>
</thead>
<tbody>
<tr>
<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>
<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>
</tbody>
</table>
@ -32,8 +102,8 @@
<p>Examples:</p>
<pre>upload_file.sh path/to/file</pre>
<pre>upload_file.sh path/to/file my_very_important_file.png</pre>
<pre>shrink_url.sh https://gitlab.com/ArisuOngaku/ilyli</pre>
<pre>shrink_url.sh https://gitlab.com/ArisuOngaku/ilyli repo</pre>
<pre>shrink_url.sh https://eternae.ink/ashpie/ily.li</pre>
<pre>shrink_url.sh https://eternae.ink/ashpie/ily.li repo</pre>
</section>
<hr>
@ -85,7 +155,7 @@
<td>url_domain</td>
<td>Choose domain name</td>
<td>No</td>
<td>{{ allowed_domains.join('|') }}</td>
<td>{$locals.allowed_domains.join('|')}</td>
</tr>
<tr>
@ -107,53 +177,11 @@
<td>url_domain</td>
<td>Choose domain name</td>
<td>No</td>
<td>{{ allowed_domains.join('|') }}</td>
<td>{$locals.allowed_domains.join('|')}</td>
</tr>
</tbody>
</table>
<p>For examples with curl, please download and review the scripts above.</p>
</section>
</section>
</div>
<section class="panel">
<h2>Auth tokens</h2>
<form action="{{ route('generate-token') }}" method="POST">
{{ macros.csrf(getCsrfToken) }}
<button type="submit"><i data-feather="plus"></i> Generate a new token</button>
</form>
<table class="data-table">
<thead>
<tr>
<th>#</th>
<th>Secret</th>
<th>Created at</th>
<th>Last used at</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for token in auth_tokens %}
<tr>
<td>{{ token.id }}</td>
<td>
<div class="copyable-text">
<div class="content">{{ token.secret }}</div>
<button class="copy-button"><i data-feather="copy"></i></button>
</div>
</td>
<td>{{ token.created_at.toISOString() }}</td>
<td>{{ token.used_at.toISOString() }}</td>
<td>
<form action="{{ route('revoke-token', token.id) }}" method="POST">
<button class="button danger"><i data-feather="trash"></i> Revoke</button>
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</section>
</BaseTemplate>

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 Controller from "swaf/Controller";
export default class AboutController extends Controller {
public routes(): void {

View File

@ -1,8 +0,0 @@
import MagicLinkAuthController from "swaf/auth/magic_link/MagicLinkAuthController";
import {MAGIC_LINK_MAIL} from "swaf/Mails";
export default class AuthController extends MagicLinkAuthController {
public constructor() {
super(MAGIC_LINK_MAIL);
}
}

View File

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

View File

@ -1,46 +1,50 @@
import Controller from "swaf/Controller";
import {RequireAuthMiddleware} 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 {NextFunction, Request, Response} from "express";
import formidable from "formidable";
import * as fs from "fs";
import AuthToken from "../models/AuthToken";
import {IncomingForm} from "formidable";
import generateSlug from "../SlugGenerator";
import {log} from "swaf/Logger";
import path from "path";
import {RequireAuthMiddleware, RequireRequestAuthMiddleware} from "swaf/auth/AuthComponent";
import {route} from "swaf/common/Routing";
import Controller from "swaf/Controller";
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 {
public routes(): void {
this.get('/files/upload', this.getFileUploader, 'file-upload', RequireAuthMiddleware);
this.get('/files/upload/script', this.downloadLinuxScript, 'file-linux-script');
this.post('/files/post', this.postFileFrontend, 'post-file-frontend', RequireAuthMiddleware, FileUploadFormMiddleware);
this.get('/files/:page([0-9]+)?', this.getFileManager, 'file-manager', RequireAuthMiddleware);
this.post('/files/delete/:slug', FileController.deleteFileRoute, 'delete-file-frontend', RequireAuthMiddleware);
this.get('/files/:page([0-9]+)?', this.getFileUploader, 'file-uploader',
RequireAuthMiddleware);
this.get('/files/upload-script', this.downloadLinuxScript, 'file-linux-script');
this.post('/files/upload', this.postFileFrontend, 'post-file-frontend',
RequireAuthMiddleware, FileUploadFormMiddleware);
this.post('/files/delete/:slug', FileController.deleteFileRoute, 'delete-file-frontend',
RequireAuthMiddleware);
}
protected async getFileUploader(req: Request, res: Response): Promise<void> {
const allowedDomains = config.get<string[]>('allowed_url_domains');
const user = req.as(RequireAuthMiddleware).getUser();
res.render('file-upload', {
const files = await FileModel.paginateForUser(req, 25, user.getOrFail('id'));
res.render('file-uploader', {
max_upload_size: config.get<string>('max_upload_size'),
auth_tokens: await AuthToken.select().where('user_id', user.id).get(),
allowed_domains: allowedDomains,
default_domain: allowedDomains[config.get<number>('default_url_domain_for_files')],
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> {
res.download('assets/files/upload_file.sh', 'upload_file.sh');
}
protected async getFileManager(req: Request, res: Response): Promise<void> {
const user = req.as(RequireAuthMiddleware).getUser();
res.render('file-manager', {
files: await FileModel.paginateForUser(req, 100, user.getOrFail('id')),
});
res.download(path.resolve(__dirname, '..', 'assets/files/upload_file.sh'), 'upload_file.sh');
}
protected async postFileFrontend(req: Request, res: Response): Promise<void> {
@ -54,13 +58,25 @@ export default class FileController extends Controller {
);
}
public static async handleFileUpload(slug: string, req: Request, res: Response): Promise<void> {
public static async handleFileUpload(
slug: string,
req: Request,
res: Response,
requestAuth: boolean = false,
): Promise<void> {
// Check for file upload
if (Object.keys(req.files).indexOf('upload') < 0) {
throw new BadRequestError('No file received.', 'You must upload exactly one (1) file.', req.url);
}
const upload = req.files['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,
);
}
// TTL
let ttl = config.get<number>('default_file_ttl');
@ -68,22 +84,23 @@ export default class FileController extends Controller {
if (req.body.ttl !== undefined) ttl = parseInt(req.body.ttl);
else if (req.body.expire_after_days !== undefined) ttl = parseInt(req.body.expire_after_days) * 24 * 3600;
const user = req.as(RequireAuthMiddleware).getUser();
const user = (requestAuth ? req.as(RequireRequestAuthMiddleware) : req.as(RequireAuthMiddleware)).getUser();
const file = FileModel.create({
user_id: user.id,
slug: slug,
real_name: upload.name,
real_name: upload.originalFilename,
storage_type: 'local',
storage_path: 'storage/uploads/' + slug,
size: upload.size,
ttl: ttl,
expires_at: ttl <= 0 ? null : new Date(Date.now() + ttl * 1000),
});
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({
json: () => res.json({
url: file.getURL(domain),
@ -92,19 +109,24 @@ export default class FileController extends Controller {
html: () => {
req.flash('success', 'Upload success!');
req.flash('url', file.getURL(domain));
res.redirectBack('/');
res.redirect(route('file-uploader'));
},
});
}
public static async deleteFileRoute(req: Request, res: Response, next: NextFunction): Promise<void> {
public static async deleteFileRoute(
req: Request,
res: Response,
next: NextFunction,
requestAuth: boolean = false,
): Promise<void> {
const slug = req.params.slug;
if (!slug) throw new BadRequestError('Cannot delete nothing.', 'Please provide a slug.', req.url);
const file = await FileModel.getBySlug(req.params.slug);
if (!file) return next();
const user = req.as(RequireAuthMiddleware).getUser();
const user = (requestAuth ? req.as(RequireRequestAuthMiddleware) : req.as(RequireAuthMiddleware)).getUser();
if (!file.canDelete(user.getOrFail('id'))) throw new ForbiddenHttpError('file', req.url);
switch (file.storage_type) {
@ -122,7 +144,7 @@ export default class FileController extends Controller {
text: () => res.send('success'),
html: () => {
req.flash('success', 'Successfully deleted file.');
res.redirectBack('/');
res.redirect(route('file-uploader'));
},
});
}
@ -130,7 +152,7 @@ export default class FileController extends Controller {
public static async deleteFile(file: FileModel): Promise<void> {
fs.unlinkSync(file.getOrFail('storage_path'));
await file.delete();
log.info('Deleted', file.storage_path, `(${file.real_name})`);
logger.info('Deleted', file.storage_path, `(${file.real_name})`);
}
}
@ -139,11 +161,11 @@ export class FileUploadFormMiddleware extends FileUploadMiddleware {
return 'upload';
}
protected makeForm(): IncomingForm {
const form = new IncomingForm();
form.uploadDir = 'storage/tmp';
form.maxFileSize = config.get<number>('max_upload_size') * 1024 * 1024;
return form;
protected getFormidableOptions(): formidable.Options {
return {
uploadDir: 'storage/tmp',
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 {route} from "swaf/common/Routing";
import Controller from "swaf/Controller";
export default class HomeController extends Controller {
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
*/
protected async goBack(req: Request, res: Response): Promise<void> {
res.redirectBack();
res.redirect(req.getPreviousUrl() || route('home'));
}
}

View File

@ -1,29 +1,30 @@
import Controller from "swaf/Controller";
import {NextFunction, Request, Response} from "express";
import {BadRequestError, NotFoundHttpError, ServerError} from "swaf/HttpError";
import config from "config";
import {RequireRequestAuthMiddleware} from "swaf/auth/AuthComponent";
import URLRedirect from "../models/URLRedirect";
import URLRedirectController from "./URLRedirectController";
import FileModel from "../models/FileModel";
import generateSlug from "../SlugGenerator";
import FileController, {FileUploadFormMiddleware} from "./FileController";
import {NextFunction, Request, Response} from "express";
import * as fs from "fs";
import {encodeRFC5987ValueChars} from "../Utils";
import {RequireRequestAuthMiddleware} from "swaf/auth/AuthComponent";
import Controller from "swaf/Controller";
import {BadRequestError, NotFoundHttpError, ServerError} from "swaf/HttpError";
import {logger} from "swaf/Logger";
import {promisify} from "util";
import {log} from "swaf/Logger";
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 {
public routes(): void {
this.post('/', this.postFile, 'post-file', RequireRequestAuthMiddleware, FileUploadFormMiddleware);
this.delete('/:slug', FileController.deleteFileRoute, 'delete-file', RequireRequestAuthMiddleware);
this.delete('/:slug', this.deleteFile, 'delete-file', RequireRequestAuthMiddleware);
this.get('/:slug', this.getFile, 'get-file');
this.put('/:slug', this.putFile, 'put-file', RequireRequestAuthMiddleware, FileUploadFormMiddleware);
this.post('/', URLRedirectController.addURL, 'post-url', RequireRequestAuthMiddleware);
this.post('/', this.addURL, 'post-url', RequireRequestAuthMiddleware);
this.delete('/:slug', this.deleteURL, 'delete-url', RequireRequestAuthMiddleware);
this.get('/:slug', this.getURLRedirect, 'get-url');
this.put('/:slug', URLRedirectController.addURL, 'put-url', RequireRequestAuthMiddleware);
this.put('/:slug', this.addURL, 'put-url', RequireRequestAuthMiddleware);
this.get(/(.*)/, this.domainFilter);
}
@ -44,7 +45,7 @@ export default class LinkController extends Controller {
// If file is bigger than max hotlink size, fallback to express download
if (stats.size > config.get<number>('max_hotlink_size') * 1024 * 1024) {
log.info(`Fallback to express download for file of size ${stats.size}`);
logger.info(`Fallback to express download for file of size ${stats.size}`);
return res.download(file.getOrFail('storage_path'), fileName);
}
@ -69,15 +70,29 @@ export default class LinkController extends Controller {
protected async postFile(req: Request, res: Response, next: NextFunction): Promise<void> {
if (req.body.type !== 'file') return next();
await FileController.handleFileUpload(req.body.slug || await generateSlug(10), req, res);
await FileController.handleFileUpload(req.body.slug || await generateSlug(10), req, res, true);
}
protected async putFile(req: Request, res: Response, next: NextFunction): Promise<void> {
if (req.body.type !== 'file') return next();
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);
await FileController.handleFileUpload(slug, req, res, true);
}
protected async deleteFile(req: Request, res: Response, next: NextFunction): Promise<void> {
return await FileController.deleteFileRoute(req, res, next, true);
}
protected async addURL(req: Request, res: Response, next: NextFunction): Promise<void> {
return await URLRedirectController.addURL(req, res, next, undefined, true);
}
protected async getURLRedirect(req: Request, res: Response, next: NextFunction): Promise<void> {
@ -100,7 +115,7 @@ export default class LinkController extends Controller {
protected async domainFilter(req: Request, res: Response, next: NextFunction): Promise<void> {
if (req.hostname !== config.get('domain')) {
if (req.path === '/') return res.redirect(config.get<string>('base_url'));
if (req.path === '/') return res.redirect(config.get<string>('public_url'));
throw new NotFoundHttpError('Page', req.url);
}
next();

View File

@ -1,33 +0,0 @@
import _MagicLinkController from "swaf/auth/magic_link/MagicLinkController";
import {Request, Response} from "express";
import Controller from "swaf/Controller";
import MagicLinkWebSocketListener from "swaf/auth/magic_link/MagicLinkWebSocketListener";
import MagicLink from "swaf/auth/models/MagicLink";
import AuthController from "./AuthController";
import {MagicLinkActionType} from "./MagicLinkActionType";
import App from "../App";
import AuthComponent from "swaf/auth/AuthComponent";
export default class MagicLinkController extends _MagicLinkController<App> {
public constructor(magicLinkWebSocketListener: MagicLinkWebSocketListener<App>) {
super(magicLinkWebSocketListener);
}
protected async performAction(magicLink: MagicLink, req: Request, res: Response): Promise<void> {
switch (magicLink.action_type) {
case MagicLinkActionType.LOGIN:
case MagicLinkActionType.REGISTER: {
await AuthController.checkAndAuth(req, res, magicLink);
const proof = await this.getApp().as(AuthComponent).getAuthGuard().isAuthenticated(req.getSession());
const user = await proof?.getResource();
if (!res.headersSent && user) {
// Auth success
req.flash('success', `Authentication success. Welcome, ${user.name}!`);
res.redirect(req.query.redirect_uri?.toString() || Controller.route('home'));
}
break;
}
}
}
}

View File

@ -1,41 +1,40 @@
import Controller from "swaf/Controller";
import {NextFunction, Request, Response} from "express";
import URLRedirect from "../models/URLRedirect";
import {RequireAuthMiddleware} from "swaf/auth/AuthComponent";
import generateSlug from "../SlugGenerator";
import config from "config";
import AuthToken from "../models/AuthToken";
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 {
public routes(): void {
this.get('/url/shrink', this.getURLShrinker, 'url-shrinker', RequireAuthMiddleware);
this.get('/url/shrink/script', this.downloadLinuxScript, 'url-linux-script');
this.post('/url/shrink', this.addURLFrontend, 'shrink-url', RequireAuthMiddleware);
this.get('/urls/:page([0-9]+)?', this.getURLRedirectManager, 'url-manager', RequireAuthMiddleware);
this.get('/url/:page([0-9]+)?', this.getUrlShrinker, 'url-shrinker', RequireAuthMiddleware);
this.get('/url/shrink-script', this.downloadLinuxScript, 'url-linux-script');
this.post('/url/shrink', this.addUrlFrontend, 'shrink-url', RequireAuthMiddleware);
}
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 allowedDomains = config.get<string[]>('allowed_url_domains');
const urls = await URLRedirect.paginateForUser(req, 25, user.getOrFail('id'));
res.render('url-shrinker', {
auth_tokens: await AuthToken.select().where('user_id', user.id).get(),
allowed_domains: allowedDomains,
default_domain: allowedDomains[config.get<number>('default_url_domain_for_urls')],
urls: urls.map(url => ({
...url,
url: url.getURL(),
})),
pagination: urls.pagination?.serialize(),
});
}
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 getURLRedirectManager(req: Request, res: Response): Promise<void> {
const user = req.as(RequireAuthMiddleware).getUser();
res.render('url-manager', {
urls: await URLRedirect.paginateForUser(req, 100, user.getOrFail('id')),
});
}
protected async addURLFrontend(req: Request, res: Response, next: NextFunction): Promise<void> {
protected async addUrlFrontend(req: Request, res: Response, next: NextFunction): Promise<void> {
req.body.type = 'url';
await URLRedirectController.addURL(
req,
@ -47,10 +46,16 @@ export default class URLRedirectController extends Controller {
);
}
public static async addURL(req: Request, res: Response, next: NextFunction, slug?: string): Promise<void> {
public static async addURL(
req: Request,
res: Response,
next: NextFunction,
slug?: string,
requestAuth: boolean = false,
): Promise<void> {
if (req.body.type !== 'url') return next();
const user = req.as(RequireAuthMiddleware).getUser();
const user = (requestAuth ? req.as(RequireRequestAuthMiddleware) : req.as(RequireAuthMiddleware)).getUser();
slug = slug || req.params.slug || req.body.slug || await generateSlug(10);
const urlRedirect = URLRedirect.create({
user_id: user.id,
@ -60,7 +65,8 @@ export default class URLRedirectController extends Controller {
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({
json: () => res.json({
url: urlRedirect.getURL(domain),
@ -69,7 +75,7 @@ export default class URLRedirectController extends Controller {
html: () => {
req.flash('success', 'URL shrunk successfully!');
req.flash('url', urlRedirect.getURL(domain));
res.redirectBack('/');
res.redirect(route('url-shrinker'));
},
});
}

View File

@ -2,19 +2,27 @@ import {delimiter} from "path";
// Load config from specified path or default + swaf/config (default defaults)
process.env['NODE_CONFIG_DIR'] =
__dirname + '/../../node_modules/swaf/config/'
__dirname + '/../node_modules/swaf/config/'
+ delimiter
+ (process.env['NODE_CONFIG_DIR'] || __dirname + '/../../config/');
+ (process.env['NODE_CONFIG_DIR'] || __dirname + '/../config/');
import {log} from "swaf/Logger";
import App from "./App";
import config from "config";
import {promises as fs} from "fs";
import {logger} from "swaf/Logger";
import App from "./App.js";
(async () => {
log.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();
})().catch(err => {
log.error(err);
logger.error(err);
});

View File

@ -1,10 +1,10 @@
import {Connection} from "mysql";
import Migration from "swaf/db/Migration";
import ModelFactory from "swaf/db/ModelFactory";
import AuthToken from "../models/AuthToken";
import AuthToken from "../models/AuthToken.js";
export default class CreateAuthTokensTable extends Migration {
public async install(connection: Connection): Promise<void> {
public async install(): Promise<void> {
await this.query(`CREATE TABLE auth_tokens
(
id INT NOT NULL AUTO_INCREMENT,
@ -14,11 +14,11 @@ export default class CreateAuthTokensTable extends Migration {
used_at DATETIME NOT NULL DEFAULT NOW(),
ttl INT UNSIGNED NOT NULL,
PRIMARY KEY (id)
)`, connection);
)`);
}
public async rollback(connection: Connection): Promise<void> {
await this.query(`DROP TABLE IF EXISTS auth_tokens`, connection);
public async rollback(): Promise<void> {
await this.query(`DROP TABLE IF EXISTS auth_tokens`);
}
public registerModels(): void {

View File

@ -1,10 +1,10 @@
import {Connection} from "mysql";
import Migration from "swaf/db/Migration";
import ModelFactory from "swaf/db/ModelFactory";
import FileModel from "../models/FileModel";
import FileModel from "../models/FileModel.js";
export default class CreateFilesTable extends Migration {
public async install(connection: Connection): Promise<void> {
public async install(): Promise<void> {
await this.query(`CREATE TABLE files
(
id INT NOT NULL AUTO_INCREMENT,
@ -17,11 +17,11 @@ export default class CreateFilesTable extends Migration {
created_at DATETIME NOT NULL DEFAULT NOW(),
ttl INT UNSIGNED NOT NULL,
PRIMARY KEY (id)
)`, connection);
)`);
}
public async rollback(connection: Connection): Promise<void> {
await this.query(`DROP TABLE IF EXISTS files`, connection);
public async rollback(): Promise<void> {
await this.query(`DROP TABLE IF EXISTS files`);
}
public registerModels(): void {

View File

@ -1,10 +1,10 @@
import Migration from "swaf/db/Migration";
import {Connection} from "mysql";
import ModelFactory from "swaf/db/ModelFactory";
import URLRedirect from "../models/URLRedirect";
import URLRedirect from "../models/URLRedirect.js";
export default class CreateUrlRedirectsTable extends Migration {
public async install(connection: Connection): Promise<void> {
public async install(): Promise<void> {
await this.query(`CREATE TABLE url_redirects
(
id INT NOT NULL AUTO_INCREMENT,
@ -13,11 +13,11 @@ export default class CreateUrlRedirectsTable extends Migration {
target_url VARCHAR(1745) NOT NULL,
created_at DATETIME NOT NULL DEFAULT NOW(),
PRIMARY KEY (id)
)`, connection);
)`);
}
public async rollback(connection: Connection): Promise<void> {
await this.query(`DROP TABLE IF EXISTS url_redirects`, connection);
public async rollback(): Promise<void> {
await this.query(`DROP TABLE IF EXISTS url_redirects`);
}
public registerModels(): void {

View File

@ -1,12 +1,11 @@
import Migration from "swaf/db/Migration";
import {Connection} from "mysql";
export default class IncreaseFilesSizeField extends Migration {
public async install(connection: Connection): Promise<void> {
await this.query(`ALTER TABLE files MODIFY size BIGINT UNSIGNED`, connection);
public async install(): Promise<void> {
await this.query(`ALTER TABLE files MODIFY size BIGINT UNSIGNED`);
}
public async rollback(connection: Connection): Promise<void> {
await this.query(`ALTER TABLE files MODIFY size INT UNSIGNED`, connection);
public async rollback(): Promise<void> {
await this.query(`ALTER TABLE files MODIFY size INT UNSIGNED`);
}
}

View File

@ -0,0 +1,45 @@
import Migration from "swaf/db/Migration";
import FileModel from "../models/FileModel.js";
export default class ReplaceTtlWithExpiresAtFilesTable extends Migration {
public async install(): Promise<void> {
await this.query(`ALTER TABLE files
ADD COLUMN expires_at DATETIME NULL`);
const files = await FileModel.select().get();
for (const file of files) {
if (file.created_at && typeof file.ttl === 'number' && file.ttl > 0) {
file.expires_at = new Date(file.created_at.getTime() + file.ttl * 1000);
}
const callbacks: (() => Promise<void>)[] = [];
await file.save(this.getCurrentConnection(), callback => {
callbacks.push(callback);
});
for (const c of callbacks) await c();
}
await this.query(`ALTER TABLE files
DROP COLUMN ttl`);
}
public async rollback(): Promise<void> {
await this.query(`ALTER TABLE files
ADD COLUMN ttl INT UNSIGNED NOT NULL DEFAULT 0`);
const files = await FileModel.select().get();
for (const file of files) {
if (file.created_at && file.expires_at) {
file.ttl = Math.ceil((file.expires_at.getTime() - file.created_at.getTime()) / 1000);
}
const callbacks: (() => Promise<void>)[] = [];
await file.save(this.getCurrentConnection(), callback => {
callbacks.push(callback);
});
for (const c of callbacks) await c();
}
await this.query(`ALTER TABLE files
DROP COLUMN expires_at`);
}
}

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 User from "swaf/auth/models/User";
import {cryptoRandomDictionary} from "swaf/Utils";
import Model from "swaf/db/Model";
import {ModelQueryResult} from "swaf/db/ModelQuery";
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;
protected readonly user_id?: number = undefined;
private secret?: string = undefined;
protected created_at?: Date = undefined;
protected used_at?: Date = undefined;
public created_at?: Date = undefined;
public used_at?: Date = undefined;
protected readonly ttl?: number = undefined;
protected init(): void {
@ -19,12 +31,13 @@ export default class AuthToken extends Model implements AuthProof<User> {
protected async autoFill(): Promise<void> {
if (!this.secret) {
this.secret = cryptoRandomDictionary(64, 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_');
this.secret = nanoid(64);
}
}
public use(): void {
public async use(): Promise<void> {
this.used_at = new Date();
await this.save();
}
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 User from "swaf/auth/models/User";
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 {
public static get table(): string {
@ -14,7 +16,9 @@ export default class FileModel extends Model {
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.sortDirection = 'DESC';
return await this.paginate(req, perPage, this.select().where('user_id', user_id));
}
@ -26,33 +30,32 @@ export default class FileModel extends Model {
public readonly storage_path?: string = undefined;
public readonly size?: number = undefined;
public created_at?: Date = undefined;
public readonly ttl?: number = undefined;
public expires_at?: Date | null = undefined;
/**
* @deprecated
*/
public ttl?: number = undefined;
protected init(): void {
this.setValidation('user_id').defined().exists(User, 'id');
this.setValidation('slug').defined().minLength(1).maxLength(259).unique(FileModel, 'slug').unique(URLRedirect, 'slug');
this.setValidation('slug').defined().minLength(1).maxLength(259)
.unique(this, 'slug')
.unique(URLRedirect, 'slug');
this.setValidation('real_name').defined().minLength(1).maxLength(259);
this.setValidation('storage_type').defined().maxLength(64);
this.setValidation('storage_path').defined().maxLength(1745);
this.setValidation('size').defined().min(0);
this.setValidation('ttl').defined().min(0).max(4294967295);
}
public getURL(domain: string = config.get<string>('base_url')): string {
return (/^https?:\/\//.test(domain) ? '' : 'https://') + domain + Controller.route('get-file', {
public getURL(domain: string = config.get<string>('public_url')): string {
return (/^https?:\/\//.test(domain) ? '' : 'https://') + domain + route('get-file', {
slug: this.getOrFail('slug'),
});
}
public getExpirationDate(): Date | null {
if (!this.created_at) return new Date();
if (this.ttl === 0) return null;
return new Date(this.created_at.getTime() + this.getOrFail('ttl') * 1000);
}
public shouldBeDeleted(): boolean {
const expirationDate = this.getExpirationDate();
const expirationDate = this.expires_at;
if (!expirationDate) return false;
return new Date().getTime() >= expirationDate.getTime();
}

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 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 {
public static get table(): string {
@ -14,7 +16,13 @@ export default class URLRedirect extends Model {
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.sortDirection = 'DESC';
return await this.paginate(req, perPage, this.select().where('user_id', user_id));
}
@ -26,12 +34,14 @@ export default class URLRedirect extends Model {
protected init(): void {
this.setValidation('user_id').defined().exists(User, 'id');
this.setValidation('slug').defined().minLength(1).maxLength(259).unique(URLRedirect, 'slug').unique(FileModel, 'slug');
this.setValidation('slug').defined().minLength(1).maxLength(259)
.unique(this, 'slug')
.unique(FileModel, 'slug');
this.setValidation('target_url').defined().maxLength(1745).regexp(/^https?:\/\/.{3,259}?\/?/i);
}
public getURL(domain: string = config.get<string>('base_url')): string {
return (/^https?:\/\//.test(domain) ? '' : 'https://') + domain + Controller.route('get-url', {
public getURL(domain: string = config.get<string>('public_url')): string {
return (/^https?:\/\//.test(domain) ? '' : 'https://') + domain + route('get-url', {
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,18 +0,0 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "public/js",
"target": "ES6",
"strict": true,
"lib": [
"es2020",
"DOM"
],
"typeRoots": [
"./node_modules/@types"
]
},
"include": [
"assets/ts/**/*"
]
}

View File

@ -1,22 +1,43 @@
{
"compilerOptions": {
"module": "CommonJS",
"esModuleInterop": true,
"outDir": "dist",
"target": "ES6",
"target": "ESNext",
"module": "ESNext",
"declaration": true,
"stripInternal": 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": [
"es2020",
"DOM"
],
"typeRoots": [
"./node_modules/@types"
"dom"
],
"resolveJsonModule": true,
"skipLibCheck": true
"skipLibCheck": true,
"allowJs": true
},
"include": [
"src/**/*",
"node_modules/swaf/types"
"include": [],
"references": [
{
"path": "src",
},
{
"path": "src/assets/ts",
},
{
"path": "src/assets/views",
}
]
}

View File

@ -11,4 +11,4 @@
"src/types/**/*",
"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,56 +0,0 @@
{% extends 'layouts/base.njk' %}
{% set title = app.name + ' - File manager' %}
{% block scripts %}
<script src="/js/fm.js"></script>
{% endblock %}
{% block body %}
<h1>File manager</h1>
<p>You're their manager, please be nice with them.</p>
<section class="panel">
<h2>File list</h2>
<table class="data-table">
<thead>
<tr>
<th>#</th>
<th>URL</th>
<th>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>
<div class="copyable-text">
<a class="content" href="{{ file.getURL() }}" target="_blank">{{ file.getURL() }}</a>
<button class="copy-button"><i data-feather="copy"></i></button>
</div>
</td>
<td>{{ file.real_name }}</td>
<td>{{ (file.size / (1024 * 1024)).toFixed(2) }}MB</td>
{% set expires_at = file.getExpirationDate() %}
<td>{% if expires_at %}{{ expires_at.toISOString() }}{% else %}Never{% endif %}</td>
<td>
{% if file.shouldBeDeleted() %}
Pending deletion
{% else %}
<form action="{{ route('delete-file-frontend', file.slug) }}" method="post">
{{ macros.csrf(getCsrfToken) }}
<button class="button danger"><i data-feather="trash"></i> Delete</button>
</form>
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</section>
{% endblock %}

View File

@ -1,56 +0,0 @@
{% extends 'layouts/base.njk' %}
{% set title = app.name + ' - File upload' %}
{% block scripts %}
<script src="/js/fm.js"></script>
{% endblock %}
{% block body %}
<h1>Upload files</h1>
<p>(except illegal ones)</p>
<div class="container">
<section class="panel">
<h2>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, 'number', 'expire_after_days', '30', 'How many days to delete this file after', null, validation_attributes='max="1825"') }}
{{ macros.field(_locals, 'checkbox', 'never_expire', '', 'Never delete this file') }}
{{ 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.field(_locals, 'checkbox', 'autogen_url', '', 'Generate url automatically', null, validation_attributes='checked') }}
{{ 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>
</div>
{% include 'desktop-utility.njk' %}
{% endblock %}

View File

@ -1,59 +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-manager') }}"><i data-feather="folder"></i> <span class="tip">File manager</span></a></li>
<li><a href="{{ route('file-upload') }}"><i data-feather="upload"></i> <span class="tip">Upload file</span></a></li>
<li><a href="{{ route('url-manager') }}"><i data-feather="link"></i> <span class="tip">URL manager</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>
<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>
{% 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,38 +0,0 @@
{% extends 'layouts/base.njk' %}
{% set title = app.name + ' - URL manager' %}
{% block scripts %}{% endblock %}
{% block body %}
<h1>URL manager</h1>
<p>These are permanent.</p>
<section class="panel">
<h2>URL list</h2>
<table class="data-table">
<thead>
<tr>
<th>#</th>
<th>URL</th>
<th>Target</th>
</tr>
</thead>
<tbody>
{% for url in urls %}
<tr>
<td>{{ url.id }}</td>
<td>
<div class="copyable-text">
<a class="content" href="{{ url.getURL() }}" target="_blank">{{ url.getURL() }}</a>
<button class="copy-button"><i data-feather="copy"></i></button>
</div>
</td>
<td>{{ url.target_url }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</section>
{% endblock %}

View File

@ -1,40 +0,0 @@
{% extends 'layouts/base.njk' %}
{% set title = app.name + ' - URL shrinker' %}
{% block scripts %}
<script src="/js/url-shrinker.js"></script>
{% endblock %}
{% block body %}
<h1>Shrink URLs</h1>
<p>(no phishing allowed)</p>
<div class="container">
<section class="panel">
<h2>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, 'text', 'slug', '', 'Custom url slug', 'Example: bear sets url to https://'+default_domain+'/bear', validation_attributes='disabled') }}
{{ macros.field(_locals, 'checkbox', 'autogen_url', '', 'Generate url automatically', null, validation_attributes='checked') }}
{{ 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>
</div>
{% include 'desktop-utility.njk' %}
{% 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;

9587
yarn.lock

File diff suppressed because it is too large Load Diff