Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 9 additions & 10 deletions extension/Userscripts Extension/Functions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1675,16 +1675,21 @@ func popupUpdateSingle(_ filename: String, _ url: String, _ subframeUrls: [Strin

// page
func getInitData() -> [String: Any]? {
let manifest = getManifest()
guard let saveLocation = getSaveLocation() else {
err("getInitData failed at (1)")
return nil
}
return [
"saveLocation": saveLocation.path,
"version": Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "??",
"build": Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "??"
]
}

func getLegacyData() -> [String: Any]? {
let manifest = getManifest()
var data:[String: Any] = manifest.settings
data["blacklist"] = manifest.blacklist
data["saveLocation"] = saveLocation.path
data["version"] = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "??"
data["build"] = Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "??"
return data
}

Expand Down Expand Up @@ -1945,11 +1950,6 @@ func popupInit() -> [String: String]? {
err("Failed to updateDeclarativeNetRequest in popupInit")
return nil
}
let manifest = getManifest()
guard let active = manifest.settings["active"] else {
err("Failed at getManifest active in popupInit")
return nil
}
// pass some info in response
guard let saveLocation = getSaveLocation() else {
err("Failed at getSaveLocation in popupInit")
Expand All @@ -1959,7 +1959,6 @@ func popupInit() -> [String: String]? {
let requireLocation = getRequireLocation()

return [
"active": active,
"saveLocation": saveLocation.absoluteString,
"documentsDirectory": documentsDirectory.absoluteString,
"requireLocation": requireLocation.absoluteString
Expand Down
23 changes: 18 additions & 5 deletions extension/Userscripts Extension/Resources/content.js
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,6 @@ function processJS(userscript) {
function wrapCode(preCode, code, filename) {
return `
(function() {
"use strict";
${preCode}
(function() {
const US_filename = "${filename}";
Expand Down Expand Up @@ -323,17 +322,19 @@ function cspFallback(e) {
}
}

browser.runtime.sendMessage({name: "REQ_USERSCRIPTS"}, response => {
const injection = () => browser.runtime.sendMessage({name: "REQ_USERSCRIPTS"}, response => {
// cancel injection if errors detected
if (!response || response.error) {
console.error(response?.error || "REQ_USERSCRIPTS returned undefined");
return;
}
// save response locally in case CSP events occur
data = response;
// combine regular and context-menu scripts
const scripts = [...data.files.js, ...data.files.menu];
// loop through each userscript and prepare for processing
for (let i = 0; i < data.files.js.length; i++) {
const userscript = data.files.js[i];
for (let i = 0; i < scripts.length; i++) {
const userscript = scripts[i];
userscript.preCode = "";
// pass references to the api methods as needed
const gmMethods = [];
Expand Down Expand Up @@ -451,7 +452,13 @@ browser.runtime.onMessage.addListener((request, sender, sendResponse) => {
const item = data.files.menu[i];
if (item.scriptObject.filename === filename) {
console.info(`Injecting ${filename} %c(js)`, "color: #fff600");
sendResponse({code: item.code});
sendResponse({
code: wrapCode(
item.preCode,
item.code,
filename
)
});
return;
}
}
Expand All @@ -460,3 +467,9 @@ browser.runtime.onMessage.addListener((request, sender, sendResponse) => {
});
// listen for CSP violations
document.addEventListener("securitypolicyviolation", cspFallback);

// should import settings.js and use `settingsStorage.get("global_active")`
browser.storage.local.get("US_GLOBAL_ACTIVE").then(results => {
if (results?.US_GLOBAL_ACTIVE === false) return console.info("Userscripts off");
injection();
});
13 changes: 11 additions & 2 deletions extension/Userscripts Extension/SafariWebExtensionHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -188,13 +188,22 @@ class SafariWebExtensionHandler: NSObject, NSExtensionRequestHandling {
}
else if name == "PAGE_INIT_DATA" {
#if os(macOS)
if let settings = getInitData(), checkDefaultDirectories() {
response.userInfo = [SFExtensionMessageKey: settings]
if let initData = getInitData(), checkDefaultDirectories() {
response.userInfo = [SFExtensionMessageKey: initData]
} else {
response.userInfo = [SFExtensionMessageKey: ["error": "failed to get init data"]]
}
#endif
}
else if name == "PAGE_LEGACY_IMPORT" {
#if os(macOS)
if let settings = getLegacyData() {
response.userInfo = [SFExtensionMessageKey: settings]
} else {
response.userInfo = [SFExtensionMessageKey: ["error": "failed to get legacy data"]]
}
#endif
}
else if name == "PAGE_ALL_FILES" {
#if os(macOS)
if let files = getAllFiles() {
Expand Down
7 changes: 1 addition & 6 deletions src/page/App.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,7 @@
log.add("Requesting initialization data", "info", false);
const initData = await browser.runtime.sendNativeMessage({name: "PAGE_INIT_DATA"});
if (initData.error) return console.error(initData.error);
for (const [key, value] of Object.entries(initData)) {
if (value === "true" || value === "false") {
initData[key] = JSON.parse(value);
}
}
settings.set(initData);
await settings.init(initData);
state.add("items-loading");
state.remove("init");

Expand Down
8 changes: 4 additions & 4 deletions src/page/Components/Settings.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@

<div
class="settings"
on:mousedown|self={() => state.remove("settings")}
on:click|self={() => state.remove("settings")}
in:fade={{duration: 150}}
out:fade={{duration: 150, delay: 75}}
>
Expand Down Expand Up @@ -120,11 +120,11 @@
<div class="modal__row">
<div>Tab Size</div>
<select
bind:value="{$settings.tabSize}"
bind:value={$settings.tabSize}
on:blur={() => update("tabSize", $settings.tabSize)}
>
<option value="2">2</option>
<option value="4">4</option>
<option value={2}>2</option>
<option value={4}>4</option>
</select>
</div>
</div>
Expand Down
67 changes: 38 additions & 29 deletions src/page/store.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {writable} from "svelte/store";
import {uniqueId} from "./utils.js";
import * as settingsStorage from "../shared/settings.js";

function notificationStore() {
const {subscribe, update} = writable([]);
Expand Down Expand Up @@ -76,40 +77,48 @@ export const state = stateStore();

function settingsStore() {
const {subscribe, update, set} = writable({});
const updateSingleSetting = (key, value) => {
update(settings => {
settings[key] = value;
// blacklist not stored in normal setting object in manifest, so handle differently
if (key === "blacklist") {
// update blacklist on swift side
const message = {name: "PAGE_UPDATE_BLACKLIST", blacklist: value};
browser.runtime.sendNativeMessage(message, response => {
if (response.error) {
log.add("Failed to save blacklist to disk", "error", true);
}
});
return settings;
}
// settings are saved as strings on the swift side
// convert all booleans to strings before dispatching
const settingsClone = {...settings};
for (const [key, value] of Object.entries(settingsClone)) {
if (typeof value === "boolean") settingsClone[key] = value.toString();
}
// remove settings in clone that aren't save in user defaults
delete settingsClone.blacklist;
delete settingsClone.version;
// update settings on swift side
const message = {name: "PAGE_UPDATE_SETTINGS", settings: settingsClone};
const init = async initData => {
// import legacy settings data just one-time
await settingsStorage.legacy_import();
// for compatibility with legacy getting names only
// once all new name is used, use settingsStorage.get()
const settings = await settingsStorage.legacy_get();
console.info("store.js settingsStore init", initData, settings);
set(Object.assign({}, initData, settings));
// sync popup, backgound, etc... settings changes
settingsStorage.onChanged((settings, area) => {
console.log(`store.js storage.${area}.onChanged`, settings);
update(obj => Object.assign(obj, settings));
});
};
const reset = async keys => {
await settingsStorage.reset(keys);
// once all new name is used, use settingsStorage.get()
const settings = await settingsStorage.legacy_get();
console.info("store.js settingsStore reset", settings);
update(obj => Object.assign(obj, settings));
};
const updateSingleSetting_old = (key, value) => {
// blacklist not stored in normal setting object in manifest, so handle differently
if (key === "blacklist") {
// update blacklist on swift side
const message = {name: "PAGE_UPDATE_BLACKLIST", blacklist: value};
browser.runtime.sendNativeMessage(message, response => {
if (response.error) {
log.add(response.error, "error", true);
log.add("Failed to save blacklist to disk", "error", true);
}
});
return settings;
});
}
};
const updateSingleSetting = (key, value) => {
update(settings => (settings[key] = value, settings));
// for compatibility with legacy setting names only
// once all new name is used, use settingsStorage.set()
settingsStorage.legacy_set({[key]: value}); // Durable Storage
// temporarily keep the old storage method until it is confirmed that all dependencies are removed
updateSingleSetting_old(key, value);
};
return {subscribe, set, updateSingleSetting};
return {subscribe, set, init, reset, updateSingleSetting};
}
export const settings = settingsStore();

Expand Down
16 changes: 6 additions & 10 deletions src/popup/App.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import iconUpdate from "../shared/img/icon-update.svg";
import iconClear from "../shared/img/icon-clear.svg";
import iconRefresh from "../shared/img/icon-refresh.svg";
import * as settingsStorage from "../shared/settings.js";

let error = undefined;
let active = true;
Expand Down Expand Up @@ -50,14 +51,9 @@

$: if (platform) document.body.classList.add(platform);

function toggleExtension(e) {
e.preventDefault(); // prevent check state from changing on click
disabled = true;
browser.runtime.sendNativeMessage({name: "POPUP_TOGGLE_EXTENSION"}, response => {
disabled = false;
if (response.error) return error = response.error;
active = !active;
});
async function toggleExtension(e) {
await settingsStorage.set({"global_active": !active});
active = await settingsStorage.get("global_active");
}

function updateAll() {
Expand Down Expand Up @@ -259,9 +255,9 @@
loading = false;
disabled = false;
return;
} else {
active = init.initData.active === "true" ? true : false;
}

active = await settingsStorage.get("global_active");

// refresh session rules
browser.runtime.sendMessage({name: "REFRESH_SESSION_RULES"});
Expand Down
15 changes: 11 additions & 4 deletions src/shared/dev.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,12 @@ const _browser = {
console.info(`Got message: ${name}`);
let response = {};
if (name === "PAGE_INIT_DATA") {
response = {
saveLocation: "/Users/someone/Library/Directory",
version: "4.0.0",
build: "44"
};
} else if (name === "PAGE_LEGACY_IMPORT") {
response = {
active: "true",
autoCloseBrackets: "true",
Expand All @@ -94,13 +100,10 @@ const _browser = {
languageCode: "en",
lint: "true",
log: "false",
saveLocation: "/Users/someone/Library/Directory",
showCount: "true",
showInvisibles: "true",
sortOrder: "lastModifiedDesc",
tabSize: "4",
version: "4.0.0",
build: "44"
tabSize: "4"
};
} else if (name === "PAGE_ALL_FILES") {
response = [];
Expand Down Expand Up @@ -416,6 +419,10 @@ const _browser = {
},
set() {
return new Promise(resolve => setTimeout(() => resolve(), _browser.delay));
},
remove: () => new Promise(resolve => setTimeout(() => resolve(), _browser.delay)),
onChanged: {
addListener: () => undefined
}
}
}
Expand Down
Loading