Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: improve native data update logic and triggers #525

Merged
merged 6 commits into from
Aug 6, 2023
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
41 changes: 23 additions & 18 deletions src/popup/App.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
let inactive = false;
let platform;
let initError;
let firstGuide;
let windowHeight = 0;
let header;
let warn;
Expand Down Expand Up @@ -220,6 +221,13 @@
loading = false;
}

async function openContainingApp() {
browser.tabs.executeScript({
code: `location="${firstGuide}"`
});
window.close();
}

async function initialize() {
// get platform first since it applies important styling
let pltfm;
Expand All @@ -239,31 +247,23 @@
}
platform = pltfm.platform;

// run init checks
// const init = await browser.runtime.sendNativeMessage({name: "POPUP_INIT"}).catch(error => {});
let init;
try {
init = await browser.runtime.sendNativeMessage({name: "POPUP_INIT"});
} catch (error) {
console.error(`Error for init promise: ${error}`);
initError = true;
loading = false;
return;
}
if (init.error) {
errorNotification = init.error;
// display native error if there is
const errorNative = await settingsStorage.get("error_native");
if (errorNative.error) {
if (errorNative.saveLocation === "unset") {
firstGuide = `${errorNative.scheme}://`;
loading = false;
return;
}
errorNotification = errorNative.error;
loading = false;
disabled = false;
return;
}

// set toggle state
active = await settingsStorage.get("global_active");

// refresh session rules
browser.runtime.sendMessage({name: "REFRESH_SESSION_RULES"});
// refresh context-menu scripts
browser.runtime.sendMessage({name: "REFRESH_CONTEXT_MENU_SCRIPTS"});

// set popup height
resize();

Expand Down Expand Up @@ -542,6 +542,11 @@
{:else}
{#if inactive}
<div class="none">Popup inactive on extension page</div>
{:else if firstGuide}
<div class="none" on:click={openContainingApp}>
Welcome, first please:&nbsp;
<span class="link">set directory</span>
</div>
{:else if initError}
<div class="none">
Something went wrong:&nbsp;
Expand Down
31 changes: 0 additions & 31 deletions src/shared/dev.js
Original file line number Diff line number Diff line change
Expand Up @@ -265,37 +265,6 @@ const _browser = {
}
]
};
} else if (name === "POPUP_INIT") {
response.initData = {
active: "true",
items: [
{
name: "Google Images Restored",
filename: "Google Images Restored.js",
disabled: false,
type: "js"
},
{
name: "Subframe Script Managerial Staffing Company",
filename: "Subframe Script.js",
disabled: false,
subframe: true,
type: "css"
}
],
updates: [
{
filename: "Google Images Restored.js",
name: "Google Images Restored",
url: "https://www.k21p.com"
},
{
filename: "New Userscript With a Really Really Long Name.js",
name: "New Userscript With a Really Really Long Name",
url: "https://www.filmgarb.com"
}
]
};
} else if (name === "POPUP_MATCHES") {
response = {
matches: [
Expand Down
11 changes: 9 additions & 2 deletions src/shared/settings.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,14 @@ const settingDefault = deepFreeze({
});

export const settingsDefine = deepFreeze([
{
name: "error_native",
type: "object",
local: true,
default: {error: undefined},
platforms: ["macos", "ipados", "ios"],
group: "Internal"
},
{
name: "legacy_imported",
type: "number",
Expand Down Expand Up @@ -173,8 +181,7 @@ export const settingsDefine = deepFreeze([
en: "The lasttime for script update check in background",
zh_hans: "后台脚本更新上次检查时间"
},
group: "Internal",
nodeType: "Toggle"
group: "Internal"
},
{
name: "scripts_auto_update",
Expand Down
86 changes: 41 additions & 45 deletions xcode/Safari-Extension/Functions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1911,62 +1911,58 @@ func getFileRemoteUpdate(_ content: String) -> [String: String] {
return ["content": remoteContent]
}

func popupInit() -> [String: String]? {
// background
func nativeChecks() -> [String: String] {
logText("nativeChecks started")
#if os(iOS)
// check the save location is set
guard (getSaveLocation() != nil) else {
err("nativeChecks: save location unset (iOS)")
return [
"error": "Native checks error (0)",
"saveLocation": "unset",
"scheme": Bundle.main.infoDictionary?["US_URL_SCHEME"] as! String
]
}
#endif
// check the default directories
let checkDefaultDirectories = checkDefaultDirectories()
guard checkDefaultDirectories() else {
err("nativeChecks: checkDefaultDirectories failed")
return ["error": "Native checks error (1)"]
}
// check the settings
let checkSettings = checkSettings()
guard checkSettings() else {
err("nativeChecks: checkSettings failed")
return ["error": "Native checks error (2)"]
}
// get all files to pass as arguments to function below
guard let allFiles = getAllFiles() else {
err("Failed to getAllFiles in popupInit")
return nil
err("nativeChecks: getAllFiles failed")
return ["error": "Native checks error (3)"]
}
// purge the manifest of old records
let purgeManifest = purgeManifest(allFiles)
// update matches in manifest
let updateManifestMatches = updateManifestMatches(allFiles)
// update the required resources
let updateManifestRequired = updateManifestRequired(allFiles)
// update declarativeNetRequest
let updateDeclarativeNetRequest = updateManifestDeclarativeNetRequests(allFiles)
// verbose error checking
if !checkDefaultDirectories {
err("Failed to checkDefaultDirectories in popupInit")
return nil
}
if !checkSettings {
err("Failed to checkSettings in popupInit")
return nil
}
if !purgeManifest {
err("Failed to purgeManifest in popupInit")
return nil
guard purgeManifest(allFiles) else {
err("nativeChecks: purgeManifest failed")
return ["error": "Native checks error (4)"]
}
if !updateManifestMatches {
err("Failed to updateManifestMatches in popupInit")
return nil
// update matches in manifest
guard updateManifestMatches(allFiles) else {
err("nativeChecks: updateManifestMatches failed")
return ["error": "Native checks error (5)"]
}
if !updateManifestRequired {
err("Failed to updateManifestRequired in popupInit")
return nil
// update the required resources
guard updateManifestRequired(allFiles) else {
err("nativeChecks: updateManifestRequired failed")
return ["error": "Native checks error (6)"]
}
if !updateDeclarativeNetRequest {
err("Failed to updateDeclarativeNetRequest in popupInit")
return nil
// update declarativeNetRequest
guard updateManifestDeclarativeNetRequests(allFiles) else {
err("nativeChecks: updateManifestDeclarativeNetRequests failed")
return ["error": "Native checks error (7)"]
}
// pass some info in response
guard let saveLocation = getSaveLocation() else {
err("Failed at getSaveLocation in popupInit")
return nil
}
let documentsDirectory = getDocumentsDirectory()
let requireLocation = getRequireLocation()

return [
"saveLocation": saveLocation.absoluteString,
"documentsDirectory": documentsDirectory.absoluteString,
"requireLocation": requireLocation.absoluteString
]
logText("nativeChecks complete")
return ["success": "Native checks complete"]
}

// userscript install
Expand Down
44 changes: 34 additions & 10 deletions xcode/Safari-Extension/Resources/background.js
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,12 @@ async function setBadgeCount() {
});
}

// on startup get declarativeNetRequests
// and set the requests for the session
// should also check and refresh when:
// 1. dnr item save event in the page occurs
// 2. dnr item toggle event in the page occurs
// 3. external editor changes script file content
async function setSessionRules() {
// not supported below safari 15.4
if (!browser.declarativeNetRequest.updateSessionRules) return;
Expand Down Expand Up @@ -187,6 +193,9 @@ function randomNumberSet(max, count) {
return [...numbers];
}

// the current update logic is similar to setSessionRules()
// this feature needs a more detailed redesign in the future
// https://github.com/quoid/userscripts/issues/453
async function getContextMenuItems() {
// macos exclusive feature
const platform = await getPlatform();
Expand Down Expand Up @@ -273,6 +282,17 @@ function contextClick(info, tab) {
});
}

async function nativeChecks() {
const response = await browser.runtime.sendNativeMessage({name: "NATIVE_CHECKS"});
// note: use settings.js once background page modularization
if (response.error) {
browser.storage.local.set({US_ERROR_NATIVE: response});
return false;
}
browser.storage.local.remove("US_ERROR_NATIVE");
return true;
}

// handles messages sent with browser.runtime.sendMessage
function handleMessage(request, sender, sendResponse) {
switch (request.name) {
Expand Down Expand Up @@ -455,22 +475,26 @@ function handleMessage(request, sender, sendResponse) {
}
}
}

browser.runtime.onInstalled.addListener(async () => {
nativeChecks();
});
browser.runtime.onStartup.addListener(async () => {
// on startup get declarativeNetRequests
// and set the requests for the session
// should also check and refresh when:
// 1. popup opens (done)
// 2. a new save event in the page occurs
// 3. the refresh button is pushed in the popup
await setSessionRules();
await getContextMenuItems();
setSessionRules();
getContextMenuItems();
});
// listens for messages from content script, popup and page
browser.runtime.onMessage.addListener(handleMessage);
// set the badge count
browser.tabs.onActivated.addListener(setBadgeCount);
browser.windows.onFocusChanged.addListener(setBadgeCount);
browser.windows.onFocusChanged.addListener(async windowId => {
if (windowId < 1) { // lose focus
return;
}
nativeChecks();
setBadgeCount();
setSessionRules();
getContextMenuItems();
});
browser.webNavigation.onCompleted.addListener(setBadgeCount);

// handle native app messages
Expand Down
11 changes: 4 additions & 7 deletions xcode/Safari-Extension/SafariWebExtensionHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ class SafariWebExtensionHandler: NSObject, NSExtensionRequestHandling {
#endif
}
}
else if name == "NATIVE_CHECKS" {
let result = nativeChecks()
response.userInfo = [SFExtensionMessageKey: result]
}
else if name == "REQ_PLATFORM" {
let platform = getPlatform()
response.userInfo = [SFExtensionMessageKey: ["platform": platform]]
Expand Down Expand Up @@ -68,13 +72,6 @@ class SafariWebExtensionHandler: NSObject, NSExtensionRequestHandling {
inBoundError = true
}
}
else if name == "POPUP_INIT" {
if let initData = popupInit() {
response.userInfo = [SFExtensionMessageKey: ["initData": initData]]
} else {
response.userInfo = [SFExtensionMessageKey: ["error": "failed to get init data"]]
}
}
else if name == "POPUP_MATCHES"{
if let url = message?["url"] as? String, let frameUrls = message?["frameUrls"] as? [String] {
if let matches = getPopupMatches(url, frameUrls) {
Expand Down
13 changes: 13 additions & 0 deletions xcode/iOS-App/Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,19 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Viewer</string>
<key>CFBundleURLName</key>
<string>$(APP_IDENTIFIER)</string>
<key>CFBundleURLSchemes</key>
<array>
<string>$(APP_URL_SCHEME)</string>
</array>
</dict>
</array>
<key>UIApplicationSceneManifest</key>
<dict>
<key>UIApplicationSupportsMultipleScenes</key>
Expand Down
Loading