From 6febea2cebb09ef5d707cdc1339a691f3082108b Mon Sep 17 00:00:00 2001 From: neobooru <50623835+neobooru@users.noreply.github.com> Date: Sun, 5 Feb 2023 16:45:28 +0100 Subject: [PATCH] Messaging improvements + more --- .eslintrc.cjs | 1 + src/background/main.ts | 105 ++++++++------- src/config.ts | 2 +- src/models/index.ts | 44 +++++-- src/options/{Options.vue => App.vue} | 21 ++- src/options/main.ts | 2 +- src/popup/{Popup.vue => App.vue} | 190 ++++++++++++++++++--------- src/popup/main.ts | 2 +- src/utils.ts | 5 + 9 files changed, 237 insertions(+), 135 deletions(-) rename src/options/{Options.vue => App.vue} (93%) rename src/popup/{Popup.vue => App.vue} (75%) diff --git a/.eslintrc.cjs b/.eslintrc.cjs index 2b682c8..e39f3e1 100644 --- a/.eslintrc.cjs +++ b/.eslintrc.cjs @@ -22,5 +22,6 @@ module.exports = { caughtErrorsIgnorePattern: "^_", }, ], + "@typescript-eslint/no-explicit-any": "off", }, }; diff --git a/src/background/main.ts b/src/background/main.ts index 197ed65..17585bb 100644 --- a/src/background/main.ts +++ b/src/background/main.ts @@ -1,6 +1,6 @@ -import { encodeTagName, getUrl } from "~/utils"; -import { BrowserCommand, Message, PostUploadCommandData } from "~/models"; -import { PostAlreadyUploadedError, SzuruError } from "~/api/models"; +import { encodeTagName, getErrorMessage } from "~/utils"; +import { BrowserCommand, PostUploadCommandData, PostUploadInfo, SetPostUploadInfoData, SetExactPostId } from "~/models"; +import { PostAlreadyUploadedError } from "~/api/models"; import SzurubooruApi from "~/api"; import { Config } from "~/config"; @@ -20,28 +20,32 @@ async function uploadPost(data: PostUploadCommandData) { 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")) - ); + // browser.runtime.sendMessage( + // new BrowserCommand("push_message", new Message("Selected instance not found in config!", "error")) + // ); return; } - const szuru = SzurubooruApi.createFromConfig(selectedSite); + const info: PostUploadInfo = { + state: "uploading", + }; try { + const szuru = SzurubooruApi.createFromConfig(selectedSite); + // 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( - 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, - // see https://stackoverflow.com/questions/8915845 - // uploadMsg.content = `Uploaded post`; - // uploadMsg.type = "success"; + const createdPost = await szuru.createPost(data.post); + + info.state = "uploaded"; + 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 // 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))); if (unsetCategoryTags.length != 0) { + info.updateTagsState = { + total: unsetCategoryTags.length, + }; 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 const query = unsetCategoryTags.map((x) => encodeTagName(x.names[0])).join(); const tags = (await szuru.getTags(query)).results; @@ -61,53 +69,50 @@ async function uploadPost(data: PostUploadCommandData) { let categoriesChangedCount = 0; for (const i in tags) { - browser.runtime.sendMessage(new BrowserCommand("pop_messages", 1)); + info.updateTagsState.current = parseInt(i); 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!; - if (existingCategories.some((x) => x.name == wantedCategory)) { - tags[i].category = wantedCategory; - await szuru.updateTag(tags[i]); - categoriesChangedCount++; - } else { - console.log( - `Not adding the '${wantedCategory}' category to the tag '${tags[i].names[0]}' because the szurubooru instance does not have this category.` - ); + const wantedCategory = tagsWithCategory.find((x) => tags[i].names.includes(x.name))?.category; + if (wantedCategory) { + if (existingCategories.some((x) => x.name == wantedCategory)) { + tags[i].category = wantedCategory; + await szuru.updateTag(tags[i]); + categoriesChangedCount++; + } else { + console.log( + `Not adding the '${wantedCategory}' category to the tag '${tags[i].names[0]}' because the szurubooru instance does not have this category.` + ); + } } } - browser.runtime.sendMessage(new BrowserCommand("pop_messages", 1)); - if (categoriesChangedCount > 0) { + info.updateTagsState.totalChanged = categoriesChangedCount; 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) { - browser.runtime.sendMessage(new BrowserCommand("pop_messages", 1)); - const error = ex as SzuruError; + if (ex.name && ex.name == "PostAlreadyUploadedError") { + 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 - if (error.name) { - console.error(error); - switch (error.name) { - case "PostAlreadyUploadedError": { - const otherPostId = (error as PostAlreadyUploadedError).otherPostId; - const url = getUrl(szuru.apiUrl.replace("api", ""), "post", otherPostId.toString()); - const msg = `Post already uploaded (${otherPostId})`; - 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; - } + // 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.post.id, info)) + ); } else { - console.error(ex); - browser.runtime.sendMessage(new BrowserCommand("push_message", new Message(ex.message, "error"))); + info.state = "error"; + info.error = getErrorMessage(ex); + browser.runtime.sendMessage( + new BrowserCommand("set_post_upload_info", new SetPostUploadInfoData(data.post.id, info)) + ); } } } diff --git a/src/config.ts b/src/config.ts index 2f72df9..c2f447d 100644 --- a/src/config.ts +++ b/src/config.ts @@ -14,7 +14,7 @@ export class Config { loadTagCounts = true; useContentTokens = true; sites: Array = []; - selectedSiteId: string | undefined = undefined; + selectedSiteId?: string; public async save() { await browser.storage.local.set({ diff --git a/src/models/index.ts b/src/models/index.ts index a2a2b33..016d6d1 100644 --- a/src/models/index.ts +++ b/src/models/index.ts @@ -1,5 +1,5 @@ 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 { public implications: TagDetails[] = []; @@ -26,6 +26,7 @@ export class TagDetails { } export class ScrapedPostDetails { + id = window.crypto.randomUUID(); name = ""; tags: TagDetails[] = []; notes: ScrapedNote[]; @@ -37,7 +38,8 @@ export class ScrapedPostDetails { source = ""; referrer?: string; resolution?: [number, number]; - reverseSearchResult: ImageSearchResult | undefined; + reverseSearchResult?: SimpleImageSearchResult; + uploadState?: PostUploadInfo; constructor(post: ScrapedPost) { 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 { constructor(public readonly id: number, public readonly percentage: number) {} } -export type MessageType = "error" | "info" | "success"; -export type MessageCategory = "none" | "persistent" | "find_similar"; +export type PostUploadState = "uploading" | "uploaded" | "error"; -export class Message { - id: string; - - constructor(public content: string, public level: MessageType = "info", public category: MessageCategory = "none") { - this.id = window.crypto.randomUUID(); - } +export class PostUploadInfo { + state: PostUploadState = "uploading"; + error?: string; + instancePostId?: number; + 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 { name: BrowserCommandName; @@ -82,3 +96,11 @@ export class BrowserCommand { export class PostUploadCommandData { 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) {} +} diff --git a/src/options/Options.vue b/src/options/App.vue similarity index 93% rename from src/options/Options.vue rename to src/options/App.vue index 9fc7abd..1819b4f 100644 --- a/src/options/Options.vue +++ b/src/options/App.vue @@ -2,6 +2,7 @@ import { useColorMode } from "@vueuse/core"; import SzuruWrapper from "~/api"; import { Config, SzuruSiteConfig } from "~/config"; +import { getErrorMessage } from "~/utils"; let autoSearchSimilar = ref(false); let loadTagCounts = ref(false); @@ -17,7 +18,7 @@ const selectedSite = computed(() => { } }); -type StatusType = "ok" | "error"; +type StatusType = "success" | "error"; async function testConnection() { if ( @@ -32,7 +33,7 @@ async function testConnection() { const api = new SzuruWrapper(selectedSite.value.domain, selectedSite.value.username, selectedSite.value.authToken); try { - const info = (await api.getInfo()); + const info = await api.getInfo(); const instanceName = info?.config.name; if (instanceName == undefined) { @@ -41,9 +42,7 @@ async function testConnection() { setStatus(`Connected to ${info.config.name} at ${selectedSite.value.domain}`); } } catch (ex) { - // TODO: This error message is not very descriptive. - console.dir(ex); - setStatus("Couldn't connect to " + selectedSite.value.domain + "\n\n" + ex, "error"); + setStatus(`Couldn't connect to ${selectedSite.value.domain}. ${getErrorMessage(ex)}`, "error"); } } @@ -62,7 +61,7 @@ async function saveSettings() { setStatus("Settings successfully saved"); } -function setStatus(text: string, type: StatusType = "ok") { +function setStatus(text: string, type: StatusType = "success") { statusText.value = text; statusType.value = "status-" + type; } @@ -197,6 +196,8 @@ let mode = useColorMode({ emitAuto: true });
+ {{ statusText }} +
@@ -243,6 +244,14 @@ html.dark .content-wrapper { line-height: 120%; } +.status-error { + color: red; +} + +.status-success { + color: green; +} + label { display: block; padding: 0.3em 0; diff --git a/src/options/main.ts b/src/options/main.ts index aff9403..18addf6 100644 --- a/src/options/main.ts +++ b/src/options/main.ts @@ -1,5 +1,5 @@ import { createApp } from "vue"; -import App from "./Options.vue"; +import App from "./App.vue"; import { setupApp } from "~/logic/common-setup"; import "../styles"; diff --git a/src/popup/Popup.vue b/src/popup/App.vue similarity index 75% rename from src/popup/Popup.vue rename to src/popup/App.vue index 5a44f6e..e9ad6ca 100644 --- a/src/popup/Popup.vue +++ b/src/popup/App.vue @@ -1,27 +1,28 @@