Messaging improvements + more

next
neobooru 2023-02-05 16:45:28 +01:00
parent b07cf788c9
commit 6febea2ceb
9 changed files with 237 additions and 135 deletions

View File

@ -22,5 +22,6 @@ module.exports = {
caughtErrorsIgnorePattern: "^_", caughtErrorsIgnorePattern: "^_",
}, },
], ],
"@typescript-eslint/no-explicit-any": "off",
}, },
}; };

View File

@ -1,6 +1,6 @@
import { encodeTagName, getUrl } from "~/utils"; import { encodeTagName, getErrorMessage } from "~/utils";
import { BrowserCommand, Message, PostUploadCommandData } from "~/models"; import { BrowserCommand, PostUploadCommandData, PostUploadInfo, SetPostUploadInfoData, SetExactPostId } from "~/models";
import { PostAlreadyUploadedError, SzuruError } from "~/api/models"; import { PostAlreadyUploadedError } from "~/api/models";
import SzurubooruApi from "~/api"; import SzurubooruApi from "~/api";
import { Config } from "~/config"; import { Config } from "~/config";
@ -20,28 +20,32 @@ async function uploadPost(data: PostUploadCommandData) {
if (!selectedSite) { if (!selectedSite) {
// TODO: Generic error handler which also shows the message in the popup frontend. // TODO: Generic error handler which also shows the message in the popup frontend.
browser.runtime.sendMessage( // browser.runtime.sendMessage(
new BrowserCommand("push_message", new Message("Selected instance not found in config!", "error")) // new BrowserCommand("push_message", new Message("Selected instance not found in config!", "error"))
); // );
return; return;
} }
const szuru = SzurubooruApi.createFromConfig(selectedSite); const info: PostUploadInfo = {
state: "uploading",
};
try { try {
const szuru = SzurubooruApi.createFromConfig(selectedSite);
// Create and upload post // Create and upload post
browser.runtime.sendMessage(new BrowserCommand("pop_messages", 10));
browser.runtime.sendMessage(new BrowserCommand("push_message", new Message("Uploading...")));
const createdPost = await szuru.createPost(data.post);
browser.runtime.sendMessage(new BrowserCommand("pop_messages", 1));
browser.runtime.sendMessage( browser.runtime.sendMessage(
new BrowserCommand("push_message", new Message("Uploaded post " + createdPost.id, "success")) new BrowserCommand("set_post_upload_info", new SetPostUploadInfoData(data.post.id, info))
); );
// TODO: Clicking a link doesn't actually open it in a new tab, const createdPost = await szuru.createPost(data.post);
// see https://stackoverflow.com/questions/8915845
// uploadMsg.content = `<a href='${this.getPostUrl(createdPost)}' target='_blank'>Uploaded post</a>`; info.state = "uploaded";
// uploadMsg.type = "success"; info.instancePostId = createdPost.id;
browser.runtime.sendMessage(
new BrowserCommand("set_post_upload_info", new SetPostUploadInfoData(data.post.id, info))
);
// Find tags with "default" category and update it // Find tags with "default" category and update it
// TODO: Make all these categories configurable // TODO: Make all these categories configurable
@ -51,9 +55,13 @@ async function uploadPost(data: PostUploadCommandData) {
.filter((x) => tagsWithCategory.some((y) => x.names.includes(y.name))); .filter((x) => tagsWithCategory.some((y) => x.names.includes(y.name)));
if (unsetCategoryTags.length != 0) { if (unsetCategoryTags.length != 0) {
info.updateTagsState = {
total: unsetCategoryTags.length,
};
browser.runtime.sendMessage( browser.runtime.sendMessage(
new BrowserCommand("push_message", new Message(`${unsetCategoryTags.length} tags need a different category`)) new BrowserCommand("set_post_upload_info", new SetPostUploadInfoData(data.post.id, info))
); );
// unsetCategoryTags is of type MicroTag[] and we need a Tag resource to update it, so let's get those // unsetCategoryTags is of type MicroTag[] and we need a Tag resource to update it, so let's get those
const query = unsetCategoryTags.map((x) => encodeTagName(x.names[0])).join(); const query = unsetCategoryTags.map((x) => encodeTagName(x.names[0])).join();
const tags = (await szuru.getTags(query)).results; const tags = (await szuru.getTags(query)).results;
@ -61,53 +69,50 @@ async function uploadPost(data: PostUploadCommandData) {
let categoriesChangedCount = 0; let categoriesChangedCount = 0;
for (const i in tags) { for (const i in tags) {
browser.runtime.sendMessage(new BrowserCommand("pop_messages", 1)); info.updateTagsState.current = parseInt(i);
browser.runtime.sendMessage( browser.runtime.sendMessage(
new BrowserCommand("push_message", new Message(`Updating tag ${i}/${unsetCategoryTags.length}`)) new BrowserCommand("set_post_upload_info", new SetPostUploadInfoData(data.post.id, info))
); );
const wantedCategory = tagsWithCategory.find((x) => tags[i].names.includes(x.name))!.category!; const wantedCategory = tagsWithCategory.find((x) => tags[i].names.includes(x.name))?.category;
if (existingCategories.some((x) => x.name == wantedCategory)) { if (wantedCategory) {
tags[i].category = wantedCategory; if (existingCategories.some((x) => x.name == wantedCategory)) {
await szuru.updateTag(tags[i]); tags[i].category = wantedCategory;
categoriesChangedCount++; await szuru.updateTag(tags[i]);
} else { categoriesChangedCount++;
console.log( } else {
`Not adding the '${wantedCategory}' category to the tag '${tags[i].names[0]}' because the szurubooru instance does not have this category.` console.log(
); `Not adding the '${wantedCategory}' category to the tag '${tags[i].names[0]}' because the szurubooru instance does not have this category.`
);
}
} }
} }
browser.runtime.sendMessage(new BrowserCommand("pop_messages", 1));
if (categoriesChangedCount > 0) { if (categoriesChangedCount > 0) {
info.updateTagsState.totalChanged = categoriesChangedCount;
browser.runtime.sendMessage( browser.runtime.sendMessage(
new BrowserCommand("push_message", new Message(`Updated ${categoriesChangedCount} tags`, "success")) new BrowserCommand("set_post_upload_info", new SetPostUploadInfoData(data.post.id, info))
); );
} }
} }
} catch (ex: any) { } catch (ex: any) {
browser.runtime.sendMessage(new BrowserCommand("pop_messages", 1)); if (ex.name && ex.name == "PostAlreadyUploadedError") {
const error = ex as SzuruError; const otherPostId = (ex as PostAlreadyUploadedError).otherPostId;
browser.runtime.sendMessage(
new BrowserCommand("set_exact_post_id", new SetExactPostId(data.post.id, otherPostId))
);
// TODO: Actual good error handling/messaging // No error message, because we have a different message for posts that are already uploaded.
if (error.name) { info.state = "error";
console.error(error); browser.runtime.sendMessage(
switch (error.name) { new BrowserCommand("set_post_upload_info", new SetPostUploadInfoData(data.post.id, info))
case "PostAlreadyUploadedError": { );
const otherPostId = (error as PostAlreadyUploadedError).otherPostId;
const url = getUrl(szuru.apiUrl.replace("api", ""), "post", otherPostId.toString());
const msg = `<a href='${url}' target='_blank'>Post already uploaded (${otherPostId})</a>`;
browser.runtime.sendMessage(new BrowserCommand("push_message", new Message(msg, "error")));
break;
}
default:
browser.runtime.sendMessage(new BrowserCommand("push_message", new Message(ex?.message ?? ex, "error")));
break;
}
} else { } else {
console.error(ex); info.state = "error";
browser.runtime.sendMessage(new BrowserCommand("push_message", new Message(ex.message, "error"))); info.error = getErrorMessage(ex);
browser.runtime.sendMessage(
new BrowserCommand("set_post_upload_info", new SetPostUploadInfoData(data.post.id, info))
);
} }
} }
} }

View File

@ -14,7 +14,7 @@ export class Config {
loadTagCounts = true; loadTagCounts = true;
useContentTokens = true; useContentTokens = true;
sites: Array<SzuruSiteConfig> = []; sites: Array<SzuruSiteConfig> = [];
selectedSiteId: string | undefined = undefined; selectedSiteId?: string;
public async save() { public async save() {
await browser.storage.local.set({ await browser.storage.local.set({

View File

@ -1,5 +1,5 @@
import { BooruTypes, ContentType, ScrapedNote, ScrapedPost, ScrapedTag } from "neo-scraper"; import { BooruTypes, ContentType, ScrapedNote, ScrapedPost, ScrapedTag } from "neo-scraper";
import { ImageSearchResult, MicroTag, Tag } from "~/api/models"; import { MicroTag, Tag } from "~/api/models";
export class TagDetails { export class TagDetails {
public implications: TagDetails[] = []; public implications: TagDetails[] = [];
@ -26,6 +26,7 @@ export class TagDetails {
} }
export class ScrapedPostDetails { export class ScrapedPostDetails {
id = window.crypto.randomUUID();
name = ""; name = "";
tags: TagDetails[] = []; tags: TagDetails[] = [];
notes: ScrapedNote[]; notes: ScrapedNote[];
@ -37,7 +38,8 @@ export class ScrapedPostDetails {
source = ""; source = "";
referrer?: string; referrer?: string;
resolution?: [number, number]; resolution?: [number, number];
reverseSearchResult: ImageSearchResult | undefined; reverseSearchResult?: SimpleImageSearchResult;
uploadState?: PostUploadInfo;
constructor(post: ScrapedPost) { constructor(post: ScrapedPost) {
this.contentUrl = post.contentUrl; this.contentUrl = post.contentUrl;
@ -52,22 +54,34 @@ export class ScrapedPostDetails {
} }
} }
export interface SimpleImageSearchResult {
exactPostId?: number;
similarPosts: SimpleSimilarPost[];
}
export interface SimpleSimilarPost {
distance: number;
postId: number;
}
export class SimilarPostInfo { export class SimilarPostInfo {
constructor(public readonly id: number, public readonly percentage: number) {} constructor(public readonly id: number, public readonly percentage: number) {}
} }
export type MessageType = "error" | "info" | "success"; export type PostUploadState = "uploading" | "uploaded" | "error";
export type MessageCategory = "none" | "persistent" | "find_similar";
export class Message { export class PostUploadInfo {
id: string; state: PostUploadState = "uploading";
error?: string;
constructor(public content: string, public level: MessageType = "info", public category: MessageCategory = "none") { instancePostId?: number;
this.id = window.crypto.randomUUID(); updateTagsState?: {
} total: number;
current?: number;
totalChanged?: number;
};
} }
export type BrowserCommandName = "grab_post" | "upload_post" | "push_message" | "pop_messages"; export type BrowserCommandName = "grab_post" | "upload_post" | "set_post_upload_info" | "set_exact_post_id";
export class BrowserCommand<T = any> { export class BrowserCommand<T = any> {
name: BrowserCommandName; name: BrowserCommandName;
@ -82,3 +96,11 @@ export class BrowserCommand<T = any> {
export class PostUploadCommandData { export class PostUploadCommandData {
constructor(public readonly post: ScrapedPostDetails, public readonly siteId: string) {} constructor(public readonly post: ScrapedPostDetails, public readonly siteId: string) {}
} }
export class SetPostUploadInfoData {
constructor(public readonly postId: string, public readonly info: PostUploadInfo) {}
}
export class SetExactPostId {
constructor(public readonly postId: string, public readonly exactPostId: number) {}
}

View File

@ -2,6 +2,7 @@
import { useColorMode } from "@vueuse/core"; import { useColorMode } from "@vueuse/core";
import SzuruWrapper from "~/api"; import SzuruWrapper from "~/api";
import { Config, SzuruSiteConfig } from "~/config"; import { Config, SzuruSiteConfig } from "~/config";
import { getErrorMessage } from "~/utils";
let autoSearchSimilar = ref(false); let autoSearchSimilar = ref(false);
let loadTagCounts = ref(false); let loadTagCounts = ref(false);
@ -17,7 +18,7 @@ const selectedSite = computed(() => {
} }
}); });
type StatusType = "ok" | "error"; type StatusType = "success" | "error";
async function testConnection() { async function testConnection() {
if ( if (
@ -32,7 +33,7 @@ async function testConnection() {
const api = new SzuruWrapper(selectedSite.value.domain, selectedSite.value.username, selectedSite.value.authToken); const api = new SzuruWrapper(selectedSite.value.domain, selectedSite.value.username, selectedSite.value.authToken);
try { try {
const info = (await api.getInfo()); const info = await api.getInfo();
const instanceName = info?.config.name; const instanceName = info?.config.name;
if (instanceName == undefined) { if (instanceName == undefined) {
@ -41,9 +42,7 @@ async function testConnection() {
setStatus(`Connected to ${info.config.name} at ${selectedSite.value.domain}`); setStatus(`Connected to ${info.config.name} at ${selectedSite.value.domain}`);
} }
} catch (ex) { } catch (ex) {
// TODO: This error message is not very descriptive. setStatus(`Couldn't connect to ${selectedSite.value.domain}. ${getErrorMessage(ex)}`, "error");
console.dir(ex);
setStatus("Couldn't connect to " + selectedSite.value.domain + "\n\n" + ex, "error");
} }
} }
@ -62,7 +61,7 @@ async function saveSettings() {
setStatus("Settings successfully saved"); setStatus("Settings successfully saved");
} }
function setStatus(text: string, type: StatusType = "ok") { function setStatus(text: string, type: StatusType = "success") {
statusText.value = text; statusText.value = text;
statusType.value = "status-" + type; statusType.value = "status-" + type;
} }
@ -197,6 +196,8 @@ let mode = useColorMode({ emitAuto: true });
</div> </div>
<div class="flex-fit flex justify-end gap-1"> <div class="flex-fit flex justify-end gap-1">
<span class="status self-center" style="margin-right: auto" :class="statusType">{{ statusText }}</span>
<button @click="testConnection">Test connection</button> <button @click="testConnection">Test connection</button>
<button @click="saveSettings" class="primary">Save settings</button> <button @click="saveSettings" class="primary">Save settings</button>
</div> </div>
@ -243,6 +244,14 @@ html.dark .content-wrapper {
line-height: 120%; line-height: 120%;
} }
.status-error {
color: red;
}
.status-success {
color: green;
}
label { label {
display: block; display: block;
padding: 0.3em 0; padding: 0.3em 0;

View File

@ -1,5 +1,5 @@
import { createApp } from "vue"; import { createApp } from "vue";
import App from "./Options.vue"; import App from "./App.vue";
import { setupApp } from "~/logic/common-setup"; import { setupApp } from "~/logic/common-setup";
import "../styles"; import "../styles";

View File

@ -1,27 +1,28 @@
<script setup lang="ts"> <script setup lang="ts">
import { useDark } from "@vueuse/core"; import { useDark } from "@vueuse/core";
import axios, { CancelTokenSource } from "axios"; import axios, { CancelTokenSource } from "axios";
import { ScrapedPost, ScrapeResults } from "neo-scraper"; import { ScrapeResults } from "neo-scraper";
import { getUrl, encodeTagName } from "~/utils"; import { getUrl, encodeTagName, getErrorMessage } from "~/utils";
import { import {
BrowserCommand, BrowserCommand,
Message,
ScrapedPostDetails, ScrapedPostDetails,
TagDetails, TagDetails,
PostUploadCommandData, PostUploadCommandData,
SimilarPostInfo, SimilarPostInfo,
SetPostUploadInfoData,
SetExactPostId,
SimpleSimilarPost,
SimpleImageSearchResult,
} from "~/models"; } from "~/models";
import SzuruWrapper from "~/api"; import SzuruWrapper from "~/api";
import { ImageSearchResult } from "~/api/models"; import { ImageSearchResult } from "~/api/models";
import { isChrome } from "~/env"; import { isChrome } from "~/env";
import { Runtime, WebRequest } from "webextension-polyfill"; import { Runtime, WebRequest } from "webextension-polyfill";
import { Ref } from "vue";
import { Config } from "~/config"; import { Config } from "~/config";
let config = new Config(); let config = new Config();
let posts = reactive([] as ScrapedPostDetails[]); let posts = reactive([] as ScrapedPostDetails[]);
let selectedPost = ref(new ScrapedPostDetails(new ScrapedPost())); let selectedPostId = ref<string | undefined>(undefined);
let messages = reactive<Message[]>([]);
let addTagInput = ref(""); let addTagInput = ref("");
let autocompleteShown = ref(false); let autocompleteShown = ref(false);
let autocompleteTags = ref<TagDetails[]>([]); let autocompleteTags = ref<TagDetails[]>([]);
@ -37,12 +38,19 @@ const activeSite = computed(() => {
} }
}); });
const selectedPost = computed(() => {
if (selectedPostId.value) {
return posts.find((x) => x.id == selectedPostId.value);
}
});
const szuru = computed(() => { const szuru = computed(() => {
return activeSite.value ? SzuruWrapper.createFromConfig(activeSite.value) : undefined; return activeSite.value ? SzuruWrapper.createFromConfig(activeSite.value) : undefined;
}); });
watch(selectedPost, () => { watch(selectedPostId, () => {
findSimilar(selectedPost); let selectedPost = posts.find((x) => x.id == selectedPostId.value);
if (selectedPost) findSimilar(selectedPost);
}); });
watch(selectedSiteId, async (x) => { watch(selectedSiteId, async (x) => {
@ -99,7 +107,7 @@ async function grabPost() {
} }
if (posts.length > 0) { if (posts.length > 0) {
selectedPost.value = posts[0]; selectedPostId.value = posts[0].id;
if (config?.loadTagCounts) { if (config?.loadTagCounts) {
loadTagCounts(); loadTagCounts();
} }
@ -111,9 +119,8 @@ async function grabPost() {
async function upload() { async function upload() {
if (!selectedSiteId.value) return; if (!selectedSiteId.value) return;
window.scrollTo(0, 0); // Don't try to upload if an exact copy is already on the server.
if (selectedPost.value?.reverseSearchResult?.exactPostId) return;
// Outsource to background.ts
// TODO: Terrible code. // TODO: Terrible code.
const post = JSON.parse(JSON.stringify(selectedPost.value)); const post = JSON.parse(JSON.stringify(selectedPost.value));
@ -156,44 +163,29 @@ function removeTag(tag: TagDetails) {
} }
} }
function getMessageClasses(message: Message) {
let classes: string[] = [];
switch (message.level) {
case "error":
classes.push("bg-danger");
break;
case "success":
classes.push("bg-success");
break;
}
return classes;
}
function getActiveSitePostUrl(postId: number): string { function getActiveSitePostUrl(postId: number): string {
if (!activeSite.value) return ""; if (!activeSite.value) return "";
return getUrl(activeSite.value.domain, "post", postId.toString()); return getUrl(activeSite.value.domain, "post", postId.toString());
} }
function getSimilarPosts(data: ImageSearchResult | undefined): SimilarPostInfo[] { function getSimilarPosts(data?: SimpleImageSearchResult): SimilarPostInfo[] {
if (!data) return []; if (!data) return [];
const lst: SimilarPostInfo[] = []; const lst: SimilarPostInfo[] = [];
for (const similarPost of data.similarPosts) { for (const similarPost of data.similarPosts) {
if (data.exactPost && data.exactPost.id == similarPost.post.id) { if (data.exactPostId == similarPost.postId) {
continue; continue;
} }
lst.push(new SimilarPostInfo(similarPost.post.id, Math.round(100 - similarPost.distance * 100))); lst.push(new SimilarPostInfo(similarPost.postId, Math.round(100 - similarPost.distance * 100)));
} }
return lst; return lst;
} }
function addTag(tag: TagDetails) { function addTag(tag: TagDetails) {
if (selectedPost) { if (selectedPost.value) {
// Only add tag if it doesn't already exist // Only add tag if it doesn't already exist
if (tag.name.length > 0 && selectedPost.value.tags.find((x) => x.name == tag.name) == undefined) { if (tag.name.length > 0 && selectedPost.value.tags.find((x) => x.name == tag.name) == undefined) {
selectedPost.value.tags.push(tag); selectedPost.value.tags.push(tag);
@ -205,14 +197,15 @@ function addTag(tag: TagDetails) {
} }
async function clickFindSimilar() { async function clickFindSimilar() {
return await findSimilar(selectedPost); let selectedPost = posts.find((x) => x.id == selectedPostId.value);
if (selectedPost) return await findSimilar(selectedPost);
} }
async function findSimilar(post: Ref<ScrapedPostDetails | undefined>) { async function findSimilar(post: ScrapedPostDetails | undefined) {
if (!post.value || !szuru.value) return; if (!post || !szuru.value) return;
// Don't load this again if it is already loaded. // Don't load this again if it is already loaded.
if (post.value.reverseSearchResult) return; if (post.reverseSearchResult) return;
isSearchingForSimilarPosts.value = true; isSearchingForSimilarPosts.value = true;
@ -220,19 +213,22 @@ async function findSimilar(post: Ref<ScrapedPostDetails | undefined>) {
let res: ImageSearchResult | undefined; let res: ImageSearchResult | undefined;
if (config.useContentTokens) { if (config.useContentTokens) {
let tmpRes = await szuru.value.uploadTempFile(post.value.contentUrl); let tmpRes = await szuru.value.uploadTempFile(post.contentUrl);
// TODO: Error handling? // TODO: Error handling?
// Save contentToken in PostViewModel so that we can reuse it when creating/uploading the post. // Save contentToken in PostViewModel so that we can reuse it when creating/uploading the post.
post.value.contentToken = tmpRes.token; post.contentToken = tmpRes.token;
res = await szuru.value.reverseSearchToken(tmpRes.token); res = await szuru.value.reverseSearchToken(tmpRes.token);
} else { } else {
res = await szuru.value.reverseSearch(post.value.contentUrl); res = await szuru.value.reverseSearch(post.contentUrl);
} }
post.value.reverseSearchResult = res; post.reverseSearchResult = {
} catch (ex) { exactPostId: res.exactPost?.id,
genericError.value = "Couldn't reverse search"; similarPosts: res.similarPosts.map((x) => <SimpleSimilarPost>{ postId: x.post.id, distance: x.distance }),
};
} catch (ex: any) {
genericError.value = "Couldn't reverse search. " + getErrorMessage(ex);
} }
isSearchingForSimilarPosts.value = false; isSearchingForSimilarPosts.value = false;
@ -350,19 +346,34 @@ async function autocompletePopulator(input: string) {
} }
} }
// Could people would use https://kazupon.github.io/vue-i18n/guide/pluralization.html
function getUpdatedTagsText(count: number) {
return `Updated ${count} tag${count > 1 ? "s" : ""}`;
}
onMounted(async () => { onMounted(async () => {
config = await Config.load(); config = await Config.load();
selectedSiteId.value = config.selectedSiteId; selectedSiteId.value = config.selectedSiteId;
browser.runtime.onMessage.addListener((cmd: BrowserCommand, _sender: Runtime.MessageSender) => { browser.runtime.onMessage.addListener((cmd: BrowserCommand, _sender: Runtime.MessageSender) => {
switch (cmd.name) { switch (cmd.name) {
// TODO: Replace with set_upload_state (or something like that) case "set_post_upload_info":
case "push_message": {
messages.push(cmd.data); const data = <SetPostUploadInfoData>cmd.data;
let post = posts.find((x) => x.id == data.postId);
if (post) post.uploadState = data.info;
}
break; break;
case "pop_messages": case "set_exact_post_id":
for (let i = 0; i < cmd.data; i++) { {
messages.pop(); const { postId, exactPostId } = <SetExactPostId>cmd.data;
let post = posts.find((x) => x.id == postId);
if (post) {
if (!post.reverseSearchResult) {
post.reverseSearchResult = { exactPostId, similarPosts: [] };
}
post.reverseSearchResult.exactPostId = exactPostId;
}
} }
break; break;
} }
@ -378,7 +389,7 @@ onMounted(async () => {
// This will probably stop working in Chrome sometime in 2023 due to the Manifest V3 webRequestBlocking bullshit. // This will probably stop working in Chrome sometime in 2023 due to the Manifest V3 webRequestBlocking bullshit.
// Firefox users should be fine. // Firefox users should be fine.
browser.webRequest.onBeforeSendHeaders.addListener( browser.webRequest.onBeforeSendHeaders.addListener(
(details: WebRequest.OnBeforeSendHeadersDetailsType) => { (details: WebRequest.OnBeforeSendHeadersDetailsType): WebRequest.BlockingResponse => {
let requestHeaders = details.requestHeaders ?? []; let requestHeaders = details.requestHeaders ?? [];
// Find which ScrapedPost this belongs to, if any. // Find which ScrapedPost this belongs to, if any.
@ -390,7 +401,7 @@ onMounted(async () => {
requestHeaders.push({ name: "Referer", value: post.referrer }); requestHeaders.push({ name: "Referer", value: post.referrer });
} }
return <WebRequest.BlockingResponse>{ return {
requestHeaders, requestHeaders,
}; };
}, },
@ -416,33 +427,80 @@ useDark();
<li v-if="!activeSite" class="bg-danger">No target server selected!</li> <li v-if="!activeSite" class="bg-danger">No target server selected!</li>
<li v-if="selectedPost.reverseSearchResult?.exactPost" class="bg-danger"> <li v-if="selectedPost?.reverseSearchResult?.exactPostId" class="bg-danger">
<a :href="getActiveSitePostUrl(selectedPost.reverseSearchResult?.exactPost.id)" <a :href="getActiveSitePostUrl(selectedPost.reverseSearchResult?.exactPostId)"
>Post already uploaded ({{ selectedPost.reverseSearchResult.exactPost.id }})</a >Post already uploaded ({{ selectedPost.reverseSearchResult.exactPostId }})</a
> >
</li> </li>
<!-- Only show error when it's not undefined and not empty. -->
<li v-if="selectedPost?.uploadState?.error?.length" class="bg-danger">
{{ selectedPost.uploadState.error }}
</li>
<li v-if="genericError" class="bg-danger">{{ genericError }}</li> <li v-if="genericError" class="bg-danger">{{ 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="selectedPost?.uploadState?.state == 'uploaded' && selectedPost?.uploadState.instancePostId"
class="bg-success"
>
<a :href="getActiveSitePostUrl(selectedPost.uploadState.instancePostId)"
>Uploaded post {{ selectedPost.uploadState.instancePostId }}</a
>
</li>
<li v-if="selectedPost?.uploadState?.updateTagsState?.totalChanged" class="bg-success">
{{ getUpdatedTagsText(selectedPost.uploadState?.updateTagsState?.totalChanged) }}
</li>
<!-- <!--
Info messages Info messages
--> -->
<li v-if="isSearchingForSimilarPosts">Searching for similar posts...</li> <li v-if="selectedPost?.uploadState?.state == 'uploading'">Uploading...</li>
<li v-if="selectedPost.reverseSearchResult?.similarPosts.length == 0">No similar posts found</li> <li
v-if="
selectedPost?.uploadState?.updateTagsState?.total &&
selectedPost.uploadState?.updateTagsState?.current == undefined
"
>
{{ selectedPost.uploadState?.updateTagsState?.total }} tags need a different category
</li>
<li v-for="similarPost in getSimilarPosts(selectedPost.reverseSearchResult)" :key="similarPost.id"> <li
v-if="
selectedPost?.uploadState?.updateTagsState?.current &&
selectedPost?.uploadState?.updateTagsState?.totalChanged == undefined
"
>
Updating tag {{ selectedPost.uploadState?.updateTagsState?.current }}/{{
selectedPost.uploadState?.updateTagsState?.total
}}
</li>
<li v-if="isSearchingForSimilarPosts && selectedPost?.uploadState == undefined">
Searching for similar posts...
</li>
<li v-if="selectedPost?.reverseSearchResult?.similarPosts.length == 0 && selectedPost.uploadState == undefined">
No similar posts found
</li>
<li v-for="similarPost in getSimilarPosts(selectedPost?.reverseSearchResult)" :key="similarPost.id">
<a :href="getActiveSitePostUrl(similarPost.id)" <a :href="getActiveSitePostUrl(similarPost.id)"
>Post {{ similarPost.id }} looks {{ similarPost.percentage }}% similar</a >Post {{ similarPost.id }} looks {{ similarPost.percentage }}% similar</a
> >
</li> </li>
<li v-for="msg in messages" :key="msg.content" :class="getMessageClasses(msg)" v-html="msg.content"></li>
</ul> </ul>
</div> </div>
<div class="popup-columns"> <div v-if="selectedPost" class="popup-columns">
<div class="popup-left"> <div class="popup-left">
<div class="popup-section"> <div class="popup-section">
<div class="section-header"> <div class="section-header">
@ -451,7 +509,7 @@ useDark();
<font-awesome-icon icon="fa-solid fa-cog" class="cursor-pointer" @click="openOptionsPage" /> <font-awesome-icon icon="fa-solid fa-cog" class="cursor-pointer" @click="openOptionsPage" />
</div> </div>
<div class="section-row" v-if="selectedPost.resolution != undefined"> <div class="section-row" v-if="selectedPost?.resolution">
<ul class="compact"> <ul class="compact">
<li>Resolution: {{ resolutionToString(selectedPost.resolution) }}</li> <li>Resolution: {{ resolutionToString(selectedPost.resolution) }}</li>
</ul> </ul>
@ -463,19 +521,16 @@ useDark();
<div style="display: flex; gap: 10px"> <div style="display: flex; gap: 10px">
<label> <label>
<input type="radio" value="safe" v-model="selectedPost.rating" /> <input type="radio" value="safe" v-model="selectedPost.rating" />
<span class="checkmark"></span>
Safe Safe
</label> </label>
<label> <label>
<input type="radio" value="sketchy" v-model="selectedPost.rating" /> <input type="radio" value="sketchy" v-model="selectedPost.rating" />
<span class="checkmark"></span>
Sketchy Sketchy
</label> </label>
<label> <label>
<input type="radio" value="unsafe" v-model="selectedPost.rating" /> <input type="radio" value="unsafe" v-model="selectedPost.rating" />
<span class="checkmark"></span>
Unsafe Unsafe
</label> </label>
</div> </div>
@ -483,7 +538,7 @@ useDark();
<div class="section-row"> <div class="section-row">
<span class="section-label">Source</span> <span class="section-label">Source</span>
<textarea v-model="selectedPost.source" /> <textarea v-model="selectedPost.source"></textarea>
</div> </div>
</div> </div>
@ -545,8 +600,8 @@ useDark();
<div class="popup-right"> <div class="popup-right">
<div class="popup-section"> <div class="popup-section">
<select v-model="selectedPost"> <select v-model="selectedPostId">
<option v-for="post in posts" v-bind:key="post.name" v-bind:value="post">{{ post.name }}</option> <option v-for="post in posts" :key="post.id" :value="post.id">{{ post.name }}</option>
</select> </select>
</div> </div>
@ -570,6 +625,11 @@ useDark();
</div> </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>
</div> </div>
</template> </template>

View File

@ -1,5 +1,5 @@
import { createApp } from "vue"; import { createApp } from "vue";
import App from "./Popup.vue"; import App from "./App.vue";
import { setupApp } from "~/logic/common-setup"; import { setupApp } from "~/logic/common-setup";
import { isChrome } from "~/env"; import { isChrome } from "~/env";

View File

@ -11,3 +11,8 @@ export function encodeTagName(tagName: string) {
// Searching for posts with re\:zero will show posts tagged with re:zero. // Searching for posts with re\:zero will show posts tagged with re:zero.
return tagName.replace(/:/g, "\\:"); return tagName.replace(/:/g, "\\:");
} }
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function getErrorMessage(ex: any) {
return ex.description ?? ex.message ?? ex;
}