Add experimental "Merge post" feature for similar posts.
parent
9675d25cd0
commit
6d8844bd43
|
|
@ -1,42 +0,0 @@
|
|||
# Developer notes
|
||||
|
||||
## How does it work?
|
||||
|
||||
This add-on has three parts.
|
||||
The first part is the popup, which is what pops up when you click on the logo.
|
||||
|
||||
The second part is a content script which is injected on the page you visit. This script tries to find importable content on the current page and sends this to the popup.
|
||||
|
||||
The third part is the background script which handles the upload functionality. This was previously part of the popup, but has since been moved to the background script.
|
||||
|
||||
### The popup
|
||||
|
||||
When opened (when you click on the add-on logo in your browser) it sends a message to the content script injected on the current page (active tab). This message asks the content script to scrape the DOM and return a SzuruPost element (with a source, contentUrl, safety, and a list of tags). Once it receives this element it renders it in the popup where you can make changes before importing it. When you click on the "Upload" button the SzuruPost will be sent to the background script which will handle the upload functionality. This is done so that the upload continues even after you close the popup. This means that you can close the popup after clicking the "Upload" button, and it'll continue with the upload.
|
||||
|
||||
### The content script
|
||||
|
||||
This script is injected on every page and does absolutely nothing until it receives the 'grab_post' message from the popup. When it does receive this message it checks if there are any loaders available to scrape this page. If a matching loader is found it'll pass the DOM of this page to the loader. The loader then uses the DOM to fill (as much as possible) a SzuruPost object. The SzuruPost is then passed back to the popup where you can change the post before importing it.
|
||||
|
||||
### The background script
|
||||
|
||||
This script handles the uploading of a post. It will also update a tag's category in your szurubooru instance when it differs from what is imported.
|
||||
|
||||
## F.A.Q
|
||||
|
||||
### How to use a newer neo-scraper version?
|
||||
|
||||
Running the below command will pull the latest neo-scraper version from github.
|
||||
|
||||
```sh
|
||||
yarn upgrade neo-scraper
|
||||
```
|
||||
|
||||
### Why send the DOM to the ILoader instead of just a URL?
|
||||
|
||||
If we send a URL to the ILoader it has to download the page again itself, which can go wrong in a dozen ways:
|
||||
|
||||
1. The website might be offline now
|
||||
2. If the website is an SPA it might not see the same version/content as you did
|
||||
3. If you made changes to the DOM but didn't submit them to the server (e.g. edit post page) the ILoader would see a different page (kinda the same as point 2)
|
||||
4. If any form of authentication (username+password/client certificate/etc.) is involved it gets tricky
|
||||
5. We already have the DOM, why download it again?
|
||||
|
|
@ -28,9 +28,13 @@
|
|||
"dependencies": {
|
||||
"axios": "^1.2.2",
|
||||
"basscss": "^8.1.0",
|
||||
"lodash": "^4.17.21",
|
||||
"markdown-it": "^13.0.1",
|
||||
"neo-scraper": "^0.5.8",
|
||||
"normalize.css": "^8.0.1"
|
||||
"normalize.css": "^8.0.1",
|
||||
"pinia": "^2.0.36",
|
||||
"pinia-plugin-persistedstate": "^3.1.0",
|
||||
"vue-router": "4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ffflorian/jszip-cli": "^3.1.6",
|
||||
|
|
@ -38,6 +42,7 @@
|
|||
"@fortawesome/free-solid-svg-icons": "^6.2.1",
|
||||
"@fortawesome/vue-fontawesome": "^3.0.3",
|
||||
"@types/fs-extra": "^9.0.13",
|
||||
"@types/lodash": "^4.14.194",
|
||||
"@types/markdown-it": "^12.2.3",
|
||||
"@types/node": "^18.11.9",
|
||||
"@types/webextension-polyfill": "^0.9.1",
|
||||
|
|
|
|||
2206
pnpm-lock.yaml
2206
pnpm-lock.yaml
File diff suppressed because it is too large
Load Diff
|
|
@ -1,4 +1,5 @@
|
|||
import axios, { AxiosRequestConfig, CancelToken } from "axios";
|
||||
import { isEqual } from "lodash";
|
||||
import {
|
||||
TagsResult,
|
||||
TagCategoriesResult,
|
||||
|
|
@ -8,6 +9,7 @@ import {
|
|||
ImageSearchResult,
|
||||
TagFields,
|
||||
TemporaryFileUploadResult,
|
||||
UpdatePostRequest,
|
||||
} from "./models";
|
||||
import { ScrapedPostDetails } from "~/models";
|
||||
import { SzuruSiteConfig } from "~/config";
|
||||
|
|
@ -45,10 +47,18 @@ export default class SzurubooruApi {
|
|||
return (await this.apiGet("info")).data;
|
||||
}
|
||||
|
||||
async getPost(id: number): Promise<Post> {
|
||||
return (await this.apiGet("post/" + id)).data;
|
||||
}
|
||||
|
||||
async updateTag(tag: Tag): Promise<any> {
|
||||
return (await this.apiPut("tag/" + encodeURIComponent(tag.names[0]), tag)).data;
|
||||
}
|
||||
|
||||
async updatePost(id: number, updateRequest: UpdatePostRequest): Promise<Post> {
|
||||
return (await this.apiPut("post/" + id, updateRequest)).data;
|
||||
}
|
||||
|
||||
async getTags(
|
||||
query: string,
|
||||
offset = 0,
|
||||
|
|
@ -109,6 +119,31 @@ export default class SzurubooruApi {
|
|||
return new SzurubooruApi(siteConfig.domain, siteConfig.username, siteConfig.authToken);
|
||||
}
|
||||
|
||||
static createUpdatePostRequest(orig: Post, newPost: Post /*, anonymous = false*/) {
|
||||
const detail = <UpdatePostRequest>{ version: newPost.version };
|
||||
|
||||
// Send only changed fields to avoid user privilege violation
|
||||
// if (anonymous === true) {
|
||||
// detail.anonymous = true;
|
||||
// }
|
||||
|
||||
if (orig.safety != newPost.safety) {
|
||||
detail.safety = newPost.safety;
|
||||
}
|
||||
|
||||
if (orig.source != newPost.source) {
|
||||
detail.source = newPost.source;
|
||||
}
|
||||
|
||||
const oldTags = orig.tags.map((x) => x.names[0]);
|
||||
const newTags = newPost.tags.map((x) => x.names[0]);
|
||||
if (isEqual(oldTags, newTags) == false) {
|
||||
detail.tags = newTags;
|
||||
}
|
||||
|
||||
return detail;
|
||||
}
|
||||
|
||||
private async apiGet(url: string, additionalHeaders: any = {}, cancelToken?: CancelToken): Promise<any> {
|
||||
const fullUrl = this.apiUrl + url;
|
||||
const config: AxiosRequestConfig = {
|
||||
|
|
@ -149,7 +184,6 @@ export default class SzurubooruApi {
|
|||
if (this.username && this.authToken) {
|
||||
const token = "Token " + btoa(`${this.username}:${this.authToken}`);
|
||||
if (!config.headers) config.headers = {};
|
||||
// @ts-expect-error xxx
|
||||
config.headers["Authorization"] = token;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -68,7 +68,7 @@ export interface Post {
|
|||
creationTime: Date;
|
||||
lastEditTime?: Date;
|
||||
safety: Safety;
|
||||
source: string;
|
||||
source: string | null;
|
||||
type: string;
|
||||
mimeType: string;
|
||||
checksum: string;
|
||||
|
|
@ -115,3 +115,15 @@ export interface ImageSearchResult {
|
|||
export interface TemporaryFileUploadResult {
|
||||
token: string;
|
||||
}
|
||||
|
||||
export interface UpdatePostRequest {
|
||||
version: number;
|
||||
tags: string[] | undefined;
|
||||
safety: Safety | undefined;
|
||||
source: string | undefined | null;
|
||||
// relations: string[];
|
||||
// notes: string[],
|
||||
// flags: string[];
|
||||
contentUrl: string | undefined;
|
||||
contentToken: string | undefined;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,14 @@
|
|||
import { encodeTagName, getErrorMessage } from "~/utils";
|
||||
import { BrowserCommand, PostUploadCommandData, PostUploadInfo, SetPostUploadInfoData, SetExactPostId } from "~/models";
|
||||
import {
|
||||
BrowserCommand,
|
||||
PostUploadCommandData,
|
||||
PostUploadInfo,
|
||||
SetPostUploadInfoData,
|
||||
SetExactPostId,
|
||||
PostUpdateCommandData,
|
||||
} from "~/models";
|
||||
import { PostAlreadyUploadedError } from "~/api/models";
|
||||
import SzurubooruApi from "~/api";
|
||||
import { Config } from "~/config";
|
||||
|
||||
// Only on dev mode
|
||||
if (import.meta.hot) {
|
||||
|
|
@ -13,40 +19,27 @@ if (import.meta.hot) {
|
|||
}
|
||||
|
||||
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
|
||||
const pushInfo = () =>
|
||||
browser.runtime.sendMessage(
|
||||
new BrowserCommand("set_post_upload_info", new SetPostUploadInfoData(data.siteId, data.post.id, info))
|
||||
new BrowserCommand("set_post_upload_info", new SetPostUploadInfoData(data.selectedSite.id, data.post.id, info))
|
||||
);
|
||||
|
||||
const contentToken = data.post.instanceSpecificData[data.siteId]?.contentToken;
|
||||
try {
|
||||
const szuru = SzurubooruApi.createFromConfig(data.selectedSite);
|
||||
|
||||
// Create and upload post
|
||||
pushInfo();
|
||||
|
||||
const contentToken = data.post.instanceSpecificData[data.selectedSite.id]?.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))
|
||||
);
|
||||
pushInfo();
|
||||
|
||||
// Find tags with "default" category and update it
|
||||
// TODO: Make all these categories configurable
|
||||
|
|
@ -59,9 +52,7 @@ async function uploadPost(data: PostUploadCommandData) {
|
|||
info.updateTagsState = {
|
||||
total: unsetCategoryTags.length,
|
||||
};
|
||||
browser.runtime.sendMessage(
|
||||
new BrowserCommand("set_post_upload_info", new SetPostUploadInfoData(data.siteId, data.post.id, info))
|
||||
);
|
||||
pushInfo();
|
||||
|
||||
// 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();
|
||||
|
|
@ -71,9 +62,7 @@ async function uploadPost(data: PostUploadCommandData) {
|
|||
|
||||
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))
|
||||
);
|
||||
pushInfo();
|
||||
|
||||
const wantedCategory = tagsWithCategory.find((x) => tags[i].names.includes(x.name))?.category;
|
||||
if (wantedCategory) {
|
||||
|
|
@ -91,30 +80,52 @@ async function uploadPost(data: PostUploadCommandData) {
|
|||
|
||||
if (categoriesChangedCount > 0) {
|
||||
info.updateTagsState.totalChanged = categoriesChangedCount;
|
||||
browser.runtime.sendMessage(
|
||||
new BrowserCommand("set_post_upload_info", new SetPostUploadInfoData(data.siteId, data.post.id, info))
|
||||
);
|
||||
pushInfo();
|
||||
}
|
||||
}
|
||||
} 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))
|
||||
new BrowserCommand("set_exact_post_id", new SetExactPostId(data.selectedSite.id, data.post.id, otherPostId))
|
||||
);
|
||||
// We don't set an error message, because we have a different message for posts that are already uploaded.
|
||||
} else {
|
||||
// Set generic error message.
|
||||
info.error = getErrorMessage(ex);
|
||||
}
|
||||
info.state = "error";
|
||||
pushInfo();
|
||||
}
|
||||
}
|
||||
|
||||
async function updatePost(data: PostUpdateCommandData) {
|
||||
const info: PostUploadInfo = {
|
||||
state: "uploading",
|
||||
instancePostId: data.postId,
|
||||
};
|
||||
|
||||
const pushInfo = () =>
|
||||
browser.runtime.sendMessage(
|
||||
new BrowserCommand(
|
||||
"set_post_update_info",
|
||||
new SetPostUploadInfoData(data.selectedSite.id, `merge-${data.postId}`, info)
|
||||
)
|
||||
);
|
||||
|
||||
// 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 {
|
||||
try {
|
||||
const szuru = SzurubooruApi.createFromConfig(data.selectedSite);
|
||||
|
||||
pushInfo();
|
||||
|
||||
await szuru.updatePost(data.postId, data.updateRequest);
|
||||
|
||||
info.state = "uploaded";
|
||||
pushInfo();
|
||||
} catch (ex: any) {
|
||||
info.state = "error";
|
||||
info.error = getErrorMessage(ex);
|
||||
browser.runtime.sendMessage(
|
||||
new BrowserCommand("set_post_upload_info", new SetPostUploadInfoData(data.siteId, data.post.id, info))
|
||||
);
|
||||
}
|
||||
pushInfo();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -125,6 +136,8 @@ async function messageHandler(cmd: BrowserCommand): Promise<any> {
|
|||
switch (cmd.name) {
|
||||
case "upload_post":
|
||||
return uploadPost(cmd.data);
|
||||
case "update_post":
|
||||
return updatePost(cmd.data);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,30 @@
|
|||
<script setup lang="ts">
|
||||
import type { PropType } from "vue";
|
||||
import type { TagDetails } from "~/models";
|
||||
import { getTagClasses, breakTagName } from "~/utils";
|
||||
|
||||
defineProps({
|
||||
tags: Array as PropType<TagDetails[]>,
|
||||
showUsages: Boolean,
|
||||
showRemoveTag: Boolean,
|
||||
});
|
||||
defineEmits(["removeTag"]);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ul class="compact-tags">
|
||||
<li v-for="tag in tags" :key="tag.name">
|
||||
<a v-if="showRemoveTag" class="remove-tag" @click="$emit('removeTag', tag)">x</a>
|
||||
<span :class="getTagClasses(tag)" v-html="breakTagName(tag.name)"></span>
|
||||
<span v-if="showUsages" class="tag-usages tag-usages-reserve-space">{{ tag.usages ? tag.usages : "" }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
</template>
|
||||
|
||||
<style scoped lang="scss">
|
||||
/* Hacky way to stop the layout from resizing when we lazy load the usage count. */
|
||||
.tag-usages-reserve-space {
|
||||
min-width: 5ch; /* 5 character width */
|
||||
display: inline-block;
|
||||
}
|
||||
</style>
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
<script setup lang="ts">
|
||||
const props = defineProps({
|
||||
modelValue: {
|
||||
type: Boolean,
|
||||
default: true,
|
||||
},
|
||||
toggleable: {
|
||||
type: Boolean,
|
||||
},
|
||||
header: {
|
||||
type: String,
|
||||
},
|
||||
});
|
||||
defineEmits(["update:modelValue"]);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="popup-section">
|
||||
<div
|
||||
class="section-header"
|
||||
:class="{
|
||||
toggleable: props.toggleable,
|
||||
}"
|
||||
@click="$emit('update:modelValue', !props.modelValue)"
|
||||
>
|
||||
<slot name="header">
|
||||
<span>{{ props.header }}</span>
|
||||
<template v-if="props.toggleable">
|
||||
<font-awesome-icon v-show="props.modelValue" icon="fa-solid fa-chevron-up" class="cursor-pointer" />
|
||||
<font-awesome-icon v-show="!props.modelValue" icon="fa-solid fa-chevron-down" class="cursor-pointer" />
|
||||
</template>
|
||||
</slot>
|
||||
</div>
|
||||
|
||||
<slot v-if="props.modelValue"></slot>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style lang="scss" scoped></style>
|
||||
|
|
@ -0,0 +1,51 @@
|
|||
<script setup lang="ts">
|
||||
defineProps({
|
||||
contentUrl: String,
|
||||
notes: {
|
||||
type: Array,
|
||||
default: () => [],
|
||||
},
|
||||
contentType: String,
|
||||
});
|
||||
|
||||
const emit = defineEmits(["onResolutionLoaded"]);
|
||||
|
||||
const imgEl = ref<HTMLImageElement | undefined>(undefined);
|
||||
|
||||
// Get image width and height from the <img> element.
|
||||
// This works because we load the full-resolution image in the <img> element.
|
||||
// This code might stop showing correct resolutions if/when we implement a progressive image loading.
|
||||
function onloadImage() {
|
||||
// I guess post/selectedPost could have a race condition here?
|
||||
// Seems very unlikely though, as the load event gets cancelled as soon as we change the :src attribute.
|
||||
// A race condition might even be impossible then.
|
||||
if (imgEl.value) {
|
||||
emit("onResolutionLoaded", [imgEl.value.naturalWidth, imgEl.value.naturalHeight]);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="post-container">
|
||||
<img v-if="contentType == 'image'" ref="imgEl" :src="contentUrl" @load="onloadImage" />
|
||||
<video v-if="contentType == 'video'" controls>
|
||||
<source :src="contentUrl" />
|
||||
</video>
|
||||
<div class="post-overlay">
|
||||
<PostNotes :notes="notes" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.post-overlay {
|
||||
position: absolute;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.post-container {
|
||||
position: relative;
|
||||
display: flex;
|
||||
}
|
||||
</style>
|
||||
|
|
@ -0,0 +1,167 @@
|
|||
<script setup lang="ts">
|
||||
import axios, { CancelTokenSource } from "axios";
|
||||
import { PropType } from "vue";
|
||||
import SzurubooruApi from "~/api";
|
||||
import { TagDetails } from "~/models";
|
||||
import { encodeTagName, getTagClasses } from "~/utils";
|
||||
|
||||
const addTagInput = ref("");
|
||||
const autocompleteShown = ref(false);
|
||||
const autocompleteTags = ref<TagDetails[]>([]);
|
||||
const cancelSource = ref<CancelTokenSource | undefined>(undefined);
|
||||
const autocompleteIndex = ref(-1);
|
||||
|
||||
const props = defineProps({
|
||||
szuru: Object as PropType<SzurubooruApi>,
|
||||
});
|
||||
const emit = defineEmits(["addTag"]);
|
||||
|
||||
function addTag(tag: TagDetails) {
|
||||
emit("addTag", tag);
|
||||
}
|
||||
|
||||
async function onAddTagKeyUp(e: KeyboardEvent) {
|
||||
await autocompletePopulator((<HTMLInputElement>e.target).value);
|
||||
}
|
||||
|
||||
function addTagFromCurrentInput() {
|
||||
addTag(new TagDetails([addTagInput.value]));
|
||||
addTagInput.value = ""; // Reset input
|
||||
|
||||
// Only needed when the button is clicked
|
||||
// When this is triggered by the enter key the `onAddTagKeyUp` will internally also hide the autocomplete.
|
||||
// Though hiding it twice doesn't hurt so we don't care.
|
||||
hideAutocomplete();
|
||||
|
||||
// TODO: Do we also want to add the implications?
|
||||
// Answer: Probably not, because if the user wanted to have implications they should've clicked/selected the autocomplete entry.
|
||||
}
|
||||
|
||||
function onAddTagKeyDown(e: KeyboardEvent) {
|
||||
if (e.code == "ArrowDown") {
|
||||
e.preventDefault();
|
||||
if (autocompleteIndex.value < autocompleteTags.value.length - 1) {
|
||||
autocompleteIndex.value++;
|
||||
}
|
||||
} else if (e.code == "ArrowUp") {
|
||||
e.preventDefault();
|
||||
if (autocompleteIndex.value >= 0) {
|
||||
autocompleteIndex.value--;
|
||||
}
|
||||
} else if (e.code == "Enter") {
|
||||
if (autocompleteIndex.value == -1) {
|
||||
addTagFromCurrentInput();
|
||||
} else {
|
||||
// Add auto completed tag
|
||||
const tagToAdd = autocompleteTags.value[autocompleteIndex.value];
|
||||
addTag(tagToAdd);
|
||||
addTagInput.value = ""; // Reset input
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function onClickAutocompleteTagItem(tag: TagDetails) {
|
||||
addTag(tag);
|
||||
addTagInput.value = ""; // Reset input
|
||||
autocompleteShown.value = false; // Hide autocomplete list
|
||||
}
|
||||
|
||||
function hideAutocomplete() {
|
||||
autocompleteIndex.value = -1;
|
||||
autocompleteShown.value = false;
|
||||
}
|
||||
|
||||
async function autocompletePopulator(input: string) {
|
||||
// Based on https://www.w3schools.com/howto/howto_js_autocomplete.asp
|
||||
|
||||
// Hide autocomplete when the input is empty, and don't do anything else.
|
||||
if (input.length == 0) {
|
||||
hideAutocomplete();
|
||||
return;
|
||||
}
|
||||
|
||||
// Cancel previous request
|
||||
if (cancelSource.value) {
|
||||
cancelSource.value.cancel();
|
||||
}
|
||||
cancelSource.value = axios.CancelToken.source();
|
||||
|
||||
const query = decodeURIComponent(`*${encodeTagName(input)}* sort:usages`);
|
||||
const res = await props.szuru?.getTags(
|
||||
query,
|
||||
0,
|
||||
100,
|
||||
["names", "category", "usages", "implications"],
|
||||
cancelSource.value.token
|
||||
);
|
||||
|
||||
if (res) {
|
||||
// TODO: Maybe search on hamming distance or something?
|
||||
autocompleteTags.value = res.results.map((x) => TagDetails.fromTag(x));
|
||||
if (autocompleteTags.value.length > 0) autocompleteShown.value = true;
|
||||
} else {
|
||||
autocompleteTags.value = [];
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div style="display: flex; flex-direction: column">
|
||||
<div style="display: flex">
|
||||
<input type="text" v-model="addTagInput" @keyup="onAddTagKeyUp" @keydown="onAddTagKeyDown" autocomplete="off" />
|
||||
<button class="primary" style="margin-left: 5px" @click="addTagFromCurrentInput">Add</button>
|
||||
</div>
|
||||
|
||||
<div class="autocomplete-items" v-bind:class="{ show: autocompleteShown }">
|
||||
<div
|
||||
v-for="(tag, idx) in autocompleteTags"
|
||||
@click="onClickAutocompleteTagItem(tag)"
|
||||
:key="tag.name"
|
||||
:class="{
|
||||
active: idx == autocompleteIndex,
|
||||
}"
|
||||
>
|
||||
<span :class="getTagClasses(tag)">{{ tag.name }}</span>
|
||||
<span class="tag-usages">{{ tag.usages ? tag.usages : "" }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.autocomplete-items {
|
||||
position: absolute;
|
||||
z-index: 10;
|
||||
background-color: var(--bg-main-color);
|
||||
border: 2px solid var(--primary-color);
|
||||
margin-top: 34px;
|
||||
display: none;
|
||||
|
||||
&.show {
|
||||
display: block;
|
||||
}
|
||||
|
||||
> div {
|
||||
cursor: pointer;
|
||||
padding: 2px 4px;
|
||||
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5em;
|
||||
|
||||
&:hover {
|
||||
background: var(--primary-color);
|
||||
> span {
|
||||
color: var(--text-color);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
> div.active {
|
||||
background: var(--primary-color);
|
||||
> span {
|
||||
color: var(--text-color);
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
|
@ -4,36 +4,3 @@ export class SzuruSiteConfig {
|
|||
username = "user";
|
||||
authToken = "";
|
||||
}
|
||||
|
||||
export class Config {
|
||||
importExistingTags = true;
|
||||
importAllTags = false;
|
||||
importCommentary = false;
|
||||
addPageUrlToSource = true;
|
||||
autoSearchSimilar = false;
|
||||
loadTagCounts = true;
|
||||
useContentTokens = true;
|
||||
sites: Array<SzuruSiteConfig> = [];
|
||||
selectedSiteId?: string;
|
||||
|
||||
public async save() {
|
||||
await browser.storage.local.set({
|
||||
config: JSON.stringify(this),
|
||||
});
|
||||
|
||||
console.dir("Save " + JSON.stringify(this));
|
||||
console.log("Saved config");
|
||||
}
|
||||
|
||||
static async load(): Promise<Config> {
|
||||
const storage = await browser.storage.local.get("config");
|
||||
let config: Config = new Config();
|
||||
|
||||
if ("config" in storage) {
|
||||
config = Object.assign(config, JSON.parse(storage["config"]));
|
||||
}
|
||||
|
||||
console.dir("Load " + JSON.stringify(config));
|
||||
return config;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,9 +1,22 @@
|
|||
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";
|
||||
import { faCog, faChevronDown, faChevronUp, faChevronLeft } from "@fortawesome/free-solid-svg-icons";
|
||||
import { createPinia } from "pinia";
|
||||
import piniaPluginPersistedstate from "pinia-plugin-persistedstate";
|
||||
|
||||
export function setupPinia(app: App) {
|
||||
const pinia = createPinia();
|
||||
pinia.use(piniaPluginPersistedstate);
|
||||
app.use(pinia);
|
||||
}
|
||||
|
||||
export function setupApp(app: App) {
|
||||
setupPinia(app);
|
||||
|
||||
library.add(faCog);
|
||||
library.add(faChevronDown);
|
||||
library.add(faChevronUp);
|
||||
library.add(faChevronLeft);
|
||||
app.component("font-awesome-icon", FontAwesomeIcon);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,13 +1,18 @@
|
|||
import { BooruTypes, ContentType, ScrapedNote, ScrapedPost, ScrapedTag } from "neo-scraper";
|
||||
import { MicroTag, Tag } from "~/api/models";
|
||||
import { MicroTag, Tag, UpdatePostRequest } from "~/api/models";
|
||||
import { SzuruSiteConfig } from "~/config";
|
||||
|
||||
export class TagDetails {
|
||||
public implications: TagDetails[] = [];
|
||||
|
||||
constructor(public name: string, public category?: string, public usages?: number) {}
|
||||
constructor(public names: string[], public category?: string, public usages?: number) {}
|
||||
|
||||
get name() {
|
||||
return this.names[0];
|
||||
}
|
||||
|
||||
static fromTag(tag: Tag) {
|
||||
const x = new TagDetails(tag.names[0], tag.category, tag.usages);
|
||||
const x = new TagDetails(tag.names, tag.category, tag.usages);
|
||||
|
||||
if (tag.implications) {
|
||||
x.implications = tag.implications.map((y) => TagDetails.fromMicroTag(y));
|
||||
|
|
@ -17,11 +22,11 @@ export class TagDetails {
|
|||
}
|
||||
|
||||
static fromMicroTag(tag: MicroTag) {
|
||||
return new TagDetails(tag.names[0], tag.category, tag.usages);
|
||||
return new TagDetails(tag.names, tag.category, tag.usages);
|
||||
}
|
||||
|
||||
static fromScapedTag(tag: ScrapedTag): TagDetails {
|
||||
return new TagDetails(tag.name, tag.category);
|
||||
return new TagDetails([tag.name], tag.category);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -90,7 +95,13 @@ export class PostUploadInfo {
|
|||
};
|
||||
}
|
||||
|
||||
export type BrowserCommandName = "grab_post" | "upload_post" | "set_post_upload_info" | "set_exact_post_id";
|
||||
export type BrowserCommandName =
|
||||
| "grab_post"
|
||||
| "upload_post"
|
||||
| "set_post_upload_info"
|
||||
| "set_exact_post_id"
|
||||
| "update_post"
|
||||
| "set_post_update_info";
|
||||
|
||||
export class BrowserCommand<T = any> {
|
||||
name: BrowserCommandName;
|
||||
|
|
@ -103,14 +114,14 @@ export class BrowserCommand<T = any> {
|
|||
}
|
||||
|
||||
export class PostUploadCommandData {
|
||||
constructor(public readonly post: ScrapedPostDetails, public readonly siteId: string) {}
|
||||
constructor(public readonly post: ScrapedPostDetails, public readonly selectedSite: SzuruSiteConfig) {}
|
||||
}
|
||||
|
||||
export class SetPostUploadInfoData {
|
||||
constructor(
|
||||
public readonly instanceId: string,
|
||||
public readonly postId: string,
|
||||
public readonly info: PostUploadInfo
|
||||
public instanceId: string,
|
||||
public postId: string,
|
||||
public info: PostUploadInfo
|
||||
) {}
|
||||
}
|
||||
|
||||
|
|
@ -121,3 +132,7 @@ export class SetExactPostId {
|
|||
public readonly exactPostId: number
|
||||
) {}
|
||||
}
|
||||
|
||||
export class PostUpdateCommandData {
|
||||
constructor(public readonly postId: number, public readonly updateRequest: UpdatePostRequest, public readonly selectedSite: SzuruSiteConfig) {}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,15 +1,15 @@
|
|||
<script setup lang="ts">
|
||||
import { useColorMode } from "@vueuse/core";
|
||||
import SzuruWrapper from "~/api";
|
||||
import { Config, SzuruSiteConfig } from "~/config";
|
||||
import { SzuruSiteConfig } from "~/config";
|
||||
import { useConfigStore } from "~/stores";
|
||||
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 statusType = ref("status-quiet");
|
||||
let sites = reactive<SzuruSiteConfig[]>([]);
|
||||
let selectedSiteId = ref<string | undefined>(undefined);
|
||||
const selectedSite = computed(() => {
|
||||
|
|
@ -18,7 +18,9 @@ const selectedSite = computed(() => {
|
|||
}
|
||||
});
|
||||
|
||||
type StatusType = "success" | "error";
|
||||
const configStore = useConfigStore();
|
||||
|
||||
type StatusType = "success" | "error" | "quiet";
|
||||
|
||||
async function testConnection() {
|
||||
if (
|
||||
|
|
@ -47,16 +49,11 @@ async function testConnection() {
|
|||
}
|
||||
|
||||
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();
|
||||
configStore.sites = sites;
|
||||
configStore.autoSearchSimilar = autoSearchSimilar.value;
|
||||
configStore.loadTagCounts = loadTagCounts.value;
|
||||
configStore.addPageUrlToSource = addPageUrlToSource.value;
|
||||
configStore.selectedSiteId = selectedSiteId.value;
|
||||
|
||||
setStatus("Settings successfully saved");
|
||||
}
|
||||
|
|
@ -80,24 +77,17 @@ function removeSelectedSite() {
|
|||
}
|
||||
|
||||
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();
|
||||
}
|
||||
statusText.value = "Version " + browser.runtime.getManifest().version;
|
||||
|
||||
for (let site of configStore.sites) {
|
||||
// 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;
|
||||
autoSearchSimilar.value = configStore.autoSearchSimilar;
|
||||
loadTagCounts.value = configStore.loadTagCounts;
|
||||
addPageUrlToSource.value = configStore.addPageUrlToSource;
|
||||
selectedSiteId.value = configStore.selectedSiteId;
|
||||
});
|
||||
|
||||
let mode = useColorMode({ emitAuto: true });
|
||||
|
|
@ -210,7 +200,7 @@ let mode = useColorMode({ emitAuto: true });
|
|||
</template>
|
||||
|
||||
<style lang="scss">
|
||||
@use "../styles/main.scss";
|
||||
@use "~/styles/main.scss";
|
||||
|
||||
.content-holder {
|
||||
padding: 1.5em;
|
||||
|
|
@ -250,6 +240,10 @@ html.dark .content-wrapper {
|
|||
line-height: 120%;
|
||||
}
|
||||
|
||||
.status {
|
||||
align-self: center;
|
||||
}
|
||||
|
||||
.status-error {
|
||||
color: red;
|
||||
}
|
||||
|
|
@ -258,6 +252,10 @@ html.dark .content-wrapper {
|
|||
color: green;
|
||||
}
|
||||
|
||||
.status-quiet {
|
||||
opacity: 0.6;
|
||||
}
|
||||
|
||||
label {
|
||||
display: block;
|
||||
padding: 0.3em 0;
|
||||
|
|
|
|||
|
|
@ -1,407 +1,14 @@
|
|||
<script setup lang="ts">
|
||||
import { useDark } from "@vueuse/core";
|
||||
import axios, { CancelTokenSource } from "axios";
|
||||
import { ScrapeResults } from "neo-scraper";
|
||||
import { getUrl, encodeTagName, getErrorMessage } from "~/utils";
|
||||
import {
|
||||
BrowserCommand,
|
||||
ScrapedPostDetails,
|
||||
TagDetails,
|
||||
PostUploadCommandData,
|
||||
SimilarPostInfo,
|
||||
SetPostUploadInfoData,
|
||||
SetExactPostId,
|
||||
SimpleSimilarPost,
|
||||
SimpleImageSearchResult,
|
||||
} from "~/models";
|
||||
import SzuruWrapper from "~/api";
|
||||
import { ImageSearchResult } from "~/api/models";
|
||||
import { isChrome, isMobile } from "~/env";
|
||||
<script lang="ts" setup>
|
||||
import { onMounted } from "vue";
|
||||
import { isChrome } from "~/env";
|
||||
import { BrowserCommand, SetPostUploadInfoData, SetExactPostId } from "~/models";
|
||||
import { Runtime, WebRequest } from "webextension-polyfill";
|
||||
import { Config } from "~/config";
|
||||
import { DeepReadonly } from "vue";
|
||||
import { useMergeStore, usePopupStore } from "~/stores";
|
||||
|
||||
let config = new Config();
|
||||
let posts = reactive([] as ScrapedPostDetails[]);
|
||||
let selectedPostId = ref<string | undefined>(undefined);
|
||||
let addTagInput = ref("");
|
||||
let autocompleteShown = ref(false);
|
||||
let autocompleteTags = ref<TagDetails[]>([]);
|
||||
let cancelSource = ref<CancelTokenSource | undefined>(undefined);
|
||||
let autocompleteIndex = ref(-1);
|
||||
let selectedSiteId = ref<string | undefined>(undefined);
|
||||
let isSearchingForSimilarPosts = ref<number>(0);
|
||||
let imgEl = ref<HTMLImageElement | null>(null);
|
||||
|
||||
const selectedInstance = computed(() => {
|
||||
if (selectedSiteId.value) {
|
||||
return config.sites.find((x) => x.id == selectedSiteId.value);
|
||||
}
|
||||
});
|
||||
|
||||
const selectedPost = computed(() => {
|
||||
if (selectedPostId.value) {
|
||||
return posts.find((x) => x.id == selectedPostId.value);
|
||||
}
|
||||
});
|
||||
|
||||
const szuru = computed(() => {
|
||||
return selectedInstance.value ? SzuruWrapper.createFromConfig(selectedInstance.value) : undefined;
|
||||
});
|
||||
|
||||
// (Reactive) shorthand for `selectedPost.value.instanceSpecificData.get(selectedSiteId.value)`.
|
||||
// This should only be used as if it were readonly, because the instanceId might change.
|
||||
const instanceSpecificData = readonly(
|
||||
computed(() => {
|
||||
if (selectedPost.value && selectedSiteId.value) {
|
||||
return selectedPost.value.instanceSpecificData[selectedSiteId.value];
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
watch(selectedPostId, () => {
|
||||
// Call findSimilar if wanted.
|
||||
if (config.autoSearchSimilar) {
|
||||
let selectedPost = posts.find((x) => x.id == selectedPostId.value);
|
||||
if (selectedPost) findSimilar(selectedPost);
|
||||
}
|
||||
});
|
||||
|
||||
watch(selectedSiteId, async (x) => {
|
||||
// If changed
|
||||
if (config.selectedSiteId != x) {
|
||||
// Update selectedSiteId in config
|
||||
config.selectedSiteId = x;
|
||||
await config.save();
|
||||
|
||||
// Call findSimilar if wanted.
|
||||
if (config.autoSearchSimilar && selectedPost.value) {
|
||||
findSimilar(selectedPost.value);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
function openOptionsPage() {
|
||||
browser.runtime.openOptionsPage();
|
||||
}
|
||||
|
||||
async function getActiveTabId(): Promise<number> {
|
||||
const activeTabs = await browser.tabs.query({
|
||||
active: true,
|
||||
currentWindow: true,
|
||||
});
|
||||
|
||||
if (activeTabs.length > 0 && activeTabs[0].id) return activeTabs[0].id;
|
||||
throw new Error("No active tab.");
|
||||
}
|
||||
|
||||
async function grabPost() {
|
||||
// Get active tab
|
||||
const activeTabId = await getActiveTabId();
|
||||
|
||||
// Send 'grab_post' to the content script on the active tab
|
||||
const x = await browser.tabs.sendMessage(activeTabId, new BrowserCommand("grab_post"));
|
||||
// We need to create a new ScrapeResults object and fill it with our data, because the get_posts()
|
||||
// method gets 'lost' when sent from the contentscript to the popup (it gets JSON.stringified and any prototype defines are lost there)
|
||||
const res = Object.assign(new ScrapeResults(), x);
|
||||
|
||||
console.dir(res);
|
||||
|
||||
// Clear current posts array
|
||||
posts.splice(0);
|
||||
|
||||
for (const result of res.results) {
|
||||
for (const i in result.posts) {
|
||||
const vm = new ScrapedPostDetails(result.posts[i]);
|
||||
vm.name = `[${result.engine}] Post ${parseInt(i) + 1}`; // parseInt() is required!
|
||||
|
||||
// Add current pageUrl to the source if either
|
||||
// a. user has addPageUrlToSource set to true
|
||||
// b. source is empty
|
||||
if (config?.addPageUrlToSource || vm.source == "") {
|
||||
if (vm.source != "") vm.source += "\n";
|
||||
vm.source += vm.pageUrl;
|
||||
}
|
||||
|
||||
// Initialize instanceSpecificData with an empty object.
|
||||
for (const site of config.sites) {
|
||||
vm.instanceSpecificData[site.id] = {};
|
||||
}
|
||||
|
||||
posts.push(vm);
|
||||
}
|
||||
}
|
||||
|
||||
if (posts.length > 0) {
|
||||
selectedPostId.value = posts[0].id;
|
||||
if (config?.loadTagCounts) {
|
||||
loadTagCounts();
|
||||
}
|
||||
} else {
|
||||
// pushInfo("No posts found.");
|
||||
}
|
||||
}
|
||||
|
||||
async function upload() {
|
||||
if (!selectedSiteId.value) return;
|
||||
|
||||
// Don't try to upload if an exact copy is already on the server.
|
||||
if (instanceSpecificData.value?.reverseSearchResult?.exactPostId) return;
|
||||
|
||||
// TODO: Terrible code.
|
||||
const post = JSON.parse(JSON.stringify(selectedPost.value));
|
||||
const cmdData = new PostUploadCommandData(post, selectedSiteId.value);
|
||||
const cmd = new BrowserCommand("upload_post", cmdData);
|
||||
await browser.runtime.sendMessage(cmd);
|
||||
// TODO: Handle errors/status update
|
||||
}
|
||||
|
||||
function getTagClasses(tag: TagDetails): string[] {
|
||||
let classes: string[] = [];
|
||||
|
||||
if (tag.category && tag.category != "default") {
|
||||
classes.push("tag-" + tag.category);
|
||||
} else {
|
||||
classes.push("tag-general");
|
||||
}
|
||||
|
||||
return classes;
|
||||
}
|
||||
|
||||
function breakTagName(tagName: string) {
|
||||
// Based on https://stackoverflow.com/a/6316913
|
||||
return tagName.replace(/_/g, "_<wbr>");
|
||||
}
|
||||
|
||||
function resolutionToString(resolution: [number, number]) {
|
||||
if (resolution && resolution.length == 2) {
|
||||
return resolution[0] + "x" + resolution[1];
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
function removeTag(tag: TagDetails) {
|
||||
if (selectedPost.value) {
|
||||
const idx = selectedPost.value.tags.indexOf(tag);
|
||||
if (idx != -1) {
|
||||
selectedPost.value.tags.splice(idx, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function getActiveSitePostUrl(postId: number): string {
|
||||
if (!selectedInstance.value) return "";
|
||||
return getUrl(selectedInstance.value.domain, "post", postId.toString());
|
||||
}
|
||||
|
||||
function getSimilarPosts(data?: DeepReadonly<SimpleImageSearchResult>): SimilarPostInfo[] {
|
||||
if (!data) return [];
|
||||
|
||||
const lst: SimilarPostInfo[] = [];
|
||||
|
||||
for (const similarPost of data.similarPosts) {
|
||||
if (data.exactPostId == similarPost.postId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
lst.push(new SimilarPostInfo(similarPost.postId, Math.round(100 - similarPost.distance * 100)));
|
||||
}
|
||||
|
||||
return lst;
|
||||
}
|
||||
|
||||
function addTag(tag: TagDetails) {
|
||||
if (selectedPost.value) {
|
||||
// Only add tag if it doesn't already exist
|
||||
if (tag.name.length > 0 && selectedPost.value.tags.find((x) => x.name == tag.name) == undefined) {
|
||||
selectedPost.value.tags.push(tag);
|
||||
|
||||
// Add implications for the tag
|
||||
selectedPost.value.tags.push(...tag.implications);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function clickFindSimilar() {
|
||||
let selectedPost = posts.find((x) => x.id == selectedPostId.value);
|
||||
if (selectedPost) return await findSimilar(selectedPost);
|
||||
}
|
||||
|
||||
async function findSimilar(post: ScrapedPostDetails | undefined) {
|
||||
if (!post || !szuru.value || !selectedSiteId.value) return;
|
||||
|
||||
const selectedInstance = szuru.value; // Get current object, and not reactive.
|
||||
let instanceSpecificData = post.instanceSpecificData[selectedSiteId.value];
|
||||
|
||||
if (!instanceSpecificData) {
|
||||
console.error("instanceSpecificData is undefined. This should never happen!");
|
||||
return;
|
||||
}
|
||||
|
||||
// Don't load this again if it is already loaded.
|
||||
if (instanceSpecificData?.reverseSearchResult) return;
|
||||
|
||||
isSearchingForSimilarPosts.value++;
|
||||
|
||||
try {
|
||||
let res: ImageSearchResult | undefined;
|
||||
|
||||
if (config.useContentTokens) {
|
||||
let tmpRes = await selectedInstance.uploadTempFile(post.contentUrl);
|
||||
// TODO: Error handling?
|
||||
// Save contentToken in PostViewModel so that we can reuse it when creating/uploading the post.
|
||||
instanceSpecificData.contentToken = tmpRes.token;
|
||||
|
||||
res = await selectedInstance.reverseSearchToken(tmpRes.token);
|
||||
} else {
|
||||
res = await selectedInstance.reverseSearch(post.contentUrl);
|
||||
}
|
||||
|
||||
instanceSpecificData.reverseSearchResult = {
|
||||
exactPostId: res.exactPost?.id,
|
||||
similarPosts: res.similarPosts.map((x) => <SimpleSimilarPost>{ postId: x.post.id, distance: x.distance }),
|
||||
};
|
||||
} catch (ex: any) {
|
||||
instanceSpecificData.genericError = "Couldn't reverse search. " + getErrorMessage(ex);
|
||||
}
|
||||
|
||||
isSearchingForSimilarPosts.value--;
|
||||
}
|
||||
|
||||
function getPostForUrl(contentUrl: string): ScrapedPostDetails | undefined {
|
||||
return posts.find((x) => x.contentUrl == contentUrl);
|
||||
}
|
||||
|
||||
async function loadTagCounts() {
|
||||
const allTags = posts.flatMap((x) => x.tags);
|
||||
|
||||
for (let i = 0; i < allTags.length; i += 100) {
|
||||
const query = allTags
|
||||
.slice(i, i + 101)
|
||||
.map((x) => encodeTagName(x.name))
|
||||
.join();
|
||||
|
||||
const resp = await szuru.value?.getTags(query);
|
||||
|
||||
// Not the best code, but it works I guess?
|
||||
if (resp) {
|
||||
for (let post of posts)
|
||||
for (let tag of resp.results)
|
||||
for (let postTag of post.tags)
|
||||
if (postTag.name == tag.names[0]) {
|
||||
postTag.usages = tag.usages;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function onAddTagKeyUp(e: KeyboardEvent) {
|
||||
await autocompletePopulator((<HTMLInputElement>e.target).value);
|
||||
}
|
||||
|
||||
function addTagFromCurrentInput() {
|
||||
addTag(new TagDetails(addTagInput.value));
|
||||
addTagInput.value = ""; // Reset input
|
||||
|
||||
// Only needed when the button is clicked
|
||||
// When this is triggered by the enter key the `onAddTagKeyUp` will internally also hide the autocomplete.
|
||||
// Though hiding it twice doesn't hurt so we don't care.
|
||||
hideAutocomplete();
|
||||
|
||||
// TODO: Do we also want to add the implications?
|
||||
// Answer: Probably not, because if the user wanted to have implications they should've clicked/selected the autocomplete entry.
|
||||
}
|
||||
|
||||
function onAddTagKeyDown(e: KeyboardEvent) {
|
||||
if (e.code == "ArrowDown") {
|
||||
e.preventDefault();
|
||||
if (autocompleteIndex.value < autocompleteTags.value.length - 1) {
|
||||
autocompleteIndex.value++;
|
||||
}
|
||||
} else if (e.code == "ArrowUp") {
|
||||
e.preventDefault();
|
||||
if (autocompleteIndex.value >= 0) {
|
||||
autocompleteIndex.value--;
|
||||
}
|
||||
} else if (e.code == "Enter") {
|
||||
if (autocompleteIndex.value == -1) {
|
||||
addTagFromCurrentInput();
|
||||
} else {
|
||||
// Add auto completed tag
|
||||
const tagToAdd = autocompleteTags.value[autocompleteIndex.value];
|
||||
addTag(tagToAdd);
|
||||
addTagInput.value = ""; // Reset input
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function onClickAutocompleteTagItem(tag: TagDetails) {
|
||||
addTag(tag);
|
||||
addTagInput.value = ""; // Reset input
|
||||
autocompleteShown.value = false; // Hide autocomplete list
|
||||
}
|
||||
|
||||
function hideAutocomplete() {
|
||||
autocompleteIndex.value = -1;
|
||||
autocompleteShown.value = false;
|
||||
}
|
||||
|
||||
async function autocompletePopulator(input: string) {
|
||||
// Based on https://www.w3schools.com/howto/howto_js_autocomplete.asp
|
||||
// TODO: Put this in a separate component
|
||||
|
||||
// Hide autocomplete when the input is empty, and don't do anything else.
|
||||
if (input.length == 0) {
|
||||
hideAutocomplete();
|
||||
return;
|
||||
}
|
||||
|
||||
// Cancel previous request
|
||||
if (cancelSource.value) {
|
||||
cancelSource.value.cancel();
|
||||
}
|
||||
cancelSource.value = axios.CancelToken.source();
|
||||
|
||||
const query = decodeURIComponent(`*${encodeTagName(input)}* sort:usages`);
|
||||
const res = await szuru.value?.getTags(
|
||||
query,
|
||||
0,
|
||||
100,
|
||||
["names", "category", "usages", "implications"],
|
||||
cancelSource.value.token
|
||||
);
|
||||
|
||||
if (res) {
|
||||
autocompleteTags.value = res.results.map((x) => TagDetails.fromTag(x));
|
||||
if (autocompleteTags.value.length > 0) autocompleteShown.value = true;
|
||||
} else {
|
||||
autocompleteTags.value = [];
|
||||
}
|
||||
}
|
||||
|
||||
// Could people would use https://kazupon.github.io/vue-i18n/guide/pluralization.html
|
||||
function getUpdatedTagsText(count: number) {
|
||||
return `Updated ${count} tag${count > 1 ? "s" : ""}`;
|
||||
}
|
||||
|
||||
// Get image width and height from the <img> element.
|
||||
// This works because we load the full-resolution image in the <img> element.
|
||||
// This code might stop showing correct resolutions if/when we implement a progressive image loading.
|
||||
function onloadImage(post: ScrapedPostDetails | undefined) {
|
||||
// I guess post/selectedPost could have a race condition here?
|
||||
// Seems very unlikely though, as the load event gets cancelled as soon as we change the :src attribute.
|
||||
// A race condition might even be impossible then.
|
||||
console.log("Setting resolution! " + imgEl.value?.naturalHeight);
|
||||
if (post && !post.resolution && imgEl.value) {
|
||||
post.resolution = [imgEl.value.naturalWidth, imgEl.value.naturalHeight];
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
config = await Config.load();
|
||||
selectedSiteId.value = config.selectedSiteId;
|
||||
const pop = usePopupStore();
|
||||
const merge = useMergeStore();
|
||||
|
||||
onMounted(() => {
|
||||
browser.runtime.onMessage.addListener((cmd: BrowserCommand, _sender: Runtime.MessageSender) => {
|
||||
console.log("Popup received message:");
|
||||
console.dir(cmd);
|
||||
|
|
@ -410,7 +17,7 @@ onMounted(async () => {
|
|||
case "set_post_upload_info":
|
||||
{
|
||||
const { postId, instanceId, info } = <SetPostUploadInfoData>cmd.data;
|
||||
let post = posts.find((x) => x.id == postId);
|
||||
let post = pop.posts.find((x) => x.id == postId);
|
||||
if (post) {
|
||||
let instanceSpecificData = post.instanceSpecificData[instanceId];
|
||||
if (instanceSpecificData) {
|
||||
|
|
@ -422,8 +29,8 @@ onMounted(async () => {
|
|||
case "set_exact_post_id":
|
||||
{
|
||||
const { postId, instanceId, exactPostId } = <SetExactPostId>cmd.data;
|
||||
let post = posts.find((x) => x.id == postId);
|
||||
if (post && selectedPostId.value) {
|
||||
let post = pop.posts.find((x) => x.id == postId);
|
||||
if (post && pop.selectedPostId) {
|
||||
let instanceSpecificData = post.instanceSpecificData[instanceId];
|
||||
if (instanceSpecificData) {
|
||||
if (instanceSpecificData?.reverseSearchResult) {
|
||||
|
|
@ -435,6 +42,17 @@ onMounted(async () => {
|
|||
}
|
||||
}
|
||||
break;
|
||||
case "set_post_update_info":
|
||||
{
|
||||
const data = <SetPostUploadInfoData>cmd.data;
|
||||
let existing = merge.uploadInfo.find((x) => x.instanceId == data.instanceId && x.postId == data.postId);
|
||||
if (existing) {
|
||||
existing.info = data.info;
|
||||
} else {
|
||||
merge.uploadInfo.push(data);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
});
|
||||
|
||||
|
|
@ -452,7 +70,7 @@ onMounted(async () => {
|
|||
let requestHeaders = details.requestHeaders ?? [];
|
||||
|
||||
// Find which ScrapedPost this belongs to, if any.
|
||||
const post = getPostForUrl(details.url);
|
||||
const post = pop.getPostForContentUrl(details.url);
|
||||
if (post != undefined && post.referrer) {
|
||||
console.log(`Setting referrer to '${post.referrer}' for request to '${post.contentUrl}'.`);
|
||||
// TODO: If the headers already have a 'Referer' header this will _not_ override that.
|
||||
|
|
@ -467,376 +85,16 @@ onMounted(async () => {
|
|||
{ urls: ["<all_urls>"] },
|
||||
extraInfoSpec
|
||||
);
|
||||
|
||||
grabPost();
|
||||
});
|
||||
|
||||
useDark();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="popup-container">
|
||||
<div class="popup-messages">
|
||||
<ul class="messages">
|
||||
<!--
|
||||
Error messages
|
||||
-->
|
||||
|
||||
<li v-if="config.sites.length == 0" class="bg-danger">No szurubooru server configured!</li>
|
||||
|
||||
<li v-if="!selectedInstance" class="bg-danger">No target server selected!</li>
|
||||
|
||||
<li v-if="instanceSpecificData?.reverseSearchResult?.exactPostId" class="bg-danger">
|
||||
<a :href="getActiveSitePostUrl(instanceSpecificData.reverseSearchResult?.exactPostId)"
|
||||
>Post already uploaded ({{ instanceSpecificData.reverseSearchResult.exactPostId }})</a
|
||||
>
|
||||
</li>
|
||||
|
||||
<!-- Only show error when it's not undefined and not empty. -->
|
||||
<li v-if="instanceSpecificData?.uploadState?.error?.length" class="bg-danger">
|
||||
Couldn't upload post. {{ instanceSpecificData.uploadState.error }}
|
||||
</li>
|
||||
|
||||
<li v-if="instanceSpecificData?.genericError" class="bg-danger">{{ instanceSpecificData.genericError }}</li>
|
||||
|
||||
<!--
|
||||
Success messages
|
||||
-->
|
||||
|
||||
<!-- TODO: Clicking a link doesn't actually open it in a new tab, see https://stackoverflow.com/questions/8915845 -->
|
||||
<li
|
||||
v-if="
|
||||
instanceSpecificData?.uploadState?.state == 'uploaded' && instanceSpecificData?.uploadState.instancePostId
|
||||
"
|
||||
class="bg-success"
|
||||
>
|
||||
<a :href="getActiveSitePostUrl(instanceSpecificData.uploadState.instancePostId)"
|
||||
>Uploaded post {{ instanceSpecificData.uploadState.instancePostId }}</a
|
||||
>
|
||||
</li>
|
||||
|
||||
<li v-if="instanceSpecificData?.uploadState?.updateTagsState?.totalChanged" class="bg-success">
|
||||
{{ getUpdatedTagsText(instanceSpecificData.uploadState?.updateTagsState?.totalChanged) }}
|
||||
</li>
|
||||
|
||||
<!--
|
||||
Info messages
|
||||
-->
|
||||
|
||||
<li v-if="instanceSpecificData?.uploadState?.state == 'uploading'">Uploading...</li>
|
||||
|
||||
<li
|
||||
v-if="
|
||||
instanceSpecificData?.uploadState?.updateTagsState?.total &&
|
||||
instanceSpecificData.uploadState?.updateTagsState?.current == undefined
|
||||
"
|
||||
>
|
||||
{{ instanceSpecificData.uploadState?.updateTagsState?.total }} tags need a different category
|
||||
</li>
|
||||
|
||||
<li
|
||||
v-if="
|
||||
instanceSpecificData?.uploadState?.updateTagsState?.current &&
|
||||
instanceSpecificData?.uploadState?.updateTagsState?.totalChanged == undefined
|
||||
"
|
||||
>
|
||||
Updating tag {{ instanceSpecificData.uploadState?.updateTagsState?.current }}/{{
|
||||
instanceSpecificData.uploadState?.updateTagsState?.total
|
||||
}}
|
||||
</li>
|
||||
|
||||
<li v-if="isSearchingForSimilarPosts > 0 && instanceSpecificData?.uploadState == undefined">
|
||||
Searching for similar posts...
|
||||
</li>
|
||||
|
||||
<li
|
||||
v-if="
|
||||
instanceSpecificData?.reverseSearchResult?.similarPosts.length == 0 &&
|
||||
instanceSpecificData.uploadState == undefined
|
||||
"
|
||||
>
|
||||
No similar posts found
|
||||
</li>
|
||||
|
||||
<li v-for="similarPost in getSimilarPosts(instanceSpecificData?.reverseSearchResult)" :key="similarPost.id">
|
||||
<a :href="getActiveSitePostUrl(similarPost.id)"
|
||||
>Post {{ similarPost.id }} looks {{ similarPost.percentage }}% similar</a
|
||||
>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div v-if="selectedPost" class="popup-columns" :class="{ mobile: isMobile }">
|
||||
<div class="popup-left">
|
||||
<div class="popup-section">
|
||||
<div class="section-header">
|
||||
<span>Basic info</span>
|
||||
<!-- <i class="fas fa-cog cursor-pointer" @click="openOptionsPage"></i> -->
|
||||
<font-awesome-icon icon="fa-solid fa-cog" class="cursor-pointer" @click="openOptionsPage" />
|
||||
</div>
|
||||
|
||||
<div class="section-row" v-if="selectedPost?.resolution">
|
||||
<ul class="compact">
|
||||
<li>Resolution: {{ resolutionToString(selectedPost.resolution) }}</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="section-row">
|
||||
<span class="section-label">Safety</span>
|
||||
|
||||
<div style="display: flex; gap: 10px">
|
||||
<label>
|
||||
<input type="radio" value="safe" v-model="selectedPost.rating" />
|
||||
Safe
|
||||
</label>
|
||||
|
||||
<label>
|
||||
<input type="radio" value="sketchy" v-model="selectedPost.rating" />
|
||||
Sketchy
|
||||
</label>
|
||||
|
||||
<label>
|
||||
<input type="radio" value="unsafe" v-model="selectedPost.rating" />
|
||||
Unsafe
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="section-row">
|
||||
<span class="section-label">Source</span>
|
||||
<textarea v-model="selectedPost.source"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="popup-section">
|
||||
<div class="section-header">
|
||||
<span>Tags</span>
|
||||
</div>
|
||||
|
||||
<div class="section-row" style="display: flex; flex-direction: column">
|
||||
<div style="display: flex">
|
||||
<input
|
||||
type="text"
|
||||
v-model="addTagInput"
|
||||
@keyup="onAddTagKeyUp"
|
||||
@keydown="onAddTagKeyDown"
|
||||
autocomplete="off"
|
||||
/>
|
||||
<button class="primary" style="margin-left: 5px" @click="addTagFromCurrentInput">Add</button>
|
||||
</div>
|
||||
|
||||
<div class="autocomplete-items" v-bind:class="{ show: autocompleteShown }">
|
||||
<div
|
||||
v-for="(tag, idx) in autocompleteTags"
|
||||
@click="onClickAutocompleteTagItem(tag)"
|
||||
:key="tag.name"
|
||||
:class="{
|
||||
active: idx == autocompleteIndex,
|
||||
}"
|
||||
>
|
||||
<span :class="getTagClasses(tag)">{{ tag.name }}</span>
|
||||
<span class="tag-usages">{{ tag.usages ? tag.usages : "" }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="section-row">
|
||||
<ul class="compact-tags">
|
||||
<li v-for="tag in selectedPost.tags" :key="tag.name">
|
||||
<a class="remove-tag" @click="removeTag(tag)">x</a>
|
||||
<span :class="getTagClasses(tag)" v-html="breakTagName(tag.name)"></span>
|
||||
<span v-if="config.loadTagCounts" class="tag-usages tag-usages-reserve-space">{{
|
||||
tag.usages ? tag.usages : ""
|
||||
}}</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="popup-section">
|
||||
<div class="section-row">
|
||||
<select v-model="selectedSiteId">
|
||||
<option v-for="site in config.sites" :key="site.id" :value="site.id">
|
||||
{{ site.domain }}
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="popup-right">
|
||||
<div class="popup-section">
|
||||
<select v-model="selectedPostId">
|
||||
<option v-for="post in posts" :key="post.id" :value="post.id">{{ post.name }}</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="popup-section">
|
||||
<div style="display: flex; gap: 5px">
|
||||
<button v-if="!config.autoSearchSimilar" class="primary" @click="clickFindSimilar">Find similar</button>
|
||||
<button class="primary full" @click="upload">Import</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="popup-section">
|
||||
<div class="post-container">
|
||||
<img
|
||||
v-if="selectedPost.contentType == 'image'"
|
||||
ref="imgEl"
|
||||
:src="selectedPost.contentUrl"
|
||||
@load="() => onloadImage(selectedPost)"
|
||||
/>
|
||||
<video v-if="selectedPost.contentType == 'video'" controls>
|
||||
<source :src="selectedPost.contentUrl" />
|
||||
</video>
|
||||
<div class="post-overlay">
|
||||
<PostNotes :notes="selectedPost.notes" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else class="p3 flex items-center gap-3">
|
||||
<span>No content found</span>
|
||||
<font-awesome-icon icon="fa-solid fa-cog" class="cursor-pointer" @click="openOptionsPage" />
|
||||
</div>
|
||||
<router-view />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style lang="scss">
|
||||
@use "../styles/main.scss";
|
||||
|
||||
video {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
textarea,
|
||||
select {
|
||||
font-size: 90%;
|
||||
}
|
||||
|
||||
label {
|
||||
flex: 1 0 auto;
|
||||
|
||||
input[type="radio"] {
|
||||
margin: 3px 3px 0 0;
|
||||
}
|
||||
}
|
||||
|
||||
.popup-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.popup-messages {
|
||||
grid-column: 1 / 3;
|
||||
margin: 0 10px;
|
||||
}
|
||||
|
||||
.popup-columns {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
|
||||
&.mobile {
|
||||
flex-direction: column-reverse;
|
||||
}
|
||||
}
|
||||
|
||||
.popup-left {
|
||||
flex: 1 0 300px;
|
||||
}
|
||||
|
||||
.popup-right {
|
||||
flex: 1 1 auto;
|
||||
}
|
||||
|
||||
.popup-section {
|
||||
margin: 10px;
|
||||
}
|
||||
|
||||
.section-header {
|
||||
height: 30px;
|
||||
padding: 0 6px 0 10px;
|
||||
background-color: var(--section-header-bg-color);
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
|
||||
> span {
|
||||
font-size: 1.2em;
|
||||
vertical-align: middle;
|
||||
color: var(--section-header-fg-color);
|
||||
}
|
||||
}
|
||||
|
||||
.section-row {
|
||||
margin: 10px 5px 0;
|
||||
}
|
||||
|
||||
.section-label {
|
||||
display: block;
|
||||
margin: 0 0 5px 0;
|
||||
}
|
||||
|
||||
.section-block {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.cursor-pointer {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.autocomplete-items {
|
||||
position: absolute;
|
||||
z-index: 10;
|
||||
background-color: var(--bg-main-color);
|
||||
border: 2px solid var(--primary-color);
|
||||
margin-top: 34px;
|
||||
display: none;
|
||||
|
||||
&.show {
|
||||
display: block;
|
||||
}
|
||||
|
||||
> div {
|
||||
cursor: pointer;
|
||||
padding: 2px 4px;
|
||||
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5em;
|
||||
|
||||
&:hover {
|
||||
background: var(--primary-color);
|
||||
> span {
|
||||
color: var(--text-color);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
> div.active {
|
||||
background: var(--primary-color);
|
||||
> span {
|
||||
color: var(--text-color);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Hacky way to stop the layout from resizing when we lazy load the usage count. */
|
||||
.tag-usages-reserve-space {
|
||||
min-width: 5ch; /* 5 character width */
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.post-container {
|
||||
position: relative;
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.post-overlay {
|
||||
position: absolute;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
@use "~/styles/main.scss";
|
||||
@use "~/styles/popup.scss";
|
||||
</style>
|
||||
|
|
|
|||
|
|
@ -1,7 +1,11 @@
|
|||
import { createApp } from "vue";
|
||||
import App from "./App.vue";
|
||||
import { setupApp } from "~/logic/common-setup";
|
||||
import { isChrome, isMobile } from "~/env";
|
||||
import { createRouter, createWebHashHistory } from "vue-router";
|
||||
|
||||
import App from "./App.vue";
|
||||
import PopupMain from "./pages/PopupMain.vue";
|
||||
import MergePost from "./pages/MergePost.vue";
|
||||
|
||||
// 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.
|
||||
|
|
@ -9,6 +13,17 @@ if (isChrome && !isMobile) {
|
|||
document.documentElement.style.width = "780px";
|
||||
}
|
||||
|
||||
const routes = [
|
||||
{ path: "/", component: PopupMain },
|
||||
{ name: "merge", path: "/merge/:siteId/:postId", component: MergePost, props: true },
|
||||
];
|
||||
|
||||
const router = createRouter({
|
||||
history: createWebHashHistory(),
|
||||
routes,
|
||||
});
|
||||
|
||||
const app = createApp(App);
|
||||
setupApp(app);
|
||||
app.use(router);
|
||||
app.mount("#app");
|
||||
|
|
|
|||
|
|
@ -0,0 +1,385 @@
|
|||
<script lang="ts" setup>
|
||||
import { isEqual, cloneDeep } from "lodash";
|
||||
import SzurubooruApi from "~/api";
|
||||
import { Post, UpdatePostRequest } from "~/api/models";
|
||||
import { BrowserCommand, PostUpdateCommandData, TagDetails } from "~/models";
|
||||
import { useConfigStore, useMergeStore, usePopupStore } from "~/stores";
|
||||
import { emptyPost, getUrl } from "~/utils";
|
||||
|
||||
const props = defineProps(["siteId", "postId"]);
|
||||
const cfg = useConfigStore();
|
||||
const merge = useMergeStore();
|
||||
const pop = usePopupStore();
|
||||
|
||||
const szuruConfig = cfg.sites.find((x) => x.id == props.siteId)!;
|
||||
const szuru = SzurubooruApi.createFromConfig(szuruConfig);
|
||||
|
||||
// Used for the update post request.
|
||||
// Should NOT be edited by the user, as this is used to compute the changeset, e.g. "Tags: +1 / -3".
|
||||
let existingPostRo: Post | undefined = undefined;
|
||||
|
||||
// Editable existing post.
|
||||
const post = ref<Post>(emptyPost());
|
||||
|
||||
// Readonly scraped post.
|
||||
const scrapedPost = pop.selectedPost;
|
||||
|
||||
// Stuff which the user can change.
|
||||
const imageToKeep = ref<"current" | "new">("new");
|
||||
const tagsToAdd = reactive([] as TagDetails[]);
|
||||
|
||||
// Computed stuff.
|
||||
const sourcesAdded = ref(0);
|
||||
const sourcesRemoved = ref(0);
|
||||
// tagsAdded = tagsToAdd.length
|
||||
const tagsRemoved = ref(0);
|
||||
|
||||
const contentUrl = computed(() => (imageToKeep.value == "current" ? post.value.contentUrl : scrapedPost?.contentUrl));
|
||||
|
||||
function removeExistingTag(tag: TagDetails) {
|
||||
const idx = post.value.tags.findIndex((x) => x.names == tag.names);
|
||||
if (idx != -1) {
|
||||
tagsRemoved.value++;
|
||||
post.value.tags.splice(idx, 1);
|
||||
}
|
||||
}
|
||||
|
||||
function addTag(tag: TagDetails) {
|
||||
// Only add tag if it doesn't already exist
|
||||
if (
|
||||
tag.name.length > 0 &&
|
||||
tagsToAdd.find((x) => x.name == tag.name) == undefined &&
|
||||
post.value.tags.find((x) => x.names.indexOf(tag.name) != -1) == undefined
|
||||
) {
|
||||
tagsToAdd.push(tag);
|
||||
|
||||
// Add implications for the tag
|
||||
if (cfg.addTagImplications) {
|
||||
tagsToAdd.push(...tag.implications);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function removeTagToAdd(tag: TagDetails) {
|
||||
const idx = tagsToAdd.indexOf(tag);
|
||||
if (idx != -1) {
|
||||
tagsToAdd.splice(idx, 1);
|
||||
}
|
||||
}
|
||||
|
||||
function appendSources() {
|
||||
if (scrapedPost) {
|
||||
const re = /\r?\n/;
|
||||
const sources = post.value.source?.split(re) ?? [];
|
||||
for (const source of scrapedPost.source.split(re)) {
|
||||
if (sources.indexOf(source) == -1) {
|
||||
sources.push(source);
|
||||
}
|
||||
}
|
||||
post.value.source = sources.join("\n");
|
||||
}
|
||||
}
|
||||
|
||||
function addMissingTags() {
|
||||
if (scrapedPost) {
|
||||
for (const tag of scrapedPost.tags) {
|
||||
if (post.value.tags.find((x) => x.names.indexOf(tag.name) != -1) == undefined) {
|
||||
tagsToAdd.push(tag);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function mergeSafety() {
|
||||
if (scrapedPost) {
|
||||
post.value.safety = scrapedPost.rating;
|
||||
}
|
||||
}
|
||||
|
||||
function getPostUrl(postId: number): string {
|
||||
return getUrl(szuruConfig.domain, "post", postId.toString());
|
||||
}
|
||||
|
||||
async function mergeChanges() {
|
||||
merge.genericError = undefined;
|
||||
|
||||
if (!scrapedPost) {
|
||||
// Should never happend.
|
||||
merge.genericError = "Invalid state. 'scrapedPost' is falsy.";
|
||||
return;
|
||||
}
|
||||
|
||||
if (!existingPostRo) {
|
||||
// Should only happen with an network error I guess?
|
||||
merge.genericError = "Invalid state. 'existingPostRo' is falsy.";
|
||||
return;
|
||||
}
|
||||
|
||||
const req = <UpdatePostRequest>{
|
||||
version: existingPostRo?.version,
|
||||
};
|
||||
|
||||
if (post.value.source != existingPostRo.source) {
|
||||
req.source = post.value.source;
|
||||
}
|
||||
|
||||
const newTags = post.value.tags.map((x) => x.names[0]).concat(tagsToAdd.map((x) => x.name));
|
||||
|
||||
if (
|
||||
!isEqual(
|
||||
newTags,
|
||||
existingPostRo.tags.map((x) => x.names[0])
|
||||
)
|
||||
) {
|
||||
req.tags = newTags;
|
||||
}
|
||||
|
||||
if (post.value.safety != existingPostRo.safety) {
|
||||
req.safety = post.value.safety;
|
||||
}
|
||||
|
||||
if (imageToKeep.value == "new") {
|
||||
req.contentUrl = scrapedPost?.contentUrl;
|
||||
}
|
||||
|
||||
if (!req.safety && !req.source && !(req.contentUrl || req.contentToken) && req.tags === undefined) {
|
||||
merge.genericError = "No changes to merge.";
|
||||
return;
|
||||
}
|
||||
|
||||
const cmdData = new PostUpdateCommandData(existingPostRo.id, req, szuruConfig);
|
||||
const cmd = new BrowserCommand("update_post", cmdData);
|
||||
await browser.runtime.sendMessage(cmd);
|
||||
}
|
||||
|
||||
watch(
|
||||
() => post.value.source,
|
||||
(value, oldValue) => {
|
||||
// TODO: Implement this.
|
||||
sourcesAdded.value = 0;
|
||||
sourcesRemoved.value = 0;
|
||||
}
|
||||
);
|
||||
|
||||
watch(
|
||||
() => cfg.merge.addMissingTags,
|
||||
(value) => {
|
||||
if (value) {
|
||||
addMissingTags();
|
||||
} else if (existingPostRo) {
|
||||
tagsToAdd.splice(0);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
watch(
|
||||
() => cfg.merge.appendSource,
|
||||
(value) => {
|
||||
if (value) {
|
||||
appendSources();
|
||||
} else if (existingPostRo) {
|
||||
post.value.source = existingPostRo.source;
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
watch(
|
||||
() => cfg.merge.mergeSafety,
|
||||
(value) => {
|
||||
if (value) {
|
||||
mergeSafety();
|
||||
} else if (existingPostRo) {
|
||||
post.value.safety = existingPostRo.safety;
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
onMounted(async () => {
|
||||
existingPostRo = await szuru?.getPost(props.postId);
|
||||
if (existingPostRo) {
|
||||
post.value = cloneDeep(existingPostRo);
|
||||
if (cfg.merge.appendSource) appendSources();
|
||||
if (cfg.merge.addMissingTags) addMissingTags();
|
||||
if (cfg.merge.mergeSafety) mergeSafety();
|
||||
|
||||
if (scrapedPost?.resolution) {
|
||||
// Set imageToKeep depending on which image has the largest resolution.
|
||||
// TODO: Would be neat if this also uses the fileSize.
|
||||
const scrapedPx = scrapedPost.resolution[0] * scrapedPost.resolution[1];
|
||||
const existingPx = existingPostRo.canvasHeight * existingPostRo.canvasWidth;
|
||||
|
||||
if (existingPx >= scrapedPx) {
|
||||
imageToKeep.value = "current";
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="popup-messages">
|
||||
<div class="messages">
|
||||
<div v-if="merge.genericError" class="bg-danger">
|
||||
<span>{{ merge.genericError }}</span>
|
||||
</div>
|
||||
|
||||
<template v-for="data in merge.uploadInfo">
|
||||
<div :key="data.postId" v-if="data.info.state == 'uploaded' && data.info.instancePostId" class="bg-success">
|
||||
<a :href="getPostUrl(data.info.instancePostId)">Merged into post {{ data.info.instancePostId }}</a>
|
||||
</div>
|
||||
|
||||
<div :key="data.postId" v-if="data.info.state == 'uploading'"><span>Merging...</span></div>
|
||||
|
||||
<!-- Only show error when it's not undefined and not empty. -->
|
||||
<div :key="data.postId" v-if="data.info.error?.length" class="bg-danger">
|
||||
<span>Couldn't merge into post. {{ data.info.error }}</span>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- <div class="popup-columns" :class="{ mobile: isMobile }"> -->
|
||||
<div class="popup-columns">
|
||||
<div class="popup-left">
|
||||
<div class="popup-section">
|
||||
<div style="display: flex; flex-direction: column; gap: 5px">
|
||||
<div style="display: flex; gap: 5px">
|
||||
<button class="bg-danger" @click="$router.back()">
|
||||
<font-awesome-icon icon="fa-solid fa-chevron-left" class="cursor-pointer" @click="undefined" />
|
||||
Back
|
||||
</button>
|
||||
<div class="section-header full">
|
||||
<span>Merge into post #{{ props.postId }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button class="primary full" @click="mergeChanges">Merge changes</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<PopupSection header="Basic info">
|
||||
<div class="section-row">
|
||||
<span class="section-label">Safety</span>
|
||||
|
||||
<div style="display: flex; gap: 10px">
|
||||
<label>
|
||||
<input type="radio" value="safe" v-model="post.safety" />
|
||||
Safe
|
||||
</label>
|
||||
|
||||
<label>
|
||||
<input type="radio" value="sketchy" v-model="post.safety" />
|
||||
Sketchy
|
||||
</label>
|
||||
|
||||
<label>
|
||||
<input type="radio" value="unsafe" v-model="post.safety" />
|
||||
Unsafe
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="section-row">
|
||||
<span class="section-label">Source</span>
|
||||
<!-- TODO: Fix this -->
|
||||
<textarea v-model="post.source"></textarea>
|
||||
</div>
|
||||
</PopupSection>
|
||||
|
||||
<PopupSection header="Existing tags" toggleable v-model="cfg.merge.expandExistingTags">
|
||||
<div class="section-row">
|
||||
<CompactTags
|
||||
:tags="post.tags.map((x) => TagDetails.fromMicroTag(x))"
|
||||
:show-remove-tag="true"
|
||||
:show-usages="true"
|
||||
@remove-tag="removeExistingTag"
|
||||
/>
|
||||
</div>
|
||||
</PopupSection>
|
||||
|
||||
<PopupSection header="Tags to add" toggleable v-model="cfg.merge.expandAddTags">
|
||||
<div class="section-row">
|
||||
<TagInput :szuru="szuru" @add-tag="addTag" />
|
||||
</div>
|
||||
|
||||
<div class="section-row">
|
||||
<CompactTags :tags="tagsToAdd" :show-remove-tag="true" :show-usages="true" @remove-tag="removeTagToAdd" />
|
||||
</div>
|
||||
</PopupSection>
|
||||
</div>
|
||||
|
||||
<div class="popup-right">
|
||||
<PopupSection header="Content">
|
||||
<div class="section-row">
|
||||
<div style="display: flex; gap: 10px; margin: 10px 0">
|
||||
<label>
|
||||
<input type="radio" value="current" v-model="imageToKeep" />
|
||||
Current ({{ post.canvasWidth }}x{{ post.canvasHeight }})
|
||||
</label>
|
||||
|
||||
<!-- TODO: Also display filesize -->
|
||||
|
||||
<label>
|
||||
<input type="radio" value="new" v-model="imageToKeep" />
|
||||
New ({{ scrapedPost?.resolution?.[0] }}x{{ scrapedPost?.resolution?.[1] }})
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<PostContentDisplay :content-url="contentUrl" content-type="image" />
|
||||
</div>
|
||||
</PopupSection>
|
||||
|
||||
<PopupSection header="Merge options" toggleable v-model="cfg.merge.expandOptions">
|
||||
<div class="section-row">
|
||||
<div style="display: flex; flex-direction: column">
|
||||
<label>
|
||||
<input type="checkbox" v-model="cfg.merge.addMissingTags" />
|
||||
Add missing tags
|
||||
</label>
|
||||
|
||||
<label>
|
||||
<input type="checkbox" v-model="cfg.merge.appendSource" />
|
||||
Append source
|
||||
</label>
|
||||
|
||||
<label>
|
||||
<input type="checkbox" v-model="cfg.merge.mergeSafety" />
|
||||
Merge safety
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</PopupSection>
|
||||
|
||||
<PopupSection header="Changes">
|
||||
<div class="section-row">
|
||||
<ul class="compact-tags">
|
||||
<li v-show="tagsToAdd.length != 0 || tagsRemoved != 0">
|
||||
Tags: <span class="success" v-show="tagsToAdd.length != 0">+{{ tagsToAdd.length }}</span>
|
||||
<span class="danger" v-show="tagsRemoved != 0">-{{ tagsRemoved }}</span>
|
||||
</li>
|
||||
<li v-show="sourcesAdded != 0 || sourcesRemoved != 0">
|
||||
Sources: <span class="success" v-show="sourcesAdded != 0">+2</span>
|
||||
<span class="danger" v-show="sourcesRemoved != 0">-1</span>
|
||||
</li>
|
||||
<li v-show="existingPostRo?.safety != post.safety">
|
||||
Safety: <s class="danger">{{ existingPostRo?.safety }}</s> <span class="success">{{ post.safety }}</span>
|
||||
</li>
|
||||
<li v-show="imageToKeep == 'new'">
|
||||
<span class="success">Updating post content</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</PopupSection>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.popup-left {
|
||||
flex: 1 1 auto;
|
||||
}
|
||||
|
||||
.popup-right {
|
||||
flex: 1 0 300px;
|
||||
}
|
||||
</style>
|
||||
|
|
@ -0,0 +1,524 @@
|
|||
<script setup lang="ts">
|
||||
import { useDark } from "@vueuse/core";
|
||||
import { ScrapeResults } from "neo-scraper";
|
||||
import { getUrl, encodeTagName, getErrorMessage } from "~/utils";
|
||||
import {
|
||||
BrowserCommand,
|
||||
ScrapedPostDetails,
|
||||
TagDetails,
|
||||
SimilarPostInfo,
|
||||
SimpleSimilarPost,
|
||||
SimpleImageSearchResult,
|
||||
PostUploadCommandData,
|
||||
} from "~/models";
|
||||
import { ImageSearchResult } from "~/api/models";
|
||||
import { isMobile } from "~/env";
|
||||
import { DeepReadonly } from "vue";
|
||||
import { useConfigStore, usePopupStore } from "~/stores";
|
||||
|
||||
const pop = usePopupStore();
|
||||
const cfg = useConfigStore();
|
||||
const isSearchingForSimilarPosts = ref<number>(0);
|
||||
|
||||
// (Reactive) shorthand for `main.selectedPost.instanceSpecificData.get(config.selectedSiteId)`.
|
||||
// This should only be used as if it were readonly, because the instanceId might change.
|
||||
const instanceSpecificData = readonly(
|
||||
computed(() => {
|
||||
if (pop.selectedPost && cfg.selectedSiteId) {
|
||||
return pop.selectedPost.instanceSpecificData[cfg.selectedSiteId];
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
watch(
|
||||
() => pop.selectedPostId,
|
||||
(value) => {
|
||||
// Call findSimilar if wanted.
|
||||
if (cfg.autoSearchSimilar) {
|
||||
let selectedPost = pop.posts.find((x) => x.id == value);
|
||||
if (selectedPost) findSimilar(selectedPost);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
watch(
|
||||
() => cfg.selectedSiteId,
|
||||
async (value, oldValue) => {
|
||||
// If changed
|
||||
if (value != oldValue) {
|
||||
// Update selectedSiteId in config
|
||||
cfg.selectedSiteId = value;
|
||||
// Call findSimilar if wanted.
|
||||
if (cfg.autoSearchSimilar && pop.selectedPost) {
|
||||
findSimilar(pop.selectedPost);
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
function openOptionsPage() {
|
||||
browser.runtime.openOptionsPage();
|
||||
}
|
||||
|
||||
async function getActiveTabId(): Promise<number> {
|
||||
const activeTabs = await browser.tabs.query({
|
||||
active: true,
|
||||
currentWindow: true,
|
||||
});
|
||||
|
||||
if (activeTabs.length > 0 && activeTabs[0].id) return activeTabs[0].id;
|
||||
throw new Error("No active tab.");
|
||||
}
|
||||
|
||||
async function grabPost() {
|
||||
// Get active tab
|
||||
const activeTabId = await getActiveTabId();
|
||||
|
||||
// Send 'grab_post' to the content script on the active tab
|
||||
const x = await browser.tabs.sendMessage(activeTabId, new BrowserCommand("grab_post"));
|
||||
// We need to create a new ScrapeResults object and fill it with our data, because the get_posts()
|
||||
// method gets 'lost' when sent from the contentscript to the popup (it gets JSON.stringified and any prototype defines are lost there)
|
||||
const res = Object.assign(new ScrapeResults(), x);
|
||||
|
||||
console.dir(res);
|
||||
|
||||
// Clear current posts array
|
||||
pop.posts.splice(0);
|
||||
|
||||
for (const result of res.results) {
|
||||
for (const i in result.posts) {
|
||||
const vm = new ScrapedPostDetails(result.posts[i]);
|
||||
vm.name = `[${result.engine}] Post ${parseInt(i) + 1}`; // parseInt() is required!
|
||||
|
||||
// Add current pageUrl to the source if either
|
||||
// a. user has addPageUrlToSource set to true
|
||||
// b. source is empty
|
||||
if (cfg?.addPageUrlToSource || vm.source == "") {
|
||||
if (vm.source != "") vm.source += "\n";
|
||||
vm.source += vm.pageUrl;
|
||||
}
|
||||
|
||||
// Initialize instanceSpecificData with an empty object.
|
||||
for (const site of cfg.sites) {
|
||||
vm.instanceSpecificData[site.id] = {};
|
||||
}
|
||||
|
||||
pop.posts.push(vm);
|
||||
}
|
||||
}
|
||||
|
||||
if (pop.posts.length > 0) {
|
||||
pop.selectedPostId = pop.posts[0].id;
|
||||
if (cfg?.loadTagCounts) {
|
||||
loadTagCounts();
|
||||
}
|
||||
} else {
|
||||
// pushInfo("No posts found.");
|
||||
}
|
||||
}
|
||||
|
||||
async function upload() {
|
||||
if (!cfg.selectedSiteId) return;
|
||||
let instanceSpecificData = pop.selectedPost?.instanceSpecificData[cfg.selectedSiteId];
|
||||
|
||||
// Don't try to upload if an exact copy is already on the server.
|
||||
if (instanceSpecificData?.reverseSearchResult?.exactPostId) return;
|
||||
|
||||
if (instanceSpecificData) {
|
||||
instanceSpecificData.uploadState = { state: "uploading" };
|
||||
}
|
||||
|
||||
const post: any = { ...pop.selectedPost };
|
||||
// @ts-expect-error ...
|
||||
const cmdData = new PostUploadCommandData(post, cfg.selectedSite);
|
||||
const cmd = new BrowserCommand("upload_post", cmdData);
|
||||
await browser.runtime.sendMessage(cmd);
|
||||
}
|
||||
|
||||
function resolutionToString(resolution: [number, number]) {
|
||||
if (resolution && resolution.length == 2) {
|
||||
return resolution[0] + "x" + resolution[1];
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
function removeTag(tag: TagDetails) {
|
||||
if (pop.selectedPost) {
|
||||
const idx = pop.selectedPost.tags.indexOf(tag);
|
||||
if (idx != -1) {
|
||||
pop.selectedPost.tags.splice(idx, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function getActiveSitePostUrl(postId: number): string {
|
||||
if (!cfg.selectedSite) return "";
|
||||
return getUrl(cfg.selectedSite.domain, "post", postId.toString());
|
||||
}
|
||||
|
||||
function getSimilarPosts(data?: DeepReadonly<SimpleImageSearchResult>): SimilarPostInfo[] {
|
||||
if (!data) return [];
|
||||
|
||||
const lst: SimilarPostInfo[] = [];
|
||||
|
||||
for (const similarPost of data.similarPosts) {
|
||||
if (data.exactPostId == similarPost.postId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
lst.push(new SimilarPostInfo(similarPost.postId, Math.round(100 - similarPost.distance * 100)));
|
||||
}
|
||||
|
||||
return lst;
|
||||
}
|
||||
|
||||
function addTag(tag: TagDetails) {
|
||||
if (pop.selectedPost) {
|
||||
// Only add tag if it doesn't already exist
|
||||
if (tag.name.length > 0 && pop.selectedPost.tags.find((x) => x.name == tag.name) == undefined) {
|
||||
pop.selectedPost.tags.push(tag);
|
||||
|
||||
// Add implications for the tag
|
||||
if (cfg.addTagImplications) {
|
||||
pop.selectedPost.tags.push(...tag.implications);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function clickFindSimilar() {
|
||||
if (pop.selectedPost) return await findSimilar(pop.selectedPost);
|
||||
}
|
||||
|
||||
async function findSimilar(post: ScrapedPostDetails | undefined) {
|
||||
if (!post || !cfg.szuru || !cfg.selectedSiteId) return;
|
||||
|
||||
const selectedInstance = cfg.szuru; // Get current object, and not reactive.
|
||||
let instanceSpecificData = post.instanceSpecificData[cfg.selectedSiteId];
|
||||
|
||||
if (!instanceSpecificData) {
|
||||
console.error("instanceSpecificData is undefined. This should never happen!");
|
||||
return;
|
||||
}
|
||||
|
||||
// Don't load this again if it is already loaded.
|
||||
if (instanceSpecificData?.reverseSearchResult) return;
|
||||
|
||||
isSearchingForSimilarPosts.value++;
|
||||
|
||||
try {
|
||||
let res: ImageSearchResult | undefined;
|
||||
|
||||
if (cfg.useContentTokens) {
|
||||
let tmpRes = await selectedInstance.uploadTempFile(post.contentUrl);
|
||||
// TODO: Error handling?
|
||||
// Save contentToken in PostViewModel so that we can reuse it when creating/uploading the post.
|
||||
instanceSpecificData.contentToken = tmpRes.token;
|
||||
|
||||
res = await selectedInstance.reverseSearchToken(tmpRes.token);
|
||||
} else {
|
||||
res = await selectedInstance.reverseSearch(post.contentUrl);
|
||||
}
|
||||
|
||||
instanceSpecificData.reverseSearchResult = {
|
||||
exactPostId: res.exactPost?.id,
|
||||
similarPosts: res.similarPosts.map((x) => <SimpleSimilarPost>{ postId: x.post.id, distance: x.distance }),
|
||||
};
|
||||
} catch (ex: any) {
|
||||
instanceSpecificData.genericError = "Couldn't reverse search. " + getErrorMessage(ex);
|
||||
}
|
||||
|
||||
isSearchingForSimilarPosts.value--;
|
||||
}
|
||||
|
||||
async function loadTagCounts() {
|
||||
const allTags = pop.posts.flatMap((x) => x.tags);
|
||||
|
||||
for (let i = 0; i < allTags.length; i += 100) {
|
||||
const query = allTags
|
||||
.slice(i, i + 101)
|
||||
.map((x) => encodeTagName(x.name))
|
||||
.join();
|
||||
|
||||
const resp = await cfg.szuru?.getTags(query);
|
||||
|
||||
// Not the best code, but it works I guess?
|
||||
if (resp) {
|
||||
for (let post of pop.posts)
|
||||
for (let tag of resp.results)
|
||||
for (let postTag of post.tags)
|
||||
if (postTag.name == tag.names[0]) {
|
||||
postTag.usages = tag.usages;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Cool people would use https://kazupon.github.io/vue-i18n/guide/pluralization.html
|
||||
function getUpdatedTagsText(count: number) {
|
||||
return `Updated ${count} tag${count > 1 ? "s" : ""}`;
|
||||
}
|
||||
|
||||
function onResolutionLoaded(res: any) {
|
||||
if (pop.selectedPost && !pop.selectedPost.resolution) {
|
||||
pop.selectedPost.resolution = res;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
if (pop.posts.length == 0) {
|
||||
grabPost();
|
||||
}
|
||||
});
|
||||
|
||||
useDark();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="popup-messages">
|
||||
<div class="messages">
|
||||
<!--
|
||||
Error messages
|
||||
-->
|
||||
|
||||
<div v-if="cfg.sites.length == 0" class="bg-danger">
|
||||
<span>No szurubooru server configured!</span>
|
||||
</div>
|
||||
|
||||
<div v-if="!cfg.selectedSite" class="bg-danger">
|
||||
<span>No target server selected!</span>
|
||||
</div>
|
||||
|
||||
<div v-if="instanceSpecificData?.reverseSearchResult?.exactPostId" class="bg-danger has-merge-button">
|
||||
<a :href="getActiveSitePostUrl(instanceSpecificData.reverseSearchResult?.exactPostId)">
|
||||
Post already uploaded ({{ instanceSpecificData.reverseSearchResult.exactPostId }})
|
||||
</a>
|
||||
|
||||
<!-- TODO: Maybe a 5px gap here? -->
|
||||
|
||||
<div style="display: flex; background: purple; border-radius: 0 2px 2px 0">
|
||||
<router-link
|
||||
:to="{
|
||||
name: 'merge',
|
||||
params: {
|
||||
siteId: cfg.selectedSiteId,
|
||||
postId: instanceSpecificData?.reverseSearchResult?.exactPostId,
|
||||
},
|
||||
}"
|
||||
style="padding: 5px 20px"
|
||||
>Merge</router-link
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Only show error when it's not undefined and not empty. -->
|
||||
<div v-if="instanceSpecificData?.uploadState?.error?.length" class="bg-danger">
|
||||
<span>Couldn't upload post. {{ instanceSpecificData.uploadState.error }}</span>
|
||||
</div>
|
||||
|
||||
<div v-if="instanceSpecificData?.genericError" class="bg-danger">
|
||||
<span>{{ instanceSpecificData.genericError }}</span>
|
||||
</div>
|
||||
|
||||
<!--
|
||||
Success messages
|
||||
-->
|
||||
|
||||
<!-- TODO: Clicking a link doesn't actually open it in a new tab, see https://stackoverflow.com/questions/8915845 -->
|
||||
<div
|
||||
v-if="
|
||||
instanceSpecificData?.uploadState?.state == 'uploaded' && instanceSpecificData?.uploadState.instancePostId
|
||||
"
|
||||
class="bg-success"
|
||||
>
|
||||
<a :href="getActiveSitePostUrl(instanceSpecificData.uploadState.instancePostId)"
|
||||
>Uploaded post {{ instanceSpecificData.uploadState.instancePostId }}</a
|
||||
>
|
||||
</div>
|
||||
|
||||
<div v-if="instanceSpecificData?.uploadState?.updateTagsState?.totalChanged" class="bg-success">
|
||||
<span>{{ getUpdatedTagsText(instanceSpecificData.uploadState?.updateTagsState?.totalChanged) }}</span>
|
||||
</div>
|
||||
|
||||
<!--
|
||||
Info messages
|
||||
-->
|
||||
|
||||
<div v-if="instanceSpecificData?.uploadState?.state == 'uploading'"><span>Uploading...</span></div>
|
||||
|
||||
<div
|
||||
v-if="
|
||||
instanceSpecificData?.uploadState?.updateTagsState?.total &&
|
||||
instanceSpecificData.uploadState?.updateTagsState?.current == undefined
|
||||
"
|
||||
>
|
||||
<span>{{ instanceSpecificData.uploadState?.updateTagsState?.total }} tags need a different category</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="
|
||||
instanceSpecificData?.uploadState?.updateTagsState?.current &&
|
||||
instanceSpecificData?.uploadState?.updateTagsState?.totalChanged == undefined
|
||||
"
|
||||
>
|
||||
<span
|
||||
>Updating tag {{ instanceSpecificData.uploadState?.updateTagsState?.current }}/{{
|
||||
instanceSpecificData.uploadState?.updateTagsState?.total
|
||||
}}</span
|
||||
>
|
||||
</div>
|
||||
|
||||
<div v-if="isSearchingForSimilarPosts > 0 && instanceSpecificData?.uploadState == undefined">
|
||||
<span>Searching for similar posts...</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="
|
||||
instanceSpecificData?.reverseSearchResult?.similarPosts.length == 0 &&
|
||||
instanceSpecificData.uploadState == undefined
|
||||
"
|
||||
>
|
||||
<span>No similar posts found</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-for="similarPost in getSimilarPosts(instanceSpecificData?.reverseSearchResult)"
|
||||
:key="similarPost.id"
|
||||
class="has-merge-button"
|
||||
>
|
||||
<a :href="getActiveSitePostUrl(similarPost.id)"
|
||||
>Post {{ similarPost.id }} looks {{ similarPost.percentage }}% similar</a
|
||||
>
|
||||
|
||||
<!-- TODO: Maybe a 5px gap here? -->
|
||||
|
||||
<div style="display: flex; background: purple; border-radius: 0 2px 2px 0">
|
||||
<router-link
|
||||
:to="{
|
||||
name: 'merge',
|
||||
params: {
|
||||
siteId: cfg.selectedSiteId,
|
||||
postId: similarPost.id,
|
||||
},
|
||||
}"
|
||||
style="padding: 5px 20px"
|
||||
>Merge</router-link
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="pop.selectedPost" class="popup-columns" :class="{ mobile: isMobile }">
|
||||
<div class="popup-left">
|
||||
<PopupSection>
|
||||
<template #header>
|
||||
<span>Basic info</span>
|
||||
<font-awesome-icon icon="fa-solid fa-cog" class="cursor-pointer" @click="openOptionsPage" />
|
||||
</template>
|
||||
|
||||
<div class="section-row" v-if="pop.selectedPost?.resolution">
|
||||
<ul class="compact">
|
||||
<li>Resolution: {{ resolutionToString(pop.selectedPost.resolution) }}</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="section-row">
|
||||
<span class="section-label">Safety</span>
|
||||
|
||||
<div style="display: flex; gap: 10px">
|
||||
<label>
|
||||
<input type="radio" value="safe" v-model="pop.selectedPost.rating" />
|
||||
Safe
|
||||
</label>
|
||||
|
||||
<label>
|
||||
<input type="radio" value="sketchy" v-model="pop.selectedPost.rating" />
|
||||
Sketchy
|
||||
</label>
|
||||
|
||||
<label>
|
||||
<input type="radio" value="unsafe" v-model="pop.selectedPost.rating" />
|
||||
Unsafe
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="section-row">
|
||||
<span class="section-label">Source</span>
|
||||
<textarea v-model="pop.selectedPost.source"></textarea>
|
||||
</div>
|
||||
</PopupSection>
|
||||
|
||||
<PopupSection header="Tags">
|
||||
<div class="section-row">
|
||||
<TagInput :szuru="cfg.szuru" @add-tag="addTag" />
|
||||
</div>
|
||||
|
||||
<div class="section-row">
|
||||
<CompactTags
|
||||
:tags="pop.selectedPost.tags"
|
||||
:show-remove-tag="true"
|
||||
:show-usages="cfg.loadTagCounts"
|
||||
@remove-tag="removeTag"
|
||||
/>
|
||||
</div>
|
||||
</PopupSection>
|
||||
|
||||
<div class="popup-section">
|
||||
<div class="section-row">
|
||||
<select v-model="cfg.selectedSiteId">
|
||||
<option v-for="site in cfg.sites" :key="site.id" :value="site.id">
|
||||
{{ site.domain }}
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="popup-right">
|
||||
<div class="popup-section">
|
||||
<select v-model="pop.selectedPostId">
|
||||
<option v-for="post in pop.posts" :key="post.id" :value="post.id">{{ post.name }}</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="popup-section">
|
||||
<div style="display: flex; gap: 5px">
|
||||
<button v-if="!cfg.autoSearchSimilar" class="primary" @click="clickFindSimilar">Find similar</button>
|
||||
<button class="primary full" @click="upload">Import</button>
|
||||
<!-- TODO: Add button to open this popup in fullscreen. -->
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="popup-section">
|
||||
<PostContentDisplay
|
||||
:content-url="pop.selectedPost.contentUrl"
|
||||
:content-type="pop.selectedPost.contentType"
|
||||
@on-resolution-loaded="onResolutionLoaded"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else class="p3 flex items-center gap-3">
|
||||
<span>No content found</span>
|
||||
<font-awesome-icon icon="fa-solid fa-cog" class="cursor-pointer" @click="openOptionsPage" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.popup-left {
|
||||
flex: 1 0 300px;
|
||||
}
|
||||
|
||||
.popup-right {
|
||||
flex: 1 1 auto;
|
||||
}
|
||||
|
||||
.has-merge-button {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
}
|
||||
</style>
|
||||
|
|
@ -0,0 +1,68 @@
|
|||
import { defineStore } from "pinia";
|
||||
import { SzuruSiteConfig } from "~/config";
|
||||
import SzurubooruApi from "~/api";
|
||||
import type { ScrapedPostDetails, SetPostUploadInfoData } from "~/models";
|
||||
|
||||
export const useConfigStore = defineStore("config", {
|
||||
state: () => ({
|
||||
addPageUrlToSource: true,
|
||||
autoSearchSimilar: false,
|
||||
loadTagCounts: true,
|
||||
useContentTokens: true,
|
||||
sites: [] as Array<SzuruSiteConfig>,
|
||||
selectedSiteId: undefined as string | undefined,
|
||||
addTagImplications: true,
|
||||
merge: {
|
||||
expandOptions: true,
|
||||
expandExistingTags: false,
|
||||
expandAddTags: true,
|
||||
addMissingTags: true,
|
||||
appendSource: true,
|
||||
mergeSafety: true,
|
||||
},
|
||||
}),
|
||||
getters: {
|
||||
selectedSite: (state) => {
|
||||
return state.sites.find((x) => x.id == state.selectedSiteId);
|
||||
},
|
||||
szuru(): SzurubooruApi | undefined {
|
||||
if (this.selectedSite) {
|
||||
return SzurubooruApi.createFromConfig(this.selectedSite);
|
||||
}
|
||||
},
|
||||
},
|
||||
actions: {
|
||||
createSzuruApiFromConfig(siteId: string) {
|
||||
const cfg = this.sites.find((x) => x.id == siteId);
|
||||
if (cfg) {
|
||||
return SzurubooruApi.createFromConfig(cfg);
|
||||
}
|
||||
},
|
||||
},
|
||||
persist: true,
|
||||
});
|
||||
|
||||
export const usePopupStore = defineStore("popup", {
|
||||
state: () => ({
|
||||
posts: [] as ScrapedPostDetails[],
|
||||
selectedPostId: undefined as string | undefined,
|
||||
isSearchingForSimilarPosts: 0,
|
||||
}),
|
||||
getters: {
|
||||
selectedPost: (state) => {
|
||||
return state.posts.find((x) => x.id == state.selectedPostId);
|
||||
},
|
||||
},
|
||||
actions: {
|
||||
getPostForContentUrl(contentUrl: string): ScrapedPostDetails | undefined {
|
||||
return this.posts.find((x) => x.contentUrl == contentUrl);
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
export const useMergeStore = defineStore("merge", {
|
||||
state: () => ({
|
||||
uploadInfo: [] as SetPostUploadInfoData[],
|
||||
genericError: undefined as string | undefined,
|
||||
}),
|
||||
});
|
||||
|
|
@ -91,6 +91,7 @@ html.dark {
|
|||
--text-color: #e6e6e6;
|
||||
color: var(--text-color);
|
||||
background-color: var(--bg-main-color);
|
||||
color-scheme: dark;
|
||||
}
|
||||
|
||||
body {
|
||||
|
|
@ -237,17 +238,18 @@ a.remove-tag {
|
|||
}
|
||||
|
||||
.messages {
|
||||
list-style-type: none;
|
||||
padding: 0;
|
||||
display: inline;
|
||||
|
||||
> li {
|
||||
padding: 5px;
|
||||
> div {
|
||||
display: flex;
|
||||
border-radius: 2px;
|
||||
background: var(--primary-color);
|
||||
color: #fff;
|
||||
|
||||
> a {
|
||||
a,
|
||||
span {
|
||||
padding: 5px;
|
||||
}
|
||||
|
||||
a {
|
||||
color: #fff;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
|
@ -269,3 +271,15 @@ a.remove-tag {
|
|||
.bg-success {
|
||||
background: var(--success-color) !important;
|
||||
}
|
||||
|
||||
.danger {
|
||||
color: var(--danger-color);
|
||||
}
|
||||
|
||||
.success {
|
||||
color: var(--success-color);
|
||||
}
|
||||
|
||||
.cursor-pointer {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,71 @@
|
|||
.popup-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.popup-messages {
|
||||
grid-column: 1 / 3;
|
||||
margin: 0 10px;
|
||||
}
|
||||
|
||||
.popup-columns {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
|
||||
&.mobile {
|
||||
flex-direction: column-reverse;
|
||||
}
|
||||
}
|
||||
|
||||
.popup-section {
|
||||
margin: 10px;
|
||||
}
|
||||
|
||||
video {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
textarea,
|
||||
select {
|
||||
font-size: 90%;
|
||||
}
|
||||
|
||||
label {
|
||||
flex: 1 0 auto;
|
||||
|
||||
input[type="radio"] {
|
||||
margin: 3px 3px 0 0;
|
||||
}
|
||||
}
|
||||
|
||||
.section-header {
|
||||
height: 30px;
|
||||
padding: 0 6px 0 10px;
|
||||
background-color: var(--section-header-bg-color);
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
|
||||
> span {
|
||||
font-size: 1.2em;
|
||||
vertical-align: middle;
|
||||
color: var(--section-header-fg-color);
|
||||
}
|
||||
|
||||
&.toggleable {
|
||||
cursor: pointer;
|
||||
}
|
||||
}
|
||||
|
||||
.section-row {
|
||||
margin: 10px 5px 0;
|
||||
}
|
||||
|
||||
.section-label {
|
||||
display: block;
|
||||
margin: 0 0 5px 0;
|
||||
}
|
||||
|
||||
.section-block {
|
||||
display: block;
|
||||
}
|
||||
64
src/utils.ts
64
src/utils.ts
|
|
@ -1,3 +1,6 @@
|
|||
import { MicroUser, Post } from "./api/models";
|
||||
import { TagDetails } from "./models";
|
||||
|
||||
export function getUrl(root: string, ...parts: string[]): string {
|
||||
let url = root.replace(/\/+$/, "");
|
||||
for (const part of parts) {
|
||||
|
|
@ -16,3 +19,64 @@ export function encodeTagName(tagName: string) {
|
|||
export function getErrorMessage(ex: any) {
|
||||
return ex.description ?? ex.message ?? ex;
|
||||
}
|
||||
|
||||
export function emptyMicroUser(): MicroUser {
|
||||
return {
|
||||
name: "",
|
||||
avatarUrl: "",
|
||||
};
|
||||
}
|
||||
|
||||
export function emptyPost(): Post {
|
||||
return {
|
||||
id: 0,
|
||||
version: 0,
|
||||
creationTime: new Date(),
|
||||
lastEditTime: new Date(),
|
||||
safety: "safe",
|
||||
source: "",
|
||||
type: "",
|
||||
mimeType: "",
|
||||
checksum: "",
|
||||
fileSize: 0,
|
||||
canvasWidth: 0,
|
||||
canvasHeight: 0,
|
||||
contentUrl: "",
|
||||
thumbnailUrl: "",
|
||||
flags: [],
|
||||
tags: [],
|
||||
relations: [],
|
||||
user: emptyMicroUser(),
|
||||
score: 0,
|
||||
ownScore: 0,
|
||||
ownFavorite: false,
|
||||
tagCount: 0,
|
||||
favoriteCount: 0,
|
||||
commentCount: 0,
|
||||
noteCount: 0,
|
||||
relationCount: 0,
|
||||
featureCount: 0,
|
||||
lastFeatureTime: new Date(),
|
||||
favoritedBy: [],
|
||||
hasCustomThumbnail: false,
|
||||
notes: [],
|
||||
comments: [],
|
||||
};
|
||||
}
|
||||
|
||||
export function getTagClasses(tag: TagDetails): string[] {
|
||||
const classes: string[] = [];
|
||||
|
||||
if (tag.category && tag.category != "default") {
|
||||
classes.push("tag-" + tag.category);
|
||||
} else {
|
||||
classes.push("tag-general");
|
||||
}
|
||||
|
||||
return classes;
|
||||
}
|
||||
|
||||
export function breakTagName(tagName: string) {
|
||||
// Based on https://stackoverflow.com/a/6316913
|
||||
return tagName.replace(/_/g, "_<wbr>");
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue