Import posts in the background (#9)

pull/10/head
neobooru 2020-05-12 19:02:56 +02:00 committed by GitHub
parent af83ce454e
commit 864523392e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
10 changed files with 1558 additions and 1608 deletions

2602
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
{ {
"name": "szuru-chrome", "name": "szuru-chrome",
"version": "0.2.4", "version": "0.3.0",
"description": "Import media from various sites into szurubooru", "description": "Import media from various sites into szurubooru",
"author": "neobooru", "author": "neobooru",
"license": "MIT", "license": "MIT",
@ -12,31 +12,31 @@
"watch:dev": "cross-env HMR=true npm run build:dev -- --watch" "watch:dev": "cross-env HMR=true npm run build:dev -- --watch"
}, },
"dependencies": { "dependencies": {
"axios": "^0.19.0", "axios": "^0.19.2",
"neo-scraper": "^0.2.3", "neo-scraper": "^0.2.3",
"ts-optchain": "^0.1.8", "ts-optchain": "^0.1.8",
"vue": "^2.6.10", "vue": "^2.6.11",
"webextension-polyfill": "^0.3.1" "webextension-polyfill": "^0.3.1"
}, },
"devDependencies": { "devDependencies": {
"archiver": "^3.1.1", "archiver": "^3.1.1",
"copy-webpack-plugin": "^5.1.1", "copy-webpack-plugin": "^5.1.1",
"core-js": "^3.0.1", "core-js": "^3.6.5",
"cross-env": "^5.2.0", "cross-env": "^5.2.1",
"css-loader": "^2.1.1", "css-loader": "^2.1.1",
"ejs": "^2.6.1", "ejs": "^2.7.4",
"file-loader": "^1.1.11", "file-loader": "^1.1.11",
"mini-css-extract-plugin": "^0.4.4", "mini-css-extract-plugin": "^0.4.4",
"node-sass": "^4.13.1", "node-sass": "^4.14.1",
"sass-loader": "^7.1.0", "sass-loader": "^7.3.1",
"ts-loader": "^6.0.4", "ts-loader": "^6.2.2",
"typescript": "^3.5.3", "typescript": "^3.8.3",
"vue-loader": "^15.4.2", "vue-loader": "^15.9.2",
"vue-template-compiler": "^2.6.10", "vue-template-compiler": "^2.6.11",
"web-ext-types": "^2.1.0", "web-ext-types": "^2.1.0",
"webextension-polyfill-ts": "^0.9.1", "webextension-polyfill-ts": "^0.9.1",
"webpack": "^4.39.1", "webpack": "^4.43.0",
"webpack-cli": "^3.1.2", "webpack-cli": "^3.3.11",
"webpack-extension-reloader": "^1.1.0" "webpack-extension-reloader": "^1.1.4"
} }
} }

24
src/Common.ts Normal file
View File

@ -0,0 +1,24 @@
export type BrowserCommandName = "grab_post" | "upload_post" | "push_message" | "remove_messages";
export type MessageType = "error" | "info" | "success";
export class BrowserCommand {
name: BrowserCommandName;
data: any;
constructor(name: BrowserCommandName, data: any = null) {
this.name = name;
this.data = data;
}
}
export class Message {
content: string;
level: MessageType;
category: string;
constructor(content: string, level: MessageType = "info", category: string | null = null) {
this.content = content;
this.level = level;
this.category = category ?? "none";
}
}

View File

@ -23,7 +23,7 @@ button.primary {
input[type="text"] { input[type="text"] {
background-color: #fafafa; background-color: #fafafa;
border: 1px solid #eee; border: 1px solid #eee;
height: 30px; height: 26px;
width: 100%; width: 100%;
} }
@ -41,7 +41,6 @@ select {
border: 1px solid #eee; border: 1px solid #eee;
height: 30px; height: 30px;
width: 100%; width: 100%;
font-family: "Open Sans", sans-serif;
} }
.compact-tags { .compact-tags {

View File

@ -26,9 +26,15 @@
] ]
} }
], ],
"background": {
"scripts": [
"scripts/background.js"
],
"persistent": false
},
"browser_specific_settings": { "browser_specific_settings": {
"gecko": { "gecko": {
"id": "szuruchrome@neobooru.com" "id": "{8cc2afc8-6c4a-4d2b-9513-46e46e5b4208}"
} }
} }
} }

View File

@ -1,95 +1,103 @@
<template> <template>
<div class="popup-container"> <div class="popup-container">
<div class="popup-row"> <div class="popup-messages">
<div class="popup-column1" style="margin: 0px 10px;"> <ul class="messages">
<ul class="messages"> <li
<li v-for="msg in messages"
v-for="msg in messages" :key="msg.name"
:key="msg.name" :class="getMessageClasses(msg)"
:class="getMessageClasses(msg)" v-html="msg.content"
v-html="msg.content" ></li>
></li> </ul>
</ul>
</div>
</div> </div>
<div class="popup-row"> <div class="popup-left">
<div class="popup-column2"> <div class="popup-section">
<div class="popup-header"> <div class="section-header">
<span>Basic info</span> <span>Basic info</span>
<i class="fas fa-cog" @click="openSettings"></i> <i class="fas fa-cog" @click="openSettings"></i>
</div> </div>
<div class="popup-content"> <div class="section-row">
<div class="popup-block"> <span class="section-label">Safety</span>
<span class="block-title">Safety</span>
<label class="container"> <label class="container">
<input type="radio" value="safe" v-model="post.rating" /> <input type="radio" value="safe" v-model="selectedPost.rating" />
<span class="checkmark"></span> <span class="checkmark"></span>
Safe Safe
</label> </label>
<label class="container"> <label class="container">
<input type="radio" value="sketchy" v-model="post.rating" /> <input type="radio" value="sketchy" v-model="selectedPost.rating" />
<span class="checkmark"></span> <span class="checkmark"></span>
Sketchy Sketchy
</label> </label>
<label class="container"> <label class="container">
<input type="radio" value="unsafe" v-model="post.rating" /> <input type="radio" value="unsafe" v-model="selectedPost.rating" />
<span class="checkmark"></span> <span class="checkmark"></span>
Unsafe Unsafe
</label> </label>
</div>
<div class="popup-block">
<span class="block-title">Source</span>
<input type="text" v-model="post.source" />
</div>
</div> </div>
<div class="popup-header"> <div class="section-row">
<span class="section-label">Source</span>
<input type="text" v-model="selectedPost.source" />
</div>
</div>
<div class="popup-section">
<div class="section-header">
<span>Tags</span> <span>Tags</span>
</div> </div>
<div class="popup-content"> <div class="section-row" style="display:flex;">
<div class="popup-block" style="display:flex;"> <input type="text" v-model="addTagInput" v-on:keyup.enter="addTag" />
<input type="text" v-model="addTagInput" v-on:keyup.enter="addTag" /> <button
<button class="primary"
class="primary" style="margin-left: 5px; height: auto;"
style="margin-left: 5px; height: auto;" @click="addTag"
@click="addTag" >Add</button>
>Add</button> </div>
</div>
<div class="popup-block"> <div class="section-row">
<ul class="compact-tags"> <ul class="compact-tags">
<li v-for="tag in post.tags" :key="tag.name"> <li v-for="tag in selectedPost.tags" :key="tag.name">
<a class="remove-tag" @click="removeTag(tag)">x</a> <a class="remove-tag" @click="removeTag(tag)">x</a>
<span :class="getTagClasses(tag)">{{ tag.name }}</span> <span :class="getTagClasses(tag)">{{ tag.name }}</span>
<span class="tag-usages">0</span> <span class="tag-usages">0</span>
</li> </li>
</ul> </ul>
</div>
</div> </div>
</div> </div>
<div class="popup-column2"> <div class="popup-section">
<img :src="post.imageUrl" /> <div class="section-row">
<select disabled>
<option>{{ activeSite != null ? activeSite.domain : "(no site available)" }}</option>
</select>
</div>
</div> </div>
</div> </div>
<div class="popup-row"> <div class="popup-right">
<div class="popup-column2"> <div class="popup-section">
<select disabled> <select v-model="selectedPost">
<option>{{ activeSite != null ? activeSite.domain : "(no site available)" }}</option> <option
v-for="post in posts"
v-bind:key="post"
v-bind:value="post"
>{{ post.name }}</option>
</select> </select>
</div> </div>
<div class="popup-column2" style="display: flex;"> <div class="popup-section">
<button class="primary" @click="findSimilar">Find similar</button> <img :src="selectedPost.imageUrl" />
<button class="primary full" style="margin-left: 5px;" @click="upload">Import</button>
<div style="display: flex;">
<button class="primary" @click="findSimilar">Find similar</button>
<button class="primary full" style="margin-left: 5px;" @click="upload">Import</button>
</div>
</div> </div>
</div> </div>
</div> </div>
@ -97,117 +105,79 @@
<script lang="ts"> <script lang="ts">
import Vue from "vue"; import Vue from "vue";
import { browser } from "webextension-polyfill-ts"; import { browser, Runtime } from "webextension-polyfill-ts";
import { ScrapedPost, ScrapedTag, ScrapeResults } from "neo-scraper"; import { ScrapedPost, ScrapedTag, ScrapeResults } from "neo-scraper";
import SzuruWrapper from "../SzuruWrapper"; import SzuruWrapper from "../SzuruWrapper";
import { Post, SzuruError } from "../SzuruTypes"; import { Post, SzuruError } from "../SzuruTypes";
import { Config, SzuruSiteConfig } from "../Config"; import { Config, SzuruSiteConfig } from "../Config";
import { BrowserCommand, Message } from "../Common";
type MessageType = "error" | "info" | "success"; class ScrapedPostViewModel extends ScrapedPost {
name: string = "";
class Message {
content: string;
type: MessageType;
constructor(content: string, type: MessageType = "info") {
this.content = content;
this.type = type;
}
} }
export default Vue.extend({ export default Vue.extend({
data() { data() {
return { return {
config: null as Config | null,
activeSite: null as SzuruSiteConfig | null, activeSite: null as SzuruSiteConfig | null,
szuru: null as SzuruWrapper | null, szuru: null as SzuruWrapper | null,
post: new ScrapedPost(), posts: [] as ScrapedPostViewModel[],
selectedPost: new ScrapedPost(), // Shouldn't be null because VueJS gets a mental breakdown when it sees a null.
messages: [] as Message[], messages: [] as Message[],
addTagInput: "" addTagInput: ""
}; };
}, },
watch: {
selectedPost() {
if (this.config && this.config.autoSearchSimilar) {
// No need to check if any vars are unset, findSimilar does that internally
this.findSimilar();
}
}
},
methods: { methods: {
// Try to scrape the post from the page // Try to scrape the post from the page
async grabPost() { async grabPost() {
// Get active tab // Get active tab
const activeTab = (await browser.tabs.query({ const activeTab = (
active: true, await browser.tabs.query({
currentWindow: true active: true,
}))[0]; currentWindow: true
})
)[0];
// Send 'grab_post' to the content script on the active tab // Send 'grab_post' to the content script on the active tab
const x = await browser.tabs.sendMessage(activeTab.id!, "grab_post"); const x = await browser.tabs.sendMessage(activeTab.id!, new BrowserCommand("grab_post"));
// We need to create a new ScrapeResults object and fill it with our data, because the get_posts() // 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) // 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); const res = Object.assign(new ScrapeResults(), x);
const post = res.posts.length > 0 ? res.posts[0] : null;
if (post) { // Clear current posts array
this.post = post; this.posts = [];
console.dir(post);
for (var result of res.results) {
for (var i in result.posts) {
const vm = Object.assign(new ScrapedPostViewModel(), result.posts[i]);
vm.name = `[${result.engine}] Post ${parseInt(i) + 1}`; // parseInt() is required!
this.posts.push(vm);
}
}
if (this.posts.length > 0) {
this.selectedPost = this.posts[0];
} else { } else {
this.pushError("Couldn't grab post"); this.pushInfo("No posts found.");
} }
}, },
// Try to upload the post to the selected szurubooru instance // Try to upload the post to the selected szurubooru instance
async upload() { async upload() {
this.clearMessages();
window.scrollTo(0, 0); window.scrollTo(0, 0);
if (!this.post || !this.post.imageUrl) { // Outsource to background.ts
this.pushError("There is no post to upload!"); const cmd = new BrowserCommand("upload_post", this.selectedPost);
return; await browser.runtime.sendMessage(cmd);
} // TODO: Handle errors/status update
if (!this.szuru) {
this.pushError("No szurubooru server configured!");
return;
}
try {
// Create and upload post
let uploadMsg = new Message("Uploading...");
this.messages.push(uploadMsg);
const createdPost = await this.szuru.createPost(this.post);
// TODO: Clicking a link doesn't actually open it in a new tab,
// see https://stackoverflow.com/questions/8915845
uploadMsg.content = `<a href='${this.getPostUrl(createdPost)}' target='_blank'>Uploaded post</a>`;
uploadMsg.type = "success";
// Find tags with "default" category and update it
// TODO: Make all these categories configurable
const tagsWithCategory = this.post.tags.filter(x => x.category);
const unsetCategoryTags = createdPost.tags
.filter(x => x.category == "default")
.filter(x => tagsWithCategory.some(y => x.names.includes(y.name)));
if (unsetCategoryTags.length != 0) {
let tagsMsg = new Message(`${unsetCategoryTags.length} tags need a different category`);
this.messages.push(tagsMsg);
// unsetCategoryTags is of type MicroTag[] and we need a Tag resource to update it, so let's get those
const query = "?query=" + unsetCategoryTags.map(x => this.encodeTagName(x.names[0]));
const tags = (await this.szuru.getTags(query)).results;
for (let i in tags) {
tagsMsg.content = `Updating tag ${i}/${unsetCategoryTags.length}`;
tags[i].category = tagsWithCategory.find(x => tags[i].names.includes(x.name))!.category!;
await this.szuru.updateTag(tags[i]);
}
tagsMsg.content = `Updated ${tags.length} tags`;
tagsMsg.type = "success";
}
} catch (ex) {
const error = ex as SzuruError;
if (error) {
this.clearMessages();
this.pushError(error.description);
} else {
// Probably too long for a message
alert(ex);
}
}
}, },
// Open extension settings page in new tab // Open extension settings page in new tab
async openSettings() { async openSettings() {
@ -227,17 +197,17 @@ export default Vue.extend({
}, },
// Remove tag from post's taglist // Remove tag from post's taglist
removeTag(tag: ScrapedTag) { removeTag(tag: ScrapedTag) {
if (this.post) { if (this.selectedPost) {
const idx = this.post.tags.indexOf(tag); const idx = this.selectedPost.tags.indexOf(tag);
if (idx != -1) { if (idx != -1) {
this.post.tags.splice(idx, 1); this.selectedPost.tags.splice(idx, 1);
} }
} }
}, },
getMessageClasses(message: Message) { getMessageClasses(message: Message) {
let classes: string[] = []; let classes: string[] = [];
switch (message.type) { switch (message.level) {
case "error": case "error":
classes.push("message-error"); classes.push("message-error");
break; break;
@ -249,75 +219,64 @@ export default Vue.extend({
return classes; return classes;
}, },
// Add info message // Add info message
pushInfo(message: string): Message { pushInfo(message: string, category: string | null = null): Message {
let msg = new Message(message); let msg = new Message(message, "info", category);
this.messages.push(msg); this.messages.push(msg);
return msg; return msg;
}, },
// Add error message // Add error message
pushError(message: string): Message { pushError(message: string, category: string | null = null): Message {
let msg = new Message(message, "error"); let msg = new Message(message, "error", category);
this.messages.push(msg); this.messages.push(msg);
return msg; return msg;
}, },
clearMessages() { // Clear messages of given category. When category is empty clear all messages.
this.messages = []; clearMessages(category: string | null) {
}, if (category) {
removeMessage(message: Message) { for (let i = 0; i < this.messages.length; i++) {
const idx = this.messages.indexOf(message); if (this.messages[i].category == category) {
if (idx != -1) this.messages.splice(idx, 1); // Decrement i to negate the i++, because if we remove one object the items
// shift one place to the left, aka index--
// If we don't do i-- we'll skip the next item in our for loop
this.messages.splice(i--, 1);
}
}
} else {
this.messages = [];
}
}, },
getPostUrl(post: Post): string { getPostUrl(post: Post): string {
if (!this.activeSite) return ""; if (!this.activeSite) return "";
return this.activeSite.domain + "/post/" + post.id; return this.activeSite.domain + "/post/" + post.id;
}, },
encodeTagName(tagName: string) {
// Searching for posts with re:zero will show an error message about unknown named token.
// Searching for posts with re\:zero will show posts tagged with re:zero.
return encodeURIComponent(tagName.replace(/\:/g, "\\:"));
},
// Add tag to the post's taglist // Add tag to the post's taglist
addTag() { addTag() {
if (this.post) { if (this.selectedPost) {
const tagName = this.addTagInput; const tagName = this.addTagInput;
this.addTagInput = ""; this.addTagInput = "";
if (this.post.tags.find(x => x.name == tagName) == undefined) { if (this.selectedPost.tags.find(x => x.name == tagName) == undefined) {
this.post.tags.push(new ScrapedTag(tagName)); this.selectedPost.tags.push(new ScrapedTag(tagName));
} }
} }
}, },
// Find posts similar to the grabbed post (this.post) // Find posts similar to the grabbed post (this.selectedPost)
async findSimilar() { async findSimilar() {
if (!this.post || !this.szuru) { if (!this.selectedPost || !this.szuru) {
return; return;
} }
// Remove messages that contain "Post already uploaded" or "No similar posts found" this.clearMessages("FIND_SIMILAR");
// but keep the other messages.
for (let i = 0; i < this.messages.length; i++) {
if (
this.messages[i].content.indexOf("No similar posts found") != -1 ||
this.messages[i].content.indexOf("Post already uploaded") != -1
) {
// Decrement i to negate the i++, because if we remove one object the items
// shift one place to the left, aka index--
// If we don't do i-- we'll skip the next item in our for loop
this.messages.splice(i--, 1);
}
}
const msgSearchSimilar = this.pushInfo("Searching for similar posts..."); const msg = this.pushInfo("Searching for similar posts...", "FIND_SIMILAR");
const res = await this.szuru.reverseSearch(this.post.imageUrl); const res = await this.szuru.reverseSearch(this.selectedPost.imageUrl);
this.removeMessage(msgSearchSimilar);
if (!res.exactPost && res.similarPosts.length == 0) { if (!res.exactPost && res.similarPosts.length == 0) {
this.pushInfo("No similar posts found"); msg.content = "No similar posts found";
} else { } else {
if (res.exactPost) { if (res.exactPost) {
this.pushError( msg.content = `<a href='${this.getPostUrl(res.exactPost)}' target='_blank'>
`<a href='${this.getPostUrl(res.exactPost)}' target='_blank'> Post already uploaded (${res.exactPost.id})</a>`;
Post already uploaded (${res.exactPost.id})</a>` msg.level = "error";
);
} }
for (const similarPost of res.similarPosts) { for (const similarPost of res.similarPosts) {
@ -328,15 +287,16 @@ export default Vue.extend({
this.pushInfo( this.pushInfo(
`<a href='${this.getPostUrl(similarPost.post)}' target='_blank'>Post ${similarPost.post.id} `<a href='${this.getPostUrl(similarPost.post)}' target='_blank'>Post ${similarPost.post.id}
looks ${Math.round(100 - similarPost.distance * 100)}% similar</a>` looks ${Math.round(100 - similarPost.distance * 100)}% similar</a>`,
"FIND_SIMILAR"
); );
} }
} }
} }
}, },
async mounted() { async mounted() {
const cfg = await Config.load(); this.config = await Config.load();
this.activeSite = cfg.sites.length > 0 ? cfg.sites[0] : null; this.activeSite = this.config.sites.length > 0 ? this.config.sites[0] : null;
if (!this.activeSite) { if (!this.activeSite) {
this.pushError("No szurubooru server configured!"); this.pushError("No szurubooru server configured!");
@ -344,13 +304,22 @@ export default Vue.extend({
this.szuru = await SzuruWrapper.createFromConfig(this.activeSite); this.szuru = await SzuruWrapper.createFromConfig(this.activeSite);
} }
// Always call grabPost, even when there is no activeSite browser.runtime.onMessage.addListener((cmd: BrowserCommand, sender: Runtime.MessageSender) => {
this.grabPost().then(() => { switch (cmd.name) {
if (cfg.autoSearchSimilar) { case "push_message":
// No need to check if any vars are unset, findSimilar does that internally this.messages.push(cmd.data);
this.findSimilar(); break;
case "remove_messages":
for (let i = 0; i < cmd.data; i++) {
if (this.messages.length == 0) break;
this.messages.pop();
}
break;
} }
}); });
// Always call grabPost, even when there is no activeSite
this.grabPost();
} }
}); });
</script> </script>
@ -358,49 +327,47 @@ export default Vue.extend({
<style scoped> <style scoped>
.popup-container { .popup-container {
width: 700px; width: 700px;
display: grid;
grid-template-columns: 300px 400px;
} }
.popup-row { .popup-messages {
display: flex; grid-column: 1 / 3;
margin: 0 10px;
} }
.popup-column1 { .popup-left {
flex: 100%; grid-column: 1;
}
.popup-right {
grid-column: 2;
}
.popup-section {
margin: 10px; margin: 10px;
} }
.popup-column2 { .section-header {
flex: 50%;
margin: 10px;
}
.popup-header {
height: 30px; height: 30px;
padding: 0 0 0 10px; padding: 0 6px 0 10px;
background-color: #eee; background-color: #eee;
margin: 0 0 10px 0;
display: flex;
justify-content: space-between;
align-items: center;
} }
.popup-content { .section-header > span {
margin: 5px; font-size: 1.2em;
}
.popup-header > span {
vertical-align: middle; vertical-align: middle;
} }
/* Horrible hack + guesswork */ .section-row {
.popup-header > i { margin: 10px 5px 0;
float: right;
margin: 8px 5px;
cursor: pointer;
} }
.popup-block { .section-label {
margin: 0 0 10px 0;
}
.block-title {
display: block; display: block;
margin: 0 0 5px 0; margin: 0 0 5px 0;
} }

View File

@ -1,2 +1,72 @@
// Dummy file so that webpack-extension-reloader doesn't complain when running `npm run watch:dev` import { ScrapedPost } from "neo-scraper";
// This file is excluded when not running in development mode import { browser, Runtime } from "webextension-polyfill-ts";
import { BrowserCommand, Message } from "../Common";
import { Config } from "../Config.ts";
import SzuruWrapper from "../SzuruWrapper.ts";
import { SzuruError } from "../SzuruTypes";
async function uploadPost(post: ScrapedPost) {
// TODO: Upload post and send status updates to popup
console.dir(post);
const cfg = await Config.load();
const szuru = (await SzuruWrapper.createFromConfig(cfg.sites[0]))!;
try {
// Create and upload post
browser.runtime.sendMessage(new BrowserCommand("remove_messages", 10));
browser.runtime.sendMessage(new BrowserCommand("push_message", new Message("Uploading...")));
const createdPost = await szuru.createPost(post);
browser.runtime.sendMessage(new BrowserCommand("remove_messages", 1));
browser.runtime.sendMessage(new BrowserCommand("push_message", new Message("Uploaded post " + createdPost.id, "success")));
// TODO: Clicking a link doesn't actually open it in a new tab,
// see https://stackoverflow.com/questions/8915845
// uploadMsg.content = `<a href='${this.getPostUrl(createdPost)}' target='_blank'>Uploaded post</a>`;
// uploadMsg.type = "success";
// Find tags with "default" category and update it
// TODO: Make all these categories configurable
const tagsWithCategory = post.tags.filter(x => x.category);
const unsetCategoryTags = createdPost.tags
.filter(x => x.category == "default")
.filter(x => tagsWithCategory.some(y => x.names.includes(y.name)));
if (unsetCategoryTags.length != 0) {
browser.runtime.sendMessage(new BrowserCommand("push_message", new Message(`${unsetCategoryTags.length} tags need a different category`)));
// unsetCategoryTags is of type MicroTag[] and we need a Tag resource to update it, so let's get those
const query = "?query=" + unsetCategoryTags.map(x => encodeTagName(x.names[0]));
const tags = (await szuru.getTags(query)).results;
for (let i in tags) {
browser.runtime.sendMessage(new BrowserCommand("remove_messages", 1));
browser.runtime.sendMessage(new BrowserCommand("push_message", new Message(`Updating tag ${i}/${unsetCategoryTags.length}`)));
tags[i].category = tagsWithCategory.find(x => tags[i].names.includes(x.name))!.category!;
await szuru.updateTag(tags[i]);
}
browser.runtime.sendMessage(new BrowserCommand("remove_messages", 1));
browser.runtime.sendMessage(new BrowserCommand("push_message", new Message(`Updated ${tags.length} tags`, "success")));
}
} catch (ex) {
const error = ex as SzuruError;
if (error) {
console.error(error);
browser.runtime.sendMessage(new BrowserCommand("push_message", new Message(ex, "error")));
} else {
console.error(ex);
browser.runtime.sendMessage(new BrowserCommand("push_message", new Message(ex, "error")));
}
}
}
function encodeTagName(tagName: string) {
// Searching for posts with re:zero will show an error message about unknown named token.
// Searching for posts with re\:zero will show posts tagged with re:zero.
return encodeURIComponent(tagName.replace(/\:/g, "\\:"));
}
async function messageHandler(cmd: BrowserCommand, sender: Runtime.MessageSender): Promise<any> {
switch (cmd.name) {
case "upload_post": return uploadPost(cmd.data);
}
}
browser.runtime.onMessage.addListener(messageHandler);

View File

@ -1,13 +1,14 @@
import { NeoScraper, ScrapeResults } from "neo-scraper"; import { NeoScraper, ScrapeResults } from "neo-scraper";
import { browser, Runtime } from "webextension-polyfill-ts"; import { browser, Runtime } from "webextension-polyfill-ts";
import { BrowserCommand } from "../Common";
function grabPost(): ScrapeResults { function grabPost(): ScrapeResults {
var scraper = new NeoScraper(); var scraper = new NeoScraper();
return scraper.scrapeDocument(document, undefined, true); return scraper.scrapeDocument(document, undefined, true);
} }
async function messageHandler(message: any, sender: Runtime.MessageSender): Promise<any> { async function messageHandler(cmd: BrowserCommand, sender: Runtime.MessageSender): Promise<any> {
switch (message) { switch (cmd.name) {
case "grab_post": return grabPost(); case "grab_post": return grabPost();
} }
} }

View File

@ -5,7 +5,7 @@
"strict": true, "strict": true,
"module": "es2015", "module": "es2015",
"moduleResolution": "node", "moduleResolution": "node",
"target": "es5", "target": "es6",
"skipLibCheck": true, "skipLibCheck": true,
"esModuleInterop": true, "esModuleInterop": true,
"experimentalDecorators": true, "experimentalDecorators": true,

View File

@ -11,6 +11,7 @@ const config = {
context: __dirname + '/src', context: __dirname + '/src',
entry: { entry: {
'scripts/content': './scripts/content.ts', 'scripts/content': './scripts/content.ts',
'scripts/background': './scripts/background.ts',
'popup/popup': './popup/popup.ts', 'popup/popup': './popup/popup.ts',
'options/options': './options/options.ts', 'options/options': './options/options.ts',
}, },
@ -98,8 +99,6 @@ if (config.mode === 'production') {
} }
if (process.env.HMR === 'true') { if (process.env.HMR === 'true') {
config.entry['scripts/background'] = './scripts/background.ts';
config.plugins = (config.plugins || []).concat([ config.plugins = (config.plugins || []).concat([
new ExtensionReloader({ new ExtensionReloader({
entries: { entries: {