Merge branch 'next'

- Show image resolution using the popups <img> naturalHeight/Width fields
- Support for multiple szurubooru instances
- Better mobile UI and CSS cleanup
- Update to Vue 3 + Vite
- Other under the hood changes
gh-actions v0.9
neobooru 2023-04-11 23:59:45 +02:00
commit 9675d25cd0
63 changed files with 8538 additions and 9297 deletions

5
.eslintignore Normal file
View File

@ -0,0 +1,5 @@
dist
node_modules
public
auto-imports.d.ts
components.d.ts

27
.eslintrc.cjs Normal file
View File

@ -0,0 +1,27 @@
module.exports = {
env: {
browser: true,
es2021: true,
},
extends: ["eslint:recommended", "plugin:vue/vue3-essential", "plugin:@typescript-eslint/recommended"],
parser: "vue-eslint-parser",
parserOptions: {
ecmaVersion: "latest",
parser: "@typescript-eslint/parser",
sourceType: "module",
},
plugins: ["vue", "@typescript-eslint"],
rules: {
semi: ["error", "always"],
"no-undef": "off",
"@typescript-eslint/no-unused-vars": [
"warn",
{
argsIgnorePattern: "^_",
varsIgnorePattern: "^_",
caughtErrorsIgnorePattern: "^_",
},
],
"@typescript-eslint/no-explicit-any": "off",
},
};

View File

@ -1,23 +0,0 @@
module.exports = {
"env": {
"browser": true,
"es2021": true
},
"extends": [
"eslint:recommended",
"plugin:vue/vue3-essential",
"plugin:@typescript-eslint/recommended"
],
"parserOptions": {
"ecmaVersion": "latest",
"parser": "@typescript-eslint/parser",
"sourceType": "module"
},
"plugins": [
"vue",
"@typescript-eslint"
],
"rules": {
semi: ["error", "always"],
}
};

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

@ -40,11 +40,13 @@ You can download a .zip containing the needed files from the [release tab](https
```sh ```sh
# Install node modules # Install node modules
yarn install pnpm install
# Use any of the following commands to build # Live dev build (watch)
yarn build pnpm dev
yarn build:dev
# Production build
pnpm build
``` ```
After this you can load them in your browser. After this you can load them in your browser.
@ -61,5 +63,3 @@ These are some things I might work on. Though honestly I don't expect this exten
- Right click any image on a page to import it - Right click any image on a page to import it
- Configurable list of tags to always ignore (e.g. tagme, highres) - Configurable list of tags to always ignore (e.g. tagme, highres)
- [low priority] Import artist commentary - [low priority] Import artist commentary
- [lowest priority] Move from 'options_page' to 'options_ui'
- [lowest priority] Multiple szurubooru instances (where you can choose to which one you want to upload the post)

View File

Before

Width:  |  Height:  |  Size: 33 KiB

After

Width:  |  Height:  |  Size: 33 KiB

View File

@ -1,50 +1,71 @@
{ {
"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"
},
"type": "module",
"scripts": { "scripts": {
"build": "webpack --config webpack.prod.cjs", "dev": "npm run clear && cross-env NODE_ENV=development run-p dev:*",
"build:dev": "webpack --config webpack.dev.cjs", "dev:prepare": "esno scripts/prepare.ts",
"build-zip": "node scripts/build-zip.cjs", "dev:web": "vite",
"sign-xpi": "node scripts/sign-xpi.js", "dev:js": "npm run build:js -- --mode development",
"watch": "webpack --watch --config webpack.dev.cjs", "build": "cross-env NODE_ENV=production run-s clear build:web build:prepare build:js",
"lint": "eslint src" "build:prepare": "esno scripts/prepare.ts",
"build:web": "vite build",
"build:js": "vite build --config vite.config.content.ts",
"pack": "cross-env NODE_ENV=production run-p pack:*",
"pack:zip": "rimraf extension.zip && jszip-cli add extension/* -o ./extension.zip",
"pack:crx": "crx pack extension -o ./extension.crx",
"pack:xpi": "cross-env WEB_EXT_ARTIFACTS_DIR=./ web-ext build --source-dir ./extension --filename extension.xpi --overwrite-dest",
"start:chromium": "web-ext run --source-dir ./extension --target=chromium",
"start:firefox": "web-ext run --source-dir ./extension --target=firefox-desktop",
"sign:firefox": "web-ext sign --use-submission-api --source-dir ./extension --channel unlisted",
"clear": "rimraf extension/dist extension/manifest.json extension.*",
"lint": "eslint .",
"test": "vitest test"
}, },
"dependencies": { "dependencies": {
"axios": "^0.27.2", "axios": "^1.2.2",
"basscss": "^8.1.0",
"markdown-it": "^13.0.1", "markdown-it": "^13.0.1",
"neo-scraper": "^0.5.8", "neo-scraper": "^0.5.8",
"normalize.css": "^8.0.1", "normalize.css": "^8.0.1"
"vue": "^2.6.14",
"webextension-polyfill": "^0.9.0"
}, },
"devDependencies": { "devDependencies": {
"@ffflorian/jszip-cli": "^3.1.6",
"@fortawesome/fontawesome-svg-core": "^6.2.1",
"@fortawesome/free-solid-svg-icons": "^6.2.1",
"@fortawesome/vue-fontawesome": "^3.0.3",
"@types/fs-extra": "^9.0.13",
"@types/markdown-it": "^12.2.3", "@types/markdown-it": "^12.2.3",
"@typescript-eslint/eslint-plugin": "^5.48.1", "@types/node": "^18.11.9",
"@typescript-eslint/parser": "^5.48.1", "@types/webextension-polyfill": "^0.9.1",
"archiver": "^5.3.1", "@typescript-eslint/eslint-plugin": "^5.44.0",
"copy-webpack-plugin": "^11.0.0", "@vitejs/plugin-vue": "^3.2.0",
"css-loader": "^6.7.1", "@vue/compiler-sfc": "^3.2.45",
"eslint": "^8.21.0", "@vue/test-utils": "^2.2.4",
"eslint-plugin-vue": "^9.3.0", "@vueuse/core": "^9.6.0",
"mini-css-extract-plugin": "^2.6.1", "chokidar": "^3.5.3",
"cross-env": "^7.0.3",
"crx": "^5.0.1",
"eslint": "^8.32.0",
"eslint-plugin-vue": "^9.9.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", "sass": "^1.57.1",
"sass-loader": "^13.2.0", "typescript": "^4.9.3",
"sign-addon": "^5.0.0", "unplugin-auto-import": "^0.12.2",
"ts-loader": "^9.3.1", "unplugin-vue-components": "^0.23.0",
"typescript": "^4.9.4", "vite": "^3.2.4",
"vue-loader": "^15.9.8", "vitest": "^0.25.3",
"vue-template-compiler": "^2.7.8", "vue": "^3.2.45",
"web-ext-types": "^3.2.1", "vue-eslint-parser": "^9.1.0",
"webextension-polyfill-ts": "^0.26.0", "web-ext": "^7.5.0",
"webpack": "^5.74.0", "webextension-polyfill": "^0.10.0"
"webpack-cli": "^4.10.0",
"webpack-ext-reloader": "^1.1.9"
} }
} }

6248
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,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,5 +1,4 @@
import axios, { AxiosRequestConfig, CancelToken } from "axios"; import axios, { AxiosRequestConfig, CancelToken } from "axios";
import { SzuruSiteConfig } from "./Config";
import { import {
TagsResult, TagsResult,
TagCategoriesResult, TagCategoriesResult,
@ -8,16 +7,17 @@ import {
SzuruError, SzuruError,
ImageSearchResult, ImageSearchResult,
TagFields, TagFields,
TemporaryFileUploadResult TemporaryFileUploadResult,
} from "./SzuruTypes"; } from "./models";
import { PostViewModel } from "./ViewModels"; import { ScrapedPostDetails } from "~/models";
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;
@ -25,7 +25,7 @@ export default class SzuruWrapper {
private readonly baseHeaders = { private readonly baseHeaders = {
Accept: "application/json", Accept: "application/json",
"Content-Type": "application/json" "Content-Type": "application/json",
}; };
/** /**
@ -53,8 +53,8 @@ export default class SzuruWrapper {
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());
@ -70,16 +70,16 @@ export default class SzuruWrapper {
return (await this.apiGet("tag-categories")).data; return (await this.apiGet("tag-categories")).data;
} }
async createPost(post: PostViewModel): Promise<Post> { async createPost(post: ScrapedPostDetails, contentToken?: string): 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 (contentToken) {
obj.contentToken = post.contentToken; obj.contentToken = contentToken;
} else { } else {
obj.contentUrl = post.contentUrl; obj.contentUrl = post.contentUrl;
} }
@ -105,20 +105,16 @@ export default class SzuruWrapper {
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,
additionalHeaders: any = {},
cancelToken: CancelToken | undefined = undefined
): Promise<any> {
const fullUrl = this.apiUrl + url; const fullUrl = this.apiUrl + url;
const config: AxiosRequestConfig = { const config: AxiosRequestConfig = {
method: "GET", method: "GET",
url: fullUrl, url: fullUrl,
cancelToken cancelToken,
}; };
config.headers = { ...this.baseHeaders, ...additionalHeaders }; config.headers = { ...this.baseHeaders, ...additionalHeaders };
@ -130,7 +126,7 @@ export default class SzuruWrapper {
const config: AxiosRequestConfig = { const config: AxiosRequestConfig = {
method: "POST", method: "POST",
url: fullUrl, url: fullUrl,
data: data data: data,
}; };
config.headers = { ...this.baseHeaders, ...additionalHeaders }; config.headers = { ...this.baseHeaders, ...additionalHeaders };
@ -142,7 +138,7 @@ export default class SzuruWrapper {
const config: AxiosRequestConfig = { const config: AxiosRequestConfig = {
method: "PUT", method: "PUT",
url: fullUrl, url: fullUrl,
data: data data: data,
}; };
config.headers = { ...this.baseHeaders, ...additionalHeaders }; config.headers = { ...this.baseHeaders, ...additionalHeaders };
@ -153,14 +149,15 @@ export default class SzuruWrapper {
if (this.username && this.authToken) { if (this.username && this.authToken) {
const token = "Token " + btoa(`${this.username}:${this.authToken}`); const token = "Token " + btoa(`${this.username}:${this.authToken}`);
if (!config.headers) config.headers = {}; if (!config.headers) config.headers = {};
// @ts-expect-error xxx
config.headers["Authorization"] = token; config.headers["Authorization"] = token;
} }
try { try {
return await axios(config); return await axios(config);
} catch (ex) { } catch (ex: any) {
const error = ex.response?.data as SzuruError | undefined; const error = ex.response?.data as SzuruError | undefined;
throw error ? error : ex; throw error?.name ? error : ex;
} }
} }
} }

View File

@ -108,7 +108,7 @@ export interface SimilarPost {
} }
export interface ImageSearchResult { export interface ImageSearchResult {
exactPost: Post | null; exactPost: Post | undefined;
similarPosts: SimilarPost[]; similarPosts: SimilarPost[];
} }

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>

131
src/background/main.ts Normal file
View File

@ -0,0 +1,131 @@
import { encodeTagName, getErrorMessage } from "~/utils";
import { BrowserCommand, PostUploadCommandData, PostUploadInfo, SetPostUploadInfoData, SetExactPostId } from "~/models";
import { PostAlreadyUploadedError } from "~/api/models";
import SzurubooruApi from "~/api";
import { Config } from "~/config";
// 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(data: PostUploadCommandData) {
console.dir(data.post);
const cfg = await Config.load();
const selectedSite = cfg.sites.find((x) => x.id == data.siteId);
if (!selectedSite) {
// TODO: Generic error handler which also shows the message in the popup frontend.
// browser.runtime.sendMessage(
// new BrowserCommand("push_message", new Message("Selected instance not found in config!", "error"))
// );
return;
}
const info: PostUploadInfo = {
state: "uploading",
};
try {
const szuru = SzurubooruApi.createFromConfig(selectedSite);
// Create and upload post
browser.runtime.sendMessage(
new BrowserCommand("set_post_upload_info", new SetPostUploadInfoData(data.siteId, data.post.id, info))
);
const contentToken = data.post.instanceSpecificData[data.siteId]?.contentToken;
const createdPost = await szuru.createPost(data.post, contentToken);
info.state = "uploaded";
info.instancePostId = createdPost.id;
browser.runtime.sendMessage(
new BrowserCommand("set_post_upload_info", new SetPostUploadInfoData(data.siteId, data.post.id, info))
);
// Find tags with "default" category and update it
// TODO: Make all these categories configurable
const tagsWithCategory = data.post.tags.filter((x) => x.category);
const unsetCategoryTags = createdPost.tags
.filter((x) => x.category == "default")
.filter((x) => tagsWithCategory.some((y) => x.names.includes(y.name)));
if (unsetCategoryTags.length != 0) {
info.updateTagsState = {
total: unsetCategoryTags.length,
};
browser.runtime.sendMessage(
new BrowserCommand("set_post_upload_info", new SetPostUploadInfoData(data.siteId, data.post.id, info))
);
// unsetCategoryTags is of type MicroTag[] and we need a Tag resource to update it, so let's get those
const query = unsetCategoryTags.map((x) => encodeTagName(x.names[0])).join();
const tags = (await szuru.getTags(query)).results;
const existingCategories = (await szuru.getTagCategories()).results;
let categoriesChangedCount = 0;
for (const i in tags) {
info.updateTagsState.current = parseInt(i);
browser.runtime.sendMessage(
new BrowserCommand("set_post_upload_info", new SetPostUploadInfoData(data.siteId, data.post.id, info))
);
const wantedCategory = tagsWithCategory.find((x) => tags[i].names.includes(x.name))?.category;
if (wantedCategory) {
if (existingCategories.some((x) => x.name == wantedCategory)) {
tags[i].category = wantedCategory;
await szuru.updateTag(tags[i]);
categoriesChangedCount++;
} else {
console.log(
`Not adding the '${wantedCategory}' category to the tag '${tags[i].names[0]}' because the szurubooru instance does not have this category.`
);
}
}
}
if (categoriesChangedCount > 0) {
info.updateTagsState.totalChanged = categoriesChangedCount;
browser.runtime.sendMessage(
new BrowserCommand("set_post_upload_info", new SetPostUploadInfoData(data.siteId, data.post.id, info))
);
}
}
} catch (ex: any) {
if (ex.name && ex.name == "PostAlreadyUploadedError") {
const otherPostId = (ex as PostAlreadyUploadedError).otherPostId;
browser.runtime.sendMessage(
new BrowserCommand("set_exact_post_id", new SetExactPostId(data.siteId, data.post.id, otherPostId))
);
// No error message, because we have a different message for posts that are already uploaded.
info.state = "error";
browser.runtime.sendMessage(
new BrowserCommand("set_post_upload_info", new SetPostUploadInfoData(data.siteId, data.post.id, info))
);
} else {
info.state = "error";
info.error = getErrorMessage(ex);
browser.runtime.sendMessage(
new BrowserCommand("set_post_upload_info", new SetPostUploadInfoData(data.siteId, data.post.id, info))
);
}
}
}
async function messageHandler(cmd: BrowserCommand): Promise<any> {
console.log("Background received message:");
console.dir(cmd);
switch (cmd.name) {
case "upload_post":
return uploadPost(cmd.data);
}
}
browser.runtime.onMessage.addListener(messageHandler);

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

@ -1,7 +1,5 @@
<script lang="ts"> <script setup lang="ts">
import Vue from "vue";
import { ScrapedNote } from "neo-scraper"; import { ScrapedNote } from "neo-scraper";
import Markdown from "./Markdown.vue";
class Point { class Point {
constructor(public x: any, public y: any) {} constructor(public x: any, public y: any) {}
@ -40,32 +38,19 @@ function _getNoteCentroid(note: any) {
return centroid; return centroid;
} }
export default Vue.extend({ defineProps(["notes"]);
props: ["notes"],
components: { Markdown }, const mouseOverNote = ref(false);
data() { const mouseOverNoteText = ref(false);
return { const hoverNote = ref<ScrapedNote | undefined>(undefined);
mouseOverNote: false,
mouseOverNoteText: false, const showHoverNote = computed(() => (!hoverNote.value ? false : mouseOverNote.value || mouseOverNoteText.value));
hoverNote: undefined as ScrapedNote | undefined const hoverNoteStyle = computed(() => {
}; if (!hoverNote.value) return "";
}, const { x, y } = _getNoteCentroid(hoverNote.value);
computed: {
showHoverNote: function(): boolean {
if (!this.hoverNote) {
return false;
}
return this.mouseOverNote || this.mouseOverNoteText;
},
// This could probably also be implemented using just CSS.
hoverNoteStyle: function(): string {
if (!this.hoverNote) return "";
const { x, y } = _getNoteCentroid(this.hoverNote);
const top = y * 100; const top = y * 100;
const left = x * 100; const left = x * 100;
return `display: block; top: ${top}%; left: ${left}%`; return `display: block; top: ${top}%; left: ${left}%`;
}
}
}); });
</script> </script>
@ -100,7 +85,7 @@ export default Vue.extend({
</div> </div>
</template> </template>
<style scoped> <style lang="scss" scoped>
.notes-overlay { .notes-overlay {
width: 100%; width: 100%;
height: 100%; height: 100%;
@ -123,21 +108,21 @@ export default Vue.extend({
text-align: left; text-align: left;
z-index: 20; z-index: 20;
transform: translate(-50%, -50%); transform: translate(-50%, -50%);
}
.note-text > .wrapper { > .wrapper {
background: lemonchiffon; background: lemonchiffon;
padding: 0.3em 0.6em; padding: 0.3em 0.6em;
border: 1px solid black; border: 1px solid black;
color: black; color: black;
box-sizing: border-box; box-sizing: border-box;
} }
.note-text > .wrapper :deep(p:last-of-type) { &:deep(p:last-of-type) {
margin-bottom: 0; margin-bottom: 0;
} }
.note-text > .wrapper :deep(p:first-of-type) { &:deep(p:first-of-type) {
margin-top: 0; margin-top: 0;
}
} }
</style> </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

@ -1,10 +1,7 @@
import { browser } from "webextension-polyfill-ts";
export type Theme = "system" | "light" | "dark";
export class SzuruSiteConfig { export class SzuruSiteConfig {
domain = ""; id = window.crypto.randomUUID();
username = ""; domain = "https://example.com";
username = "user";
authToken = ""; authToken = "";
} }
@ -16,8 +13,8 @@ export class Config {
autoSearchSimilar = false; autoSearchSimilar = false;
loadTagCounts = true; loadTagCounts = true;
useContentTokens = true; useContentTokens = true;
theme: Theme = "system";
sites: Array<SzuruSiteConfig> = []; sites: Array<SzuruSiteConfig> = [];
selectedSiteId?: string;
public async save() { public async save() {
await browser.storage.local.set({ await browser.storage.local.set({

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;
}

18
src/env.ts Normal file
View File

@ -0,0 +1,18 @@
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/i);
// Based on https://stackoverflow.com/a/25394023
export const isMobile = navigator.userAgent.match(/Android/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}"
}
}
}

60
src/manifest.ts Normal file
View File

@ -0,0 +1,60 @@
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: process.env.SZ_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"],
},
],
browser_specific_settings: {
gecko: {
id: "{13372607-2257-4360-8f51-5ce66fa73350}",
},
},
};
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;
}

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

@ -0,0 +1,123 @@
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?: string, public usages?: number) {}
static fromTag(tag: Tag) {
const x = new TagDetails(tag.names[0], 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], tag.category, tag.usages);
}
static fromScapedTag(tag: ScrapedTag): TagDetails {
return new TagDetails(tag.name, tag.category);
}
}
export class InstanceSpecificData {
contentToken?: string;
genericError?: string;
reverseSearchResult?: SimpleImageSearchResult;
uploadState?: PostUploadInfo;
}
type MappedInstanceSpecificData = {
[key: string]: InstanceSpecificData;
};
export class ScrapedPostDetails {
id = window.crypto.randomUUID();
name = "";
tags: TagDetails[] = [];
notes: ScrapedNote[];
contentUrl: string;
pageUrl: string;
contentType: ContentType;
rating: BooruTypes.SafetyRating;
source = "";
referrer?: string;
resolution?: [number, number];
instanceSpecificData: MappedInstanceSpecificData = {};
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 interface SimpleImageSearchResult {
exactPostId?: number;
similarPosts: SimpleSimilarPost[];
}
export interface SimpleSimilarPost {
distance: number;
postId: number;
}
export class SimilarPostInfo {
constructor(public readonly id: number, public readonly percentage: number) {}
}
export type PostUploadState = "uploading" | "uploaded" | "error";
export class PostUploadInfo {
state: PostUploadState = "uploading";
error?: string;
instancePostId?: number;
updateTagsState?: {
total: number;
current?: number;
totalChanged?: number;
};
}
export type BrowserCommandName = "grab_post" | "upload_post" | "set_post_upload_info" | "set_exact_post_id";
export class BrowserCommand<T = any> {
name: BrowserCommandName;
data?: T;
constructor(name: BrowserCommandName, data?: T) {
this.name = name;
this.data = data;
}
}
export class PostUploadCommandData {
constructor(public readonly post: ScrapedPostDetails, public readonly siteId: string) {}
}
export class SetPostUploadInfoData {
constructor(
public readonly instanceId: string,
public readonly postId: string,
public readonly info: PostUploadInfo
) {}
}
export class SetExactPostId {
constructor(
public readonly instanceId: string,
public readonly postId: string,
public readonly exactPostId: number
) {}
}

View File

@ -1,32 +1,168 @@
<script setup lang="ts">
import { useColorMode } from "@vueuse/core";
import SzuruWrapper from "~/api";
import { Config, SzuruSiteConfig } from "~/config";
import { getErrorMessage } from "~/utils";
let autoSearchSimilar = ref(false);
let loadTagCounts = ref(false);
let addPageUrlToSource = ref(false);
let useContentTokens = ref(false);
let statusText = ref("");
let statusType = ref("");
let sites = reactive<SzuruSiteConfig[]>([]);
let selectedSiteId = ref<string | undefined>(undefined);
const selectedSite = computed(() => {
if (selectedSiteId.value) {
return sites.find((x) => x.id == selectedSiteId.value);
}
});
type StatusType = "success" | "error";
async function testConnection() {
if (
!selectedSite.value ||
!selectedSite.value.domain ||
!selectedSite.value.username ||
!selectedSite.value.authToken
) {
setStatus("Domain, username and authentication token are all required.", "error");
return;
}
const api = new SzuruWrapper(selectedSite.value.domain, selectedSite.value.username, selectedSite.value.authToken);
try {
const info = await api.getInfo();
const instanceName = info?.config.name;
if (instanceName == undefined) {
setStatus(`Connected to ${selectedSite.value.domain}, but it is not a szurubooru instance.`, "error");
} else {
setStatus(`Connected to ${info.config.name} at ${selectedSite.value.domain}`);
}
} catch (ex) {
setStatus(`Couldn't connect to ${selectedSite.value.domain}. ${getErrorMessage(ex)}`, "error");
}
}
async function saveSettings() {
let config = await Config.load();
config.sites = sites;
config.autoSearchSimilar = autoSearchSimilar.value;
config.loadTagCounts = loadTagCounts.value;
config.addPageUrlToSource = addPageUrlToSource.value;
config.useContentTokens = useContentTokens.value;
config.selectedSiteId = selectedSiteId.value;
await config.save();
setStatus("Settings successfully saved");
}
function setStatus(text: string, type: StatusType = "success") {
statusText.value = text;
statusType.value = "status-" + type;
}
function addSite() {
const site = new SzuruSiteConfig();
sites.push(site);
selectedSiteId.value = site.id;
}
function removeSelectedSite() {
if (selectedSite.value) {
const idx = sites.indexOf(selectedSite.value);
sites.splice(idx, 1);
}
}
onMounted(async () => {
let config = await Config.load();
for (let site of config.sites) {
// Generate IDs for sites which are missing them.
// This is needed to correctly import old configs.
if (!site.id) {
site.id = window.crypto.randomUUID();
}
// This somehow makes `site` reactive.
sites.push(site);
}
autoSearchSimilar.value = config.autoSearchSimilar;
loadTagCounts.value = config.loadTagCounts;
addPageUrlToSource.value = config.addPageUrlToSource;
useContentTokens.value = config.useContentTokens;
selectedSiteId.value = config.selectedSiteId;
});
let mode = useColorMode({ emitAuto: true });
</script>
<template> <template>
<div class="content-holder"> <div class="content-holder">
<div class="content-wrapper"> <div class="content-wrapper flex flex-wrap gap-3">
<strong>SzuruChrome Settings</strong> <div class="flex-fit"><strong>SzuruChrome Settings</strong></div>
<p>General settings which apply to all engines.</p> <div class="flex-fit">
<div class="fit flex flex-wrap">
<div class="flex-fit">
<label>Szurubooru Instances</label>
<ul class="input"> <!-- This isn't perfectly responsive for very small devices. -->
<li class="full-width"> <div class="fit flex gap-1 flex-fit">
<label>Szurubooru URL</label> <select v-model="selectedSiteId">
<input text="Szurubooru URL" type="text" name="domain" v-model="domain" /> <option v-for="site in sites" :key="site.id" :value="site.id">
</li> {{ site.username }} @ {{ site.domain }}
<li><label>Username</label><input text="Username" type="text" name="username" v-model="username" /></li> </option>
<li style="min-width: 320px"> </select>
<button class="primary" @click="addSite">Add</button>
<button class="bg-danger" @click="removeSelectedSite">Remove</button>
</div>
</div>
<div v-if="selectedSite" class="flex-fit flex flex-wrap gap-1 border-box pb2">
<div style="flex: 1 1 20ch">
<label>URL</label>
<input
v-if="selectedSite"
text="Szurubooru URL"
type="text"
name="domain"
v-model.lazy="selectedSite.domain"
/>
</div>
<div style="flex: 1 1 12ch">
<label>Username</label>
<input text="Username" type="text" name="username" v-model="selectedSite.username" />
</div>
<div style="flex: 1 1 28ch">
<label>Authentication token</label> <label>Authentication token</label>
<input text="Authentication token" type="text" name="token" v-model="authToken" /> <input text="Authentication token" type="text" name="token" v-model="selectedSite.authToken" />
</li> </div>
<li> </div>
</div>
</div>
<div class="flex-fit flex flex-wrap gap-3">
<div class="settings-block" style="flex: 1 0 10ch">
<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>
</li> <p class="hint">This setting auto-saves.</p>
</ul> </div>
<ul class="input"> <div class="settings-block">
<li>
<label> <label>
<input type="checkbox" v-model="autoSearchSimilar" /> <input type="checkbox" v-model="autoSearchSimilar" />
Automatically search for similar posts Automatically search for similar posts
@ -35,8 +171,9 @@
Automatically start searching for similar posts when opening the popup. Enabling this option will hide the Automatically start searching for similar posts when opening the popup. Enabling this option will hide the
"Find Similar" button. "Find Similar" button.
</p> </p>
</li> </div>
<li>
<div class="settings-block">
<label> <label>
<input type="checkbox" v-model="addPageUrlToSource" /> <input type="checkbox" v-model="addPageUrlToSource" />
Add page URL to the source list Add page URL to the source list
@ -46,8 +183,9 @@
(e.g. twitter/pixiv/artstation). Note: if the source is empty/not detected then the page URL will always be (e.g. twitter/pixiv/artstation). Note: if the source is empty/not detected then the page URL will always be
used as fallback source. used as fallback source.
</p> </p>
</li> </div>
<li>
<div class="settings-block">
<label> <label>
<input type="checkbox" v-model="loadTagCounts" /> <input type="checkbox" v-model="loadTagCounts" />
Show how often a tag is used in the selected szurubooru instance Show how often a tag is used in the selected szurubooru instance
@ -56,181 +194,86 @@
Shows how often a given tag is used in the selected szurubooru instance. No number will be displayed when Shows how often a given tag is used in the selected szurubooru instance. No number will be displayed when
the tag does not yet exist. the tag does not yet exist.
</p> </p>
</li> </div>
</ul> </div>
<div class="settings-footer"> <div class="flex-fit flex flex-wrap justify-between gap-3">
<span class="status" :class="statusType">{{ statusText }}</span> <span class="status" :class="statusType">{{ statusText }}</span>
<div class="flex gap-1">
<button @click="testConnection">Test connection</button> <button @click="testConnection">Test connection</button>
<button @click="saveSettings" class="primary">Save settings</button> <button @click="saveSettings" class="primary">Save settings</button>
</div> </div>
</div> </div>
</div> </div>
</div>
</template> </template>
<script lang="ts"> <style lang="scss">
import Vue from "vue"; @use "../styles/main.scss";
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>
.content-holder { .content-holder {
padding: 1.5em; padding: 1.5em;
display: flex; display: flex;
justify-content: center; justify-content: center;
> .content-wrapper { > .content-wrapper {
box-sizing: border-box; // box-sizing: border-box;
text-align: left; // text-align: left;
display: inline-block; // display: inline-block;
flex: auto; // flex: auto;
max-width: 1000px; max-width: 1000px;
// gap: 1rem;
&:not(.transparent) {
background: #f5f5f5;
padding: 1.8em; padding: 1.8em;
} background: #f5f5f5;
} }
} }
html[data-theme="dark"] .content-holder > .content-wrapper:not(.transparent) { html.dark .content-wrapper {
background: var(--section-header-bg-color); background: var(--section-header-bg-color);
} }
.settings-footer { .settings-block {
display: flex;
gap: 5px;
flex-wrap: wrap;
.status {
flex-grow: 1;
}
> span.status-ok {
color: green;
}
> span.status-error {
color: red;
}
}
.input {
list-style-type: none;
padding: 0;
display: flex;
flex-wrap: wrap;
gap: 10px;
li {
flex: 1 0 200px; flex: 1 0 200px;
}
li.full-width {
min-width: 100%;
}
label { label {
display: block; padding: 0;
padding: 0.3em 0; margin-bottom: 0.3em;
} }
} }
.hint { .hint {
margin-top: 0.2em; margin-top: 0.4em;
margin-bottom: 0; margin-bottom: 0;
color: var(--secondary-text); color: var(--secondary-text);
font-size: 80%; font-size: 80%;
line-height: 120%; line-height: 120%;
} }
.status-error {
color: red;
}
.status-success {
color: green;
}
label {
display: block;
padding: 0.3em 0;
}
input[type="checkbox"] {
margin: 0 3px 0 0;
}
@media only screen and (max-width: 600px) {
.content-holder {
padding: 0;
}
.status {
flex: 0 0 100%;
}
}
</style> </style>

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

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

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

@ -0,0 +1,7 @@
import { createApp } from "vue";
import App from "./App.vue";
import { setupApp } from "~/logic/common-setup";
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)
});

File diff suppressed because it is too large Load Diff

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>

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

@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<base target="_blank" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Popup</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="./main.ts"></script>
</body>
</html>

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

@ -0,0 +1,14 @@
import { createApp } from "vue";
import App from "./App.vue";
import { setupApp } from "~/logic/common-setup";
import { isChrome, isMobile } from "~/env";
// 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 && !isMobile) {
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,104 +0,0 @@
import { browser } from "webextension-polyfill-ts";
import { BrowserCommand, Message, encodeTagName, getUrl } from "../Common";
import { Config } from "../Config";
import SzuruWrapper from "../SzuruWrapper";
import { PostAlreadyUploadedError, SzuruError } from "../SzuruTypes";
import { PostViewModel } from "../ViewModels";
async function uploadPost(post: PostViewModel) {
console.dir(post);
const cfg = await Config.load();
const szuru = SzuruWrapper.createFromConfig(cfg.sites[0]);
try {
// Create and upload post
browser.runtime.sendMessage(new BrowserCommand("remove_messages", 10));
browser.runtime.sendMessage(new BrowserCommand("push_message", new Message("Uploading...")));
const createdPost = await szuru.createPost(post);
browser.runtime.sendMessage(new BrowserCommand("remove_messages", 1));
browser.runtime.sendMessage(
new BrowserCommand("push_message", new Message("Uploaded post " + createdPost.id, "success"))
);
// TODO: Clicking a link doesn't actually open it in a new tab,
// see https://stackoverflow.com/questions/8915845
// uploadMsg.content = `<a href='${this.getPostUrl(createdPost)}' target='_blank'>Uploaded post</a>`;
// uploadMsg.type = "success";
// Find tags with "default" category and update it
// TODO: Make all these categories configurable
const tagsWithCategory = post.tags.filter((x) => x.category);
const unsetCategoryTags = createdPost.tags
.filter((x) => x.category == "default")
.filter((x) => tagsWithCategory.some((y) => x.names.includes(y.name)));
if (unsetCategoryTags.length != 0) {
browser.runtime.sendMessage(
new BrowserCommand("push_message", new Message(`${unsetCategoryTags.length} tags need a different category`))
);
// unsetCategoryTags is of type MicroTag[] and we need a Tag resource to update it, so let's get those
const query = unsetCategoryTags.map((x) => encodeTagName(x.names[0])).join();
const tags = (await szuru.getTags(query)).results;
const existingCategories = (await szuru.getTagCategories()).results;
let categoriesChangedCount = 0;
for (const i in tags) {
browser.runtime.sendMessage(new BrowserCommand("remove_messages", 1));
browser.runtime.sendMessage(
new BrowserCommand("push_message", new Message(`Updating tag ${i}/${unsetCategoryTags.length}`))
);
const wantedCategory = tagsWithCategory.find((x) => tags[i].names.includes(x.name))!.category!;
if (existingCategories.some((x) => x.name == wantedCategory)) {
tags[i].category = wantedCategory;
await szuru.updateTag(tags[i]);
categoriesChangedCount++;
} else {
console.log(
`Not adding the '${wantedCategory}' category to the tag '${tags[i].names[0]}' because the szurubooru instance does not have this category.`
);
}
}
browser.runtime.sendMessage(new BrowserCommand("remove_messages", 1));
if (categoriesChangedCount > 0) {
browser.runtime.sendMessage(
new BrowserCommand("push_message", new Message(`Updated ${categoriesChangedCount} tags`, "success"))
);
}
}
} catch (ex) {
browser.runtime.sendMessage(new BrowserCommand("remove_messages", 1));
const error = ex as SzuruError;
// TODO: Actual good error handling/messaging
if (error.name) {
console.error(error);
switch (error.name) {
case "PostAlreadyUploadedError": {
const otherPostId = (error as PostAlreadyUploadedError).otherPostId;
const url = getUrl(szuru.apiUrl.replace("api", ""), "post", otherPostId.toString());
const msg = `<a href='${url}' target='_blank'>Post already uploaded (${otherPostId})</a>`;
browser.runtime.sendMessage(new BrowserCommand("push_message", new Message(msg, "error")));
break;
}
default:
browser.runtime.sendMessage(new BrowserCommand("push_message", new Message(ex?.message ?? ex, "error")));
break;
}
} else {
console.error(ex);
browser.runtime.sendMessage(new BrowserCommand("push_message", new Message(ex.message, "error")));
}
}
}
async function messageHandler(cmd: BrowserCommand): Promise<any> {
switch (cmd.name) {
case "upload_post":
return uploadPost(cmd.data);
}
}
browser.runtime.onMessage.addListener(messageHandler);

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);

View File

@ -1,9 +1,56 @@
@use "sass:color";
@use "basscss/css/basscss-cp.css";
:root {
--space-1: 0.25rem;
--space-2: 0.5rem;
--space-3: 1rem;
--space-4: 2rem;
}
.flex-fit {
flex: 0 0 100%;
}
.gap-1 {
gap: var(--space-1);
}
.gap-2 {
gap: var(--space-2);
}
.gap-3 {
gap: var(--space-3);
}
.gap-4 {
gap: var(--space-4);
}
.gapx-1 {
column-gap: var(--space-1);
}
.gapx-2 {
column-gap: var(--space-2);
}
.gapx-3 {
column-gap: var(--space-3);
}
.gapx-4 {
column-gap: var(--space-4);
}
/* open-sans-regular - latin */ /* open-sans-regular - latin */
@font-face { @font-face {
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 {
@ -11,26 +58,34 @@ body {
font-size: 16px; font-size: 16px;
} }
$primary-color: #24aadd;
$danger-color: #f44336;
$primary-color-dark: color.scale($primary-color, $lightness: -30%);
$danger-color-dark: color.scale($danger-color, $lightness: -50%);
// TODO: Darker success color
:root { :root {
--button-bg-color: #a2a2a2; --button-bg-color: #a2a2a2;
--primary-color: #24aadd; --primary-color: #{$primary-color};
--bg-main-color: #fff; --bg-main-color: #fff;
--bg-secondary-color: #fafafa; --bg-secondary-color: #fafafa;
--border-color: #eee; --border-color: #eee;
--secondary-text: #888; --secondary-text: #888;
--error-color: #f44336; --danger-color: #{$danger-color};
--success-color: #4caf50; --success-color: #4caf50;
--section-header-fg-color: #4c4c4c; --section-header-fg-color: #4c4c4c;
--section-header-bg-color: #eee; --section-header-bg-color: #eee;
--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: #{$primary-color-dark};
--bg-main-color: #1a1a1a; --bg-main-color: #1a1a1a;
--bg-secondary-color: #3e3e3e; --bg-secondary-color: #3e3e3e;
--border-color: #474747; --border-color: #474747;
--danger-color: #{$danger-color-dark};
--section-header-fg-color: #d9d9d9; --section-header-fg-color: #d9d9d9;
--section-header-bg-color: #272727; --section-header-bg-color: #272727;
--text-color: #e6e6e6; --text-color: #e6e6e6;
@ -43,11 +98,20 @@ body {
display: block; display: block;
} }
input[type="email"],
input[type="number"],
input[type="password"],
input[type="text"],
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 +184,13 @@ 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;
line-height: 1.2rem;
}
} }
.tag-general { .tag-general {
@ -158,7 +229,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 {
@ -192,10 +262,10 @@ a.remove-tag {
} }
} }
.message-error { .bg-danger {
background: var(--error-color) !important; background: var(--danger-color) !important;
} }
.message-success { .bg-success {
background: var(--success-color) !important; background: var(--success-color) !important;
} }

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);
});
});

18
src/utils.ts Normal file
View File

@ -0,0 +1,18 @@
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, "\\:");
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function getErrorMessage(ex: any) {
return ex.description ?? ex.message ?? ex;
}

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