[wip] Update to Vue 3 + Vite

Based on https://github.com/antfu/vitesse-webext
next
neobooru 2023-01-28 20:20:36 +01:00
parent e6852e1d2e
commit fbd89fa253
63 changed files with 8054 additions and 9056 deletions

3
.eslintignore Normal file
View File

@ -0,0 +1,3 @@
dist
node_modules
public

21
.gitignore vendored
View File

@ -1,5 +1,16 @@
.vscode/ .DS_Store
/node_modules .idea/
/*.log .vite-ssg-dist
/dist .vite-ssg-temp
/release *.crx
*.local
*.log
*.pem
*.xpi
*.zip
dist
dist-ssr
extension/manifest.json
node_modules
src/auto-imports.d.ts
src/components.d.ts

2
.npmrc Normal file
View File

@ -0,0 +1,2 @@
shamefully-hoist=true
auto-install-peers=true

6
.vscode/extensions.json vendored Normal file
View File

@ -0,0 +1,6 @@
{
"recommendations": [
"vue.volar",
"dbaeumer.vscode-eslint",
]
}

6
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,6 @@
{
"typescript.tsdk": "node_modules/typescript/lib",
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
}

View File

Before

Width:  |  Height:  |  Size: 33 KiB

After

Width:  |  Height:  |  Size: 33 KiB

View File

@ -1,50 +1,67 @@
{ {
"name": "szuru-chrome", "name": "szuruchrome",
"version": "0.0.0", "displayName": "SzuruChrome",
"description": "Import media from various sites into szurubooru.", "description": "Import media from various sites into szurubooru.",
"author": "neobooru", "version": "0.0.0",
"license": "MIT", "private": true,
"repository": { "packageManager": "pnpm@7.8.0",
"url": "https://github.com/neobooru/SzuruChrome" "scripts": {
}, "dev": "npm run clear && cross-env NODE_ENV=development run-p dev:*",
"type": "module", "dev:prepare": "esno scripts/prepare.ts",
"scripts": { "dev:web": "vite",
"build": "webpack --config webpack.prod.cjs", "dev:js": "npm run build:js -- --mode development",
"build:dev": "webpack --config webpack.dev.cjs", "build": "cross-env NODE_ENV=production run-s clear build:web build:prepare build:js",
"build-zip": "node scripts/build-zip.cjs", "build:prepare": "esno scripts/prepare.ts",
"sign-xpi": "node scripts/sign-xpi.js", "build:web": "vite build",
"watch": "webpack --watch --config webpack.dev.cjs", "build:js": "vite build --config vite.config.content.ts",
"lint": "eslint src" "pack": "cross-env NODE_ENV=production run-p pack:*",
}, "pack:zip": "rimraf extension.zip && jszip-cli add extension/* -o ./extension.zip",
"dependencies": { "pack:crx": "crx pack extension -o ./extension.crx",
"axios": "^0.27.2", "pack:xpi": "cross-env WEB_EXT_ARTIFACTS_DIR=./ web-ext build --source-dir ./extension --filename extension.xpi --overwrite-dest",
"markdown-it": "^13.0.1", "start:chromium": "web-ext run --source-dir ./extension --target=chromium",
"neo-scraper": "^0.5.8", "start:firefox": "web-ext run --source-dir ./extension --target=firefox-desktop",
"normalize.css": "^8.0.1", "clear": "rimraf extension/dist extension/manifest.json extension.*",
"vue": "^2.6.14", "lint": "eslint .",
"webextension-polyfill": "^0.9.0" "test": "vitest test"
}, },
"devDependencies": { "dependencies": {
"@types/markdown-it": "^12.2.3", "axios": "^1.2.2",
"@typescript-eslint/eslint-plugin": "^5.48.1", "markdown-it": "^13.0.1",
"@typescript-eslint/parser": "^5.48.1", "neo-scraper": "^0.5.8",
"archiver": "^5.3.1", "normalize.css": "^8.0.1"
"copy-webpack-plugin": "^11.0.0", },
"css-loader": "^6.7.1", "devDependencies": {
"eslint": "^8.21.0", "@ffflorian/jszip-cli": "^3.1.6",
"eslint-plugin-vue": "^9.3.0", "@fortawesome/fontawesome-svg-core": "^6.2.1",
"mini-css-extract-plugin": "^2.6.1", "@fortawesome/free-solid-svg-icons": "^6.2.1",
"sass": "^1.57.1", "@fortawesome/vue-fontawesome": "^3.0.3",
"sass-loader": "^13.2.0", "@types/fs-extra": "^9.0.13",
"sign-addon": "^5.0.0", "@types/markdown-it": "^12.2.3",
"ts-loader": "^9.3.1", "@types/node": "^18.11.9",
"typescript": "^4.9.4", "@types/webextension-polyfill": "^0.9.1",
"vue-loader": "^15.9.8", "@typescript-eslint/eslint-plugin": "^5.44.0",
"vue-template-compiler": "^2.7.8", "@vitejs/plugin-vue": "^3.2.0",
"web-ext-types": "^3.2.1", "@vue/compiler-sfc": "^3.2.45",
"webextension-polyfill-ts": "^0.26.0", "@vue/test-utils": "^2.2.4",
"webpack": "^5.74.0", "@vueuse/core": "^9.6.0",
"webpack-cli": "^4.10.0", "chokidar": "^3.5.3",
"webpack-ext-reloader": "^1.1.9" "cross-env": "^7.0.3",
} "crx": "^5.0.1",
} "eslint": "^8.28.0",
"esno": "^0.16.3",
"fs-extra": "^10.1.0",
"jsdom": "^20.0.3",
"kolorist": "^1.6.0",
"npm-run-all": "^4.1.5",
"rimraf": "^3.0.2",
"sass": "^1.57.1",
"typescript": "^4.9.3",
"unplugin-auto-import": "^0.12.2",
"unplugin-vue-components": "^0.23.0",
"vite": "^3.2.4",
"vitest": "^0.25.3",
"vue": "^3.2.45",
"web-ext": "^7.3.1",
"webextension-polyfill": "^0.10.0"
}
}

6201
pnpm-lock.yaml Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,53 +0,0 @@
#!/usr/bin/env node
const fs = require("fs");
const path = require("path");
const archiver = require("archiver");
const DEST_DIR = path.join(__dirname, "../dist");
const DEST_ZIP_DIR = path.join(__dirname, "../release");
const extractExtensionData = () => {
const extPackageJson = require("../package.json");
return {
name: extPackageJson.name,
version: extPackageJson.version
};
};
const makeDestZipDirIfNotExists = () => {
if (!fs.existsSync(DEST_ZIP_DIR)) {
fs.mkdirSync(DEST_ZIP_DIR);
}
};
const buildZip = (src, dist, zipFilename) => {
console.info(`Building ${zipFilename}...`);
const archive = archiver("zip", { zlib: { level: 9 } });
const stream = fs.createWriteStream(path.join(dist, zipFilename));
return new Promise((resolve, reject) => {
archive
.directory(src, false)
.on("error", err => reject(err))
.pipe(stream);
stream.on("close", () => resolve());
archive.finalize();
});
};
const main = () => {
const { version } = extractExtensionData();
const zipFilename = `SzuruChrome-${version}.zip`;
makeDestZipDirIfNotExists();
buildZip(DEST_DIR, DEST_ZIP_DIR, zipFilename)
.then(() => console.info("OK"))
.catch(console.err);
};
main();

10
scripts/manifest.ts Normal file
View File

@ -0,0 +1,10 @@
import fs from "fs-extra";
import { getManifest } from "../src/manifest";
import { log, r } from "./utils";
export async function writeManifest() {
await fs.writeJSON(r("extension/manifest.json"), await getManifest(), { spaces: 2 });
log("PRE", "write manifest.json");
}
writeManifest();

38
scripts/prepare.ts Normal file
View File

@ -0,0 +1,38 @@
// generate stub index.html files for dev entry
import { execSync } from "child_process";
import fs from "fs-extra";
import chokidar from "chokidar";
import { isDev, log, port, r } from "./utils";
/**
* Stub index.html to use Vite in development
*/
async function stubIndexHtml() {
const views = ["options", "popup", "background"];
for (const view of views) {
await fs.ensureDir(r(`extension/dist/${view}`));
let data = await fs.readFile(r(`src/${view}/index.html`), "utf-8");
data = data
.replace('"./main.ts"', `"http://localhost:${port}/${view}/main.ts"`)
.replace('<div id="app"></div>', '<div id="app">Vite server did not start</div>');
await fs.writeFile(r(`extension/dist/${view}/index.html`), data, "utf-8");
log("PRE", `stub ${view}`);
}
}
function writeManifest() {
execSync("npx esno ./scripts/manifest.ts", { stdio: "inherit" });
}
writeManifest();
if (isDev) {
stubIndexHtml();
chokidar.watch(r("src/**/*.html")).on("change", () => {
stubIndexHtml();
});
chokidar.watch([r("src/manifest.ts"), r("package.json")]).on("change", () => {
writeManifest();
});
}

View File

@ -1,51 +0,0 @@
#!/usr/bin/env node
import { fileURLToPath } from 'url';
import { join } from "path";
import { existsSync, renameSync } from "fs";
import { argv, exit } from "process";
import { signAddon } from 'sign-addon';
import info from "../package.json" assert { type: "json" };
const __dirname = fileURLToPath(new URL('.', import.meta.url));
const version = info.version;
const RELEASE_DIR = join(__dirname, "../release");
async function main() {
const args = argv.slice(2);
if (args.length != 3) {
console.log("USAGE: yarn sign-zip <extension_id> <api_key> <api_secret>");
exit(1);
}
const id = args[0];
const apiKey = args[1];
const apiSecret = args[2];
const zipPath = join(RELEASE_DIR, `SzuruChrome-${version}.zip`);
const xpiPath = join(RELEASE_DIR, `SzuruChrome-${version}.xpi`);
// Ensure the file exists.
if (!existsSync(zipPath)) {
console.error(zipPath + " does not exist. Make sure to run 'yarn build' and 'yarn build-zip'.");
exit(1);
}
const result = await signAddon({
id,
xpiPath: zipPath,
version,
apiKey,
apiSecret,
downloadDir: RELEASE_DIR
});
if (result.success) {
console.log(result.downloadedFiles[0]);
renameSync(result.downloadedFiles[0], xpiPath);
} else {
exit(1);
}
}
main();

10
scripts/utils.ts Normal file
View File

@ -0,0 +1,10 @@
import { resolve } from 'path';
import { bgCyan, black } from 'kolorist';
export const port = parseInt(process.env.PORT || '') || 3303;
export const r = (...args: string[]) => resolve(__dirname, '..', ...args);
export const isDev = process.env.NODE_ENV !== 'production';
export function log(name: string, message: string) {
console.log(black(bgCyan(` ${name} `)), message);
}

View File

@ -1,55 +0,0 @@
import { Config, Theme } from "./Config";
export type BrowserCommandName = "grab_post" | "upload_post" | "push_message" | "remove_messages";
export type MessageType = "error" | "info" | "success";
export class BrowserCommand {
name: BrowserCommandName;
data: any;
constructor(name: BrowserCommandName, data: any = null) {
this.name = name;
this.data = data;
}
}
export class Message {
content: string;
level: MessageType;
category: string;
constructor(content: string, level: MessageType = "info", category: string | null = null) {
this.content = content;
this.level = level;
this.category = category ?? "none";
}
}
export function getUrl(root: string, ...parts: string[]): string {
let url = root.replace(/\/+$/, "");
for (const part of parts) {
url += "/" + part.replace(/\/+$/, "");
}
return url;
}
export function isChrome() {
return /Chrome/.test(navigator.userAgent);
}
export function encodeTagName(tagName: string) {
// Searching for posts with re:zero will show an error message about unknown named token.
// Searching for posts with re\:zero will show posts tagged with re:zero.
return tagName.replace(/:/g, "\\:");
}
export async function applyTheme(theme?: Theme) {
if (!theme) {
var cfg = await Config.load();
theme = cfg.theme;
}
if (theme == "system") {
theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
}
document.documentElement.setAttribute("data-theme", theme);
}

View File

@ -1,7 +1,3 @@
import { browser } from "webextension-polyfill-ts";
export type Theme = "system" | "light" | "dark";
export class SzuruSiteConfig { export class SzuruSiteConfig {
domain = ""; domain = "";
username = ""; username = "";
@ -16,7 +12,6 @@ export class Config {
autoSearchSimilar = false; autoSearchSimilar = false;
loadTagCounts = true; loadTagCounts = true;
useContentTokens = true; useContentTokens = true;
theme: Theme = "system";
sites: Array<SzuruSiteConfig> = []; sites: Array<SzuruSiteConfig> = [];
public async save() { public async save() {

View File

@ -1,52 +0,0 @@
import { BooruTypes, ContentType, ScrapedNote, ScrapedPost, ScrapedTag } from "neo-scraper";
import { MicroTag, Tag } from "./SzuruTypes";
export class TagViewModel {
public implications: TagViewModel[] = [];
constructor(public name: string, public category?: BooruTypes.TagCategory, public usages?: number | undefined) {}
static fromTag(tag: Tag) {
const x = new TagViewModel(tag.names[0], <BooruTypes.TagCategory>tag.category, tag.usages);
if (tag.implications) {
x.implications = tag.implications.map((y) => TagViewModel.fromMicroTag(y));
}
return x;
}
static fromMicroTag(tag: MicroTag) {
return new TagViewModel(tag.names[0], <BooruTypes.TagCategory>tag.category, tag.usages);
}
static fromScapedTag(tag: ScrapedTag): TagViewModel {
return new TagViewModel(tag.name, tag.category);
}
}
export class PostViewModel {
name = "";
tags: TagViewModel[] = [];
notes: ScrapedNote[];
contentUrl: string;
contentToken: string | undefined;
pageUrl: string;
contentType: ContentType;
rating: BooruTypes.SafetyRating;
source = "";
referrer: string | undefined;
resolution: [number, number] | undefined;
constructor(post: ScrapedPost) {
this.contentUrl = post.contentUrl;
this.pageUrl = post.pageUrl;
this.contentType = post.contentType;
this.rating = post.rating;
this.source = post.sources.join("\n");
this.referrer = post.referrer;
this.tags = post.tags.map((x) => TagViewModel.fromScapedTag(x));
this.notes = post.notes;
this.resolution = post.resolution;
}
}

View File

@ -1,166 +1,163 @@
import axios, { AxiosRequestConfig, CancelToken } from "axios"; import axios, { AxiosRequestConfig, CancelToken } from "axios";
import { SzuruSiteConfig } from "./Config"; import {
import { TagsResult,
TagsResult, TagCategoriesResult,
TagCategoriesResult, Post,
Post, Tag,
Tag, SzuruError,
SzuruError, ImageSearchResult,
ImageSearchResult, TagFields,
TagFields, TemporaryFileUploadResult,
TemporaryFileUploadResult } from "./models";
} from "./SzuruTypes"; import { PostDetails } from "~/models";
import { PostViewModel } from "./ViewModels"; import { SzuruSiteConfig } from "~/config";
/** /**
* A 1:1 wrapper around the szurubooru API. * A 1:1 wrapper around the szurubooru API.
* *
* @class SzuruWrapper * @class SzuruWrapper
*/ */
export default class SzuruWrapper { export default class SzurubooruApi {
baseUrl: string; baseUrl: string;
apiUrl: string; apiUrl: string;
username: string; username: string;
authToken: string; authToken: string;
private readonly baseHeaders = { private readonly baseHeaders = {
Accept: "application/json", Accept: "application/json",
"Content-Type": "application/json" "Content-Type": "application/json",
}; };
/** /**
* Creates an instance of SzuruWrapper. * Creates an instance of SzuruWrapper.
* @param {string} baseUrl * @param {string} baseUrl
* @memberof SzuruWrapper * @memberof SzuruWrapper
*/ */
constructor(baseUrl: string, username: string, authToken: string) { constructor(baseUrl: string, username: string, authToken: string) {
const x = baseUrl.replace(/\/+$/, ""); // Trim trailing slashes, to make sure we only have one const x = baseUrl.replace(/\/+$/, ""); // Trim trailing slashes, to make sure we only have one
this.baseUrl = x + "/"; this.baseUrl = x + "/";
this.apiUrl = x + "/api/"; this.apiUrl = x + "/api/";
this.username = username; this.username = username;
this.authToken = authToken; this.authToken = authToken;
} }
async getInfo(): Promise<any> { async getInfo(): Promise<any> {
return (await this.apiGet("info")).data; return (await this.apiGet("info")).data;
} }
async updateTag(tag: Tag): Promise<any> { async updateTag(tag: Tag): Promise<any> {
return (await this.apiPut("tag/" + encodeURIComponent(tag.names[0]), tag)).data; return (await this.apiPut("tag/" + encodeURIComponent(tag.names[0]), tag)).data;
} }
async getTags( async getTags(
query: string, query: string,
offset = 0, offset = 0,
limit = 100, limit = 100,
fields: TagFields[] | undefined = undefined, fields?: TagFields[],
cancelToken: CancelToken | undefined = undefined cancelToken?: CancelToken
): Promise<TagsResult> { ): Promise<TagsResult> {
const params = new URLSearchParams(); const params = new URLSearchParams();
params.append("offset", offset.toString()); params.append("offset", offset.toString());
params.append("limit", limit.toString()); params.append("limit", limit.toString());
if (fields && fields.length > 0) params.append("fields", fields.join()); if (fields && fields.length > 0) params.append("fields", fields.join());
if (query) params.append("query", query); if (query) params.append("query", query);
return (await this.apiGet("tags?" + params.toString(), {}, cancelToken)).data; return (await this.apiGet("tags?" + params.toString(), {}, cancelToken)).data;
} }
async getTagCategories(): Promise<TagCategoriesResult> { async getTagCategories(): Promise<TagCategoriesResult> {
return (await this.apiGet("tag-categories")).data; return (await this.apiGet("tag-categories")).data;
} }
async createPost(post: PostViewModel): Promise<Post> { async createPost(post: PostDetails): Promise<Post> {
const obj = <any>{ const obj = <any>{
tags: post.tags.map(x => x.name), tags: post.tags.map((x) => x.name),
safety: post.rating, safety: post.rating,
source: post.source, source: post.source,
notes: post.notes notes: post.notes,
}; };
if (post.contentToken) { if (post.contentToken) {
obj.contentToken = post.contentToken; obj.contentToken = post.contentToken;
} else { } else {
obj.contentUrl = post.contentUrl; obj.contentUrl = post.contentUrl;
} }
console.log("Create new post object"); console.log("Create new post object");
console.dir(obj); console.dir(obj);
return (await this.apiPost("posts", obj)).data; return (await this.apiPost("posts", obj)).data;
} }
async reverseSearch(contentUrl: string): Promise<ImageSearchResult> { async reverseSearch(contentUrl: string): Promise<ImageSearchResult> {
const obj = { contentUrl }; const obj = { contentUrl };
return (await this.apiPost("posts/reverse-search", obj)).data; return (await this.apiPost("posts/reverse-search", obj)).data;
} }
async reverseSearchToken(contentToken: string): Promise<ImageSearchResult> { async reverseSearchToken(contentToken: string): Promise<ImageSearchResult> {
const obj = { contentToken }; const obj = { contentToken };
return (await this.apiPost("posts/reverse-search", obj)).data; return (await this.apiPost("posts/reverse-search", obj)).data;
} }
async uploadTempFile(contentUrl: string): Promise<TemporaryFileUploadResult> { async uploadTempFile(contentUrl: string): Promise<TemporaryFileUploadResult> {
const obj = { contentUrl }; const obj = { contentUrl };
return (await this.apiPost("uploads", obj)).data; return (await this.apiPost("uploads", obj)).data;
} }
static createFromConfig(siteConfig: SzuruSiteConfig): SzuruWrapper { static createFromConfig(siteConfig: SzuruSiteConfig): SzurubooruApi {
return new SzuruWrapper(siteConfig.domain, siteConfig.username, siteConfig.authToken); return new SzurubooruApi(siteConfig.domain, siteConfig.username, siteConfig.authToken);
} }
private async apiGet( private async apiGet(url: string, additionalHeaders: any = {}, cancelToken?: CancelToken): Promise<any> {
url: string, const fullUrl = this.apiUrl + url;
additionalHeaders: any = {}, const config: AxiosRequestConfig = {
cancelToken: CancelToken | undefined = undefined method: "GET",
): Promise<any> { url: fullUrl,
const fullUrl = this.apiUrl + url; cancelToken,
const config: AxiosRequestConfig = { };
method: "GET",
url: fullUrl, config.headers = { ...this.baseHeaders, ...additionalHeaders };
cancelToken return this.execute(config);
}; }
config.headers = { ...this.baseHeaders, ...additionalHeaders }; private async apiPost(url: string, data: any, additionalHeaders: any = {}): Promise<any> {
return this.execute(config); const fullUrl = this.apiUrl + url;
} const config: AxiosRequestConfig = {
method: "POST",
private async apiPost(url: string, data: any, additionalHeaders: any = {}): Promise<any> { url: fullUrl,
const fullUrl = this.apiUrl + url; data: data,
const config: AxiosRequestConfig = { };
method: "POST",
url: fullUrl, config.headers = { ...this.baseHeaders, ...additionalHeaders };
data: data return this.execute(config);
}; }
config.headers = { ...this.baseHeaders, ...additionalHeaders }; private async apiPut(url: string, data: any, additionalHeaders: any = {}): Promise<any> {
return this.execute(config); const fullUrl = this.apiUrl + url;
} const config: AxiosRequestConfig = {
method: "PUT",
private async apiPut(url: string, data: any, additionalHeaders: any = {}): Promise<any> { url: fullUrl,
const fullUrl = this.apiUrl + url; data: data,
const config: AxiosRequestConfig = { };
method: "PUT",
url: fullUrl, config.headers = { ...this.baseHeaders, ...additionalHeaders };
data: data return this.execute(config);
}; }
config.headers = { ...this.baseHeaders, ...additionalHeaders }; private async execute(config: AxiosRequestConfig): Promise<any> {
return this.execute(config); if (this.username && this.authToken) {
} const token = "Token " + btoa(`${this.username}:${this.authToken}`);
if (!config.headers) config.headers = {};
private async execute(config: AxiosRequestConfig): Promise<any> { // @ts-expect-error
if (this.username && this.authToken) { config.headers["Authorization"] = token;
const token = "Token " + btoa(`${this.username}:${this.authToken}`); }
if (!config.headers) config.headers = {};
config.headers["Authorization"] = token; try {
} return await axios(config);
} catch (ex: any) {
try { const error = ex.response?.data as SzuruError | undefined;
return await axios(config); throw error ? error : ex;
} catch (ex) { }
const error = ex.response?.data as SzuruError | undefined; }
throw error ? error : ex; }
}
}
}

View File

@ -1,117 +1,117 @@
/** /**
* Generated based on my setup, so some fields might be missing (but they also are unused so far so it doesn't really matter). * Generated based on my setup, so some fields might be missing (but they also are unused so far so it doesn't really matter).
*/ */
export type Safety = "safe" | "sketchy" | "unsafe"; export type Safety = "safe" | "sketchy" | "unsafe";
export type TagFields = "names" | "category" | "usages" | "implications"; export type TagFields = "names" | "category" | "usages" | "implications";
export type TagsResult = PagedSearchResult<Tag>; export type TagsResult = PagedSearchResult<Tag>;
export type TagCategoriesResult = UnpagedSearchResult<TagCategory>; export type TagCategoriesResult = UnpagedSearchResult<TagCategory>;
export interface SzuruError { export interface SzuruError {
name: string; name: string;
title: string; title: string;
description: string; description: string;
} }
export interface PostAlreadyUploadedError extends SzuruError { export interface PostAlreadyUploadedError extends SzuruError {
otherPostId: number; otherPostId: number;
otherPostUrl: string; otherPostUrl: string;
} }
export interface PagedSearchResult<T> { export interface PagedSearchResult<T> {
query: string; query: string;
offset: number; offset: number;
limit: number; limit: number;
total: number; total: number;
results: T[]; results: T[];
} }
export interface UnpagedSearchResult<T> { export interface UnpagedSearchResult<T> {
results: T[]; results: T[];
} }
export interface MicroTag { export interface MicroTag {
names: string[]; names: string[];
category: string; category: string;
usages: number; usages: number;
} }
export interface Tag { export interface Tag {
names: string[]; names: string[];
category: string; category: string;
version: number; version: number;
description?: string; // Markdown description?: string; // Markdown
creationTime: Date; creationTime: Date;
lastEditTime?: Date; lastEditTime?: Date;
usages: number; usages: number;
suggestions: MicroTag[]; suggestions: MicroTag[];
implications: MicroTag[]; implications: MicroTag[];
} }
export interface TagCategory { export interface TagCategory {
name: string; name: string;
version: number; version: number;
color: string; color: string;
usages: number; usages: number;
default: boolean; default: boolean;
} }
export interface MicroUser { export interface MicroUser {
name: string; name: string;
avatarUrl: string; avatarUrl: string;
} }
export interface Post { export interface Post {
id: number; id: number;
version: number; version: number;
creationTime: Date; creationTime: Date;
lastEditTime?: Date; lastEditTime?: Date;
safety: Safety; safety: Safety;
source: string; source: string;
type: string; type: string;
mimeType: string; mimeType: string;
checksum: string; checksum: string;
fileSize: number; fileSize: number;
canvasWidth: number; canvasWidth: number;
canvasHeight: number; canvasHeight: number;
contentUrl: string; contentUrl: string;
thumbnailUrl: string; thumbnailUrl: string;
flags: string[]; flags: string[];
tags: MicroTag[]; tags: MicroTag[];
relations: any[]; // MicroPost resource relations: any[]; // MicroPost resource
user: MicroUser; user: MicroUser;
score: number; score: number;
ownScore: number; ownScore: number;
ownFavorite: boolean; ownFavorite: boolean;
tagCount: number; tagCount: number;
favoriteCount: number; favoriteCount: number;
commentCount: number; commentCount: number;
noteCount: number; noteCount: number;
relationCount: number; relationCount: number;
featureCount: number; featureCount: number;
lastFeatureTime?: Date; lastFeatureTime?: Date;
favoritedBy: MicroUser[]; favoritedBy: MicroUser[];
hasCustomThumbnail: boolean; hasCustomThumbnail: boolean;
notes: any[]; // Note resource notes: any[]; // Note resource
comments: any[]; // Comment resource comments: any[]; // Comment resource
} }
export interface SzuruNote { export interface SzuruNote {
polygon: number[][]; polygon: number[][];
text: string; text: string;
} }
export interface SimilarPost { export interface SimilarPost {
distance: number; distance: number;
post: Post; post: Post;
} }
export interface ImageSearchResult { export interface ImageSearchResult {
exactPost: Post | null; exactPost: Post | undefined;
similarPosts: SimilarPost[]; similarPosts: SimilarPost[];
} }
export interface TemporaryFileUploadResult { export interface TemporaryFileUploadResult {
token: string; token: string;
} }

View File

@ -0,0 +1,18 @@
import { isFirefox, isForbiddenUrl } from "~/env";
// Firefox fetch files from cache instead of reloading changes from disk,
// hmr will not work as Chromium based browser
browser.webNavigation.onCommitted.addListener(({ tabId, frameId, url }) => {
// Filter out non main window events.
if (frameId !== 0) return;
if (isForbiddenUrl(url)) return;
// inject the latest scripts
browser.tabs
.executeScript(tabId, {
file: `${isFirefox ? "" : "."}/dist/contentScripts/index.global.js`,
runAt: "document_end",
})
.catch((error) => console.error(error));
});

10
src/background/index.html Normal file
View File

@ -0,0 +1,10 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Background</title>
</head>
<body>
<script type="module" src="./main.ts"></script>
</body>
</html>

View File

@ -1,22 +1,36 @@
import { browser } from "webextension-polyfill-ts"; import { encodeTagName, getUrl } from "~/utils";
import { BrowserCommand, Message, encodeTagName, getUrl } from "../Common"; import { BrowserCommand, Message, PostDetails } from "~/models";
import { Config } from "../Config"; import { PostAlreadyUploadedError, SzuruError } from "~/api/models";
import SzuruWrapper from "../SzuruWrapper"; import SzurubooruApi from "~/api";
import { PostAlreadyUploadedError, SzuruError } from "../SzuruTypes"; import { Config } from "~/config";
import { PostViewModel } from "../ViewModels";
async function uploadPost(post: PostViewModel) { // Only on dev mode
if (import.meta.hot) {
// @ts-expect-error for background HMR
import("/@vite/client");
// load latest content script
import("./contentScriptHMR");
}
async function uploadPost(post: PostDetails) {
console.dir(post); console.dir(post);
const cfg = await Config.load(); const cfg = await Config.load();
const szuru = SzuruWrapper.createFromConfig(cfg.sites[0]);
if (cfg.sites.length == 0) {
// TODO: Generic error handler which also shows the message in the popup frontend.
browser.runtime.sendMessage(new BrowserCommand("push_message", new Message("cfg.sites.length == 0", "error")));
return;
}
const szuru = SzurubooruApi.createFromConfig(cfg.sites[0]);
try { try {
// Create and upload post // Create and upload post
browser.runtime.sendMessage(new BrowserCommand("remove_messages", 10)); browser.runtime.sendMessage(new BrowserCommand("pop_messages", 10));
browser.runtime.sendMessage(new BrowserCommand("push_message", new Message("Uploading..."))); browser.runtime.sendMessage(new BrowserCommand("push_message", new Message("Uploading...")));
const createdPost = await szuru.createPost(post); const createdPost = await szuru.createPost(post);
browser.runtime.sendMessage(new BrowserCommand("remove_messages", 1)); browser.runtime.sendMessage(new BrowserCommand("pop_messages", 1));
browser.runtime.sendMessage( browser.runtime.sendMessage(
new BrowserCommand("push_message", new Message("Uploaded post " + createdPost.id, "success")) new BrowserCommand("push_message", new Message("Uploaded post " + createdPost.id, "success"))
); );
@ -44,7 +58,7 @@ async function uploadPost(post: PostViewModel) {
let categoriesChangedCount = 0; let categoriesChangedCount = 0;
for (const i in tags) { for (const i in tags) {
browser.runtime.sendMessage(new BrowserCommand("remove_messages", 1)); browser.runtime.sendMessage(new BrowserCommand("pop_messages", 1));
browser.runtime.sendMessage( browser.runtime.sendMessage(
new BrowserCommand("push_message", new Message(`Updating tag ${i}/${unsetCategoryTags.length}`)) new BrowserCommand("push_message", new Message(`Updating tag ${i}/${unsetCategoryTags.length}`))
); );
@ -61,7 +75,7 @@ async function uploadPost(post: PostViewModel) {
} }
} }
browser.runtime.sendMessage(new BrowserCommand("remove_messages", 1)); browser.runtime.sendMessage(new BrowserCommand("pop_messages", 1));
if (categoriesChangedCount > 0) { if (categoriesChangedCount > 0) {
browser.runtime.sendMessage( browser.runtime.sendMessage(
@ -69,9 +83,10 @@ async function uploadPost(post: PostViewModel) {
); );
} }
} }
} catch (ex) { } catch (ex: any) {
browser.runtime.sendMessage(new BrowserCommand("remove_messages", 1)); browser.runtime.sendMessage(new BrowserCommand("pop_messages", 1));
const error = ex as SzuruError; const error = ex as SzuruError;
// TODO: Actual good error handling/messaging // TODO: Actual good error handling/messaging
if (error.name) { if (error.name) {
console.error(error); console.error(error);
@ -95,6 +110,9 @@ async function uploadPost(post: PostViewModel) {
} }
async function messageHandler(cmd: BrowserCommand): Promise<any> { async function messageHandler(cmd: BrowserCommand): Promise<any> {
console.log("Received message");
console.dir(cmd);
switch (cmd.name) { switch (cmd.name) {
case "upload_post": case "upload_post":
return uploadPost(cmd.data); return uploadPost(cmd.data);

View File

@ -0,0 +1,22 @@
<!-- Based on https://github.com/cloudacy/vue-markdown-render/blob/master/src/VueMarkdown.ts -->
<script setup lang="ts">
import MarkdownIt from "markdown-it";
const props = defineProps({
source: {
type: String,
required: true,
},
});
const md = new MarkdownIt({
breaks: true,
});
let content = computed(() => md?.render(props.source));
</script>
<template>
<div v-html="content"></div>
</template>

View File

@ -0,0 +1,128 @@
<script setup lang="ts">
import { ScrapedNote } from "neo-scraper";
class Point {
constructor(public x: any, public y: any) {}
}
// HACK: Copied from old client
function* range(start = 0, end: any = null, step = 1) {
if (end === null) {
end = start;
start = 0;
}
for (let i = start; i < end; i += step) {
yield i;
}
}
// HACK: Copied from old client
function _getNoteCentroid(note: any) {
const vertexCount = note.polygon.length;
const centroid = new Point(0, 0);
let signedArea = 0.0;
for (let i of range(vertexCount)) {
const x0 = note.polygon.at(i)[0];
const y0 = note.polygon.at(i)[1];
const x1 = note.polygon.at((i + 1) % vertexCount)[0];
const y1 = note.polygon.at((i + 1) % vertexCount)[1];
const a = x0 * y1 - x1 * y0;
signedArea += a;
centroid.x += (x0 + x1) * a;
centroid.y += (y0 + y1) * a;
}
signedArea *= 0.5;
centroid.x /= 6 * signedArea;
centroid.y /= 6 * signedArea;
return centroid;
}
defineProps(["notes"]);
const mouseOverNote = ref(false);
const mouseOverNoteText = ref(false);
const hoverNote = ref<ScrapedNote | undefined>(undefined);
const showHoverNote = computed(() => (!hoverNote.value ? false : mouseOverNote.value || mouseOverNoteText.value));
const hoverNoteStyle = computed(() => {
if (!hoverNote.value) return "";
const { x, y } = _getNoteCentroid(hoverNote.value);
const top = y * 100;
const left = x * 100;
return `display: block; top: ${top}%; left: ${left}%`;
});
</script>
<template>
<div>
<div
v-if="hoverNote && showHoverNote"
class="note-text"
:style="hoverNoteStyle"
@mouseenter="mouseOverNoteText = true"
@mouseleave="mouseOverNoteText = false"
>
<div class="wrapper">
<Markdown :source="hoverNote.text" />
</div>
</div>
<svg class="notes-overlay" preserveAspectRatio="none" viewBox="0 0 1 1">
<g v-for="note in notes">
<polygon
vector-effect="non-scaling-stroke"
stroke-alignment="inside"
:points="note.polygon.join()"
@mouseenter="
hoverNote = note;
mouseOverNote = true;
"
@mouseleave="mouseOverNote = false"
/>
</g>
</svg>
</div>
</template>
<style lang="scss" scoped>
.notes-overlay {
width: 100%;
height: 100%;
position: absolute;
}
.notes-overlay g {
stroke-width: 1px;
}
.notes-overlay g polygon {
fill: rgba(255, 255, 205, 0.3);
stroke: rgba(0, 0, 0, 0.2);
}
.note-text {
position: absolute;
max-width: 22.5em;
display: none;
text-align: left;
z-index: 20;
transform: translate(-50%, -50%);
> .wrapper {
background: lemonchiffon;
padding: 0.3em 0.6em;
border: 1px solid black;
color: black;
box-sizing: border-box;
}
& :deep(p:last-of-type) {
margin-bottom: 0;
}
& :deep(p:first-of-type) {
margin-top: 0;
}
}
</style>

View File

@ -0,0 +1,11 @@
import { describe, expect, it } from "vitest";
import { mount } from "@vue/test-utils";
import Logo from "../Logo.vue";
describe("Logo Component", () => {
it("should render", () => {
const wrapper = mount(Logo);
expect(wrapper.html()).toBeTruthy();
});
});

View File

@ -0,0 +1,19 @@
import { NeoScraper, ScrapeResults } from "neo-scraper";
import { BrowserCommand } from "~/models";
// Firefox `browser.tabs.executeScript()` requires scripts return a primitive value
(() => {
function grabPost(): ScrapeResults {
const scraper = new NeoScraper();
return scraper.scrapeDocument(document, true);
}
async function messageHandler(cmd: BrowserCommand): Promise<any> {
switch (cmd.name) {
case "grab_post":
return grabPost();
}
}
browser.runtime.onMessage.addListener(messageHandler);
})();

4363
src/css/fontawesome.css vendored

File diff suppressed because it is too large Load Diff

View File

@ -1,17 +0,0 @@
/*!
* Font Awesome Free 5.10.1 by @fontawesome - https://fontawesome.com
* License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License)
*/
@font-face {
font-family: "Font Awesome 5 Free";
font-style: normal;
font-weight: 900;
font-display: auto;
src: url("../fonts/fa-solid-900.woff2") format("woff2");
}
.fa,
.fas {
font-family: "Font Awesome 5 Free";
font-weight: 900;
}

15
src/env.ts Normal file
View File

@ -0,0 +1,15 @@
const forbiddenProtocols = [
"chrome-extension://",
"chrome-search://",
"chrome://",
"devtools://",
"edge://",
"https://chrome.google.com/webstore",
];
export function isForbiddenUrl(url: string): boolean {
return forbiddenProtocols.some((protocol) => url.startsWith(protocol));
}
export const isFirefox = navigator.userAgent.includes("Firefox");
export const isChrome = navigator.userAgent.match(/chrome|chromium|crios/i);

Binary file not shown.

6
src/global.d.ts vendored Normal file
View File

@ -0,0 +1,6 @@
declare const __DEV__: boolean;
declare module "*.vue" {
const component: any;
export default component;
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.6 KiB

View File

@ -0,0 +1,9 @@
import type { App } from "vue";
import { library } from "@fortawesome/fontawesome-svg-core";
import { FontAwesomeIcon } from "@fortawesome/vue-fontawesome";
import { faCog } from "@fortawesome/free-solid-svg-icons";
export function setupApp(app: App) {
library.add(faCog);
app.component("font-awesome-icon", FontAwesomeIcon);
}

View File

@ -1,30 +0,0 @@
{
"name": "SzuruChrome",
"description": "Import media from various sites into szurubooru.",
"version": null,
"manifest_version": 2,
"icons": {
"48": "icons/icon_48.png",
"128": "icons/icon_128.png"
},
"browser_action": {
"default_title": "SzuruChrome",
"default_popup": "popup/popup.html"
},
"options_page": "options/options.html",
"permissions": ["storage", "activeTab", "webRequest", "webRequestBlocking", "<all_urls>"],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["vendor.js", "scripts/content.js"]
}
],
"background": {
"scripts": ["vendor.js", "scripts/background.js"]
},
"browser_specific_settings": {
"gecko": {
"id": "{13372607-2257-4360-8f51-5ce66fa73350}"
}
}
}

55
src/manifest.ts Normal file
View File

@ -0,0 +1,55 @@
import fs from "fs-extra";
import type { Manifest } from "webextension-polyfill";
import type PkgType from "../package.json";
import { isDev, port, r } from "../scripts/utils";
export async function getManifest() {
const pkg = (await fs.readJSON(r("package.json"))) as typeof PkgType;
// update this file to update this manifest.json
// can also be conditional based on your need
const manifest: Manifest.WebExtensionManifest = {
name: pkg.displayName,
description: pkg.description,
version: pkg.version,
manifest_version: 2,
icons: {
16: "./assets/icon-128.png",
48: "./assets/icon-128.png",
128: "./assets/icon-128.png",
},
browser_action: {
default_title: pkg.displayName,
default_popup: "./dist/popup/index.html",
},
options_ui: {
page: "./dist/options/index.html",
open_in_tab: true,
chrome_style: false,
},
background: {
page: "./dist/background/index.html",
// persistent: false,
},
permissions: ["storage", "activeTab", "webRequest", "webRequestBlocking", "<all_urls>"],
content_scripts: [
{
matches: ["http://*/*", "https://*/*"],
js: ["./dist/contentScripts/index.global.js"],
},
],
};
if (isDev) {
// for content script, as browsers will cache them for each reload,
// we use a background script to always inject the latest version
// see src/background/contentScriptHMR.ts
delete manifest.content_scripts;
manifest.permissions?.push("webNavigation");
// this is required on dev for Vite script to load
manifest.content_security_policy = `script-src 'self' http://localhost:${port}; object-src 'self'`;
}
return manifest;
}

75
src/models/index.ts Normal file
View File

@ -0,0 +1,75 @@
import { BooruTypes, ContentType, ScrapedNote, ScrapedPost, ScrapedTag } from "neo-scraper";
import { MicroTag, Tag } from "~/api/models";
export class TagDetails {
public implications: TagDetails[] = [];
constructor(public name: string, public category?: BooruTypes.TagCategory, public usages?: number) {}
static fromTag(tag: Tag) {
const x = new TagDetails(tag.names[0], <BooruTypes.TagCategory>tag.category, tag.usages);
if (tag.implications) {
x.implications = tag.implications.map((y) => TagDetails.fromMicroTag(y));
}
return x;
}
static fromMicroTag(tag: MicroTag) {
return new TagDetails(tag.names[0], <BooruTypes.TagCategory>tag.category, tag.usages);
}
static fromScapedTag(tag: ScrapedTag): TagDetails {
return new TagDetails(tag.name, tag.category);
}
}
export class PostDetails {
name = "";
tags: TagDetails[] = [];
notes: ScrapedNote[];
contentUrl: string;
contentToken?: string;
pageUrl: string;
contentType: ContentType;
rating: BooruTypes.SafetyRating;
source = "";
referrer?: string;
resolution?: [number, number];
constructor(post: ScrapedPost) {
this.contentUrl = post.contentUrl;
this.pageUrl = post.pageUrl;
this.contentType = post.contentType;
this.rating = post.rating;
this.source = post.sources.join("\n");
this.referrer = post.referrer;
this.tags = post.tags.map((x) => TagDetails.fromScapedTag(x));
this.notes = post.notes;
this.resolution = post.resolution;
}
}
export type MessageType = "error" | "info" | "success";
export type MessageCategory = "none" | "persistent" | "find_similar";
export class Message {
id: string;
constructor(public content: string, public level: MessageType = "info", public category: MessageCategory = "none") {
this.id = window.crypto.randomUUID();
}
}
export type BrowserCommandName = "grab_post" | "upload_post" | "push_message" | "pop_messages";
export class BrowserCommand<T = any> {
name: BrowserCommandName;
data?: T;
constructor(name: BrowserCommandName, data?: T) {
this.name = name;
this.data = data;
}
}

View File

@ -1,3 +1,87 @@
<script setup lang="ts">
import { useColorMode } from "@vueuse/core";
import SzuruWrapper from "~/api";
import { Config } from "~/config";
let domain = ref("");
let username = ref("");
let authToken = ref("");
let autoSearchSimilar = ref(false);
let loadTagCounts = ref(false);
let addPageUrlToSource = ref(false);
let useContentTokens = ref(false);
let statusText = ref("");
let statusType = ref("");
type StatusType = "ok" | "error";
async function testConnection() {
if (!domain.value || !username.value || !authToken.value) {
setStatus("Domain, username and authentication token are all required.", "error");
return;
}
const api = new SzuruWrapper(domain.value, username.value, authToken.value);
try {
const info = (await api.getInfo()) as any;
const instanceName = info?.config.name;
if (instanceName == undefined) {
setStatus(`Connected to ${domain.value}, but it is not a szurubooru instance.`, "error");
} else {
setStatus(`Connected to ${info.config.name} at ${domain.value}`);
}
} catch (ex) {
// TODO: This error message is not very descriptive.
console.dir(ex);
setStatus("Couldn't connect to " + domain.value + "\n\n" + ex, "error");
}
}
async function saveSettings() {
let config = await Config.load();
// We currently only support one domain
config.sites = [
{
domain: domain.value,
username: username.value,
authToken: authToken.value,
},
];
config.autoSearchSimilar = autoSearchSimilar.value;
config.loadTagCounts = loadTagCounts.value;
config.addPageUrlToSource = addPageUrlToSource.value;
config.useContentTokens = useContentTokens.value;
await config.save();
setStatus("Settings successfully saved");
}
function setStatus(text: string, type: StatusType = "ok") {
statusText.value = text;
statusType.value = "status-" + type;
}
onMounted(async () => {
let config = await Config.load();
if (config.sites.length > 0) {
domain.value = config.sites[0].domain;
username.value = config.sites[0].username;
authToken.value = config.sites[0].authToken;
}
autoSearchSimilar.value = config.autoSearchSimilar;
loadTagCounts.value = config.loadTagCounts;
addPageUrlToSource.value = config.addPageUrlToSource;
useContentTokens.value = config.useContentTokens;
});
let mode = useColorMode({ emitAuto: true });
</script>
<template> <template>
<div class="content-holder"> <div class="content-holder">
<div class="content-wrapper"> <div class="content-wrapper">
@ -17,8 +101,8 @@
</li> </li>
<li> <li>
<label>Theme</label> <label>Theme</label>
<select v-model="theme"> <select v-model="mode">
<option value="system">System</option> <option value="auto">System</option>
<option value="light">Light</option> <option value="light">Light</option>
<option value="dark">Dark</option> <option value="dark">Dark</option>
</select> </select>
@ -69,100 +153,6 @@
</div> </div>
</template> </template>
<script lang="ts">
import Vue from "vue";
import SzuruWrapper from "../SzuruWrapper";
import { Config, SzuruSiteConfig, Theme } from "../Config";
import { applyTheme } from "../Common";
type StatusType = "ok" | "error";
export default Vue.extend({
data() {
return {
domain: "",
username: "",
authToken: "",
autoSearchSimilar: false,
loadTagCounts: false,
addPageUrlToSource: false,
useContentTokens: false,
theme: "system" as Theme,
statusText: "",
statusType: "",
};
},
methods: {
async testConnection() {
if (!this.domain || !this.username || !this.authToken) {
this.setStatus("Domain, username and authentication token are all required.", "error");
return;
}
const api = new SzuruWrapper(this.domain, this.username, this.authToken);
try {
const info = (await api.getInfo()) as any;
const instanceName = info?.config.name;
if (instanceName == undefined) {
this.setStatus(`Connected to ${this.domain}, but it is not a szurubooru instance.`, "error");
} else {
this.setStatus(`Connected to ${info.config.name} at ${this.domain}`);
}
} catch (ex) {
// TODO: This error message is not very descriptive.
console.dir(ex);
this.setStatus("Couldn't connect to " + this.domain + "\n\n" + ex, "error");
}
},
async saveSettings() {
let config = await Config.load();
// We currently only support one domain
let siteConfig = new SzuruSiteConfig();
siteConfig.domain = this.domain;
siteConfig.username = this.username;
siteConfig.authToken = this.authToken;
config.sites = [siteConfig];
config.autoSearchSimilar = this.autoSearchSimilar;
config.loadTagCounts = this.loadTagCounts;
config.addPageUrlToSource = this.addPageUrlToSource;
config.useContentTokens = this.useContentTokens;
config.theme = this.theme;
await config.save();
this.setStatus("Settings successfully saved");
},
setStatus(text: string, type: StatusType = "ok") {
this.statusText = text;
this.statusType = "status-" + type;
},
},
async mounted() {
let config = await Config.load();
// console.log(`Loaded ${config.sites.length} sites`);
// We currently only support one domain
if (config.sites.length > 0) {
this.domain = config.sites[0].domain;
this.username = config.sites[0].username;
this.authToken = config.sites[0].authToken;
}
this.autoSearchSimilar = config.autoSearchSimilar;
this.loadTagCounts = config.loadTagCounts;
this.addPageUrlToSource = config.addPageUrlToSource;
this.useContentTokens = config.useContentTokens;
this.theme = config.theme;
},
watch: {
theme: (value) => applyTheme(value),
},
});
</script>
<style lang="scss" scoped> <style lang="scss" scoped>
.content-holder { .content-holder {
padding: 1.5em; padding: 1.5em;
@ -183,7 +173,7 @@ export default Vue.extend({
} }
} }
html[data-theme="dark"] .content-holder > .content-wrapper:not(.transparent) { html.dark .content-holder > .content-wrapper:not(.transparent) {
background: var(--section-header-bg-color); background: var(--section-header-bg-color);
} }

12
src/options/index.html Normal file
View File

@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<base target="_blank" />
<title>Options</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="./main.ts"></script>
</body>
</html>

8
src/options/main.ts Normal file
View File

@ -0,0 +1,8 @@
import { createApp } from "vue";
import App from "./Options.vue";
import { setupApp } from "~/logic/common-setup";
import "../styles";
const app = createApp(App);
setupApp(app);
app.mount("#app");

View File

@ -1,14 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>SzuruChrome - Options</title>
<link rel="stylesheet" href="options.css" />
</head>
<body>
<div id="app"></div>
<script src="../vendor.js"></script>
<script src="options.js"></script>
</body>
</html>

View File

@ -1,13 +0,0 @@
import "normalize.css";
import "../css/style.scss";
import Vue from "vue";
import App from "./App.vue";
import { applyTheme } from "../Common";
applyTheme();
new Vue({
el: "#app",
render: h => h(App)
});

View File

@ -1,668 +0,0 @@
<template>
<div class="popup-container">
<div class="popup-messages">
<ul class="messages">
<li v-for="msg in messages" :key="msg.content" :class="getMessageClasses(msg)" v-html="msg.content"></li>
</ul>
</div>
<div class="popup-columns">
<div class="popup-left">
<div class="popup-section">
<div class="section-header">
<span>Basic info</span>
<i class="fas fa-cog cursor-pointer" @click="openSettings"></i>
</div>
<div class="section-row" v-if="selectedPost.resolution != undefined">
<ul class="compact">
<li>Resolution: {{ resolutionToString(selectedPost.resolution) }}</li>
</ul>
</div>
<div class="section-row">
<span class="section-label">Safety</span>
<div class="flex">
<label>
<input type="radio" value="safe" v-model="selectedPost.rating" />
<span class="checkmark"></span>
Safe
</label>
<label>
<input type="radio" value="sketchy" v-model="selectedPost.rating" />
<span class="checkmark"></span>
Sketchy
</label>
<label>
<input type="radio" value="unsafe" v-model="selectedPost.rating" />
<span class="checkmark"></span>
Unsafe
</label>
</div>
</div>
<div class="section-row">
<span class="section-label">Source</span>
<textarea v-model="selectedPost.source" />
</div>
</div>
<div class="popup-section">
<div class="section-header">
<span>Tags</span>
</div>
<div class="section-row" style="display: flex; flex-direction: column">
<div style="display: flex">
<input
type="text"
v-model="addTagInput"
@keyup="onAddTagKeyUp"
@keydown="onAddTagKeyDown"
autocomplete="off"
/>
<button class="primary" style="margin-left: 5px" @click="addTagFromCurrentInput">Add</button>
</div>
<div class="autocomplete-items" v-bind:class="{ show: autocompleteShown }">
<div
v-for="(tag, idx) in autocompleteTags"
@click="onClickAutocompleteTagItem(tag)"
:key="tag.name"
:class="{
active: idx == autocompleteIndex,
}"
>
<span :class="getTagClasses(tag)">{{ tag.name }}</span>
<span class="tag-usages">{{ tag.usages ? tag.usages : "" }}</span>
</div>
</div>
</div>
<div class="section-row">
<ul class="compact-tags">
<li v-for="tag in selectedPost.tags" :key="tag.name">
<a class="remove-tag" @click="removeTag(tag)">x</a>
<span :class="getTagClasses(tag)" v-html="breakTagName(tag.name)"></span>
<span v-if="showTagUsages" class="tag-usages tag-usages-reserve-space">{{
tag.usages ? tag.usages : ""
}}</span>
</li>
</ul>
</div>
</div>
<div class="popup-section">
<div class="section-row">
<select disabled>
<option>{{ activeSite != null ? activeSite.domain : "(no site available)" }}</option>
</select>
</div>
</div>
</div>
<div class="popup-right">
<div class="popup-section">
<select v-model="selectedPost">
<option v-for="post in posts" v-bind:key="post.name" v-bind:value="post">{{ post.name }}</option>
</select>
</div>
<div class="popup-section">
<div style="display: flex; gap: 5px">
<button v-if="showFindSimilarButton" class="primary" @click="findSimilar">Find similar</button>
<button class="primary full" @click="upload">Import</button>
</div>
</div>
<div class="popup-section">
<div class="post-container">
<img :src="selectedPost.contentUrl" v-if="selectedPost.contentType == 'image'" />
<video v-if="selectedPost.contentType == 'video'" controls>
<source :src="selectedPost.contentUrl" />
</video>
<div class="post-overlay">
<PostNotes :notes="selectedPost.notes" />
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script lang="ts">
import Vue from "vue";
import axios, { CancelTokenSource } from "axios";
import { browser, Runtime, WebRequest } from "webextension-polyfill-ts";
import { ScrapedPost, ScrapeResults } from "neo-scraper";
import SzuruWrapper from "../SzuruWrapper";
import { ImageSearchResult, Post } from "../SzuruTypes";
import { Config, SzuruSiteConfig } from "../Config";
import { BrowserCommand, Message, getUrl, isChrome, encodeTagName } from "../Common";
import { PostViewModel, TagViewModel } from "../ViewModels";
import PostNotes from "./components/PostNotes.vue";
export default Vue.extend({
components: { PostNotes },
data() {
return {
config: null as Config | null,
activeSite: null as SzuruSiteConfig | null,
szuru: null as SzuruWrapper | null,
posts: [] as PostViewModel[],
selectedPost: new PostViewModel(new ScrapedPost()), // Shouldn't be null because VueJS gets a mental breakdown when it sees a null.
messages: [] as Message[],
addTagInput: "",
autocompleteShown: false,
autocompleteTags: [] as TagViewModel[],
cancelSource: null as CancelTokenSource | null,
autocompleteIndex: -1,
showTagUsages: false,
showFindSimilarButton: true,
};
},
watch: {
selectedPost() {
if (this.config && this.config.autoSearchSimilar) {
// No need to check if any vars are unset, findSimilar does that internally
this.findSimilar();
}
},
},
methods: {
async getActiveTabId() {
const activeTabs = await browser.tabs.query({
active: true,
currentWindow: true,
});
if (activeTabs.length > 0) return activeTabs[0].id!;
throw new Error("No active tab.");
},
// Try to scrape the post from the page
async grabPost() {
// Get active tab
const activeTabId = await this.getActiveTabId();
// Send 'grab_post' to the content script on the active tab
const x = await browser.tabs.sendMessage(activeTabId, new BrowserCommand("grab_post"));
// We need to create a new ScrapeResults object and fill it with our data, because the get_posts()
// method gets 'lost' when sent from the contentscript to the popup (it gets JSON.stringified and any prototype defines are lost there)
const res = Object.assign(new ScrapeResults(), x);
// Clear current posts array
this.posts = [];
for (const result of res.results) {
for (const i in result.posts) {
const vm = new PostViewModel(result.posts[i]);
vm.name = `[${result.engine}] Post ${parseInt(i) + 1}`; // parseInt() is required!
// Add current pageUrl to the source if either
// a. user has addPageUrlToSource set to true
// b. source is empty
if (this.config?.addPageUrlToSource || vm.source == "") {
if (vm.source != "") vm.source += "\n";
vm.source += vm.pageUrl;
}
this.posts.push(vm);
}
}
if (this.posts.length > 0) {
this.selectedPost = this.posts[0];
if (this.config?.loadTagCounts) {
this.loadTagCounts();
}
} else {
this.pushInfo("No posts found.");
}
},
// Try to upload the post to the selected szurubooru instance
async upload() {
window.scrollTo(0, 0);
// Outsource to background.ts
const cmd = new BrowserCommand("upload_post", this.selectedPost);
await browser.runtime.sendMessage(cmd);
// TODO: Handle errors/status update
},
// Open extension settings page in new tab
async openSettings() {
const url = browser.runtime.getURL("options/options.html");
window.open(url);
},
getTagClasses(tag: TagViewModel): string[] {
let classes: string[] = [];
if (tag.category && <any>tag.category != "default") {
classes.push("tag-" + tag.category);
} else {
classes.push("tag-general");
}
return classes;
},
breakTagName(tagName: string) {
// Based on https://stackoverflow.com/a/6316913
return tagName.replace(/\_/g, "_<wbr>");
},
resolutionToString(resolution: [number, number]) {
if (resolution && resolution.length == 2) {
return resolution[0] + "x" + resolution[1];
}
return "";
},
// Remove tag from post's taglist
removeTag(tag: TagViewModel) {
if (this.selectedPost) {
const idx = this.selectedPost.tags.indexOf(tag);
if (idx != -1) {
this.selectedPost.tags.splice(idx, 1);
}
}
},
getMessageClasses(message: Message) {
let classes: string[] = [];
switch (message.level) {
case "error":
classes.push("message-error");
break;
case "success":
classes.push("message-success");
break;
}
return classes;
},
// Add info message
pushInfo(message: string, category: string | null = null): Message {
let msg = new Message(message, "info", category);
this.messages.push(msg);
return msg;
},
// Add error message
pushError(message: string, category: string | null = null): Message {
let msg = new Message(message, "error", category);
this.messages.push(msg);
return msg;
},
// Clear messages of given category. When category is empty clear all messages.
clearMessages(category: string | null = null) {
if (category) {
for (let i = 0; i < this.messages.length; i++) {
if (this.messages[i].category == category) {
// Decrement i to negate the i++, because if we remove one object the items
// shift one place to the left, aka index--
// If we don't do i-- we'll skip the next item in our for loop
this.messages.splice(i--, 1);
}
}
} else {
this.messages = [];
}
},
getPostUrl(post: Post): string {
if (!this.activeSite) return "";
return getUrl(this.activeSite.domain, "post", post.id.toString());
},
// Add tag to the post's taglist
addTag(tag: TagViewModel) {
if (this.selectedPost) {
// Only add tag if it doesn't already exist
if (tag.name.length > 0 && this.selectedPost.tags.find((x) => x.name == tag.name) == undefined) {
this.selectedPost.tags.push(tag);
// Add implications for the tag
this.selectedPost.tags.push(...tag.implications);
}
}
},
// Find posts similar to the grabbed post (this.selectedPost)
async findSimilar() {
if (!this.selectedPost || !this.szuru) {
return;
}
this.clearMessages("FIND_SIMILAR");
const msg = this.pushInfo("Searching for similar posts...", "FIND_SIMILAR");
try {
let res: ImageSearchResult | undefined;
if (this.config?.useContentTokens) {
let tmpRes = await this.szuru.uploadTempFile(this.selectedPost.contentUrl);
// TODO: Error handling?
// Save contentToken in PostViewModel so that we can reuse it when creating/uploading the post.
this.selectedPost.contentToken = tmpRes.token;
res = await this.szuru.reverseSearchToken(tmpRes.token);
} else {
res = await this.szuru.reverseSearch(this.selectedPost.contentUrl);
}
if (!res.exactPost && res.similarPosts.length == 0) {
msg.content = "No similar posts found";
} else {
if (res.exactPost) {
msg.content = `<a href='${this.getPostUrl(res.exactPost)}' target='_blank'>
Post already uploaded (${res.exactPost.id})</a>`;
msg.level = "error";
}
for (const similarPost of res.similarPosts) {
// Don't show this message for the exactPost (because we have a different message for that)
if (res.exactPost && res.exactPost.id == similarPost.post.id) {
continue;
}
this.pushInfo(
`<a href='${this.getPostUrl(similarPost.post)}' target='_blank'>Post ${similarPost.post.id}
looks ${Math.round(100 - similarPost.distance * 100)}% similar</a>`,
"FIND_SIMILAR"
);
}
}
} catch (ex) {
this.clearMessages();
this.pushError("Error: couldn't reverse search.");
}
},
// Returns ScrapedPost for a contentUrl, or undefined if the given contentUrl does not belong to a ScrapedPost.
getPostForUrl(contentUrl: string): PostViewModel | undefined {
for (const post of this.posts) {
if (post.contentUrl == contentUrl) return post;
}
return undefined;
},
async loadTagCounts() {
const allTags = this.posts.flatMap((x) => x.tags);
for (let i = 0; i < allTags.length; i += 100) {
const query = allTags
.slice(i, i + 101)
.map((x) => encodeTagName(x.name))
.join();
const resp = await this.szuru?.getTags(query);
// Not the best code, but it works I guess?
if (resp) {
for (let post of this.posts)
for (let tag of resp.results)
for (let postTag of post.tags)
if (postTag.name == tag.names[0]) {
postTag.usages = tag.usages;
break;
}
}
}
},
async onAddTagKeyUp(e: KeyboardEvent) {
await this.autocompletePopulator((<HTMLInputElement>e.target).value);
},
addTagFromCurrentInput() {
this.addTag(new TagViewModel(this.addTagInput));
this.addTagInput = ""; // Reset input
// Only needed when the button is clicked
// When this is triggered by the enter key the `onAddTagKeyUp` will internally also hide the autocomplete.
// Though hiding it twice doesn't hurt so we don't care.
this.hideAutocomplete();
// TODO: Do we also want to add the implications?
// Answer: Probably not, because if the user wanted to have implications they should've clicked/selected the autocomplete entry.
},
onAddTagKeyDown(e: KeyboardEvent) {
if (e.code == "ArrowDown") {
e.preventDefault();
if (this.autocompleteIndex < this.autocompleteTags.length - 1) {
this.autocompleteIndex++;
}
} else if (e.code == "ArrowUp") {
e.preventDefault();
if (this.autocompleteIndex >= 0) {
this.autocompleteIndex--;
}
} else if (e.code == "Enter") {
if (this.autocompleteIndex == -1) {
this.addTagFromCurrentInput();
} else {
// Add auto completed tag
const tagToAdd = this.autocompleteTags[this.autocompleteIndex];
this.addTag(tagToAdd);
this.addTagInput = ""; // Reset input
}
}
},
onClickAutocompleteTagItem(tag: TagViewModel) {
this.addTag(tag);
this.addTagInput = ""; // Reset input
this.autocompleteShown = false; // Hide autocomplete list
},
hideAutocomplete() {
this.autocompleteIndex = -1;
this.autocompleteShown = false;
},
async autocompletePopulator(input: string) {
// Based on https://www.w3schools.com/howto/howto_js_autocomplete.asp
// TODO: Put this in a separate component
// Hide autocomplete when the input is empty, and don't do anything else.
if (input.length == 0) {
this.hideAutocomplete();
return;
}
// Cancel previous request
if (this.cancelSource) {
this.cancelSource.cancel();
}
this.cancelSource = axios.CancelToken.source();
const query = decodeURIComponent(`*${encodeTagName(input)}* sort:usages`);
const resp = await this.szuru?.getTags(
query,
0,
100,
["names", "category", "usages", "implications"],
this.cancelSource.token
);
this.autocompleteTags = resp!.results.map((x) => TagViewModel.fromTag(x));
if (this.autocompleteTags.length > 0) this.autocompleteShown = true;
},
},
async mounted() {
this.config = await Config.load();
this.showTagUsages = this.config.loadTagCounts;
this.showFindSimilarButton = !this.config.autoSearchSimilar;
this.activeSite = this.config.sites.length > 0 ? this.config.sites[0] : null;
if (!this.activeSite) {
this.pushError("No szurubooru server configured!");
} else {
this.szuru = SzuruWrapper.createFromConfig(this.activeSite);
}
browser.runtime.onMessage.addListener((cmd: BrowserCommand, _sender: Runtime.MessageSender) => {
switch (cmd.name) {
case "push_message":
this.messages.push(cmd.data);
break;
case "remove_messages":
for (let i = 0; i < cmd.data; i++) {
if (this.messages.length == 0) break;
this.messages.pop();
}
break;
}
});
let extraInfoSpec: WebRequest.OnBeforeSendHeadersOptions[] = ["requestHeaders", "blocking"];
if (isChrome()) {
extraInfoSpec.push("extraHeaders" as any);
}
// Add "Referer" header to all requests if post.referrer is set.
// This is needed in some rare cases where websites disallow hotlinking to images.
// This will probably stop working in Chrome sometime in 2023 due to the Manifest V3 webRequestBlocking bullshit.
// Firefox users should be fine.
browser.webRequest.onBeforeSendHeaders.addListener(
(details: WebRequest.OnBeforeSendHeadersDetailsType) => {
let requestHeaders = details.requestHeaders ?? [];
// Find which ScrapedPost this belongs to, if any.
const post = this.getPostForUrl(details.url);
if (post != undefined && post.referrer) {
console.log(`Setting referrer to '${post.referrer}' for request to '${post.contentUrl}'.`);
// TODO: If the headers already have a 'Referer' header this will _not_ override that.
// As far as I am aware the 'img' tag doesn't set this header, so it shouldn't be a problem.
requestHeaders.push({ name: "Referer", value: post.referrer });
}
return <WebRequest.BlockingResponse>{
requestHeaders,
};
},
{ urls: ["<all_urls>"] },
extraInfoSpec
);
// Always call grabPost, even when there is no activeSite
await this.grabPost();
},
});
</script>
<style lang="scss" scoped>
video {
width: 100%;
}
textarea,
select {
font-size: 90%;
}
label {
flex: 1 0 auto;
input[type="radio"] {
margin: 3px 3px 0 0;
}
}
.popup-container {
display: flex;
flex-direction: column;
}
.popup-messages {
grid-column: 1 / 3;
margin: 0 10px;
}
.popup-columns {
display: flex;
flex-direction: row;
}
.popup-left {
flex: 1 0 auto;
}
.popup-right {
flex: 1 1 auto;
}
.popup-section {
margin: 10px;
}
.section-header {
height: 30px;
padding: 0 6px 0 10px;
background-color: var(--section-header-bg-color);
display: flex;
justify-content: space-between;
align-items: center;
> span {
font-size: 1.2em;
vertical-align: middle;
color: var(--section-header-fg-color);
}
}
.section-row {
margin: 10px 5px 0;
}
.section-label {
display: block;
margin: 0 0 5px 0;
}
.section-block {
display: block;
}
.cursor-pointer {
cursor: pointer;
}
.autocomplete-items {
position: absolute;
z-index: 10;
background-color: var(--bg-main-color);
border: 2px solid var(--primary-color);
margin-top: 34px;
display: none;
&.show {
display: block;
}
> div {
cursor: pointer;
padding: 2px 4px;
&:hover {
background: var(--primary-color);
> span {
color: var(--text-color);
}
}
}
> div.active {
background: var(--primary-color);
> span {
color: var(--text-color);
}
}
}
/* Hacky way to stop the layout from resizing when we lazy load the usage count. */
.tag-usages-reserve-space {
min-width: 5ch; /* 5 character width */
display: inline-block;
}
.post-container {
position: relative;
display: flex;
}
.post-overlay {
position: absolute;
width: 100%;
height: 100%;
}
</style>

696
src/popup/Popup.vue Normal file
View File

@ -0,0 +1,696 @@
<script setup lang="ts">
import { useDark } from "@vueuse/core";
import axios, { CancelTokenSource } from "axios";
import { ScrapedPost, ScrapeResults } from "neo-scraper";
import { getUrl, encodeTagName } from "~/utils";
import { BrowserCommand, Message, PostDetails, TagDetails, MessageCategory } from "~/models";
import SzuruWrapper from "~/api";
import { ImageSearchResult, Post } from "~/api/models";
import { isChrome } from "~/env";
import { Runtime, WebRequest } from "webextension-polyfill";
import { Ref } from "vue";
import { Config, SzuruSiteConfig } from "~/config";
let config = new Config();
let activeSite = ref<SzuruSiteConfig | undefined>(undefined);
let posts = reactive([] as PostDetails[]);
let selectedPost = ref(new PostDetails(new ScrapedPost()));
let messages = reactive<Message[]>([]);
let addTagInput = ref("");
let autocompleteShown = ref(false);
let autocompleteTags = ref<TagDetails[]>([]);
let cancelSource = ref<CancelTokenSource | undefined>(undefined);
let autocompleteIndex = ref(-1);
let szuru = computed(() => {
return activeSite.value ? SzuruWrapper.createFromConfig(activeSite.value) : undefined;
});
watch(selectedPost, () => {
findSimilar(selectedPost);
});
function openOptionsPage() {
browser.runtime.openOptionsPage();
}
async function getActiveTabId() {
const activeTabs = await browser.tabs.query({
active: true,
currentWindow: true,
});
if (activeTabs.length > 0) return activeTabs[0].id!;
throw new Error("No active tab.");
}
async function grabPost() {
// Get active tab
const activeTabId = await getActiveTabId();
// Send 'grab_post' to the content script on the active tab
const x = await browser.tabs.sendMessage(activeTabId, new BrowserCommand("grab_post"));
// We need to create a new ScrapeResults object and fill it with our data, because the get_posts()
// method gets 'lost' when sent from the contentscript to the popup (it gets JSON.stringified and any prototype defines are lost there)
const res = Object.assign(new ScrapeResults(), x);
console.dir(res);
// Clear current posts array
posts.splice(0);
for (const result of res.results) {
for (const i in result.posts) {
const vm = new PostDetails(result.posts[i]);
vm.name = `[${result.engine}] Post ${parseInt(i) + 1}`; // parseInt() is required!
// Add current pageUrl to the source if either
// a. user has addPageUrlToSource set to true
// b. source is empty
if (config?.addPageUrlToSource || vm.source == "") {
if (vm.source != "") vm.source += "\n";
vm.source += vm.pageUrl;
}
posts.push(vm);
}
}
if (posts.length > 0) {
selectedPost.value = posts[0];
if (config?.loadTagCounts) {
loadTagCounts();
}
} else {
pushInfo("No posts found.");
}
}
async function upload() {
window.scrollTo(0, 0);
// Outsource to background.ts
// TODO: Terrible code.
const x = JSON.parse(JSON.stringify(selectedPost.value));
const cmd = new BrowserCommand("upload_post", x);
await browser.runtime.sendMessage(cmd);
// TODO: Handle errors/status update
}
function getTagClasses(tag: TagDetails): string[] {
let classes: string[] = [];
if (tag.category && <any>tag.category != "default") {
classes.push("tag-" + tag.category);
} else {
classes.push("tag-general");
}
return classes;
}
function breakTagName(tagName: string) {
// Based on https://stackoverflow.com/a/6316913
return tagName.replace(/\_/g, "_<wbr>");
}
function resolutionToString(resolution: [number, number]) {
if (resolution && resolution.length == 2) {
return resolution[0] + "x" + resolution[1];
}
return "";
}
function removeTag(tag: TagDetails) {
if (selectedPost.value) {
const idx = selectedPost.value.tags.indexOf(tag);
if (idx != -1) {
selectedPost.value.tags.splice(idx, 1);
}
}
}
function getMessageClasses(message: Message) {
let classes: string[] = [];
switch (message.level) {
case "error":
classes.push("message-error");
break;
case "success":
classes.push("message-success");
break;
}
return classes;
}
function pushInfo(message: string, category?: MessageCategory): Message {
let msg = new Message(message, "info", category);
messages.push(msg);
return msg;
}
function pushError(message: string, category?: MessageCategory): Message {
let msg = new Message(message, "error", category);
messages.push(msg);
return msg;
}
function removeMessage(message: Message) {
for (let i = 0; i < messages.length; i++) {
if (messages[i].id == message.id) {
messages.splice(i, 1);
break;
}
}
}
function clearMessages(category?: MessageCategory) {
if (category) {
for (let i = 0; i < messages.length; i++) {
if (messages[i].category == category) {
// Decrement i to negate the i++, because if we remove one object the items
// shift one place to the left, aka index--
// If we don't do i-- we'll skip the next item in our for loop
messages.splice(i--, 1);
}
}
} else {
messages.splice(0);
}
}
function getPostUrl(post: Post): string {
if (!activeSite.value) return "";
return getUrl(activeSite.value.domain, "post", post.id.toString());
}
function addTag(tag: TagDetails) {
if (selectedPost) {
// Only add tag if it doesn't already exist
if (tag.name.length > 0 && selectedPost.value.tags.find((x) => x.name == tag.name) == undefined) {
selectedPost.value.tags.push(tag);
// Add implications for the tag
selectedPost.value.tags.push(...tag.implications);
}
}
}
async function clickFindSimilar() {
return await findSimilar(selectedPost);
}
async function findSimilar(post: Ref<PostDetails | undefined>) {
if (!post.value || !szuru.value) {
return;
}
clearMessages("find_similar");
const msg = pushInfo("Searching for similar posts...", "find_similar");
try {
let res: ImageSearchResult | undefined;
if (config.useContentTokens) {
let tmpRes = await szuru.value.uploadTempFile(post.value.contentUrl);
// TODO: Error handling?
// Save contentToken in PostViewModel so that we can reuse it when creating/uploading the post.
post.value.contentToken = tmpRes.token;
res = await szuru.value.reverseSearchToken(tmpRes.token);
} else {
res = await szuru.value.reverseSearch(post.value.contentUrl);
}
if (!res.exactPost && res.similarPosts.length == 0) {
msg.content = "No similar posts found";
} else {
if (res.exactPost) {
msg.content = `<a href='${getPostUrl(res.exactPost)}' target='_blank'>Post already uploaded (${
res.exactPost.id
})</a>`;
msg.level = "error";
}
for (const similarPost of res.similarPosts) {
// Don't show this message for the exactPost (because we have a different message for that)
if (res.exactPost && res.exactPost.id == similarPost.post.id) {
continue;
}
pushInfo(
`<a href='${getPostUrl(similarPost.post)}' target='_blank'>Post ${similarPost.post.id}
looks ${Math.round(100 - similarPost.distance * 100)}% similar</a>`,
"find_similar"
);
}
}
} catch (ex) {
clearMessages();
pushError("Error: couldn't reverse search.");
}
}
function getPostForUrl(contentUrl: string): PostDetails | undefined {
for (const post of posts) {
if (post.contentUrl == contentUrl) return post;
}
return undefined;
}
async function loadTagCounts() {
const allTags = posts.flatMap((x) => x.tags);
for (let i = 0; i < allTags.length; i += 100) {
const query = allTags
.slice(i, i + 101)
.map((x) => encodeTagName(x.name))
.join();
const resp = await szuru.value?.getTags(query);
// Not the best code, but it works I guess?
if (resp) {
for (let post of posts)
for (let tag of resp.results)
for (let postTag of post.tags)
if (postTag.name == tag.names[0]) {
postTag.usages = tag.usages;
break;
}
}
}
}
async function onAddTagKeyUp(e: KeyboardEvent) {
await autocompletePopulator((<HTMLInputElement>e.target).value);
}
function addTagFromCurrentInput() {
addTag(new TagDetails(addTagInput.value));
addTagInput.value = ""; // Reset input
// Only needed when the button is clicked
// When this is triggered by the enter key the `onAddTagKeyUp` will internally also hide the autocomplete.
// Though hiding it twice doesn't hurt so we don't care.
hideAutocomplete();
// TODO: Do we also want to add the implications?
// Answer: Probably not, because if the user wanted to have implications they should've clicked/selected the autocomplete entry.
}
function onAddTagKeyDown(e: KeyboardEvent) {
if (e.code == "ArrowDown") {
e.preventDefault();
if (autocompleteIndex.value < autocompleteTags.value.length - 1) {
autocompleteIndex.value++;
}
} else if (e.code == "ArrowUp") {
e.preventDefault();
if (autocompleteIndex.value >= 0) {
autocompleteIndex.value--;
}
} else if (e.code == "Enter") {
if (autocompleteIndex.value == -1) {
addTagFromCurrentInput();
} else {
// Add auto completed tag
const tagToAdd = autocompleteTags.value[autocompleteIndex.value];
addTag(tagToAdd);
addTagInput.value = ""; // Reset input
}
}
}
function onClickAutocompleteTagItem(tag: TagDetails) {
addTag(tag);
addTagInput.value = ""; // Reset input
autocompleteShown.value = false; // Hide autocomplete list
}
function hideAutocomplete() {
autocompleteIndex.value = -1;
autocompleteShown.value = false;
}
async function autocompletePopulator(input: string) {
// Based on https://www.w3schools.com/howto/howto_js_autocomplete.asp
// TODO: Put this in a separate component
// Hide autocomplete when the input is empty, and don't do anything else.
if (input.length == 0) {
hideAutocomplete();
return;
}
// Cancel previous request
if (cancelSource.value) {
cancelSource.value.cancel();
}
cancelSource.value = axios.CancelToken.source();
const query = decodeURIComponent(`*${encodeTagName(input)}* sort:usages`);
const resp = await szuru.value?.getTags(
query,
0,
100,
["names", "category", "usages", "implications"],
cancelSource.value.token
);
autocompleteTags.value = resp!.results.map((x) => TagDetails.fromTag(x));
if (autocompleteTags.value.length > 0) autocompleteShown.value = true;
}
onMounted(async () => {
config = await Config.load();
activeSite.value = config.sites.length > 0 ? config.sites[0] : undefined;
if (!activeSite.value) {
pushError("No szurubooru server configured!", "persistent");
} else {
// TODO: We can probably delete this code, because of the computed(() => ...);
// szuru = SzuruWrapper.createFromConfig(this.activeSite);
}
browser.runtime.onMessage.addListener((cmd: BrowserCommand, _sender: Runtime.MessageSender) => {
switch (cmd.name) {
case "push_message":
messages.push(cmd.data);
break;
case "pop_messages":
for (let i = 0; i < cmd.data; i++) {
messages.pop();
}
break;
}
});
let extraInfoSpec: WebRequest.OnBeforeSendHeadersOptions[] = ["requestHeaders", "blocking"];
if (isChrome) {
extraInfoSpec.push("extraHeaders" as any);
}
// Add "Referer" header to all requests if post.referrer is set.
// This is needed in some rare cases where websites disallow hotlinking to images.
// This will probably stop working in Chrome sometime in 2023 due to the Manifest V3 webRequestBlocking bullshit.
// Firefox users should be fine.
browser.webRequest.onBeforeSendHeaders.addListener(
(details: WebRequest.OnBeforeSendHeadersDetailsType) => {
let requestHeaders = details.requestHeaders ?? [];
// Find which ScrapedPost this belongs to, if any.
const post = getPostForUrl(details.url);
if (post != undefined && post.referrer) {
console.log(`Setting referrer to '${post.referrer}' for request to '${post.contentUrl}'.`);
// TODO: If the headers already have a 'Referer' header this will _not_ override that.
// As far as I am aware the 'img' tag doesn't set this header, so it shouldn't be a problem.
requestHeaders.push({ name: "Referer", value: post.referrer });
}
return <WebRequest.BlockingResponse>{
requestHeaders,
};
},
{ urls: ["<all_urls>"] },
extraInfoSpec
);
grabPost();
});
useDark();
</script>
<template>
<div class="popup-container">
<div class="popup-messages">
<ul class="messages">
<li v-for="msg in messages" :key="msg.content" :class="getMessageClasses(msg)" v-html="msg.content"></li>
</ul>
</div>
<div class="popup-columns">
<div class="popup-left">
<div class="popup-section">
<div class="section-header">
<span>Basic info</span>
<!-- <i class="fas fa-cog cursor-pointer" @click="openOptionsPage"></i> -->
<font-awesome-icon icon="fa-solid fa-cog" class="cursor-pointer" @click="openOptionsPage" />
</div>
<div class="section-row" v-if="selectedPost.resolution != undefined">
<ul class="compact">
<li>Resolution: {{ resolutionToString(selectedPost.resolution) }}</li>
</ul>
</div>
<div class="section-row">
<span class="section-label">Safety</span>
<div style="display: flex; gap: 10px">
<label>
<input type="radio" value="safe" v-model="selectedPost.rating" />
<span class="checkmark"></span>
Safe
</label>
<label>
<input type="radio" value="sketchy" v-model="selectedPost.rating" />
<span class="checkmark"></span>
Sketchy
</label>
<label>
<input type="radio" value="unsafe" v-model="selectedPost.rating" />
<span class="checkmark"></span>
Unsafe
</label>
</div>
</div>
<div class="section-row">
<span class="section-label">Source</span>
<textarea v-model="selectedPost.source" />
</div>
</div>
<div class="popup-section">
<div class="section-header">
<span>Tags</span>
</div>
<div class="section-row" style="display: flex; flex-direction: column">
<div style="display: flex">
<input
type="text"
v-model="addTagInput"
@keyup="onAddTagKeyUp"
@keydown="onAddTagKeyDown"
autocomplete="off"
/>
<button class="primary" style="margin-left: 5px" @click="addTagFromCurrentInput">Add</button>
</div>
<div class="autocomplete-items" v-bind:class="{ show: autocompleteShown }">
<div
v-for="(tag, idx) in autocompleteTags"
@click="onClickAutocompleteTagItem(tag)"
:key="tag.name"
:class="{
active: idx == autocompleteIndex,
}"
>
<span :class="getTagClasses(tag)">{{ tag.name }}</span>
<span class="tag-usages">{{ tag.usages ? tag.usages : "" }}</span>
</div>
</div>
</div>
<div class="section-row">
<ul class="compact-tags">
<li v-for="tag in selectedPost.tags" :key="tag.name">
<a class="remove-tag" @click="removeTag(tag)">x</a>
<span :class="getTagClasses(tag)" v-html="breakTagName(tag.name)"></span>
<span v-if="config.loadTagCounts" class="tag-usages tag-usages-reserve-space">{{
tag.usages ? tag.usages : ""
}}</span>
</li>
</ul>
</div>
</div>
<div class="popup-section">
<div class="section-row">
<select disabled>
<option>{{ activeSite ? activeSite.domain : "(no site available)" }}</option>
</select>
</div>
</div>
</div>
<div class="popup-right">
<div class="popup-section">
<select v-model="selectedPost">
<option v-for="post in posts" v-bind:key="post.name" v-bind:value="post">{{ post.name }}</option>
</select>
</div>
<div class="popup-section">
<div style="display: flex; gap: 5px">
<button v-if="!config.autoSearchSimilar" class="primary" @click="clickFindSimilar">Find similar</button>
<button class="primary full" @click="upload">Import</button>
</div>
</div>
<div class="popup-section">
<div class="post-container">
<img :src="selectedPost.contentUrl" v-if="selectedPost.contentType == 'image'" />
<video v-if="selectedPost.contentType == 'video'" controls>
<source :src="selectedPost.contentUrl" />
</video>
<div class="post-overlay">
<PostNotes :notes="selectedPost.notes" />
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<style lang="scss" scoped>
video {
width: 100%;
}
textarea,
select {
font-size: 90%;
}
label {
flex: 1 0 auto;
input[type="radio"] {
margin: 3px 3px 0 0;
}
}
.popup-container {
display: flex;
flex-direction: column;
}
.popup-messages {
grid-column: 1 / 3;
margin: 0 10px;
}
.popup-columns {
display: flex;
flex-direction: row;
}
.popup-left {
flex: 1 0 auto;
}
.popup-right {
flex: 1 1 auto;
}
.popup-section {
margin: 10px;
}
.section-header {
height: 30px;
padding: 0 6px 0 10px;
background-color: var(--section-header-bg-color);
display: flex;
justify-content: space-between;
align-items: center;
> span {
font-size: 1.2em;
vertical-align: middle;
color: var(--section-header-fg-color);
}
}
.section-row {
margin: 10px 5px 0;
}
.section-label {
display: block;
margin: 0 0 5px 0;
}
.section-block {
display: block;
}
.cursor-pointer {
cursor: pointer;
}
.autocomplete-items {
position: absolute;
z-index: 10;
background-color: var(--bg-main-color);
border: 2px solid var(--primary-color);
margin-top: 34px;
display: none;
&.show {
display: block;
}
> div {
cursor: pointer;
padding: 2px 4px;
display: flex;
align-items: center;
gap: 0.5em;
&:hover {
background: var(--primary-color);
> span {
color: var(--text-color);
}
}
}
> div.active {
background: var(--primary-color);
> span {
color: var(--text-color);
}
}
}
/* Hacky way to stop the layout from resizing when we lazy load the usage count. */
.tag-usages-reserve-space {
min-width: 5ch; /* 5 character width */
display: inline-block;
}
.post-container {
position: relative;
display: flex;
}
.post-overlay {
position: absolute;
width: 100%;
height: 100%;
}
</style>

View File

@ -1,38 +0,0 @@
<!-- Based on https://github.com/cloudacy/vue-markdown-render/blob/master/src/VueMarkdown.ts -->
<script lang="ts">
import Vue from "vue";
import MarkdownIt, { Options } from "markdown-it";
export default Vue.extend({
name: "VueMarkdown",
props: {
source: {
type: String,
required: true
}
},
data() {
return {
md: null as MarkdownIt | null
};
},
computed: {
content(): string | undefined {
console.log(this.source);
return this.md?.render(this.source);
}
},
created() {
const options: Options = {
breaks: true
};
this.md = new MarkdownIt(options);
}
});
</script>
<template>
<div v-html="content" />
</template>

12
src/popup/index.html Normal file
View File

@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<base target="_blank" />
<title>Popup</title>
</head>
<body style="min-width: 100px">
<div id="app"></div>
<script type="module" src="./main.ts"></script>
</body>
</html>

16
src/popup/main.ts Normal file
View File

@ -0,0 +1,16 @@
import { createApp } from "vue";
import App from "./Popup.vue";
import { setupApp } from "~/logic/common-setup";
import { isChrome } from "~/env";
import "../styles";
// Firefox automatically makes the popup as large as can be, Chrome doesn't.
// However setting the width to 780px gives us horizontal scrollbars on Firefox.
if (isChrome) {
document.documentElement.style.width = "780px";
}
const app = createApp(App);
setupApp(app);
app.mount("#app");

View File

@ -1,14 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Title</title>
<link rel="stylesheet" href="popup.css" />
</head>
<body>
<div id="app"></div>
<script src="../vendor.js"></script>
<script src="popup.js"></script>
</body>
</html>

View File

@ -1,21 +0,0 @@
import "normalize.css";
import "../css/style.scss";
import "../css/fontawesome.css";
import "../css/solid.css";
import Vue from "vue";
import App from "./App.vue";
import { applyTheme } from "../Common";
applyTheme();
// Firefox automatically makes the popup as large as can be, Chrome doesn't.
// However setting the width to 780px gives us horizontal scrollbars on Firefox.
if (navigator.userAgent.match(/chrome|chromium|crios/i)) {
document.documentElement.style.width = "780px";
}
new Vue({
el: "#app",
render: (h) => h(App),
});

View File

@ -1,17 +0,0 @@
import { NeoScraper, ScrapeResults } from "neo-scraper";
import { browser } from "webextension-polyfill-ts";
import { BrowserCommand } from "../Common";
function grabPost(): ScrapeResults {
const scraper = new NeoScraper();
return scraper.scrapeDocument(document, true);
}
async function messageHandler(cmd: BrowserCommand): Promise<any> {
switch (cmd.name) {
case "grab_post":
return grabPost();
}
}
browser.runtime.onMessage.addListener(messageHandler);

1
src/styles/index.ts Normal file
View File

@ -0,0 +1 @@
import "./main.scss";

View File

@ -3,7 +3,7 @@
font-family: "Open Sans"; font-family: "Open Sans";
font-style: normal; font-style: normal;
font-weight: 400; font-weight: 400;
src: local(""), url("../fonts/open-sans-v34-latin-regular.woff2") format("woff2"); src: local(""), url("/assets/open-sans-v34-latin-regular.woff2") format("woff2");
} }
body { body {
@ -25,7 +25,7 @@ body {
--text-color: #111; --text-color: #111;
} }
html[data-theme="dark"] { html.dark {
--button-bg-color: #666; --button-bg-color: #666;
--primary-color: #1b87b0; --primary-color: #1b87b0;
--bg-main-color: #1a1a1a; --bg-main-color: #1a1a1a;
@ -43,11 +43,16 @@ body {
display: block; display: block;
} }
select,
button {
height: 30px;
}
button { button {
background-color: var(--button-bg-color); background-color: var(--button-bg-color);
border: none; border: none;
color: #fff; color: #fff;
height: 30px;
cursor: pointer; cursor: pointer;
padding: 0 10px; padding: 0 10px;
white-space: nowrap; white-space: nowrap;
@ -120,6 +125,12 @@ ul.compact {
list-style-type: none; list-style-type: none;
padding: 0; padding: 0;
display: inline; display: inline;
li {
display: flex;
align-items: center;
gap: 0.5em;
}
} }
.tag-general { .tag-general {
@ -158,7 +169,6 @@ ul.compact {
color: var(--secondary-text); color: var(--secondary-text);
font-size: 90%; font-size: 90%;
text-indent: initial; text-indent: initial;
margin-left: 0.7em;
} }
a.remove-tag { a.remove-tag {

7
src/tests/demo.spec.ts Normal file
View File

@ -0,0 +1,7 @@
import { describe, expect, it } from 'vitest';
describe('Demo', () => {
it('should work', () => {
expect(1 + 1).toBe(2);
});
});

13
src/utils.ts Normal file
View File

@ -0,0 +1,13 @@
export function getUrl(root: string, ...parts: string[]): string {
let url = root.replace(/\/+$/, "");
for (const part of parts) {
url += "/" + part.replace(/\/+$/, "");
}
return url;
}
export function encodeTagName(tagName: string) {
// Searching for posts with re:zero will show an error message about unknown named token.
// Searching for posts with re\:zero will show posts tagged with re:zero.
return tagName.replace(/:/g, "\\:");
}

4
src/vue-shims.d.ts vendored
View File

@ -1,4 +0,0 @@
declare module "*.vue" {
import Vue from "vue";
export default Vue;
}

View File

@ -1,16 +1,32 @@
{ {
"compilerOptions": { "compilerOptions": {
"outDir": "./dist/", "baseUrl": ".",
"sourceMap": true, "module": "ESNext",
"target": "es2016",
"lib": [
"DOM",
"ESNext"
],
"strict": true, "strict": true,
"module": "es2020",
"moduleResolution": "node",
"target": "es2019",
"skipLibCheck": true,
"esModuleInterop": true, "esModuleInterop": true,
"experimentalDecorators": true, "incremental": false,
"useUnknownInCatchVariables": false, "skipLibCheck": true,
"lib": ["es2019", "dom"] "jsx": "preserve",
"moduleResolution": "node",
"resolveJsonModule": true,
"noUnusedLocals": true,
"forceConsistentCasingInFileNames": true,
"types": [
"vite/client"
],
"paths": {
"~/*": [
"src/*"
]
}
}, },
"include": ["./src/**/*"] "exclude": [
"dist",
"node_modules"
]
} }

33
vite.config.content.ts Normal file
View File

@ -0,0 +1,33 @@
import { defineConfig } from "vite";
import { sharedConfig } from "./vite.config";
import { isDev, r } from "./scripts/utils";
import packageJson from "./package.json";
// bundling the content script using Vite
export default defineConfig({
...sharedConfig,
define: {
__DEV__: isDev,
// https://github.com/vitejs/vite/issues/9320
// https://github.com/vitejs/vite/issues/9186
"process.env.NODE_ENV": JSON.stringify(isDev ? "development" : "production"),
},
build: {
watch: isDev ? {} : undefined,
outDir: r("extension/dist/contentScripts"),
cssCodeSplit: false,
emptyOutDir: false,
sourcemap: isDev ? "inline" : false,
lib: {
entry: r("src/contentScripts/index.ts"),
name: packageJson.name,
formats: ["iife"],
},
rollupOptions: {
output: {
entryFileNames: "index.global.js",
extend: true,
},
},
},
});

90
vite.config.ts Normal file
View File

@ -0,0 +1,90 @@
/// <reference types="vitest" />
import { dirname, relative } from "path";
import type { UserConfig } from "vite";
import { defineConfig } from "vite";
import Vue from "@vitejs/plugin-vue";
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { isDev, port, r } from "./scripts/utils";
export const sharedConfig: UserConfig = {
root: r("src"),
resolve: {
alias: {
"~/": `${r("src")}/`,
},
},
define: {
__DEV__: isDev,
},
plugins: [
Vue(),
AutoImport({
imports: [
"vue",
{
"webextension-polyfill": [["*", "browser"]],
},
],
dts: r("src/auto-imports.d.ts"),
}),
Components({
dirs: [r("src/components")],
// generate `components.d.ts` for ts support with Volar
dts: r("src/components.d.ts"),
resolvers: [
// auto import icons
// IconsResolver({
// componentPrefix: "",
// }),
],
}),
// rewrite assets to use relative path
{
name: "assets-rewrite",
enforce: "post",
apply: "build",
transformIndexHtml(html, { path }) {
return html.replace(/"\/assets\//g, `"${relative(dirname(path), "/assets")}/`);
},
},
],
optimizeDeps: {
include: ["vue", "@vueuse/core", "webextension-polyfill"],
},
};
export default defineConfig(({ command }) => ({
...sharedConfig,
base: command === "serve" ? `http://localhost:${port}/` : "/dist/",
server: {
port,
hmr: {
host: "localhost",
},
},
build: {
outDir: r("extension/dist"),
emptyOutDir: false,
sourcemap: isDev ? "inline" : false,
// https://developer.chrome.com/docs/webstore/program_policies/#:~:text=Code%20Readability%20Requirements
terserOptions: {
mangle: false,
},
rollupOptions: {
input: {
background: r("src/background/index.html"),
options: r("src/options/index.html"),
popup: r("src/popup/index.html"),
},
},
},
test: {
globals: true,
environment: "jsdom",
},
}));

View File

@ -1,102 +0,0 @@
const webpack = require("webpack");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CopyPlugin = require("copy-webpack-plugin");
const TerserPlugin = require("terser-webpack-plugin");
const { VueLoaderPlugin } = require("vue-loader");
const { version } = require("./package.json");
module.exports = {
context: __dirname + "/src",
entry: {
"scripts/content": { import: "./scripts/content.ts", dependOn: "vendor" },
"scripts/background": { import: "./scripts/background.ts", dependOn: "vendor" },
"popup/popup": { import: "./popup/popup.ts", dependOn: "vendor" },
"options/options": { import: "./options/options.ts", dependOn: "vendor" },
vendor: ["axios", "neo-scraper", "vue", "webextension-polyfill-ts"],
},
output: {
path: __dirname + "/dist",
filename: "[name].js",
},
resolve: {
extensions: [".ts", ".js", ".vue"],
},
module: {
rules: [
{
test: /\.vue$/,
loader: "vue-loader",
},
{
test: /\.tsx?$/,
loader: "ts-loader",
exclude: /node_modules/,
options: {
appendTsSuffixTo: [/\.vue$/],
},
},
{
test: /.s?css$/,
use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"],
},
{
test: /\.(png|jpg|gif|svg|ico)$/,
type: "asset/resource",
generator: {
filename: "[name][ext]",
},
},
{
test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
type: "asset/resource",
generator: {
filename: "fonts/[name][ext]",
},
},
// Added because https://github.com/graphql/graphql-js/issues/2721#issuecomment-723008284 (not a GraphQL specific issue).
{
test: /\.m?js/,
resolve: {
fullySpecified: false,
},
},
],
},
plugins: [
new webpack.DefinePlugin({
global: "window",
}),
new VueLoaderPlugin(),
new MiniCssExtractPlugin({
filename: "[name].css",
}),
new CopyPlugin({
patterns: [
{ from: "icons", to: "icons" },
{ from: "popup/popup.html", to: "popup/popup.html" },
{ from: "options/options.html", to: "options/options.html" },
{
from: "manifest.json",
to: "manifest.json",
transform: (content) => {
const jsonContent = JSON.parse(content);
jsonContent.version = version;
// if (config.mode === "development") {
// jsonContent["content_security_policy"] = "script-src 'self' 'unsafe-eval'; object-src 'self'";
// }
return JSON.stringify(jsonContent, null, 2);
},
},
],
}),
],
optimization: {
minimizer: [
new TerserPlugin({
extractComments: false,
})
],
},
};

View File

@ -1,18 +0,0 @@
const { merge } = require("webpack-merge");
const ExtensionReloader = require("webpack-ext-reloader");
const common = require("./webpack.common.cjs");
module.exports = merge(common, {
mode: "development",
devtool: "source-map",
plugins: [
new ExtensionReloader({
reloadPage: true,
entries: {
contentScript: "scripts/content",
background: "scripts/background",
extensionPage: ["popup/popup", "options/options"],
},
}),
],
});

View File

@ -1,6 +0,0 @@
const { merge } = require("webpack-merge");
const common = require("./webpack.common.cjs");
module.exports = merge(common, {
mode: "production"
});

3052
yarn.lock

File diff suppressed because it is too large Load Diff