Initial public commit

feature-show_image_resolution
neobooru 2019-08-04 18:36:47 +02:00
commit d49d2fd5aa
39 changed files with 12451 additions and 0 deletions

5
.gitignore vendored Normal file
View File

@ -0,0 +1,5 @@
.vscode/
/node_modules
/*.log
/dist
/dist-zip

4
.prettierrc Normal file
View File

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

105
README.md Normal file
View File

@ -0,0 +1,105 @@
# SzuruChrome
Chrome/Firefox extension which can import media from various sites into a [szurubooru](https://github.com/rr-/szurubooru) instance.
## Supported sites
- Gelbooru/Safebooru
## Installation
_Work in progress_
For development see [build/debug](#Builddebug).
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.
## 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)).
### 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.
### 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.
## Build/debug
```sh
# Install node modules
npm install
# Use any of the following commands to build once
npm run build
npm run build:dev
# Or use one of these to build + rebuild on changes
npm run watch
npm run watch:dev
```
After this you can load them in your browser.
Chrome: `chrome://extensions/` -> "Load unpacked" -> Select `./dist` folder
Firefox: `about:debugging` -> "Load Temporary Add-on..." -> Select any file in the `./dist` folder (it will load all files)
## 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
- Support more sites
- [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
### I can't connect to a szurubooru instance because it complains about CORS
See workaround below.
```apache
# CORS hack
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS"
Header always set Access-Control-Allow-Headers "Authorization, Content-Type"
# CORS custom response for OPTIONS request (because szurubooru doesn't handle this, yet)
RewriteEngine on
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=204,L]
```
### I can't connect to a szurubooru instance which requires a client certificate (Firefox only)
Because the CORS spec is a bitch the preflight request is sent without the client certificate. A workaround would be to add the following to your apache2 config. Chrome has a 'bug' where it does send the client certificate in the preflight request (the sane thing to do if you ask me).
```apache
<Location "/api">
# Can also be set to 'none'
SSLVerifyClient optional
</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:
1. The website might be offline now
2. If the website is a SPA it might not see the same version/content as you did
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.

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 168 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 181 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 139 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 147 KiB

2
docs/design/README.md Normal file
View File

@ -0,0 +1,2 @@
These might not be 100% accurate
E.g. source is seen as a direct image link, but it is generally set to the post page and status messages aren't included (as I only thought of those after finishing all the design stuff).

6792
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

43
package.json Normal file
View File

@ -0,0 +1,43 @@
{
"name": "szuru-chrome",
"version": "0.1.0",
"description": "Import media from various sites into szurubooru",
"author": "neobooru",
"license": "MIT",
"scripts": {
"prettier": "prettier \"src/**/*.{ts,js,vue}\"",
"prettier:write": "npm run prettier -- --write",
"build": "cross-env NODE_ENV=production webpack --hide-modules",
"build:dev": "cross-env NODE_ENV=development webpack --hide-modules",
"build-zip": "node scripts/build-zip.js",
"watch": "npm run build -- --watch",
"watch:dev": "cross-env HMR=true npm run build:dev -- --watch"
},
"dependencies": {
"axios": "^0.19.0",
"ts-optchain": "^0.1.8",
"vue": "^2.6.10",
"webextension-polyfill": "^0.3.1"
},
"devDependencies": {
"archiver": "^3.1.1",
"copy-webpack-plugin": "^4.5.3",
"core-js": "^3.0.1",
"cross-env": "^5.2.0",
"css-loader": "^2.1.1",
"ejs": "^2.6.1",
"file-loader": "^1.1.11",
"mini-css-extract-plugin": "^0.4.4",
"node-sass": "^4.9.3",
"sass-loader": "^7.1.0",
"ts-loader": "^6.0.4",
"typescript": "^3.5.3",
"vue-loader": "^15.4.2",
"vue-template-compiler": "^2.6.10",
"web-ext-types": "^2.1.0",
"webextension-polyfill-ts": "^0.9.1",
"webpack": "^4.39.1",
"webpack-cli": "^3.1.2",
"webpack-extension-reloader": "^1.1.0"
}
}

53
scripts/build-zip.js Normal file
View File

@ -0,0 +1,53 @@
#!/usr/bin/env node
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 extractExtensionData = () => {
const extPackageJson = require('../package.json');
return {
name: extPackageJson.name,
version: extPackageJson.version
}
};
const makeDestZipDirIfNotExists = () => {
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 stream = fs.createWriteStream(path.join(dist, zipFilename));
return new Promise((resolve, reject) => {
archive
.directory(src, false)
.on('error', err => reject(err))
.pipe(stream);
stream.on('close', () => resolve());
archive.finalize();
});
};
const main = () => {
const {name, version} = extractExtensionData();
const zipFilename = `${name}-v${version}.zip`;
makeDestZipDirIfNotExists();
buildZip(DEST_DIR, DEST_ZIP_DIR, zipFilename)
.then(() => console.info('OK'))
.catch(console.err);
};
main();

36
src/Config.ts Normal file
View File

@ -0,0 +1,36 @@
import { browser } from "webextension-polyfill-ts";
export class SzuruSiteConfig {
domain: string = "";
username: string = "";
authToken: string = "";
}
export class Config {
importExistingTags: boolean = true;
importAllTags: boolean = false;
importCommentary: boolean = false;
sites: Array<SzuruSiteConfig> = [];
public async save() {
await browser.storage.local.set({
"config": JSON.stringify(this)
});
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"]));
}
console.dir("Load " + JSON.stringify(config));
return config;
}
}

39
src/SzuruTypes.ts Normal file
View File

@ -0,0 +1,39 @@
export type SzuruSafety = "safe" | "sketchy" | "unsafe";
export class SzuruCategory {
name: string;
color: string;
private constructor(name: string, color: string = "") {
this.name = name;
this.color = color;
}
static readonly Copyright = new SzuruCategory("copyright", "#a0a");
static readonly Character = new SzuruCategory("character", "#0a0");
static readonly Artist = new SzuruCategory("artist", "#a00");
static readonly Meta = new SzuruCategory("meta", "#f80");
}
export class SzuruTag {
name: string = "";
category?: SzuruCategory;
constructor(name: string, category?: SzuruCategory) {
this.name = name;
this.category = category;
}
}
export class SzuruPost {
safety: SzuruSafety = "safe";
source: string = "";
imageUrl: string = "";
tags: SzuruTag[] = [];
}
export interface SzuruError {
name: string;
title: string;
description: string;
}

99
src/SzuruWrapper.ts Normal file
View File

@ -0,0 +1,99 @@
import axios, { AxiosRequestConfig, AxiosPromise, Method } from 'axios';
import { SzuruPost, SzuruError } from './SzuruTypes';
import { Config } from './Config';
/**
* A 1:1 wrapper around the szurubooru API.
*
* @class SzuruWrapper
*/
export default class SzuruWrapper {
baseUrl: string;
apiUrl: string;
username: string;
authToken: string;
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");
}
async createPost(post: SzuruPost): Promise<void> {
var obj = {
tags: post.tags.map(x => x.name),
safety: post.safety,
source: post.source,
contentUrl: post.imageUrl
};
console.log("Create new post object");
console.dir(obj);
await this.apiPost("posts", obj);
}
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 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(): Promise<SzuruWrapper | null> {
const config = await Config.load();
if (config.sites.length == 0) {
return null;
}
return new SzuruWrapper(config.sites[0].domain, config.sites[0].username, config.sites[0].authToken);
}
}

4363
src/css/fontawesome.css vendored Normal file

File diff suppressed because it is too large Load Diff

16
src/css/solid.css Normal file
View File

@ -0,0 +1,16 @@
/*!
* Font Awesome Free 5.10.1 by @fontawesome - https://fontawesome.com
* License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License)
*/
@font-face {
font-family: 'Font Awesome 5 Free';
font-style: normal;
font-weight: 900;
font-display: auto;
src: url("../fonts/fa-solid-900.eot");
src: url("../fonts/fa-solid-900.eot?#iefix") format("embedded-opentype"), url("../fonts/fa-solid-900.woff2") format("woff2"), url("../fonts/fa-solid-900.woff") format("woff"), url("../fonts/fa-solid-900.ttf") format("truetype"); }
.fa,
.fas {
font-family: 'Font Awesome 5 Free';
font-weight: 900; }

106
src/css/style.css Normal file
View File

@ -0,0 +1,106 @@
body {
margin: 0px;
font-family: "Open Sans", sans-serif;
display: block;
font-size: 100%;
}
button {
background-color: #a2a2a2;
border: none;
color: white;
font-family: "Open Sans", sans-serif;
height: 30px;
cursor: pointer;
}
button.primary {
background-color: #24aadd;
}
input[type="text"] {
background-color: #fafafa;
border: 1px solid #eee;
height: 30px;
width: 100%;
}
img {
max-width: 100%;
max-height: 100%;
}
.full {
width: 100%;
}
select {
background-color: #fafafa;
border: 1px solid #eee;
height: 30px;
width: 100%;
font-family: "Open Sans", sans-serif;
}
.compact-tags {
list-style-type: none;
padding: 0;
display: inline;
}
.tag-copyright {
color: rgb(170, 0, 170);
}
.tag-character {
color: rgb(0, 170, 0);
}
.tag-artist {
color: rgb(170, 0, 0);
}
.tag-meta {
color: rgb(255, 128, 0);
}
.remove-tag,
.tag-usages {
color: #888;
}
a.remove-tag {
text-decoration: none;
cursor: pointer;
}
.tag-usages {
font-size: 90%;
margin-left: 0.7em;
}
.messages {
list-style-type: none;
padding: 0;
display: inline;
}
.messages > li {
padding: 5px;
border-radius: 2px;
background: #24aadd;
color: white;
}
.messages > li > a {
color: white;
text-decoration: none;
}
.messages > li:not(:last-child) {
margin-bottom: 5px;
}
.message-error {
background: #f44336 !important;
}

BIN
src/fonts/fa-solid-900.eot Normal file

Binary file not shown.

BIN
src/fonts/fa-solid-900.ttf Normal file

Binary file not shown.

BIN
src/fonts/fa-solid-900.woff Normal file

Binary file not shown.

Binary file not shown.

BIN
src/icons/icon_128.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

BIN
src/icons/icon_48.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.6 KiB

133
src/loaders/Gelbooru.ts Normal file
View File

@ -0,0 +1,133 @@
import ILoader from "./ILoader"
import { SzuruPost, SzuruTag, SzuruCategory } from "../SzuruTypes";
export default class Gelbooru implements ILoader {
canImport(location: Location): boolean {
return (
location.host == "safebooru.org" ||
location.host == "gelbooru.com"
);
}
async grabPost(dom: Document): Promise<SzuruPost | null> {
/**
* Make sure to use the `dom` variable and NOT `document`!
*/
// TODO: Replace this with version checking, instead of just one 'special case' domain
let isSafebooru: boolean;
const safebooruSiteTitle = dom.querySelector("#site-title > a") as HTMLAnchorElement;
if (safebooruSiteTitle && safebooruSiteTitle.innerText == "Safebooru") {
// If safebooru (and maybe other sites?)
isSafebooru = true;
} else {
// If gelbooru (version 0.2.5)
isSafebooru = false;
}
console.log("isSafebooru: " + isSafebooru);
let post = new SzuruPost();
// Set source to the current page (NOT a direct link to the image)
post.source = dom.location.href;
// Get image url (direct url to image)
const originalImageElements = dom.querySelectorAll("li > a");
for (const idx in originalImageElements) {
const el = originalImageElements[idx] as HTMLAnchorElement;
if (el && el.innerText == "Original image") {
post.imageUrl = el.href;
break;
}
}
// Set safety
const safetyExp = new RegExp("Rating: (.*)");
let safetyElements: NodeListOf<Element>;
if (isSafebooru) {
safetyElements = dom.querySelectorAll("#stats > ul > li");
} else {
safetyElements = dom.querySelectorAll("#tag-list > div > li");
}
for (const idx in safetyElements) {
const el = safetyElements[idx] as HTMLLIElement;
if (el && el.innerText) {
// matches is an array where (index)
// 0: full string
// 1: capture group 1 (rating, so 'Safe', 'Questionable', 'Explicit')
const matches = el.innerText.match(safetyExp);
if (matches && matches.length > 0) {
switch (matches[1].toLowerCase()) {
case "safe":
post.safety = "safe";
break;
case "questionable":
post.safety = "sketchy";
break;
case "explicit":
post.safety = "unsafe";
break;
}
}
}
}
// Set tags
let tagElements: NodeListOf<Element>;
if (isSafebooru) {
tagElements = dom.querySelectorAll("#tag-sidebar > li");
} else {
tagElements = dom.querySelectorAll("#tag-list > div > li[class^='tag-type']");
}
for (const idx in tagElements) {
const el = tagElements[idx] as HTMLLIElement;
if (el && el.innerText) {
let tagName: string;
if (isSafebooru) {
tagName = el.getElementsByTagName("a")[0].innerText.replace(/\s/g, "_");
} else {
// First <a> is "?"
// Second <a> is "actual_tag_name"
tagName = el.getElementsByTagName("a")[1].innerText.replace(/\s/g, "_");
}
let category: SzuruCategory | undefined;
switch (el.className) {
case "tag-type-copyright":
category = SzuruCategory.Copyright;
break;
case "tag-type-character":
category = SzuruCategory.Character;
break;
case "tag-type-artist":
category = SzuruCategory.Artist;
break;
case "tag-type-metadata":
category = SzuruCategory.Meta;
break;
}
let tag = new SzuruTag(tagName, category);
post.tags.push(tag);
}
}
// console.dir(post);
// If post has enough filled fields to be considered a valid post
if (post.imageUrl) {
return post;
} else {
return null;
}
}
};

6
src/loaders/ILoader.ts Normal file
View File

@ -0,0 +1,6 @@
import { SzuruPost } from "../SzuruTypes";
export default interface ILoader {
canImport(location: Location): boolean;
grabPost(dom: Document): Promise<SzuruPost | null>;
}

1
src/loaders/index.ts Normal file
View File

@ -0,0 +1 @@
export { default as Gelbooru } from "./Gelbooru";

29
src/manifest.json Normal file
View File

@ -0,0 +1,29 @@
{
"name": "SzuruChrome",
"description": "Import media from various sites into szurubooru",
"version": null,
"manifest_version": 2,
"icons": {
"48": "icons/icon_48.png",
"128": "icons/icon_128.png"
},
"browser_action": {
"default_title": "SzuruChrome",
"default_popup": "popup/popup.html"
},
"options_page": "options/options.html",
"permissions": [
"storage",
"activeTab"
],
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": [
"scripts/content.js"
]
}
]
}

122
src/options/App.vue Normal file
View File

@ -0,0 +1,122 @@
<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 />
<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: ""
};
},
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;
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];
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;
}
}
});
</script>
<style scoped>
.settings-container {
margin: 0;
position: absolute;
top: 50%;
left: 50%;
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
padding: 20px;
background-color: #f5f5f5;
}
.settings-header {
padding: 0 0 20px 0;
}
.settings-footer-buttons {
padding: 20px 0 0 0;
float: right;
}
.settings-content > label {
display: inline-block;
}
</style>

18
src/options/options.html Normal file
View File

@ -0,0 +1,18 @@
<!DOCTYPE html>
<html lang="en">
<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>
<body>
<div id="app"></div>
<script src="options.js"></script>
</body>
</html>

9
src/options/options.ts Normal file
View File

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

267
src/popup/App.vue Normal file
View File

@ -0,0 +1,267 @@
<template>
<div class="popup-container">
<div class="popup-row">
<div class="popup-column1" style="margin: 10px 10px 0px 10px;">
<ul class="messages">
<li
v-for="msg in messages"
:key="msg.name"
:class="getMessageClasses(msg)"
v-html="msg.content"
></li>
</ul>
</div>
</div>
<div class="popup-row">
<div class="popup-column2">
<div class="popup-header">
<span>Basic info</span>
<i class="fas fa-cog" @click="openSettings"></i>
</div>
<div class="popup-content">
<div class="popup-block">
<span class="block-title">Safety</span>
<label class="container">
<input type="radio" value="safe" v-model="post.safety" />
<span class="checkmark"></span>
Safe
</label>
<label class="container">
<input type="radio" value="sketchy" v-model="post.safety" />
<span class="checkmark"></span>
Sketchy
</label>
<label class="container">
<input type="radio" value="unsafe" v-model="post.safety" />
<span class="checkmark"></span>
Unsafe
</label>
</div>
<div class="popup-block">
<span class="block-title">Source</span>
<input type="text" v-model="post.source" />
</div>
</div>
<div class="popup-header">
<span>Tags</span>
</div>
<div class="popup-content">
<div class="popup-block">
<ul class="compact-tags">
<li v-for="tag in post.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>
<div class="popup-column2">
<img :src="post.imageUrl" />
</div>
</div>
<div class="popup-row">
<div class="popup-column2">
<select disabled>
<option>https://szuru.example.com</option>
</select>
</div>
<div class="popup-column2">
<button class="primary full" @click="upload">Import</button>
</div>
</div>
</div>
</template>
<script lang="ts">
import Vue from "vue";
import { browser } from "webextension-polyfill-ts";
import { SzuruPost, SzuruCategory, SzuruTag, SzuruError } from "../SzuruTypes";
import SzuruWrapper from "../SzuruWrapper";
type MessageType = "error" | "info";
class Message {
content: string;
type: MessageType;
constructor(content: string, type: MessageType = "info") {
this.content = content;
this.type = type;
}
}
export default Vue.extend({
data() {
return {
szuru: null as SzuruWrapper | null,
post: null as SzuruPost | null,
messages: [] as Message[]
};
},
methods: {
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 post = (await browser.tabs.sendMessage(activeTab.id!, "grab_post")) as SzuruPost;
if (post) {
this.post = post;
// console.dir(post);
} else {
this.pushError("Couldn't grab post");
}
},
async upload() {
// Clear messages
this.messages = [];
if (!this.post || !this.post.imageUrl) {
this.pushError("There is no post to upload!");
return;
}
if (!this.szuru) {
this.pushError("No szurubooru server configured!");
return;
}
try {
const createdPost = await this.szuru.createPost(this.post);
// TODO: Add url to post page on szurubooru
this.pushInfo("Uploaded <a href='#'>post</a>");
} catch (ex) {
const error = ex as SzuruError;
if (error) {
this.pushError(error.description);
} else {
// Probably too long for a message
alert(ex);
}
}
if (this.messages.length > 0) {
window.scrollTo(0, 0);
}
},
async openSettings() {
const url = browser.extension.getURL("options/options.html");
window.open(url);
},
getTagClasses(tag: SzuruTag): string[] {
let classes: string[] = []
if (tag.category) {
classes.push("tag-" + tag.category.name);
}
return classes;
},
removeTag(tag: SzuruTag) {
if (this.post) {
const idx = this.post.tags.indexOf(tag);
if (idx != -1) {
this.post.tags.splice(idx, 1);
}
}
},
getMessageClasses(message: Message) {
let classes: string[] = []
switch (message.type) {
case "error":
classes.push("message-error");
break;
}
return classes;
},
pushInfo(message: string) {
this.messages.push(new Message(message));
},
pushError(message: string) {
this.messages.push(new Message(message, "error"));
}
},
mounted() {
this.grabPost();
SzuruWrapper.createFromConfig().then((x) => {
if (x) {
this.szuru = x;
} else {
this.pushError("No szurubooru server configured!");
}
});
}
});
</script>
<style scoped>
.popup-container {
width: 700px;
}
.popup-row {
display: flex;
}
.popup-column1 {
flex: 100%;
margin: 10px;
}
.popup-column2 {
flex: 50%;
margin: 10px;
}
.popup-header {
height: 30px;
padding: 0 0 0 10px;
background-color: #eee;
margin: 0 0 10px 0;
}
.popup-content {
margin: 5px;
}
.popup-header > span {
vertical-align: middle;
}
/* Horrible hack + guesswork */
.popup-header > i {
float: right;
margin: 8px 5px;
cursor: pointer;
}
.popup-block {
margin: 0 0 10px 0;
}
.block-title {
display: block;
margin: 0 0 5px 0;
}
</style>

17
src/popup/popup.html Normal file
View File

@ -0,0 +1,17 @@
<!DOCTYPE html>
<html lang="en">
<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>
<body>
<div id="app">
</div>
<script src="popup.js"></script>
</body>
</html>

11
src/popup/popup.ts Normal file
View File

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

View File

@ -0,0 +1,2 @@
// Dummy file so that webpack-extension-reloader doesn't complain when running `npm run watch:dev`
// This file is excluded when not running in development mode

25
src/scripts/content.ts Normal file
View File

@ -0,0 +1,25 @@
import { browser, Runtime } from "webextension-polyfill-ts";
import * as loaders from "../loaders";
import { SzuruPost } from "../SzuruTypes";
import ILoader from "../loaders/ILoader";
async function grabPost(): Promise<SzuruPost | null> {
for (const loaderName in loaders) {
// HACK:
const loader = new (loaders as any)[loaderName]() as ILoader;
if (loader.canImport(window.location)) {
console.log(`Using ${loaderName} importer to scrape this page`)
return await loader.grabPost(document);
}
}
return null;
}
async function messageHandler(message: any, sender: Runtime.MessageSender): Promise<any> {
switch (message) {
case "grab_post": return grabPost();
}
}
browser.runtime.onMessage.addListener(messageHandler);

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

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

25
tsconfig.json Normal file
View File

@ -0,0 +1,25 @@
{
"compilerOptions": {
"outDir": "./dist/",
"sourceMap": true,
"strict": true,
"module": "es2015",
"moduleResolution": "node",
"target": "es5",
"skipLibCheck": true,
"esModuleInterop": true,
"experimentalDecorators": true,
"lib": [
"es2015",
"dom"
],
"plugins": [
{
"transform": "ts-optchain/transform"
},
]
},
"include": [
"./src/**/*"
],
}

119
webpack.config.js Normal file
View File

@ -0,0 +1,119 @@
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 config = {
mode: process.env.NODE_ENV,
context: __dirname + '/src',
entry: {
'scripts/content': './scripts/content.ts',
'popup/popup': './popup/popup.ts',
'options/options': './options/options.ts',
},
output: {
path: __dirname + '/dist',
filename: '[name].js',
},
resolve: {
extensions: ['.ts', '.js', '.vue'],
},
devtool: 'inline-source-map',
module: {
rules: [
{
test: /\.vue$/,
loaders: 'vue-loader',
},
{
test: /\.tsx?$/,
loader: 'ts-loader',
exclude: /node_modules/,
options: {
appendTsSuffixTo: [/\.vue$/],
}
},
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, 'css-loader'],
},
{
test: /\.(png|jpg|gif|svg|ico)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?emitFile=false',
},
},
{
test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?emitFile=false',
outputPath: '/fonts/'
},
},
],
},
plugins: [
new webpack.DefinePlugin({
global: 'window',
}),
new VueLoaderPlugin(),
new MiniCssExtractPlugin({
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: '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'";
}
return JSON.stringify(jsonContent, null, 2);
},
},
]),
]
};
if (config.mode === 'production') {
config.plugins = (config.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"',
},
}),
]);
}
if (process.env.HMR === 'true') {
config.entry['scripts/background'] = './scripts/background.ts';
config.plugins = (config.plugins || []).concat([
new ExtensionReloader({
entries: {
contentScript: 'scripts/content',
background: 'scripts/background'
}
}),
]);
}
function transformHtml(content) {
return ejs.render(content.toString(), {
...process.env,
});
}
module.exports = config;