Update formatting, a small fix, and some cleanup

pull/25/head v0.4.1
neobooru 2021-01-01 23:26:18 +01:00
parent 78fcc974da
commit c044a68a13
21 changed files with 1562 additions and 1714 deletions

View File

@ -1,4 +1,4 @@
{
"printWidth": 120,
"tabWidth": 4
"tabWidth": 2
}

View File

@ -4,12 +4,16 @@ Chrome/Firefox extension which can import media from various sites into a [szuru
## Supported sites
- Gelbooru/Safebooru/Rule34.xxx
- Danbooru (and Safebooru variant)
- Rule34 paheal (Shimmie2)
- yande.re/konachan (Moebooru)
- Reddit
- Twitter
- Danbooru (and Safebooru variant)
- Gelbooru/Safebooru/Rule34.xxx/tbib.org
- yande.re/konachan (Moebooru)
- SankakuComplex (doesn't currently work because of the hotlink protection)
- Rule34 paheal (Shimmie2)
- E-Shuushuu
- Zerochan
- Reddit
- Twitter
- Fallback (simply grabs the largest image on a page)
## Installation
@ -26,15 +30,24 @@ The layout is obviously not designed for mobile, so at times it looks less than
## How does it work?
This add-on has two 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 _every_ website ([why?](#Why-is-the-content-script-injected-on-every-page)).
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, imageUrl, 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 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, imageUrl, 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 ([why?](#Why-is-the-content-script-injected-on-every-page)) and does absolutely nothing until it receives the 'grab_post' message from the popup. Once it does received 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.
This script is injected on every page and does absolutely nothing until it receives the 'grab_post' message from the popup. Once it does received 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.
## Build/debug
@ -57,16 +70,16 @@ Firefox: `about:debugging` -> "Load Temporary Add-on..." -> Select any file in t
## Planned features
- Finishing the initial version of this add-on (see visual design doc for all features)
- Auto-set tag category when creating a new tag (imported tag)
- Reverse image search to check whether (similar) file already exist before uploading it
- Right click any image on a page to import it
- Configurable list of tags to always ignore (e.g. tagme, highres)
- [low priority] Import artist commentary
- [low priority] Import notes
- [lowest priority] Move from 'options_page' to 'options_ui'
- [lowest priority] Multiple szurubooru instances (where you can choose to which one you want to upload the post)
- [lowest priority] Application size could be reduced, but I am not too worried about that because it's all local and zipped it is just 1.2MB
These are some things I might work on. Though honestly I don't expect this extension to change much anytime soon.
- Finishing the initial version of this add-on (see visual design doc for all features)
- Right click any image on a page to import it
- Configurable list of tags to always ignore (e.g. tagme, highres)
- [low priority] Import artist commentary
- [low priority] Import notes
- [lowest priority] Move from 'options_page' to 'options_ui'
- [lowest priority] Multiple szurubooru instances (where you can choose to which one you want to upload the post)
- [lowest priority] Application size could be reduced, but I am not too worried about that because it's all local and zipped it is just 1.2MB
## FAQ
@ -97,10 +110,6 @@ Because the CORS spec is a bitch the preflight request is sent without the clien
</Location>
```
### Why is the content script injected on every page?
Because I didn't know that you can inject a script from the popup (after opening it, so only when needed). I might change this later.
### Why send the DOM to the ILoader instead of just an url?
If we send an URL to the ILoader it has to download the page again itself, which can go wrong in a dozen ways:
@ -110,7 +119,3 @@ If we send an URL to the ILoader it has to download the page again itself, which
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?
### Why is the CSS so bad?
Because CSS scares me.

1631
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,9 +1,12 @@
{
"name": "szuru-chrome",
"version": "0.3.2",
"description": "Import media from various sites into szurubooru",
"version": "0.4.1",
"description": "Import media from various sites into szurubooru.",
"author": "neobooru",
"license": "MIT",
"repository": {
"url": "https://github.com/neobooru/SzuruChrome"
},
"scripts": {
"build": "cross-env NODE_ENV=production webpack --hide-modules",
"build:dev": "cross-env NODE_ENV=development webpack --hide-modules",
@ -12,9 +15,8 @@
"watch:dev": "cross-env HMR=true npm run build:dev -- --watch"
},
"dependencies": {
"axios": "^0.19.2",
"axios": "^0.21.1",
"neo-scraper": "^0.2.5",
"ts-optchain": "^0.1.8",
"vue": "^2.6.11",
"webextension-polyfill": "^0.3.1"
},
@ -24,7 +26,6 @@
"core-js": "^3.6.5",
"cross-env": "^5.2.1",
"css-loader": "^2.1.1",
"ejs": "^2.7.4",
"file-loader": "^1.1.11",
"mini-css-extract-plugin": "^0.4.4",
"node-sass": "^4.14.1",

View File

@ -1,52 +1,52 @@
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const archiver = require('archiver');
const fs = require("fs");
const path = require("path");
const archiver = require("archiver");
const DEST_DIR = path.join(__dirname, '../dist');
const DEST_ZIP_DIR = path.join(__dirname, '../dist-zip');
const DEST_DIR = path.join(__dirname, "../dist");
const DEST_ZIP_DIR = path.join(__dirname, "../dist-zip");
const extractExtensionData = () => {
const extPackageJson = require('../package.json');
const extPackageJson = require("../package.json");
return {
name: extPackageJson.name,
version: extPackageJson.version
}
};
};
const makeDestZipDirIfNotExists = () => {
if(!fs.existsSync(DEST_ZIP_DIR)) {
if (!fs.existsSync(DEST_ZIP_DIR)) {
fs.mkdirSync(DEST_ZIP_DIR);
}
}
};
const buildZip = (src, dist, zipFilename) => {
console.info(`Building ${zipFilename}...`);
const archive = archiver('zip', { zlib: { level: 9 }});
const archive = archiver("zip", { zlib: { level: 9 } });
const stream = fs.createWriteStream(path.join(dist, zipFilename));
return new Promise((resolve, reject) => {
archive
.directory(src, false)
.on('error', err => reject(err))
.on("error", err => reject(err))
.pipe(stream);
stream.on('close', () => resolve());
stream.on("close", () => resolve());
archive.finalize();
});
};
const main = () => {
const {name, version} = extractExtensionData();
const { name, version } = extractExtensionData();
const zipFilename = `${name}-v${version}.zip`;
makeDestZipDirIfNotExists();
buildZip(DEST_DIR, DEST_ZIP_DIR, zipFilename)
.then(() => console.info('OK'))
.then(() => console.info("OK"))
.catch(console.err);
};

View File

@ -2,31 +2,31 @@ export type BrowserCommandName = "grab_post" | "upload_post" | "push_message" |
export type MessageType = "error" | "info" | "success";
export class BrowserCommand {
name: BrowserCommandName;
data: any;
name: BrowserCommandName;
data: any;
constructor(name: BrowserCommandName, data: any = null) {
this.name = name;
this.data = data;
}
constructor(name: BrowserCommandName, data: any = null) {
this.name = name;
this.data = data;
}
}
export class Message {
content: string;
level: MessageType;
category: string;
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";
}
constructor(content: string, level: MessageType = "info", category: string | null = null) {
this.content = content;
this.level = level;
this.category = category ?? "none";
}
}
export function getUrl(root: string, ...parts: string[]): string {
let url = root.replace(/\/+$/, "");
for (const part of parts) {
url += "/" + part.replace(/\/+$/, "");
}
return url;
let url = root.replace(/\/+$/, "");
for (const part of parts) {
url += "/" + part.replace(/\/+$/, "");
}
return url;
}

View File

@ -1,36 +1,36 @@
import { browser } from "webextension-polyfill-ts";
export class SzuruSiteConfig {
domain: string = "";
username: string = "";
authToken: string = "";
domain: string = "";
username: string = "";
authToken: string = "";
}
export class Config {
importExistingTags: boolean = true;
importAllTags: boolean = false;
importCommentary: boolean = false;
autoSearchSimilar: boolean = false;
sites: Array<SzuruSiteConfig> = [];
importExistingTags: boolean = true;
importAllTags: boolean = false;
importCommentary: boolean = false;
autoSearchSimilar: boolean = false;
sites: Array<SzuruSiteConfig> = [];
public async save() {
await browser.storage.local.set({
config: JSON.stringify(this)
});
public async save() {
await browser.storage.local.set({
config: JSON.stringify(this)
});
console.dir("Save " + JSON.stringify(this));
console.log("Saved config");
console.dir("Save " + JSON.stringify(this));
console.log("Saved config");
}
static async load(): Promise<Config> {
let storage = await browser.storage.local.get("config");
let config: Config = new Config();
if ("config" in storage) {
config = Object.assign(config, JSON.parse(storage["config"]));
}
static async load(): Promise<Config> {
let 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;
}
console.dir("Load " + JSON.stringify(config));
return config;
}
}

View File

@ -4,99 +4,99 @@
export type Safety = "safe" | "sketchy" | "unsafe";
export type TagsResult = PagedSearchResult<Tag>
export type TagCategoriesResult = UnpagedSearchResult<TagCategory>
export type TagsResult = PagedSearchResult<Tag>;
export type TagCategoriesResult = UnpagedSearchResult<TagCategory>;
export interface SzuruError {
name: string;
title: string;
description: string;
name: string;
title: string;
description: string;
}
export interface PagedSearchResult<T> {
query: string;
offset: number;
limit: number;
total: number;
results: T[];
query: string;
offset: number;
limit: number;
total: number;
results: T[];
}
export interface UnpagedSearchResult<T> {
results: T[];
results: T[];
}
export interface MicroTag {
names: string[];
category: string;
usages: number;
names: string[];
category: string;
usages: number;
}
export interface Tag {
names: string[];
category: string;
version: number;
description?: string; // Markdown
creationTime: Date;
lastEditTime?: Date;
usages: number;
suggestions: MicroTag[];
implications: MicroTag[];
names: string[];
category: string;
version: number;
description?: string; // Markdown
creationTime: Date;
lastEditTime?: Date;
usages: number;
suggestions: MicroTag[];
implications: MicroTag[];
}
export interface TagCategory {
name: string;
version: number;
color: string;
usages: number;
default: boolean;
name: string;
version: number;
color: string;
usages: number;
default: boolean;
}
export interface MicroUser {
name: string;
avatarUrl: string;
name: string;
avatarUrl: string;
}
export interface Post {
id: number;
version: number;
creationTime: Date;
lastEditTime?: Date;
safety: Safety;
source: string;
type: string;
mimeType: string;
checksum: string;
fileSize: number;
canvasWidth: number;
canvasHeight: number;
contentUrl: string;
thumbnailUrl: string;
flags: string[];
tags: MicroTag[];
relations: any[]; // MicroPost resource
user: MicroUser;
score: number;
ownScore: number;
ownFavorite: boolean;
tagCount: number;
favoriteCount: number;
commentCount: number;
noteCount: number;
relationCount: number;
featureCount: number;
lastFeatureTime?: Date;
favoritedBy: MicroUser[];
hasCustomThumbnail: boolean;
notes: any[]; // Note resource
comments: any[]; // Comment resource
id: number;
version: number;
creationTime: Date;
lastEditTime?: Date;
safety: Safety;
source: string;
type: string;
mimeType: string;
checksum: string;
fileSize: number;
canvasWidth: number;
canvasHeight: number;
contentUrl: string;
thumbnailUrl: string;
flags: string[];
tags: MicroTag[];
relations: any[]; // MicroPost resource
user: MicroUser;
score: number;
ownScore: number;
ownFavorite: boolean;
tagCount: number;
favoriteCount: number;
commentCount: number;
noteCount: number;
relationCount: number;
featureCount: number;
lastFeatureTime?: Date;
favoritedBy: MicroUser[];
hasCustomThumbnail: boolean;
notes: any[]; // Note resource
comments: any[]; // Comment resource
}
export interface SimilarPost {
distance: number;
post: Post;
distance: number;
post: Post;
}
export interface ImageSearchResult {
exactPost: Post | null;
similarPosts: SimilarPost[];
exactPost: Post | null;
similarPosts: SimilarPost[];
}

View File

@ -9,122 +9,122 @@ import { TagsResult, TagCategoriesResult, Post, Tag, SzuruError, ImageSearchResu
* @class SzuruWrapper
*/
export default class SzuruWrapper {
baseUrl: string;
apiUrl: string;
username: string;
authToken: string;
baseUrl: string;
apiUrl: string;
username: string;
authToken: string;
private readonly baseHeaders = {
"Accept": "application/json",
"Content-Type": "application/json"
private readonly baseHeaders = {
Accept: "application/json",
"Content-Type": "application/json"
};
/**
* Creates an instance of SzuruWrapper.
* @param {string} baseUrl
* @memberof SzuruWrapper
*/
constructor(baseUrl: string, username: string, authToken: string) {
const x = baseUrl.replace(/\/+$/, ""); // Trim trailing slashes, to make sure we only have one
this.baseUrl = x + "/";
this.apiUrl = x + "/api/";
this.username = username;
this.authToken = authToken;
}
async getInfo(): Promise<any> {
return (await this.apiGet("info")).data;
}
async updateTag(tag: Tag): Promise<any> {
return (await this.apiPut("tag/" + tag.names[0], tag)).data;
}
async getTags(query: string): Promise<TagsResult> {
let url = "tags";
if (query) {
url += query;
}
return (await this.apiGet(url)).data;
}
async getTagCategories(): Promise<TagCategoriesResult> {
return (await this.apiGet("tag-categories")).data;
}
async createPost(post: ScrapedPost): Promise<Post> {
var obj = {
tags: post.tags.map(x => x.name),
safety: post.rating,
source: post.source,
contentUrl: post.imageUrl
};
/**
* Creates an instance of SzuruWrapper.
* @param {string} baseUrl
* @memberof SzuruWrapper
*/
constructor(baseUrl: string, username: string, authToken: string) {
const x = baseUrl.replace(/\/+$/, ""); // Trim trailing slashes, to make sure we only have one
this.baseUrl = x + "/";
this.apiUrl = x + "/api/";
this.username = username;
this.authToken = authToken;
console.log("Create new post object");
console.dir(obj);
return (await this.apiPost("posts", obj)).data;
}
async reverseSearch(imageUrl: string): Promise<ImageSearchResult> {
var obj = {
contentUrl: imageUrl
};
return (await this.apiPost("posts/reverse-search", obj)).data;
}
private async apiGet(url: string, additionalHeaders: any = {}): Promise<any> {
const fullUrl = this.apiUrl + url;
const config: AxiosRequestConfig = {
method: "GET",
url: fullUrl
};
config.headers = { ...this.baseHeaders, ...additionalHeaders };
return await this.execute(config);
}
private async apiPost(url: string, data: any, additionalHeaders: any = {}): Promise<any> {
const fullUrl = this.apiUrl + url;
const config: AxiosRequestConfig = {
method: "POST",
url: fullUrl,
data: data
};
config.headers = { ...this.baseHeaders, ...additionalHeaders };
return await this.execute(config);
}
private async apiPut(url: string, data: any, additionalHeaders: any = {}): Promise<any> {
const fullUrl = this.apiUrl + url;
const config: AxiosRequestConfig = {
method: "PUT",
url: fullUrl,
data: data
};
config.headers = { ...this.baseHeaders, ...additionalHeaders };
return await this.execute(config);
}
private async execute(config: AxiosRequestConfig): Promise<any> {
if (this.username && this.authToken) {
const token = "Token " + btoa(`${this.username}:${this.authToken}`);
config.headers["Authorization"] = token;
// console.log(token);
}
async getInfo(): Promise<any> {
return (await this.apiGet("info")).data;
try {
return await axios(config);
} catch (ex) {
const error = ex.response.data as SzuruError;
throw error ? error : ex;
}
}
async updateTag(tag: Tag): Promise<any> {
return (await this.apiPut("tag/" + tag.names[0], tag)).data;
}
async getTags(query: string): Promise<TagsResult> {
let url = "tags";
if (query) {
url += query;
}
return (await this.apiGet(url)).data;
}
async getTagCategories(): Promise<TagCategoriesResult> {
return (await this.apiGet("tag-categories")).data;
}
async createPost(post: ScrapedPost): Promise<Post> {
var obj = {
tags: post.tags.map(x => x.name),
safety: post.rating,
source: post.source,
contentUrl: post.imageUrl
};
console.log("Create new post object");
console.dir(obj);
return (await this.apiPost("posts", obj)).data;
}
async reverseSearch(imageUrl: string): Promise<ImageSearchResult> {
var obj = {
contentUrl: imageUrl
};
return (await this.apiPost("posts/reverse-search", obj)).data;
}
private async apiGet(url: string, additionalHeaders: any = {}): Promise<any> {
const fullUrl = this.apiUrl + url;
const config: AxiosRequestConfig = {
method: "GET",
url: fullUrl
}
config.headers = { ...this.baseHeaders, ...additionalHeaders };
return await this.execute(config);
}
private async apiPost(url: string, data: any, additionalHeaders: any = {}): Promise<any> {
const fullUrl = this.apiUrl + url;
const config: AxiosRequestConfig = {
method: "POST",
url: fullUrl,
data: data
}
config.headers = { ...this.baseHeaders, ...additionalHeaders };
return await this.execute(config);
}
private async apiPut(url: string, data: any, additionalHeaders: any = {}): Promise<any> {
const fullUrl = this.apiUrl + url;
const config: AxiosRequestConfig = {
method: "PUT",
url: fullUrl,
data: data
}
config.headers = { ...this.baseHeaders, ...additionalHeaders };
return await this.execute(config);
}
private async execute(config: AxiosRequestConfig): Promise<any> {
if (this.username && this.authToken) {
const token = "Token " + btoa(`${this.username}:${this.authToken}`);
config.headers["Authorization"] = token;
// console.log(token);
}
try {
return await axios(config);
} catch (ex) {
const error = ex.response.data as SzuruError;
throw error ? error : ex;
}
}
static async createFromConfig(siteConfig: SzuruSiteConfig): Promise<SzuruWrapper | null> {
return new SzuruWrapper(siteConfig.domain, siteConfig.username, siteConfig.authToken);
}
static async createFromConfig(siteConfig: SzuruSiteConfig): Promise<SzuruWrapper | null> {
return new SzuruWrapper(siteConfig.domain, siteConfig.username, siteConfig.authToken);
}
}

View File

@ -1,6 +1,6 @@
{
"name": "SzuruChrome",
"description": "Import media from various sites into szurubooru",
"description": "Import media from various sites into szurubooru.",
"version": null,
"manifest_version": 2,
"icons": {
@ -34,7 +34,7 @@
},
"browser_specific_settings": {
"gecko": {
"id": "{8cc2afc8-6c4a-4d2b-9513-46e46e5b4208}"
"id": "{13372607-2257-4360-8f51-5ce66fa73350}"
}
}
}

View File

@ -1,134 +1,129 @@
<template>
<div class="settings-container">
<div class="settings-header">
<strong>SzuruChrome settings</strong>
</div>
<div class="settings-content">
<label>
Szurubooru URL
<br />
<input type="text" name="domain" v-model="domain" />
</label>
<br />
<label>
Username
<br />
<input type="text" name="username" v-model="username" />
</label>
<label>
Authentication token
<br />
<input type="text" name="token" v-model="authToken" />
</label>
<br />
<label>
Automatically search for similar posts
<input
type="checkbox"
name="autoSearchSimilar"
v-model="autoSearchSimilar"
/>
</label>
<br />
<div class="settings-footer-buttons">
<button @click="testConnection">Test connection</button>
<button @click="saveSettings" class="primary">Save settings</button>
</div>
</div>
<div class="settings-container">
<div class="settings-header">
<strong>SzuruChrome settings</strong>
</div>
<div class="settings-content">
<label>
Szurubooru URL
<br />
<input type="text" name="domain" v-model="domain" />
</label>
<br />
<label>
Username
<br />
<input type="text" name="username" v-model="username" />
</label>
<label>
Authentication token
<br />
<input type="text" name="token" v-model="authToken" />
</label>
<br />
<label>
Automatically search for similar posts
<input type="checkbox" name="autoSearchSimilar" v-model="autoSearchSimilar" />
</label>
<br />
<div class="settings-footer-buttons">
<button @click="testConnection">Test connection</button>
<button @click="saveSettings" class="primary">Save settings</button>
</div>
</div>
</div>
</template>
<script lang="ts">
import Vue from "vue";
import { oc } from "ts-optchain";
import SzuruWrapper from "../SzuruWrapper";
import { Config, SzuruSiteConfig } from "../Config";
export default Vue.extend({
data() {
return {
domain: "",
username: "",
authToken: "",
autoSearchSimilar: false
};
},
methods: {
async testConnection() {
if (!this.domain || !this.username || !this.authToken) {
alert("Domain, username and authentication token are all required.");
return;
}
data() {
return {
domain: "",
username: "",
authToken: "",
autoSearchSimilar: false,
};
},
methods: {
async testConnection() {
if (!this.domain || !this.username || !this.authToken) {
alert("Domain, username and authentication token are all required.");
return;
}
const api = new SzuruWrapper(this.domain, this.username, this.authToken);
try {
const info = (await api.getInfo()) as any;
const instanceName = oc(info).config.domain;
const api = new SzuruWrapper(this.domain, this.username, this.authToken);
try {
const info = (await api.getInfo()) as any;
const instanceName = info?.config.name;
if (instanceName == undefined) {
alert(`Connected to ${this.domain}, but it is not a szurubooru instance.`);
} else {
alert(`Connected to ${info.config.name} at ${this.domain}`);
}
} catch (ex) {
alert("Couldn't connect to " + this.domain + "\n\n" + ex);
}
},
async saveSettings() {
let config = await Config.load();
console.dir(config);
// We currently only support one domain
let siteConfig = new SzuruSiteConfig();
siteConfig.domain = this.domain;
siteConfig.username = this.username;
siteConfig.authToken = this.authToken;
config.sites = [siteConfig];
config.autoSearchSimilar = this.autoSearchSimilar;
await config.save();
if (instanceName == undefined) {
alert(`Connected to ${this.domain}, but it is not a szurubooru instance.`);
} else {
alert(`Connected to ${info.config.name} at ${this.domain}`);
}
} catch (ex) {
alert("Couldn't connect to " + this.domain + "\n\n" + ex);
}
},
async mounted() {
let config = await Config.load();
async saveSettings() {
let config = await Config.load();
console.dir(config);
console.log(`Loaded ${config.sites.length} sites`);
// We currently only support one domain
let siteConfig = new SzuruSiteConfig();
siteConfig.domain = this.domain;
siteConfig.username = this.username;
siteConfig.authToken = this.authToken;
config.sites = [siteConfig];
config.autoSearchSimilar = this.autoSearchSimilar;
// We currently only support one domain
if (config.sites.length > 0) {
this.domain = config.sites[0].domain;
this.username = config.sites[0].username;
this.authToken = config.sites[0].authToken;
this.autoSearchSimilar = config.autoSearchSimilar;
}
await config.save();
},
},
async mounted() {
let config = await Config.load();
console.log(`Loaded ${config.sites.length} sites`);
// We currently only support one domain
if (config.sites.length > 0) {
this.domain = config.sites[0].domain;
this.username = config.sites[0].username;
this.authToken = config.sites[0].authToken;
this.autoSearchSimilar = config.autoSearchSimilar;
}
},
});
</script>
<style scoped>
.settings-container {
margin: 0;
position: absolute;
top: 50%;
left: 50%;
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
margin: 0;
position: absolute;
top: 50%;
left: 50%;
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
padding: 20px;
background-color: #f5f5f5;
padding: 20px;
background-color: #f5f5f5;
}
.settings-header {
padding: 0 0 20px 0;
padding: 0 0 20px 0;
}
.settings-footer-buttons {
padding: 20px 0 0 0;
float: right;
padding: 20px 0 0 0;
float: right;
}
.settings-content > label {
display: inline-block;
display: inline-block;
}
</style>

View File

@ -1,18 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<head>
<meta charset="UTF-8" />
<title>SzuruChrome - Options</title>
<link rel="stylesheet" href="options.css" />
<% if (NODE_ENV === 'development') { %>
<!-- Load some resources only in development environment -->
<% } %>
</head>
</head>
<body>
<body>
<div id="app"></div>
<script src="options.js"></script>
</body>
</body>
</html>

View File

@ -1,9 +1,9 @@
import '../css/style.css';
import "../css/style.css";
import Vue from 'vue';
import App from './App';
import Vue from "vue";
import App from "./App";
new Vue({
el: '#app',
render: h => h(App)
})
el: "#app",
render: h => h(App)
});

View File

@ -1,106 +1,93 @@
<template>
<div class="popup-container">
<div class="popup-messages">
<ul class="messages">
<li
v-for="msg in messages"
:key="msg.name"
:class="getMessageClasses(msg)"
v-html="msg.content"
></li>
</ul>
</div>
<div class="popup-left">
<div class="popup-section">
<div class="section-header">
<span>Basic info</span>
<i class="fas fa-cog" @click="openSettings"></i>
</div>
<div class="section-row">
<span class="section-label">Safety</span>
<label class="container">
<input type="radio" value="safe" v-model="selectedPost.rating" />
<span class="checkmark"></span>
Safe
</label>
<label class="container">
<input type="radio" value="sketchy" v-model="selectedPost.rating" />
<span class="checkmark"></span>
Sketchy
</label>
<label class="container">
<input type="radio" value="unsafe" v-model="selectedPost.rating" />
<span class="checkmark"></span>
Unsafe
</label>
</div>
<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>
</div>
<div class="section-row" style="display:flex;">
<input type="text" v-model="addTagInput" v-on:keyup.enter="addTag" />
<button
class="primary"
style="margin-left: 5px; height: auto;"
@click="addTag"
>Add</button>
</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)">{{ tag.name }}</span>
<span class="tag-usages">0</span>
</li>
</ul>
</div>
</div>
<div class="popup-section">
<div class="section-row">
<select disabled>
<option>{{ activeSite != null ? activeSite.domain : "(no site available)" }}</option>
</select>
</div>
</div>
</div>
<div class="popup-right">
<div class="popup-section">
<select v-model="selectedPost">
<option
v-for="post in posts"
v-bind:key="post"
v-bind:value="post"
>{{ post.name }}</option>
</select>
</div>
<div class="popup-section">
<img :src="selectedPost.imageUrl" />
<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 class="popup-container">
<div class="popup-messages">
<ul class="messages">
<li v-for="msg in messages" :key="msg.name" :class="getMessageClasses(msg)" v-html="msg.content"></li>
</ul>
</div>
<div class="popup-left">
<div class="popup-section">
<div class="section-header">
<span>Basic info</span>
<i class="fas fa-cog" @click="openSettings"></i>
</div>
<div class="section-row">
<span class="section-label">Safety</span>
<label class="container">
<input type="radio" value="safe" v-model="selectedPost.rating" />
<span class="checkmark"></span>
Safe
</label>
<label class="container">
<input type="radio" value="sketchy" v-model="selectedPost.rating" />
<span class="checkmark"></span>
Sketchy
</label>
<label class="container">
<input type="radio" value="unsafe" v-model="selectedPost.rating" />
<span class="checkmark"></span>
Unsafe
</label>
</div>
<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>
</div>
<div class="section-row" style="display: flex">
<input type="text" v-model="addTagInput" v-on:keyup.enter="addTag" />
<button class="primary" style="margin-left: 5px; height: auto" @click="addTag">Add</button>
</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)">{{ tag.name }}</span>
<span class="tag-usages">0</span>
</li>
</ul>
</div>
</div>
<div class="popup-section">
<div class="section-row">
<select disabled>
<option>{{ activeSite != null ? activeSite.domain : "(no site available)" }}</option>
</select>
</div>
</div>
</div>
<div class="popup-right">
<div class="popup-section">
<select v-model="selectedPost">
<option v-for="post in posts" v-bind:key="post" v-bind:value="post">{{ post.name }}</option>
</select>
</div>
<div class="popup-section">
<img :src="selectedPost.imageUrl" />
<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>
</template>
<script lang="ts">
@ -113,262 +100,262 @@ import { Config, SzuruSiteConfig } from "../Config";
import { BrowserCommand, Message, getUrl } from "../Common";
class ScrapedPostViewModel extends ScrapedPost {
name: string = "";
name: string = "";
}
export default Vue.extend({
data() {
return {
config: null as Config | null,
activeSite: null as SzuruSiteConfig | null,
szuru: null as SzuruWrapper | null,
posts: [] as ScrapedPostViewModel[],
selectedPost: new ScrapedPost(), // Shouldn't be null because VueJS gets a mental breakdown when it sees a null.
messages: [] as Message[],
addTagInput: ""
};
data() {
return {
config: null as Config | null,
activeSite: null as SzuruSiteConfig | null,
szuru: null as SzuruWrapper | null,
posts: [] as ScrapedPostViewModel[],
selectedPost: new ScrapedPost(), // Shouldn't be null because VueJS gets a mental breakdown when it sees a null.
messages: [] as Message[],
addTagInput: "",
};
},
watch: {
selectedPost() {
if (this.config && this.config.autoSearchSimilar) {
// No need to check if any vars are unset, findSimilar does that internally
this.findSimilar();
}
},
watch: {
selectedPost() {
if (this.config && this.config.autoSearchSimilar) {
// No need to check if any vars are unset, findSimilar does that internally
this.findSimilar();
}
},
methods: {
// Try to scrape the post from the page
async grabPost() {
// Get active tab
const activeTab = (
await browser.tabs.query({
active: true,
currentWindow: true,
})
)[0];
// Send 'grab_post' to the content script on the active tab
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()
// 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);
// Clear current posts array
this.posts = [];
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 {
this.pushInfo("No posts found.");
}
},
methods: {
// Try to scrape the post from the page
async grabPost() {
// Get active tab
const activeTab = (
await browser.tabs.query({
active: true,
currentWindow: true
})
)[0];
// Try to upload the post to the selected szurubooru instance
async upload() {
window.scrollTo(0, 0);
// Send 'grab_post' to the content script on the active tab
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()
// 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);
// Outsource to background.ts
const cmd = new BrowserCommand("upload_post", this.selectedPost);
await browser.runtime.sendMessage(cmd);
// TODO: Handle errors/status update
},
// Open extension settings page in new tab
async openSettings() {
const url = browser.extension.getURL("options/options.html");
window.open(url);
},
getTagClasses(tag: ScrapedTag): string[] {
let classes: string[] = [];
// Clear current posts array
this.posts = [];
if (tag.category) {
classes.push("tag-" + tag.category);
} else {
classes.push("tag-general");
}
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);
}
}
return classes;
},
// Remove tag from post's taglist
removeTag(tag: ScrapedTag) {
if (this.selectedPost) {
const idx = this.selectedPost.tags.indexOf(tag);
if (idx != -1) {
this.selectedPost.tags.splice(idx, 1);
}
}
},
getMessageClasses(message: Message) {
let classes: string[] = [];
if (this.posts.length > 0) {
this.selectedPost = this.posts[0];
} else {
this.pushInfo("No posts found.");
}
},
// Try to upload the post to the selected szurubooru instance
async upload() {
window.scrollTo(0, 0);
switch (message.level) {
case "error":
classes.push("message-error");
break;
case "success":
classes.push("message-success");
break;
}
// Outsource to background.ts
const cmd = new BrowserCommand("upload_post", this.selectedPost);
await browser.runtime.sendMessage(cmd);
// TODO: Handle errors/status update
},
// Open extension settings page in new tab
async openSettings() {
const url = browser.extension.getURL("options/options.html");
window.open(url);
},
getTagClasses(tag: ScrapedTag): string[] {
let classes: string[] = [];
return classes;
},
// Add info message
pushInfo(message: string, category: string | null = null): Message {
let msg = new Message(message, "info", category);
this.messages.push(msg);
return msg;
},
// Add error message
pushError(message: string, category: string | null = null): Message {
let msg = new Message(message, "error", category);
this.messages.push(msg);
return msg;
},
// Clear messages of given category. When category is empty clear all messages.
clearMessages(category: string | null) {
if (category) {
for (let i = 0; i < this.messages.length; i++) {
if (this.messages[i].category == category) {
// 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 {
if (!this.activeSite) return "";
return getUrl(this.activeSite.domain, "post", post.id.toString());
},
// Add tag to the post's taglist
addTag() {
if (this.selectedPost) {
const tagName = this.addTagInput;
this.addTagInput = "";
if (this.selectedPost.tags.find((x) => x.name == tagName) == undefined) {
this.selectedPost.tags.push(new ScrapedTag(tagName));
}
}
},
// Find posts similar to the grabbed post (this.selectedPost)
async findSimilar() {
if (!this.selectedPost || !this.szuru) {
return;
}
if (tag.category) {
classes.push("tag-" + tag.category);
} else {
classes.push("tag-general");
}
this.clearMessages("FIND_SIMILAR");
return classes;
},
// Remove tag from post's taglist
removeTag(tag: ScrapedTag) {
if (this.selectedPost) {
const idx = this.selectedPost.tags.indexOf(tag);
if (idx != -1) {
this.selectedPost.tags.splice(idx, 1);
}
}
},
getMessageClasses(message: Message) {
let classes: string[] = [];
const msg = this.pushInfo("Searching for similar posts...", "FIND_SIMILAR");
const res = await this.szuru.reverseSearch(this.selectedPost.imageUrl);
switch (message.level) {
case "error":
classes.push("message-error");
break;
case "success":
classes.push("message-success");
break;
}
return classes;
},
// Add info message
pushInfo(message: string, category: string | null = null): Message {
let msg = new Message(message, "info", category);
this.messages.push(msg);
return msg;
},
// Add error message
pushError(message: string, category: string | null = null): Message {
let msg = new Message(message, "error", category);
this.messages.push(msg);
return msg;
},
// Clear messages of given category. When category is empty clear all messages.
clearMessages(category: string | null) {
if (category) {
for (let i = 0; i < this.messages.length; i++) {
if (this.messages[i].category == category) {
// 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 {
if (!this.activeSite) return "";
return getUrl(this.activeSite.domain, "post", post.id.toString());
},
// Add tag to the post's taglist
addTag() {
if (this.selectedPost) {
const tagName = this.addTagInput;
this.addTagInput = "";
if (this.selectedPost.tags.find(x => x.name == tagName) == undefined) {
this.selectedPost.tags.push(new ScrapedTag(tagName));
}
}
},
// Find posts similar to the grabbed post (this.selectedPost)
async findSimilar() {
if (!this.selectedPost || !this.szuru) {
return;
}
this.clearMessages("FIND_SIMILAR");
const msg = this.pushInfo("Searching for similar posts...", "FIND_SIMILAR");
const res = await this.szuru.reverseSearch(this.selectedPost.imageUrl);
if (!res.exactPost && res.similarPosts.length == 0) {
msg.content = "No similar posts found";
} else {
if (res.exactPost) {
msg.content = `<a href='${this.getPostUrl(res.exactPost)}' target='_blank'>
if (!res.exactPost && res.similarPosts.length == 0) {
msg.content = "No similar posts found";
} else {
if (res.exactPost) {
msg.content = `<a href='${this.getPostUrl(res.exactPost)}' target='_blank'>
Post already uploaded (${res.exactPost.id})</a>`;
msg.level = "error";
}
msg.level = "error";
}
for (const similarPost of res.similarPosts) {
// Don't show this message for the exactPost (because we have a different message for that)
if (res.exactPost && res.exactPost.id == similarPost.post.id) {
continue;
}
for (const similarPost of res.similarPosts) {
// Don't show this message for the exactPost (because we have a different message for that)
if (res.exactPost && res.exactPost.id == similarPost.post.id) {
continue;
}
this.pushInfo(
`<a href='${this.getPostUrl(similarPost.post)}' target='_blank'>Post ${similarPost.post.id}
this.pushInfo(
`<a href='${this.getPostUrl(similarPost.post)}' target='_blank'>Post ${similarPost.post.id}
looks ${Math.round(100 - similarPost.distance * 100)}% similar</a>`,
"FIND_SIMILAR"
);
}
}
"FIND_SIMILAR"
);
}
}
},
async mounted() {
this.config = await Config.load();
this.activeSite = this.config.sites.length > 0 ? this.config.sites[0] : null;
},
async mounted() {
this.config = await Config.load();
this.activeSite = this.config.sites.length > 0 ? this.config.sites[0] : null;
if (!this.activeSite) {
this.pushError("No szurubooru server configured!");
} else {
this.szuru = await SzuruWrapper.createFromConfig(this.activeSite);
}
browser.runtime.onMessage.addListener((cmd: BrowserCommand, sender: Runtime.MessageSender) => {
switch (cmd.name) {
case "push_message":
this.messages.push(cmd.data);
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();
if (!this.activeSite) {
this.pushError("No szurubooru server configured!");
} else {
this.szuru = await SzuruWrapper.createFromConfig(this.activeSite);
}
browser.runtime.onMessage.addListener((cmd: BrowserCommand, sender: Runtime.MessageSender) => {
switch (cmd.name) {
case "push_message":
this.messages.push(cmd.data);
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>
<style scoped>
.popup-container {
width: 700px;
display: grid;
grid-template-columns: 300px 400px;
width: 700px;
display: grid;
grid-template-columns: 300px 400px;
}
.popup-messages {
grid-column: 1 / 3;
margin: 0 10px;
grid-column: 1 / 3;
margin: 0 10px;
}
.popup-left {
grid-column: 1;
grid-column: 1;
}
.popup-right {
grid-column: 2;
grid-column: 2;
}
.popup-section {
margin: 10px;
margin: 10px;
}
.section-header {
height: 30px;
padding: 0 6px 0 10px;
background-color: #eee;
height: 30px;
padding: 0 6px 0 10px;
background-color: #eee;
display: flex;
justify-content: space-between;
align-items: center;
display: flex;
justify-content: space-between;
align-items: center;
}
.section-header > span {
font-size: 1.2em;
vertical-align: middle;
font-size: 1.2em;
vertical-align: middle;
}
.section-row {
margin: 10px 5px 0;
margin: 10px 5px 0;
}
.section-label {
display: block;
margin: 0 0 5px 0;
display: block;
margin: 0 0 5px 0;
}
</style>

View File

@ -1,18 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<head>
<meta charset="UTF-8" />
<title>Title</title>
<link rel="stylesheet" href="popup.css" />
<% if (NODE_ENV === 'development') { %>
<!-- Load some resources only in development environment -->
<% } %>
</head>
</head>
<body>
<body>
<div id="app"></div>
<script src="popup.js"></script>
</body>
</body>
</html>

View File

@ -1,11 +1,11 @@
import '../css/style.css';
import '../css/fontawesome.css';
import '../css/solid.css';
import "../css/style.css";
import "../css/fontawesome.css";
import "../css/solid.css";
import Vue from 'vue';
import App from './App';
import Vue from "vue";
import App from "./App";
new Vue({
el: '#app',
render: h => h(App)
})
el: "#app",
render: h => h(App)
});

View File

@ -6,67 +6,76 @@ 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);
// 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]))!;
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);
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("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")));
}
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, "\\:"));
// 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);
}
switch (cmd.name) {
case "upload_post":
return uploadPost(cmd.data);
}
}
browser.runtime.onMessage.addListener(messageHandler);

View File

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

4
src/vue-shims.d.ts vendored
View File

@ -1,4 +1,4 @@
declare module "*.vue" {
import Vue from "vue";
export default Vue;
import Vue from "vue";
export default Vue;
}

View File

@ -3,7 +3,7 @@
"outDir": "./dist/",
"sourceMap": true,
"strict": true,
"module": "es2015",
"module": "es2020",
"moduleResolution": "node",
"target": "es6",
"skipLibCheck": true,
@ -12,11 +12,6 @@
"lib": [
"es2017",
"dom"
],
"plugins": [
{
"transform": "ts-optchain/transform"
}
]
},
"include": [

View File

@ -1,118 +1,114 @@
const webpack = require('webpack');
const ejs = require('ejs');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ExtensionReloader = require('webpack-extension-reloader');
const { VueLoaderPlugin } = require('vue-loader');
const { version } = require('./package.json');
const webpack = require("webpack");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const ExtensionReloader = require("webpack-extension-reloader");
const { VueLoaderPlugin } = require("vue-loader");
const { version } = require("./package.json");
const config = {
mode: process.env.NODE_ENV,
context: __dirname + '/src',
context: __dirname + "/src",
entry: {
'scripts/content': './scripts/content.ts',
'scripts/background': './scripts/background.ts',
'popup/popup': './popup/popup.ts',
'options/options': './options/options.ts',
"scripts/content": "./scripts/content.ts",
"scripts/background": "./scripts/background.ts",
"popup/popup": "./popup/popup.ts",
"options/options": "./options/options.ts"
},
output: {
path: __dirname + '/dist',
filename: '[name].js',
path: __dirname + "/dist",
filename: "[name].js"
},
resolve: {
extensions: ['.ts', '.js', '.vue'],
extensions: [".ts", ".js", ".vue"]
},
devtool: 'inline-source-map',
performance: {
hints: false
},
devtool: "inline-source-map",
module: {
rules: [
{
test: /\.vue$/,
loaders: 'vue-loader',
loaders: "vue-loader"
},
{
test: /\.tsx?$/,
loader: 'ts-loader',
loader: "ts-loader",
exclude: /node_modules/,
options: {
appendTsSuffixTo: [/\.vue$/],
appendTsSuffixTo: [/\.vue$/]
}
},
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, 'css-loader'],
use: [MiniCssExtractPlugin.loader, "css-loader"]
},
{
test: /\.(png|jpg|gif|svg|ico)$/,
loader: 'file-loader',
loader: "file-loader",
options: {
name: '[name].[ext]?emitFile=false',
},
name: "[name].[ext]?emitFile=false"
}
},
{
test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
loader: 'file-loader',
loader: "file-loader",
options: {
name: '[name].[ext]?emitFile=false',
outputPath: '/fonts/'
},
},
],
name: "[name].[ext]?emitFile=false",
outputPath: "/fonts/"
}
}
]
},
plugins: [
new webpack.DefinePlugin({
global: 'window',
global: "window"
}),
new VueLoaderPlugin(),
new MiniCssExtractPlugin({
filename: '[name].css',
filename: "[name].css"
}),
new CopyWebpackPlugin([
{ from: 'icons', to: 'icons', ignore: ['icon.xcf'] },
{ from: 'popup/popup.html', to: 'popup/popup.html', transform: transformHtml },
{ from: 'options/options.html', to: 'options/options.html', transform: transformHtml },
{ from: "icons", to: "icons", ignore: ["icon.xcf"] },
{ from: "popup/popup.html", to: "popup/popup.html" },
{ from: "options/options.html", to: "options/options.html" },
{
from: 'manifest.json',
to: 'manifest.json',
transform: (content) => {
from: "manifest.json",
to: "manifest.json",
transform: content => {
const jsonContent = JSON.parse(content);
jsonContent.version = version;
if (config.mode === 'development') {
jsonContent['content_security_policy'] = "script-src 'self' 'unsafe-eval'; object-src 'self'";
if (config.mode === "development") {
jsonContent["content_security_policy"] = "script-src 'self' 'unsafe-eval'; object-src 'self'";
}
return JSON.stringify(jsonContent, null, 2);
},
},
]),
}
}
])
]
};
if (config.mode === 'production') {
if (config.mode === "production") {
config.plugins = (config.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"',
},
}),
"process.env": {
NODE_ENV: '"production"'
}
})
]);
}
if (process.env.HMR === 'true') {
if (process.env.HMR === "true") {
config.plugins = (config.plugins || []).concat([
new ExtensionReloader({
entries: {
contentScript: 'scripts/content',
background: 'scripts/background'
contentScript: "scripts/content",
background: "scripts/background"
}
}),
})
]);
}
function transformHtml(content) {
return ejs.render(content.toString(), {
...process.env,
});
}
module.exports = config;