parent
78fcc974da
commit
c044a68a13
|
|
@ -1,4 +1,4 @@
|
||||||
{
|
{
|
||||||
"printWidth": 120,
|
"printWidth": 120,
|
||||||
"tabWidth": 4
|
"tabWidth": 2
|
||||||
}
|
}
|
||||||
61
README.md
61
README.md
|
|
@ -4,12 +4,16 @@ Chrome/Firefox extension which can import media from various sites into a [szuru
|
||||||
|
|
||||||
## Supported sites
|
## Supported sites
|
||||||
|
|
||||||
- Gelbooru/Safebooru/Rule34.xxx
|
- Danbooru (and Safebooru variant)
|
||||||
- Danbooru (and Safebooru variant)
|
- Gelbooru/Safebooru/Rule34.xxx/tbib.org
|
||||||
- Rule34 paheal (Shimmie2)
|
- yande.re/konachan (Moebooru)
|
||||||
- yande.re/konachan (Moebooru)
|
- SankakuComplex (doesn't currently work because of the hotlink protection)
|
||||||
- Reddit
|
- Rule34 paheal (Shimmie2)
|
||||||
- Twitter
|
- E-Shuushuu
|
||||||
|
- Zerochan
|
||||||
|
- Reddit
|
||||||
|
- Twitter
|
||||||
|
- Fallback (simply grabs the largest image on a page)
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
|
|
@ -17,7 +21,7 @@ _Work in progress_
|
||||||
|
|
||||||
For development see [build/debug](#Builddebug).
|
For development see [build/debug](#Builddebug).
|
||||||
There also is a .xpi for Firefox on the [release tab](https://github.com/neobooru/SzuruChrome/releases).
|
There also is a .xpi for Firefox on the [release tab](https://github.com/neobooru/SzuruChrome/releases).
|
||||||
There _isn't_ a .crx for Chrome because you can't install it anyway, so you'll have to use the unpacked extension.
|
There _isn't_ a .crx for Chrome because you can't install it anyway, so you'll have to use the unpacked extension.
|
||||||
|
|
||||||
This extension should also work on Firefox Android (I can't test this because Firefox Android doesn't support client certificates).
|
This extension should also work on Firefox Android (I can't test this because Firefox Android doesn't support client certificates).
|
||||||
Same goes for Kiwi Browser and pretty much all other Chromium based browsers with extension support.
|
Same goes for Kiwi Browser and pretty much all other Chromium based browsers with extension support.
|
||||||
|
|
@ -26,15 +30,24 @@ The layout is obviously not designed for mobile, so at times it looks less than
|
||||||
|
|
||||||
## How does it work?
|
## 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
|
### 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
|
### 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
|
## Build/debug
|
||||||
|
|
||||||
|
|
@ -57,16 +70,16 @@ Firefox: `about:debugging` -> "Load Temporary Add-on..." -> Select any file in t
|
||||||
|
|
||||||
## Planned features
|
## Planned features
|
||||||
|
|
||||||
- Finishing the initial version of this add-on (see visual design doc for all features)
|
These are some things I might work on. Though honestly I don't expect this extension to change much anytime soon.
|
||||||
- Auto-set tag category when creating a new tag (imported tag)
|
|
||||||
- Reverse image search to check whether (similar) file already exist before uploading it
|
- 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
|
- Right click any image on a page to import it
|
||||||
- Configurable list of tags to always ignore (e.g. tagme, highres)
|
- Configurable list of tags to always ignore (e.g. tagme, highres)
|
||||||
- [low priority] Import artist commentary
|
- [low priority] Import artist commentary
|
||||||
- [low priority] Import notes
|
- [low priority] Import notes
|
||||||
- [lowest priority] Move from 'options_page' to 'options_ui'
|
- [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] 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
|
- [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
|
## FAQ
|
||||||
|
|
||||||
|
|
@ -97,10 +110,6 @@ Because the CORS spec is a bitch the preflight request is sent without the clien
|
||||||
</Location>
|
</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?
|
### 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:
|
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)
|
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
|
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?
|
5. We already have the DOM, why download it again?
|
||||||
|
|
||||||
### Why is the CSS so bad?
|
|
||||||
|
|
||||||
Because CSS scares me.
|
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load Diff
11
package.json
11
package.json
|
|
@ -1,9 +1,12 @@
|
||||||
{
|
{
|
||||||
"name": "szuru-chrome",
|
"name": "szuru-chrome",
|
||||||
"version": "0.3.2",
|
"version": "0.4.1",
|
||||||
"description": "Import media from various sites into szurubooru",
|
"description": "Import media from various sites into szurubooru.",
|
||||||
"author": "neobooru",
|
"author": "neobooru",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"repository": {
|
||||||
|
"url": "https://github.com/neobooru/SzuruChrome"
|
||||||
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "cross-env NODE_ENV=production webpack --hide-modules",
|
"build": "cross-env NODE_ENV=production webpack --hide-modules",
|
||||||
"build:dev": "cross-env NODE_ENV=development 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"
|
"watch:dev": "cross-env HMR=true npm run build:dev -- --watch"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"axios": "^0.19.2",
|
"axios": "^0.21.1",
|
||||||
"neo-scraper": "^0.2.5",
|
"neo-scraper": "^0.2.5",
|
||||||
"ts-optchain": "^0.1.8",
|
|
||||||
"vue": "^2.6.11",
|
"vue": "^2.6.11",
|
||||||
"webextension-polyfill": "^0.3.1"
|
"webextension-polyfill": "^0.3.1"
|
||||||
},
|
},
|
||||||
|
|
@ -24,7 +26,6 @@
|
||||||
"core-js": "^3.6.5",
|
"core-js": "^3.6.5",
|
||||||
"cross-env": "^5.2.1",
|
"cross-env": "^5.2.1",
|
||||||
"css-loader": "^2.1.1",
|
"css-loader": "^2.1.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.14.1",
|
"node-sass": "^4.14.1",
|
||||||
|
|
|
||||||
|
|
@ -1,53 +1,53 @@
|
||||||
#!/usr/bin/env node
|
#!/usr/bin/env node
|
||||||
|
|
||||||
const fs = require('fs');
|
const fs = require("fs");
|
||||||
const path = require('path');
|
const path = require("path");
|
||||||
const archiver = require('archiver');
|
const archiver = require("archiver");
|
||||||
|
|
||||||
const DEST_DIR = path.join(__dirname, '../dist');
|
const DEST_DIR = path.join(__dirname, "../dist");
|
||||||
const DEST_ZIP_DIR = path.join(__dirname, '../dist-zip');
|
const DEST_ZIP_DIR = path.join(__dirname, "../dist-zip");
|
||||||
|
|
||||||
const extractExtensionData = () => {
|
const extractExtensionData = () => {
|
||||||
const extPackageJson = require('../package.json');
|
const extPackageJson = require("../package.json");
|
||||||
|
|
||||||
return {
|
return {
|
||||||
name: extPackageJson.name,
|
name: extPackageJson.name,
|
||||||
version: extPackageJson.version
|
version: extPackageJson.version
|
||||||
}
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
const makeDestZipDirIfNotExists = () => {
|
const makeDestZipDirIfNotExists = () => {
|
||||||
if(!fs.existsSync(DEST_ZIP_DIR)) {
|
if (!fs.existsSync(DEST_ZIP_DIR)) {
|
||||||
fs.mkdirSync(DEST_ZIP_DIR);
|
fs.mkdirSync(DEST_ZIP_DIR);
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
const buildZip = (src, dist, zipFilename) => {
|
const buildZip = (src, dist, zipFilename) => {
|
||||||
console.info(`Building ${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));
|
const stream = fs.createWriteStream(path.join(dist, zipFilename));
|
||||||
|
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
archive
|
archive
|
||||||
.directory(src, false)
|
.directory(src, false)
|
||||||
.on('error', err => reject(err))
|
.on("error", err => reject(err))
|
||||||
.pipe(stream);
|
.pipe(stream);
|
||||||
|
|
||||||
stream.on('close', () => resolve());
|
stream.on("close", () => resolve());
|
||||||
archive.finalize();
|
archive.finalize();
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const main = () => {
|
const main = () => {
|
||||||
const {name, version} = extractExtensionData();
|
const { name, version } = extractExtensionData();
|
||||||
const zipFilename = `${name}-v${version}.zip`;
|
const zipFilename = `${name}-v${version}.zip`;
|
||||||
|
|
||||||
makeDestZipDirIfNotExists();
|
makeDestZipDirIfNotExists();
|
||||||
|
|
||||||
buildZip(DEST_DIR, DEST_ZIP_DIR, zipFilename)
|
buildZip(DEST_DIR, DEST_ZIP_DIR, zipFilename)
|
||||||
.then(() => console.info('OK'))
|
.then(() => console.info("OK"))
|
||||||
.catch(console.err);
|
.catch(console.err);
|
||||||
};
|
};
|
||||||
|
|
||||||
main();
|
main();
|
||||||
|
|
|
||||||
|
|
@ -2,31 +2,31 @@ export type BrowserCommandName = "grab_post" | "upload_post" | "push_message" |
|
||||||
export type MessageType = "error" | "info" | "success";
|
export type MessageType = "error" | "info" | "success";
|
||||||
|
|
||||||
export class BrowserCommand {
|
export class BrowserCommand {
|
||||||
name: BrowserCommandName;
|
name: BrowserCommandName;
|
||||||
data: any;
|
data: any;
|
||||||
|
|
||||||
constructor(name: BrowserCommandName, data: any = null) {
|
constructor(name: BrowserCommandName, data: any = null) {
|
||||||
this.name = name;
|
this.name = name;
|
||||||
this.data = data;
|
this.data = data;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export class Message {
|
export class Message {
|
||||||
content: string;
|
content: string;
|
||||||
level: MessageType;
|
level: MessageType;
|
||||||
category: string;
|
category: string;
|
||||||
|
|
||||||
constructor(content: string, level: MessageType = "info", category: string | null = null) {
|
constructor(content: string, level: MessageType = "info", category: string | null = null) {
|
||||||
this.content = content;
|
this.content = content;
|
||||||
this.level = level;
|
this.level = level;
|
||||||
this.category = category ?? "none";
|
this.category = category ?? "none";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getUrl(root: string, ...parts: string[]): string {
|
export function getUrl(root: string, ...parts: string[]): string {
|
||||||
let url = root.replace(/\/+$/, "");
|
let url = root.replace(/\/+$/, "");
|
||||||
for (const part of parts) {
|
for (const part of parts) {
|
||||||
url += "/" + part.replace(/\/+$/, "");
|
url += "/" + part.replace(/\/+$/, "");
|
||||||
}
|
}
|
||||||
return url;
|
return url;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,36 +1,36 @@
|
||||||
import { browser } from "webextension-polyfill-ts";
|
import { browser } from "webextension-polyfill-ts";
|
||||||
|
|
||||||
export class SzuruSiteConfig {
|
export class SzuruSiteConfig {
|
||||||
domain: string = "";
|
domain: string = "";
|
||||||
username: string = "";
|
username: string = "";
|
||||||
authToken: string = "";
|
authToken: string = "";
|
||||||
}
|
}
|
||||||
|
|
||||||
export class Config {
|
export class Config {
|
||||||
importExistingTags: boolean = true;
|
importExistingTags: boolean = true;
|
||||||
importAllTags: boolean = false;
|
importAllTags: boolean = false;
|
||||||
importCommentary: boolean = false;
|
importCommentary: boolean = false;
|
||||||
autoSearchSimilar: boolean = false;
|
autoSearchSimilar: boolean = false;
|
||||||
sites: Array<SzuruSiteConfig> = [];
|
sites: Array<SzuruSiteConfig> = [];
|
||||||
|
|
||||||
public async save() {
|
public async save() {
|
||||||
await browser.storage.local.set({
|
await browser.storage.local.set({
|
||||||
config: JSON.stringify(this)
|
config: JSON.stringify(this)
|
||||||
});
|
});
|
||||||
|
|
||||||
console.dir("Save " + JSON.stringify(this));
|
console.dir("Save " + JSON.stringify(this));
|
||||||
console.log("Saved config");
|
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> {
|
console.dir("Load " + JSON.stringify(config));
|
||||||
let storage = await browser.storage.local.get("config");
|
return 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;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -4,99 +4,99 @@
|
||||||
|
|
||||||
export type Safety = "safe" | "sketchy" | "unsafe";
|
export type Safety = "safe" | "sketchy" | "unsafe";
|
||||||
|
|
||||||
export type TagsResult = PagedSearchResult<Tag>
|
export type TagsResult = PagedSearchResult<Tag>;
|
||||||
export type TagCategoriesResult = UnpagedSearchResult<TagCategory>
|
export type TagCategoriesResult = UnpagedSearchResult<TagCategory>;
|
||||||
|
|
||||||
export interface SzuruError {
|
export interface SzuruError {
|
||||||
name: string;
|
name: string;
|
||||||
title: string;
|
title: string;
|
||||||
description: string;
|
description: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PagedSearchResult<T> {
|
export interface PagedSearchResult<T> {
|
||||||
query: string;
|
query: string;
|
||||||
offset: number;
|
offset: number;
|
||||||
limit: number;
|
limit: number;
|
||||||
total: number;
|
total: number;
|
||||||
results: T[];
|
results: T[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UnpagedSearchResult<T> {
|
export interface UnpagedSearchResult<T> {
|
||||||
results: T[];
|
results: T[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface MicroTag {
|
export interface MicroTag {
|
||||||
names: string[];
|
names: string[];
|
||||||
category: string;
|
category: string;
|
||||||
usages: number;
|
usages: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Tag {
|
export interface Tag {
|
||||||
names: string[];
|
names: string[];
|
||||||
category: string;
|
category: string;
|
||||||
version: number;
|
version: number;
|
||||||
description?: string; // Markdown
|
description?: string; // Markdown
|
||||||
creationTime: Date;
|
creationTime: Date;
|
||||||
lastEditTime?: Date;
|
lastEditTime?: Date;
|
||||||
usages: number;
|
usages: number;
|
||||||
suggestions: MicroTag[];
|
suggestions: MicroTag[];
|
||||||
implications: MicroTag[];
|
implications: MicroTag[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface TagCategory {
|
export interface TagCategory {
|
||||||
name: string;
|
name: string;
|
||||||
version: number;
|
version: number;
|
||||||
color: string;
|
color: string;
|
||||||
usages: number;
|
usages: number;
|
||||||
default: boolean;
|
default: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface MicroUser {
|
export interface MicroUser {
|
||||||
name: string;
|
name: string;
|
||||||
avatarUrl: string;
|
avatarUrl: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Post {
|
export interface Post {
|
||||||
id: number;
|
id: number;
|
||||||
version: number;
|
version: number;
|
||||||
creationTime: Date;
|
creationTime: Date;
|
||||||
lastEditTime?: Date;
|
lastEditTime?: Date;
|
||||||
safety: Safety;
|
safety: Safety;
|
||||||
source: string;
|
source: string;
|
||||||
type: string;
|
type: string;
|
||||||
mimeType: string;
|
mimeType: string;
|
||||||
checksum: string;
|
checksum: string;
|
||||||
fileSize: number;
|
fileSize: number;
|
||||||
canvasWidth: number;
|
canvasWidth: number;
|
||||||
canvasHeight: number;
|
canvasHeight: number;
|
||||||
contentUrl: string;
|
contentUrl: string;
|
||||||
thumbnailUrl: string;
|
thumbnailUrl: string;
|
||||||
flags: string[];
|
flags: string[];
|
||||||
tags: MicroTag[];
|
tags: MicroTag[];
|
||||||
relations: any[]; // MicroPost resource
|
relations: any[]; // MicroPost resource
|
||||||
user: MicroUser;
|
user: MicroUser;
|
||||||
score: number;
|
score: number;
|
||||||
ownScore: number;
|
ownScore: number;
|
||||||
ownFavorite: boolean;
|
ownFavorite: boolean;
|
||||||
tagCount: number;
|
tagCount: number;
|
||||||
favoriteCount: number;
|
favoriteCount: number;
|
||||||
commentCount: number;
|
commentCount: number;
|
||||||
noteCount: number;
|
noteCount: number;
|
||||||
relationCount: number;
|
relationCount: number;
|
||||||
featureCount: number;
|
featureCount: number;
|
||||||
lastFeatureTime?: Date;
|
lastFeatureTime?: Date;
|
||||||
favoritedBy: MicroUser[];
|
favoritedBy: MicroUser[];
|
||||||
hasCustomThumbnail: boolean;
|
hasCustomThumbnail: boolean;
|
||||||
notes: any[]; // Note resource
|
notes: any[]; // Note resource
|
||||||
comments: any[]; // Comment resource
|
comments: any[]; // Comment resource
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface SimilarPost {
|
export interface SimilarPost {
|
||||||
distance: number;
|
distance: number;
|
||||||
post: Post;
|
post: Post;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ImageSearchResult {
|
export interface ImageSearchResult {
|
||||||
exactPost: Post | null;
|
exactPost: Post | null;
|
||||||
similarPosts: SimilarPost[];
|
similarPosts: SimilarPost[];
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -9,122 +9,122 @@ import { TagsResult, TagCategoriesResult, Post, Tag, SzuruError, ImageSearchResu
|
||||||
* @class SzuruWrapper
|
* @class SzuruWrapper
|
||||||
*/
|
*/
|
||||||
export default class SzuruWrapper {
|
export default class SzuruWrapper {
|
||||||
baseUrl: string;
|
baseUrl: string;
|
||||||
apiUrl: string;
|
apiUrl: string;
|
||||||
username: string;
|
username: string;
|
||||||
authToken: string;
|
authToken: string;
|
||||||
|
|
||||||
private readonly baseHeaders = {
|
private readonly baseHeaders = {
|
||||||
"Accept": "application/json",
|
Accept: "application/json",
|
||||||
"Content-Type": "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
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
console.log("Create new post object");
|
||||||
* Creates an instance of SzuruWrapper.
|
console.dir(obj);
|
||||||
* @param {string} baseUrl
|
|
||||||
* @memberof SzuruWrapper
|
return (await this.apiPost("posts", obj)).data;
|
||||||
*/
|
}
|
||||||
constructor(baseUrl: string, username: string, authToken: string) {
|
|
||||||
const x = baseUrl.replace(/\/+$/, ""); // Trim trailing slashes, to make sure we only have one
|
async reverseSearch(imageUrl: string): Promise<ImageSearchResult> {
|
||||||
this.baseUrl = x + "/";
|
var obj = {
|
||||||
this.apiUrl = x + "/api/";
|
contentUrl: imageUrl
|
||||||
this.username = username;
|
};
|
||||||
this.authToken = authToken;
|
|
||||||
|
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> {
|
try {
|
||||||
return (await this.apiGet("info")).data;
|
return await axios(config);
|
||||||
|
} catch (ex) {
|
||||||
|
const error = ex.response.data as SzuruError;
|
||||||
|
throw error ? error : ex;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async updateTag(tag: Tag): Promise<any> {
|
static async createFromConfig(siteConfig: SzuruSiteConfig): Promise<SzuruWrapper | null> {
|
||||||
return (await this.apiPut("tag/" + tag.names[0], tag)).data;
|
return new SzuruWrapper(siteConfig.domain, siteConfig.username, siteConfig.authToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
{
|
{
|
||||||
"name": "SzuruChrome",
|
"name": "SzuruChrome",
|
||||||
"description": "Import media from various sites into szurubooru",
|
"description": "Import media from various sites into szurubooru.",
|
||||||
"version": null,
|
"version": null,
|
||||||
"manifest_version": 2,
|
"manifest_version": 2,
|
||||||
"icons": {
|
"icons": {
|
||||||
|
|
@ -34,7 +34,7 @@
|
||||||
},
|
},
|
||||||
"browser_specific_settings": {
|
"browser_specific_settings": {
|
||||||
"gecko": {
|
"gecko": {
|
||||||
"id": "{8cc2afc8-6c4a-4d2b-9513-46e46e5b4208}"
|
"id": "{13372607-2257-4360-8f51-5ce66fa73350}"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -1,134 +1,129 @@
|
||||||
<template>
|
<template>
|
||||||
<div class="settings-container">
|
<div class="settings-container">
|
||||||
<div class="settings-header">
|
<div class="settings-header">
|
||||||
<strong>SzuruChrome settings</strong>
|
<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>
|
</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>
|
</template>
|
||||||
|
|
||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import Vue from "vue";
|
import Vue from "vue";
|
||||||
import { oc } from "ts-optchain";
|
|
||||||
import SzuruWrapper from "../SzuruWrapper";
|
import SzuruWrapper from "../SzuruWrapper";
|
||||||
import { Config, SzuruSiteConfig } from "../Config";
|
import { Config, SzuruSiteConfig } from "../Config";
|
||||||
|
|
||||||
export default Vue.extend({
|
export default Vue.extend({
|
||||||
data() {
|
data() {
|
||||||
return {
|
return {
|
||||||
domain: "",
|
domain: "",
|
||||||
username: "",
|
username: "",
|
||||||
authToken: "",
|
authToken: "",
|
||||||
autoSearchSimilar: false
|
autoSearchSimilar: false,
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
methods: {
|
methods: {
|
||||||
async testConnection() {
|
async testConnection() {
|
||||||
if (!this.domain || !this.username || !this.authToken) {
|
if (!this.domain || !this.username || !this.authToken) {
|
||||||
alert("Domain, username and authentication token are all required.");
|
alert("Domain, username and authentication token are all required.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const api = new SzuruWrapper(this.domain, this.username, this.authToken);
|
const api = new SzuruWrapper(this.domain, this.username, this.authToken);
|
||||||
try {
|
try {
|
||||||
const info = (await api.getInfo()) as any;
|
const info = (await api.getInfo()) as any;
|
||||||
const instanceName = oc(info).config.domain;
|
const instanceName = info?.config.name;
|
||||||
|
|
||||||
if (instanceName == undefined) {
|
if (instanceName == undefined) {
|
||||||
alert(`Connected to ${this.domain}, but it is not a szurubooru instance.`);
|
alert(`Connected to ${this.domain}, but it is not a szurubooru instance.`);
|
||||||
} else {
|
} else {
|
||||||
alert(`Connected to ${info.config.name} at ${this.domain}`);
|
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();
|
|
||||||
}
|
}
|
||||||
|
} catch (ex) {
|
||||||
|
alert("Couldn't connect to " + this.domain + "\n\n" + ex);
|
||||||
|
}
|
||||||
},
|
},
|
||||||
async mounted() {
|
async saveSettings() {
|
||||||
let config = await Config.load();
|
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
|
await config.save();
|
||||||
if (config.sites.length > 0) {
|
},
|
||||||
this.domain = config.sites[0].domain;
|
},
|
||||||
this.username = config.sites[0].username;
|
async mounted() {
|
||||||
this.authToken = config.sites[0].authToken;
|
let config = await Config.load();
|
||||||
this.autoSearchSimilar = config.autoSearchSimilar;
|
|
||||||
}
|
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>
|
</script>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
.settings-container {
|
.settings-container {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
position: absolute;
|
position: absolute;
|
||||||
top: 50%;
|
top: 50%;
|
||||||
left: 50%;
|
left: 50%;
|
||||||
-ms-transform: translate(-50%, -50%);
|
-ms-transform: translate(-50%, -50%);
|
||||||
transform: translate(-50%, -50%);
|
transform: translate(-50%, -50%);
|
||||||
|
|
||||||
padding: 20px;
|
padding: 20px;
|
||||||
background-color: #f5f5f5;
|
background-color: #f5f5f5;
|
||||||
}
|
}
|
||||||
|
|
||||||
.settings-header {
|
.settings-header {
|
||||||
padding: 0 0 20px 0;
|
padding: 0 0 20px 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.settings-footer-buttons {
|
.settings-footer-buttons {
|
||||||
padding: 20px 0 0 0;
|
padding: 20px 0 0 0;
|
||||||
float: right;
|
float: right;
|
||||||
}
|
}
|
||||||
|
|
||||||
.settings-content > label {
|
.settings-content > label {
|
||||||
display: inline-block;
|
display: inline-block;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|
|
||||||
|
|
@ -1,18 +1,13 @@
|
||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
|
<head>
|
||||||
<head>
|
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<title>SzuruChrome - Options</title>
|
<title>SzuruChrome - Options</title>
|
||||||
<link rel="stylesheet" href="options.css" />
|
<link rel="stylesheet" href="options.css" />
|
||||||
<% if (NODE_ENV === 'development') { %>
|
</head>
|
||||||
<!-- Load some resources only in development environment -->
|
|
||||||
<% } %>
|
|
||||||
</head>
|
|
||||||
|
|
||||||
<body>
|
<body>
|
||||||
<div id="app"></div>
|
<div id="app"></div>
|
||||||
<script src="options.js"></script>
|
<script src="options.js"></script>
|
||||||
</body>
|
</body>
|
||||||
|
|
||||||
</html>
|
</html>
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,9 @@
|
||||||
import '../css/style.css';
|
import "../css/style.css";
|
||||||
|
|
||||||
import Vue from 'vue';
|
import Vue from "vue";
|
||||||
import App from './App';
|
import App from "./App";
|
||||||
|
|
||||||
new Vue({
|
new Vue({
|
||||||
el: '#app',
|
el: "#app",
|
||||||
render: h => h(App)
|
render: h => h(App)
|
||||||
})
|
});
|
||||||
|
|
|
||||||
|
|
@ -1,106 +1,93 @@
|
||||||
<template>
|
<template>
|
||||||
<div class="popup-container">
|
<div class="popup-container">
|
||||||
<div class="popup-messages">
|
<div class="popup-messages">
|
||||||
<ul class="messages">
|
<ul class="messages">
|
||||||
<li
|
<li v-for="msg in messages" :key="msg.name" :class="getMessageClasses(msg)" v-html="msg.content"></li>
|
||||||
v-for="msg in messages"
|
</ul>
|
||||||
: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>
|
</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>
|
</template>
|
||||||
|
|
||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
|
|
@ -113,262 +100,262 @@ import { Config, SzuruSiteConfig } from "../Config";
|
||||||
import { BrowserCommand, Message, getUrl } from "../Common";
|
import { BrowserCommand, Message, getUrl } from "../Common";
|
||||||
|
|
||||||
class ScrapedPostViewModel extends ScrapedPost {
|
class ScrapedPostViewModel extends ScrapedPost {
|
||||||
name: string = "";
|
name: string = "";
|
||||||
}
|
}
|
||||||
|
|
||||||
export default Vue.extend({
|
export default Vue.extend({
|
||||||
data() {
|
data() {
|
||||||
return {
|
return {
|
||||||
config: null as Config | null,
|
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,
|
||||||
posts: [] as ScrapedPostViewModel[],
|
posts: [] as ScrapedPostViewModel[],
|
||||||
selectedPost: new ScrapedPost(), // Shouldn't be null because VueJS gets a mental breakdown when it sees a null.
|
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();
|
||||||
|
}
|
||||||
},
|
},
|
||||||
watch: {
|
},
|
||||||
selectedPost() {
|
methods: {
|
||||||
if (this.config && this.config.autoSearchSimilar) {
|
// Try to scrape the post from the page
|
||||||
// No need to check if any vars are unset, findSimilar does that internally
|
async grabPost() {
|
||||||
this.findSimilar();
|
// 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 upload the post to the selected szurubooru instance
|
||||||
// Try to scrape the post from the page
|
async upload() {
|
||||||
async grabPost() {
|
window.scrollTo(0, 0);
|
||||||
// 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
|
// Outsource to background.ts
|
||||||
const x = await browser.tabs.sendMessage(activeTab.id!, new BrowserCommand("grab_post"));
|
const cmd = new BrowserCommand("upload_post", this.selectedPost);
|
||||||
// We need to create a new ScrapeResults object and fill it with our data, because the get_posts()
|
await browser.runtime.sendMessage(cmd);
|
||||||
// method gets 'lost' when sent from the contentscript to the popup (it gets JSON.stringified and any prototype defines are lost there)
|
// TODO: Handle errors/status update
|
||||||
const res = Object.assign(new ScrapeResults(), x);
|
},
|
||||||
|
// 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
|
if (tag.category) {
|
||||||
this.posts = [];
|
classes.push("tag-" + tag.category);
|
||||||
|
} else {
|
||||||
|
classes.push("tag-general");
|
||||||
|
}
|
||||||
|
|
||||||
for (var result of res.results) {
|
return classes;
|
||||||
for (var i in result.posts) {
|
},
|
||||||
const vm = Object.assign(new ScrapedPostViewModel(), result.posts[i]);
|
// Remove tag from post's taglist
|
||||||
vm.name = `[${result.engine}] Post ${parseInt(i) + 1}`; // parseInt() is required!
|
removeTag(tag: ScrapedTag) {
|
||||||
this.posts.push(vm);
|
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) {
|
switch (message.level) {
|
||||||
this.selectedPost = this.posts[0];
|
case "error":
|
||||||
} else {
|
classes.push("message-error");
|
||||||
this.pushInfo("No posts found.");
|
break;
|
||||||
}
|
case "success":
|
||||||
},
|
classes.push("message-success");
|
||||||
// Try to upload the post to the selected szurubooru instance
|
break;
|
||||||
async upload() {
|
}
|
||||||
window.scrollTo(0, 0);
|
|
||||||
|
|
||||||
// Outsource to background.ts
|
return classes;
|
||||||
const cmd = new BrowserCommand("upload_post", this.selectedPost);
|
},
|
||||||
await browser.runtime.sendMessage(cmd);
|
// Add info message
|
||||||
// TODO: Handle errors/status update
|
pushInfo(message: string, category: string | null = null): Message {
|
||||||
},
|
let msg = new Message(message, "info", category);
|
||||||
// Open extension settings page in new tab
|
this.messages.push(msg);
|
||||||
async openSettings() {
|
return msg;
|
||||||
const url = browser.extension.getURL("options/options.html");
|
},
|
||||||
window.open(url);
|
// Add error message
|
||||||
},
|
pushError(message: string, category: string | null = null): Message {
|
||||||
getTagClasses(tag: ScrapedTag): string[] {
|
let msg = new Message(message, "error", category);
|
||||||
let classes: string[] = [];
|
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) {
|
this.clearMessages("FIND_SIMILAR");
|
||||||
classes.push("tag-" + tag.category);
|
|
||||||
} else {
|
|
||||||
classes.push("tag-general");
|
|
||||||
}
|
|
||||||
|
|
||||||
return classes;
|
const msg = this.pushInfo("Searching for similar posts...", "FIND_SIMILAR");
|
||||||
},
|
const res = await this.szuru.reverseSearch(this.selectedPost.imageUrl);
|
||||||
// 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[] = [];
|
|
||||||
|
|
||||||
switch (message.level) {
|
if (!res.exactPost && res.similarPosts.length == 0) {
|
||||||
case "error":
|
msg.content = "No similar posts found";
|
||||||
classes.push("message-error");
|
} else {
|
||||||
break;
|
if (res.exactPost) {
|
||||||
case "success":
|
msg.content = `<a href='${this.getPostUrl(res.exactPost)}' target='_blank'>
|
||||||
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'>
|
|
||||||
Post already uploaded (${res.exactPost.id})</a>`;
|
Post already uploaded (${res.exactPost.id})</a>`;
|
||||||
msg.level = "error";
|
msg.level = "error";
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const similarPost of res.similarPosts) {
|
for (const similarPost of res.similarPosts) {
|
||||||
// Don't show this message for the exactPost (because we have a different message for that)
|
// 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) {
|
if (res.exactPost && res.exactPost.id == similarPost.post.id) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
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"
|
"FIND_SIMILAR"
|
||||||
);
|
);
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
},
|
},
|
||||||
async mounted() {
|
},
|
||||||
this.config = await Config.load();
|
async mounted() {
|
||||||
this.activeSite = this.config.sites.length > 0 ? this.config.sites[0] : null;
|
this.config = await Config.load();
|
||||||
|
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!");
|
||||||
} else {
|
} else {
|
||||||
this.szuru = await SzuruWrapper.createFromConfig(this.activeSite);
|
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();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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>
|
</script>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
.popup-container {
|
.popup-container {
|
||||||
width: 700px;
|
width: 700px;
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: 300px 400px;
|
grid-template-columns: 300px 400px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.popup-messages {
|
.popup-messages {
|
||||||
grid-column: 1 / 3;
|
grid-column: 1 / 3;
|
||||||
margin: 0 10px;
|
margin: 0 10px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.popup-left {
|
.popup-left {
|
||||||
grid-column: 1;
|
grid-column: 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
.popup-right {
|
.popup-right {
|
||||||
grid-column: 2;
|
grid-column: 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
.popup-section {
|
.popup-section {
|
||||||
margin: 10px;
|
margin: 10px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.section-header {
|
.section-header {
|
||||||
height: 30px;
|
height: 30px;
|
||||||
padding: 0 6px 0 10px;
|
padding: 0 6px 0 10px;
|
||||||
background-color: #eee;
|
background-color: #eee;
|
||||||
|
|
||||||
display: flex;
|
display: flex;
|
||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
.section-header > span {
|
.section-header > span {
|
||||||
font-size: 1.2em;
|
font-size: 1.2em;
|
||||||
vertical-align: middle;
|
vertical-align: middle;
|
||||||
}
|
}
|
||||||
|
|
||||||
.section-row {
|
.section-row {
|
||||||
margin: 10px 5px 0;
|
margin: 10px 5px 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.section-label {
|
.section-label {
|
||||||
display: block;
|
display: block;
|
||||||
margin: 0 0 5px 0;
|
margin: 0 0 5px 0;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|
|
||||||
|
|
@ -1,18 +1,13 @@
|
||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
|
<head>
|
||||||
<head>
|
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<title>Title</title>
|
<title>Title</title>
|
||||||
<link rel="stylesheet" href="popup.css" />
|
<link rel="stylesheet" href="popup.css" />
|
||||||
<% if (NODE_ENV === 'development') { %>
|
</head>
|
||||||
<!-- Load some resources only in development environment -->
|
|
||||||
<% } %>
|
|
||||||
</head>
|
|
||||||
|
|
||||||
<body>
|
<body>
|
||||||
<div id="app"></div>
|
<div id="app"></div>
|
||||||
<script src="popup.js"></script>
|
<script src="popup.js"></script>
|
||||||
</body>
|
</body>
|
||||||
|
|
||||||
</html>
|
</html>
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,11 @@
|
||||||
import '../css/style.css';
|
import "../css/style.css";
|
||||||
import '../css/fontawesome.css';
|
import "../css/fontawesome.css";
|
||||||
import '../css/solid.css';
|
import "../css/solid.css";
|
||||||
|
|
||||||
import Vue from 'vue';
|
import Vue from "vue";
|
||||||
import App from './App';
|
import App from "./App";
|
||||||
|
|
||||||
new Vue({
|
new Vue({
|
||||||
el: '#app',
|
el: "#app",
|
||||||
render: h => h(App)
|
render: h => h(App)
|
||||||
})
|
});
|
||||||
|
|
|
||||||
|
|
@ -6,67 +6,76 @@ import SzuruWrapper from "../SzuruWrapper.ts";
|
||||||
import { SzuruError } from "../SzuruTypes";
|
import { SzuruError } from "../SzuruTypes";
|
||||||
|
|
||||||
async function uploadPost(post: ScrapedPost) {
|
async function uploadPost(post: ScrapedPost) {
|
||||||
// TODO: Upload post and send status updates to popup
|
// TODO: Upload post and send status updates to popup
|
||||||
console.dir(post);
|
console.dir(post);
|
||||||
|
|
||||||
const cfg = await Config.load();
|
const cfg = await Config.load();
|
||||||
const szuru = (await SzuruWrapper.createFromConfig(cfg.sites[0]))!;
|
const szuru = (await SzuruWrapper.createFromConfig(cfg.sites[0]))!;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Create and upload post
|
// Create and upload post
|
||||||
browser.runtime.sendMessage(new BrowserCommand("remove_messages", 10));
|
browser.runtime.sendMessage(new BrowserCommand("remove_messages", 10));
|
||||||
browser.runtime.sendMessage(new BrowserCommand("push_message", new Message("Uploading...")));
|
browser.runtime.sendMessage(new BrowserCommand("push_message", new Message("Uploading...")));
|
||||||
const createdPost = await szuru.createPost(post);
|
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("remove_messages", 1));
|
||||||
browser.runtime.sendMessage(new BrowserCommand("push_message", new Message("Uploaded post " + createdPost.id, "success")));
|
browser.runtime.sendMessage(
|
||||||
|
new BrowserCommand("push_message", new Message(`Updating tag ${i}/${unsetCategoryTags.length}`))
|
||||||
// TODO: Clicking a link doesn't actually open it in a new tab,
|
);
|
||||||
// see https://stackoverflow.com/questions/8915845
|
tags[i].category = tagsWithCategory.find(x => tags[i].names.includes(x.name))!.category!;
|
||||||
// uploadMsg.content = `<a href='${this.getPostUrl(createdPost)}' target='_blank'>Uploaded post</a>`;
|
await szuru.updateTag(tags[i]);
|
||||||
// uploadMsg.type = "success";
|
}
|
||||||
|
browser.runtime.sendMessage(new BrowserCommand("remove_messages", 1));
|
||||||
// Find tags with "default" category and update it
|
browser.runtime.sendMessage(
|
||||||
// TODO: Make all these categories configurable
|
new BrowserCommand("push_message", new Message(`Updated ${tags.length} tags`, "success"))
|
||||||
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")));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
} 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) {
|
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 an error message about unknown named token.
|
||||||
// Searching for posts with re\:zero will show posts tagged with re:zero.
|
// Searching for posts with re\:zero will show posts tagged with re:zero.
|
||||||
return encodeURIComponent(tagName.replace(/\:/g, "\\:"));
|
return encodeURIComponent(tagName.replace(/\:/g, "\\:"));
|
||||||
}
|
}
|
||||||
|
|
||||||
async function messageHandler(cmd: BrowserCommand, sender: Runtime.MessageSender): Promise<any> {
|
async function messageHandler(cmd: BrowserCommand, sender: Runtime.MessageSender): Promise<any> {
|
||||||
switch (cmd.name) {
|
switch (cmd.name) {
|
||||||
case "upload_post": return uploadPost(cmd.data);
|
case "upload_post":
|
||||||
}
|
return uploadPost(cmd.data);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
browser.runtime.onMessage.addListener(messageHandler);
|
browser.runtime.onMessage.addListener(messageHandler);
|
||||||
|
|
|
||||||
|
|
@ -3,14 +3,15 @@ import { browser, Runtime } from "webextension-polyfill-ts";
|
||||||
import { BrowserCommand } from "../Common";
|
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(cmd: BrowserCommand, sender: Runtime.MessageSender): Promise<any> {
|
async function messageHandler(cmd: BrowserCommand, sender: Runtime.MessageSender): Promise<any> {
|
||||||
switch (cmd.name) {
|
switch (cmd.name) {
|
||||||
case "grab_post": return grabPost();
|
case "grab_post":
|
||||||
}
|
return grabPost();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
browser.runtime.onMessage.addListener(messageHandler);
|
browser.runtime.onMessage.addListener(messageHandler);
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
declare module "*.vue" {
|
declare module "*.vue" {
|
||||||
import Vue from "vue";
|
import Vue from "vue";
|
||||||
export default Vue;
|
export default Vue;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,7 @@
|
||||||
"outDir": "./dist/",
|
"outDir": "./dist/",
|
||||||
"sourceMap": true,
|
"sourceMap": true,
|
||||||
"strict": true,
|
"strict": true,
|
||||||
"module": "es2015",
|
"module": "es2020",
|
||||||
"moduleResolution": "node",
|
"moduleResolution": "node",
|
||||||
"target": "es6",
|
"target": "es6",
|
||||||
"skipLibCheck": true,
|
"skipLibCheck": true,
|
||||||
|
|
@ -12,11 +12,6 @@
|
||||||
"lib": [
|
"lib": [
|
||||||
"es2017",
|
"es2017",
|
||||||
"dom"
|
"dom"
|
||||||
],
|
|
||||||
"plugins": [
|
|
||||||
{
|
|
||||||
"transform": "ts-optchain/transform"
|
|
||||||
}
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"include": [
|
"include": [
|
||||||
|
|
|
||||||
|
|
@ -1,118 +1,114 @@
|
||||||
const webpack = require('webpack');
|
const webpack = require("webpack");
|
||||||
const ejs = require('ejs');
|
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
|
||||||
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
|
const CopyWebpackPlugin = require("copy-webpack-plugin");
|
||||||
const CopyWebpackPlugin = require('copy-webpack-plugin');
|
const ExtensionReloader = require("webpack-extension-reloader");
|
||||||
const ExtensionReloader = require('webpack-extension-reloader');
|
const { VueLoaderPlugin } = require("vue-loader");
|
||||||
const { VueLoaderPlugin } = require('vue-loader');
|
const { version } = require("./package.json");
|
||||||
const { version } = require('./package.json');
|
|
||||||
|
|
||||||
const config = {
|
const config = {
|
||||||
mode: process.env.NODE_ENV,
|
mode: process.env.NODE_ENV,
|
||||||
context: __dirname + '/src',
|
context: __dirname + "/src",
|
||||||
entry: {
|
entry: {
|
||||||
'scripts/content': './scripts/content.ts',
|
"scripts/content": "./scripts/content.ts",
|
||||||
'scripts/background': './scripts/background.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"
|
||||||
},
|
},
|
||||||
output: {
|
output: {
|
||||||
path: __dirname + '/dist',
|
path: __dirname + "/dist",
|
||||||
filename: '[name].js',
|
filename: "[name].js"
|
||||||
},
|
},
|
||||||
resolve: {
|
resolve: {
|
||||||
extensions: ['.ts', '.js', '.vue'],
|
extensions: [".ts", ".js", ".vue"]
|
||||||
},
|
},
|
||||||
devtool: 'inline-source-map',
|
performance: {
|
||||||
|
hints: false
|
||||||
|
},
|
||||||
|
devtool: "inline-source-map",
|
||||||
module: {
|
module: {
|
||||||
rules: [
|
rules: [
|
||||||
{
|
{
|
||||||
test: /\.vue$/,
|
test: /\.vue$/,
|
||||||
loaders: 'vue-loader',
|
loaders: "vue-loader"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
test: /\.tsx?$/,
|
test: /\.tsx?$/,
|
||||||
loader: 'ts-loader',
|
loader: "ts-loader",
|
||||||
exclude: /node_modules/,
|
exclude: /node_modules/,
|
||||||
options: {
|
options: {
|
||||||
appendTsSuffixTo: [/\.vue$/],
|
appendTsSuffixTo: [/\.vue$/]
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
test: /\.css$/,
|
test: /\.css$/,
|
||||||
use: [MiniCssExtractPlugin.loader, 'css-loader'],
|
use: [MiniCssExtractPlugin.loader, "css-loader"]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
test: /\.(png|jpg|gif|svg|ico)$/,
|
test: /\.(png|jpg|gif|svg|ico)$/,
|
||||||
loader: 'file-loader',
|
loader: "file-loader",
|
||||||
options: {
|
options: {
|
||||||
name: '[name].[ext]?emitFile=false',
|
name: "[name].[ext]?emitFile=false"
|
||||||
},
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
|
test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
|
||||||
loader: 'file-loader',
|
loader: "file-loader",
|
||||||
options: {
|
options: {
|
||||||
name: '[name].[ext]?emitFile=false',
|
name: "[name].[ext]?emitFile=false",
|
||||||
outputPath: '/fonts/'
|
outputPath: "/fonts/"
|
||||||
},
|
}
|
||||||
},
|
}
|
||||||
],
|
]
|
||||||
},
|
},
|
||||||
plugins: [
|
plugins: [
|
||||||
new webpack.DefinePlugin({
|
new webpack.DefinePlugin({
|
||||||
global: 'window',
|
global: "window"
|
||||||
}),
|
}),
|
||||||
new VueLoaderPlugin(),
|
new VueLoaderPlugin(),
|
||||||
new MiniCssExtractPlugin({
|
new MiniCssExtractPlugin({
|
||||||
filename: '[name].css',
|
filename: "[name].css"
|
||||||
}),
|
}),
|
||||||
new CopyWebpackPlugin([
|
new CopyWebpackPlugin([
|
||||||
{ from: 'icons', to: 'icons', ignore: ['icon.xcf'] },
|
{ from: "icons", to: "icons", ignore: ["icon.xcf"] },
|
||||||
{ from: 'popup/popup.html', to: 'popup/popup.html', transform: transformHtml },
|
{ from: "popup/popup.html", to: "popup/popup.html" },
|
||||||
{ from: 'options/options.html', to: 'options/options.html', transform: transformHtml },
|
{ from: "options/options.html", to: "options/options.html" },
|
||||||
{
|
{
|
||||||
from: 'manifest.json',
|
from: "manifest.json",
|
||||||
to: 'manifest.json',
|
to: "manifest.json",
|
||||||
transform: (content) => {
|
transform: content => {
|
||||||
const jsonContent = JSON.parse(content);
|
const jsonContent = JSON.parse(content);
|
||||||
jsonContent.version = version;
|
jsonContent.version = version;
|
||||||
|
|
||||||
if (config.mode === 'development') {
|
if (config.mode === "development") {
|
||||||
jsonContent['content_security_policy'] = "script-src 'self' 'unsafe-eval'; object-src 'self'";
|
jsonContent["content_security_policy"] = "script-src 'self' 'unsafe-eval'; object-src 'self'";
|
||||||
}
|
}
|
||||||
|
|
||||||
return JSON.stringify(jsonContent, null, 2);
|
return JSON.stringify(jsonContent, null, 2);
|
||||||
},
|
}
|
||||||
},
|
}
|
||||||
]),
|
])
|
||||||
]
|
]
|
||||||
};
|
};
|
||||||
|
|
||||||
if (config.mode === 'production') {
|
if (config.mode === "production") {
|
||||||
config.plugins = (config.plugins || []).concat([
|
config.plugins = (config.plugins || []).concat([
|
||||||
new webpack.DefinePlugin({
|
new webpack.DefinePlugin({
|
||||||
'process.env': {
|
"process.env": {
|
||||||
NODE_ENV: '"production"',
|
NODE_ENV: '"production"'
|
||||||
},
|
}
|
||||||
}),
|
})
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (process.env.HMR === 'true') {
|
if (process.env.HMR === "true") {
|
||||||
config.plugins = (config.plugins || []).concat([
|
config.plugins = (config.plugins || []).concat([
|
||||||
new ExtensionReloader({
|
new ExtensionReloader({
|
||||||
entries: {
|
entries: {
|
||||||
contentScript: 'scripts/content',
|
contentScript: "scripts/content",
|
||||||
background: 'scripts/background'
|
background: "scripts/background"
|
||||||
}
|
}
|
||||||
}),
|
})
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
function transformHtml(content) {
|
|
||||||
return ejs.render(content.toString(), {
|
|
||||||
...process.env,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = config;
|
module.exports = config;
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue