Compare commits

..

No commits in common. "a74163b29a446dfc6b95e211e90f3b7478bae25b" and "321cc93cf56ec5ab47c99a28a679aacd86a143d4" have entirely different histories.

7 changed files with 305 additions and 436 deletions

View File

@ -1,29 +1,50 @@
import { getDb, getKnownEmojiIds, getKnownStickerIds, storeImage } from "./db.js";
getDb();
var functions = {
async storeFiles(files, type) {
console.debug("storeFiles", files, type);
var knownIds = type == "sticker" ? await getKnownStickerIds() : await getKnownEmojiIds();
console.debug("knownIds", knownIds);
for (let file of files) {
if (knownIds.includes(file.id)) continue;
console.log("store", file.id);
await storeImage({
date: file.versions[1].created_at,
currentId_emoji: file.tags.includes("emoji") ? file.id : null,
currentId_sticker: file.tags.includes("sticker") ? file.id : null,
internalId: file.id,
animationStyle: file.animationStyle,
data: await fetch(file.versions[1].file.url).then(res => res.blob())
});
async storeEmojis(emojis) {
console.debug("storeEmojis", emojis);
var emojiStore = (await chrome.storage.local.get(["emojis"])).emojis || [];
loop1: for (let emoji of emojis) {
for (let existingEmoji of emojiStore) {
if (existingEmoji.currentId == emoji.id) continue loop1;
}
console.log("store", emoji.id);
var blob = await fetch(emoji.versions[1].file.url).then(res => res.blob());
var dataString = await blobToDataURL(blob);
var emojiDoc = {
date: emoji.versions[1].created_at,
currentId: emoji.id,
internalId: emoji.id,
animationStyle: emoji.animationStyle
};
await chrome.storage.local.set({[`data-${emojiDoc.internalId}`]: dataString});
emojiStore.push(emojiDoc);
}
chrome.storage.local.set({emojis: emojiStore});
}
};
chrome.runtime.onMessage.addListener(function([method, ...args], sender, sendResponse) {
console.debug(arguments);
functions[method].apply(null, args).then(sendResponse);
functions[method]?.apply(null, args).then(sendResponse).catch(error => sendResponse({error: error.toString()}));;
return true;
});
});
function blobToDataURL(blob) {
return new Promise((resolve, reject) => {
var reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = () => {
resolve(reader.result);
};
reader.onerror = reject;
});
}

View File

@ -1,52 +1,32 @@
fetch("https://vrchat.com/api/1/files?tag=emoji&n=100&offset=0").then(res => res.json()).then(data => {
if (!data.error)
chrome.runtime.sendMessage(["storeEmojis", data]);
});
var functions = {
async getFiles(tag = "emoji") {
var res = await fetch(`https://vrchat.com/api/1/files?tag=${tag}&n=100&offset=0`);
return {
status: res.status,
body: await res.json(),
retryAfter: res.headers.get("Retry-After") || undefined
};
async getEmojis() {
return await fetch("https://vrchat.com/api/1/files?tag=emoji&n=100&offset=0").then(res => res.json());
},
async deleteFile(id) {
var res = await fetch(`https://vrchat.com/api/1/file/${id}`, {method: "DELETE"});
return {
status: res.status,
body: await res.json(),
retryAfter: res.headers.get("Retry-After") || undefined
};
async deleteEmoji(id) {
return await fetch(`https://vrchat.com/api/1/file/${id}`, {method: "DELETE"}).then(res => res.json());
},
async createFile(url, tag = "emoji", animationStyle) {
async createEmoji(url, animationStyle) {
var blob = await fetch(url).then(res => res.blob());
var form = new FormData();
form.append("tag", tag);
if (tag == "emoji") form.append("animationStyle", animationStyle);
form.append("tag", "emoji");
form.append("animationStyle", animationStyle);
form.append("maskTag", "square");
form.append("file", blob);
var res = await fetch("https://vrchat.com/api/1/file/image", {
return await fetch("https://vrchat.com/api/1/file/image", {
method: "POST",
body: form
});
return {
status: res.status,
body: await res.json(),
retryAfter: res.headers.get("Retry-After") || undefined
};
}).then(res => res.json());
}
};
functions.getFiles("emoji").then(data => {
if (!data.error) chrome.runtime.sendMessage(["storeFiles", data.body, "emoji"]);
else console.error(data.error);
});
functions.getFiles("sticker").then(data => {
if (!data.error) chrome.runtime.sendMessage(["storeFiles", data.body, "sticker"]);
else console.error(data.error);
});
chrome.runtime.onMessage.addListener(function([method, ...args], sender, sendResponse) {
console.debug(arguments);
functions[method].apply(null, args)
.then(response => sendResponse({response}))
.catch(error => sendResponse({error: error.toString()}));
functions[method]?.apply(null, args).then(sendResponse).catch(error => sendResponse({error: error.toString()}));
return true;
});

139
db.js
View File

@ -1,139 +0,0 @@
var db;
export function getDb() {
return db ||= initDb();
}
function initDb() {
return new Promise((resolve, reject) => {
var request = indexedDB.open("database");
request.onerror = () => reject(request.error);
request.onsuccess = event => {
console.debug("onsuccess");
resolve(event.target.result);
};
request.onupgradeneeded = event => {
console.debug("onupgradeneeded");
//request.onsuccess = null;
var db = event.target.result;
var objectStore = db.createObjectStore("images", { keyPath: "internalId", autoIncrement: true });
objectStore.createIndex("currentId_emoji", "currentId_emoji", {unique: true});
objectStore.createIndex("currentId_sticker", "currentId_sticker", {unique: true});
db.createObjectStore("settings");
chrome.storage.local.get().then(async storage => {
console.debug("storage", storage);
for (let emoji of storage.emojis) {
try {
emoji.data = await fetch(storage[`data-${emoji.internalId}`]).then(res => res.blob());
await storeImage(emoji);
} catch (error) {
console.error(error);
}
}
await setSetting("defaultAnimationStyle", storage.defaultAnimationStyle);
//resolve(db);
console.debug("finished upgrade");
});
};
request.onversionchange = () => {
db = undefined; // idk
};
});
}
export async function getKnownEmojiIds() {
var db = await getDb();
return await new Promise((resolve, reject) => {
var request = db.transaction(["images"], "readonly").objectStore("images").index("currentId_emoji").getAllKeys();
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
export async function getKnownStickerIds() {
var db = await getDb();
return await new Promise((resolve, reject) => {
var request = db.transaction(["images"], "readonly").objectStore("images").index("currentId_sticker").getAllKeys();
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
export async function getAllImages() {
var db = await getDb();
return await new Promise((resolve, reject) => {
var request = db.transaction(["images"], "readonly").objectStore("images").getAll();
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
export async function storeImage(entry) {
var db = await getDb();
return await new Promise((resolve, reject) => {
var request = db.transaction(["images"], "readwrite").objectStore("images").add(entry);
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
export async function getImage(internalId) {
var db = await getDb();
return await new Promise((resolve, reject) => {
var request = db.transaction(["images"], "readonly").objectStore("images").get(internalId);
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
export async function updateImage(internalId, update) {
var db = await getDb();
return await new Promise((resolve, reject) => {
var objectStore = db.transaction(["images"], "readwrite").objectStore("images");
var request = objectStore.get(internalId);
request.onsuccess = event => {
var request = objectStore.put(Object.assign(event.target.result, update));
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
};
request.onerror = () => reject(request.error);
});
}
export async function deleteImage(internalId) {
var db = await getDb();
return await new Promise((resolve, reject) => {
var request = db.transaction(["images"], "readwrite").objectStore("images").delete(internalId);
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
export async function deleteAllImages() {
var db = await getDb();
return await new Promise((resolve, reject) => {
var request = db.transaction(["images"], "readwrite").objectStore("images").clear();
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
export async function setSetting(key, value) {
var db = await getDb();
return await new Promise((resolve, reject) => {
var request = db.transaction(["settings"], "readwrite").objectStore("settings").put(value, key);
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
export async function getSetting(key) {
var db = await getDb();
return await new Promise((resolve, reject) => {
var request = db.transaction(["settings"], "readonly").objectStore("settings").get(key);
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}

13
dep/jszip.min.js vendored

File diff suppressed because one or more lines are too long

View File

@ -1,6 +1,6 @@
<!DOCTYPE html><html><head>
<meta charset="UTF-8" />
<title>VRChat Emoji and Sticker Manager</title>
<title>VRChat Emoji Manager</title>
<style>
@ -67,20 +67,18 @@
flex-grow: 1;
}
</style>
<style id="dynamicstyle"></style>
</head><body>
<div id="emojigrid"></div>
<div id="bottompanel">
<div id="errorDiv"></div>
<div class="emojistuff">Default Animation Style: <select id="default_animation_style_select"><option value="aura">Aura</option><option value="bats">Bats</option><option value="bees">Bees</option><option value="bounce">Bounce</option><option value="cloud">Cloud</option><option value="confetti">Confetti</option><option value="crying">Crying</option><option value="dislike">Dislike</option><option value="fire">Fire</option><option value="idea">Idea</option><option value="lasers">Lasers</option><option value="like">Like</option><option value="magnet">Magnet</option><option value="mistletoe">Mistletoe</option><option value="money">Money</option><option value="noise">Noise</option><option value="orbit">Orbit</option><option value="pizza">Pizza</option><option value="rain">Rain</option><option value="rotate">Rotate</option><option value="shake">Shake</option><option value="snow">Snow</option><option value="snowball">Snowball</option><option value="spin">Spin</option><option value="splash">Splash</option><option value="stop">Stop</option><option value="zzz">ZZZ</option></select></div>
<div><button id="modebtn">Sticker Mode</button></div>
<div><button id="addbtn">Add</button></div>
<div><button id="deletebtn">Delete</button></div>
<div>Default Animation Style: <select id="default_animation_style_select"><option value="aura">Aura</option><option value="bats">Bats</option><option value="bees">Bees</option><option value="bounce">Bounce</option><option value="cloud">Cloud</option><option value="confetti">Confetti</option><option value="crying">Crying</option><option value="dislike">Dislike</option><option value="fire">Fire</option><option value="idea">Idea</option><option value="lasers">Lasers</option><option value="like">Like</option><option value="magnet">Magnet</option><option value="mistletoe">Mistletoe</option><option value="money">Money</option><option value="noise">Noise</option><option value="orbit">Orbit</option><option value="pizza">Pizza</option><option value="rain">Rain</option><option value="rotate">Rotate</option><option value="shake">Shake</option><option value="snow">Snow</option><option value="snowball">Snowball</option><option value="spin">Spin</option><option value="splash">Splash</option><option value="stop">Stop</option><option value="zzz">ZZZ</option></select></div>
<div><button id="addbtn">Add Emojis</button></div>
<div><button id="deletebtn">Delete Emojis</button></div>
<div><button id="importbtn">Import</button></div>
<div><button id="exportbtn">Export</button></div>
<div><button id="clearbtn">Clear</button></div>
</div>
<script src="dep/jszip.min.js"></script>
<script type="module" src="manage.js"></script>
<script src="manage.js"></script>
</body></html>

456
manage.js
View File

@ -1,36 +1,34 @@
import * as db from "../db.js";
var mode = localStorage.mode ||= "emoji";
if (mode == "sticker") stickerMode();
function stickerMode() {
localStorage.mode = mode = "sticker";
modebtn.innerText = "Emoji Mode";
dynamicstyle.innerHTML = `.emojistuff {display: none}`;
}
function emojiMode() {
localStorage.mode = mode = "emoji";
modebtn.innerText = "Sticker Mode";
dynamicstyle.innerHTML = ``;
}
modebtn.onclick = function switchMode() {
if (mode == "emoji") {
stickerMode();
} else {
emojiMode();
}
loadToggleState();
}
const ANIMATION_STYLES = `default Aura Bats Bees Bounce Cloud Confetti Crying Dislike Fire Idea Lasers Like Magnet Mistletoe Money Noise Orbit Pizza Rain Rotate Shake Snow Snowball Spin Splash Stop ZZZ`.split(' ');
const animationStyleRegex = new RegExp(`(${ANIMATION_STYLES.join('|')})`, 'i');
const ANIMATION_STYLES = `default
Aura
Bats
Bees
Bounce
Cloud
Confetti
Crying
Dislike
Fire
Idea
Lasers
Like
Magnet
Mistletoe
Money
Noise
Orbit
Pizza
Rain
Rotate
Shake
Snow
Snowball
Spin
Splash
Stop
ZZZ`.split('\n');
function createAnimationStyleSelect() {
let select = document.createElement("select");
select.classList.add("emojistuff");
ANIMATION_STYLES.forEach(a => {
let option = document.createElement("option");
option.innerText = a;
@ -45,34 +43,24 @@ function createAnimationStyleSelect() {
}
db.getSetting("defaultAnimationStyle").then(defaultAnimationStyle => {
default_animation_style_select.value = defaultAnimationStyle || "aura";
});
default_animation_style_select.onchange = async function () {
await db.setSetting("defaultAnimationStyle", this.value);
var enabled = [...document.querySelectorAll("[data-state=enabled]")].filter(e => !e.querySelector("select").value);
if (enabled.length) {
default_animation_style_select.disabled = true;
await Promise.all(enabled.map(div => (async ()=>{
await div.disable();
await div.enable();
})()));
default_animation_style_select.disabled = false;
}
};
addbtn.onclick = async () => {
try {
var fileHandles = await showOpenFilePicker({
id: "add",
multiple: true,
types: [ { description: "Image", accept: { "image/*": [], } } ]
});
} catch (error) {
return;
}
var fileHandles = await showOpenFilePicker({
id: "add",
multiple: true,
types: [
{
description: "Any image supported by browser",
accept: {
"image/*": [],
}
}
]
});
if (!fileHandles.length) return;
var files = [];
for (let fileHandle of fileHandles) {
@ -85,11 +73,13 @@ addbtn.onclick = async () => {
await addFiles(files);
};
document.body.onpaste = event => {
if (event.clipboardData.files.length) {
addFiles(event.clipboardData.files);
}
};
document.body.ondragover = event => event.preventDefault();
document.body.ondrop = event => {
event.preventDefault();
@ -98,7 +88,9 @@ document.body.ondrop = event => {
}
};
async function addFiles(files) {
var newEmojis = [];
var errors = [];
for (let file of files) {
try {
@ -124,16 +116,15 @@ async function addFiles(files) {
canvas.height = largestDim;
let ctx = canvas.getContext("2d");
ctx.drawImage(image, offsetX, offsetY, width, height);
let data = await new Promise(r => canvas.toBlob(r, "image/png"));
let data = canvas.toDataURL();
URL.revokeObjectURL(image.src);
let e = {
internalId: randomId(),
date: new Date().toISOString(),
animationStyle: file.name.match(animationStyleRegex)?.[1] || undefined,
data
date: new Date().toISOString()
};
await db.storeImage(e);
createEmojiSquare(e);
await chrome.storage.local.set({["data-"+e.internalId]: data});
newEmojis.push(e);
createEmojiSquare(e, data);
errorDiv.innerText = "";
} catch(error) {
console.error(error);
@ -143,7 +134,10 @@ async function addFiles(files) {
if (errors.length) {
displayError(`Errors occured adding ${errors.length} files: ${errors.join(', ')}`);
}
loadToggleState();
var {emojis} = await chrome.storage.local.get("emojis");
emojis ||= [];
emojis = emojis.concat(newEmojis);
await chrome.storage.local.set({emojis});
}
@ -155,7 +149,7 @@ deletebtn.onclick = () => {
if (deleteMode) {
deleteMode = false;
document.body.classList.remove("deletemode");
deletebtn.innerText = "Delete";
deletebtn.innerText = "Delete Emojis";
return;
}
deleteMode = true;
@ -163,35 +157,71 @@ deletebtn.onclick = () => {
deletebtn.innerText = "Stop Delete";
};
chrome.storage.local.get("defaultAnimationStyle").then(({defaultAnimationStyle}) => {
default_animation_style_select.value = defaultAnimationStyle || "aura";
});
default_animation_style_select.onchange = async function () {
chrome.storage.local.set({defaultAnimationStyle: this.value});
var enabled = [...document.querySelectorAll("[data-state=enabled]")].filter(e => !e.querySelector("select").value);
if (enabled.length) {
default_animation_style_select.disabled = true;
enabled.forEach(e => e.querySelector("select").disabled = true);
let {emojis} = await chrome.storage.local.get("emojis");
for (let div of enabled) {
div.dataset.state = "pending";
try {
await callContentScript("deleteEmoji", div.dataset.currentId);
} catch(error) {
displayError(error);
}
try {
let newEmoji = await callContentScript("createEmoji", div.querySelector("img").src, div.querySelector("select").value || default_animation_style_select.value);
emojis.find(e => e.internalId == div.dataset.internalId).currentId = newEmoji.id;
div.dataset.currentId = newEmoji.id;
div.dataset.state = "enabled";
} catch (error) {
displayError(error);
}
div.querySelector("select").disabled = false;
}
await chrome.storage.local.set({emojis});
default_animation_style_select.disabled = false;
}
};
importbtn.onclick = async () => {
try {
try {
var [fileHandle] = await showOpenFilePicker({
id: "import",
types: [ { description: "ZIP or vrcem json", accept: { "application/zip": ".zip", "application/json": ".json" } } ]
});
} catch (error) {
return;
}
var [fileHandle] = await showOpenFilePicker({
id: "import",
types: [
{
description: "vrcem export file",
accept: {
"application/json": ".json",
}
}
]
});
if (!fileHandle) return;
var file = await fileHandle.getFile();
if (file.name.toLowerCase().endsWith(".json")) {
let text = await file.text();
let store = JSON.parse(text);
var pngs = await Promise.all(store.emojis.map(async emoji => {
var blob = await fetch(store[`data-${emoji.internalId}`]).then(res => res.blob());
return new File([blob], `${emoji.animationStyle}.png`);
}));
} else {
var zip = await JSZip.loadAsync(file);
var pngs = zip.file(/^[^\/]*\.png$/i);
pngs = await Promise.all(pngs.map(async png => {
var blob = await png.async("blob");
return new File([blob], png.name);
}));
var text = await file.text();
var store = JSON.parse(text);
var set = {};
for (let key in store) {
if (key.startsWith("data-")) {
set[key] = store[key];
}
}
await addFiles(pngs);
var {emojis} = chrome.storage.local.get("emojis");
emojis ||= [];
store.emojis.forEach(emoji => {
var existing = emojis.find(e => e.internalId == emoji.internalId);
if (existing) Object.apply(existing, emoji);
else emojis.push(emoji);
});
set.emojis = emojis;
await chrome.storage.local.set(set);
location.reload();
} catch(error) {
displayError(error);
}
@ -199,16 +229,13 @@ importbtn.onclick = async () => {
exportbtn.onclick = async () => {
try {
var images = await db.getAllImages();
var zip = new JSZip();
for (let image of images) {
zip.file(`${image.internalId}.${image.animationStyle}.png`, image.data);
}
var blob = await zip.generateAsync({type: "blob"});
var store = await chrome.storage.local.get();
store = JSON.stringify(store);
var blob = new Blob([store],{type: "application/json"});
var url = URL.createObjectURL(blob);
var a = document.createElement("a");
a.href = url;
a.download = `vrcem-${new Date().toISOString()}.zip`;
a.download = `vrcem-${new Date().toISOString()}.json`;
a.click();
URL.revokeObjectURL(url);
} catch (error) {
@ -217,137 +244,130 @@ exportbtn.onclick = async () => {
};
clearbtn.onclick = async () => {
if (!confirm("Delete all images?????")) return;
await db.deleteAllImages();
emojigrid.innerHTML = '';
};
(async function loadEmojis() {
errorDiv.innerText = "";
var images = await db.getAllImages();
if (!images.length) throw new Error("No emoji.");
for (let image of images) {
createEmojiSquare(image);
}
await loadToggleState();
})().catch(displayError);
async function refreshImages() {
console.debug("refreshImages");
var images = await db.getAllImages();
for (let image of images) {
if (!document.querySelector(`[data-internal-id="${image.internalId}"]`)) createEmojiSquare(image);
}
var ids = images.map(i => i.internalId);
for (let emojisquare of document.querySelectorAll(".emojisquare")) {
if (!ids.includes(emojisquare.dataset.internalId)) emojisquare.delete();
}
}
async function loadToggleState() {
console.debug("loadToggleState");
try {
var elements = document.querySelectorAll(".emojisquare");
if (elements.length === 0) return;
var currentFiles = await callContentScript("getFiles", mode);
var active = currentFiles?.map(e => e.id);
elements.forEach(e => {
e.dataset.state = active.includes(e.dataset["currentId_"+mode]) ? "enabled" : "disabled";
});
errorDiv.innerText = "";
if (!confirm("Remove all emojis from storage. Are you SURE?????")) return;
await chrome.storage.local.clear();
location.reload();
} catch (error) {
displayError(error);
}
};
onfocus = () => loadToggleState().catch(displayError);
loadEmojis().catch(displayError);
async function loadEmojis() {
errorDiv.innerText = "";
var store = await chrome.storage.local.get();
if (!store.emojis) throw new Error("No emoji.");
for (let emoji of store.emojis) {
createEmojiSquare(emoji, store["data-" + emoji.internalId]);
}
await loadToggleState();
}
onfocus = () => refreshImages().then(loadToggleState);
function createEmojiSquare({internalId, data, animationStyle, currentId_emoji, currentId_sticker}) {
var div = document.createElement("div");
function createEmojiSquare(emoji, url) {
let div = document.createElement("div");
div.className = "emojisquare";
div.dataset.internalId = internalId;
div.blob = data;
if (currentId_emoji) div.dataset.currentId_emoji = currentId_emoji;
if (currentId_sticker) div.dataset.currentId_sticker = currentId_sticker;
div.dataset.internalId = emoji.internalId;
if (emoji.currentId) div.dataset.currentId = emoji.currentId;
div.onclick = async function onEmojiClick(event) {
if (this.dataset.state == "pending") return;
var selectedState = this.dataset.state;
this.dataset.state = "pending";
div.querySelector("select").disabled = true;
errorDiv.innerText = "";
Object.assign(div, {
async enable() {
var lastState = this.dataset.state;
this.dataset.state = "pending";
select.disabled = true;
errorDiv.innerText = "";
try {
this.dataurl ||= await blobToDataURL(this.blob);
var newEmoji = await callContentScript("createFile", this.dataurl, mode, select.value || default_animation_style_select.value);
} catch (error) {
this.dataset.state = lastState;
select.disabled = false;
displayError(error);
return;
}
await db.updateImage(this.dataset.internalId, {["currentId_"+mode]: newEmoji.id});
this.dataset["currentId_"+mode] = newEmoji.id;
this.dataset.state = "enabled";
select.disabled = false;
},
async disable() {
var lastState = this.dataset.state;
this.dataset.state = "pending";
select.disabled = true;
errorDiv.innerText = "";
try {
await callContentScript("deleteFile", this.dataset["currentId_"+mode]);
await db.updateImage(this.dataset.internalId, {["currentId_"+mode]: null});
delete this.dataset["currentId_"+mode];
} catch (error) {
this.dataset.state = lastState;
select.disabled = false;
displayError(error);
return;
}
this.dataset.state = "disabled";
div.querySelector("select").disabled = false;
},
async toggle() {
if (this.dataset.state == "enabled") {
await this.disable();
} else if (this.dataset.state == "disabled") {
await this.enable();
}
},
async delete() {
await db.deleteImage(this.dataset.internalId);
if (this.dataset["currentId_emoji"]) callContentScript("deleteFile", this.dataset["currentId_emoji"]).catch(displayError);
if (this.dataset["currentId_sticker"]) callContentScript("deleteFile", this.dataset["currentId_sticker"]).catch(displayError);
if (deleteMode) {
let {emojis} = await chrome.storage.local.get("emojis");
emojis = emojis.filter(e => e.internalId != this.dataset.internalId);
await chrome.storage.local.set({emojis});
this.remove();
if (this.dataset.currentId) callContentScript("deleteEmoji", this.dataset.currentId);
return;
}
});
div.onclick = function onEmojiClick() {
if (deleteMode) this.delete();
else this.toggle();
if (emojigrid.querySelector(".emojisquare:not([data-state])")) loadToggleState();
if (emojigrid.querySelector(".emojisquare:not([data-state])")) {
try {
await loadToggleState();
} catch (error) {
displayError(error);
this.dataset.state = selectedState;
return;
}
}
if (selectedState == "enabled") {
// disable
callContentScript("deleteEmoji", this.dataset.currentId).then(() => {
this.dataset.state = "disabled";
div.querySelector("select").disabled = false;
}).catch(error => {
this.dataset.state = selectedState;
div.querySelector("select").disabled = false;
displayError(error);
});
return;
}
// enable
callContentScript("createEmoji", this.querySelector("img").src, this.querySelector("select").value || default_animation_style_select.value).then(newEmoji => {
chrome.storage.local.get("emojis").then(({emojis}) => {
emojis.find(e => e.internalId == this.dataset.internalId).currentId = newEmoji.id;
chrome.storage.local.set({emojis});
this.dataset.currentId = newEmoji.id;
this.dataset.state = "enabled";
div.querySelector("select").disabled = false;
});
}).catch(error => {
this.dataset.state = selectedState;
div.querySelector("select").disabled = false;
displayError(error);
});
};
var imgdiv = document.createElement("div");
let imgdiv = document.createElement("div");
imgdiv.className = "imgcontainer";
var img = document.createElement("img");
img.src = URL.createObjectURL(data);
let img = document.createElement("img");
img.src = url;
imgdiv.appendChild(img);
div.appendChild(imgdiv);
var select = createAnimationStyleSelect();
select.value = animationStyle || '';
let select = createAnimationStyleSelect();
select.value = emoji.animationStyle || '';
select.onclick = event => event.stopPropagation();
select.onchange = async event => {
await db.updateImage(div.dataset.internalId, {animationStyle: event.target.value});
var {emojis} = await chrome.storage.local.get("emojis");
var e = emojis.find(e => e.internalId == div.dataset.internalId);
e.animationStyle = event.target.value;
await chrome.storage.local.set({emojis});
if (div.dataset.state == "enabled") {
await div.disable();
await div.enable();
//recreate
div.dataset.state = "pending";
select.disabled = true;
callContentScript("deleteEmoji", div.dataset.currentId).finally(() => {
callContentScript("createEmoji", img.src, select.value || default_animation_style_select.value).then(newEmoji => {
chrome.storage.local.get("emojis").then(({emojis}) => {
emojis.find(e => e.internalId == div.dataset.internalId).currentId = newEmoji.id;
chrome.storage.local.set({emojis});
div.dataset.currentId = newEmoji.id;
div.dataset.state = "enabled";
select.disabled = false;
});
}).catch(error => {
displayError(error);
});
}).catch(error => {
displayError(error);
});
}
};
div.appendChild(select);
@ -357,7 +377,17 @@ function createEmojiSquare({internalId, data, animationStyle, currentId_emoji, c
}
async function loadToggleState() {
console.debug("loadToggleState");
var elements = document.querySelectorAll(".emojisquare");
if (elements.length === 0) return;
var currentEmojis = await callContentScript("getEmojis");
var active = currentEmojis?.map(e => e.id);
elements.forEach(e => {
e.dataset.state = active.includes(e.dataset.currentId) ? "enabled" : "disabled";
});
errorDiv.innerText = "";
}
function displayError(error) {
console.error(error);
@ -371,8 +401,6 @@ function displayError(error) {
html += ` Click "Add Emojis" to get started.`;
if (error.includes("Could not establish connection. Receiving end does not exist."))
html += `<br>Please reload your VRChat tab.`;
if (error.includes("You must upload a valid imageǃ"))
html += `<br> (NSFW images are not allowed)`;
errorDiv.innerHTML = html;
}
@ -384,16 +412,10 @@ async function getVRchatTab() {
async function callContentScript(method, ...args) {
var tab = await getVRchatTab();
var {error, response} = await chrome.tabs.sendMessage(tab.id, [method, ...args]);
if (error) throw error;
var response = await chrome.tabs.sendMessage(tab.id, [method, ...args]);
console.debug(response);
if (response.status == 429) {
throw new Error(`VRChat API ratelimited. Please wait ${response.retryAfter} seconds.`);
}
if (response.body.error) {
throw new Error(`VRChat API said: ${response.body.error.message}`);
}
return response.body;
if (response.error) throw response.error;
else return response;
};
@ -413,10 +435,10 @@ function loadImage(src) {
});
}
function blobToDataURL(blob) {
function fileToDataURL(file) {
return new Promise((resolve, reject) => {
let reader = new FileReader();
reader.readAsDataURL(blob);
reader.readAsDataURL(file);
reader.onload = () => {
resolve(reader.result);
};

View File

@ -1,8 +1,8 @@
{
"manifest_version": 3,
"name": "VRChat Emoji and Sticker Manager",
"version": "1.2024.10.9",
"description": "Store more than 9 emoji or stickers, toggle them on and off and change their animation styles.",
"name": "VRChat Emoji Manager",
"version": "1.2024.10.7",
"description": "Store more than 9 emoji, toggle them on and off and change their animation styles.",
"homepage_url": "https://gitea.moe/lamp/vrchat-emoji-manager",
"icons": {
"128": "icon128.png"