Compare commits

...

163 Commits

Author SHA1 Message Date
Alice Gaudon af72cb6799 Version 1.1.0 2022-03-07 19:14:37 +01:00
Alice Gaudon 47f0a45cb1 install dependencies 2022-03-07 19:09:37 +01:00
Alice Gaudon 0a0a8a8952 Merge remote-tracking branch 'boilerplate/develop' into develop
# Conflicts:
#	package.json
2022-03-07 19:07:15 +01:00
Alice Gaudon a5b7cf9268 upgrade dependencies 2022-03-07 19:04:29 +01:00
Alice Gaudon 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
Alice Gaudon f54438e9dd chore(front/NavMenu): move Auth Tokens link to new Account dropdown from swaf 2022-03-06 18:34:55 +01:00
Alice Gaudon 848c952073 fix(back/AuthTokenController): fix auth tokens pagination size 2022-03-06 18:34:03 +01:00
Alice Gaudon e3f7b5e7c7 feat(front/auth-token): make token revoke action button mode to gain space 2022-03-06 18:33:41 +01:00
Alice Gaudon 8ddcd50c35 feat(front/auth-token): use better icon for new token generation button 2022-03-06 18:33:36 +01:00
Alice Gaudon 8d13bd0c8d chore(back/AuthToken): update to new AuthProof use method from swaf 2022-03-06 16:39:27 +01:00
Alice Gaudon c54a201e98 chore(front): convert auth-tokens to svelte 2022-03-06 13:17:02 +01:00
Alice Gaudon 3abd692ce3 feat(front): improve about page, remove redundant link from nav menu 2022-03-06 12:24:50 +01:00
Alice Gaudon eaac5f3ace chore(front): remove old asset files 2022-03-05 10:13:12 +01:00
Alice Gaudon 5cb13c221d feat(front/url-shrinker): update url-shrinker icon to shrink 2022-03-05 10:12:49 +01:00
Alice Gaudon 7c65f1b6ae chore(front/url-shrinker): convert url-shrinker to svelte 2022-03-05 10:12:26 +01:00
Alice Gaudon c025aa2539 chore(front/file-uploader): remove unnecessary css, container, update col-grow class names 2022-03-05 10:11:19 +01:00
Alice Gaudon 1b5e088d74 chore(front/global css): remove old scss files and add new and updated _vars.scss 2022-03-05 09:08:53 +01:00
Alice Gaudon 53c7423115 fix(front/file-uploader): remove unnecessary data-table-container usage 2022-03-05 09:08:14 +01:00
Alice Gaudon c2182dbbca chore(back/scripts): move linux scripts to new assets folder 2022-03-05 09:06:58 +01:00
Alice Gaudon 27f760d503 feat(front/file-uploader): make copy button in file list work again 2022-03-02 11:37:02 +01:00
Alice Gaudon a8f82564a5 feat(front/file-uploader): display human readable time in file list 2022-03-02 11:22:29 +01:00
Alice Gaudon 9807158bb9 feat(front/file-uploader): improve file list table density and looks 2022-03-02 11:16:37 +01:00
Alice Gaudon 11fccbfc0d fix sass->scss asset dir name 2022-03-02 11:11:57 +01:00
Alice Gaudon 15441a0941 feat(front/FileUpload): display errors and allow retrying or canceling the upload 2022-03-02 11:10:58 +01:00
Alice Gaudon 7ad0eac6db feat(front/file-uploader): reduce page height changes/unnecessary visual changes, improve ux 2022-03-02 11:09:55 +01:00
Alice Gaudon c906827fe1 fix(front/file-uploader): do not add failed uploads to finished uploads list 2022-03-02 11:07:27 +01:00
Alice Gaudon 5477c858ef fix(front/file-uploader): prevent starting upload if another upload is running 2022-03-02 11:06:53 +01:00
Alice Gaudon 79fb4e28c8 chore(front/file-uploader): convert file-uploader view to svelte 2022-03-02 10:26:48 +01:00
Alice Gaudon e94b98aee0 Merge remote-tracking branch 'origin/develop' into develop 2022-03-01 10:50:35 +01:00
Alice Gaudon 47156c9a77 Remove feather icons in favor of lucide icons (included with swaf) 2022-03-01 10:50:14 +01:00
Alice Gaudon 79d23a4604 swaf upgrade: convert views to svelte 2022-02-19 10:17:21 +01:00
Alice Gaudon 5571737d93 swaf upgrade: fix eslint 2022-02-19 09:30:51 +01:00
Alice Gaudon 377c073cd2 swaf upgrade: move views to new assets folder 2022-02-18 20:46:50 +01:00
Alice Gaudon b1ba6b9106 swaf upgrade: make code compile 2022-02-18 20:46:34 +01:00
Alice Gaudon 69b234d95c upgrade dependencies 2022-02-18 20:35:36 +01:00
Alice Gaudon 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
Alice Gaudon 5f5275ceb1 upgrade dependencies 2021-12-24 15:20:28 +01:00
Alice Gaudon eb0364a2f7 Fix eslint and fix linting issues 2021-11-21 17:52:56 +01:00
Alice Gaudon f2f34dd00f Update eslint config with swaf 2021-11-21 17:44:12 +01:00
Alice Gaudon 8c1230d501 Remove reference to deleted tsconfig.frontend.json from eslint config 2021-11-21 17:41:48 +01:00
Alice Gaudon 6002ad5290 Remove webpack and unused dependencies 2021-11-21 17:07:31 +01:00
Alice Gaudon 257a407faf Remove unused old assets 2021-11-21 16:58:59 +01:00
Alice Gaudon 569a50e43a Upgrade swaf and dependencies 2021-11-20 19:54:59 +01:00
Alice Gaudon 938e8b4ebb Add imagemin-webp 2021-06-07 11:24:52 +02:00
Alice Gaudon 7e260ebde2 Upgrade dependencies, replace img-loader with image-minimizer-webpack-plugin 2021-06-07 11:21:43 +02:00
Alice Gaudon efbc895ba3 Bump @types/node 2021-04-30 11:55:59 +02:00
Alice Gaudon 2cb5b6f8f9 Replace node-sass with sass 2021-04-30 11:55:59 +02:00
Alice Gaudon 3b833e013b Version 1.0.3 2021-04-22 20:15:51 +02:00
Alice Gaudon d5aa2c70db File upload list: hide size and expires at columns on mobile 2021-04-22 20:14:53 +02:00
Alice Gaudon 4573846c7b Prevent shrunk url list from overflowing 2021-04-22 20:05:24 +02:00
Alice Gaudon 75650bf23f Restore default table cell behavior for actions and table-col-grow-cell 2021-04-22 20:04:48 +02:00
Alice Gaudon 53c5763909 Add user confirmation dialog on delete file button 2021-04-22 19:48:55 +02:00
Alice Gaudon 51da9f4c7c Prevent upload list from overflowing and add standalone copy text button 2021-04-22 19:25:20 +02:00
Alice Gaudon 3e5f245121 Put checkboxes before their field in file upload and url shrink forms 2021-04-22 18:35:36 +02:00
Alice Gaudon 30960e42c5 Add default text row in file upload list and shrunk url list 2021-04-22 18:34:53 +02:00
Alice Gaudon 03989be9ab Upgrade dependencies 2021-04-22 18:25:43 +02:00
Alice Gaudon bc5fda7d16 Merge branch 'boilerplate' into develop 2021-04-22 14:24:20 +02:00
Alice Gaudon f5d135d331 Merge branch 'develop' 2021-04-22 14:21:08 +02:00
Alice Gaudon 82439366ba Fix imagemin peer dependency of img-loader 2021-04-22 14:06:53 +02:00
Alice Gaudon 162f884103 Upgrade dependencies 2021-04-22 12:34:20 +02:00
Alice Gaudon 00bb24cf2e Update repository url 2021-04-22 12:30:40 +02:00
Alice Gaudon 459c83b47d Version 1.0.2 2021-03-30 17:27:19 +02:00
Alice Gaudon 349a8b65de Fix file uploading not working (ttl doesn't exist anymore) 2021-03-30 17:27:04 +02:00
Alice Gaudon 8555a35970 Version 1.0.1 2021-03-30 17:03:24 +02:00
Alice Gaudon 9ef3a07f5f Merge branch 'boilerplate' into develop 2021-03-30 17:01:59 +02:00
Alice Gaudon 4bcee79e8a Merge branch 'develop' 2021-03-30 16:56:44 +02:00
Alice Gaudon d223c9c77f Update config to new swaf version 2021-03-30 16:56:35 +02:00
Alice Gaudon 0b07ff68d9 Remove forgotten debug log 2021-03-30 16:46:41 +02:00
Alice Gaudon e2c1d17f75 Version 1.0.0 2021-03-30 16:36:14 +02:00
Alice Gaudon 1dcbb6b414 Add old file deletion daily job 2021-03-30 16:31:23 +02:00
Alice Gaudon c8d7c664e2 files: replace ttl with expires_at 2021-03-30 16:22:46 +02:00
Alice Gaudon faa728aacb layout.scss: allow .form-field to be hidden with .hidden 2021-03-30 14:36:06 +02:00
Alice Gaudon 33947012e4 urls and files: hide custom slug field when generating automatically 2021-03-30 14:32:40 +02:00
Alice Gaudon 1e00834324 File uploader: change subtitle to a better disclaimer 2021-03-30 14:30:46 +02:00
Alice Gaudon fe60a611b6 layout.scss: allow .form-field to be hidden with .hidden 2021-03-30 14:27:03 +02:00
Alice Gaudon 6e92eb2740 Simplify menu auth-tokens display text 2021-03-30 14:12:42 +02:00
Alice Gaudon 84b0ed9d88 Merge branch 'boilerplate' into develop 2021-03-30 12:46:05 +02:00
Alice Gaudon 00b1f25804 Merge branch 'develop' 2021-03-30 12:45:12 +02:00
Alice Gaudon 12f82f0f3d package.json: use NodeJS scripts instead of unix commands 2021-03-30 12:44:09 +02:00
Alice Gaudon ceaa0769bc Upgrade dependencies 2021-03-30 12:39:40 +02:00
Alice Gaudon 0f83dd7ad6 layout.scss: add pagination default style 2021-03-30 12:34:24 +02:00
Alice Gaudon f853be6fb9 layout.scss: add pagination default style 2021-03-30 12:32:41 +02:00
Alice Gaudon 0de960a168 urls & files: set page size to 25, add page nav and sort by create desc 2021-03-30 12:32:21 +02:00
Alice Gaudon 0dfae21005 Move auth tokens to dedicated page 2021-03-30 12:19:56 +02:00
Alice Gaudon a5729af3c1 Merge file/url creating form and manager 2021-03-30 12:19:56 +02:00
Alice Gaudon a2a9d20994 Remove old domain gris.li from default production config 2021-03-30 12:19:56 +02:00
Alice Gaudon 42c705ac6b Upgrade dependencies 2021-03-30 12:19:53 +02:00
Alice Gaudon ecd18cabe2 Version 0.6.0 2021-01-26 14:38:52 +01:00
Alice Gaudon 959e5ca276 Remove duplicate definition of .copyable-text and improve table layout 2021-01-26 14:30:46 +01:00
Alice Gaudon 7d6242861e frontend: make use of new width space and use more icons 2021-01-26 14:29:29 +01:00
Alice Gaudon 8b42d83edf Remove duplicate definition of .copyable-text and improve table layout 2021-01-26 14:28:53 +01:00
Alice Gaudon a8954fbf22 Update config parameter base_url -> public_url 2021-01-26 14:27:55 +01:00
Alice Gaudon 42c49974ea frontend: reorganize menu with dropdowns 2021-01-26 14:27:26 +01:00
Alice Gaudon 4b7d33d9d3 Merge branch 'boilerplate' into develop 2021-01-26 13:38:21 +01:00
Alice Gaudon 1cdd118806 Merge branch 'develop' 2021-01-26 13:37:58 +01:00
Alice Gaudon 145d8df70a css: move menu .tip visibility to layout.scss 2021-01-26 13:37:41 +01:00
Alice Gaudon 6723cdb1ee Merge branch 'boilerplate' into develop 2021-01-26 13:18:11 +01:00
Alice Gaudon 2726fd16cc Merge branch 'develop' 2021-01-26 13:17:51 +01:00
Alice Gaudon 8612b0f33a css: move lighter theme to layout.scss and make header css mobile first 2021-01-26 13:00:38 +01:00
Alice Gaudon bda464ab16 css: move a hover color and td.actions improvements to layout.scss 2021-01-26 13:00:23 +01:00
Alice Gaudon e7165edafd Add hover color on warning buttons 2021-01-26 11:43:42 +01:00
Alice Gaudon 16394c0d4c Set icon size for titles 2021-01-26 11:43:13 +01:00
Alice Gaudon d2a67a12ee Fix subpanel leaking out of their container 2021-01-26 11:42:24 +01:00
Alice Gaudon 1043690a5d Add bigger container max-width for desktop view 2021-01-26 11:38:26 +01:00
Alice Gaudon d6f4d612fe Update to swaf 0.23.4 2021-01-25 17:56:56 +01:00
Alice Gaudon c6b4c2dfe3 Install and upgrade dependencies 2021-01-25 13:28:45 +01:00
Alice Gaudon f5ccab3b34 Merge remote-tracking branch 'boilerplate/master' into develop 2021-01-25 13:26:58 +01:00
Alice Gaudon 46168c0e90 Merge branch 'develop' 2021-01-25 13:20:25 +01:00
Alice Gaudon 5eaebd5d12 Upgrade dependencies and bump swaf to ^0.23.0 2021-01-25 13:18:49 +01:00
Alice Gaudon ff1f3d6f19 .gitignore: add config/local.* 2021-01-25 11:55:41 +01:00
Alice Gaudon 2290170569 Add maildev as a dev dependency 2021-01-25 11:45:00 +01:00
Alice Gaudon 9f3a541c3e Add maildev as a dev dependency 2021-01-25 11:44:22 +01:00
Alice Gaudon 93ac2f151d Version 0.5.5 2020-11-27 15:29:13 +01:00
Alice Gaudon 892cf26628 Fix api authentication 2020-11-27 15:28:28 +01:00
Alice Gaudon 13abf62368 Add FixUserMainEmailRelation migration 2020-11-27 15:12:00 +01:00
Alice Gaudon 9d6d8e8463 Version 0.5.4 2020-11-22 15:20:14 +01:00
Alice Gaudon f605474182 Update views 2020-11-22 15:19:58 +01:00
Alice Gaudon 456b3a3170 Fix configuration 2020-11-22 15:19:47 +01:00
Alice Gaudon aa8735cf23 Convert frontend js to ts 2020-11-22 14:57:25 +01:00
Alice Gaudon 83ab56b4ac Fix linting errors 2020-11-22 14:13:57 +01:00
Alice Gaudon 5e7d29ab98 Fix configuration files 2020-11-22 14:06:56 +01:00
Alice Gaudon 767a9e0641 Temporary skip lib check pending swaf update 2020-11-22 13:49:51 +01:00
Alice Gaudon 21bd0a42d0 Swaf upgrade: fix compilation errors 2020-11-22 13:49:08 +01:00
Alice Gaudon 973110f1a4 Update repository url 2020-11-22 13:03:45 +01:00
Alice Gaudon 6851c889bf Upgrade dependencies 2020-11-22 13:03:11 +01:00
Alice Gaudon 16e24b6373 Merge remote-tracking branch 'boilerplate/develop' into develop 2020-11-22 13:02:05 +01:00
Alice Gaudon 14d8261da0 Upgrade dependencies 2020-11-22 12:55:37 +01:00
Alice Gaudon 5f59800229 Make express download fallback max size configurable 2020-11-22 12:52:01 +01:00
Alice Gaudon ba5b90a4f9 swaf rename: rename project to swaf-boilerplate 2020-11-13 10:54:35 +01:00
Alice Gaudon f16d63c74f frontend: refactor $mobileThreshold and container media queries 2020-11-03 20:29:57 +01:00
Alice Gaudon 04f19f5a28 Fix yarn dev script 2020-11-03 17:26:32 +01:00
Alice Gaudon a4df579937 Rename "dist" task to more relevant "build" 2020-11-03 10:44:25 +01:00
Alice Gaudon 9e07d4bff4 config: remove insecure default values 2020-11-02 18:37:39 +01:00
Alice Gaudon 292e843cd1 Upgrade packages i.e. wms-core 2020-11-02 18:17:55 +01:00
Alice Gaudon a8bad1c8c1 Upgrade wms-core and add eslint 2020-10-05 13:38:03 +02:00
Alice Gaudon d91110fb67 Drop UglifyJS webpack plugin in favor of Terser 2020-10-01 14:38:16 +02:00
Alice Gaudon dcdc8dd704 Convert frontend js to typescript 2020-09-23 13:30:48 +02:00
Alice Gaudon 5f2215f491 Prevent tooltips and dropdowns from overflowing on y axis 2020-09-16 12:41:18 +02:00
Alice Gaudon a3a19da038 Fix inline controls styling 2020-09-15 16:34:28 +02:00
Alice Gaudon 7664d36848 Force .feather icon vertical alignment 2020-09-15 16:34:21 +02:00
Alice Gaudon a92b657e4a forms: make value property update a function and update textareas too 2020-09-15 16:33:02 +02:00
Alice Gaudon ab8e756034 Make sure textareas have the right font 2020-09-10 21:02:39 +02:00
Alice Gaudon 16895e52e8 Fix input hint and errors display 2020-09-10 16:19:01 +02:00
Alice Gaudon f70112e956 Add optional input field illustration feather icon 2020-09-10 16:18:52 +02:00
Alice Gaudon c68d5819b1 Allow links that are target=_blank to opt-out from the icon 2020-09-05 17:36:20 +02:00
Alice Gaudon 3598f68183 Add font-awesome 2020-09-05 17:36:08 +02:00
Alice Gaudon 3b124a993b main.ts: fix config path order 2020-09-03 12:59:16 +02:00
Alice Gaudon 5157b12b77 tsconfig.json: restore wms-core/types include and add test 2020-09-03 11:46:00 +02:00
Alice Gaudon bce48f81b6 package.json: upgrade dependencies and move wms-core to regular deps 2020-09-03 08:30:15 +02:00
Alice Gaudon 52929e5be0 package.json: fix repository url 2020-09-03 08:29:37 +02:00
Alice Gaudon 54faa5c873 Use config package's multi-directory built-in support
This avoids full object overriding when you just want to set specific fields
2020-09-03 08:29:14 +02:00
Alice Gaudon f45daa4a9f Improve links hover feedback 2020-09-02 20:42:19 +02:00
Alice Gaudon 61c8f32c47 Fix header z-index 2020-08-30 21:05:17 +02:00
Alice Gaudon 7143e7a843 Add textarea styling 2020-08-30 21:03:26 +02:00
Alice Gaudon 4316daf241 header: add menu dropdowns and auth-user special menu item 2020-08-30 21:03:20 +02:00
Alice Gaudon b136bdc64e Fix main header css selector and set default icon size to 16px 2020-08-30 09:34:14 +02:00
Alice Gaudon 3f3bec85fc layout.scss: fix select chevron position when field has error 2020-07-30 11:14:55 +02:00
Alice Gaudon 95f61333f6 Add basic breadcrumb style 2020-07-30 10:56:05 +02:00
Alice Gaudon 7d75df2f56 Improve tips styling and allow it in any button 2020-07-30 10:56:02 +02:00
Alice Gaudon 3b94b9818c Fix .inline-fields alignment 2020-07-27 17:30:54 +02:00
Alice Gaudon ffe92674e5 Improve panels design 2020-07-27 16:03:30 +02:00
Alice Gaudon 44b32401a7 Merge branch 'develop' 2020-07-16 09:25:10 +02:00
Alice Gaudon c87eec28b2 Make icon only menu layout default 2020-07-15 11:04:45 +02:00
86 changed files with 6268 additions and 8400 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');
}
},
}

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 +1,3 @@
# ily.li is a simple file self-hosting solution
Boilerplate for a quickstart with [swaf](https://eternae.ink/arisu/swaf)

View File

@ -1,3 +1,6 @@
# Please customize values i.e. paths, user, group, WorkingDirectory based on your environment. Do not use the same
# user and group for different applications.
[Unit]
Description=ily.li website
After=network-online.target

View File

@ -1,12 +0,0 @@
{
"bundles": {
"app": "js/app.js",
"fm": "js/fm.js",
"url-shrinker": "js/url-shrinker.js",
"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,9 +0,0 @@
import './external_links';
import './message_icons';
import './forms';
import './copyable_text';
import './main_menu';
import '../sass/app.scss';
console.log('Hello world!');

View File

@ -1,12 +0,0 @@
document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('.copyable-text').forEach(el => {
const contentEl = el.querySelector('.content');
contentEl.addEventListener('click', () => {
window.getSelection().selectAllChildren(contentEl);
});
el.querySelector('.copy-button').addEventListener('click', () => {
window.getSelection().selectAllChildren(contentEl);
document.execCommand('copy');
});
});
});

View File

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

View File

@ -1,131 +0,0 @@
document.addEventListener('DOMContentLoaded', () => {
const form = document.getElementById('upload-form');
if (!form) return;
const upload = document.getElementById('file-upload');
const uploadLink = document.getElementById('file-upload-link');
const uploadField = document.getElementById('field-upload');
const neverExpireCheckbox = document.getElementById('field-never_expire');
const expireAfterDaysField = document.getElementById('field-expire_after_days');
const autogenUrlCheckbox = document.getElementById('field-autogen_url');
const slugField = document.getElementById('field-slug');
neverExpireCheckbox.addEventListener('change', () => {
expireAfterDaysField.disabled = neverExpireCheckbox.checked;
});
autogenUrlCheckbox.addEventListener('change', () => {
slugField.disabled = autogenUrlCheckbox.checked;
});
let uploadForm;
form.addEventListener('submit', e => {
e.preventDefault();
if (!uploadForm || uploadForm.isFinished()) {
uploadForm = new UploadForm(form, upload, uploadLink, uploadField.files[0].name);
uploadForm.updateView();
uploadForm.start();
}
});
});
function UploadForm(form, upload, uploadLink, fileName) {
this.form = form;
this.upload = upload;
this.uploadLink = uploadLink;
this.fileName = fileName;
this.progressBar = this.upload.querySelector('.progress-bar');
this.progressBarContent = this.progressBar.querySelector('.content');
this.status = this.upload.querySelector('.status');
this.speed = this.status.querySelector('.speed');
this.finished = false;
this.xferSpeed = [];
this.lastTransferTime = null;
this.xhr = new XMLHttpRequest();
this.xhr.responseType = 'json';
this.xhr.upload.addEventListener('progress', e => {
if (e.lengthComputable) {
this.progressBar.classList.remove('undefined');
let percent = ((e.loaded / e.total) * 100).toFixed(2) + '%';
this.progressBar.style = `--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;
let response = this.xhr.response;
console.log('done', response);
if (response.status === 'error') {
if (response.messages) {
this.restoreView();
window.applyFormMessages(this.form, response.messages);
}
} else if (response.url) {
this.status.innerHTML = 'Done!';
this.uploadLink.querySelector('.content').innerText = response.url;
this.uploadLink.classList.remove('hidden');
} else {
window.location.reload();
}
});
this.xhr.addEventListener('error', (e) => {
this.finished = true;
console.error('error', e);
this.status.innerHTML = 'Error; upload was interrupted.';
});
}
UploadForm.prototype.isFinished = function () {
return this.finished;
}
UploadForm.prototype.updateView = function () {
this.upload.querySelector('.name').innerText = this.fileName;
this.form.classList.add('hidden');
this.upload.classList.remove('hidden');
this.status.innerHTML = `Uploading @ <span class="speed">--</span>`;
this.speed = this.status.querySelector('.speed');
}
UploadForm.prototype.restoreView = function () {
this.status.classList.add('hidden');
this.upload.classList.add('hidden');
this.form.classList.remove('hidden');
};
UploadForm.prototype.start = function () {
const formData = new FormData(this.form);
this.xhr.open('POST', this.form.action);
this.xhr.send(formData);
}
const units = ['K', 'M', 'G', 'T'];
UploadForm.prototype.updateSpeed = function (loaded) {
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++;
}
this.speed.innerText = (speed).toFixed(2) + units[unit] + 'Bps';
}
this.lastTransferTime = time;
this.lastLoaded = loaded;
}

View File

@ -1,29 +0,0 @@
// For labels to update their state (css selectors based on the value attribute)
document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('input').forEach(el => {
if (el.type !== 'checkbox') {
el.setAttribute('value', el.value);
el.addEventListener('change', () => {
el.setAttribute('value', el.value);
});
}
});
});
window.applyFormMessages = function (formElement, messages) {
for (const fieldName of Object.keys(messages)) {
const field = formElement.querySelector('#field-' + fieldName);
let parent = field.parentElement;
while (parent && !parent.classList.contains('form-field')) parent = parent.parentElement;
if (field) {
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,17 +0,0 @@
document.addEventListener('DOMContentLoaded', () => {
const menuButton = document.getElementById('menu-button');
const mainMenu = document.getElementById('main-menu');
menuButton.addEventListener('click', (e) => {
e.stopPropagation();
mainMenu.classList.toggle('open');
});
mainMenu.addEventListener('click', (e) => {
e.stopPropagation();
});
document.addEventListener('click', () => {
mainMenu.classList.remove('open');
});
});

View File

@ -1,21 +0,0 @@
import feather from "feather-icons";
document.addEventListener('DOMContentLoaded', () => {
const messageTypeToIcon = {
info: 'info',
success: 'check',
warning: 'alert-triangle',
error: 'x-circle',
question: 'help-circle',
};
document.querySelectorAll('.message').forEach(el => {
const type = el.dataset['type'];
const icon = el.querySelector('.icon');
const svgContainer = document.createElement('div');
svgContainer.innerHTML = feather.icons[messageTypeToIcon[type]].toSvg();
el.insertBefore(svgContainer.firstChild, icon);
icon.remove();
});
feather.replace();
});

View File

@ -1,11 +0,0 @@
document.addEventListener('DOMContentLoaded', () => {
const form = document.getElementById('url-shrink-form');
if (!form) return;
const autogenUrlCheckbox = document.getElementById('field-autogen_url');
const slugField = document.getElementById('field-slug');
autogenUrlCheckbox.addEventListener('change', () => {
slugField.disabled = autogenUrlCheckbox.checked;
});
});

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,30 +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%);
$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
$menuLayoutSwitchTreshold: 700px;

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,749 +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;
}
header {
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 {
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);
}
.tip {
visibility: visible;
opacity: 1;
transition: opacity ease-out 100ms;
transition-delay: 150ms;
}
}
.feather {
--icon-size: 24px;
}
}
button {
margin: 8px;
padding: 24px;
height: 32px;
.feather {
margin-right: 0;
}
.tip {
text-transform: initial;
font-weight: initial;
}
}
form {
display: flex;
justify-content: center;
align-items: center;
padding: 0;
}
}
}
#menu-button {
display: none;
}
}
@media (max-width: $menuLayoutSwitchTreshold) {
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;
}
}
}
}
}
}
@media (min-width: $menuLayoutSwitchTreshold) {
nav ul li {
a, button {
.tip {
visibility: hidden;
position: absolute;
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;
}
}
&:last-child {
a, 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;
}
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: 16px;
&::before, &::after {
content: "";
flex: 1;
margin: 0 32px;
height: 0;
border-bottom: 1px solid $defaultTextColor;
opacity: 0.2;
}
}
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, 5%);
}
.feather.feather-external-link {
--icon-size: 16px;
margin-left: 4px;
margin-top: -3px;
}
}
form {
padding: 8px 16px;
text-align: center;
.form-field {
position: relative;
display: flex;
flex-direction: column;
margin: 16px auto;
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, .input-group {
border: 0;
color: $defaultTextColor;
background: lighten($panelBackground, 4%);
border-radius: 5px;
font-size: 16px;
&:focus, &:not([value=""]), &[type="file"] {
~ label {
top: 8px;
font-size: 14px;
}
}
}
input, select, .form-display {
display: block;
padding: 32px 8px 8px 8px;
width: 100%;
}
select {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
&::-ms-expand {
display: none;
}
& + .feather {
position: absolute;
z-index: -1;
right: 8px;
bottom: 8px;
transition: transform 150ms ease-out;
}
// Temporary
&:focus + .feather {
transform: rotateX(180deg);
}
}
input[type=color] {
height: calc(32px + 8px + 32px);
}
&.inline {
flex-direction: row;
input[type=checkbox] {
text-align: left;
width: min-content;
height: min-content;
& ~ label {
position: static;
display: inline;
padding-left: 8px;
font-size: 16px;
}
}
}
.input-group {
display: flex;
flex-shrink: 1;
flex-direction: row;
div {
position: relative;
flex: 1;
input {
width: 100%;
margin-top: 24px;
padding-top: 8px;
border: 0;
background: transparent;
}
> input + * {
position: absolute;
top: 32px;
right: 28px;
user-select: none;
text-align: right;
}
}
}
}
.inline-fields {
display: flex;
flex-direction: row;
align-items: center;
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;
}
}
.max-content {
width: max-content;
}
// ---
// --- Layout helpers
// ---
.center {
text-align: center;
}
.container {
padding: 0 16px;
max-width: 632px;
margin: 0 auto;
}
.panel {
margin: 16px 0;
padding: 8px;
background-color: $panelBackground;
border-radius: 5px;
p {
margin: 16px 8px;
}
}
.sub-panel {
margin: 32px -18px;
padding: 1px 16px;
border: 2px solid lighten($panelBackground, 4%);
border-radius: 5px;
}
// ---
// --- Feather
// ---
.feather {
flex-shrink: 0;
--icon-size: 24px;
width: var(--icon-size);
height: 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;
}
}

66
config/default.json5 Normal file
View File

@ -0,0 +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,
},
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,41 +0,0 @@
export default Object.assign(require("wms-core/config/default").default, {
app: {
name: 'ily.li',
contact_email: 'contact@ily.li'
},
domain: 'localhost',
base_url: 'http://localhost:4893',
public_websocket_url: 'ws://localhost:4893',
port: 4893,
mysql: {
connectionLimit: 10,
host: "localhost",
user: "root",
password: "",
database: "ilyli",
create_database_automatically: false
},
magic_link: {
validity_period: 20
},
newlyGeneratedSlugSize: 3,
default_file_ttl: 30, // 30 seconds
max_upload_size: 1, // MB
approval_mode: 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',
},
allowed_url_domains: [
'localhost:4893',
'127.0.0.1:4893',
],
default_url_domain_for_files: 0,
default_url_domain_for_urls: 1,
});

36
config/production.json5 Normal file
View File

@ -0,0 +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,
// 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,29 +0,0 @@
export default Object.assign(require("wms-core/config/production").default, {
domain: 'ily.li',
base_url: 'https://ily.li',
public_websocket_url: 'wss://ily.li',
mysql: {
connectionLimit: 10,
host: "localhost",
user: "root",
password: "",
database: "ilyli",
},
magic_link: {
validity_period: 900
},
newlyGeneratedSlugSize: 5,
default_file_ttl: 30 * 24 * 3600, // 30 days
max_upload_size: 8192, // MB
approval_mode: true,
mail: {
secure: true,
allow_invalid_tls: false
},
allowed_url_domains: [
'ily.li',
'gris.li',
],
default_url_domain_for_files: 0,
default_url_domain_for_urls: 1,
});

9
config/test.json5 Normal file
View File

@ -0,0 +1,9 @@
{
mysql: {
host: "localhost",
user: "root",
password: "",
database: "ilyli_test",
create_database_automatically: true,
},
}

View File

@ -1,9 +0,0 @@
export default Object.assign(require("wms-core/config/test").default, {
mysql: {
database: "ilyli_test",
create_database_automatically: true
},
magic_link: {
validity_period: 2
},
});

View File

@ -1,57 +1,59 @@
{
"name": "ily.li",
"version": "0.5.3",
"version": "1.1.0",
"description": "Self-hosted file pusher",
"repository": "https://gitlab.com/ArisuOngaku/ily.li",
"repository": "https://eternae.ink/ashpie/ily.li",
"author": "Alice Gaudon <alice@gaudon.pro>",
"license": "GPL-3.0-only",
"main": "dist/main.js",
"scripts": {
"test": "jest --verbose --runInBand",
"dist-webpack": "webpack --mode production",
"dist": "tsc && npm run dist-webpack",
"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 dist && node dist/main.js"
"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",
"@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/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.0.27",
"@types/node": "^17.0.4",
"@types/nodemailer": "^6.4.0",
"@types/nunjucks": "^3.1.3",
"@types/ws": "^7.2.6",
"babel-loader": "^8.1.0",
"concurrently": "^5.1.0",
"css-loader": "^4.2.1",
"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": "^0.11.0",
"node-sass": "^4.14.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",
"ts-jest": "^26.1.1",
"typescript": "^4.0.2",
"uglifyjs-webpack-plugin": "^2.2.0",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.11",
"wms-core": "^0.21.4"
"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"
"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,66 +1,85 @@
import Application from "wms-core/Application";
import {Type} from "wms-core/Utils";
import Migration from "wms-core/db/Migration";
import CreateMigrationsTable from "wms-core/migrations/CreateMigrationsTable";
import CreateLogsTable from "wms-core/migrations/CreateLogsTable";
import ExpressAppComponent from "wms-core/components/ExpressAppComponent";
import NunjucksComponent from "wms-core/components/NunjucksComponent";
import MysqlComponent from "wms-core/components/MysqlComponent";
import LogRequestsComponent from "wms-core/components/LogRequestsComponent";
import RedisComponent from "wms-core/components/RedisComponent";
import ServeStaticDirectoryComponent from "wms-core/components/ServeStaticDirectoryComponent";
import MaintenanceComponent from "wms-core/components/MaintenanceComponent";
import MailComponent from "wms-core/components/MailComponent";
import SessionComponent from "wms-core/components/SessionComponent";
import FormHelperComponent from "wms-core/components/FormHelperComponent";
import CsrfProtectionComponent from "wms-core/components/CsrfProtectionComponent";
import WebSocketServerComponent from "wms-core/components/WebSocketServerComponent";
import AboutController from "./controllers/AboutController";
import AutoUpdateComponent from "wms-core/components/AutoUpdateComponent";
import AuthController from "./controllers/AuthController";
import MagicLinkWebSocketListener from "wms-core/auth/magic_link/MagicLinkWebSocketListener";
import MagicLinkController from "./controllers/MagicLinkController";
import MailController from "wms-core/auth/MailController";
import FileController from "./controllers/FileController";
import CreateUsersAndUserEmailsTable from "wms-core/auth/migrations/CreateUsersAndUserEmailsTable";
import CreateMagicLinksTable from "wms-core/auth/migrations/CreateMagicLinksTable";
import CreateAuthTokensTable from "./migrations/CreateAuthTokensTable";
import AuthComponent from "wms-core/auth/AuthComponent";
import AuthGuard from "wms-core/auth/AuthGuard";
import MagicLink from "wms-core/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 "wms-core/auth/migrations/AddApprovedFieldToUsersTable";
import CreateUrlRedirectsTable from "./migrations/CreateUrlRedirectsTable";
import AuthTokenController from "./controllers/AuthTokenController";
import URLRedirectController from "./controllers/URLRedirectController";
import LinkController from "./controllers/LinkController";
import BackendController from "wms-core/helpers/BackendController";
import RedirectBackComponent from "wms-core/components/RedirectBackComponent";
import Application from "swaf/Application";
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 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 SessionComponent from "swaf/components/SessionComponent";
import WebSocketServerComponent from "swaf/components/WebSocketServerComponent";
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 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 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 {
private readonly port: number;
private magicLinkWebSocketListener?: MagicLinkWebSocketListener;
constructor(port: number) {
super(require('../package.json').version);
this.port = port;
public constructor(
version: string,
private readonly addr: string,
private readonly port: number,
) {
super(version);
}
protected getMigrations(): Type<Migration>[] {
protected getMigrations(): MigrationType<Migration>[] {
return [
CreateMigrationsTable,
CreateLogsTable,
CreateUsersAndUserEmailsTable,
CreateMagicLinksTable,
DummyMigration,
CreateUsersAndUserEmailsTableMigration,
CreateMagicLinksTableMigration,
CreateAuthTokensTable,
CreateFilesTable,
IncreaseFilesSizeField,
AddApprovedFieldToUsersTable,
AddApprovedFieldToUsersTableMigration,
CreateUrlRedirectsTable,
DropLegacyLogsTable,
DummyMigration,
AddUsedToMagicLinksMigration,
MakeMagicLinksSessionNotUniqueMigration,
AddPasswordToUsersMigration,
DummyMigration,
ReplaceTtlWithExpiresAtFilesTable,
];
}
@ -71,13 +90,8 @@ export default class App extends Application {
}
private registerComponents() {
const redisComponent = new RedisComponent();
const mysqlComponent = new MysqlComponent();
const expressAppComponent = new ExpressAppComponent(this.port);
this.use(expressAppComponent);
// Base
this.use(new ExpressAppComponent(this.addr, this.port));
this.use(new LogRequestsComponent());
// Static files
@ -85,41 +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: Express.Session): Promise<any | 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 super.getProofForRequest(req);
}
}));
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());
@ -128,12 +133,15 @@ 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() {
this.magicLinkWebSocketListener = new MagicLinkWebSocketListener();
this.use(this.magicLinkWebSocketListener);
this.use(new MagicLinkWebSocketListener());
}
private registerControllers() {
@ -141,12 +149,13 @@ export default class App extends Application {
this.use(new LinkController());
// Priority
this.use(new AuthController());
this.use(new MagicLinkController(this.magicLinkWebSocketListener!));
this.use(new BackendController());
// Core functionality
this.use(new MailController());
this.use(new AuthController());
this.use(new MagicLinkController(this.as<MagicLinkWebSocketListener<this>>(MagicLinkWebSocketListener)));
// Core
this.use(new AccountController());
this.use(new BackendController());
// Other functionality
this.use(new AuthTokenController());
@ -158,4 +167,4 @@ export default class App extends Application {
this.use(new FileController());
this.use(new URLRedirectController());
}
}
}

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,17 +1,17 @@
import {cryptoRandomDictionary} from "wms-core/Utils";
import config from "config";
import FileModel from "./models/FileModel";
import {ServerError} from "wms-core/HttpError";
import {nanoid} from "nanoid";
import {ServerError} from "swaf/HttpError";
import FileModel from "./models/FileModel.js";
const SLUG_DICTIONARY = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
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;
}
i++;
} while (i < tries);
throw new ServerError('Failed to generate slug; newly generated slug size should be increased by 1.');
};
}

View File

@ -1,4 +1,4 @@
export function encodeRFC5987ValueChars(str: string) {
export function encodeRFC5987ValueChars(str: string): string {
return encodeURIComponent(str).
// Note that although RFC3986 reserves "!", RFC5987 does not,
// so we do not need to escape it

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,8 +1,8 @@
import Controller from "wms-core/Controller";
import {Request, Response} from "express";
import Controller from "swaf/Controller";
export default class AboutController extends Controller {
routes(): void {
public routes(): void {
this.get('/', this.getAbout, 'home');
this.get('/', this.getAbout, 'about');
}
@ -10,4 +10,4 @@ export default class AboutController extends Controller {
private async getAbout(req: Request, res: Response) {
res.render('about');
}
}
}

View File

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

View File

@ -1,23 +1,44 @@
import Controller from "wms-core/Controller";
import {REQUIRE_AUTH_MIDDLEWARE} from "wms-core/auth/AuthComponent";
import config from "config";
import {Request, Response} from "express";
import AuthToken from "../models/AuthToken";
import {BadRequestError, ForbiddenHttpError, NotFoundHttpError} from "wms-core/HttpError";
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 {
routes(): void {
this.post('/gen-auth-token', this.postGenAuthToken, 'generate-token', REQUIRE_AUTH_MIDDLEWARE);
this.post('/revoke-auth-token/:id', this.postRevokeAuthToken, 'revoke-token', REQUIRE_AUTH_MIDDLEWARE);
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({
user_id: req.models.user!.id,
user_id: user.id,
ttl: req.body.ttl ? parseInt(req.body.ttl) : 365 * 24 * 3600,
});
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> {
@ -26,11 +47,13 @@ export default class AuthTokenController extends Controller {
const authToken = await AuthToken.getById<AuthToken>(parseInt(id));
if (!authToken) throw new NotFoundHttpError('Auth token', req.url);
if (!authToken.canDelete(req.models.user!.id!)) throw new ForbiddenHttpError('auth token', req.url);
const user = req.as(RequireAuthMiddleware).getUser();
if (!authToken.canDelete(user.getOrFail('id'))) throw new ForbiddenHttpError('auth token', req.url);
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,58 +1,82 @@
import Controller from "wms-core/Controller";
import {REQUIRE_AUTH_MIDDLEWARE} from "wms-core/auth/AuthComponent";
import {NextFunction, Request, Response} from "express";
import {BadRequestError, ForbiddenHttpError, ServerError} from "wms-core/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 Logger from "wms-core/Logger";
import FileUploadMiddleware from "wms-core/FileUploadMiddleware";
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 {
routes(): void {
this.get('/files/upload', this.getFileUploader, 'file-upload', REQUIRE_AUTH_MIDDLEWARE);
this.get('/files/upload/script', this.downloadLinuxScript, 'file-linux-script');
this.post('/files/post', this.postFileFrontend, 'post-file-frontend', REQUIRE_AUTH_MIDDLEWARE, FILE_UPLOAD_FORM_MIDDLEWARE);
this.get('/files/:page([0-9]+)?', this.getFileManager, 'file-manager', REQUIRE_AUTH_MIDDLEWARE);
this.post('/files/delete/:slug', FileController.deleteFileRoute, 'delete-file-frontend', REQUIRE_AUTH_MIDDLEWARE);
public routes(): void {
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');
res.render('file-upload', {
const user = req.as(RequireAuthMiddleware).getUser();
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', req.models.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> {
res.render('file-manager', {
files: await FileModel.paginateForUser(req, 100, req.models.user!.id!),
});
res.download(path.resolve(__dirname, '..', 'assets/files/upload_file.sh'), 'upload_file.sh');
}
protected async postFileFrontend(req: Request, res: Response): Promise<void> {
req.body.type = 'file';
await FileController.handleFileUpload(req.body.autogen_url === undefined && req.body.slug ? req.body.slug : await generateSlug(10), req, res);
await FileController.handleFileUpload(
req.body.autogen_url === undefined && req.body.slug ?
req.body.slug :
await generateSlug(10),
req,
res,
);
}
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 (!req.files || !req.files['upload']) {
if (Object.keys(req.files).indexOf('upload') < 0) {
throw new BadRequestError('No file received.', 'You must upload exactly one (1) file.', req.url);
}
let upload = req.files['upload'];
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');
@ -60,20 +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 = (requestAuth ? req.as(RequireRequestAuthMiddleware) : req.as(RequireAuthMiddleware)).getUser();
const file = FileModel.create({
user_id: req.models.user!.id,
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.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),
@ -82,18 +109,25 @@ 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();
if (!file.canDelete(req.models.user!.id!)) throw new ForbiddenHttpError('file', req.url);
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) {
case 'local':
@ -110,21 +144,28 @@ export default class FileController extends Controller {
text: () => res.send('success'),
html: () => {
req.flash('success', 'Successfully deleted file.');
res.redirectBack('/');
res.redirect(route('file-uploader'));
},
});
}
public static async deleteFile(file: FileModel): Promise<void> {
fs.unlinkSync(file.storage_path!);
fs.unlinkSync(file.getOrFail('storage_path'));
await file.delete();
Logger.info('Deleted', file.storage_path, `(${file.real_name})`);
logger.info('Deleted', file.storage_path, `(${file.real_name})`);
}
}
export const FILE_UPLOAD_FORM_MIDDLEWARE = new FileUploadMiddleware(() => {
const form = new IncomingForm();
form.uploadDir = 'storage/tmp';
form.maxFileSize = config.get<number>('max_upload_size') * 1024 * 1024;
return form;
}, 'upload');
export class FileUploadFormMiddleware extends FileUploadMiddleware {
protected getDefaultField(): string {
return 'upload';
}
protected getFormidableOptions(): formidable.Options {
return {
uploadDir: 'storage/tmp',
maxFileSize: config.get<number>('max_upload_size') * 1024 * 1024,
};
}
}

View File

@ -0,0 +1,26 @@
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 {
this.get('/', this.getHome, 'home');
this.get('/about', this.getAbout, 'about');
this.get('/back', this.goBack, 'about');
}
protected async getHome(req: Request, res: Response): Promise<void> {
res.render('home');
}
protected async getAbout(req: Request, res: Response): Promise<void> {
res.render('about');
}
/**
* This is to test and assert that swaf extended types are available
*/
protected async goBack(req: Request, res: Response): Promise<void> {
res.redirect(req.getPreviousUrl() || route('home'));
}
}

View File

@ -1,36 +1,35 @@
import Controller from "wms-core/Controller";
import {NextFunction, Request, Response} from "express";
import {BadRequestError, NotFoundHttpError, ServerError} from "wms-core/HttpError";
import config from "config";
import {REQUIRE_REQUEST_AUTH_MIDDLEWARE} from "wms-core/auth/AuthComponent";
import URLRedirect from "../models/URLRedirect";
import URLRedirectController from "./URLRedirectController";
import FileModel from "../models/FileModel";
import generateSlug from "../SlugGenerator";
import FileController, {FILE_UPLOAD_FORM_MIDDLEWARE} 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 * as buffer from "buffer";
import Logger from "wms-core/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 {
routes(): void {
this.post('/', this.postFile, 'post-file', REQUIRE_REQUEST_AUTH_MIDDLEWARE, FILE_UPLOAD_FORM_MIDDLEWARE);
this.delete('/:slug', FileController.deleteFileRoute, 'delete-file', REQUIRE_REQUEST_AUTH_MIDDLEWARE);
public routes(): void {
this.post('/', this.postFile, 'post-file', RequireRequestAuthMiddleware, FileUploadFormMiddleware);
this.delete('/:slug', this.deleteFile, 'delete-file', RequireRequestAuthMiddleware);
this.get('/:slug', this.getFile, 'get-file');
this.put('/:slug', this.putFile, 'put-file', REQUIRE_REQUEST_AUTH_MIDDLEWARE, FILE_UPLOAD_FORM_MIDDLEWARE);
this.put('/:slug', this.putFile, 'put-file', RequireRequestAuthMiddleware, FileUploadFormMiddleware);
this.post('/', URLRedirectController.addURL, 'post-url', REQUIRE_REQUEST_AUTH_MIDDLEWARE);
this.delete('/:slug', this.deleteURL, 'delete-url', REQUIRE_REQUEST_AUTH_MIDDLEWARE);
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', REQUIRE_REQUEST_AUTH_MIDDLEWARE);
this.put('/:slug', this.addURL, 'put-url', RequireRequestAuthMiddleware);
this.get(/(.*)/, this.domainFilter);
}
protected async getFile(req: Request, res: Response, next: NextFunction): Promise<void> {
console.log('get file', req.params.slug)
const file = await FileModel.getBySlug(req.params.slug);
if (!file) return next();
if (file.shouldBeDeleted()) {
@ -38,29 +37,31 @@ export default class LinkController extends Controller {
return next();
}
switch (file.storage_type) {
case 'local':
const stats = await promisify(fs.stat)(file.storage_path!);
const fileName = file.getOrFail('real_name');
// If file is bigger than max supported one shot reading, fallback to express download
if (stats.size > buffer.constants.MAX_LENGTH) {
Logger.info(`Fallback to express download for file of size ${stats.size}`);
return res.download(file.storage_path!);
switch (file.storage_type) {
case 'local': {
const stats = await promisify(fs.stat)(file.getOrFail('storage_path'));
// If file is bigger than max hotlink size, fallback to express download
if (stats.size > config.get<number>('max_hotlink_size') * 1024 * 1024) {
logger.info(`Fallback to express download for file of size ${stats.size}`);
return res.download(file.getOrFail('storage_path'), fileName);
}
// File type
const fileName = file.real_name!;
const parts = fileName.split('.');
res.type(parts[parts.length - 1]);
// File name
res.header('Content-Disposition', `inline; filename*=UTF-8''${encodeRFC5987ValueChars(fileName)}`);
fs.readFile(file.storage_path!, (err, data) => {
fs.readFile(file.getOrFail('storage_path'), (err, data) => {
if (err) return next(err);
res.send(data);
});
break;
}
default:
throw new ServerError(`This file cannot be served. Download protocol for ${file.storage_type} storage type not implemented.`);
}
@ -69,22 +70,36 @@ 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> {
const url = await URLRedirect.getBySlug(req.params.slug);
if (!url) return next();
res.redirect(url.target_url!, 301);
res.redirect(url.getOrFail('target_url'), 301);
}
protected async deleteURL(req: Request, res: Response, next: NextFunction): Promise<void> {
@ -94,13 +109,13 @@ export default class LinkController extends Controller {
throw new BadRequestError(
'Deleting url redirects is disabled for security reasons.',
'If you still want to disable the redirection, please contact us via email.',
req.url
req.url,
);
}
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,4 +1,4 @@
import MagicLink from "wms-core/auth/models/MagicLink";
import MagicLink from "swaf/auth/models/MagicLink";
export enum MagicLinkActionType {
LOGIN = 'Login',
@ -6,7 +6,7 @@ export enum MagicLinkActionType {
}
export function getActionMessage(magicLink: MagicLink): string {
switch (magicLink.getActionType()) {
switch (magicLink.action_type) {
case MagicLinkActionType.LOGIN:
return 'You have been authenticated.';
case MagicLinkActionType.REGISTER:
@ -14,4 +14,4 @@ export function getActionMessage(magicLink: MagicLink): string {
}
return '';
}
}

View File

@ -1,30 +0,0 @@
import _MagicLinkController from "wms-core/auth/magic_link/MagicLinkController";
import {Request, Response} from "express";
import Controller from "wms-core/Controller";
import MagicLinkWebSocketListener from "wms-core/auth/magic_link/MagicLinkWebSocketListener";
import MagicLink from "wms-core/auth/models/MagicLink";
import AuthController from "./AuthController";
import {MagicLinkActionType} from "./MagicLinkActionType";
export default class MagicLinkController extends _MagicLinkController {
constructor(magicLinkWebSocketListener: MagicLinkWebSocketListener) {
super(magicLinkWebSocketListener);
}
protected async performAction(magicLink: MagicLink, req: Request, res: Response): Promise<void> {
switch (magicLink.getActionType()) {
case MagicLinkActionType.LOGIN:
case MagicLinkActionType.REGISTER:
await AuthController.checkAndAuth(req, res, magicLink);
const proof = await req.authGuard.isAuthenticated(req.session!);
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,56 +1,72 @@
import Controller from "wms-core/Controller";
import {NextFunction, Request, Response} from "express";
import URLRedirect from "../models/URLRedirect";
import {REQUIRE_AUTH_MIDDLEWARE} from "wms-core/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 {
routes(): void {
this.get('/url/shrink', this.getURLShrinker, 'url-shrinker', REQUIRE_AUTH_MIDDLEWARE);
this.get('/url/shrink/script', this.downloadLinuxScript, 'url-linux-script');
this.post('/url/shrink', this.addURLFrontend, 'shrink-url', REQUIRE_AUTH_MIDDLEWARE);
this.get('/urls/:page([0-9]+)?', this.getURLRedirectManager, 'url-manager', REQUIRE_AUTH_MIDDLEWARE);
public routes(): void {
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', req.models.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> {
res.render('url-manager', {
urls: await URLRedirect.paginateForUser(req, 100, req.models.user!.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, res, next, req.body.autogen_url === undefined && req.body.slug ? req.body.slug : await generateSlug(10));
await URLRedirectController.addURL(
req,
res,
next,
req.body.autogen_url === undefined && req.body.slug ?
req.body.slug :
await generateSlug(10),
);
}
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 = (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: req.models.user!.id,
user_id: user.id,
slug: slug,
target_url: req.body.target_url,
});
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),
@ -59,8 +75,8 @@ 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

@ -1,10 +1,28 @@
import Logger from "wms-core/Logger";
import App from "./App";
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/'
+ delimiter
+ (process.env['NODE_CONFIG_DIR'] || __dirname + '/../config/');
import config from "config";
import {promises as fs} from "fs";
import {logger} from "swaf/Logger";
import App from "./App.js";
(async () => {
const app = new App(config.get<number>('port'));
logger.debug('Config path:', process.env['NODE_CONFIG_DIR']);
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 => {
Logger.error(err);
});
logger.error(err);
});

View File

@ -1,10 +1,10 @@
import {Connection} from "mysql";
import Migration from "wms-core/db/Migration";
import ModelFactory from "wms-core/db/ModelFactory";
import AuthToken from "../models/AuthToken";
import Migration from "swaf/db/Migration";
import ModelFactory from "swaf/db/ModelFactory";
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,15 +14,15 @@ 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 {
ModelFactory.register(AuthToken);
}
}
}

View File

@ -1,10 +1,10 @@
import {Connection} from "mysql";
import Migration from "wms-core/db/Migration";
import ModelFactory from "wms-core/db/ModelFactory";
import FileModel from "../models/FileModel";
import Migration from "swaf/db/Migration";
import ModelFactory from "swaf/db/ModelFactory";
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,14 +17,14 @@ 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 {
ModelFactory.register(FileModel);
}
}
}

View File

@ -1,10 +1,10 @@
import Migration from "wms-core/db/Migration";
import {Connection} from "mysql";
import ModelFactory from "wms-core/db/ModelFactory";
import URLRedirect from "../models/URLRedirect";
import Migration from "swaf/db/Migration";
import ModelFactory from "swaf/db/ModelFactory";
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,14 +13,14 @@ 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 {
ModelFactory.register(URLRedirect);
}
}
}

View File

@ -1,15 +1,11 @@
import Migration from "wms-core/db/Migration";
import {Connection} from "mysql";
import Migration from "swaf/db/Migration";
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`);
}
public registerModels(): void {
}
}
}

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,41 +1,53 @@
import Model from "wms-core/db/Model";
import AuthProof from "wms-core/auth/AuthProof";
import User from "wms-core/auth/models/User";
import {cryptoRandomDictionary} from "wms-core/Utils";
import {Request} from "express";
import {nanoid} from "nanoid";
import AuthProof from "swaf/auth/AuthProof";
import User from "swaf/auth/models/User";
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;
protected readonly secret?: string = undefined;
protected created_at?: Date = undefined;
protected used_at?: Date = undefined;
private secret?: string = undefined;
public created_at?: Date = undefined;
public used_at?: Date = undefined;
protected readonly ttl?: number = undefined;
protected init() {
protected init(): void {
this.setValidation('user_id').defined().exists(User, 'id');
this.setValidation('secret').defined().between(32, 64);
this.setValidation('ttl').defined().min(1).max(5 * 365 * 24 * 3600 /* 5 years */);
}
protected async autoFill(): Promise<void> {
await super.autoFill();
// @ts-ignore
if (!this.secret) this['secret'] = cryptoRandomDictionary(64, 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_');
if (!this.secret) {
this.secret = nanoid(64);
}
}
public use() {
public async use(): Promise<void> {
this.used_at = new Date();
await this.save();
}
public canDelete(user_id: number) {
public canDelete(user_id: number): boolean {
return this.user_id === user_id;
}
public getExpirationDate(): Date {
if (!this.created_at) return new Date();
return new Date(this.created_at.getTime() + this.ttl! * 1000);
return new Date(this.created_at.getTime() + this.getOrFail('ttl') * 1000);
}
public async getResource(): Promise<User | null> {
@ -53,4 +65,8 @@ export default class AuthToken extends Model implements AuthProof<User> {
public async revoke(): Promise<void> {
await this.delete();
}
}
protected getSecret(): string | undefined {
return this.secret;
}
}

View File

@ -1,9 +1,11 @@
import Model from "wms-core/db/Model";
import Controller from "wms-core/Controller";
import config from "config";
import User from "wms-core/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;
protected init() {
/**
* @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', {
slug: this.slug!,
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.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 "wms-core/db/Model";
import User from "wms-core/auth/models/User";
import FileModel from "./FileModel";
import {Request} from "express";
import config from "config";
import Controller from "wms-core/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,13 +34,15 @@ 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', {
slug: this.slug!,
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

@ -2,4 +2,4 @@ describe('Write your tests', () => {
test('Remove this when you have some tests', () => {
expect(false).toBe(true);
});
});
});

View File

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

14
tsconfig.test.json Normal file
View File

@ -0,0 +1,14 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"typeRoots": [
"node_modules/@types",
"src/types",
"test/types"
]
},
"include": [
"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 wms-core</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,86 +0,0 @@
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const UglifyJSPlugin = require('uglifyjs-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: /\.(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')({}),
]
}
}
]
}
],
},
plugins: [
new MiniCssExtractPlugin({
filename: '../css/[name].css',
}),
]
};
if (!dev) {
config.optimization = {
minimizer: [
new UglifyJSPlugin(),
]
};
}
module.exports = config;

10669
yarn.lock

File diff suppressed because it is too large Load Diff