Cleanup/Formatting

This commit is contained in:
Kieran 2023-10-13 22:04:45 +01:00
parent ef4ca27f4b
commit 0408f77dea
Signed by: Kieran
GPG Key ID: DE71CEB3925BE941
86 changed files with 3940 additions and 2745 deletions

View File

@ -45,7 +45,7 @@ public class UserController : Controller
var requestedId = isMe ? loggedUser!.Value : id.FromBase58Guid();
var user = await _store.Get(requestedId);
if (user == default) return NotFound();
if (loggedUser != requestedId && !user.Flags.HasFlag(UserFlags.PublicProfile))
if (loggedUser != requestedId && !user.Flags.HasFlag(UserFlags.PublicProfile) && !HttpContext.IsRole(Roles.Admin))
return NotFound();
var isMyProfile = requestedId == user.Id;

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,20 @@
#!/usr/bin/env node
const { existsSync } = require(`fs`);
const { createRequire } = require(`module`);
const { resolve } = require(`path`);
const relPnpApiPath = "../../../../.pnp.cjs";
const absPnpApiPath = resolve(__dirname, relPnpApiPath);
const absRequire = createRequire(absPnpApiPath);
if (existsSync(absPnpApiPath)) {
if (!process.versions.pnp) {
// Setup the environment to be able to require eslint
require(absPnpApiPath).setup();
}
}
// Defer to the real eslint your application uses
module.exports = absRequire(`eslint`);

View File

@ -0,0 +1,6 @@
{
"name": "eslint",
"version": "8.51.0-sdk",
"main": "./lib/api.js",
"type": "commonjs"
}

View File

@ -0,0 +1,5 @@
# This file is automatically generated by @yarnpkg/sdks.
# Manual changes might be lost!
integrations:
- vscode

20
VoidCat/spa/.yarn/sdks/prettier/index.js vendored Executable file
View File

@ -0,0 +1,20 @@
#!/usr/bin/env node
const { existsSync } = require(`fs`);
const { createRequire } = require(`module`);
const { resolve } = require(`path`);
const relPnpApiPath = "../../../.pnp.cjs";
const absPnpApiPath = resolve(__dirname, relPnpApiPath);
const absRequire = createRequire(absPnpApiPath);
if (existsSync(absPnpApiPath)) {
if (!process.versions.pnp) {
// Setup the environment to be able to require prettier
require(absPnpApiPath).setup();
}
}
// Defer to the real prettier your application uses
module.exports = absRequire(`prettier`);

View File

@ -0,0 +1,6 @@
{
"name": "prettier",
"version": "3.0.3-sdk",
"main": "./index.js",
"type": "commonjs"
}

View File

@ -0,0 +1,20 @@
#!/usr/bin/env node
const { existsSync } = require(`fs`);
const { createRequire } = require(`module`);
const { resolve } = require(`path`);
const relPnpApiPath = "../../../../.pnp.cjs";
const absPnpApiPath = resolve(__dirname, relPnpApiPath);
const absRequire = createRequire(absPnpApiPath);
if (existsSync(absPnpApiPath)) {
if (!process.versions.pnp) {
// Setup the environment to be able to require typescript/lib/tsc.js
require(absPnpApiPath).setup();
}
}
// Defer to the real typescript/lib/tsc.js your application uses
module.exports = absRequire(`typescript/lib/tsc.js`);

View File

@ -0,0 +1,272 @@
#!/usr/bin/env node
const { existsSync } = require(`fs`);
const { createRequire } = require(`module`);
const { resolve } = require(`path`);
const relPnpApiPath = "../../../../.pnp.cjs";
const absPnpApiPath = resolve(__dirname, relPnpApiPath);
const absRequire = createRequire(absPnpApiPath);
const moduleWrapper = (tsserver) => {
if (!process.versions.pnp) {
return tsserver;
}
const { isAbsolute } = require(`path`);
const pnpApi = require(`pnpapi`);
const isVirtual = (str) => str.match(/\/(\$\$virtual|__virtual__)\//);
const isPortal = (str) => str.startsWith("portal:/");
const normalize = (str) => str.replace(/\\/g, `/`).replace(/^\/?/, `/`);
const dependencyTreeRoots = new Set(
pnpApi.getDependencyTreeRoots().map((locator) => {
return `${locator.name}@${locator.reference}`;
}),
);
// VSCode sends the zip paths to TS using the "zip://" prefix, that TS
// doesn't understand. This layer makes sure to remove the protocol
// before forwarding it to TS, and to add it back on all returned paths.
function toEditorPath(str) {
// We add the `zip:` prefix to both `.zip/` paths and virtual paths
if (
isAbsolute(str) &&
!str.match(/^\^?(zip:|\/zip\/)/) &&
(str.match(/\.zip\//) || isVirtual(str))
) {
// We also take the opportunity to turn virtual paths into physical ones;
// this makes it much easier to work with workspaces that list peer
// dependencies, since otherwise Ctrl+Click would bring us to the virtual
// file instances instead of the real ones.
//
// We only do this to modules owned by the the dependency tree roots.
// This avoids breaking the resolution when jumping inside a vendor
// with peer dep (otherwise jumping into react-dom would show resolution
// errors on react).
//
const resolved = isVirtual(str) ? pnpApi.resolveVirtual(str) : str;
if (resolved) {
const locator = pnpApi.findPackageLocator(resolved);
if (
locator &&
(dependencyTreeRoots.has(`${locator.name}@${locator.reference}`) ||
isPortal(locator.reference))
) {
str = resolved;
}
}
str = normalize(str);
if (str.match(/\.zip\//)) {
switch (hostInfo) {
// Absolute VSCode `Uri.fsPath`s need to start with a slash.
// VSCode only adds it automatically for supported schemes,
// so we have to do it manually for the `zip` scheme.
// The path needs to start with a caret otherwise VSCode doesn't handle the protocol
//
// Ref: https://github.com/microsoft/vscode/issues/105014#issuecomment-686760910
//
// 2021-10-08: VSCode changed the format in 1.61.
// Before | ^zip:/c:/foo/bar.zip/package.json
// After | ^/zip//c:/foo/bar.zip/package.json
//
// 2022-04-06: VSCode changed the format in 1.66.
// Before | ^/zip//c:/foo/bar.zip/package.json
// After | ^/zip/c:/foo/bar.zip/package.json
//
// 2022-05-06: VSCode changed the format in 1.68
// Before | ^/zip/c:/foo/bar.zip/package.json
// After | ^/zip//c:/foo/bar.zip/package.json
//
case `vscode <1.61`:
{
str = `^zip:${str}`;
}
break;
case `vscode <1.66`:
{
str = `^/zip/${str}`;
}
break;
case `vscode <1.68`:
{
str = `^/zip${str}`;
}
break;
case `vscode`:
{
str = `^/zip/${str}`;
}
break;
// To make "go to definition" work,
// We have to resolve the actual file system path from virtual path
// and convert scheme to supported by [vim-rzip](https://github.com/lbrayner/vim-rzip)
case `coc-nvim`:
{
str = normalize(resolved).replace(/\.zip\//, `.zip::`);
str = resolve(`zipfile:${str}`);
}
break;
// Support neovim native LSP and [typescript-language-server](https://github.com/theia-ide/typescript-language-server)
// We have to resolve the actual file system path from virtual path,
// everything else is up to neovim
case `neovim`:
{
str = normalize(resolved).replace(/\.zip\//, `.zip::`);
str = `zipfile://${str}`;
}
break;
default:
{
str = `zip:${str}`;
}
break;
}
} else {
str = str.replace(/^\/?/, process.platform === `win32` ? `` : `/`);
}
}
return str;
}
function fromEditorPath(str) {
switch (hostInfo) {
case `coc-nvim`:
{
str = str.replace(/\.zip::/, `.zip/`);
// The path for coc-nvim is in format of /<pwd>/zipfile:/<pwd>/.yarn/...
// So in order to convert it back, we use .* to match all the thing
// before `zipfile:`
return process.platform === `win32`
? str.replace(/^.*zipfile:\//, ``)
: str.replace(/^.*zipfile:/, ``);
}
break;
case `neovim`:
{
str = str.replace(/\.zip::/, `.zip/`);
// The path for neovim is in format of zipfile:///<pwd>/.yarn/...
return str.replace(/^zipfile:\/\//, ``);
}
break;
case `vscode`:
default:
{
return str.replace(
/^\^?(zip:|\/zip(\/ts-nul-authority)?)\/+/,
process.platform === `win32` ? `` : `/`,
);
}
break;
}
}
// Force enable 'allowLocalPluginLoads'
// TypeScript tries to resolve plugins using a path relative to itself
// which doesn't work when using the global cache
// https://github.com/microsoft/TypeScript/blob/1b57a0395e0bff191581c9606aab92832001de62/src/server/project.ts#L2238
// VSCode doesn't want to enable 'allowLocalPluginLoads' due to security concerns but
// TypeScript already does local loads and if this code is running the user trusts the workspace
// https://github.com/microsoft/vscode/issues/45856
const ConfiguredProject = tsserver.server.ConfiguredProject;
const { enablePluginsWithOptions: originalEnablePluginsWithOptions } =
ConfiguredProject.prototype;
ConfiguredProject.prototype.enablePluginsWithOptions = function () {
this.projectService.allowLocalPluginLoads = true;
return originalEnablePluginsWithOptions.apply(this, arguments);
};
// And here is the point where we hijack the VSCode <-> TS communications
// by adding ourselves in the middle. We locate everything that looks
// like an absolute path of ours and normalize it.
const Session = tsserver.server.Session;
const { onMessage: originalOnMessage, send: originalSend } =
Session.prototype;
let hostInfo = `unknown`;
Object.assign(Session.prototype, {
onMessage(/** @type {string | object} */ message) {
const isStringMessage = typeof message === "string";
const parsedMessage = isStringMessage ? JSON.parse(message) : message;
if (
parsedMessage != null &&
typeof parsedMessage === `object` &&
parsedMessage.arguments &&
typeof parsedMessage.arguments.hostInfo === `string`
) {
hostInfo = parsedMessage.arguments.hostInfo;
if (hostInfo === `vscode` && process.env.VSCODE_IPC_HOOK) {
const [, major, minor] = (
process.env.VSCODE_IPC_HOOK.match(
// The RegExp from https://semver.org/ but without the caret at the start
/(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/,
) ?? []
).map(Number);
if (major === 1) {
if (minor < 61) {
hostInfo += ` <1.61`;
} else if (minor < 66) {
hostInfo += ` <1.66`;
} else if (minor < 68) {
hostInfo += ` <1.68`;
}
}
}
}
const processedMessageJSON = JSON.stringify(
parsedMessage,
(key, value) => {
return typeof value === "string" ? fromEditorPath(value) : value;
},
);
return originalOnMessage.call(
this,
isStringMessage
? processedMessageJSON
: JSON.parse(processedMessageJSON),
);
},
send(/** @type {any} */ msg) {
return originalSend.call(
this,
JSON.parse(
JSON.stringify(msg, (key, value) => {
return typeof value === `string` ? toEditorPath(value) : value;
}),
),
);
},
});
return tsserver;
};
if (existsSync(absPnpApiPath)) {
if (!process.versions.pnp) {
// Setup the environment to be able to require typescript/lib/tsserver.js
require(absPnpApiPath).setup();
}
}
// Defer to the real typescript/lib/tsserver.js your application uses
module.exports = moduleWrapper(absRequire(`typescript/lib/tsserver.js`));

View File

@ -0,0 +1,272 @@
#!/usr/bin/env node
const { existsSync } = require(`fs`);
const { createRequire } = require(`module`);
const { resolve } = require(`path`);
const relPnpApiPath = "../../../../.pnp.cjs";
const absPnpApiPath = resolve(__dirname, relPnpApiPath);
const absRequire = createRequire(absPnpApiPath);
const moduleWrapper = (tsserver) => {
if (!process.versions.pnp) {
return tsserver;
}
const { isAbsolute } = require(`path`);
const pnpApi = require(`pnpapi`);
const isVirtual = (str) => str.match(/\/(\$\$virtual|__virtual__)\//);
const isPortal = (str) => str.startsWith("portal:/");
const normalize = (str) => str.replace(/\\/g, `/`).replace(/^\/?/, `/`);
const dependencyTreeRoots = new Set(
pnpApi.getDependencyTreeRoots().map((locator) => {
return `${locator.name}@${locator.reference}`;
}),
);
// VSCode sends the zip paths to TS using the "zip://" prefix, that TS
// doesn't understand. This layer makes sure to remove the protocol
// before forwarding it to TS, and to add it back on all returned paths.
function toEditorPath(str) {
// We add the `zip:` prefix to both `.zip/` paths and virtual paths
if (
isAbsolute(str) &&
!str.match(/^\^?(zip:|\/zip\/)/) &&
(str.match(/\.zip\//) || isVirtual(str))
) {
// We also take the opportunity to turn virtual paths into physical ones;
// this makes it much easier to work with workspaces that list peer
// dependencies, since otherwise Ctrl+Click would bring us to the virtual
// file instances instead of the real ones.
//
// We only do this to modules owned by the the dependency tree roots.
// This avoids breaking the resolution when jumping inside a vendor
// with peer dep (otherwise jumping into react-dom would show resolution
// errors on react).
//
const resolved = isVirtual(str) ? pnpApi.resolveVirtual(str) : str;
if (resolved) {
const locator = pnpApi.findPackageLocator(resolved);
if (
locator &&
(dependencyTreeRoots.has(`${locator.name}@${locator.reference}`) ||
isPortal(locator.reference))
) {
str = resolved;
}
}
str = normalize(str);
if (str.match(/\.zip\//)) {
switch (hostInfo) {
// Absolute VSCode `Uri.fsPath`s need to start with a slash.
// VSCode only adds it automatically for supported schemes,
// so we have to do it manually for the `zip` scheme.
// The path needs to start with a caret otherwise VSCode doesn't handle the protocol
//
// Ref: https://github.com/microsoft/vscode/issues/105014#issuecomment-686760910
//
// 2021-10-08: VSCode changed the format in 1.61.
// Before | ^zip:/c:/foo/bar.zip/package.json
// After | ^/zip//c:/foo/bar.zip/package.json
//
// 2022-04-06: VSCode changed the format in 1.66.
// Before | ^/zip//c:/foo/bar.zip/package.json
// After | ^/zip/c:/foo/bar.zip/package.json
//
// 2022-05-06: VSCode changed the format in 1.68
// Before | ^/zip/c:/foo/bar.zip/package.json
// After | ^/zip//c:/foo/bar.zip/package.json
//
case `vscode <1.61`:
{
str = `^zip:${str}`;
}
break;
case `vscode <1.66`:
{
str = `^/zip/${str}`;
}
break;
case `vscode <1.68`:
{
str = `^/zip${str}`;
}
break;
case `vscode`:
{
str = `^/zip/${str}`;
}
break;
// To make "go to definition" work,
// We have to resolve the actual file system path from virtual path
// and convert scheme to supported by [vim-rzip](https://github.com/lbrayner/vim-rzip)
case `coc-nvim`:
{
str = normalize(resolved).replace(/\.zip\//, `.zip::`);
str = resolve(`zipfile:${str}`);
}
break;
// Support neovim native LSP and [typescript-language-server](https://github.com/theia-ide/typescript-language-server)
// We have to resolve the actual file system path from virtual path,
// everything else is up to neovim
case `neovim`:
{
str = normalize(resolved).replace(/\.zip\//, `.zip::`);
str = `zipfile://${str}`;
}
break;
default:
{
str = `zip:${str}`;
}
break;
}
} else {
str = str.replace(/^\/?/, process.platform === `win32` ? `` : `/`);
}
}
return str;
}
function fromEditorPath(str) {
switch (hostInfo) {
case `coc-nvim`:
{
str = str.replace(/\.zip::/, `.zip/`);
// The path for coc-nvim is in format of /<pwd>/zipfile:/<pwd>/.yarn/...
// So in order to convert it back, we use .* to match all the thing
// before `zipfile:`
return process.platform === `win32`
? str.replace(/^.*zipfile:\//, ``)
: str.replace(/^.*zipfile:/, ``);
}
break;
case `neovim`:
{
str = str.replace(/\.zip::/, `.zip/`);
// The path for neovim is in format of zipfile:///<pwd>/.yarn/...
return str.replace(/^zipfile:\/\//, ``);
}
break;
case `vscode`:
default:
{
return str.replace(
/^\^?(zip:|\/zip(\/ts-nul-authority)?)\/+/,
process.platform === `win32` ? `` : `/`,
);
}
break;
}
}
// Force enable 'allowLocalPluginLoads'
// TypeScript tries to resolve plugins using a path relative to itself
// which doesn't work when using the global cache
// https://github.com/microsoft/TypeScript/blob/1b57a0395e0bff191581c9606aab92832001de62/src/server/project.ts#L2238
// VSCode doesn't want to enable 'allowLocalPluginLoads' due to security concerns but
// TypeScript already does local loads and if this code is running the user trusts the workspace
// https://github.com/microsoft/vscode/issues/45856
const ConfiguredProject = tsserver.server.ConfiguredProject;
const { enablePluginsWithOptions: originalEnablePluginsWithOptions } =
ConfiguredProject.prototype;
ConfiguredProject.prototype.enablePluginsWithOptions = function () {
this.projectService.allowLocalPluginLoads = true;
return originalEnablePluginsWithOptions.apply(this, arguments);
};
// And here is the point where we hijack the VSCode <-> TS communications
// by adding ourselves in the middle. We locate everything that looks
// like an absolute path of ours and normalize it.
const Session = tsserver.server.Session;
const { onMessage: originalOnMessage, send: originalSend } =
Session.prototype;
let hostInfo = `unknown`;
Object.assign(Session.prototype, {
onMessage(/** @type {string | object} */ message) {
const isStringMessage = typeof message === "string";
const parsedMessage = isStringMessage ? JSON.parse(message) : message;
if (
parsedMessage != null &&
typeof parsedMessage === `object` &&
parsedMessage.arguments &&
typeof parsedMessage.arguments.hostInfo === `string`
) {
hostInfo = parsedMessage.arguments.hostInfo;
if (hostInfo === `vscode` && process.env.VSCODE_IPC_HOOK) {
const [, major, minor] = (
process.env.VSCODE_IPC_HOOK.match(
// The RegExp from https://semver.org/ but without the caret at the start
/(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/,
) ?? []
).map(Number);
if (major === 1) {
if (minor < 61) {
hostInfo += ` <1.61`;
} else if (minor < 66) {
hostInfo += ` <1.66`;
} else if (minor < 68) {
hostInfo += ` <1.68`;
}
}
}
}
const processedMessageJSON = JSON.stringify(
parsedMessage,
(key, value) => {
return typeof value === "string" ? fromEditorPath(value) : value;
},
);
return originalOnMessage.call(
this,
isStringMessage
? processedMessageJSON
: JSON.parse(processedMessageJSON),
);
},
send(/** @type {any} */ msg) {
return originalSend.call(
this,
JSON.parse(
JSON.stringify(msg, (key, value) => {
return typeof value === `string` ? toEditorPath(value) : value;
}),
),
);
},
});
return tsserver;
};
if (existsSync(absPnpApiPath)) {
if (!process.versions.pnp) {
// Setup the environment to be able to require typescript/lib/tsserverlibrary.js
require(absPnpApiPath).setup();
}
}
// Defer to the real typescript/lib/tsserverlibrary.js your application uses
module.exports = moduleWrapper(absRequire(`typescript/lib/tsserverlibrary.js`));

View File

@ -0,0 +1,20 @@
#!/usr/bin/env node
const { existsSync } = require(`fs`);
const { createRequire } = require(`module`);
const { resolve } = require(`path`);
const relPnpApiPath = "../../../../.pnp.cjs";
const absPnpApiPath = resolve(__dirname, relPnpApiPath);
const absRequire = createRequire(absPnpApiPath);
if (existsSync(absPnpApiPath)) {
if (!process.versions.pnp) {
// Setup the environment to be able to require typescript/lib/typescript.js
require(absPnpApiPath).setup();
}
}
// Defer to the real typescript/lib/typescript.js your application uses
module.exports = absRequire(`typescript/lib/typescript.js`);

View File

@ -0,0 +1,6 @@
{
"name": "typescript",
"version": "5.2.2-sdk",
"main": "./lib/typescript.js",
"type": "commonjs"
}

View File

@ -1 +1 @@
yarnPath: .yarn/releases/yarn-3.6.2.cjs
yarnPath: .yarn/releases/yarn-3.6.4.cjs

View File

@ -7,5 +7,10 @@
"build": "yarn workspace @void-cat/api build && yarn workspace @void-cat/app build",
"start": "yarn workspace @void-cat/api build && yarn workspace @void-cat/app start"
},
"packageManager": "yarn@3.6.2"
"packageManager": "yarn@3.6.4",
"devDependencies": {
"eslint": "^8.51.0",
"prettier": "^3.0.3",
"typescript": "^5.2.2"
}
}

View File

@ -66,7 +66,7 @@ export class VoidApi {
stateChange?: StateChangeHandler,
progress?: ProgressHandler,
proxyChallenge?: ProxyChallengeHandler,
chunkSize?: number
chunkSize?: number,
): VoidUploader {
if (StreamUploader.canUse()) {
return new StreamUploader(
@ -76,7 +76,7 @@ export class VoidApi {
progress,
proxyChallenge,
this.#auth,
chunkSize
chunkSize,
);
} else {
return new XHRUploader(
@ -86,7 +86,7 @@ export class VoidApi {
progress,
proxyChallenge,
this.#auth,
chunkSize
chunkSize,
);
}
}
@ -142,7 +142,7 @@ export class VoidApi {
return this.#req<PagedResponse<VoidFileResponse>>(
"POST",
`/user/${uid}/files`,
pageReq
pageReq,
);
}
@ -170,7 +170,7 @@ export class VoidApi {
return this.#req<PagedResponse<VoidFileResponse>>(
"POST",
"/admin/file",
pageReq
pageReq,
);
}
@ -182,7 +182,7 @@ export class VoidApi {
return this.#req<PagedResponse<AdminUserListResult>>(
"POST",
`/admin/users`,
pageReq
pageReq,
);
}

View File

@ -13,7 +13,10 @@ import sjcl from "sjcl";
export const sjclcodec = {
/** Convert from a bitArray to an array of bytes. */
fromBits: function (arr) {
var out = [], bl = sjcl.bitArray.bitLength(arr), i, tmp;
var out = [],
bl = sjcl.bitArray.bitLength(arr),
i,
tmp;
for (i = 0; i < bl / 8; i++) {
if ((i & 3) === 0) {
tmp = arr[i / 4];
@ -26,9 +29,11 @@ export const sjclcodec = {
/** Convert from an array of bytes to a bitArray. */
/** @return {bitArray} */
toBits: function (bytes) {
var out = [], i, tmp = 0;
var out = [],
i,
tmp = 0;
for (i = 0; i < bytes.length; i++) {
tmp = tmp << 8 | bytes[i];
tmp = (tmp << 8) | bytes[i];
if ((i & 3) === 3) {
out.push(tmp);
tmp = 0;
@ -38,5 +43,5 @@ export const sjclcodec = {
out.push(sjcl.bitArray.partial(8 * (i & 3), tmp));
}
return out;
}
},
};

View File

@ -1,9 +1,9 @@
export { VoidApi } from "./api"
export { VoidApi } from "./api";
export { UploadState } from "./upload";
export { StreamEncryption } from "./stream-encryption";
export class ApiError extends Error {
readonly statusCode: number
readonly statusCode: number;
constructor(statusCode: number, msg: string) {
super(msg);
@ -12,165 +12,165 @@ export class ApiError extends Error {
}
export interface LoginSession {
jwt?: string
profile?: Profile
error?: string
jwt?: string;
profile?: Profile;
error?: string;
}
export interface AdminUserListResult {
user: AdminProfile
uploads: number
user: AdminProfile;
uploads: number;
}
export interface Profile {
id: string
avatar?: string
name?: string
created: string
lastLogin: string
roles: Array<string>
publicProfile: boolean
publicUploads: boolean
needsVerification?: boolean
id: string;
avatar?: string;
name?: string;
created: string;
lastLogin: string;
roles: Array<string>;
publicProfile: boolean;
publicUploads: boolean;
needsVerification?: boolean;
}
export interface PagedResponse<T> {
totalResults: number,
results: Array<T>
totalResults: number;
results: Array<T>;
}
export interface AdminProfile extends Profile {
email: string
storage: string
email: string;
storage: string;
}
export interface Bandwidth {
ingress: number
egress: number
ingress: number;
egress: number;
}
export interface BandwidthPoint {
time: string
ingress: number
egress: number
time: string;
ingress: number;
egress: number;
}
export interface SiteInfoResponse {
count: number
totalBytes: number
count: number;
totalBytes: number;
buildInfo: {
version: string
gitHash: string
buildTime: string
}
bandwidth: Bandwidth
fileStores: Array<string>
uploadSegmentSize: number
captchaSiteKey?: string
oAuthProviders: Array<string>
timeSeriesMetrics?: Array<BandwidthPoint>
version: string;
gitHash: string;
buildTime: string;
};
bandwidth: Bandwidth;
fileStores: Array<string>;
uploadSegmentSize: number;
captchaSiteKey?: string;
oAuthProviders: Array<string>;
timeSeriesMetrics?: Array<BandwidthPoint>;
}
export interface PagedRequest {
pageSize: number
page: number
pageSize: number;
page: number;
}
export interface VoidUploadResult {
ok: boolean
file?: VoidFileResponse
errorMessage?: string
ok: boolean;
file?: VoidFileResponse;
errorMessage?: string;
}
export interface VoidFileResponse {
id: string,
metadata?: VoidFileMeta
payment?: Payment
uploader?: Profile
bandwidth?: Bandwidth
virusScan?: VirusScanStatus
id: string;
metadata?: VoidFileMeta;
payment?: Payment;
uploader?: Profile;
bandwidth?: Bandwidth;
virusScan?: VirusScanStatus;
}
export interface VoidFileMeta {
name?: string
description?: string
size: number
uploaded: string
mimeType: string
digest?: string
expires?: string
url?: string
editSecret?: string
encryptionParams?: string
magnetLink?: string
storage: string
name?: string;
description?: string;
size: number;
uploaded: string;
mimeType: string;
digest?: string;
expires?: string;
url?: string;
editSecret?: string;
encryptionParams?: string;
magnetLink?: string;
storage: string;
}
export interface VirusScanStatus {
isVirus: boolean
names?: string
isVirus: boolean;
names?: string;
}
export interface Payment {
service: PaymentServices
required: boolean
currency: PaymentCurrencies
amount: number
strikeHandle?: string
service: PaymentServices;
required: boolean;
currency: PaymentCurrencies;
amount: number;
strikeHandle?: string;
}
export interface SetPaymentConfigRequest {
editSecret: string
currency: PaymentCurrencies
amount: number
strikeHandle?: string
required: boolean
editSecret: string;
currency: PaymentCurrencies;
amount: number;
strikeHandle?: string;
required: boolean;
}
export interface PaymentOrder {
id: string
status: PaymentOrderState
orderLightning?: PaymentOrderLightning
id: string;
status: PaymentOrderState;
orderLightning?: PaymentOrderLightning;
}
export interface PaymentOrderLightning {
invoice: string
expire: string
invoice: string;
expire: string;
}
export interface ApiKey {
id: string
created: string
expiry: string
token: string
id: string;
created: string;
expiry: string;
token: string;
}
export enum PaymentCurrencies {
BTC = 0,
USD = 1,
EUR = 2,
GBP = 3
GBP = 3,
}
export enum PaymentServices {
None = 0,
Strike = 1
Strike = 1,
}
export enum PaymentOrderState {
Unpaid = 0,
Paid = 1,
Expired = 2
Expired = 2,
}
export enum PagedSortBy {
Name = 0,
Date = 1,
Size = 2,
Id = 3
Id = 3,
}
export enum PageSortOrder {
Asc = 0,
Dsc = 1
Dsc = 1,
}

View File

@ -4,8 +4,8 @@ import sjcl, { SjclCipher } from "sjcl";
import { buf2hex } from "./utils";
interface EncryptionParams {
ts: number,
cs: number
ts: number;
cs: number;
}
/**
@ -18,7 +18,11 @@ export class StreamEncryption {
readonly #key: sjcl.BitArray;
readonly #iv: sjcl.BitArray;
constructor(key: string | sjcl.BitArray | undefined, iv: string | sjcl.BitArray | undefined, params?: EncryptionParams | string) {
constructor(
key: string | sjcl.BitArray | undefined,
iv: string | sjcl.BitArray | undefined,
params?: EncryptionParams | string,
) {
if (!key && !iv) {
key = buf2hex(globalThis.crypto.getRandomValues(new Uint8Array(16)));
iv = buf2hex(globalThis.crypto.getRandomValues(new Uint8Array(12)));
@ -34,19 +38,23 @@ export class StreamEncryption {
}
this.#tagSize = params?.ts ?? 128;
this.#chunkSize = params?.cs ?? (1024 * 1024 * 10);
this.#chunkSize = params?.cs ?? 1024 * 1024 * 10;
this.#aes = new sjcl.cipher.aes(key);
this.#key = key;
this.#iv = iv;
console.log(`ts=${this.#tagSize}, cs=${this.#chunkSize}, key=${key}, iv=${this.#iv}`);
console.log(
`ts=${this.#tagSize}, cs=${this.#chunkSize}, key=${key}, iv=${this.#iv}`,
);
}
/**
* Return formatted encryption key
*/
getKey() {
return `${sjcl.codec.hex.fromBits(this.#key)}:${sjcl.codec.hex.fromBits(this.#iv)}`;
return `${sjcl.codec.hex.fromBits(this.#key)}:${sjcl.codec.hex.fromBits(
this.#iv,
)}`;
}
/**
@ -55,8 +63,8 @@ export class StreamEncryption {
getParams() {
return {
ts: this.#tagSize,
cs: this.#chunkSize
}
cs: this.#chunkSize,
};
}
/**
@ -75,21 +83,39 @@ export class StreamEncryption {
_getCryptoStream(mode: number) {
let offset = 0;
let buffer = new Uint8Array(this.#chunkSize + (mode === 1 ? this.#tagSize / 8 : 0));
return new TransformStream({
let buffer = new Uint8Array(
this.#chunkSize + (mode === 1 ? this.#tagSize / 8 : 0),
);
return new TransformStream(
{
transform: async (chunk, controller) => {
chunk = await chunk;
try {
let toBuffer = Math.min(chunk.byteLength, buffer.byteLength - offset);
let toBuffer = Math.min(
chunk.byteLength,
buffer.byteLength - offset,
);
buffer.set(chunk.slice(0, toBuffer), offset);
offset += toBuffer;
if (offset === buffer.byteLength) {
let buff = sjclcodec.toBits(buffer);
let encryptedBuf = sjclcodec.fromBits(
mode === 0 ?
sjcl.mode.gcm.encrypt(this.#aes, buff, this.#iv, [], this.#tagSize) :
sjcl.mode.gcm.decrypt(this.#aes, buff, this.#iv, [], this.#tagSize)
mode === 0
? sjcl.mode.gcm.encrypt(
this.#aes,
buff,
this.#iv,
[],
this.#tagSize,
)
: sjcl.mode.gcm.decrypt(
this.#aes,
buff,
this.#iv,
[],
this.#tagSize,
),
);
controller.enqueue(new Uint8Array(encryptedBuf));
@ -105,14 +131,28 @@ export class StreamEncryption {
let lastBuffer = buffer.slice(0, offset);
let buff = sjclcodec.toBits(lastBuffer);
let encryptedBuf = sjclcodec.fromBits(
mode === 0 ?
sjcl.mode.gcm.encrypt(this.#aes, buff, this.#iv, [], this.#tagSize) :
sjcl.mode.gcm.decrypt(this.#aes, buff, this.#iv, [], this.#tagSize)
mode === 0
? sjcl.mode.gcm.encrypt(
this.#aes,
buff,
this.#iv,
[],
this.#tagSize,
)
: sjcl.mode.gcm.decrypt(
this.#aes,
buff,
this.#iv,
[],
this.#tagSize,
),
);
controller.enqueue(new Uint8Array(encryptedBuf));
}
}, {
highWaterMark: this.#chunkSize
});
},
},
{
highWaterMark: this.#chunkSize,
},
);
}
}

View File

@ -6,9 +6,15 @@ export class StreamUploader extends VoidUploader {
#encrypt?: StreamEncryption;
static canUse() {
const rawUA = globalThis.navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./);
const rawUA = globalThis.navigator.userAgent.match(
/Chrom(e|ium)\/([0-9]+)\./,
);
const majorVersion = rawUA ? parseInt(rawUA[2], 10) : 0;
return majorVersion >= 105 && "getRandomValues" in globalThis.crypto && globalThis.location.protocol === "https:";
return (
majorVersion >= 105 &&
"getRandomValues" in globalThis.crypto &&
globalThis.location.protocol === "https:"
);
}
canEncrypt(): boolean {
@ -24,7 +30,7 @@ export class StreamUploader extends VoidUploader {
}
getEncryptionKey() {
return this.#encrypt?.getKey()
return this.#encrypt?.getKey();
}
async upload(headers?: HeadersInit): Promise<VoidUploadResult> {
@ -33,37 +39,47 @@ export class StreamUploader extends VoidUploader {
let offset = 0;
const DefaultChunkSize = 1024 * 1024;
const rsBase = new ReadableStream({
const rsBase = new ReadableStream(
{
start: async () => {
this.onStateChange?.(UploadState.Uploading);
},
pull: async (controller) => {
const chunk = await this.readChunk(offset, controller.desiredSize ?? DefaultChunkSize);
const chunk = await this.readChunk(
offset,
controller.desiredSize ?? DefaultChunkSize,
);
if (chunk.byteLength === 0) {
controller.close();
return;
}
this.onProgress?.(offset + chunk.byteLength);
offset += chunk.byteLength
offset += chunk.byteLength;
controller.enqueue(chunk);
},
cancel: (reason) => {
console.log(reason);
},
type: "bytes"
}, {
highWaterMark: DefaultChunkSize
});
type: "bytes",
},
{
highWaterMark: DefaultChunkSize,
},
);
const absoluteUrl = `${this.uri}/upload`;
const reqHeaders = {
"Content-Type": "application/octet-stream",
"V-Content-Type": !this.file.type ? "application/octet-stream" : this.file.type,
"V-Content-Type": !this.file.type
? "application/octet-stream"
: this.file.type,
"V-Filename": "name" in this.file ? this.file.name : "",
"V-Full-Digest": hash,
} as Record<string, string>;
if (this.#encrypt) {
reqHeaders["V-EncryptionParams"] = JSON.stringify(this.#encrypt!.getParams());
reqHeaders["V-EncryptionParams"] = JSON.stringify(
this.#encrypt!.getParams(),
);
}
if (this.auth) {
reqHeaders["Authorization"] = await this.auth(absoluteUrl, "POST");
@ -71,17 +87,19 @@ export class StreamUploader extends VoidUploader {
const req = await fetch(absoluteUrl, {
method: "POST",
mode: "cors",
body: this.#encrypt ? rsBase.pipeThrough(this.#encrypt!.getEncryptionTransform()) : rsBase,
body: this.#encrypt
? rsBase.pipeThrough(this.#encrypt!.getEncryptionTransform())
: rsBase,
headers: {
...reqHeaders,
...headers
...headers,
},
// @ts-ignore New stream spec
duplex: 'half'
duplex: "half",
});
if (req.ok) {
return await req.json() as VoidUploadResult;
return (await req.json()) as VoidUploadResult;
} else {
throw new Error("Unknown error");
}

View File

@ -40,7 +40,7 @@ export abstract class VoidUploader {
progress?: ProgressHandler,
proxyChallenge?: ProxyChallengeHandler,
auth?: AuthHandler,
chunkSize?: number
chunkSize?: number,
) {
this.uri = uri;
this.file = file;

View File

@ -1,3 +1,5 @@
export function buf2hex(buffer: number[] | ArrayBuffer) {
return [...new Uint8Array(buffer)].map(x => x.toString(16).padStart(2, '0')).join('');
return [...new Uint8Array(buffer)]
.map((x) => x.toString(16).padStart(2, "0"))
.join("");
}

View File

@ -27,7 +27,7 @@ export class XHRUploader extends VoidUploader {
undefined,
1,
1,
headers
headers,
);
}
}
@ -35,7 +35,7 @@ export class XHRUploader extends VoidUploader {
async #doSplitXHRUpload(
hash: string,
splitSize: number,
headers?: HeadersInit
headers?: HeadersInit,
) {
let xhr: VoidUploadResult | null = null;
const segments = Math.ceil(this.file.size / splitSize);
@ -49,7 +49,7 @@ export class XHRUploader extends VoidUploader {
xhr?.file?.metadata?.editSecret,
s + 1,
segments,
headers
headers,
);
if (!xhr.ok) {
break;
@ -75,7 +75,7 @@ export class XHRUploader extends VoidUploader {
editSecret?: string,
part?: number,
partOf?: number,
headers?: HeadersInit
headers?: HeadersInit,
) {
this.onStateChange?.(UploadState.Uploading);
@ -112,11 +112,11 @@ export class XHRUploader extends VoidUploader {
req.setRequestHeader("Content-Type", "application/octet-stream");
req.setRequestHeader(
"V-Content-Type",
!this.file.type ? "application/octet-stream" : this.file.type
!this.file.type ? "application/octet-stream" : this.file.type,
);
req.setRequestHeader(
"V-Filename",
"name" in this.file ? this.file.name : ""
"name" in this.file ? this.file.name : "",
);
req.setRequestHeader("V-Full-Digest", fullDigest);
req.setRequestHeader("V-Segment", `${part}/${partOf}`);

View File

@ -3,9 +3,9 @@
configure: {
resolve: {
fallback: {
"crypto": false
}
}
}
}
}
crypto: false,
},
},
},
},
};

View File

@ -1,17 +1,17 @@
<!DOCTYPE html>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<link rel="icon" href="%PUBLIC_URL%/favicon.ico"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta name="theme-color" content="#000000"/>
<meta name="description" content="void.cat - free, simple file sharing."/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo.png"/>
<link rel="manifest" href="%PUBLIC_URL%/manifest.json"/>
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta name="description" content="void.cat - free, simple file sharing." />
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo.png" />
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<title>void.cat</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>

View File

@ -1,16 +1,16 @@
import "./Admin.css";
import {useState} from "react";
import {useSelector} from "react-redux";
import {Navigate} from "react-router-dom";
import {AdminProfile} from "@void-cat/api";
import { useState } from "react";
import { useSelector } from "react-redux";
import { Navigate } from "react-router-dom";
import { AdminProfile } from "@void-cat/api";
import {UserList} from "./UserList";
import {VoidButton} from "../Components/Shared/VoidButton";
import { UserList } from "./UserList";
import { VoidButton } from "../Components/Shared/VoidButton";
import VoidModal from "../Components/Shared/VoidModal";
import EditUser from "./EditUser";
import useApi from "Hooks/UseApi";
import {RootState} from "Store";
import { RootState } from "Store";
import ImageGrid from "../Components/Shared/ImageGrid";
export function Admin() {
@ -30,23 +30,28 @@ export function Admin() {
}
if (!auth) {
return <Navigate to="/login"/>;
return <Navigate to="/login" />;
} else {
return (
<div className="admin">
<h2>Users</h2>
<UserList actions={(i) => [
<UserList
actions={(i) => [
<VoidButton key={`delete-${i.id}`}>Delete</VoidButton>,
<VoidButton key={`edit-${i.id}`} onClick={() => setEditUser(i)}>Edit</VoidButton>
]}/>
<VoidButton key={`edit-${i.id}`} onClick={() => setEditUser(i)}>
Edit
</VoidButton>,
]}
/>
<h2>Files</h2>
<ImageGrid loadPage={r => AdminApi.adminListFiles(r)}/>
<ImageGrid loadPage={(r) => AdminApi.adminListFiles(r)} />
{editUser &&
{editUser && (
<VoidModal title="Edit user">
<EditUser user={editUser} onClose={() => setEditUser(undefined)}/>
</VoidModal>}
<EditUser user={editUser} onClose={() => setEditUser(undefined)} />
</VoidModal>
)}
</div>
);
}

View File

@ -1,15 +1,22 @@
import {useState} from "react";
import {useSelector} from "react-redux";
import {AdminProfile} from "@void-cat/api";
import { useState } from "react";
import { useSelector } from "react-redux";
import { AdminProfile } from "@void-cat/api";
import {VoidButton} from "../Components/Shared/VoidButton";
import { VoidButton } from "../Components/Shared/VoidButton";
import useApi from "Hooks/UseApi";
import {RootState} from "Store";
export default function EditUser({user, onClose}: {user: AdminProfile, onClose: () => void}) {
import { RootState } from "Store";
export default function EditUser({
user,
onClose,
}: {
user: AdminProfile;
onClose: () => void;
}) {
const adminApi = useApi();
const fileStores = useSelector((state: RootState) => state.info?.info?.fileStores ?? ["local-disk"])
const fileStores = useSelector(
(state: RootState) => state.info?.info?.fileStores ?? ["local-disk"],
);
const [storage, setStorage] = useState(user.storage);
const [email, setEmail] = useState(user.email);
@ -17,7 +24,7 @@ export default function EditUser({user, onClose}: {user: AdminProfile, onClose:
await adminApi.adminUpdateUser({
...user,
email,
storage
storage,
});
onClose();
}
@ -27,18 +34,32 @@ export default function EditUser({user, onClose}: {user: AdminProfile, onClose:
Editing user '{user.name}' ({user.id})
<dl>
<dt>Email:</dt>
<dd><input type="text" value={email} onChange={(e) => setEmail(e.target.value)}/></dd>
<dd>
<input
type="text"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</dd>
<dt>File storage:</dt>
<dd>
<select value={storage} onChange={(e) => setStorage(e.target.value)}>
<option disabled={true}>Current: {storage}</option>
{fileStores.map(e => <option key={e}>{e}</option>)}
{fileStores.map((e) => (
<option key={e}>{e}</option>
))}
</select>
</dd>
<dt>Roles:</dt>
<dd>{user.roles.map(e => <span className="btn" key={e}>{e}</span>)}</dd>
<dd>
{user.roles.map((e) => (
<span className="btn" key={e}>
{e}
</span>
))}
</dd>
</dl>
<VoidButton onClick={() => updateUser()}>Save</VoidButton>
<VoidButton onClick={() => onClose()}>Cancel</VoidButton>

View File

@ -1,18 +1,25 @@
import {useDispatch} from "react-redux";
import {ReactNode, useEffect, useState} from "react";
import { useDispatch } from "react-redux";
import { ReactNode, useEffect, useState } from "react";
import moment from "moment";
import {AdminProfile, AdminUserListResult, ApiError, PagedResponse, PagedSortBy, PageSortOrder} from "@void-cat/api";
import {
AdminProfile,
AdminUserListResult,
ApiError,
PagedResponse,
PagedSortBy,
PageSortOrder,
} from "@void-cat/api";
import {logout} from "../LoginState";
import {PageSelector} from "../Components/Shared/PageSelector";
import { logout } from "../LoginState";
import { PageSelector } from "../Components/Shared/PageSelector";
import useApi from "Hooks/UseApi";
interface UserListProps {
actions: (u: AdminProfile) => ReactNode
actions: (u: AdminProfile) => ReactNode;
}
export function UserList({actions}: UserListProps) {
export function UserList({ actions }: UserListProps) {
const AdminApi = useApi();
const dispatch = useDispatch();
@ -27,7 +34,7 @@ export function UserList({actions}: UserListProps) {
page: page,
pageSize,
sortBy: PagedSortBy.Date,
sortOrder: PageSortOrder.Dsc
sortOrder: PageSortOrder.Dsc,
};
const rsp = await AdminApi.adminUserList(pageReq);
setUsers(rsp);
@ -46,7 +53,9 @@ export function UserList({actions}: UserListProps) {
function renderUser(r: AdminUserListResult) {
return (
<tr key={r.user.id}>
<td><a href={`/u/${r.user.id}`}>{r.user.name}</a></td>
<td>
<a href={`/u/${r.user.id}`}>{r.user.name}</a>
</td>
<td>{moment(r.user.created).fromNow()}</td>
<td>{moment(r.user.lastLogin).fromNow()}</td>
<td>{r.uploads}</td>
@ -74,17 +83,18 @@ export function UserList({actions}: UserListProps) {
<th>Actions</th>
</tr>
</thead>
<tbody>
{users && users.results.map(renderUser)}
</tbody>
<tbody>{users && users.results.map(renderUser)}</tbody>
<tbody>
<tr>
<td>
{users && <PageSelector
{users && (
<PageSelector
onSelectPage={(x) => setPage(x)}
page={page}
total={users.totalResults}
pageSize={pageSize}/>}
pageSize={pageSize}
/>
)}
</td>
</tr>
</tbody>

View File

@ -1,70 +1,79 @@
import './App.css';
import "./App.css";
import {createBrowserRouter, LoaderFunctionArgs, Outlet, RouterProvider} from "react-router-dom";
import {Provider} from "react-redux";
import {
createBrowserRouter,
LoaderFunctionArgs,
Outlet,
RouterProvider,
} from "react-router-dom";
import { Provider } from "react-redux";
import store from "./Store";
import {FilePreview} from "./Pages/FilePreview";
import {HomePage} from "./Pages/HomePage";
import {Admin} from "./Admin/Admin";
import {UserLogin} from "./Pages/UserLogin";
import {ProfilePage} from "./Pages/Profile";
import {Header} from "./Components/Shared/Header";
import {Donate} from "./Pages/Donate";
import {VoidApi} from "@void-cat/api";
import {ApiHost} from "./Const";
import { FilePreview } from "./Pages/FilePreview";
import { HomePage } from "./Pages/HomePage";
import { Admin } from "./Admin/Admin";
import { UserLogin } from "./Pages/UserLogin";
import { ProfilePage } from "./Pages/Profile";
import { Header } from "./Components/Shared/Header";
import { Donate } from "./Pages/Donate";
import { VoidApi } from "@void-cat/api";
import { ApiHost } from "./Const";
const router = createBrowserRouter([
{
element: <AppLayout/>,
element: <AppLayout />,
children: [
{
path: "/",
element: <HomePage/>
element: <HomePage />,
},
{
path: "/login",
element: <UserLogin/>
element: <UserLogin />,
},
{
path: "/u/:id",
loader: async ({params}: LoaderFunctionArgs) => {
const api = new VoidApi(ApiHost, store.getState().login.jwt);
if(params.id) {
loader: async ({ params }: LoaderFunctionArgs) => {
const state = store.getState();
const api = new VoidApi(ApiHost, state.login.jwt ? () => Promise.resolve(`Bearer ${state.login.jwt}`) : undefined);
if (params.id) {
try {
return await api.getUser(params.id);
} catch (e) {
console.error(e);
}
}
return null;
},
element: <ProfilePage/>
element: <ProfilePage />,
},
{
path: "/admin",
element: <Admin/>
element: <Admin />,
},
{
path: "/:id",
element: <FilePreview/>
element: <FilePreview />,
},
{
path: "/donate",
element: <Donate/>
}
]
}
])
element: <Donate />,
},
],
},
]);
export function AppLayout() {
return (
<div className="app">
<Provider store={store}>
<Header/>
<Outlet/>
<Header />
<Outlet />
</Provider>
</div>
);
}
export default function App() {
return <RouterProvider router={router}/>
return <RouterProvider router={router} />;
}

View File

@ -1,32 +1,45 @@
import "./FileEdit.css";
import {useState} from "react";
import {useSelector} from "react-redux";
import { useState } from "react";
import { useSelector } from "react-redux";
import moment from "moment";
import {PaymentServices, SetPaymentConfigRequest, VoidFileResponse} from "@void-cat/api";
import {
PaymentServices,
SetPaymentConfigRequest,
VoidFileResponse,
} from "@void-cat/api";
import {StrikePaymentConfig} from "./StrikePaymentConfig";
import {NoPaymentConfig} from "./NoPaymentConfig";
import {VoidButton} from "../Shared/VoidButton";
import { StrikePaymentConfig } from "./StrikePaymentConfig";
import { NoPaymentConfig } from "./NoPaymentConfig";
import { VoidButton } from "../Shared/VoidButton";
import useApi from "Hooks/UseApi";
import {RootState} from "Store";
import { RootState } from "Store";
interface FileEditProps {
file: VoidFileResponse
file: VoidFileResponse;
}
export function FileEdit({file}: FileEditProps) {
export function FileEdit({ file }: FileEditProps) {
const Api = useApi();
const profile = useSelector((s: RootState) => s.login.profile);
const [payment, setPayment] = useState(file.payment?.service);
const [name, setName] = useState(file.metadata?.name ?? "");
const [description, setDescription] = useState(file.metadata?.description ?? "");
const [expiry, setExpiry] = useState<number | undefined>(file.metadata?.expires ? moment(file.metadata?.expires).unix() * 1000 : undefined);
const [description, setDescription] = useState(
file.metadata?.description ?? "",
);
const [expiry, setExpiry] = useState<number | undefined>(
file.metadata?.expires
? moment(file.metadata?.expires).unix() * 1000
: undefined,
);
const localFile = window.localStorage.getItem(file.id);
const privateFile: VoidFileResponse = profile?.id === file.uploader?.id
const privateFile: VoidFileResponse =
profile?.id === file.uploader?.id
? file
: localFile ? JSON.parse(localFile) : undefined;
: localFile
? JSON.parse(localFile)
: undefined;
if (!privateFile?.metadata?.editSecret) {
return null;
}
@ -46,7 +59,7 @@ export function FileEdit({file}: FileEditProps) {
name,
description,
editSecret: privateFile?.metadata?.editSecret,
expires: moment(expiry).toISOString()
expires: moment(expiry).toISOString(),
};
await Api.updateFileMetadata(file.id, meta);
}
@ -54,10 +67,21 @@ export function FileEdit({file}: FileEditProps) {
function renderPaymentConfig() {
switch (payment) {
case PaymentServices.None: {
return <NoPaymentConfig privateFile={privateFile} onSaveConfig={savePaymentConfig}/>;
return (
<NoPaymentConfig
privateFile={privateFile}
onSaveConfig={savePaymentConfig}
/>
);
}
case PaymentServices.Strike: {
return <StrikePaymentConfig file={file} privateFile={privateFile} onSaveConfig={savePaymentConfig}/>
return (
<StrikePaymentConfig
file={file}
privateFile={privateFile}
onSaveConfig={savePaymentConfig}
/>
);
}
}
return null;
@ -69,13 +93,28 @@ export function FileEdit({file}: FileEditProps) {
<h3>File info</h3>
<dl>
<dt>Filename:</dt>
<dd><input type="text" value={name} onChange={(e) => setName(e.target.value)}/></dd>
<dd>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</dd>
<dt>Description:</dt>
<dd><input type="text" value={description} onChange={(e) => setDescription(e.target.value)}/></dd>
<dd>
<input
type="text"
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
</dd>
<dt>Expiry</dt>
<dd>
<input type="datetime-local"
value={expiry ? moment(expiry).toISOString().replace("Z", "") : ""}
<input
type="datetime-local"
value={
expiry ? moment(expiry).toISOString().replace("Z", "") : ""
}
max={moment.utc().add(1, "year").toISOString().replace("Z", "")}
min={moment.utc().toISOString().replace("Z", "")}
onChange={(e) => {
@ -84,17 +123,21 @@ export function FileEdit({file}: FileEditProps) {
} else {
setExpiry(undefined);
}
}}/>
}}
/>
</dd>
</dl>
<VoidButton onClick={() => saveMeta()} options={{showSuccess: true}}>
<VoidButton onClick={() => saveMeta()} options={{ showSuccess: true }}>
Save
</VoidButton>
</div>
<div className="flx-1">
<h3>Payment Config</h3>
Type:
<select onChange={(e) => setPayment(parseInt(e.target.value))} value={payment}>
<select
onChange={(e) => setPayment(parseInt(e.target.value))}
value={payment}
>
<option value={0}>None</option>
<option value={1}>Strike</option>
</select>

View File

@ -1,29 +1,36 @@
import React from "react";
import {VoidButton} from "../Shared/VoidButton";
import {PaymentCurrencies, SetPaymentConfigRequest, VoidFileResponse} from "@void-cat/api";
import { VoidButton } from "../Shared/VoidButton";
import {
PaymentCurrencies,
SetPaymentConfigRequest,
VoidFileResponse,
} from "@void-cat/api";
interface NoPaymentConfigProps {
privateFile: VoidFileResponse
onSaveConfig: (c: SetPaymentConfigRequest) => Promise<any>
privateFile: VoidFileResponse;
onSaveConfig: (c: SetPaymentConfigRequest) => Promise<any>;
}
export function NoPaymentConfig({privateFile, onSaveConfig}: NoPaymentConfigProps) {
export function NoPaymentConfig({
privateFile,
onSaveConfig,
}: NoPaymentConfigProps) {
async function saveConfig() {
const cfg = {
editSecret: privateFile.metadata!.editSecret,
required: false,
amount: 0,
currency: PaymentCurrencies.BTC
currency: PaymentCurrencies.BTC,
} as SetPaymentConfigRequest;
await onSaveConfig(cfg)
await onSaveConfig(cfg);
}
return (
<div>
<VoidButton onClick={saveConfig} options={{showSuccess: true}}>
<VoidButton onClick={saveConfig} options={{ showSuccess: true }}>
Save
</VoidButton>
</div>
)
);
}

View File

@ -1,20 +1,30 @@
import {useState} from "react";
import {VoidButton} from "../Shared/VoidButton";
import { useState } from "react";
import { VoidButton } from "../Shared/VoidButton";
import {PaymentCurrencies, SetPaymentConfigRequest, VoidFileResponse} from "@void-cat/api";
import {
PaymentCurrencies,
SetPaymentConfigRequest,
VoidFileResponse,
} from "@void-cat/api";
interface StrikePaymentConfigProps {
file: VoidFileResponse
privateFile: VoidFileResponse
onSaveConfig: (cfg: SetPaymentConfigRequest) => Promise<any>
file: VoidFileResponse;
privateFile: VoidFileResponse;
onSaveConfig: (cfg: SetPaymentConfigRequest) => Promise<any>;
}
export function StrikePaymentConfig({file, privateFile, onSaveConfig}: StrikePaymentConfigProps) {
export function StrikePaymentConfig({
file,
privateFile,
onSaveConfig,
}: StrikePaymentConfigProps) {
const payment = file.payment;
const editSecret = privateFile.metadata!.editSecret;
const [username, setUsername] = useState(payment?.strikeHandle ?? "hrf");
const [currency, setCurrency] = useState(payment?.currency ?? PaymentCurrencies.USD);
const [currency, setCurrency] = useState(
payment?.currency ?? PaymentCurrencies.USD,
);
const [price, setPrice] = useState(payment?.amount ?? 1);
const [required, setRequired] = useState(payment?.required);
@ -24,20 +34,29 @@ export function StrikePaymentConfig({file, privateFile, onSaveConfig}: StrikePay
strikeHandle: username,
currency,
amount: price,
required
required,
} as SetPaymentConfigRequest;
await onSaveConfig(cfg)
await onSaveConfig(cfg);
}
return (
<div>
<dl>
<dt>Strike username:</dt>
<dd><input type="text" value={username} onChange={(e) => setUsername(e.target.value)}/></dd>
<dd>
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
</dd>
<dt>Currency:</dt>
<dd>
<select onChange={(e) => setCurrency(parseInt(e.target.value))} value={currency}>
<select
onChange={(e) => setCurrency(parseInt(e.target.value))}
value={currency}
>
<option value={PaymentCurrencies.BTC}>BTC</option>
<option value={PaymentCurrencies.USD}>USD</option>
<option value={PaymentCurrencies.EUR}>EUR</option>
@ -45,11 +64,23 @@ export function StrikePaymentConfig({file, privateFile, onSaveConfig}: StrikePay
</select>
</dd>
<dt>Price:</dt>
<dd><input type="number" value={price} onChange={(e) => setPrice(Number(e.target.value))}/></dd>
<dd>
<input
type="number"
value={price}
onChange={(e) => setPrice(Number(e.target.value))}
/>
</dd>
<dt>Required:</dt>
<dd><input type="checkbox" checked={required} onChange={(e) => setRequired(e.target.checked)}/></dd>
<dd>
<input
type="checkbox"
checked={required}
onChange={(e) => setRequired(e.target.checked)}
/>
</dd>
</dl>
<VoidButton onClick={saveStrikeConfig} options={{showSuccess: true}}>
<VoidButton onClick={saveStrikeConfig} options={{ showSuccess: true }}>
Save
</VoidButton>
</div>

View File

@ -1,18 +1,18 @@
import "./FilePayment.css";
import {useState} from "react";
import {LightningPayment} from "./LightningPayment";
import {VoidButton} from "../Shared/VoidButton";
import {PaymentOrder, PaymentServices, VoidFileResponse} from "@void-cat/api";
import { useState } from "react";
import { LightningPayment } from "./LightningPayment";
import { VoidButton } from "../Shared/VoidButton";
import { PaymentOrder, PaymentServices, VoidFileResponse } from "@void-cat/api";
import useApi from "Hooks/UseApi";
import {FormatCurrency} from "Util";
import { FormatCurrency } from "Util";
interface FilePaymentProps {
file: VoidFileResponse
onPaid: () => Promise<void>
file: VoidFileResponse;
onPaid: () => Promise<void>;
}
export function FilePayment({file, onPaid}: FilePaymentProps) {
export function FilePayment({ file, onPaid }: FilePaymentProps) {
const Api = useApi();
const paymentKey = `payment-${file.id}`;
const [order, setOrder] = useState<any>();
@ -41,25 +41,31 @@ export function FilePayment({file, onPaid}: FilePaymentProps) {
}
if (!order) {
const amountString = FormatCurrency(file.payment.amount, file.payment.currency);
const amountString = FormatCurrency(
file.payment.amount,
file.payment.currency,
);
if (file.payment.required) {
return (
<div className="payment">
<h3>
You must pay {amountString} to view this file.
</h3>
<h3>You must pay {amountString} to view this file.</h3>
<VoidButton onClick={fetchOrder}>Pay</VoidButton>
</div>
);
} else {
return (
<VoidButton onClick={fetchOrder}>Tip {amountString}</VoidButton>
);
return <VoidButton onClick={fetchOrder}>Tip {amountString}</VoidButton>;
}
} else {
switch (file.payment.service) {
case PaymentServices.Strike: {
return <LightningPayment file={file} order={order} onReset={reset} onPaid={handlePaid}/>;
return (
<LightningPayment
file={file}
order={order}
onReset={reset}
onPaid={handlePaid}
/>
);
}
}
}

View File

@ -1,19 +1,28 @@
import QRCode from "qrcode.react";
import {useEffect} from "react";
import {PaymentOrder, PaymentOrderState, VoidFileResponse} from "@void-cat/api";
import { useEffect } from "react";
import {
PaymentOrder,
PaymentOrderState,
VoidFileResponse,
} from "@void-cat/api";
import {Countdown} from "../Shared/Countdown";
import { Countdown } from "../Shared/Countdown";
import useApi from "Hooks/UseApi";
interface LightningPaymentProps {
file: VoidFileResponse
order: PaymentOrder
onPaid: (s: PaymentOrder) => void
onReset: () => void
file: VoidFileResponse;
order: PaymentOrder;
onPaid: (s: PaymentOrder) => void;
onReset: () => void;
}
export function LightningPayment({file, order, onPaid, onReset}: LightningPaymentProps) {
export function LightningPayment({
file,
order,
onPaid,
onReset,
}: LightningPaymentProps) {
const Api = useApi();
const link = `lightning:${order.orderLightning?.invoice}`;
@ -38,13 +47,12 @@ export function LightningPayment({file, order, onPaid, onReset}: LightningPaymen
return (
<div className="lightning-invoice" onClick={openInvoice}>
<h1>Pay with Lightning </h1>
<QRCode
value={link}
size={512}
includeMargin={true}/>
<QRCode value={link} size={512} includeMargin={true} />
<dl>
<dt>Expires:</dt>
<dd><Countdown to={order.orderLightning!.expire} onEnded={onReset}/></dd>
<dd>
<Countdown to={order.orderLightning!.expire} onEnded={onReset} />
</dd>
</dl>
</div>
);

View File

@ -1,20 +1,20 @@
import {useEffect, useState} from "react";
import { useEffect, useState } from "react";
import "./TextPreview.css";
export function TextPreview({link}: { link: string }) {
export function TextPreview({ link }: { link: string }) {
let [content, setContent] = useState("Loading..");
async function getContent(link: string) {
let req = await fetch(`${link}?t=${new Date().getTime()}`, {
headers: {
"pragma": "no-cache",
"cache-control": "no-cache"
}
pragma: "no-cache",
"cache-control": "no-cache",
},
});
if (req.ok) {
setContent(await req.text());
} else {
setContent("ERROR :(")
setContent("ERROR :(");
}
}
@ -24,7 +24,5 @@ export function TextPreview({link}: { link: string }) {
}
}, [link]);
return (
<pre className="text-preview">{content}</pre>
)
return <pre className="text-preview">{content}</pre>;
}

View File

@ -1,15 +1,15 @@
import "./Dropzone.css";
import {Fragment, useEffect, useState} from "react";
import {FileUpload} from "./FileUpload";
import { Fragment, useEffect, useState } from "react";
import { FileUpload } from "./FileUpload";
export function Dropzone() {
let [files, setFiles] = useState<Array<File>>([]);
function selectFiles() {
let i = document.createElement('input');
i.setAttribute('type', 'file');
i.setAttribute('multiple', '');
i.addEventListener('change', function (evt) {
let i = document.createElement("input");
i.setAttribute("type", "file");
i.setAttribute("multiple", "");
i.addEventListener("change", function (evt) {
if (evt.target && "files" in evt.target) {
setFiles(evt.target.files as Array<File>);
}
@ -22,7 +22,10 @@ export function Dropzone() {
e.stopPropagation();
if ("dataTransfer" in e && (e.dataTransfer?.files?.length ?? 0) > 0) {
setFiles([...e.dataTransfer!.files]);
} else if ("clipboardData" in e && (e.clipboardData?.files?.length ?? 0) > 0) {
} else if (
"clipboardData" in e &&
(e.clipboardData?.files?.length ?? 0) > 0
) {
setFiles([...e.clipboardData!.files]);
}
}
@ -30,13 +33,9 @@ export function Dropzone() {
function renderUploads() {
let fElm = [];
for (let f of files) {
fElm.push(<FileUpload file={f} key={f.name}/>);
fElm.push(<FileUpload file={f} key={f.name} />);
}
return (
<Fragment>
{fElm}
</Fragment>
);
return <Fragment>{fElm}</Fragment>;
}
function renderDrop() {

View File

@ -31,7 +31,7 @@
left: 0;
width: 100vw;
height: 100vh;
background-color: rgba(0,0,0,0.8);
background-color: rgba(0, 0, 0, 0.8);
}
.upload .iframe-challenge iframe {

View File

@ -1,22 +1,22 @@
import "./FileUpload.css";
import {useEffect, useMemo, useState} from "react";
import {useSelector} from "react-redux";
import {UploadState, VoidFileResponse} from "@void-cat/api";
import { useEffect, useMemo, useState } from "react";
import { useSelector } from "react-redux";
import { UploadState, VoidFileResponse } from "@void-cat/api";
import {VoidButton} from "../Shared/VoidButton";
import {useFileTransfer} from "../Shared/FileTransferHook";
import { VoidButton } from "../Shared/VoidButton";
import { useFileTransfer } from "../Shared/FileTransferHook";
import {RootState} from "Store";
import {ConstName, FormatBytes} from "Util";
import { RootState } from "Store";
import { ConstName, FormatBytes } from "Util";
import useApi from "Hooks/UseApi";
interface FileUploadProps {
file: File | Blob
file: File | Blob;
}
export function FileUpload({file}: FileUploadProps) {
export function FileUpload({ file }: FileUploadProps) {
const info = useSelector((s: RootState) => s.info.info);
const {speed, progress, loaded, setFileSize, reset} = useFileTransfer();
const { speed, progress, loaded, setFileSize, reset } = useFileTransfer();
const Api = useApi();
const [result, setResult] = useState<VoidFileResponse>();
const [error, setError] = useState("");
@ -26,7 +26,13 @@ export function FileUpload({file}: FileUploadProps) {
const [encrypt, setEncrypt] = useState(true);
const uploader = useMemo(() => {
return Api.getUploader(file, setUState, loaded, setChallenge, info?.uploadSegmentSize);
return Api.getUploader(
file,
setUState,
loaded,
setChallenge,
info?.uploadSegmentSize,
);
}, [Api, file]);
useEffect(() => {
@ -37,7 +43,7 @@ export function FileUpload({file}: FileUploadProps) {
reset();
setFileSize(file.size);
if (!uploader.canEncrypt() && uState === UploadState.NotStarted) {
startUpload().catch(console.error)
startUpload().catch(console.error);
}
}, [file, uploader, uState]);
@ -50,7 +56,10 @@ export function FileUpload({file}: FileUploadProps) {
setUState(UploadState.Done);
setResult(result.file);
setEncryptionKey(uploader.getEncryptionKey() ?? "");
window.localStorage.setItem(result.file!.id, JSON.stringify(result.file!));
window.localStorage.setItem(
result.file!.id,
JSON.stringify(result.file!),
);
} else {
setUState(UploadState.Failed);
setError(result.errorMessage!);
@ -68,27 +77,44 @@ export function FileUpload({file}: FileUploadProps) {
function renderStatus() {
if (result && uState === UploadState.Done) {
let link = `/${result.id}`;
return (<dl>
return (
<dl>
<dt>Link:</dt>
<dd><a target="_blank" href={link} rel="noreferrer">{result.id}</a></dd>
{encryptionKey ? <>
<dd>
<a target="_blank" href={link} rel="noreferrer">
{result.id}
</a>
</dd>
{encryptionKey ? (
<>
<dt>Encryption Key:</dt>
<dd>
<VoidButton onClick={() => navigator.clipboard.writeText(encryptionKey)}>Copy</VoidButton>
<VoidButton
onClick={() => navigator.clipboard.writeText(encryptionKey)}
>
Copy
</VoidButton>
</dd>
</> : null}
</dl>)
</>
) : null}
</dl>
);
} else if (uState === UploadState.NotStarted) {
return (
<>
<dl>
<dt>Encrypt file:</dt>
<dd><input type="checkbox" checked={encrypt} onChange={(e) => setEncrypt(e.target.checked)}/>
<dd>
<input
type="checkbox"
checked={encrypt}
onChange={(e) => setEncrypt(e.target.checked)}
/>
</dd>
</dl>
<VoidButton onClick={() => startUpload()}>Upload</VoidButton>
</>
)
);
} else {
return (
<dl>
@ -106,7 +132,7 @@ export function FileUpload({file}: FileUploadProps) {
function getChallengeElement() {
let elm = document.createElement("iframe");
elm.contentWindow?.document.write(challenge);
return <div dangerouslySetInnerHTML={{__html: elm.outerHTML}}/>;
return <div dangerouslySetInnerHTML={{ __html: elm.outerHTML }} />;
}
return (
@ -119,13 +145,15 @@ export function FileUpload({file}: FileUploadProps) {
<dd>{FormatBytes(file.size)}</dd>
</dl>
</div>
<div className="status">
{renderStatus()}
</div>
{uState === UploadState.Challenge &&
<div className="iframe-challenge" onClick={() => window.location.reload()}>
<div className="status">{renderStatus()}</div>
{uState === UploadState.Challenge && (
<div
className="iframe-challenge"
onClick={() => window.location.reload()}
>
{getChallengeElement()}
</div>}
</div>
)}
</div>
);
}

View File

@ -1,18 +1,22 @@
import "./FooterLinks.css"
import {useSelector} from "react-redux";
import {Link} from "react-router-dom";
import "./FooterLinks.css";
import { useSelector } from "react-redux";
import { Link } from "react-router-dom";
import {RootState} from "Store";
import { RootState } from "Store";
export function FooterLinks() {
const profile = useSelector((s:RootState) => s.login.profile);
const profile = useSelector((s: RootState) => s.login.profile);
return (
<div className="footer">
<a href="https://discord.gg/8BkxTGs" target="_blank" rel="noreferrer">
Discord
</a>
<a href="https://git.v0l.io/Kieran/void.cat/" target="_blank" rel="noreferrer">
<a
href="https://git.v0l.io/Kieran/void.cat/"
target="_blank"
rel="noreferrer"
>
GitHub
</a>
<Link to="/donate">Donate</Link>

View File

@ -1,11 +1,11 @@
import "./GlobalStats.css";
import {Fragment} from "react";
import { Fragment } from "react";
import moment from "moment";
import {useSelector} from "react-redux";
import { useSelector } from "react-redux";
import Icon from "Components/Shared/Icon";
import {RootState} from "Store";
import {FormatBytes} from "Util";
import { RootState } from "Store";
import { FormatBytes } from "Util";
export function GlobalStats() {
let stats = useSelector((s: RootState) => s.info.info);
@ -14,27 +14,29 @@ export function GlobalStats() {
<Fragment>
<dl className="stats">
<div>
<Icon name="upload-cloud"/>
<Icon name="upload-cloud" />
{FormatBytes(stats?.bandwidth?.ingress ?? 0, 2)}
</div>
<div>
<Icon name="download-cloud"/>
<Icon name="download-cloud" />
{FormatBytes(stats?.bandwidth?.egress ?? 0, 2)}
</div>
<div>
<Icon name="save"/>
<Icon name="save" />
{FormatBytes(stats?.totalBytes ?? 0, 2)}
</div>
<div>
<Icon name="hash"/>
<Icon name="hash" />
{stats?.count ?? 0}
</div>
</dl>
{stats?.buildInfo && <div className="build-info">
{stats?.buildInfo && (
<div className="build-info">
{stats.buildInfo.version}-{stats.buildInfo.gitHash}
<br/>
<br />
{moment(stats.buildInfo.buildTime).fromNow()}
</div>}
</div>
)}
</Fragment>
);
}

View File

@ -1,13 +1,13 @@
import {Bar, BarChart, Tooltip, XAxis} from "recharts";
import { Bar, BarChart, Tooltip, XAxis } from "recharts";
import moment from "moment";
import {BandwidthPoint} from "@void-cat/api";
import { BandwidthPoint } from "@void-cat/api";
import {FormatBytes} from "Util";
import { FormatBytes } from "Util";
interface MetricsGraphProps {
metrics?: Array<BandwidthPoint>
metrics?: Array<BandwidthPoint>;
}
export function MetricsGraph({metrics}: MetricsGraphProps) {
export function MetricsGraph({ metrics }: MetricsGraphProps) {
if (!metrics || metrics.length === 0) return null;
return (
@ -15,12 +15,20 @@ export function MetricsGraph({metrics}: MetricsGraphProps) {
width={Math.min(window.innerWidth, 900)}
height={200}
data={metrics}
margin={{left: 0, right: 0}}
style={{userSelect: "none"}}>
<XAxis dataKey="time" tickFormatter={(v) => `${moment(v).format("DD-MMM")}`}/>
<Bar dataKey="egress" fill="#ccc"/>
<Tooltip formatter={(v) => FormatBytes(v as number)} labelStyle={{color: "#aaa"}} itemStyle={{color: "#eee"}}
contentStyle={{backgroundColor: "#111"}}/>
margin={{ left: 0, right: 0 }}
style={{ userSelect: "none" }}
>
<XAxis
dataKey="time"
tickFormatter={(v) => `${moment(v).format("DD-MMM")}`}
/>
<Bar dataKey="egress" fill="#ccc" />
<Tooltip
formatter={(v) => FormatBytes(v as number)}
labelStyle={{ color: "#aaa" }}
itemStyle={{ color: "#eee" }}
contentStyle={{ backgroundColor: "#111" }}
/>
</BarChart>
);
}

View File

@ -1,8 +1,8 @@
import {useEffect, useState} from "react";
import { useEffect, useState } from "react";
import moment from "moment";
import {ApiKey} from "@void-cat/api";
import { ApiKey } from "@void-cat/api";
import {VoidButton} from "../Shared/VoidButton";
import { VoidButton } from "../Shared/VoidButton";
import VoidModal from "../Shared/VoidModal";
import useApi from "Hooks/UseApi";
@ -25,7 +25,7 @@ export default function ApiKeyList() {
async function createApiKey() {
try {
const rsp = await Api.createApiKey({
expiry: new Date(new Date().getTime() + DefaultExpiry)
expiry: new Date(new Date().getTime() + DefaultExpiry),
});
setNewApiKey(rsp);
} catch (e) {
@ -34,7 +34,7 @@ export default function ApiKeyList() {
}
function openDocs() {
window.open("/swagger", "_blank")
window.open("/swagger", "_blank");
}
useEffect(() => {
@ -62,22 +62,25 @@ export default function ApiKeyList() {
</tr>
</thead>
<tbody>
{apiKeys.map(e => <tr key={e.id}>
{apiKeys.map((e) => (
<tr key={e.id}>
<td>{e.id}</td>
<td>{moment(e.created).fromNow()}</td>
<td>{moment(e.expiry).fromNow()}</td>
<td>
<VoidButton>Delete</VoidButton>
</td>
</tr>)}
</tr>
))}
</tbody>
</table>
{newApiKey &&
<VoidModal title="New Api Key" style={{maxWidth: "50vw"}}>
{newApiKey && (
<VoidModal title="New Api Key" style={{ maxWidth: "50vw" }}>
Please save this now as it will not be shown again:
<pre className="copy">{newApiKey.token}</pre>
<VoidButton onClick={() => setNewApiKey(undefined)}>Close</VoidButton>
</VoidModal>}
</VoidModal>
)}
</>
);
}

View File

@ -1,10 +1,10 @@
import {useEffect, useState} from "react";
import { useEffect, useState } from "react";
interface CountdownProps {
to: number | string | Date
onEnded?: () => void
to: number | string | Date;
onEnded?: () => void;
}
export function Countdown({onEnded, to}: CountdownProps) {
export function Countdown({ onEnded, to }: CountdownProps) {
const [time, setTime] = useState(0);
useEffect(() => {
@ -18,7 +18,7 @@ export function Countdown({onEnded, to}: CountdownProps) {
}
}, 100);
return () => clearInterval(t);
}, [])
}, []);
return <div>{time.toFixed(1)}s</div>
return <div>{time.toFixed(1)}s</div>;
}

View File

@ -1,17 +1,24 @@
import {useDispatch} from "react-redux";
import {ReactNode, useEffect, useState} from "react";
import {Link} from "react-router-dom";
import { useDispatch } from "react-redux";
import { ReactNode, useEffect, useState } from "react";
import { Link } from "react-router-dom";
import moment from "moment";
import {ApiError, PagedRequest, PagedResponse, PagedSortBy, PageSortOrder, VoidFileResponse} from "@void-cat/api";
import {
ApiError,
PagedRequest,
PagedResponse,
PagedSortBy,
PageSortOrder,
VoidFileResponse,
} from "@void-cat/api";
import {logout} from "../../LoginState";
import {PageSelector} from "./PageSelector";
import { logout } from "../../LoginState";
import { PageSelector } from "./PageSelector";
import {FormatBytes} from "Util";
import { FormatBytes } from "Util";
interface FileListProps {
actions?: (f: VoidFileResponse) => ReactNode
loadPage: (req: PagedRequest) => Promise<PagedResponse<any>>
actions?: (f: VoidFileResponse) => ReactNode;
loadPage: (req: PagedRequest) => Promise<PagedResponse<any>>;
}
export function FileList(props: FileListProps) {
@ -29,7 +36,7 @@ export function FileList(props: FileListProps) {
page: page,
pageSize,
sortBy: PagedSortBy.Date,
sortOrder: PageSortOrder.Dsc
sortOrder: PageSortOrder.Dsc,
};
const rsp = await loadPage(pageReq);
setFiles(rsp);
@ -51,8 +58,16 @@ export function FileList(props: FileListProps) {
return (
<tr key={i.id}>
<td><Link to={`/${i.id}`}>{i.id.substring(0, 4)}..</Link></td>
<td>{meta?.name ? (meta?.name.length > 20 ? `${meta?.name.substring(0, 20)}..` : meta?.name) : null}</td>
<td>
<Link to={`/${i.id}`}>{i.id.substring(0, 4)}..</Link>
</td>
<td>
{meta?.name
? meta?.name.length > 20
? `${meta?.name.substring(0, 20)}..`
: meta?.name
: null}
</td>
<td>{meta?.uploaded ? moment(meta?.uploaded).fromNow() : null}</td>
<td>{meta?.size ? FormatBytes(meta?.size, 2) : null}</td>
<td>{bw ? FormatBytes(bw.egress, 2) : null}</td>
@ -62,7 +77,7 @@ export function FileList(props: FileListProps) {
}
useEffect(() => {
loadFileList().catch(console.error)
loadFileList().catch(console.error);
}, [page]);
if (accessDenied) {
@ -82,16 +97,25 @@ export function FileList(props: FileListProps) {
</tr>
</thead>
<tbody>
{files ? files.results.map(a => renderItem(a)) : <tr>
{files ? (
files.results.map((a) => renderItem(a))
) : (
<tr>
<td colSpan={99}>No files</td>
</tr>}
</tr>
)}
</tbody>
<tbody>
<tr>
<td colSpan={999}>
{files &&
<PageSelector onSelectPage={(x) => setPage(x)} page={page} total={files.totalResults}
pageSize={pageSize}/>}
{files && (
<PageSelector
onSelectPage={(x) => setPage(x)}
page={page}
total={files.totalResults}
pageSize={pageSize}
/>
)}
</td>
</tr>
</tbody>

View File

@ -1,5 +1,5 @@
import {useState} from "react";
import {RateCalculator} from "./RateCalculator";
import { useState } from "react";
import { RateCalculator } from "./RateCalculator";
export function useFileTransfer() {
const [speed, setSpeed] = useState(0);
@ -7,7 +7,8 @@ export function useFileTransfer() {
const calc = new RateCalculator();
return {
speed, progress,
speed,
progress,
setFileSize: (size: number) => {
calc.SetFileSize(size);
},
@ -21,6 +22,6 @@ export function useFileTransfer() {
setSpeed(calc.GetSpeed());
setProgress(calc.GetProgress());
},
reset: () => calc.Reset()
}
reset: () => calc.Reset(),
};
}

View File

@ -1,21 +1,21 @@
import "./Header.css";
import VoidCat from "../../image/voidcat.png";
import {useEffect} from "react";
import {Link} from "react-router-dom";
import {useDispatch, useSelector} from "react-redux";
import { useEffect } from "react";
import { Link } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import {InlineProfile} from "./InlineProfile";
import {logout, setAuth, setProfile} from "../../LoginState";
import {setInfo} from "../../SiteInfoStore";
import { InlineProfile } from "./InlineProfile";
import { logout, setAuth, setProfile } from "../../LoginState";
import { setInfo } from "../../SiteInfoStore";
import useApi from "Hooks/UseApi";
import {RootState} from "Store";
import { RootState } from "Store";
export function Header() {
const dispatch = useDispatch();
const jwt = useSelector((s: RootState) => s.login.jwt);
const profile = useSelector((s: RootState) => s.login.profile)
const profile = useSelector((s: RootState) => s.login.profile);
const Api = useApi();
async function initProfile() {
@ -27,10 +27,15 @@ export function Header() {
console.error(e);
dispatch(logout());
}
} else if (window.location.pathname === "/login" && window.location.hash.length > 1) {
dispatch(setAuth({
jwt: window.location.hash.substring(1)
}));
} else if (
window.location.pathname === "/login" &&
window.location.hash.length > 1
) {
dispatch(
setAuth({
jwt: window.location.hash.substring(1),
}),
);
}
}
@ -46,20 +51,22 @@ export function Header() {
return (
<div className="header page">
<img src={VoidCat} alt="logo" className="logo"/>
<img src={VoidCat} alt="logo" className="logo" />
<div className="title">
<Link to="/">
{window.location.hostname}
</Link>
<Link to="/">{window.location.hostname}</Link>
</div>
{profile ?
<InlineProfile profile={profile} options={{
showName: false
}}/> :
{profile ? (
<InlineProfile
profile={profile}
options={{
showName: false,
}}
/>
) : (
<Link to="/login">
<div className="btn">Login</div>
</Link>}
</Link>
)}
</div>
)
);
}

View File

@ -12,7 +12,12 @@ const Icon = (props: Props) => {
const href = "/icons.svg#" + props.name;
return (
<svg width={size} height={size} className={props.className} onClick={props.onClick}>
<svg
width={size}
height={size}
className={props.className}
onClick={props.onClick}
>
<use href={href} />
</svg>
);

View File

@ -14,7 +14,9 @@
height: 150px;
}
.image-grid img, .image-grid video, .image-grid audio {
.image-grid img,
.image-grid video,
.image-grid audio {
max-width: stretch;
max-height: stretch;
}

View File

@ -1,15 +1,22 @@
import "./ImageGrid.css";
import {ApiError, PagedRequest, PagedResponse, PagedSortBy, PageSortOrder, VoidFileResponse} from "@void-cat/api";
import {useEffect, useState} from "react";
import {Link} from "react-router-dom";
import {useDispatch} from "react-redux";
import {
ApiError,
PagedRequest,
PagedResponse,
PagedSortBy,
PageSortOrder,
VoidFileResponse,
} from "@void-cat/api";
import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { useDispatch } from "react-redux";
import {logout} from "../../LoginState";
import {PageSelector} from "./PageSelector";
import { logout } from "../../LoginState";
import { PageSelector } from "./PageSelector";
interface ImageGridProps {
loadPage: (req: PagedRequest) => Promise<PagedResponse<any>>
loadPage: (req: PagedRequest) => Promise<PagedResponse<any>>;
}
export default function ImageGrid(props: ImageGridProps) {
@ -26,7 +33,7 @@ export default function ImageGrid(props: ImageGridProps) {
page: page,
pageSize,
sortBy: PagedSortBy.Date,
sortOrder: PageSortOrder.Dsc
sortOrder: PageSortOrder.Dsc,
};
const rsp = await loadPage(pageReq);
setFiles(rsp);
@ -43,7 +50,7 @@ export default function ImageGrid(props: ImageGridProps) {
}
useEffect(() => {
loadFileList().catch(console.error)
loadFileList().catch(console.error);
}, [page]);
function renderPreview(info: VoidFileResponse) {
@ -60,7 +67,7 @@ export default function ImageGrid(props: ImageGridProps) {
case "image/jpg":
case "image/jpeg":
case "image/png": {
return <img src={link} alt={info.metadata.name}/>;
return <img src={link} alt={info.metadata.name} />;
}
case "audio/aac":
case "audio/opus":
@ -69,7 +76,7 @@ export default function ImageGrid(props: ImageGridProps) {
case "audio/midi":
case "audio/mpeg":
case "audio/ogg": {
return <audio src={link}/>;
return <audio src={link} />;
}
case "video/x-msvideo":
case "video/mpeg":
@ -80,26 +87,34 @@ export default function ImageGrid(props: ImageGridProps) {
case "video/x-matroska":
case "video/webm":
case "video/quicktime": {
return <video src={link}/>;
return <video src={link} />;
}
default: {
return <b>{info.metadata?.name ?? info.id}</b>
return <b>{info.metadata?.name ?? info.id}</b>;
}
}
}
}
if (accessDenied) {
return <h3>Access Denied</h3>
return <h3>Access Denied</h3>;
}
return <>
return (
<>
<div className="image-grid">
{files?.results.map(v => <Link key={v.id} to={`/${v.id}`}>
{files?.results.map((v) => (
<Link key={v.id} to={`/${v.id}`}>
{renderPreview(v)}
</Link>)}
</Link>
))}
</div>
<PageSelector onSelectPage={(x) => setPage(x)} page={page} total={files?.totalResults ?? 0}
pageSize={pageSize}/>
<PageSelector
onSelectPage={(x) => setPage(x)}
page={page}
total={files?.totalResults ?? 0}
pageSize={pageSize}
/>
</>
);
}

View File

@ -1,4 +1,3 @@
.small-profile {
display: inline-flex;
align-items: center;

View File

@ -1,27 +1,27 @@
import "./InlineProfile.css";
import {CSSProperties} from "react";
import {Link} from "react-router-dom";
import {Profile} from "@void-cat/api";
import { CSSProperties } from "react";
import { Link } from "react-router-dom";
import { Profile } from "@void-cat/api";
import {DefaultAvatar} from "Const";
import { DefaultAvatar } from "Const";
const DefaultSize = 64;
interface InlineProfileProps {
profile: Profile
profile: Profile;
options?: {
size?: number
showName?: boolean
link?: boolean
}
size?: number;
showName?: boolean;
link?: boolean;
};
}
export function InlineProfile({profile, options}: InlineProfileProps) {
export function InlineProfile({ profile, options }: InlineProfileProps) {
options = {
size: DefaultSize,
showName: true,
link: true,
...options
...options,
};
let avatarUrl = profile.avatar ?? DefaultAvatar;
@ -29,7 +29,7 @@ export function InlineProfile({profile, options}: InlineProfileProps) {
avatarUrl = `/d/${avatarUrl}`;
}
let avatarStyles = {
backgroundImage: `url(${avatarUrl})`
backgroundImage: `url(${avatarUrl})`,
} as CSSProperties;
if (options.size !== DefaultSize) {
avatarStyles.width = `${options.size}px`;
@ -38,12 +38,12 @@ export function InlineProfile({profile, options}: InlineProfileProps) {
const elms = (
<div className="small-profile">
<div className="avatar" style={avatarStyles}/>
<div className="avatar" style={avatarStyles} />
{options.showName ? <div className="name">{profile.name}</div> : null}
</div>
);
if (options.link === true) {
return <Link to={`/u/${profile.id}`}>{elms}</Link>
return <Link to={`/u/${profile.id}`}>{elms}</Link>;
}
return elms;
}

View File

@ -1,13 +1,13 @@
import {useState} from "react";
import {useDispatch, useSelector} from "react-redux";
import { useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import HCaptcha from "@hcaptcha/react-hcaptcha";
import "./Login.css";
import {setAuth} from "../../LoginState";
import {VoidButton} from "./VoidButton";
import { setAuth } from "../../LoginState";
import { VoidButton } from "./VoidButton";
import useApi from "Hooks/UseApi";
import {RootState} from "Store";
import { RootState } from "Store";
export function Login() {
const Api = useApi();
@ -16,7 +16,9 @@ export function Login() {
const [error, setError] = useState("");
const [captchaResponse, setCaptchaResponse] = useState("");
const captchaKey = useSelector((s: RootState) => s.info.info?.captchaSiteKey);
const oAuthProviders = useSelector((s: RootState) => s.info.info?.oAuthProviders);
const oAuthProviders = useSelector(
(s: RootState) => s.info.info?.oAuthProviders,
);
const dispatch = useDispatch();
async function login(fnLogin: typeof Api.login) {
@ -25,10 +27,12 @@ export function Login() {
try {
const rsp = await fnLogin(username, password, captchaResponse);
if (rsp.jwt) {
dispatch(setAuth({
dispatch(
setAuth({
jwt: rsp.jwt,
profile: rsp.profile!
}));
profile: rsp.profile!,
}),
);
} else {
setError(rsp.error!);
}
@ -44,20 +48,44 @@ export function Login() {
<h2>Login</h2>
<dl>
<dt>Username:</dt>
<dd><input type="text" placeholder="user@example.com" onChange={(e) => setUsername(e.target.value)}
value={username}/>
<dd>
<input
type="text"
placeholder="user@example.com"
onChange={(e) => setUsername(e.target.value)}
value={username}
/>
</dd>
<dt>Password:</dt>
<dd><input type="password" onChange={(e) => setPassword(e.target.value)} value={password}/></dd>
<dd>
<input
type="password"
onChange={(e) => setPassword(e.target.value)}
value={password}
/>
</dd>
</dl>
{captchaKey ? <HCaptcha sitekey={captchaKey} onVerify={v => setCaptchaResponse(v)}/> : null}
{captchaKey ? (
<HCaptcha
sitekey={captchaKey}
onVerify={(v) => setCaptchaResponse(v)}
/>
) : null}
<VoidButton onClick={() => login(Api.login.bind(Api))}>Login</VoidButton>
<VoidButton onClick={() => login(Api.register.bind(Api))}>Register</VoidButton>
<br/>
{oAuthProviders ?
oAuthProviders.map(a => <VoidButton key={a} onClick={() => window.location.href = `/auth/${a}`}>
<VoidButton onClick={() => login(Api.register.bind(Api))}>
Register
</VoidButton>
<br />
{oAuthProviders
? oAuthProviders.map((a) => (
<VoidButton
key={a}
onClick={() => (window.location.href = `/auth/${a}`)}
>
Login with {a}
</VoidButton>) : null}
</VoidButton>
))
: null}
{error && <div className="error-msg">{error}</div>}
</div>
);

View File

@ -32,4 +32,3 @@
line-height: 32px;
margin-left: 10px;
}

View File

@ -1,13 +1,13 @@
import "./PageSelector.css";
interface PageSelectorProps {
total: number
pageSize: number
page: number
onSelectPage?: (v: number) => void
total: number;
pageSize: number;
page: number;
onSelectPage?: (v: number) => void;
options?: {
showPages: number
}
showPages: number;
};
}
export function PageSelector(props: PageSelectorProps) {
@ -17,19 +17,28 @@ export function PageSelector(props: PageSelectorProps) {
const onSelectPage = props.onSelectPage;
const options = {
showPages: 3,
...props.options
...props.options,
};
const totalPages = Math.floor(total / pageSize);
const first = Math.max(0, page - options.showPages);
const firstDiff = page - first;
const last = Math.min(totalPages, page + options.showPages + options.showPages - firstDiff);
const last = Math.min(
totalPages,
page + options.showPages + options.showPages - firstDiff,
);
const buttons = [];
for (let x = first; x <= last; x++) {
buttons.push(<div onClick={() => onSelectPage?.(x)} key={x} className={page === x ? "active" : ""}>
buttons.push(
<div
onClick={() => onSelectPage?.(x)}
key={x}
className={page === x ? "active" : ""}
>
{x + 1}
</div>);
</div>,
);
}
return (

View File

@ -1,6 +1,6 @@
interface RateReport {
time: number
amount: number
time: number;
amount: number;
}
export class RateCalculator {
@ -36,7 +36,7 @@ export class RateCalculator {
ReportProgress(amount: number) {
this.#reports.push({
time: new Date().getTime(),
amount
amount,
});
this.#lastLoaded += amount;
this.#progress = this.#lastLoaded / this.#fileSize;
@ -46,7 +46,7 @@ export class RateCalculator {
ReportLoaded(loaded: number) {
this.#reports.push({
time: new Date().getTime(),
amount: loaded - this.#lastLoaded
amount: loaded - this.#lastLoaded,
});
this.#lastLoaded = loaded;
this.#progress = this.#lastLoaded / this.#fileSize;
@ -56,7 +56,7 @@ export class RateCalculator {
RateWindow(s: number) {
let total = 0.0;
const windowStart = new Date().getTime() - (s * 1000);
const windowStart = new Date().getTime() - s * 1000;
for (let r of this.#reports) {
if (r.time >= windowStart) {
total += r.amount;

View File

@ -1,18 +1,18 @@
import React, {MouseEvent, ReactNode, useEffect, useState} from "react";
import React, { MouseEvent, ReactNode, useEffect, useState } from "react";
import Icon from "./Icon";
interface VoidButtonProps {
onClick?: (e: MouseEvent<HTMLDivElement>) => Promise<unknown> | unknown
onClick?: (e: MouseEvent<HTMLDivElement>) => Promise<unknown> | unknown;
options?: {
showSuccess: boolean
}
children: ReactNode
showSuccess: boolean;
};
children: ReactNode;
}
export function VoidButton(props: VoidButtonProps) {
const options = {
showSuccess: false,
...props.options
...props.options,
};
const [disabled, setDisabled] = useState(false);
const [success, setSuccess] = useState(false);
@ -46,11 +46,18 @@ export function VoidButton(props: VoidButtonProps) {
return (
<div className="flex-inline flex-center">
<div>
<div className={`btn${disabled ? " disabled" : ""}`} onClick={handleClick}>
<div
className={`btn${disabled ? " disabled" : ""}`}
onClick={handleClick}
>
{props.children}
</div>
</div>
{success && <div><Icon name="check-circle"/></div>}
{success && (
<div>
<Icon name="check-circle" />
</div>
)}
</div>
);
}

View File

@ -1,10 +1,10 @@
import "./VoidModal.css";
import {CSSProperties, ReactNode} from "react";
import { CSSProperties, ReactNode } from "react";
interface VoidModalProps {
title?: string
style?: CSSProperties
children: ReactNode
title?: string;
style?: CSSProperties;
children: ReactNode;
}
export default function VoidModal(props: VoidModalProps) {
const title = props.title;
@ -13,13 +13,9 @@ export default function VoidModal(props: VoidModalProps) {
return (
<div className="modal-bg">
<div className="modal" style={style}>
<div className="modal-header">
{title ?? "Unknown modal"}
</div>
<div className="modal-body">
{props.children ?? "Missing body"}
<div className="modal-header">{title ?? "Unknown modal"}</div>
<div className="modal-body">{props.children ?? "Missing body"}</div>
</div>
</div>
</div>
)
);
}

View File

@ -1,10 +1,10 @@
import {useSelector} from "react-redux";
import {VoidApi} from "@void-cat/api";
import { useSelector } from "react-redux";
import { VoidApi } from "@void-cat/api";
import {RootState} from "Store";
import {ApiHost} from "Const";
import { RootState } from "Store";
import { ApiHost } from "Const";
export default function useApi() {
const auth = useSelector((s: RootState) => s.login.jwt);
return new VoidApi(ApiHost, auth);
return new VoidApi(ApiHost, auth ? () => Promise.resolve(`Bearer ${auth}`) : undefined);
}

View File

@ -1,14 +1,14 @@
import {createSlice, PayloadAction} from "@reduxjs/toolkit";
import {Profile} from "@void-cat/api";
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { Profile } from "@void-cat/api";
interface LoginStore {
jwt?: string
profile?: Profile
jwt?: string;
profile?: Profile;
}
interface SetAuthPayload {
jwt: string
profile?: Profile
jwt: string;
profile?: Profile;
}
const LocalStorageKey = "token";
@ -16,7 +16,7 @@ export const LoginState = createSlice({
name: "Login",
initialState: {
jwt: window.localStorage.getItem(LocalStorageKey) ?? undefined,
profile: undefined
profile: undefined,
} as LoginStore,
reducers: {
setAuth: (state, action: PayloadAction<SetAuthPayload>) => {
@ -31,9 +31,9 @@ export const LoginState = createSlice({
state.jwt = undefined;
state.profile = undefined;
window.localStorage.removeItem(LocalStorageKey);
}
}
},
},
});
export const {setAuth, setProfile, logout} = LoginState.actions;
export const { setAuth, setProfile, logout } = LoginState.actions;
export default LoginState.reducer;

View File

@ -1,3 +1,2 @@
.donate {
}

View File

@ -1,5 +1,5 @@
import "./Donate.css"
import {useState} from "react";
import "./Donate.css";
import { useState } from "react";
export function Donate() {
const Hostname = "pay.v0l.io";
@ -11,23 +11,39 @@ export function Donate() {
return (
<div className="page donate">
<h2>Donate with Bitcoin</h2>
<form method="POST" action={`https://${Hostname}/api/v1/invoices`} className="flex">
<input type="hidden" name="storeId" value={StoreId}/>
<input type="hidden" name="checkoutDesc" value="Donation"/>
<form
method="POST"
action={`https://${Hostname}/api/v1/invoices`}
className="flex"
>
<input type="hidden" name="storeId" value={StoreId} />
<input type="hidden" name="checkoutDesc" value="Donation" />
<div className="flex">
<input name="price" type="number" min="1" step="1" value={price}
onChange={(e) => setPrice(parseFloat(e.target.value))}/>
<select name="currency" value={currency} onChange={(e) => setCurrency(e.target.value)}>
<input
name="price"
type="number"
min="1"
step="1"
value={price}
onChange={(e) => setPrice(parseFloat(e.target.value))}
/>
<select
name="currency"
value={currency}
onChange={(e) => setCurrency(e.target.value)}
>
<option>USD</option>
<option>GBP</option>
<option>EUR</option>
<option>BTC</option>
</select>
</div>
<input type="image"
<input
type="image"
name="submit"
src={`https://${Hostname}/img/paybutton/pay.svg`}
alt="Pay with BTCPay Server, a Self-Hosted Bitcoin Payment Processor"/>
alt="Pay with BTCPay Server, a Self-Hosted Bitcoin Payment Processor"
/>
</form>
</div>
);

View File

@ -2,7 +2,10 @@
margin-top: 2vh;
}
.preview img, .preview video, .preview object, .preview audio {
.preview img,
.preview video,
.preview object,
.preview audio {
max-width: 100%;
max-height: 100vh;
}

View File

@ -1,20 +1,24 @@
import "./FilePreview.css";
import {Fragment, useEffect, useState} from "react";
import {useParams} from "react-router-dom";
import {Helmet} from "react-helmet";
import {PaymentOrder, VoidFileResponse, StreamEncryption} from "@void-cat/api";
import { Fragment, useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { Helmet } from "react-helmet";
import {
PaymentOrder,
VoidFileResponse,
StreamEncryption,
} from "@void-cat/api";
import {TextPreview} from "../Components/FilePreview/TextPreview";
import {FileEdit} from "../Components/FileEdit/FileEdit";
import {FilePayment} from "../Components/FilePreview/FilePayment";
import {InlineProfile} from "../Components/Shared/InlineProfile";
import {VoidButton} from "../Components/Shared/VoidButton";
import {useFileTransfer} from "../Components/Shared/FileTransferHook";
import { TextPreview } from "../Components/FilePreview/TextPreview";
import { FileEdit } from "../Components/FileEdit/FileEdit";
import { FilePayment } from "../Components/FilePreview/FilePayment";
import { InlineProfile } from "../Components/Shared/InlineProfile";
import { VoidButton } from "../Components/Shared/VoidButton";
import { useFileTransfer } from "../Components/Shared/FileTransferHook";
import Icon from "../Components/Shared/Icon";
import useApi from "Hooks/UseApi";
import {FormatBytes} from "Util";
import {ApiHost} from "Const";
import { FormatBytes } from "Util";
import { ApiHost } from "Const";
export function FilePreview() {
const Api = useApi();
@ -24,7 +28,7 @@ export function FilePreview() {
const [link, setLink] = useState("#");
const [key, setKey] = useState("");
const [error, setError] = useState("");
const {speed, progress, update, setFileSize} = useFileTransfer();
const { speed, progress, update, setFileSize } = useFileTransfer();
async function loadInfo() {
if (params.id) {
@ -34,7 +38,7 @@ export function FilePreview() {
}
function isFileEncrypted() {
return "string" === typeof info?.metadata?.encryptionParams
return "string" === typeof info?.metadata?.encryptionParams;
}
function isDecrypted() {
@ -62,11 +66,16 @@ export function FilePreview() {
let hashKey = key.match(/([0-9a-z]{32}):([0-9a-z]{24})/);
if (hashKey?.length === 3) {
let [key, iv] = [hashKey[1], hashKey[2]];
let enc = new StreamEncryption(key, iv, info.metadata?.encryptionParams);
let enc = new StreamEncryption(
key,
iv,
info.metadata?.encryptionParams,
);
let rsp = await fetch(link);
if (rsp.ok) {
const reader = rsp.body?.pipeThrough(enc.getDecryptionTransform())
const reader = rsp.body
?.pipeThrough(enc.getDecryptionTransform())
.pipeThrough(decryptionProgressTransform());
const newResponse = new Response(reader);
setLink(window.URL.createObjectURL(await newResponse.blob()));
@ -78,7 +87,7 @@ export function FilePreview() {
if (e instanceof Error) {
setError(e.message);
} else {
setError("Unknown error")
setError("Unknown error");
}
}
}
@ -88,7 +97,7 @@ export function FilePreview() {
transform: (chunk, controller) => {
update(chunk.length);
controller.enqueue(chunk);
}
},
});
}
@ -97,10 +106,15 @@ export function FilePreview() {
return (
<div className="encrypted">
<h3>This file is encrypted, please enter the encryption key:</h3>
<input type="password" placeholder="Encryption key" value={key}
onChange={(e) => setKey(e.target.value)}/>
<input
type="password"
placeholder="Encryption key"
value={key}
onChange={(e) => setKey(e.target.value)}
/>
<VoidButton onClick={() => decryptFile()}>Decrypt</VoidButton>
{progress > 0 && `${(100 * progress).toFixed(0)}% (${FormatBytes(speed)}/s)`}
{progress > 0 &&
`${(100 * progress).toFixed(0)}% (${FormatBytes(speed)}/s)`}
{error && <h4 className="error">{error}</h4>}
</div>
);
@ -110,7 +124,7 @@ export function FilePreview() {
if (!info) return;
if (info.payment && info.payment.service !== 0 && !order) {
return <FilePayment file={info} onPaid={loadInfo}/>;
return <FilePayment file={info} onPaid={loadInfo} />;
}
}
@ -128,7 +142,7 @@ export function FilePreview() {
case "image/jpg":
case "image/jpeg":
case "image/png": {
return <img src={link} alt={info.metadata.name}/>;
return <img src={link} alt={info.metadata.name} />;
}
case "audio/aac":
case "audio/opus":
@ -137,7 +151,7 @@ export function FilePreview() {
case "audio/midi":
case "audio/mpeg":
case "audio/ogg": {
return <audio src={link} controls/>;
return <audio src={link} controls />;
}
case "video/x-msvideo":
case "video/mpeg":
@ -148,7 +162,7 @@ export function FilePreview() {
case "video/x-matroska":
case "video/webm":
case "video/quicktime": {
return <video src={link} controls/>;
return <video src={link} controls />;
}
case "application/json":
case "text/javascript":
@ -156,13 +170,13 @@ export function FilePreview() {
case "text/csv":
case "text/css":
case "text/plain": {
return <TextPreview link={link}/>;
return <TextPreview link={link} />;
}
case "application/pdf": {
return <object data={link}/>;
return <object data={link} />;
}
default: {
return <h3>{info.metadata?.name ?? info.id}</h3>
return <h3>{info.metadata?.name ?? info.id}</h3>;
}
}
}
@ -170,22 +184,44 @@ export function FilePreview() {
function renderOpenGraphTags() {
const tags = [
<meta key="og-site_name" property={"og:site_name"} content={"void.cat"}/>,
<meta key="og-title" property={"og:title"} content={info?.metadata?.name}/>,
<meta key="og-description" property={"og:description"} content={info?.metadata?.description}/>,
<meta key="og-url" property={"og:url"} content={`https://${window.location.host}/${info?.id}`}/>
<meta
key="og-site_name"
property={"og:site_name"}
content={"void.cat"}
/>,
<meta
key="og-title"
property={"og:title"}
content={info?.metadata?.name}
/>,
<meta
key="og-description"
property={"og:description"}
content={info?.metadata?.description}
/>,
<meta
key="og-url"
property={"og:url"}
content={`https://${window.location.host}/${info?.id}`}
/>,
];
const mime = info?.metadata?.mimeType;
if (mime?.startsWith("image/")) {
tags.push(<meta key="og-image" property={"og:image"} content={link}/>);
tags.push(<meta key="og-image-type" property={"og:image:type"} content={mime}/>);
tags.push(<meta key="og-image" property={"og:image"} content={link} />);
tags.push(
<meta key="og-image-type" property={"og:image:type"} content={mime} />,
);
} else if (mime?.startsWith("video/")) {
tags.push(<meta key="og-video" property={"og:video"} content={link}/>);
tags.push(<meta key="og-video-type" property={"og:video:type"} content={mime}/>);
tags.push(<meta key="og-video" property={"og:video"} content={link} />);
tags.push(
<meta key="og-video-type" property={"og:video:type"} content={mime} />,
);
} else if (mime?.startsWith("audio/")) {
tags.push(<meta key="og-audio" property={"og:audio"} content={link}/>);
tags.push(<meta key="og-audio-type" property={"og:audio:type"} content={mime}/>);
tags.push(<meta key="og-audio" property={"og:audio"} content={link} />);
tags.push(
<meta key="og-audio-type" property={"og:audio:type"} content={mime} />,
);
}
return tags;
@ -197,12 +233,11 @@ export function FilePreview() {
return (
<div className="virus-warning">
<p>
This file apears to be a virus, take care when downloading this file.
This file apears to be a virus, take care when downloading this
file.
</p>
Detected as:
<pre>
{scanResult.names}
</pre>
<pre>{scanResult.names}</pre>
</div>
);
}
@ -234,34 +269,41 @@ export function FilePreview() {
<Fragment>
<Helmet>
<title>void.cat - {info.metadata?.name ?? info.id}</title>
{info.metadata?.description ?
<meta name="description" content={info.metadata?.description}/> : null}
{info.metadata?.description ? (
<meta name="description" content={info.metadata?.description} />
) : null}
{renderOpenGraphTags()}
</Helmet>
{renderVirusWarning()}
<div className="flex flex-center">
<div className="flx-grow">
{info.uploader ? <InlineProfile profile={info.uploader}/> : null}
{info.uploader ? <InlineProfile profile={info.uploader} /> : null}
</div>
<div>
{canAccessFile() &&
{canAccessFile() && (
<>
<a className="btn" href={info?.metadata?.magnetLink}>
<Icon name="link" size={14} className="mr10"/>
<Icon name="link" size={14} className="mr10" />
Magnet
</a>
<a className="btn" href={`${link}.torrent`}
download={info.metadata?.name ?? info.id}>
<Icon name="file" size={14} className="mr10"/>
<a
className="btn"
href={`${link}.torrent`}
download={info.metadata?.name ?? info.id}
>
<Icon name="file" size={14} className="mr10" />
Torrent
</a>
<a className="btn" href={link}
download={info.metadata?.name ?? info.id}>
<Icon name="download" size={14} className="mr10"/>
<a
className="btn"
href={link}
download={info.metadata?.name ?? info.id}
>
<Icon name="download" size={14} className="mr10" />
Direct Download
</a>
</>}
</>
)}
</div>
</div>
{renderPayment()}
@ -269,17 +311,19 @@ export function FilePreview() {
{renderEncryptedDownload()}
<div className="file-stats">
<div>
<Icon name="download-cloud"/>
<Icon name="download-cloud" />
{FormatBytes(info?.bandwidth?.egress ?? 0, 2)}
</div>
<div>
<Icon name="save"/>
<Icon name="save" />
{FormatBytes(info?.metadata?.size ?? 0, 2)}
</div>
</div>
<FileEdit file={info}/>
<FileEdit file={info} />
</Fragment>
) : "Not Found"}
) : (
"Not Found"
)}
</div>
);
}

View File

@ -1,20 +1,20 @@
import {useSelector} from "react-redux";
import { useSelector } from "react-redux";
import {Dropzone} from "../Components/FileUpload/Dropzone";
import {GlobalStats} from "../Components/HomePage/GlobalStats";
import {FooterLinks} from "../Components/HomePage/FooterLinks";
import {MetricsGraph} from "../Components/HomePage/MetricsGraph";
import { Dropzone } from "../Components/FileUpload/Dropzone";
import { GlobalStats } from "../Components/HomePage/GlobalStats";
import { FooterLinks } from "../Components/HomePage/FooterLinks";
import { MetricsGraph } from "../Components/HomePage/MetricsGraph";
import {RootState} from "Store";
import { RootState } from "Store";
export function HomePage() {
const metrics = useSelector((s: RootState) => s.info.info);
return (
<div className="page">
<Dropzone/>
<GlobalStats/>
<MetricsGraph metrics={metrics?.timeSeriesMetrics}/>
<FooterLinks/>
<Dropzone />
<GlobalStats />
<MetricsGraph metrics={metrics?.timeSeriesMetrics} />
<FooterLinks />
</div>
);
}

View File

@ -1,5 +1,4 @@
.profile {
}
.profile .name {

View File

@ -1,17 +1,17 @@
import "./Profile.css";
import {Fragment, useState} from "react";
import {useDispatch, useSelector} from "react-redux";
import {default as moment} from "moment";
import {useLoaderData} from "react-router-dom";
import {Profile} from "@void-cat/api";
import { Fragment, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { default as moment } from "moment";
import { useLoaderData } from "react-router-dom";
import { Profile } from "@void-cat/api";
import useApi from "Hooks/UseApi";
import {RootState} from "Store";
import {DefaultAvatar} from "Const";
import { RootState } from "Store";
import { DefaultAvatar } from "Const";
import {logout, setProfile as setGlobalProfile} from "../LoginState";
import {FileList} from "../Components/Shared/FileList";
import {VoidButton} from "../Components/Shared/VoidButton";
import { logout, setProfile as setGlobalProfile } from "../LoginState";
import { FileList } from "../Components/Shared/FileList";
import { VoidButton } from "../Components/Shared/VoidButton";
import ApiKeyList from "../Components/Profile/ApiKeyList";
export function ProfilePage() {
@ -32,10 +32,10 @@ export function ProfilePage() {
async function changeAvatar() {
const res = await new Promise<Array<File>>((resolve) => {
let i = document.createElement('input');
i.setAttribute('type', 'file');
i.setAttribute('multiple', '');
i.addEventListener('change', async function (evt) {
let i = document.createElement("input");
i.setAttribute("type", "file");
i.setAttribute("multiple", "");
i.addEventListener("change", async function (evt) {
resolve((evt.target as any).files);
});
i.click();
@ -47,10 +47,9 @@ export function ProfilePage() {
if (rsp.ok) {
setProfile({
...profile,
avatar: rsp.file?.id
avatar: rsp.file?.id,
} as Profile);
}
}
async function saveUser(p: Profile) {
@ -87,19 +86,32 @@ export function ProfilePage() {
return (
<Fragment>
<h2>Please enter email verification code</h2>
<small>Your account will automatically be deleted in 7 days if you do not verify your email
address.</small>
<br/>
<input type="text" placeholder="Verification code" value={emailCode}
onChange={(e) => setEmailCode(e.target.value)}/>
<VoidButton onClick={() => submitCode(profile.id, emailCode)}>Submit</VoidButton>
<VoidButton onClick={() => {
<small>
Your account will automatically be deleted in 7 days if you do not
verify your email address.
</small>
<br />
<input
type="text"
placeholder="Verification code"
value={emailCode}
onChange={(e) => setEmailCode(e.target.value)}
/>
<VoidButton onClick={() => submitCode(profile.id, emailCode)}>
Submit
</VoidButton>
<VoidButton
onClick={() => {
dispatch(logout());
}}>Logout</VoidButton>
<br/>
}}
>
Logout
</VoidButton>
<br />
{emailCodeError && <b>{emailCodeError}</b>}
{(emailCodeError && !newCodeSent) &&
<a onClick={() => sendNewCode(profile.id)}>Send verification email</a>}
{emailCodeError && !newCodeSent && (
<a onClick={() => sendNewCode(profile.id)}>Send verification email</a>
)}
</Fragment>
);
}
@ -112,30 +124,48 @@ export function ProfilePage() {
<dl>
<dt>Public Profile:</dt>
<dd>
<input type="checkbox" checked={profile.publicProfile}
onChange={(e) => setProfile({
<input
type="checkbox"
checked={profile.publicProfile}
onChange={(e) =>
setProfile({
...profile,
publicProfile: e.target.checked
})}/>
publicProfile: e.target.checked,
})
}
/>
</dd>
<dt>Public Uploads:</dt>
<dd>
<input type="checkbox" checked={profile.publicUploads}
onChange={(e) => setProfile({
<input
type="checkbox"
checked={profile.publicUploads}
onChange={(e) =>
setProfile({
...profile,
publicUploads: e.target.checked
})}/>
publicUploads: e.target.checked,
})
}
/>
</dd>
</dl>
<div className="flex flex-center">
<div>
<VoidButton onClick={() => saveUser(profile)} options={{showSuccess: true}}>Save</VoidButton>
<VoidButton
onClick={() => saveUser(profile)}
options={{ showSuccess: true }}
>
Save
</VoidButton>
</div>
<div>
<VoidButton onClick={() => {
<VoidButton
onClick={() => {
dispatch(logout());
}}>Logout</VoidButton>
}}
>
Logout
</VoidButton>
</div>
</div>
</Fragment>
@ -149,26 +179,34 @@ export function ProfilePage() {
avatarUrl = `/d/${avatarUrl}`;
}
let avatarStyles = {
backgroundImage: `url(${avatarUrl})`
backgroundImage: `url(${avatarUrl})`,
};
return (
<div className="page">
<div className="profile">
<div className="name">
{cantEditProfile ?
<input value={profile.name}
onChange={(e) => setProfile({
{cantEditProfile ? (
<input
value={profile.name}
onChange={(e) =>
setProfile({
...profile,
name: e.target.value
})}/>
: profile.name}
name: e.target.value,
})
}
/>
) : (
profile.name
)}
</div>
<div className="flex">
<div className="flx-1">
<div className="avatar" style={avatarStyles}>
{cantEditProfile ? <div className="edit-avatar" onClick={() => changeAvatar()}>
{cantEditProfile ? (
<div className="edit-avatar" onClick={() => changeAvatar()}>
<h3>Edit</h3>
</div> : null}
</div>
) : null}
</div>
</div>
<div className="flx-1">
@ -176,15 +214,21 @@ export function ProfilePage() {
<dt>Created</dt>
<dd>{moment(profile.created).fromNow()}</dd>
<dt>Roles</dt>
<dd>{profile.roles.map(a => <span key={a} className="btn">{a}</span>)}</dd>
<dd>
{profile.roles.map((a) => (
<span key={a} className="btn">
{a}
</span>
))}
</dd>
</dl>
</div>
</div>
{cantEditProfile ? renderProfileEdit() : null}
{needsEmailVerify ? renderEmailVerify() : null}
<h1>Uploads</h1>
<FileList loadPage={(req) => Api.listUserFiles(profile.id, req)}/>
{cantEditProfile ? <ApiKeyList/> : null}
<FileList loadPage={(req) => Api.listUserFiles(profile.id, req)} />
{cantEditProfile ? <ApiKeyList /> : null}
</div>
</div>
);

View File

@ -1,9 +1,9 @@
import {useSelector} from "react-redux";
import {useNavigate} from "react-router-dom";
import {useEffect} from "react";
import { useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import { useEffect } from "react";
import {Login} from "../Components/Shared/Login";
import {RootState} from "Store";
import { Login } from "../Components/Shared/Login";
import { RootState } from "Store";
export function UserLogin() {
const auth = useSelector((s: RootState) => s.login.jwt);
@ -17,7 +17,7 @@ export function UserLogin() {
return (
<div className="page">
<Login/>
<Login />
</div>
)
);
}

View File

@ -1,17 +1,17 @@
import {createSlice, PayloadAction} from "@reduxjs/toolkit";
import {SiteInfoResponse} from "@void-cat/api";
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { SiteInfoResponse } from "@void-cat/api";
export const SiteInfoState = createSlice({
name: "SiteInfo",
initialState: {
info: null as SiteInfoResponse | null
info: null as SiteInfoResponse | null,
},
reducers: {
setInfo: (state, action: PayloadAction<SiteInfoResponse>) => {
state.info = action.payload;
},
}
},
});
export const {setInfo} = SiteInfoState.actions;
export const { setInfo } = SiteInfoState.actions;
export default SiteInfoState.reducer;

View File

@ -1,12 +1,12 @@
import {configureStore} from "@reduxjs/toolkit";
import { configureStore } from "@reduxjs/toolkit";
import loginReducer from "./LoginState";
import siteInfoReducer from "./SiteInfoStore";
const store = configureStore({
reducer: {
login: loginReducer,
info: siteInfoReducer
}
info: siteInfoReducer,
},
});
export type RootState = ReturnType<typeof store.getState>;

View File

@ -8,27 +8,21 @@ import * as Const from "Const";
*/
export function FormatBytes(b: number, f?: number) {
f ??= 2;
if (b >= Const.YiB)
return (b / Const.YiB).toFixed(f) + ' YiB';
if (b >= Const.ZiB)
return (b / Const.ZiB).toFixed(f) + ' ZiB';
if (b >= Const.EiB)
return (b / Const.EiB).toFixed(f) + ' EiB';
if (b >= Const.PiB)
return (b / Const.PiB).toFixed(f) + ' PiB';
if (b >= Const.TiB)
return (b / Const.TiB).toFixed(f) + ' TiB';
if (b >= Const.GiB)
return (b / Const.GiB).toFixed(f) + ' GiB';
if (b >= Const.MiB)
return (b / Const.MiB).toFixed(f) + ' MiB';
if (b >= Const.kiB)
return (b / Const.kiB).toFixed(f) + ' KiB';
return b.toFixed(f) + ' B'
if (b >= Const.YiB) return (b / Const.YiB).toFixed(f) + " YiB";
if (b >= Const.ZiB) return (b / Const.ZiB).toFixed(f) + " ZiB";
if (b >= Const.EiB) return (b / Const.EiB).toFixed(f) + " EiB";
if (b >= Const.PiB) return (b / Const.PiB).toFixed(f) + " PiB";
if (b >= Const.TiB) return (b / Const.TiB).toFixed(f) + " TiB";
if (b >= Const.GiB) return (b / Const.GiB).toFixed(f) + " GiB";
if (b >= Const.MiB) return (b / Const.MiB).toFixed(f) + " MiB";
if (b >= Const.kiB) return (b / Const.kiB).toFixed(f) + " KiB";
return b.toFixed(f) + " B";
}
export function buf2hex(buffer: number[] | ArrayBuffer) {
return [...new Uint8Array(buffer)].map(x => x.toString(16).padStart(2, '0')).join('');
return [...new Uint8Array(buffer)]
.map((x) => x.toString(16).padStart(2, "0"))
.join("");
}
export function ConstName(type: object, val: any) {
@ -43,31 +37,31 @@ export function FormatCurrency(value: number, currency: string | number) {
switch (currency) {
case 0:
case "BTC": {
let hasDecimals = (value % 1) > 0;
let hasDecimals = value % 1 > 0;
return `${value.toLocaleString(undefined, {
minimumFractionDigits: hasDecimals ? 8 : 0, // Sats
maximumFractionDigits: 11 // MSats
maximumFractionDigits: 11, // MSats
})}`;
}
case 1:
case "USD": {
return value.toLocaleString(undefined, {
style: "currency",
currency: "USD"
currency: "USD",
});
}
case 2:
case "EUR": {
return value.toLocaleString(undefined, {
style: "currency",
currency: "EUR"
currency: "EUR",
});
}
case 3:
case "GBP": {
return value.toLocaleString(undefined, {
style: "currency",
currency: "GBP"
currency: "GBP",
});
}
}

View File

@ -1,8 +1,8 @@
@import url('https://fonts.googleapis.com/css2?family=Source+Code+Pro:wght@400;700&display=swap');
@import url("https://fonts.googleapis.com/css2?family=Source+Code+Pro:wght@400;700&display=swap");
body {
margin: 0;
font-family: 'Source Code Pro', monospace;
font-family: "Source Code Pro", monospace;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
background-color: black;
@ -60,7 +60,12 @@ a:hover {
align-items: center;
}
input[type="text"], input[type="number"], input[type="password"], input[type="datetime-local"], input[type="checkbox"], select {
input[type="text"],
input[type="number"],
input[type="password"],
input[type="datetime-local"],
input[type="checkbox"],
select {
display: inline-block;
line-height: 1.1;
border-radius: 10px;

View File

@ -1,12 +1,14 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import React from "react";
import ReactDOM from "react-dom/client";
import './index.css';
import App from './App';
import "./index.css";
import App from "./App";
const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement);
const root = ReactDOM.createRoot(
document.getElementById("root") as HTMLElement,
);
root.render(
<React.StrictMode>
<App/>
</React.StrictMode>
<App />
</React.StrictMode>,
);

View File

@ -1,18 +1,18 @@
const {createProxyMiddleware} = require('http-proxy-middleware');
const { createProxyMiddleware } = require("http-proxy-middleware");
const settings = require("../package.json");
module.exports = function (app) {
const proxy = createProxyMiddleware({
target: settings.proxy,
changeOrigin: true,
secure: false
secure: false,
});
app.use('/admin', proxy);
app.use('/d', proxy);
app.use('/info', proxy);
app.use('/upload', proxy);
app.use('/auth', proxy);
app.use('/swagger', proxy);
app.use('/user', proxy);
app.use("/admin", proxy);
app.use("/d", proxy);
app.use("/info", proxy);
app.use("/upload", proxy);
app.use("/auth", proxy);
app.use("/swagger", proxy);
app.use("/user", proxy);
};

View File

@ -1841,6 +1841,13 @@ __metadata:
languageName: node
linkType: hard
"@eslint/js@npm:8.51.0":
version: 8.51.0
resolution: "@eslint/js@npm:8.51.0"
checksum: 0228bf1e1e0414843e56d9ff362a2a72d579c078f93174666f29315690e9e30a8633ad72c923297f7fd7182381b5a476805ff04dac8debe638953eb1ded3ac73
languageName: node
linkType: hard
"@eslint/js@npm:^8.47.0":
version: 8.47.0
resolution: "@eslint/js@npm:8.47.0"
@ -1871,6 +1878,17 @@ __metadata:
languageName: node
linkType: hard
"@humanwhocodes/config-array@npm:^0.11.11":
version: 0.11.11
resolution: "@humanwhocodes/config-array@npm:0.11.11"
dependencies:
"@humanwhocodes/object-schema": ^1.2.1
debug: ^4.1.1
minimatch: ^3.0.5
checksum: db84507375ab77b8ffdd24f498a5b49ad6b64391d30dd2ac56885501d03964d29637e05b1ed5aefa09d57ac667e28028bc22d2da872bfcd619652fbdb5f4ca19
languageName: node
linkType: hard
"@humanwhocodes/config-array@npm:^0.11.8":
version: 0.11.8
resolution: "@humanwhocodes/config-array@npm:0.11.8"
@ -6422,6 +6440,53 @@ __metadata:
languageName: node
linkType: hard
"eslint@npm:^8.51.0":
version: 8.51.0
resolution: "eslint@npm:8.51.0"
dependencies:
"@eslint-community/eslint-utils": ^4.2.0
"@eslint-community/regexpp": ^4.6.1
"@eslint/eslintrc": ^2.1.2
"@eslint/js": 8.51.0
"@humanwhocodes/config-array": ^0.11.11
"@humanwhocodes/module-importer": ^1.0.1
"@nodelib/fs.walk": ^1.2.8
ajv: ^6.12.4
chalk: ^4.0.0
cross-spawn: ^7.0.2
debug: ^4.3.2
doctrine: ^3.0.0
escape-string-regexp: ^4.0.0
eslint-scope: ^7.2.2
eslint-visitor-keys: ^3.4.3
espree: ^9.6.1
esquery: ^1.4.2
esutils: ^2.0.2
fast-deep-equal: ^3.1.3
file-entry-cache: ^6.0.1
find-up: ^5.0.0
glob-parent: ^6.0.2
globals: ^13.19.0
graphemer: ^1.4.0
ignore: ^5.2.0
imurmurhash: ^0.1.4
is-glob: ^4.0.0
is-path-inside: ^3.0.3
js-yaml: ^4.1.0
json-stable-stringify-without-jsonify: ^1.0.1
levn: ^0.4.1
lodash.merge: ^4.6.2
minimatch: ^3.1.2
natural-compare: ^1.4.0
optionator: ^0.9.3
strip-ansi: ^6.0.1
text-table: ^0.2.0
bin:
eslint: bin/eslint.js
checksum: 214fa5d1fcb67af1b8992ce9584ccd85e1aa7a482f8b8ea5b96edc28fa838a18a3b69456db45fc1ed3ef95f1e9efa9714f737292dc681e572d471d02fda9649c
languageName: node
linkType: hard
"espree@npm:^9.5.2":
version: 9.5.2
resolution: "espree@npm:9.5.2"
@ -10975,6 +11040,15 @@ __metadata:
languageName: node
linkType: hard
"prettier@npm:^3.0.3":
version: 3.0.3
resolution: "prettier@npm:3.0.3"
bin:
prettier: bin/prettier.cjs
checksum: e10b9af02b281f6c617362ebd2571b1d7fc9fb8a3bd17e371754428cda992e5e8d8b7a046e8f7d3e2da1dcd21aa001e2e3c797402ebb6111b5cd19609dd228e0
languageName: node
linkType: hard
"pretty-bytes@npm:^5.3.0, pretty-bytes@npm:^5.4.1":
version: 5.6.0
resolution: "pretty-bytes@npm:5.6.0"
@ -11893,6 +11967,10 @@ __metadata:
"root-workspace-0b6124@workspace:.":
version: 0.0.0-use.local
resolution: "root-workspace-0b6124@workspace:."
dependencies:
eslint: ^8.51.0
prettier: ^3.0.3
typescript: ^5.2.2
languageName: unknown
linkType: soft
@ -13195,6 +13273,16 @@ __metadata:
languageName: node
linkType: hard
"typescript@npm:^5.2.2":
version: 5.2.2
resolution: "typescript@npm:5.2.2"
bin:
tsc: bin/tsc
tsserver: bin/tsserver
checksum: 7912821dac4d962d315c36800fe387cdc0a6298dba7ec171b350b4a6e988b51d7b8f051317786db1094bd7431d526b648aba7da8236607febb26cf5b871d2d3c
languageName: node
linkType: hard
"typescript@patch:typescript@^5.0.4#~builtin<compat/typescript>":
version: 5.0.4
resolution: "typescript@patch:typescript@npm%3A5.0.4#~builtin<compat/typescript>::version=5.0.4&hash=b5f058"
@ -13215,6 +13303,16 @@ __metadata:
languageName: node
linkType: hard
"typescript@patch:typescript@^5.2.2#~builtin<compat/typescript>":
version: 5.2.2
resolution: "typescript@patch:typescript@npm%3A5.2.2#~builtin<compat/typescript>::version=5.2.2&hash=f3b441"
bin:
tsc: bin/tsc
tsserver: bin/tsserver
checksum: 0f4da2f15e6f1245e49db15801dbee52f2bbfb267e1c39225afdab5afee1a72839cd86000e65ee9d7e4dfaff12239d28beaf5ee431357fcced15fb08583d72ca
languageName: node
linkType: hard
"unbox-primitive@npm:^1.0.2":
version: 1.0.2
resolution: "unbox-primitive@npm:1.0.2"