filesafe/controllers/albumsController.js

692 lines
20 KiB
JavaScript
Raw Normal View History

const EventEmitter = require('events')
const fs = require('fs')
const path = require('path')
const randomstring = require('randomstring')
const Zip = require('jszip')
Updates (very important to read) Client-side CSS & JS files will now be processed with Gulp. Gulp tasks are configured in gulpfile.js file. CSS files will be optimized with postcss-preset-env, which will auto-add vendor prefixes and convert any parts necessary for browsers compatibility. Afterwards they will be minified with cssnano. JS files will be optimized with bublé, likewise for browsers compatibility. Afterwards they will be minified with terser. Unprocessed CSS & JS files will now be located at src directory, while the processed results will be located at dist directory. Due to bublé, the JS files should now be compatible up to IE 11 at the minimum. Previously the safe would not work in IE 11 due to extensive usage of template literals. Due to that as well, JS files in src directory will now extensively use arrow functions for my personal comfort (as they will be converted too). The server will use the processed files at dist directory by default. If you want to rebuild the files by your own, you can run "yarn build". Gulp is a development dependency, so make sure you have installed all development dependencies (e.i. NOT using "yarn install --production"). --- yarn lint -> gulp lint yarn build -> gulp default yarn watch -> gulp watch yarn develop -> env NODE_ENV=development yarn watch --- Fixed not being able to demote staff into normal users. /api/token/verify will no longer respond with 401 HTTP error code, unless an error occurred (which will be 500 HTTP error code). Fixed /nojs route not displaying file's original name when a duplicate is found on the server. Removed is-breeze CSS class name, in favor of Bulma's is-info. Removed custom styling from auth page, in favor of global styling. Removed all usage of style HTML attribute in favor of CSS classes. Renamed js/s/ to js/misc/. Use loading spinners on dashboard's sidebar menus. Disable all other sidebar menus when something is loading. Changed title HTML attribute of disabled control buttons in uploads & users list. Hid checkboxes and WIP controls from users list. Better error messages handling. Especially homepage will now support CF's HTTP error codes. Updated various icons. Also, added fontello config file at public/libs/fontello/config.json. This should let you edit them more easily with fontello. Use Gatsby icon for my blog's link in homepage's footer. A bunch of other improvements here & there.
2019-09-15 06:20:11 +00:00
const paths = require('./pathsController')
Manage albums admin page, and more! Resolves #194. Added pagination for Manage your albums page. Albums sidebar will now only list 9 albums at most. Use Manage your albums page to view the rest. Albums in the list will now have View uploads button after all. Delete album button for albums renamed to Disable album. Since techincally the server would've always been disabling the albums instead of deleting them. It was something upstream dev's decided, and I haven't bothered changing its behavior. I'll work on actual Delete album feature some other days. As the title says, added Manage albums admin page. Viewing uploads of an album will hook into albumid: filter key. I'll work on filter and bulk operations some other days. Updated styling for disabled albums and users. Instead of havine a line through them, they will be greyed out. Disable public page of albums will still use line through however. Links to album's disabled public page are now clickable. Added a new button styling is-dangerish. It'll be orange. Renamed /api/albums/delete to /api/albums/disable. For backwards compatibility, /api/albums/delete will still work but automatically re-routed to /api/albums/disable. /api/uploads/list will no longer print SQLite errors for moderators or higher when encountering them. It was originally used to inform moderators of non-existing colum names when used for sorting. But on one of the recent commits, I had added a check for allowed colum names. Improved some caching in dashboard page. Added new entries to cookie policy. Some other small things. Bumped v1 version string and rebuilt client assets.
2020-06-01 04:44:16 +00:00
const perms = require('./permissionController')
const uploadController = require('./uploadController')
Updates (very important to read) Client-side CSS & JS files will now be processed with Gulp. Gulp tasks are configured in gulpfile.js file. CSS files will be optimized with postcss-preset-env, which will auto-add vendor prefixes and convert any parts necessary for browsers compatibility. Afterwards they will be minified with cssnano. JS files will be optimized with bublé, likewise for browsers compatibility. Afterwards they will be minified with terser. Unprocessed CSS & JS files will now be located at src directory, while the processed results will be located at dist directory. Due to bublé, the JS files should now be compatible up to IE 11 at the minimum. Previously the safe would not work in IE 11 due to extensive usage of template literals. Due to that as well, JS files in src directory will now extensively use arrow functions for my personal comfort (as they will be converted too). The server will use the processed files at dist directory by default. If you want to rebuild the files by your own, you can run "yarn build". Gulp is a development dependency, so make sure you have installed all development dependencies (e.i. NOT using "yarn install --production"). --- yarn lint -> gulp lint yarn build -> gulp default yarn watch -> gulp watch yarn develop -> env NODE_ENV=development yarn watch --- Fixed not being able to demote staff into normal users. /api/token/verify will no longer respond with 401 HTTP error code, unless an error occurred (which will be 500 HTTP error code). Fixed /nojs route not displaying file's original name when a duplicate is found on the server. Removed is-breeze CSS class name, in favor of Bulma's is-info. Removed custom styling from auth page, in favor of global styling. Removed all usage of style HTML attribute in favor of CSS classes. Renamed js/s/ to js/misc/. Use loading spinners on dashboard's sidebar menus. Disable all other sidebar menus when something is loading. Changed title HTML attribute of disabled control buttons in uploads & users list. Hid checkboxes and WIP controls from users list. Better error messages handling. Especially homepage will now support CF's HTTP error codes. Updated various icons. Also, added fontello config file at public/libs/fontello/config.json. This should let you edit them more easily with fontello. Use Gatsby icon for my blog's link in homepage's footer. A bunch of other improvements here & there.
2019-09-15 06:20:11 +00:00
const utils = require('./utilsController')
const apiErrorsHandler = require('./handlers/apiErrorsHandler.js')
const ClientError = require('./utils/ClientError')
const ServerError = require('./utils/ServerError')
Updates (very important to read) Client-side CSS & JS files will now be processed with Gulp. Gulp tasks are configured in gulpfile.js file. CSS files will be optimized with postcss-preset-env, which will auto-add vendor prefixes and convert any parts necessary for browsers compatibility. Afterwards they will be minified with cssnano. JS files will be optimized with bublé, likewise for browsers compatibility. Afterwards they will be minified with terser. Unprocessed CSS & JS files will now be located at src directory, while the processed results will be located at dist directory. Due to bublé, the JS files should now be compatible up to IE 11 at the minimum. Previously the safe would not work in IE 11 due to extensive usage of template literals. Due to that as well, JS files in src directory will now extensively use arrow functions for my personal comfort (as they will be converted too). The server will use the processed files at dist directory by default. If you want to rebuild the files by your own, you can run "yarn build". Gulp is a development dependency, so make sure you have installed all development dependencies (e.i. NOT using "yarn install --production"). --- yarn lint -> gulp lint yarn build -> gulp default yarn watch -> gulp watch yarn develop -> env NODE_ENV=development yarn watch --- Fixed not being able to demote staff into normal users. /api/token/verify will no longer respond with 401 HTTP error code, unless an error occurred (which will be 500 HTTP error code). Fixed /nojs route not displaying file's original name when a duplicate is found on the server. Removed is-breeze CSS class name, in favor of Bulma's is-info. Removed custom styling from auth page, in favor of global styling. Removed all usage of style HTML attribute in favor of CSS classes. Renamed js/s/ to js/misc/. Use loading spinners on dashboard's sidebar menus. Disable all other sidebar menus when something is loading. Changed title HTML attribute of disabled control buttons in uploads & users list. Hid checkboxes and WIP controls from users list. Better error messages handling. Especially homepage will now support CF's HTTP error codes. Updated various icons. Also, added fontello config file at public/libs/fontello/config.json. This should let you edit them more easily with fontello. Use Gatsby icon for my blog's link in homepage's footer. A bunch of other improvements here & there.
2019-09-15 06:20:11 +00:00
const config = require('./../config')
const logger = require('./../logger')
const self = {
Updated Updated some dev dependencies. --- Gulp will now build CSS/JS files during development into dist-dev directory, to prevent IDE's Git from unnecessarily building diff's. Added dist-dev to ignore files. --- The entire config fille will now be passed to Nunjuck templates for ease of access of config values. Root domain for use in Nunjuck templates will now be parsed from config. Better page titles. Updated help message for "Uploads history order" option in homepage's config tab. Added "Load images for preview" option to homepage's config tab. Setting this to false will now prevent image uploads from loading themselves for previews. Uploads' original names in homepage's uploads history are now selectable. Min/max length for user/pass are now enforced in auth's front-end. Improved performance of album public pages. Their generated HTML pages will now be cached into memory. Unfortunately, No-JS version of their pages will be cached separately, so each album may take up to double the memory space. File names in thumbnails no longer have their full URLs as tooltips. I saw no point in that behavior. Added video icons. Homepage's uploads history will now display video icons for videos. "View thumbnail" button in Dashboard is now renamed to "Show preview". Their icons will also be changed depending on their file types. Added max length for albums' title & description. These will be enforced both in front-end and back-end. Existing albums that have surpassed the limits will not be enforced. A few other small improvements.
2019-09-17 04:13:41 +00:00
// Don't forget to update max length of text inputs in
// home.js & dashboard.js when changing these values
titleMaxLength: 70,
Updated Updated some dev dependencies. --- Gulp will now build CSS/JS files during development into dist-dev directory, to prevent IDE's Git from unnecessarily building diff's. Added dist-dev to ignore files. --- The entire config fille will now be passed to Nunjuck templates for ease of access of config values. Root domain for use in Nunjuck templates will now be parsed from config. Better page titles. Updated help message for "Uploads history order" option in homepage's config tab. Added "Load images for preview" option to homepage's config tab. Setting this to false will now prevent image uploads from loading themselves for previews. Uploads' original names in homepage's uploads history are now selectable. Min/max length for user/pass are now enforced in auth's front-end. Improved performance of album public pages. Their generated HTML pages will now be cached into memory. Unfortunately, No-JS version of their pages will be cached separately, so each album may take up to double the memory space. File names in thumbnails no longer have their full URLs as tooltips. I saw no point in that behavior. Added video icons. Homepage's uploads history will now display video icons for videos. "View thumbnail" button in Dashboard is now renamed to "Show preview". Their icons will also be changed depending on their file types. Added max length for albums' title & description. These will be enforced both in front-end and back-end. Existing albums that have surpassed the limits will not be enforced. A few other small improvements.
2019-09-17 04:13:41 +00:00
descMaxLength: 4000,
onHold: new Set()
}
2017-10-04 00:13:38 +00:00
2022-06-22 06:27:38 +00:00
const homeDomain = utils.conf.homeDomain || utils.conf.domain
const zipMaxTotalSize = parseInt(config.cloudflare.zipMaxTotalSize)
const zipMaxTotalSizeBytes = zipMaxTotalSize * 1e6
const zipOptions = config.uploads.jsZipOptions
// Force 'type' option to 'nodebuffer'
zipOptions.type = 'nodebuffer'
// Apply fallbacks for missing config values
if (zipOptions.streamFiles === undefined) zipOptions.streamFiles = true
if (zipOptions.compression === undefined) zipOptions.compression = 'DEFLATE'
if (zipOptions.compressionOptions === undefined) zipOptions.compressionOptions = {}
if (zipOptions.compressionOptions.level === undefined) zipOptions.compressionOptions.level = 1
self.zipEmitters = new Map()
class ZipEmitter extends EventEmitter {
constructor (identifier) {
super()
this.identifier = identifier
this.once('done', () => self.zipEmitters.delete(this.identifier))
}
}
self.getUniqueRandomName = async () => {
for (let i = 0; i < utils.idMaxTries; i++) {
const identifier = randomstring.generate(config.uploads.albumIdentifierLength)
if (self.onHold.has(identifier)) continue
// Put token on-hold (wait for it to be inserted to DB)
self.onHold.add(identifier)
const album = await utils.db.table('albums')
.where('identifier', identifier)
.select('id')
.first()
if (album) {
self.onHold.delete(identifier)
logger.log(`Album with identifier ${identifier} already exists (${i + 1}/${utils.idMaxTries}).`)
continue
}
return identifier
}
throw new ServerError('Failed to allocate a unique identifier for the album. Try again?')
}
self.list = async (req, res, next) => {
try {
const user = await utils.authorize(req)
const all = req.headers.all === '1'
const simple = req.headers.simple
const ismoderator = perms.is(user, 'moderator')
if (all && !ismoderator) return res.status(403).end()
const filter = function () {
if (!all) {
this.where({
enabled: 1,
userid: user.id
})
}
}
Manage albums admin page, and more! Resolves #194. Added pagination for Manage your albums page. Albums sidebar will now only list 9 albums at most. Use Manage your albums page to view the rest. Albums in the list will now have View uploads button after all. Delete album button for albums renamed to Disable album. Since techincally the server would've always been disabling the albums instead of deleting them. It was something upstream dev's decided, and I haven't bothered changing its behavior. I'll work on actual Delete album feature some other days. As the title says, added Manage albums admin page. Viewing uploads of an album will hook into albumid: filter key. I'll work on filter and bulk operations some other days. Updated styling for disabled albums and users. Instead of havine a line through them, they will be greyed out. Disable public page of albums will still use line through however. Links to album's disabled public page are now clickable. Added a new button styling is-dangerish. It'll be orange. Renamed /api/albums/delete to /api/albums/disable. For backwards compatibility, /api/albums/delete will still work but automatically re-routed to /api/albums/disable. /api/uploads/list will no longer print SQLite errors for moderators or higher when encountering them. It was originally used to inform moderators of non-existing colum names when used for sorting. But on one of the recent commits, I had added a check for allowed colum names. Improved some caching in dashboard page. Added new entries to cookie policy. Some other small things. Bumped v1 version string and rebuilt client assets.
2020-06-01 04:44:16 +00:00
// Query albums count for pagination
const count = await utils.db.table('albums')
Manage albums admin page, and more! Resolves #194. Added pagination for Manage your albums page. Albums sidebar will now only list 9 albums at most. Use Manage your albums page to view the rest. Albums in the list will now have View uploads button after all. Delete album button for albums renamed to Disable album. Since techincally the server would've always been disabling the albums instead of deleting them. It was something upstream dev's decided, and I haven't bothered changing its behavior. I'll work on actual Delete album feature some other days. As the title says, added Manage albums admin page. Viewing uploads of an album will hook into albumid: filter key. I'll work on filter and bulk operations some other days. Updated styling for disabled albums and users. Instead of havine a line through them, they will be greyed out. Disable public page of albums will still use line through however. Links to album's disabled public page are now clickable. Added a new button styling is-dangerish. It'll be orange. Renamed /api/albums/delete to /api/albums/disable. For backwards compatibility, /api/albums/delete will still work but automatically re-routed to /api/albums/disable. /api/uploads/list will no longer print SQLite errors for moderators or higher when encountering them. It was originally used to inform moderators of non-existing colum names when used for sorting. But on one of the recent commits, I had added a check for allowed colum names. Improved some caching in dashboard page. Added new entries to cookie policy. Some other small things. Bumped v1 version string and rebuilt client assets.
2020-06-01 04:44:16 +00:00
.where(filter)
.count('id as count')
.then(rows => rows[0].count)
if (!count) return res.json({ success: true, albums: [], count })
Manage albums admin page, and more! Resolves #194. Added pagination for Manage your albums page. Albums sidebar will now only list 9 albums at most. Use Manage your albums page to view the rest. Albums in the list will now have View uploads button after all. Delete album button for albums renamed to Disable album. Since techincally the server would've always been disabling the albums instead of deleting them. It was something upstream dev's decided, and I haven't bothered changing its behavior. I'll work on actual Delete album feature some other days. As the title says, added Manage albums admin page. Viewing uploads of an album will hook into albumid: filter key. I'll work on filter and bulk operations some other days. Updated styling for disabled albums and users. Instead of havine a line through them, they will be greyed out. Disable public page of albums will still use line through however. Links to album's disabled public page are now clickable. Added a new button styling is-dangerish. It'll be orange. Renamed /api/albums/delete to /api/albums/disable. For backwards compatibility, /api/albums/delete will still work but automatically re-routed to /api/albums/disable. /api/uploads/list will no longer print SQLite errors for moderators or higher when encountering them. It was originally used to inform moderators of non-existing colum names when used for sorting. But on one of the recent commits, I had added a check for allowed colum names. Improved some caching in dashboard page. Added new entries to cookie policy. Some other small things. Bumped v1 version string and rebuilt client assets.
2020-06-01 04:44:16 +00:00
const fields = ['id', 'name']
Manage albums admin page, and more! Resolves #194. Added pagination for Manage your albums page. Albums sidebar will now only list 9 albums at most. Use Manage your albums page to view the rest. Albums in the list will now have View uploads button after all. Delete album button for albums renamed to Disable album. Since techincally the server would've always been disabling the albums instead of deleting them. It was something upstream dev's decided, and I haven't bothered changing its behavior. I'll work on actual Delete album feature some other days. As the title says, added Manage albums admin page. Viewing uploads of an album will hook into albumid: filter key. I'll work on filter and bulk operations some other days. Updated styling for disabled albums and users. Instead of havine a line through them, they will be greyed out. Disable public page of albums will still use line through however. Links to album's disabled public page are now clickable. Added a new button styling is-dangerish. It'll be orange. Renamed /api/albums/delete to /api/albums/disable. For backwards compatibility, /api/albums/delete will still work but automatically re-routed to /api/albums/disable. /api/uploads/list will no longer print SQLite errors for moderators or higher when encountering them. It was originally used to inform moderators of non-existing colum names when used for sorting. But on one of the recent commits, I had added a check for allowed colum names. Improved some caching in dashboard page. Added new entries to cookie policy. Some other small things. Bumped v1 version string and rebuilt client assets.
2020-06-01 04:44:16 +00:00
let albums
if (simple) {
albums = await utils.db.table('albums')
Manage albums admin page, and more! Resolves #194. Added pagination for Manage your albums page. Albums sidebar will now only list 9 albums at most. Use Manage your albums page to view the rest. Albums in the list will now have View uploads button after all. Delete album button for albums renamed to Disable album. Since techincally the server would've always been disabling the albums instead of deleting them. It was something upstream dev's decided, and I haven't bothered changing its behavior. I'll work on actual Delete album feature some other days. As the title says, added Manage albums admin page. Viewing uploads of an album will hook into albumid: filter key. I'll work on filter and bulk operations some other days. Updated styling for disabled albums and users. Instead of havine a line through them, they will be greyed out. Disable public page of albums will still use line through however. Links to album's disabled public page are now clickable. Added a new button styling is-dangerish. It'll be orange. Renamed /api/albums/delete to /api/albums/disable. For backwards compatibility, /api/albums/delete will still work but automatically re-routed to /api/albums/disable. /api/uploads/list will no longer print SQLite errors for moderators or higher when encountering them. It was originally used to inform moderators of non-existing colum names when used for sorting. But on one of the recent commits, I had added a check for allowed colum names. Improved some caching in dashboard page. Added new entries to cookie policy. Some other small things. Bumped v1 version string and rebuilt client assets.
2020-06-01 04:44:16 +00:00
.where(filter)
.select(fields)
return res.json({ success: true, albums, count })
} else {
let offset = Number(req.params.page)
if (isNaN(offset)) offset = 0
else if (offset < 0) offset = Math.max(0, Math.ceil(count / 25) + offset)
fields.push('identifier', 'enabled', 'timestamp', 'editedAt', 'zipGeneratedAt', 'download', 'public', 'description')
if (all) fields.push('userid')
Manage albums admin page, and more! Resolves #194. Added pagination for Manage your albums page. Albums sidebar will now only list 9 albums at most. Use Manage your albums page to view the rest. Albums in the list will now have View uploads button after all. Delete album button for albums renamed to Disable album. Since techincally the server would've always been disabling the albums instead of deleting them. It was something upstream dev's decided, and I haven't bothered changing its behavior. I'll work on actual Delete album feature some other days. As the title says, added Manage albums admin page. Viewing uploads of an album will hook into albumid: filter key. I'll work on filter and bulk operations some other days. Updated styling for disabled albums and users. Instead of havine a line through them, they will be greyed out. Disable public page of albums will still use line through however. Links to album's disabled public page are now clickable. Added a new button styling is-dangerish. It'll be orange. Renamed /api/albums/delete to /api/albums/disable. For backwards compatibility, /api/albums/delete will still work but automatically re-routed to /api/albums/disable. /api/uploads/list will no longer print SQLite errors for moderators or higher when encountering them. It was originally used to inform moderators of non-existing colum names when used for sorting. But on one of the recent commits, I had added a check for allowed colum names. Improved some caching in dashboard page. Added new entries to cookie policy. Some other small things. Bumped v1 version string and rebuilt client assets.
2020-06-01 04:44:16 +00:00
albums = await utils.db.table('albums')
Manage albums admin page, and more! Resolves #194. Added pagination for Manage your albums page. Albums sidebar will now only list 9 albums at most. Use Manage your albums page to view the rest. Albums in the list will now have View uploads button after all. Delete album button for albums renamed to Disable album. Since techincally the server would've always been disabling the albums instead of deleting them. It was something upstream dev's decided, and I haven't bothered changing its behavior. I'll work on actual Delete album feature some other days. As the title says, added Manage albums admin page. Viewing uploads of an album will hook into albumid: filter key. I'll work on filter and bulk operations some other days. Updated styling for disabled albums and users. Instead of havine a line through them, they will be greyed out. Disable public page of albums will still use line through however. Links to album's disabled public page are now clickable. Added a new button styling is-dangerish. It'll be orange. Renamed /api/albums/delete to /api/albums/disable. For backwards compatibility, /api/albums/delete will still work but automatically re-routed to /api/albums/disable. /api/uploads/list will no longer print SQLite errors for moderators or higher when encountering them. It was originally used to inform moderators of non-existing colum names when used for sorting. But on one of the recent commits, I had added a check for allowed colum names. Improved some caching in dashboard page. Added new entries to cookie policy. Some other small things. Bumped v1 version string and rebuilt client assets.
2020-06-01 04:44:16 +00:00
.where(filter)
.limit(25)
.offset(25 * offset)
.select(fields)
}
2017-10-04 00:13:38 +00:00
Manage albums admin page, and more! Resolves #194. Added pagination for Manage your albums page. Albums sidebar will now only list 9 albums at most. Use Manage your albums page to view the rest. Albums in the list will now have View uploads button after all. Delete album button for albums renamed to Disable album. Since techincally the server would've always been disabling the albums instead of deleting them. It was something upstream dev's decided, and I haven't bothered changing its behavior. I'll work on actual Delete album feature some other days. As the title says, added Manage albums admin page. Viewing uploads of an album will hook into albumid: filter key. I'll work on filter and bulk operations some other days. Updated styling for disabled albums and users. Instead of havine a line through them, they will be greyed out. Disable public page of albums will still use line through however. Links to album's disabled public page are now clickable. Added a new button styling is-dangerish. It'll be orange. Renamed /api/albums/delete to /api/albums/disable. For backwards compatibility, /api/albums/delete will still work but automatically re-routed to /api/albums/disable. /api/uploads/list will no longer print SQLite errors for moderators or higher when encountering them. It was originally used to inform moderators of non-existing colum names when used for sorting. But on one of the recent commits, I had added a check for allowed colum names. Improved some caching in dashboard page. Added new entries to cookie policy. Some other small things. Bumped v1 version string and rebuilt client assets.
2020-06-01 04:44:16 +00:00
const albumids = {}
for (const album of albums) {
album.download = album.download !== 0
album.public = album.public !== 0
album.uploads = 0
album.size = 0
album.zipSize = null
album.descriptionHtml = album.description
? utils.md.instance.render(album.description)
: ''
2017-10-04 00:13:38 +00:00
Manage albums admin page, and more! Resolves #194. Added pagination for Manage your albums page. Albums sidebar will now only list 9 albums at most. Use Manage your albums page to view the rest. Albums in the list will now have View uploads button after all. Delete album button for albums renamed to Disable album. Since techincally the server would've always been disabling the albums instead of deleting them. It was something upstream dev's decided, and I haven't bothered changing its behavior. I'll work on actual Delete album feature some other days. As the title says, added Manage albums admin page. Viewing uploads of an album will hook into albumid: filter key. I'll work on filter and bulk operations some other days. Updated styling for disabled albums and users. Instead of havine a line through them, they will be greyed out. Disable public page of albums will still use line through however. Links to album's disabled public page are now clickable. Added a new button styling is-dangerish. It'll be orange. Renamed /api/albums/delete to /api/albums/disable. For backwards compatibility, /api/albums/delete will still work but automatically re-routed to /api/albums/disable. /api/uploads/list will no longer print SQLite errors for moderators or higher when encountering them. It was originally used to inform moderators of non-existing colum names when used for sorting. But on one of the recent commits, I had added a check for allowed colum names. Improved some caching in dashboard page. Added new entries to cookie policy. Some other small things. Bumped v1 version string and rebuilt client assets.
2020-06-01 04:44:16 +00:00
// Map by IDs
albumids[album.id] = album
}
2017-10-04 00:13:38 +00:00
const getAlbumZipSize = async album => {
if (!album.zipGeneratedAt) return
try {
const filePath = path.join(paths.zips, `${album.identifier}.zip`)
const stats = await paths.stat(filePath)
albumids[album.id].zipSize = stats.size
} catch (error) {
if (error.code !== 'ENOENT') logger.error(error)
}
}
await Promise.all(albums.map(album => getAlbumZipSize(album)))
const uploads = await utils.db.table('files')
Manage albums admin page, and more! Resolves #194. Added pagination for Manage your albums page. Albums sidebar will now only list 9 albums at most. Use Manage your albums page to view the rest. Albums in the list will now have View uploads button after all. Delete album button for albums renamed to Disable album. Since techincally the server would've always been disabling the albums instead of deleting them. It was something upstream dev's decided, and I haven't bothered changing its behavior. I'll work on actual Delete album feature some other days. As the title says, added Manage albums admin page. Viewing uploads of an album will hook into albumid: filter key. I'll work on filter and bulk operations some other days. Updated styling for disabled albums and users. Instead of havine a line through them, they will be greyed out. Disable public page of albums will still use line through however. Links to album's disabled public page are now clickable. Added a new button styling is-dangerish. It'll be orange. Renamed /api/albums/delete to /api/albums/disable. For backwards compatibility, /api/albums/delete will still work but automatically re-routed to /api/albums/disable. /api/uploads/list will no longer print SQLite errors for moderators or higher when encountering them. It was originally used to inform moderators of non-existing colum names when used for sorting. But on one of the recent commits, I had added a check for allowed colum names. Improved some caching in dashboard page. Added new entries to cookie policy. Some other small things. Bumped v1 version string and rebuilt client assets.
2020-06-01 04:44:16 +00:00
.whereIn('albumid', Object.keys(albumids))
.select('albumid', 'size')
2017-10-04 00:13:38 +00:00
for (const upload of uploads) {
if (albumids[upload.albumid]) {
Manage albums admin page, and more! Resolves #194. Added pagination for Manage your albums page. Albums sidebar will now only list 9 albums at most. Use Manage your albums page to view the rest. Albums in the list will now have View uploads button after all. Delete album button for albums renamed to Disable album. Since techincally the server would've always been disabling the albums instead of deleting them. It was something upstream dev's decided, and I haven't bothered changing its behavior. I'll work on actual Delete album feature some other days. As the title says, added Manage albums admin page. Viewing uploads of an album will hook into albumid: filter key. I'll work on filter and bulk operations some other days. Updated styling for disabled albums and users. Instead of havine a line through them, they will be greyed out. Disable public page of albums will still use line through however. Links to album's disabled public page are now clickable. Added a new button styling is-dangerish. It'll be orange. Renamed /api/albums/delete to /api/albums/disable. For backwards compatibility, /api/albums/delete will still work but automatically re-routed to /api/albums/disable. /api/uploads/list will no longer print SQLite errors for moderators or higher when encountering them. It was originally used to inform moderators of non-existing colum names when used for sorting. But on one of the recent commits, I had added a check for allowed colum names. Improved some caching in dashboard page. Added new entries to cookie policy. Some other small things. Bumped v1 version string and rebuilt client assets.
2020-06-01 04:44:16 +00:00
albumids[upload.albumid].uploads++
albumids[upload.albumid].size += parseInt(upload.size)
}
}
Manage albums admin page, and more! Resolves #194. Added pagination for Manage your albums page. Albums sidebar will now only list 9 albums at most. Use Manage your albums page to view the rest. Albums in the list will now have View uploads button after all. Delete album button for albums renamed to Disable album. Since techincally the server would've always been disabling the albums instead of deleting them. It was something upstream dev's decided, and I haven't bothered changing its behavior. I'll work on actual Delete album feature some other days. As the title says, added Manage albums admin page. Viewing uploads of an album will hook into albumid: filter key. I'll work on filter and bulk operations some other days. Updated styling for disabled albums and users. Instead of havine a line through them, they will be greyed out. Disable public page of albums will still use line through however. Links to album's disabled public page are now clickable. Added a new button styling is-dangerish. It'll be orange. Renamed /api/albums/delete to /api/albums/disable. For backwards compatibility, /api/albums/delete will still work but automatically re-routed to /api/albums/disable. /api/uploads/list will no longer print SQLite errors for moderators or higher when encountering them. It was originally used to inform moderators of non-existing colum names when used for sorting. But on one of the recent commits, I had added a check for allowed colum names. Improved some caching in dashboard page. Added new entries to cookie policy. Some other small things. Bumped v1 version string and rebuilt client assets.
2020-06-01 04:44:16 +00:00
// If we are not listing all albums, send response
if (!all) return res.json({ success: true, albums, count, homeDomain })
Manage albums admin page, and more! Resolves #194. Added pagination for Manage your albums page. Albums sidebar will now only list 9 albums at most. Use Manage your albums page to view the rest. Albums in the list will now have View uploads button after all. Delete album button for albums renamed to Disable album. Since techincally the server would've always been disabling the albums instead of deleting them. It was something upstream dev's decided, and I haven't bothered changing its behavior. I'll work on actual Delete album feature some other days. As the title says, added Manage albums admin page. Viewing uploads of an album will hook into albumid: filter key. I'll work on filter and bulk operations some other days. Updated styling for disabled albums and users. Instead of havine a line through them, they will be greyed out. Disable public page of albums will still use line through however. Links to album's disabled public page are now clickable. Added a new button styling is-dangerish. It'll be orange. Renamed /api/albums/delete to /api/albums/disable. For backwards compatibility, /api/albums/delete will still work but automatically re-routed to /api/albums/disable. /api/uploads/list will no longer print SQLite errors for moderators or higher when encountering them. It was originally used to inform moderators of non-existing colum names when used for sorting. But on one of the recent commits, I had added a check for allowed colum names. Improved some caching in dashboard page. Added new entries to cookie policy. Some other small things. Bumped v1 version string and rebuilt client assets.
2020-06-01 04:44:16 +00:00
// Otherwise proceed to querying usernames
const userids = albums
.map(album => album.userid)
.filter((v, i, a) => {
return v !== null && v !== undefined && v !== '' && a.indexOf(v) === i
})
// If there are no albums attached to a registered user, send response
if (!userids.length) return res.json({ success: true, albums, count, homeDomain })
Manage albums admin page, and more! Resolves #194. Added pagination for Manage your albums page. Albums sidebar will now only list 9 albums at most. Use Manage your albums page to view the rest. Albums in the list will now have View uploads button after all. Delete album button for albums renamed to Disable album. Since techincally the server would've always been disabling the albums instead of deleting them. It was something upstream dev's decided, and I haven't bothered changing its behavior. I'll work on actual Delete album feature some other days. As the title says, added Manage albums admin page. Viewing uploads of an album will hook into albumid: filter key. I'll work on filter and bulk operations some other days. Updated styling for disabled albums and users. Instead of havine a line through them, they will be greyed out. Disable public page of albums will still use line through however. Links to album's disabled public page are now clickable. Added a new button styling is-dangerish. It'll be orange. Renamed /api/albums/delete to /api/albums/disable. For backwards compatibility, /api/albums/delete will still work but automatically re-routed to /api/albums/disable. /api/uploads/list will no longer print SQLite errors for moderators or higher when encountering them. It was originally used to inform moderators of non-existing colum names when used for sorting. But on one of the recent commits, I had added a check for allowed colum names. Improved some caching in dashboard page. Added new entries to cookie policy. Some other small things. Bumped v1 version string and rebuilt client assets.
2020-06-01 04:44:16 +00:00
// Query usernames of user IDs from currently selected files
const usersTable = await utils.db.table('users')
Manage albums admin page, and more! Resolves #194. Added pagination for Manage your albums page. Albums sidebar will now only list 9 albums at most. Use Manage your albums page to view the rest. Albums in the list will now have View uploads button after all. Delete album button for albums renamed to Disable album. Since techincally the server would've always been disabling the albums instead of deleting them. It was something upstream dev's decided, and I haven't bothered changing its behavior. I'll work on actual Delete album feature some other days. As the title says, added Manage albums admin page. Viewing uploads of an album will hook into albumid: filter key. I'll work on filter and bulk operations some other days. Updated styling for disabled albums and users. Instead of havine a line through them, they will be greyed out. Disable public page of albums will still use line through however. Links to album's disabled public page are now clickable. Added a new button styling is-dangerish. It'll be orange. Renamed /api/albums/delete to /api/albums/disable. For backwards compatibility, /api/albums/delete will still work but automatically re-routed to /api/albums/disable. /api/uploads/list will no longer print SQLite errors for moderators or higher when encountering them. It was originally used to inform moderators of non-existing colum names when used for sorting. But on one of the recent commits, I had added a check for allowed colum names. Improved some caching in dashboard page. Added new entries to cookie policy. Some other small things. Bumped v1 version string and rebuilt client assets.
2020-06-01 04:44:16 +00:00
.whereIn('id', userids)
.select('id', 'username')
const users = {}
for (const user of usersTable) {
Manage albums admin page, and more! Resolves #194. Added pagination for Manage your albums page. Albums sidebar will now only list 9 albums at most. Use Manage your albums page to view the rest. Albums in the list will now have View uploads button after all. Delete album button for albums renamed to Disable album. Since techincally the server would've always been disabling the albums instead of deleting them. It was something upstream dev's decided, and I haven't bothered changing its behavior. I'll work on actual Delete album feature some other days. As the title says, added Manage albums admin page. Viewing uploads of an album will hook into albumid: filter key. I'll work on filter and bulk operations some other days. Updated styling for disabled albums and users. Instead of havine a line through them, they will be greyed out. Disable public page of albums will still use line through however. Links to album's disabled public page are now clickable. Added a new button styling is-dangerish. It'll be orange. Renamed /api/albums/delete to /api/albums/disable. For backwards compatibility, /api/albums/delete will still work but automatically re-routed to /api/albums/disable. /api/uploads/list will no longer print SQLite errors for moderators or higher when encountering them. It was originally used to inform moderators of non-existing colum names when used for sorting. But on one of the recent commits, I had added a check for allowed colum names. Improved some caching in dashboard page. Added new entries to cookie policy. Some other small things. Bumped v1 version string and rebuilt client assets.
2020-06-01 04:44:16 +00:00
users[user.id] = user.username
}
Manage albums admin page, and more! Resolves #194. Added pagination for Manage your albums page. Albums sidebar will now only list 9 albums at most. Use Manage your albums page to view the rest. Albums in the list will now have View uploads button after all. Delete album button for albums renamed to Disable album. Since techincally the server would've always been disabling the albums instead of deleting them. It was something upstream dev's decided, and I haven't bothered changing its behavior. I'll work on actual Delete album feature some other days. As the title says, added Manage albums admin page. Viewing uploads of an album will hook into albumid: filter key. I'll work on filter and bulk operations some other days. Updated styling for disabled albums and users. Instead of havine a line through them, they will be greyed out. Disable public page of albums will still use line through however. Links to album's disabled public page are now clickable. Added a new button styling is-dangerish. It'll be orange. Renamed /api/albums/delete to /api/albums/disable. For backwards compatibility, /api/albums/delete will still work but automatically re-routed to /api/albums/disable. /api/uploads/list will no longer print SQLite errors for moderators or higher when encountering them. It was originally used to inform moderators of non-existing colum names when used for sorting. But on one of the recent commits, I had added a check for allowed colum names. Improved some caching in dashboard page. Added new entries to cookie policy. Some other small things. Bumped v1 version string and rebuilt client assets.
2020-06-01 04:44:16 +00:00
await res.json({ success: true, albums, count, users, homeDomain })
Manage albums admin page, and more! Resolves #194. Added pagination for Manage your albums page. Albums sidebar will now only list 9 albums at most. Use Manage your albums page to view the rest. Albums in the list will now have View uploads button after all. Delete album button for albums renamed to Disable album. Since techincally the server would've always been disabling the albums instead of deleting them. It was something upstream dev's decided, and I haven't bothered changing its behavior. I'll work on actual Delete album feature some other days. As the title says, added Manage albums admin page. Viewing uploads of an album will hook into albumid: filter key. I'll work on filter and bulk operations some other days. Updated styling for disabled albums and users. Instead of havine a line through them, they will be greyed out. Disable public page of albums will still use line through however. Links to album's disabled public page are now clickable. Added a new button styling is-dangerish. It'll be orange. Renamed /api/albums/delete to /api/albums/disable. For backwards compatibility, /api/albums/delete will still work but automatically re-routed to /api/albums/disable. /api/uploads/list will no longer print SQLite errors for moderators or higher when encountering them. It was originally used to inform moderators of non-existing colum names when used for sorting. But on one of the recent commits, I had added a check for allowed colum names. Improved some caching in dashboard page. Added new entries to cookie policy. Some other small things. Bumped v1 version string and rebuilt client assets.
2020-06-01 04:44:16 +00:00
} catch (error) {
return apiErrorsHandler(error, req, res, next)
Manage albums admin page, and more! Resolves #194. Added pagination for Manage your albums page. Albums sidebar will now only list 9 albums at most. Use Manage your albums page to view the rest. Albums in the list will now have View uploads button after all. Delete album button for albums renamed to Disable album. Since techincally the server would've always been disabling the albums instead of deleting them. It was something upstream dev's decided, and I haven't bothered changing its behavior. I'll work on actual Delete album feature some other days. As the title says, added Manage albums admin page. Viewing uploads of an album will hook into albumid: filter key. I'll work on filter and bulk operations some other days. Updated styling for disabled albums and users. Instead of havine a line through them, they will be greyed out. Disable public page of albums will still use line through however. Links to album's disabled public page are now clickable. Added a new button styling is-dangerish. It'll be orange. Renamed /api/albums/delete to /api/albums/disable. For backwards compatibility, /api/albums/delete will still work but automatically re-routed to /api/albums/disable. /api/uploads/list will no longer print SQLite errors for moderators or higher when encountering them. It was originally used to inform moderators of non-existing colum names when used for sorting. But on one of the recent commits, I had added a check for allowed colum names. Improved some caching in dashboard page. Added new entries to cookie policy. Some other small things. Bumped v1 version string and rebuilt client assets.
2020-06-01 04:44:16 +00:00
}
}
2017-10-04 00:13:38 +00:00
self.create = async (req, res, next) => {
try {
const user = await utils.authorize(req)
const name = typeof req.body.name === 'string'
? utils.escape(req.body.name.trim().substring(0, self.titleMaxLength))
: ''
if (!name) throw new ClientError('No album name specified.')
const album = await utils.db.table('albums')
.where({
name,
enabled: 1,
userid: user.id
})
.first()
if (album) throw new ClientError('Album name already in use.', { statusCode: 403 })
const identifier = await self.getUniqueRandomName()
const ids = await utils.db.table('albums').insert({
name,
enabled: 1,
userid: user.id,
identifier,
timestamp: Math.floor(Date.now() / 1000),
editedAt: 0,
zipGeneratedAt: 0,
download: (req.body.download === false || req.body.download === 0) ? 0 : 1,
public: (req.body.public === false || req.body.public === 0) ? 0 : 1,
description: typeof req.body.description === 'string'
Updated Updated some dev dependencies. --- Gulp will now build CSS/JS files during development into dist-dev directory, to prevent IDE's Git from unnecessarily building diff's. Added dist-dev to ignore files. --- The entire config fille will now be passed to Nunjuck templates for ease of access of config values. Root domain for use in Nunjuck templates will now be parsed from config. Better page titles. Updated help message for "Uploads history order" option in homepage's config tab. Added "Load images for preview" option to homepage's config tab. Setting this to false will now prevent image uploads from loading themselves for previews. Uploads' original names in homepage's uploads history are now selectable. Min/max length for user/pass are now enforced in auth's front-end. Improved performance of album public pages. Their generated HTML pages will now be cached into memory. Unfortunately, No-JS version of their pages will be cached separately, so each album may take up to double the memory space. File names in thumbnails no longer have their full URLs as tooltips. I saw no point in that behavior. Added video icons. Homepage's uploads history will now display video icons for videos. "View thumbnail" button in Dashboard is now renamed to "Show preview". Their icons will also be changed depending on their file types. Added max length for albums' title & description. These will be enforced both in front-end and back-end. Existing albums that have surpassed the limits will not be enforced. A few other small improvements.
2019-09-17 04:13:41 +00:00
? utils.escape(req.body.description.trim().substring(0, self.descMaxLength))
: ''
More improvements to albums, and others Improvements related to albums: * Changed "rename album" option with a better "edit album" feature. With it you can also disable download or public link and even request a new public link (https://i.fiery.me/fz1y.png). This also adds a new API route: /api/albums/edit. The old API route, /api/albums/rename, is still available but will silently be using the new API in backend. * Deleting album will now also delete its zip archive if exists. * Renaming albums will also rename its zip archive if exists. * Generating zip will use async fs.readFile instead of fs.readFileSync. This should improve generating speed somewhat. * The codes that tries to generate random identifier for album will now check whether an album with the same identifier already exists. It will also rely on "uploads.maxTries" config option to limit how many times it will try to re-generate a new random identifier. * Added a new config option "uploads.albumIdentifierLength" which sets the length of the randomly generated identifier. * Added "download" and "public" columns to "albums" table in database/db.js. Existing users can run "node database/migration.js" to add the columns. Others: * uploadsController.getUniqueRandomName will no longer accept 3 paramters (previously it would accept a callback in the third parameter). It will now instead return a Promise. * Album name of disabled/deleted albums will no longer be shown in uploads list. * Added "fileLength" column to "users" table in database/db.js. * Renamed HTTP404.html and HTTP500.html in /pages/error to 404.html and 500.html respectively. I'm still using symlinks though. * Added a new CSS named sweetalert.css which will be used in homepage, auth and dashboard. It will style all sweetalert modals with dark theme (matching the current color scheme used in this branch). * Updated icons (added download icon). * Some other improvements/tweaks here and there.
2018-04-28 17:26:39 +00:00
})
utils.invalidateStatsCache('albums')
self.onHold.delete(identifier)
2017-10-04 00:13:38 +00:00
await res.json({ success: true, id: ids[0] })
} catch (error) {
return apiErrorsHandler(error, req, res, next)
}
More improvements to albums, and others Improvements related to albums: * Changed "rename album" option with a better "edit album" feature. With it you can also disable download or public link and even request a new public link (https://i.fiery.me/fz1y.png). This also adds a new API route: /api/albums/edit. The old API route, /api/albums/rename, is still available but will silently be using the new API in backend. * Deleting album will now also delete its zip archive if exists. * Renaming albums will also rename its zip archive if exists. * Generating zip will use async fs.readFile instead of fs.readFileSync. This should improve generating speed somewhat. * The codes that tries to generate random identifier for album will now check whether an album with the same identifier already exists. It will also rely on "uploads.maxTries" config option to limit how many times it will try to re-generate a new random identifier. * Added a new config option "uploads.albumIdentifierLength" which sets the length of the randomly generated identifier. * Added "download" and "public" columns to "albums" table in database/db.js. Existing users can run "node database/migration.js" to add the columns. Others: * uploadsController.getUniqueRandomName will no longer accept 3 paramters (previously it would accept a callback in the third parameter). It will now instead return a Promise. * Album name of disabled/deleted albums will no longer be shown in uploads list. * Added "fileLength" column to "users" table in database/db.js. * Renamed HTTP404.html and HTTP500.html in /pages/error to 404.html and 500.html respectively. I'm still using symlinks though. * Added a new CSS named sweetalert.css which will be used in homepage, auth and dashboard. It will style all sweetalert modals with dark theme (matching the current color scheme used in this branch). * Updated icons (added download icon). * Some other improvements/tweaks here and there.
2018-04-28 17:26:39 +00:00
}
self.delete = async (req, res, next) => {
Manage albums admin page, and more! Resolves #194. Added pagination for Manage your albums page. Albums sidebar will now only list 9 albums at most. Use Manage your albums page to view the rest. Albums in the list will now have View uploads button after all. Delete album button for albums renamed to Disable album. Since techincally the server would've always been disabling the albums instead of deleting them. It was something upstream dev's decided, and I haven't bothered changing its behavior. I'll work on actual Delete album feature some other days. As the title says, added Manage albums admin page. Viewing uploads of an album will hook into albumid: filter key. I'll work on filter and bulk operations some other days. Updated styling for disabled albums and users. Instead of havine a line through them, they will be greyed out. Disable public page of albums will still use line through however. Links to album's disabled public page are now clickable. Added a new button styling is-dangerish. It'll be orange. Renamed /api/albums/delete to /api/albums/disable. For backwards compatibility, /api/albums/delete will still work but automatically re-routed to /api/albums/disable. /api/uploads/list will no longer print SQLite errors for moderators or higher when encountering them. It was originally used to inform moderators of non-existing colum names when used for sorting. But on one of the recent commits, I had added a check for allowed colum names. Improved some caching in dashboard page. Added new entries to cookie policy. Some other small things. Bumped v1 version string and rebuilt client assets.
2020-06-01 04:44:16 +00:00
// Map /delete requests to /disable route
req.body.del = true
Manage albums admin page, and more! Resolves #194. Added pagination for Manage your albums page. Albums sidebar will now only list 9 albums at most. Use Manage your albums page to view the rest. Albums in the list will now have View uploads button after all. Delete album button for albums renamed to Disable album. Since techincally the server would've always been disabling the albums instead of deleting them. It was something upstream dev's decided, and I haven't bothered changing its behavior. I'll work on actual Delete album feature some other days. As the title says, added Manage albums admin page. Viewing uploads of an album will hook into albumid: filter key. I'll work on filter and bulk operations some other days. Updated styling for disabled albums and users. Instead of havine a line through them, they will be greyed out. Disable public page of albums will still use line through however. Links to album's disabled public page are now clickable. Added a new button styling is-dangerish. It'll be orange. Renamed /api/albums/delete to /api/albums/disable. For backwards compatibility, /api/albums/delete will still work but automatically re-routed to /api/albums/disable. /api/uploads/list will no longer print SQLite errors for moderators or higher when encountering them. It was originally used to inform moderators of non-existing colum names when used for sorting. But on one of the recent commits, I had added a check for allowed colum names. Improved some caching in dashboard page. Added new entries to cookie policy. Some other small things. Bumped v1 version string and rebuilt client assets.
2020-06-01 04:44:16 +00:00
return self.disable(req, res, next)
}
self.disable = async (req, res, next) => {
try {
const user = await utils.authorize(req)
2017-10-04 00:13:38 +00:00
const ismoderator = perms.is(user, 'moderator')
const id = parseInt(req.body.id)
if (isNaN(id)) throw new ClientError('No album specified.')
const purge = req.body.purge
const del = ismoderator ? req.body.del : false
const filter = function () {
this.where('id', id)
if (!ismoderator) {
this.andWhere({
enabled: 1,
userid: user.id
})
}
}
const album = await utils.db.table('albums')
.where(filter)
.first()
if (!album) {
throw new ClientError('Could not get album with the specified ID.')
}
2017-10-04 00:13:38 +00:00
if (purge) {
const files = await utils.db.table('files')
.where({
albumid: id,
userid: album.userid
})
if (files.length) {
const ids = files.map(file => file.id)
const failed = await utils.bulkDeleteFromDb('id', ids, user)
if (failed.length) return res.json({ success: false, failed })
}
utils.invalidateStatsCache('uploads')
}
if (del) {
await utils.db.table('albums')
.where(filter)
.first()
.del()
} else {
await utils.db.table('albums')
.where(filter)
.first()
.update('enabled', 0)
}
utils.invalidateAlbumsCache([id])
utils.invalidateStatsCache('albums')
try {
await paths.unlink(path.join(paths.zips, `${album.identifier}.zip`))
} catch (error) {
// Re-throw non-ENOENT error
if (error.code !== 'ENOENT') throw error
}
await res.json({ success: true })
} catch (error) {
return apiErrorsHandler(error, req, res, next)
}
}
2017-10-04 00:13:38 +00:00
self.edit = async (req, res, next) => {
try {
const user = await utils.authorize(req)
2017-10-04 00:13:38 +00:00
const ismoderator = perms.is(user, 'moderator')
Manage albums admin page, and more! Resolves #194. Added pagination for Manage your albums page. Albums sidebar will now only list 9 albums at most. Use Manage your albums page to view the rest. Albums in the list will now have View uploads button after all. Delete album button for albums renamed to Disable album. Since techincally the server would've always been disabling the albums instead of deleting them. It was something upstream dev's decided, and I haven't bothered changing its behavior. I'll work on actual Delete album feature some other days. As the title says, added Manage albums admin page. Viewing uploads of an album will hook into albumid: filter key. I'll work on filter and bulk operations some other days. Updated styling for disabled albums and users. Instead of havine a line through them, they will be greyed out. Disable public page of albums will still use line through however. Links to album's disabled public page are now clickable. Added a new button styling is-dangerish. It'll be orange. Renamed /api/albums/delete to /api/albums/disable. For backwards compatibility, /api/albums/delete will still work but automatically re-routed to /api/albums/disable. /api/uploads/list will no longer print SQLite errors for moderators or higher when encountering them. It was originally used to inform moderators of non-existing colum names when used for sorting. But on one of the recent commits, I had added a check for allowed colum names. Improved some caching in dashboard page. Added new entries to cookie policy. Some other small things. Bumped v1 version string and rebuilt client assets.
2020-06-01 04:44:16 +00:00
const id = parseInt(req.body.id)
if (isNaN(id)) throw new ClientError('No album specified.')
2017-10-04 00:13:38 +00:00
const name = typeof req.body.name === 'string'
? utils.escape(req.body.name.trim().substring(0, self.titleMaxLength))
: ''
2017-10-04 00:13:38 +00:00
if (!name) throw new ClientError('No album name specified.')
const filter = function () {
this.where('id', id)
Manage albums admin page, and more! Resolves #194. Added pagination for Manage your albums page. Albums sidebar will now only list 9 albums at most. Use Manage your albums page to view the rest. Albums in the list will now have View uploads button after all. Delete album button for albums renamed to Disable album. Since techincally the server would've always been disabling the albums instead of deleting them. It was something upstream dev's decided, and I haven't bothered changing its behavior. I'll work on actual Delete album feature some other days. As the title says, added Manage albums admin page. Viewing uploads of an album will hook into albumid: filter key. I'll work on filter and bulk operations some other days. Updated styling for disabled albums and users. Instead of havine a line through them, they will be greyed out. Disable public page of albums will still use line through however. Links to album's disabled public page are now clickable. Added a new button styling is-dangerish. It'll be orange. Renamed /api/albums/delete to /api/albums/disable. For backwards compatibility, /api/albums/delete will still work but automatically re-routed to /api/albums/disable. /api/uploads/list will no longer print SQLite errors for moderators or higher when encountering them. It was originally used to inform moderators of non-existing colum names when used for sorting. But on one of the recent commits, I had added a check for allowed colum names. Improved some caching in dashboard page. Added new entries to cookie policy. Some other small things. Bumped v1 version string and rebuilt client assets.
2020-06-01 04:44:16 +00:00
if (!ismoderator) {
this.andWhere({
enabled: 1,
userid: user.id
})
}
}
Manage albums admin page, and more! Resolves #194. Added pagination for Manage your albums page. Albums sidebar will now only list 9 albums at most. Use Manage your albums page to view the rest. Albums in the list will now have View uploads button after all. Delete album button for albums renamed to Disable album. Since techincally the server would've always been disabling the albums instead of deleting them. It was something upstream dev's decided, and I haven't bothered changing its behavior. I'll work on actual Delete album feature some other days. As the title says, added Manage albums admin page. Viewing uploads of an album will hook into albumid: filter key. I'll work on filter and bulk operations some other days. Updated styling for disabled albums and users. Instead of havine a line through them, they will be greyed out. Disable public page of albums will still use line through however. Links to album's disabled public page are now clickable. Added a new button styling is-dangerish. It'll be orange. Renamed /api/albums/delete to /api/albums/disable. For backwards compatibility, /api/albums/delete will still work but automatically re-routed to /api/albums/disable. /api/uploads/list will no longer print SQLite errors for moderators or higher when encountering them. It was originally used to inform moderators of non-existing colum names when used for sorting. But on one of the recent commits, I had added a check for allowed colum names. Improved some caching in dashboard page. Added new entries to cookie policy. Some other small things. Bumped v1 version string and rebuilt client assets.
2020-06-01 04:44:16 +00:00
const album = await utils.db.table('albums')
Manage albums admin page, and more! Resolves #194. Added pagination for Manage your albums page. Albums sidebar will now only list 9 albums at most. Use Manage your albums page to view the rest. Albums in the list will now have View uploads button after all. Delete album button for albums renamed to Disable album. Since techincally the server would've always been disabling the albums instead of deleting them. It was something upstream dev's decided, and I haven't bothered changing its behavior. I'll work on actual Delete album feature some other days. As the title says, added Manage albums admin page. Viewing uploads of an album will hook into albumid: filter key. I'll work on filter and bulk operations some other days. Updated styling for disabled albums and users. Instead of havine a line through them, they will be greyed out. Disable public page of albums will still use line through however. Links to album's disabled public page are now clickable. Added a new button styling is-dangerish. It'll be orange. Renamed /api/albums/delete to /api/albums/disable. For backwards compatibility, /api/albums/delete will still work but automatically re-routed to /api/albums/disable. /api/uploads/list will no longer print SQLite errors for moderators or higher when encountering them. It was originally used to inform moderators of non-existing colum names when used for sorting. But on one of the recent commits, I had added a check for allowed colum names. Improved some caching in dashboard page. Added new entries to cookie policy. Some other small things. Bumped v1 version string and rebuilt client assets.
2020-06-01 04:44:16 +00:00
.where(filter)
.first()
2017-10-04 00:13:38 +00:00
if (!album) {
throw new ClientError('Could not get album with the specified ID.')
}
const albumNewState = (ismoderator && typeof req.body.enabled !== 'undefined')
? Boolean(req.body.enabled)
: null
const nameInUse = await utils.db.table('albums')
.where({
name,
enabled: 1,
userid: user.id
})
.whereNot('id', id)
.first()
if ((album.enabled || (albumNewState === true)) && nameInUse) {
if (req._old) {
// Old rename API (stick with 200 status code for this)
throw new ClientError('You did not specify a new name.', { statusCode: 200 })
} else {
throw new ClientError('Album name already in use.', { statusCode: 403 })
}
}
const update = {
name,
download: Boolean(req.body.download),
public: Boolean(req.body.public),
description: typeof req.body.description === 'string'
? utils.escape(req.body.description.trim().substring(0, self.descMaxLength))
: ''
}
if (albumNewState !== null) {
update.enabled = albumNewState
}
Manage albums admin page, and more! Resolves #194. Added pagination for Manage your albums page. Albums sidebar will now only list 9 albums at most. Use Manage your albums page to view the rest. Albums in the list will now have View uploads button after all. Delete album button for albums renamed to Disable album. Since techincally the server would've always been disabling the albums instead of deleting them. It was something upstream dev's decided, and I haven't bothered changing its behavior. I'll work on actual Delete album feature some other days. As the title says, added Manage albums admin page. Viewing uploads of an album will hook into albumid: filter key. I'll work on filter and bulk operations some other days. Updated styling for disabled albums and users. Instead of havine a line through them, they will be greyed out. Disable public page of albums will still use line through however. Links to album's disabled public page are now clickable. Added a new button styling is-dangerish. It'll be orange. Renamed /api/albums/delete to /api/albums/disable. For backwards compatibility, /api/albums/delete will still work but automatically re-routed to /api/albums/disable. /api/uploads/list will no longer print SQLite errors for moderators or higher when encountering them. It was originally used to inform moderators of non-existing colum names when used for sorting. But on one of the recent commits, I had added a check for allowed colum names. Improved some caching in dashboard page. Added new entries to cookie policy. Some other small things. Bumped v1 version string and rebuilt client assets.
2020-06-01 04:44:16 +00:00
if (req.body.requestLink) {
update.identifier = await self.getUniqueRandomName()
}
await utils.db.table('albums')
Manage albums admin page, and more! Resolves #194. Added pagination for Manage your albums page. Albums sidebar will now only list 9 albums at most. Use Manage your albums page to view the rest. Albums in the list will now have View uploads button after all. Delete album button for albums renamed to Disable album. Since techincally the server would've always been disabling the albums instead of deleting them. It was something upstream dev's decided, and I haven't bothered changing its behavior. I'll work on actual Delete album feature some other days. As the title says, added Manage albums admin page. Viewing uploads of an album will hook into albumid: filter key. I'll work on filter and bulk operations some other days. Updated styling for disabled albums and users. Instead of havine a line through them, they will be greyed out. Disable public page of albums will still use line through however. Links to album's disabled public page are now clickable. Added a new button styling is-dangerish. It'll be orange. Renamed /api/albums/delete to /api/albums/disable. For backwards compatibility, /api/albums/delete will still work but automatically re-routed to /api/albums/disable. /api/uploads/list will no longer print SQLite errors for moderators or higher when encountering them. It was originally used to inform moderators of non-existing colum names when used for sorting. But on one of the recent commits, I had added a check for allowed colum names. Improved some caching in dashboard page. Added new entries to cookie policy. Some other small things. Bumped v1 version string and rebuilt client assets.
2020-06-01 04:44:16 +00:00
.where(filter)
.update(update)
Updated Updated some dev dependencies. --- Gulp will now build CSS/JS files during development into dist-dev directory, to prevent IDE's Git from unnecessarily building diff's. Added dist-dev to ignore files. --- The entire config fille will now be passed to Nunjuck templates for ease of access of config values. Root domain for use in Nunjuck templates will now be parsed from config. Better page titles. Updated help message for "Uploads history order" option in homepage's config tab. Added "Load images for preview" option to homepage's config tab. Setting this to false will now prevent image uploads from loading themselves for previews. Uploads' original names in homepage's uploads history are now selectable. Min/max length for user/pass are now enforced in auth's front-end. Improved performance of album public pages. Their generated HTML pages will now be cached into memory. Unfortunately, No-JS version of their pages will be cached separately, so each album may take up to double the memory space. File names in thumbnails no longer have their full URLs as tooltips. I saw no point in that behavior. Added video icons. Homepage's uploads history will now display video icons for videos. "View thumbnail" button in Dashboard is now renamed to "Show preview". Their icons will also be changed depending on their file types. Added max length for albums' title & description. These will be enforced both in front-end and back-end. Existing albums that have surpassed the limits will not be enforced. A few other small improvements.
2019-09-17 04:13:41 +00:00
utils.invalidateAlbumsCache([id])
Improved albums public page cache and more Removed its dependency towards albums' editedAt property. Editing album's metas (name, description, etc) will no longer update its editedAt property. Instead it will now ONLY be updated when adding/removing files to/from it. Just like how it was meant to be, which was to be used to check whether it's necessary to re-generate their downloadable ZIPs. Albums public page cache will still be properly invalidated when adding/removing files to/from it, as well as after editing their metas. Added views/album-notice.njk to be used to render okay-ish notice when an album's public page is still being generated. I was originally thinking of using it for disabled albums as well, but I refrained from it to reduce the possibility of disabled album IDs from being easily scanned (as it just returns 404 now). Removed invalidatedAt property from stats cache. Instead their caches will immediately be nullified as they should (thus frees up memory slightly as well). Stats cache for albums will now only be cleared when truly necessary. As in, adding/removing files to/from albums will no longer clear them. Updated Nunjucks files to properly use h1, h2, h3 tags in actual hierarchical orders. Elements that don't need to use hX tags will now use P instead. Nothing changes visually, only structurally. Fixed some elements in Nunjucks using single quotes instead of double quotes. They'd have worked the same, but consistency. Added h1 title in FAQ page. Make text for no JS warning a bit bigger, and improved the phrasing a little bit.
2020-06-03 03:44:24 +00:00
utils.invalidateStatsCache('albums')
if (req.body.requestLink) {
self.onHold.delete(update.identifier)
// Rename zip archive of the album if it exists
try {
const oldZip = path.join(paths.zips, `${album.identifier}.zip`)
const newZip = path.join(paths.zips, `${update.identifier}.zip`)
await paths.rename(oldZip, newZip)
} catch (error) {
// Re-throw non-ENOENT error
if (error.code !== 'ENOENT') throw error
}
More improvements to albums, and others Improvements related to albums: * Changed "rename album" option with a better "edit album" feature. With it you can also disable download or public link and even request a new public link (https://i.fiery.me/fz1y.png). This also adds a new API route: /api/albums/edit. The old API route, /api/albums/rename, is still available but will silently be using the new API in backend. * Deleting album will now also delete its zip archive if exists. * Renaming albums will also rename its zip archive if exists. * Generating zip will use async fs.readFile instead of fs.readFileSync. This should improve generating speed somewhat. * The codes that tries to generate random identifier for album will now check whether an album with the same identifier already exists. It will also rely on "uploads.maxTries" config option to limit how many times it will try to re-generate a new random identifier. * Added a new config option "uploads.albumIdentifierLength" which sets the length of the randomly generated identifier. * Added "download" and "public" columns to "albums" table in database/db.js. Existing users can run "node database/migration.js" to add the columns. Others: * uploadsController.getUniqueRandomName will no longer accept 3 paramters (previously it would accept a callback in the third parameter). It will now instead return a Promise. * Album name of disabled/deleted albums will no longer be shown in uploads list. * Added "fileLength" column to "users" table in database/db.js. * Renamed HTTP404.html and HTTP500.html in /pages/error to 404.html and 500.html respectively. I'm still using symlinks though. * Added a new CSS named sweetalert.css which will be used in homepage, auth and dashboard. It will style all sweetalert modals with dark theme (matching the current color scheme used in this branch). * Updated icons (added download icon). * Some other improvements/tweaks here and there.
2018-04-28 17:26:39 +00:00
await res.json({
success: true,
identifier: update.identifier
More improvements to albums, and others Improvements related to albums: * Changed "rename album" option with a better "edit album" feature. With it you can also disable download or public link and even request a new public link (https://i.fiery.me/fz1y.png). This also adds a new API route: /api/albums/edit. The old API route, /api/albums/rename, is still available but will silently be using the new API in backend. * Deleting album will now also delete its zip archive if exists. * Renaming albums will also rename its zip archive if exists. * Generating zip will use async fs.readFile instead of fs.readFileSync. This should improve generating speed somewhat. * The codes that tries to generate random identifier for album will now check whether an album with the same identifier already exists. It will also rely on "uploads.maxTries" config option to limit how many times it will try to re-generate a new random identifier. * Added a new config option "uploads.albumIdentifierLength" which sets the length of the randomly generated identifier. * Added "download" and "public" columns to "albums" table in database/db.js. Existing users can run "node database/migration.js" to add the columns. Others: * uploadsController.getUniqueRandomName will no longer accept 3 paramters (previously it would accept a callback in the third parameter). It will now instead return a Promise. * Album name of disabled/deleted albums will no longer be shown in uploads list. * Added "fileLength" column to "users" table in database/db.js. * Renamed HTTP404.html and HTTP500.html in /pages/error to 404.html and 500.html respectively. I'm still using symlinks though. * Added a new CSS named sweetalert.css which will be used in homepage, auth and dashboard. It will style all sweetalert modals with dark theme (matching the current color scheme used in this branch). * Updated icons (added download icon). * Some other improvements/tweaks here and there.
2018-04-28 17:26:39 +00:00
})
} else {
await res.json({ success: true, name })
}
} catch (error) {
return apiErrorsHandler(error, req, res, next)
More improvements to albums, and others Improvements related to albums: * Changed "rename album" option with a better "edit album" feature. With it you can also disable download or public link and even request a new public link (https://i.fiery.me/fz1y.png). This also adds a new API route: /api/albums/edit. The old API route, /api/albums/rename, is still available but will silently be using the new API in backend. * Deleting album will now also delete its zip archive if exists. * Renaming albums will also rename its zip archive if exists. * Generating zip will use async fs.readFile instead of fs.readFileSync. This should improve generating speed somewhat. * The codes that tries to generate random identifier for album will now check whether an album with the same identifier already exists. It will also rely on "uploads.maxTries" config option to limit how many times it will try to re-generate a new random identifier. * Added a new config option "uploads.albumIdentifierLength" which sets the length of the randomly generated identifier. * Added "download" and "public" columns to "albums" table in database/db.js. Existing users can run "node database/migration.js" to add the columns. Others: * uploadsController.getUniqueRandomName will no longer accept 3 paramters (previously it would accept a callback in the third parameter). It will now instead return a Promise. * Album name of disabled/deleted albums will no longer be shown in uploads list. * Added "fileLength" column to "users" table in database/db.js. * Renamed HTTP404.html and HTTP500.html in /pages/error to 404.html and 500.html respectively. I'm still using symlinks though. * Added a new CSS named sweetalert.css which will be used in homepage, auth and dashboard. It will style all sweetalert modals with dark theme (matching the current color scheme used in this branch). * Updated icons (added download icon). * Some other improvements/tweaks here and there.
2018-04-28 17:26:39 +00:00
}
}
self.rename = async (req, res, next) => {
More improvements to albums, and others Improvements related to albums: * Changed "rename album" option with a better "edit album" feature. With it you can also disable download or public link and even request a new public link (https://i.fiery.me/fz1y.png). This also adds a new API route: /api/albums/edit. The old API route, /api/albums/rename, is still available but will silently be using the new API in backend. * Deleting album will now also delete its zip archive if exists. * Renaming albums will also rename its zip archive if exists. * Generating zip will use async fs.readFile instead of fs.readFileSync. This should improve generating speed somewhat. * The codes that tries to generate random identifier for album will now check whether an album with the same identifier already exists. It will also rely on "uploads.maxTries" config option to limit how many times it will try to re-generate a new random identifier. * Added a new config option "uploads.albumIdentifierLength" which sets the length of the randomly generated identifier. * Added "download" and "public" columns to "albums" table in database/db.js. Existing users can run "node database/migration.js" to add the columns. Others: * uploadsController.getUniqueRandomName will no longer accept 3 paramters (previously it would accept a callback in the third parameter). It will now instead return a Promise. * Album name of disabled/deleted albums will no longer be shown in uploads list. * Added "fileLength" column to "users" table in database/db.js. * Renamed HTTP404.html and HTTP500.html in /pages/error to 404.html and 500.html respectively. I'm still using symlinks though. * Added a new CSS named sweetalert.css which will be used in homepage, auth and dashboard. It will style all sweetalert modals with dark theme (matching the current color scheme used in this branch). * Updated icons (added download icon). * Some other improvements/tweaks here and there.
2018-04-28 17:26:39 +00:00
req._old = true
req.body = { name: req.body.name }
return self.edit(req, res, next)
}
2017-10-04 00:13:38 +00:00
self.get = async (req, res, next) => {
try {
const identifier = req.params.identifier
if (identifier === undefined) {
throw new ClientError('No identifier provided.')
}
const album = await utils.db.table('albums')
.where({
identifier,
enabled: 1
})
.first()
More improvements to albums, and others Improvements related to albums: * Changed "rename album" option with a better "edit album" feature. With it you can also disable download or public link and even request a new public link (https://i.fiery.me/fz1y.png). This also adds a new API route: /api/albums/edit. The old API route, /api/albums/rename, is still available but will silently be using the new API in backend. * Deleting album will now also delete its zip archive if exists. * Renaming albums will also rename its zip archive if exists. * Generating zip will use async fs.readFile instead of fs.readFileSync. This should improve generating speed somewhat. * The codes that tries to generate random identifier for album will now check whether an album with the same identifier already exists. It will also rely on "uploads.maxTries" config option to limit how many times it will try to re-generate a new random identifier. * Added a new config option "uploads.albumIdentifierLength" which sets the length of the randomly generated identifier. * Added "download" and "public" columns to "albums" table in database/db.js. Existing users can run "node database/migration.js" to add the columns. Others: * uploadsController.getUniqueRandomName will no longer accept 3 paramters (previously it would accept a callback in the third parameter). It will now instead return a Promise. * Album name of disabled/deleted albums will no longer be shown in uploads list. * Added "fileLength" column to "users" table in database/db.js. * Renamed HTTP404.html and HTTP500.html in /pages/error to 404.html and 500.html respectively. I'm still using symlinks though. * Added a new CSS named sweetalert.css which will be used in homepage, auth and dashboard. It will style all sweetalert modals with dark theme (matching the current color scheme used in this branch). * Updated icons (added download icon). * Some other improvements/tweaks here and there.
2018-04-28 17:26:39 +00:00
if (!album || album.public === 0) {
throw new ClientError('Album not found.', { statusCode: 404 })
}
2017-10-04 00:13:38 +00:00
const title = album.name
const files = await utils.db.table('files')
.select('name')
.where('albumid', album.id)
.orderBy('id', 'desc')
2017-10-04 00:13:38 +00:00
for (const file of files) {
if (req._upstreamCompat) {
2022-06-22 06:27:38 +00:00
file.url = `${utils.conf.domain}/${file.name}`
} else {
2022-06-22 06:27:38 +00:00
file.file = `${utils.conf.domain}/${file.name}`
}
2017-10-04 00:13:38 +00:00
const extname = utils.extname(file.name)
if (utils.mayGenerateThumb(extname)) {
2022-06-22 06:27:38 +00:00
file.thumb = `${utils.conf.domain}/thumbs/${file.name.slice(0, -extname.length)}.png`
if (req._upstreamCompat) file.thumbSquare = file.thumb
}
}
await res.json({
success: true,
description: 'Successfully retrieved files.',
title,
download: Boolean(album.download),
count: files.length,
files
})
} catch (error) {
return apiErrorsHandler(error, req, res, next)
}
}
self.generateZip = async (req, res, next) => {
try {
const versionString = parseInt(req.query.v)
const identifier = req.params.identifier
if (identifier === undefined) {
throw new ClientError('No identifier provided.')
}
if (!config.uploads.generateZips) {
throw new ClientError('ZIP generation disabled.', { statusCode: 403 })
}
const album = await utils.db.table('albums')
.where({
identifier,
enabled: 1
})
.first()
if (!album) {
throw new ClientError('Album not found.', { statusCode: 404 })
} else if (album.download === 0) {
throw new ClientError('Download for this album is disabled.', { statusCode: 403 })
}
if ((isNaN(versionString) || versionString <= 0) && album.editedAt) {
return res.redirect(`${album.identifier}?v=${album.editedAt}`)
}
if (album.zipGeneratedAt > album.editedAt) {
try {
const filePath = path.join(paths.zips, `${identifier}.zip`)
await paths.access(filePath)
await res.download(filePath, `${album.name}.zip`)
return
} catch (error) {
// Re-throw non-ENOENT error
if (error.code !== 'ENOENT') throw error
}
}
More improvements to albums, and others Improvements related to albums: * Changed "rename album" option with a better "edit album" feature. With it you can also disable download or public link and even request a new public link (https://i.fiery.me/fz1y.png). This also adds a new API route: /api/albums/edit. The old API route, /api/albums/rename, is still available but will silently be using the new API in backend. * Deleting album will now also delete its zip archive if exists. * Renaming albums will also rename its zip archive if exists. * Generating zip will use async fs.readFile instead of fs.readFileSync. This should improve generating speed somewhat. * The codes that tries to generate random identifier for album will now check whether an album with the same identifier already exists. It will also rely on "uploads.maxTries" config option to limit how many times it will try to re-generate a new random identifier. * Added a new config option "uploads.albumIdentifierLength" which sets the length of the randomly generated identifier. * Added "download" and "public" columns to "albums" table in database/db.js. Existing users can run "node database/migration.js" to add the columns. Others: * uploadsController.getUniqueRandomName will no longer accept 3 paramters (previously it would accept a callback in the third parameter). It will now instead return a Promise. * Album name of disabled/deleted albums will no longer be shown in uploads list. * Added "fileLength" column to "users" table in database/db.js. * Renamed HTTP404.html and HTTP500.html in /pages/error to 404.html and 500.html respectively. I'm still using symlinks though. * Added a new CSS named sweetalert.css which will be used in homepage, auth and dashboard. It will style all sweetalert modals with dark theme (matching the current color scheme used in this branch). * Updated icons (added download icon). * Some other improvements/tweaks here and there.
2018-04-28 17:26:39 +00:00
if (self.zipEmitters.has(identifier)) {
logger.log(`Waiting previous zip task for album: ${identifier}.`)
return self.zipEmitters.get(identifier).once('done', (filePath, fileName, clientErr) => {
if (filePath && fileName) {
res.download(filePath, fileName)
} else if (clientErr) {
apiErrorsHandler(clientErr, req, res, next)
}
})
}
self.zipEmitters.set(identifier, new ZipEmitter(identifier))
logger.log(`Starting zip task for album: ${identifier}.`)
More improvements to albums, and others Improvements related to albums: * Changed "rename album" option with a better "edit album" feature. With it you can also disable download or public link and even request a new public link (https://i.fiery.me/fz1y.png). This also adds a new API route: /api/albums/edit. The old API route, /api/albums/rename, is still available but will silently be using the new API in backend. * Deleting album will now also delete its zip archive if exists. * Renaming albums will also rename its zip archive if exists. * Generating zip will use async fs.readFile instead of fs.readFileSync. This should improve generating speed somewhat. * The codes that tries to generate random identifier for album will now check whether an album with the same identifier already exists. It will also rely on "uploads.maxTries" config option to limit how many times it will try to re-generate a new random identifier. * Added a new config option "uploads.albumIdentifierLength" which sets the length of the randomly generated identifier. * Added "download" and "public" columns to "albums" table in database/db.js. Existing users can run "node database/migration.js" to add the columns. Others: * uploadsController.getUniqueRandomName will no longer accept 3 paramters (previously it would accept a callback in the third parameter). It will now instead return a Promise. * Album name of disabled/deleted albums will no longer be shown in uploads list. * Added "fileLength" column to "users" table in database/db.js. * Renamed HTTP404.html and HTTP500.html in /pages/error to 404.html and 500.html respectively. I'm still using symlinks though. * Added a new CSS named sweetalert.css which will be used in homepage, auth and dashboard. It will style all sweetalert modals with dark theme (matching the current color scheme used in this branch). * Updated icons (added download icon). * Some other improvements/tweaks here and there.
2018-04-28 17:26:39 +00:00
const files = await utils.db.table('files')
.select('name', 'size')
.where('albumid', album.id)
if (files.length === 0) {
logger.log(`Finished zip task for album: ${identifier} (no files).`)
const clientErr = new ClientError('There are no files in the album.', { statusCode: 200 })
self.zipEmitters.get(identifier).emit('done', null, null, clientErr)
throw clientErr
}
if (zipMaxTotalSize) {
const totalSizeBytes = files.reduce((accumulator, file) => accumulator + parseInt(file.size), 0)
if (totalSizeBytes > zipMaxTotalSizeBytes) {
logger.log(`Finished zip task for album: ${identifier} (size exceeds).`)
const clientErr = new ClientError(`Total size of all files in the album exceeds ${zipMaxTotalSize} MB limit.`, { statusCode: 403 })
self.zipEmitters.get(identifier).emit('done', null, null, clientErr)
throw clientErr
}
}
const zipPath = path.join(paths.zips, `${album.identifier}.zip`)
const archive = new Zip()
try {
// Since we are adding all files concurrently,
// their order in the ZIP file may not be in alphabetical order.
// However, ZIP viewers in general should sort the files themselves.
await Promise.all(files.map(async file => {
const data = await paths.readFile(path.join(paths.uploads, file.name))
archive.file(file.name, data)
}))
await new Promise((resolve, reject) => {
archive.generateNodeStream(zipOptions)
More improvements to albums, and others Improvements related to albums: * Changed "rename album" option with a better "edit album" feature. With it you can also disable download or public link and even request a new public link (https://i.fiery.me/fz1y.png). This also adds a new API route: /api/albums/edit. The old API route, /api/albums/rename, is still available but will silently be using the new API in backend. * Deleting album will now also delete its zip archive if exists. * Renaming albums will also rename its zip archive if exists. * Generating zip will use async fs.readFile instead of fs.readFileSync. This should improve generating speed somewhat. * The codes that tries to generate random identifier for album will now check whether an album with the same identifier already exists. It will also rely on "uploads.maxTries" config option to limit how many times it will try to re-generate a new random identifier. * Added a new config option "uploads.albumIdentifierLength" which sets the length of the randomly generated identifier. * Added "download" and "public" columns to "albums" table in database/db.js. Existing users can run "node database/migration.js" to add the columns. Others: * uploadsController.getUniqueRandomName will no longer accept 3 paramters (previously it would accept a callback in the third parameter). It will now instead return a Promise. * Album name of disabled/deleted albums will no longer be shown in uploads list. * Added "fileLength" column to "users" table in database/db.js. * Renamed HTTP404.html and HTTP500.html in /pages/error to 404.html and 500.html respectively. I'm still using symlinks though. * Added a new CSS named sweetalert.css which will be used in homepage, auth and dashboard. It will style all sweetalert modals with dark theme (matching the current color scheme used in this branch). * Updated icons (added download icon). * Some other improvements/tweaks here and there.
2018-04-28 17:26:39 +00:00
.pipe(fs.createWriteStream(zipPath))
.on('error', error => reject(error))
.on('finish', () => resolve())
})
} catch (error) {
logger.error(error)
throw new ServerError(error.message)
}
logger.log(`Finished zip task for album: ${identifier} (success).`)
await utils.db.table('albums')
.where('id', album.id)
.update('zipGeneratedAt', Math.floor(Date.now() / 1000))
utils.invalidateStatsCache('albums')
const filePath = path.join(paths.zips, `${identifier}.zip`)
const fileName = `${album.name}.zip`
self.zipEmitters.get(identifier).emit('done', filePath, fileName)
await res.download(filePath, fileName)
} catch (error) {
return apiErrorsHandler(error, req, res, next)
}
}
self.listFiles = async (req, res, next) => {
if (req.params.page === undefined) {
// Map to /api/album/get, but with lolisafe upstream compatibility, when accessed with this API route
req.params.identifier = req.params.id
delete req.params.id
req._upstreamCompat = true
res._json = res.json
res.json = (body = {}) => {
// Rebuild JSON payload to match lolisafe upstream
const rebuild = {}
const maps = {
success: null,
description: 'message',
title: 'name',
download: 'downloadEnabled',
count: null
}
Object.keys(body).forEach(key => {
if (maps[key] !== undefined) {
if (maps[key]) rebuild[maps[key]] = body[key]
} else {
rebuild[key] = body[key]
}
})
if (rebuild.message) rebuild.message = rebuild.message.replace(/\.$/, '')
return res._json(rebuild)
}
return self.get(req, res, next)
} else {
return uploadController.list(req, res, next)
}
}
self.addFiles = async (req, res, next) => {
let ids, albumid, failed, albumids
try {
const user = await utils.authorize(req)
ids = req.body.ids
if (!Array.isArray(ids) || !ids.length) {
throw new ClientError('No files specified.')
}
albumid = parseInt(req.body.albumid)
if (isNaN(albumid) || albumid < 0) albumid = null
failed = []
albumids = []
if (albumid !== null) {
const album = await utils.db.table('albums')
.where('id', albumid)
.where(function () {
if (user.username !== 'root') {
this.where('userid', user.id)
}
})
.first()
if (!album) {
throw new ClientError('Album does not exist or it does not belong to the user.', { statusCode: 404 })
}
albumids.push(albumid)
}
const files = await utils.db.table('files')
.whereIn('id', ids)
.where('userid', user.id)
failed = ids.filter(id => !files.find(file => file.id === id))
await utils.db.table('files')
.whereIn('id', files.map(file => file.id))
.update('albumid', albumid)
utils.invalidateStatsCache('albums')
files.forEach(file => {
if (file.albumid && !albumids.includes(file.albumid)) {
albumids.push(file.albumid)
}
})
await utils.db.table('albums')
.whereIn('id', albumids)
.update('editedAt', Math.floor(Date.now() / 1000))
Improved albums public page cache and more Removed its dependency towards albums' editedAt property. Editing album's metas (name, description, etc) will no longer update its editedAt property. Instead it will now ONLY be updated when adding/removing files to/from it. Just like how it was meant to be, which was to be used to check whether it's necessary to re-generate their downloadable ZIPs. Albums public page cache will still be properly invalidated when adding/removing files to/from it, as well as after editing their metas. Added views/album-notice.njk to be used to render okay-ish notice when an album's public page is still being generated. I was originally thinking of using it for disabled albums as well, but I refrained from it to reduce the possibility of disabled album IDs from being easily scanned (as it just returns 404 now). Removed invalidatedAt property from stats cache. Instead their caches will immediately be nullified as they should (thus frees up memory slightly as well). Stats cache for albums will now only be cleared when truly necessary. As in, adding/removing files to/from albums will no longer clear them. Updated Nunjucks files to properly use h1, h2, h3 tags in actual hierarchical orders. Elements that don't need to use hX tags will now use P instead. Nothing changes visually, only structurally. Fixed some elements in Nunjucks using single quotes instead of double quotes. They'd have worked the same, but consistency. Added h1 title in FAQ page. Make text for no JS warning a bit bigger, and improved the phrasing a little bit.
2020-06-03 03:44:24 +00:00
utils.invalidateAlbumsCache(albumids)
await res.json({ success: true, failed })
} catch (error) {
if (Array.isArray(failed) && (failed.length === ids.length)) {
return apiErrorsHandler(new ServerError(`Could not ${albumid === null ? 'add' : 'remove'} any files ${albumid === null ? 'to' : 'from'} the album.`), req, res, next)
} else {
return apiErrorsHandler(error, req, res, next)
}
}
}
module.exports = self