Compare commits

...

28 Commits

Author SHA1 Message Date
Nes 633bf05dad Add updates.json 2026-10-30 15:05:16 -07:00
Nes370 37b359597c Update icon-128.png
Replaced default icon with Nol <3
2026-10-12 20:32:09 -07:00
neobooru c17bd87089 Update neo-scraper to 0.11.1 2026-08-19 00:41:28 +02:00
neobooru 59145cebdc Lock primevue to version 3.45.0
Needed because we override some of their styles. These overrides slightly changed in newer versions.
2026-08-19 00:13:40 +02:00
neobooru 4895e126fb Update dependencies + small fix 2026-08-19 00:07:46 +02:00
neobooru a0a0a591bc Run prettier 2026-08-18 23:25:03 +02:00
neobooru 381dac72d4 Update 'Tags to ignore' interface 2026-08-18 23:24:43 +02:00
G1org1owo 646241b45f PopupMain.vue: filter tags for each post based on tag ignores 2026-08-18 23:22:06 +02:00
G1org1owo 45f20ebfc8 Add config interface for tag ignores 2026-08-18 23:22:06 +02:00
G1org1owo 3d243252cd Add ability to select multiple tabs 2026-08-18 22:33:57 +02:00
neobooru 0f83292e86 Disable upload notifications by default 2026-08-18 22:23:49 +02:00
Keo Cheung be2afe55ff Add option to send browser notifications 2026-08-18 22:22:02 +02:00
Keo Cheung 5101c79c59 Send notifications after uploading 2026-08-18 22:22:02 +02:00
neobooru e2bf28a29b Update neo-scraper to 0.11.0 2026-07-31 02:18:44 +02:00
G1org1owo 1a6fe13512 Fix undefined tag usages access in PopupMain.vue 2025-08-27 22:15:36 +02:00
neobooru ce6a6c6521 Update neo-scraper to 0.10.1 2025-04-12 01:05:04 +02:00
neobooru 3aa31955ce Use ubuntu 24.04 for builds and fix artifact naming issue 2025-02-19 00:11:51 +01:00
neobooru 24cec0bd81 Update web-ext to v8 2025-02-19 00:06:51 +01:00
neobooru f4a1b2a1ea Update to neo-scraper v0.10.0
And try to rename build artifacts
2025-02-19 00:01:16 +01:00
neobooru e9d37caf7c Update actions/upload-artifact version 2025-02-17 00:30:49 +01:00
neobooru afe4ff535b Fix issue where merging new image content for existing posts did not work when uploadMode is set to "content" 2025-02-17 00:24:09 +01:00
shibao 9e07ee1594 add alwaysUploadAsContent option 2025-01-21 23:43:28 +01:00
neobooru 7c5c4d3ccd Fix pnpm-lock.yaml 2024-12-09 00:30:54 +01:00
neobooru 4bea802819 Update neo-scraper to 0.9.3 2024-12-08 18:58:45 +01:00
neobooru c08e6473e9 Update neo-scraper to fix yande.re issues 2024-07-11 23:10:09 +02:00
neobooru 76a4c01577 Fix linter warning 2024-07-10 20:34:00 +02:00
G1org1owo cae923b68a Refactor nesting in loadTagCounts() 2024-07-09 01:31:35 +02:00
G1org1owo 5ff664e725 Check for aliases when loading tag counts 2024-07-09 01:21:12 +02:00
14 changed files with 3377 additions and 3011 deletions

View File

@ -15,7 +15,7 @@ on:
jobs: jobs:
build_chrome: build_chrome:
name: "Build Chrome Extension" name: "Build Chrome Extension"
runs-on: ubuntu-20.04 runs-on: ubuntu-24.04
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v2 uses: actions/checkout@v2
@ -30,14 +30,14 @@ jobs:
- name: Pack ZIP - name: Pack ZIP
run: pnpm pack:zip run: pnpm pack:zip
- uses: actions/upload-artifact@v3 - uses: actions/upload-artifact@v4
with: with:
name: Chrome Extension (Unsigned) name: Chrome Extension (Unsigned)
path: extension.zip path: extension.zip
build_unlisted_firefox: build_unlisted_firefox:
name: "Build Unlisted Firefox Extension" name: "Build Unlisted Firefox Extension"
runs-on: ubuntu-20.04 runs-on: ubuntu-24.04
# Doesn't really need the Chrome build, but we can reuse its cache. # Doesn't really need the Chrome build, but we can reuse its cache.
needs: build_chrome needs: build_chrome
if: github.ref == 'refs/heads/master' || startsWith(github.ref, 'refs/tags/v') if: github.ref == 'refs/heads/master' || startsWith(github.ref, 'refs/tags/v')
@ -60,14 +60,17 @@ jobs:
WEB_EXT_API_KEY: ${{ secrets.WEB_EXT_API_KEY }} WEB_EXT_API_KEY: ${{ secrets.WEB_EXT_API_KEY }}
WEB_EXT_API_SECRET: ${{ secrets.WEB_EXT_API_SECRET }} WEB_EXT_API_SECRET: ${{ secrets.WEB_EXT_API_SECRET }}
- uses: actions/upload-artifact@v3 - name: Rename XPI
run: rename.ul szuruchrome_gh- SzuruChrome-v web-ext-artifacts/*.xpi
- uses: actions/upload-artifact@v4
with: with:
name: Firefox Extension (Signed) name: Firefox Extension (Signed)
path: web-ext-artifacts/*.xpi path: web-ext-artifacts/*.xpi
build_amo_firefox: build_amo_firefox:
name: "Build Firefox Extension for AMO" name: "Build Firefox Extension for AMO"
runs-on: ubuntu-20.04 runs-on: ubuntu-24.04
# Doesn't really need the Chrome build, but we can reuse its cache. # Doesn't really need the Chrome build, but we can reuse its cache.
needs: build_chrome needs: build_chrome
# Only run (on master branch && if tagged) or (manually dispatching). # Only run (on master branch && if tagged) or (manually dispatching).

Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

After

Width:  |  Height:  |  Size: 36 KiB

View File

@ -19,7 +19,7 @@
"pack:xpi": "cross-env WEB_EXT_ARTIFACTS_DIR=./ web-ext build --source-dir ./extension --filename extension.xpi --overwrite-dest", "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:chromium": "web-ext run --source-dir ./extension --target=chromium",
"start:firefox": "web-ext run --source-dir ./extension --target=firefox-desktop", "start:firefox": "web-ext run --source-dir ./extension --target=firefox-desktop",
"sign:firefox": "web-ext sign --use-submission-api --source-dir ./extension", "sign:firefox": "web-ext sign --source-dir ./extension",
"clear": "rimraf extension/dist extension/manifest.json extension.*", "clear": "rimraf extension/dist extension/manifest.json extension.*",
"lint": "eslint .", "lint": "eslint .",
"extlint": "web-ext lint -s extension", "extlint": "web-ext lint -s extension",
@ -27,55 +27,55 @@
"pretty": "prettier -w ." "pretty": "prettier -w ."
}, },
"dependencies": { "dependencies": {
"axios": "^1.6.3", "axios": "^1.19.0",
"byte-size": "^8.1.1", "byte-size": "^8.2.1",
"deepmerge": "^4.3.1", "deepmerge": "^4.3.1",
"lodash": "^4.17.21", "lodash": "^4.18.1",
"markdown-it": "^14.0.0", "markdown-it": "^14.3.0",
"neo-scraper": "^0.9.0", "neo-scraper": "^0.11.1",
"normalize.css": "^8.0.1", "normalize.css": "^8.0.1",
"pinia": "^2.1.7", "pinia": "^2.3.1",
"primeflex": "^3.3.1", "primeflex": "^3.3.1",
"primevue": "^3.45.0", "primevue": "3.45.0",
"vue-router": "^4.2.5" "vue-router": "^4.6.4"
}, },
"devDependencies": { "devDependencies": {
"@ffflorian/jszip-cli": "^3.5.8", "@ffflorian/jszip-cli": "^3.16.5",
"@fortawesome/fontawesome-svg-core": "^6.5.1", "@fortawesome/fontawesome-svg-core": "^6.7.2",
"@fortawesome/free-solid-svg-icons": "^6.5.1", "@fortawesome/free-solid-svg-icons": "^6.7.2",
"@fortawesome/vue-fontawesome": "^3.0.5", "@fortawesome/vue-fontawesome": "^3.3.3",
"@types/byte-size": "^8.1.2", "@types/byte-size": "^8.1.2",
"@types/fs-extra": "^11.0.4", "@types/fs-extra": "^11.0.4",
"@types/lodash": "^4.14.202", "@types/lodash": "^4.17.25",
"@types/markdown-it": "^13.0.7", "@types/markdown-it": "^13.0.9",
"@types/node": "^20.10.5", "@types/node": "^20.19.43",
"@types/webextension-polyfill": "^0.10.7", "@types/webextension-polyfill": "^0.10.7",
"@typescript-eslint/eslint-plugin": "^6.16.0", "@typescript-eslint/eslint-plugin": "^6.21.0",
"@vitejs/plugin-vue": "^5.0.1", "@vitejs/plugin-vue": "^5.2.4",
"@vue/compiler-sfc": "^3.4.0", "@vue/compiler-sfc": "^3.5.41",
"@vue/test-utils": "^2.4.3", "@vue/test-utils": "^2.4.11",
"@vueuse/core": "^10.7.1", "@vueuse/core": "^10.11.1",
"chokidar": "^3.5.3", "chokidar": "^3.6.0",
"cross-env": "^7.0.3", "cross-env": "^7.0.3",
"crx": "^5.0.1", "crx": "^5.0.1",
"eslint": "^8.56.0", "eslint": "^8.57.1",
"eslint-plugin-vue": "^9.19.2", "eslint-plugin-vue": "^9.33.0",
"esno": "^4.0.0", "esno": "^4.8.0",
"fs-extra": "^11.2.0", "fs-extra": "^11.4.0",
"jsdom": "^23.0.1", "jsdom": "^23.2.0",
"kolorist": "^1.8.0", "kolorist": "^1.8.0",
"npm-run-all": "^4.1.5", "npm-run-all": "^4.1.5",
"prettier": "^3.1.1", "prettier": "^3.9.6",
"rimraf": "^3.0.2", "rimraf": "^3.0.2",
"sass": "^1.69.6", "sass": "^1.102.0",
"typescript": "^5.3.3", "typescript": "^5.9.3",
"unplugin-auto-import": "^0.17.3", "unplugin-auto-import": "^0.17.8",
"unplugin-vue-components": "^0.26.0", "unplugin-vue-components": "^0.26.0",
"vite": "^5.0.10", "vite": "^5.4.21",
"vitest": "^1.1.0", "vitest": "^1.6.1",
"vue": "^3.4.0", "vue": "^3.5.41",
"vue-eslint-parser": "^9.3.2", "vue-eslint-parser": "^9.4.3",
"web-ext": "^7.9.0", "web-ext": "^8.10.0",
"webextension-polyfill": "^0.10.0" "webextension-polyfill": "^0.10.0"
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,4 @@
import { encodeTagName, getErrorMessage } from "~/utils"; import { encodeTagName, getErrorMessage, getUrl } from "~/utils";
import { import {
BrowserCommand, BrowserCommand,
PostUploadCommandData, PostUploadCommandData,
@ -19,6 +19,13 @@ if (import.meta.hot) {
import("./contentScriptHMR"); import("./contentScriptHMR");
} }
browser.notifications.onClicked.addListener((url) => {
if (url) {
browser.tabs.create({ url });
browser.notifications.clear(url);
}
});
async function uploadPost(data: PostUploadCommandData) { async function uploadPost(data: PostUploadCommandData) {
const info: PostUploadInfo = { const info: PostUploadInfo = {
state: "uploading", state: "uploading",
@ -117,6 +124,16 @@ async function uploadPost(data: PostUploadCommandData) {
await szuru.updatePool(existingPool.id, updateRequest); await szuru.updatePool(existingPool.id, updateRequest);
} }
} }
if (data.sendNotifications && browser.notifications) {
const createdPostUrl = getUrl(data.selectedSite.domain, "post", createdPost.id.toString());
browser.notifications.create(createdPostUrl, {
type: "basic",
iconUrl: browser.runtime.getURL("assets/icon-128.png"),
title: data.selectedSite.domain,
message: `Uploaded ${data.post.contentUrl}`,
});
}
} catch (ex: any) { } catch (ex: any) {
console.error(ex); console.error(ex);
if (ex.name && ex.name == "PostAlreadyUploadedError") { if (ex.name && ex.name == "PostAlreadyUploadedError") {

View File

@ -31,7 +31,7 @@ export async function getManifest() {
page: "./dist/background/index.html", page: "./dist/background/index.html",
// persistent: false, // persistent: false,
}, },
permissions: ["storage", "activeTab", "webRequest", "webRequestBlocking", "<all_urls>"], permissions: ["storage", "activeTab", "webRequest", "webRequestBlocking", "notifications", "<all_urls>"],
content_scripts: [ content_scripts: [
{ {
matches: ["http://*/*", "https://*/*"], matches: ["http://*/*", "https://*/*"],

View File

@ -8,7 +8,7 @@ export class TagDetails {
public names: string[], public names: string[],
public category?: string, public category?: string,
public usages?: number, public usages?: number,
) { } ) {}
get name() { get name() {
return this.names[0]; return this.names[0];
@ -38,7 +38,7 @@ export class PoolDetails {
public names: string[], public names: string[],
public category?: string, public category?: string,
public postCount?: number, public postCount?: number,
) { } ) {}
get name() { get name() {
return this.names[0]; return this.names[0];
@ -109,7 +109,7 @@ export class SimilarPostInfo {
constructor( constructor(
public readonly id: number, public readonly id: number,
public readonly percentage: number, public readonly percentage: number,
) { } ) {}
} }
export type PostUploadState = "uploading" | "uploaded" | "error"; export type PostUploadState = "uploading" | "uploaded" | "error";
@ -148,7 +148,8 @@ export class PostUploadCommandData {
constructor( constructor(
public readonly post: ScrapedPostDetails, public readonly post: ScrapedPostDetails,
public readonly selectedSite: SzuruSiteConfig, public readonly selectedSite: SzuruSiteConfig,
) { } public readonly sendNotifications: boolean,
) {}
} }
export class SetPostUploadInfoData { export class SetPostUploadInfoData {
@ -156,7 +157,7 @@ export class SetPostUploadInfoData {
public instanceId: string, public instanceId: string,
public postId: string, public postId: string,
public info: PostUploadInfo, public info: PostUploadInfo,
) { } ) {}
} }
export class SetExactPostId { export class SetExactPostId {
@ -164,7 +165,7 @@ export class SetExactPostId {
public readonly instanceId: string, public readonly instanceId: string,
public readonly postId: string, public readonly postId: string,
public readonly exactPostId: number, public readonly exactPostId: number,
) { } ) {}
} }
export class PostUpdateCommandData { export class PostUpdateCommandData {
@ -172,14 +173,14 @@ export class PostUpdateCommandData {
public readonly postId: number, public readonly postId: number,
public readonly updateRequest: UpdatePostRequest, public readonly updateRequest: UpdatePostRequest,
public readonly selectedSite: SzuruSiteConfig, public readonly selectedSite: SzuruSiteConfig,
) { } ) {}
} }
export class FetchCommandData { export class FetchCommandData {
constructor( constructor(
public readonly url: string, public readonly url: string,
public readonly options: RequestInit | undefined = undefined, public readonly options: RequestInit | undefined = undefined,
) { } ) {}
} }
export class SzuruSiteConfig { export class SzuruSiteConfig {
@ -193,7 +194,7 @@ export class TagCategoryColor {
constructor( constructor(
public name: string, public name: string,
public color: string, public color: string,
) { } ) {}
} }
export const getDefaultTagCategories = () => [ export const getDefaultTagCategories = () => [

View File

@ -8,7 +8,7 @@ import TabView from "primevue/tabview";
import TabPanel from "primevue/tabpanel"; import TabPanel from "primevue/tabpanel";
import DataTable from "primevue/datatable"; import DataTable from "primevue/datatable";
import Column from "primevue/column"; import Column from "primevue/column";
import { SzuruSiteConfig, TagCategoryColor, getDefaultTagCategories } from "~/models"; import { TagDetails, SzuruSiteConfig, TagCategoryColor, getDefaultTagCategories } from "~/models";
import SzurubooruApi from "~/api"; import SzurubooruApi from "~/api";
type StatusType = "success" | "error" | "quiet"; type StatusType = "success" | "error" | "quiet";
@ -102,6 +102,14 @@ async function importTagCategoriesFromInstance() {
} }
} }
function addTagIgnore() {
cfg.value.tagIgnores.push(new TagDetails([""]));
}
function resetTagIgnores() {
cfg.value.tagIgnores.splice(0);
}
// For debugging // For debugging
const wnd = window as any; const wnd = window as any;
wnd.szc_get_config = () => JSON.parse(JSON.stringify(cfg.value)); wnd.szc_get_config = () => JSON.parse(JSON.stringify(cfg.value));
@ -139,6 +147,25 @@ wnd.szc_set_config_version = (v = 0) => (cfg.value.version = v);
</p> </p>
</div> </div>
<div class="col-12 md:col-6">
<label>
<input type="checkbox" v-model="cfg.alwaysUploadAsContent" />
Always upload as content
</label>
<p class="hint">This will always upload the image content directly, instead of as an URL</p>
</div>
<div class="col-12 md:col-6">
<label>
<input type="checkbox" v-model="cfg.sendUploadNotifications" />
Send browser notifications after uploading
</label>
<p class="hint">
This will send a browser notification after a successful upload. Clicking the notification will open the
uploaded post in a new tab.
</p>
</div>
<span class="col-12 status-quiet">{{ versionInfo }}</span> <span class="col-12 status-quiet">{{ versionInfo }}</span>
</div> </div>
</TabPanel> </TabPanel>
@ -249,49 +276,70 @@ wnd.szc_set_config_version = (v = 0) => (cfg.value.version = v);
</TabPanel> </TabPanel>
<TabPanel header="Tags"> <TabPanel header="Tags">
<div class="grid"> <div class="separated-content">
<DataTable :value="cfg.tagCategories" table-class="col-12" style="width: 100%"> <div class="grid">
<Column v-for="col of columns" :key="col.field" :field="col.field" :header="col.header"> <DataTable :value="cfg.tagCategories" table-class="col-12" style="width: 100%">
<template #body="{ data, field }"> <Column v-for="col of columns" :key="col.field" :field="col.field" :header="col.header">
<template v-if="field == 'color'"> <template #body="{ data, field }">
<div class="color-preview"> <template v-if="field == 'color'">
<input type="text" class="color" v-model="data[field]" /> <div class="color-preview">
<div <input type="text" class="color" v-model="data[field]" />
class="preview background-preview" <div
:style="{ 'border-color': data[field], 'background-color': data[field] }" class="preview background-preview"
></div> :style="{ 'border-color': data[field], 'background-color': data[field] }"
<div ></div>
class="preview text-preview" <div
:style="{ 'border-color': data[field], color: data[field] }" class="preview text-preview"
></div> :style="{ 'border-color': data[field], color: data[field] }"
</div> ></div>
</div>
</template>
<template v-else>
<input type="text" :name="field" v-model="data[field]" />
</template>
</template> </template>
</Column>
<template v-else> <Column field="name">
<input type="text" :name="field" v-model="data[field]" /> <template #body="{ index }">
<a class="color-primary cursor-pointer" @click="() => cfg.tagCategories.splice(index, 1)">Remove</a>
</template> </template>
</template> </Column>
</Column> </DataTable>
<Column field="name"> <div class="col-12 flex flex-wrap grid grid-nogutter gap-1">
<template #body="{ index }"> <button class="primary" @click="addTagCategory">Add new category</button>
<a class="color-primary cursor-pointer" @click="() => cfg.tagCategories.splice(index, 1)">Remove</a> <button @click="importTagCategoriesFromInstance">Import from active instance</button>
</template> <button class="bg-danger sm:ml-auto" @click="resetTagCategories">Reset to default</button>
</Column> </div>
</DataTable>
<div class="col-12 flex flex-wrap grid grid-nogutter gap-1">
<button class="primary" @click="addTagCategory">Add new category</button>
<button @click="importTagCategoriesFromInstance">Import from active instance</button>
<button class="bg-danger sm:ml-auto" @click="resetTagCategories">Reset to default</button>
</div> </div>
<!-- TODO: Tag category colors -->
<div class="grid">
<DataTable :value="cfg.tagIgnores" table-class="col-12" style="width: 100%">
<Column field="names" header="Tags to ignore">
<template #body="{ data, field }">
<input type="text" :name="field" v-model="data[field][0]" />
</template>
</Column>
<Column field="remove">
<template #body="{ index }">
<a class="color-primary cursor-pointer" @click="() => cfg.tagIgnores.splice(index, 1)">Remove</a>
</template>
</Column>
</DataTable>
<div class="col-12 flex flex-wrap grid grid-nogutter gap-1">
<button class="primary" @click="addTagIgnore">Add tag</button>
<button class="bg-danger sm:ml-auto" @click="resetTagIgnores">Clear</button>
</div>
</div>
<!-- TODO: Category ignore list -->
</div> </div>
<!-- TODO: Tag category colors -->
<!-- TODO: Tag ignore list -->
<!-- TODO: Category ignore list -->
</TabPanel> </TabPanel>
<!-- <TabPanel header="About"> <!-- <TabPanel header="About">

View File

@ -5,7 +5,7 @@ import { Post, UpdatePostRequest } from "~/api/models";
import { isMobile } from "~/env"; import { isMobile } from "~/env";
import { BrowserCommand, PostUpdateCommandData, TagDetails } from "~/models"; import { BrowserCommand, PostUpdateCommandData, TagDetails } from "~/models";
import { cfg, useMergeStore, usePopupStore } from "~/stores"; import { cfg, useMergeStore, usePopupStore } from "~/stores";
import { emptyPost, getUrl } from "~/utils"; import { emptyPost, ensurePostHasContentToken, getUrl } from "~/utils";
const props = defineProps(["siteId", "postId"]); const props = defineProps(["siteId", "postId"]);
const merge = useMergeStore(); const merge = useMergeStore();
@ -140,7 +140,10 @@ async function mergeChanges() {
} }
if (imageToKeep.value == "new") { if (imageToKeep.value == "new") {
req.contentUrl = scrapedPost?.contentUrl; // In practice this should not be needed, because finding similar posts requires the use of content tokens.
// So if a similar post is found, it means that a contentToken has already been set.
await ensurePostHasContentToken(szuru, scrapedPost, cfg);
req.contentToken = scrapedPost.instanceSpecificData[cfg.value.selectedSiteId!].contentToken!;
} }
if (!req.safety && !req.source && !(req.contentUrl || req.contentToken) && req.tags === undefined) { if (!req.safety && !req.source && !(req.contentUrl || req.contentToken) && req.tags === undefined) {

View File

@ -2,7 +2,7 @@
import { useDark } from "@vueuse/core"; import { useDark } from "@vueuse/core";
import { cloneDeep } from "lodash"; import { cloneDeep } from "lodash";
import { ScrapeResults } from "neo-scraper"; import { ScrapeResults } from "neo-scraper";
import { getUrl, encodeTagName, getErrorMessage, getPostInfoSummary } from "~/utils"; import { getUrl, encodeTagName, getErrorMessage, getPostInfoSummary, ensurePostHasContentToken } from "~/utils";
import { import {
BrowserCommand, BrowserCommand,
ScrapedPostDetails, ScrapedPostDetails,
@ -73,32 +73,43 @@ function openOptionsPage() {
browser.runtime.openOptionsPage(); browser.runtime.openOptionsPage();
} }
async function getActiveTabId(): Promise<number> { async function getSelectedTabIds(): Promise<number[]> {
const activeTabs = await browser.tabs.query({ const selectedTabs = await browser.tabs.query({
active: true, highlighted: true,
currentWindow: true, currentWindow: true,
}); });
if (activeTabs.length > 0 && activeTabs[0].id) return activeTabs[0].id; if (selectedTabs.length > 0 && selectedTabs[0].id) {
return selectedTabs.filter((tab) => tab.id).map((tab) => tab.id as number);
}
throw new Error("No active tab."); throw new Error("No active tab.");
} }
async function grabPost() { async function grabPost() {
// Get active tab // Get active tab
const activeTabId = await getActiveTabId(); const selectedTabIds = await getSelectedTabIds();
// Send 'grab_post' to the content script on the active tab let scrapeResults: ScrapeResults = new ScrapeResults();
const x = await browser.tabs.sendMessage(activeTabId, new BrowserCommand("grab_post")); for (const selectedTabId of selectedTabIds) {
// We need to create a new ScrapeResults object and fill it with our data, because the get_posts() // Send 'grab_post' to the content script on the active tabs
// method gets 'lost' when sent from the contentscript to the popup (it gets JSON.stringified and any prototype defines are lost there) const x = await browser.tabs.sendMessage(selectedTabId, new BrowserCommand("grab_post"));
const res: ScrapeResults = Object.assign(new ScrapeResults(), x); // 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 results: ScrapeResults = Object.assign(new ScrapeResults(), x);
console.dir(res); for (const result of results.results) {
const res = scrapeResults.results.find((r) => r.engine === result.engine);
if (res) res.posts.push(...result.posts);
else scrapeResults.results.push(result);
}
}
console.dir(scrapeResults);
// Clear current posts array // Clear current posts array
pop.posts.splice(0); pop.posts.splice(0);
for (const result of res.results) { for (const result of scrapeResults.results) {
for (const i in result.posts) { for (const i in result.posts) {
const vm = new ScrapedPostDetails(result.posts[i]); const vm = new ScrapedPostDetails(result.posts[i]);
const name = result.posts[i].name ?? `Post ${parseInt(i) + 1}`; // parseInt() is required! const name = result.posts[i].name ?? `Post ${parseInt(i) + 1}`; // parseInt() is required!
@ -108,6 +119,10 @@ async function grabPost() {
vm.tags.splice(0); vm.tags.splice(0);
} }
if (cfg.value.alwaysUploadAsContent && vm.name !== "[fallback] Upload as URL") {
vm.uploadMode = "content";
}
// Add current pageUrl to the source if either // Add current pageUrl to the source if either
// a. user has addPageUrlToSource set to true // a. user has addPageUrlToSource set to true
// b. source is empty // b. source is empty
@ -121,6 +136,14 @@ async function grabPost() {
vm.instanceSpecificData[site.id] = {}; vm.instanceSpecificData[site.id] = {};
} }
// Remove ignored tags
// The complexity for this is quite bad but all the other ways I tried were even worse
vm.tags = vm.tags.filter((tag) =>
cfg.value.tagIgnores.every(
(ignoredTag) => tag.name != ignoredTag.names[0], // no getters after deserializing
),
);
pop.posts.push(vm); pop.posts.push(vm);
} }
} }
@ -163,11 +186,15 @@ async function upload() {
const post: ScrapedPostDetails = cloneDeep(pop.selectedPost)!; const post: ScrapedPostDetails = cloneDeep(pop.selectedPost)!;
// uploadMode "content" requires a content token to work. So ensure it is set. // uploadMode "content" requires a content token to work. So ensure it is set.
if (post.uploadMode == "content") { if (post.uploadMode === "content") {
await ensurePostHasContentToken(post); await ensurePostHasContentToken(szuru.value!, post, cfg);
} }
const cmdData = new PostUploadCommandData(post, <SzuruSiteConfig>cloneDeep(selectedSite.value)); const cmdData = new PostUploadCommandData(
post,
<SzuruSiteConfig>cloneDeep(selectedSite.value),
cfg.value.sendUploadNotifications,
);
const cmd = new BrowserCommand("upload_post", cmdData); const cmd = new BrowserCommand("upload_post", cmdData);
await browser.runtime.sendMessage(cmd); await browser.runtime.sendMessage(cmd);
} catch (ex: any) { } catch (ex: any) {
@ -245,31 +272,14 @@ async function clickFindSimilar() {
if (pop.selectedPost) return await findSimilar(pop.selectedPost); if (pop.selectedPost) return await findSimilar(pop.selectedPost);
} }
async function ensurePostHasContentToken(post: ScrapedPostDetails) {
if (!szuru.value || !cfg.value.selectedSiteId) return;
const selectedInstance = toRaw(szuru.value); // Get current object, and not reactive.
let instanceSpecificData = post.instanceSpecificData[cfg.value.selectedSiteId];
if (!instanceSpecificData) {
console.error("instanceSpecificData is undefined. This should never happen!");
return;
}
try {
let tmpRes = await selectedInstance.uploadTempFile(post.contentUrl, post.uploadMode);
// Save contentToken in PostViewModel so that we can reuse it when creating/uploading the post.
instanceSpecificData.contentToken = tmpRes.token;
} catch (ex) {
instanceSpecificData.genericError = "Couldn't upload content. " + getErrorMessage(ex);
throw ex;
}
}
async function findSimilar(post: ScrapedPostDetails | undefined) { async function findSimilar(post: ScrapedPostDetails | undefined) {
if (!post || !szuru.value || !cfg.value.selectedSiteId) return; if (!post || !szuru.value || !cfg.value.selectedSiteId) return;
// TODO: This code might not work. // TODO: This code might not work.
// Why is toRaw used?
// I guess it could happen that the selectedInstance changes halfway during this function?
// And in that case toRaw would ensure we have the original selected instance (as it was at the start of this function).
// In theory this sounds correct, but idk if it is needed in practice.
const selectedInstance = toRaw(szuru.value); // Get current object, and not reactive. const selectedInstance = toRaw(szuru.value); // Get current object, and not reactive.
let instanceSpecificData = post.instanceSpecificData[cfg.value.selectedSiteId]; let instanceSpecificData = post.instanceSpecificData[cfg.value.selectedSiteId];
@ -284,7 +294,7 @@ async function findSimilar(post: ScrapedPostDetails | undefined) {
isSearchingForSimilarPosts.value++; isSearchingForSimilarPosts.value++;
try { try {
await ensurePostHasContentToken(post); await ensurePostHasContentToken(selectedInstance, post, cfg);
const res = await selectedInstance.reverseSearchToken(instanceSpecificData.contentToken!); const res = await selectedInstance.reverseSearchToken(instanceSpecificData.contentToken!);
@ -313,12 +323,10 @@ async function loadTagCounts() {
// Not the best code, but it works I guess? // Not the best code, but it works I guess?
if (resp) { if (resp) {
for (let post of pop.posts) for (let post of pop.posts)
for (let tag of resp.results) for (let tag of resp.results) {
for (let postTag of post.tags) const postTag = post.tags.find((postTag) => tag.names.includes(postTag.name));
if (postTag.name == tag.names[0]) { if (postTag) postTag.usages = tag.usages;
postTag.usages = tag.usages; }
break;
}
} }
} }
} }
@ -404,7 +412,7 @@ useDark();
<template> <template>
<div class="popup-messages"> <div class="popup-messages">
<div class="messages"> <div class="messages">
<!-- <!--
Error messages Error messages
--> -->

View File

@ -1,6 +1,7 @@
import { defineStore } from "pinia"; import { defineStore } from "pinia";
import deepMerge from "deepmerge"; import deepMerge from "deepmerge";
import { import {
type TagDetails,
getDefaultTagCategories, getDefaultTagCategories,
type ScrapedPostDetails, type ScrapedPostDetails,
type SetPostUploadInfoData, type SetPostUploadInfoData,
@ -14,6 +15,8 @@ export const cfg = useStorageLocal(
{ {
version: 0, version: 0,
addPageUrlToSource: true, addPageUrlToSource: true,
alwaysUploadAsContent: false,
sendUploadNotifications: false,
autoSearchSimilar: false, autoSearchSimilar: false,
loadTagCounts: true, loadTagCounts: true,
fetchPostInfo: true, fetchPostInfo: true,
@ -38,6 +41,7 @@ export const cfg = useStorageLocal(
showInstancePicker: true, showInstancePicker: true,
}, },
tagCategories: [] as Array<TagCategoryColor>, tagCategories: [] as Array<TagCategoryColor>,
tagIgnores: [] as Array<TagDetails>,
}, },
{ {
mergeDefaults(storageValue, defaults) { mergeDefaults(storageValue, defaults) {

View File

@ -268,3 +268,9 @@ a.remove-tag {
.color-primary { .color-primary {
color: var(--primary-color); color: var(--primary-color);
} }
.separated-content > * + * {
padding-top: 1rem;
margin-top: 1.5rem;
border-top: 3px solid #333;
}

View File

@ -1,6 +1,7 @@
import byteSize from "byte-size"; import byteSize from "byte-size";
import { MicroUser, Post } from "./api/models"; import { MicroUser, Post } from "./api/models";
import { ScrapedPostDetails, TagDetails } from "./models"; import { ScrapedPostDetails, TagDetails } from "./models";
import SzurubooruApi from "./api";
export function getUrl(root: string, ...parts: string[]): string { export function getUrl(root: string, ...parts: string[]): string {
let url = root.replace(/\/+$/, ""); let url = root.replace(/\/+$/, "");
@ -102,3 +103,28 @@ export function getPostInfoSummary(post: ScrapedPostDetails) {
} }
return parts.join(" / "); return parts.join(" / ");
} }
export async function ensurePostHasContentToken(selectedInstance: SzurubooruApi, post: ScrapedPostDetails, cfg: any) {
if (!selectedInstance || !cfg.value.selectedSiteId) return;
const instanceSpecificData = post.instanceSpecificData[cfg.value.selectedSiteId];
if (!instanceSpecificData) {
console.error("instanceSpecificData is undefined. This should never happen!");
return;
}
if (instanceSpecificData.contentToken) {
console.log("[ensurePostHasContentToken] contentToken is already set.");
return;
}
try {
const tmpRes = await selectedInstance.uploadTempFile(post.contentUrl, post.uploadMode);
// Save contentToken in PostViewModel so that we can reuse it when creating/uploading the post.
instanceSpecificData.contentToken = tmpRes.token;
} catch (ex) {
instanceSpecificData.genericError = "Couldn't upload content. " + getErrorMessage(ex);
throw ex;
}
}

12
updates.json Normal file
View File

@ -0,0 +1,12 @@
{
"addons": {
"suzuruchrome@goblincave": {
"updates": [
{
"version": "0.1.4",
"update_link": "https://gitea.goblincave.synology.me/Nes/SzuruChrome/releases/download/mod-v0.1.X/SzuruChrome_v0.1.4.xpi"
}
]
}
}
}