yawn
5 years ago in Plain Text
//META{"name":"OCR"}*//
class OCR {
get local() {
return {
startMessage: "${pluginName} ${version} has started.",
description: 'Optical character recognition. (Image to text)',
reset: "Reset settings",
settings: {
panel: 'Settings panel',
labels: {
apikey: 'Apikey'
},
help: {},
protip: {
label: 'Protip:',
tip: 'Register for an apikey here. (500 calls/day) https://ocr.space/ocrapi'
}
}
};
}
getAuthor() {
return "Arhippa"
}
getName() {
return "OCR"
}
getDescription() {
return this.local.description
}
getVersion() {
return "0.2"
}
start() {
if (!document.getElementById(`${this.getName()}-style`)) BdApi.injectCSS(`${this.getName()}-style`, this.css.thumb);
let libraryScript = document.getElementById('ZLibraryScript');
if (typeof window.ZLibrary !== "undefined") this.initialize();
else libraryScript.addEventListener('load', () => this.initialize());
}
initialize() {
if (settingsCookie['fork-ps-2'] === false) ZLibrary.Toasts.show(ZLibrary.Utilities.formatTString(this.local.startMessage, {
pluginName: this.getName(),
version: this.getVersion()
}));
this.initialized = true;
this.loadSettings();
this.injectThumbIcons();
}
stop() {
if (document.getElementById(`${this.getName()}-style`)) BdApi.clearCSS(`${this.getName()}-style`);
this.RemoveThumbIcons();
this.initialized = false;
}
load() {
let libraryScript = document.getElementById('ZLibraryScript');
if (!ZLibrary && !libraryScript) {
libraryScript = document.createElement('script');
libraryScript.setAttribute('type', 'text/javascript');
libraryScript.addEventListener("error", function() {
if (typeof ZLibrary === "undefined") {
window.BdApi.alert("Library Missing", `The library plugin needed for ${this.getName()} is missing and could not be loaded.<br /><br /><a href="https://betterdiscord.net/ghdl?url=https://raw.githubusercontent.com/rauenzi/BDPluginLibrary/master/release/0PluginLibrary.plugin.js" target="_blank">Click here to download the library!</a>`);
}
}.bind(this));
libraryScript.setAttribute('src', 'https://rauenzi.github.io/BDPluginLibrary/release/ZLibrary.js');
libraryScript.setAttribute('id', 'ZLibraryScript');
document.head.appendChild(libraryScript);
}
}
unload() {}
injectThumbIcons() {
var fs = require('fs');
let list = document.querySelectorAll("img");
for (let i = 0; i < list.length; i++) {
let elem = list[i].parentElement;
if (!elem.href ||
!elem.classList.contains('imageWrapper-2p5ogY') ||
elem.querySelector('.thumbOCR')
) continue;
let div = document.createElement('div');
div.innerHTML = "OCR";
div.className = "thumbOCR";
this.loadSettings();
div.onclick = (e) => {
e.stopPropagation();
e.preventDefault();
this.doOCR(e);
};
elem.insertAdjacentElement('afterbegin', div);
}
this.injectionTimeout = setTimeout(this.injectThumbIcons.bind(this), 2000);
}
RemoveThumbIcons() {
clearTimeout(this.injectionTimeout);
$('div.thumbOCR').each(function(i, obj) {
$(this).remove();
});
}
saveSettings() {
ZLibrary.PluginUtilities.saveSettings(this.getName(), this.settings);
}
loadSettings() {
this.settings = ZLibrary.PluginUtilities.loadSettings(this.getName(), this.defaultSettings);
}
getSettingsPanel() {
let panel = $("<form>").addClass("form").css("width", "100%");
if (this.initialized) this.generateSettings(panel);
return panel[0];
}
generateSettings(panel) {
new ZLibrary.Settings.SettingGroup(this.local.settings.panel, {
callback: this.loadSettings(),
collapsible: false,
shown: true
}).appendTo(panel).append(
new ZLibrary.Settings.Textbox(this.local.settings.labels.apikey, '', this.settings.apikey, text => {
this.settings.apikey = text;
this.saveSettings();
}));
panel.append(
$(`<div class='protip-12obwm inline-136HKr'>
<div class='pro-1T8RK7 small-29zrCQ size12-3R0845 height16-2Lv3qA statusGreen-pvYWjA weightBold-2yjlgw'>${this.local.settings.protip.label}</div>
<div class='tip-2ab612 primary-jw0I4K'>${this.local.settings.protip.tip}</div>
</div>`),
$(`<button type="button" class="button-38aScr lookOutlined-3sRXeN colorRed-1TFJan sizeMedium-1AC_Sl grow-q77ONN" style='margin: 10px 0; float: right;'><div class="contents-18-Yxp">${this.local.reset}</div></button>`)
.click(() => {
this.settings = this.defaultSettings;
this.saveSettings();
panel.empty();
this.generateSettings(panel);
})
);
}
doOCR(e) {
var button = e.srcElement;
var url = button.parentElement.href;
if (url.endsWith('.html') && button.parentElement.getElementsByTagName('img')[0] && button.parentElement.getElementsByTagName('img')[0].src.startsWith('https://images-ext-2.discordapp.net')) {
url = button.parentElement.getElementsByTagName('img')[0].src;
url = url.substring(url.indexOf('/https'), url.indexOf('?') || url.length).substring(1).replace('https/', 'https://');
}
if (!url) {
button.innerHTML = "Error";
return;
}
button.innerHTML = "OCR'ing...";
var name = url.split('/')[6];
var xhr = new XMLHttpRequest(),
method = "GET",
url = 'https://api.ocr.space/parse/imageurl?apikey=' + this.settings.apikey + '&url=' + url;
xhr.open(method, url, true);
xhr.onreadystatechange = (e) => {
if (xhr.readyState != 4) return;
var jsonResponse = JSON.parse(xhr.responseText);
try {
var result = jsonResponse['ParsedResults'][0]['ParsedText']
button.innerHTML = "OCR'd!";
var x = document.getElementsByClassName("textArea-2Spzkt da-textArea textArea-2Spzkt da-textArea scrollbarGhostHairline-1mSOM1 scrollbar-3dvm_9 da-scrollbarGhostHairline da-scrollbar")[0];
x.focus();
document.execCommand("insertText", false, result.substring(0, result.length - 1));
var length = result.length
x.setSelectionRange(length, length);
} catch (typeerror) {
BDFDB.showToast(`Error during OCR!`)
button.innerHTML = "Error!";
}
}
xhr.send();
}
get defaultSettings() {
return {
apikey: 4c1e1876b488957
};
}
get css() {
return {
thumb: `
.thumbOCR {
z-index: 9000!important;
background-color: rgba(51, 51, 51, .9);
position: absolute;
display: block;
padding: 3px 9px;
margin: 5px;
border-radius: 3px;
font-family: inherit;
color: #FFF;
font-weight: 500;
font-size: 16px;
opacity: 0;
}
.messageGroupCozy-1BZuO8:hover .thumbOCR,
.imageWrapper-2p5ogY:hover .thumbOCR {
opacity: 0.9;
}
.thumbOCR:hover {
opacity: 1 !important;
}`
};
}
}