Skip to content

Commit

Permalink
fix: AriaNG froze after downloading an empty config
Browse files Browse the repository at this point in the history
1. Refine the settings storage logic
2. Refactor the config.js
  • Loading branch information
alexhua committed Mar 17, 2024
1 parent 0d174be commit 7c79d35
Show file tree
Hide file tree
Showing 10 changed files with 82 additions and 74 deletions.
2 changes: 1 addition & 1 deletion _locales/en/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@
"message": "It seems Aria2 Manager is not installed, access \"Alex Recommends\" channel for more information?"
},
"ClearSettingsDes":{
"message": "Confirm to clear extension's local settings?"
"message": "Confirm to clear all settings?"
},
"ColorMode":{
"message": "Color Mode"
Expand Down
2 changes: 1 addition & 1 deletion _locales/ja/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@
"message": "Aria2 Managerはインストールされていないようですが、詳細については、Alex推奨チャネルにアクセスしてください?"
},
"ClearSettingsDes":{
"message": "拡張機能のローカル設定をクリアしてもよろしいですか"
"message": "すべての設定をクリアすることを確認しますか"
},
"ColorMode":{
"message": "カラーモード"
Expand Down
2 changes: 1 addition & 1 deletion _locales/ko/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@
"message": "Aria2 Manager가 설치되어 있지 않은 것 같습니다.\"Alex 추천\"채널을 방문하여 자세한 내용을 확인하시겠습니까?"
},
"ClearSettingsDes":{
"message": "확장 프로그램의 로컬 설정을 지우시겠습니까?"
"message": "모든 설정을 지우십니까?"
},
"ColorMode":{
"message": "컬러 모드"
Expand Down
2 changes: 1 addition & 1 deletion _locales/uk/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@
"message": "Здається, Aria2 Manager не встановлено, звертайтеся до каналу \"Alex Recommends\" для отримання додаткової інформації?"
},
"ClearSettingsDes":{
"message": "Підтвердіть очищення локальних налаштувань розширення?"
"message": "Підтверджувати вилучення всіх параметрів?"
},
"ColorMode":{
"message": "Колірний режим"
Expand Down
2 changes: 1 addition & 1 deletion _locales/zh_CN/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@
"message": "好像没有安装Aria2 Manager,访问“Alex推荐”频道了解更多信息?"
},
"ClearSettingsDes": {
"message": "确认清除扩展的本地设置"
"message": "确认清除所有设置"
},
"ColorMode":{
"message": "颜色模式"
Expand Down
2 changes: 1 addition & 1 deletion _locales/zh_TW/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@
"message": "好像沒有安裝Aria2 Manager,訪問“Alex推薦”頻道瞭解更多資訊?"
},
"ClearSettingsDes": {
"message": "確認清除擴充的本地設定"
"message": "確認清除所有設定"
},
"ColorMode":{
"message": "顔色模式"
Expand Down
16 changes: 3 additions & 13 deletions background.js
Original file line number Diff line number Diff line change
Expand Up @@ -751,21 +751,11 @@ function registerAllListeners() {
});

chrome.runtime.onInstalled.addListener(function (details) {
let optionsUrl = chrome.runtime.getURL("options.html");
let manifest = chrome.runtime.getManifest();
if (details.reason == "install") {
chrome.tabs.create({
url: optionsUrl
});
const url = chrome.runtime.getURL("options.html");
chrome.storage.local.set(Configs).then(() => chrome.tabs.create({ url }));
} else if (details.reason == "update") {
// chrome.storage.local.get("rpcList").then(configs => {
// if (!configs.rpcList) {
// /* Old local storage should be upgraded to Chrome storage */
// chrome.tabs.create({
// url: optionsUrl + "?action=upgrade-storage"
// });
// }
// })
const manifest = chrome.runtime.getManifest();
/* new version update notification */
let title = `Version ${manifest.version} 🚀`;
let message = `${manifest.name} has been updated.`;
Expand Down
46 changes: 41 additions & 5 deletions js/config.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,50 @@
const Configs = {
ariaNgOptions: {},
export const DefaultAriaNgOptions = {
language: 'TBD',
theme: 'system',
title: '${downspeed}, ${upspeed} - ${title}',
titleRefreshInterval: 5000,
browserNotification: false,
browserNotificationSound: true,
browserNotificationFrequency: 'unlimited',
rpcAlias: 'Aria2',
rpcHost: 'localhost',
rpcPort: '6800',
rpcInterface: 'jsonrpc',
protocol: 'ws',
httpMethod: 'POST',
rpcRequestHeaders: '',
rpcOptions: {},
secret: '',
extendRpcServers: [],
webSocketReconnectInterval: 5000,
globalStatRefreshInterval: 1000,
downloadTaskRefreshInterval: 1000,
keyboardShortcuts: true,
swipeGesture: true,
dragAndDropTasks: true,
rpcListDisplayOrder: 'recentlyUsed',
afterCreatingNewTask: 'task-list',
removeOldTaskAfterRetrying: true,
confirmTaskRemoval: true,
includePrefixWhenCopyingFromTaskDetails: false,
showPiecesInfoInTaskDetailPage: 'le10240',
afterRetryingTask: 'task-list-default',
displayOrder: 'default:asc',
fileListDisplayOrder: 'default:asc',
peerListDisplayOrder: 'default:asc'
}

export const DefaultConfigs = {
ariaNgOptions: DefaultAriaNgOptions,
contextMenus: true,
askBeforeExport: false,
exportAll: true,
integration: true,
integration: false,
fileSize: "100",
askBeforeDownload: false,
allowExternalRequest: false,
monitorAria2: false,
monitorAll:false,
monitorAll: false,
keepAwake: false,
allowNotification: false,
keepSilent: false,
Expand All @@ -22,4 +58,4 @@ const Configs = {
blockedExts: []
};

export default Configs;
export default DefaultConfigs;
43 changes: 29 additions & 14 deletions js/options.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import Utils from "./utils.js";
import Default from "./config.js";
import { DefaultConfigs, DefaultAriaNgOptions } from "./config.js";

const AriaNgOptionsKey = "AriaNg.Options"; // AriaNG options local storage key

Expand All @@ -15,8 +15,13 @@ var Configs =
Utils.localizeHtmlPage();
if (location.search.endsWith("upgrade-storage"))
await upgradeStorage();
let configs = await chrome.storage.local.get();
Object.assign(Configs, Default, configs);
let configs = null;
try {
configs = await chrome.storage.local.get();
} catch (error) {
console.error("init: " + error.message);
}
Object.assign(Configs, DefaultConfigs, configs);

setColorMode();

Expand Down Expand Up @@ -154,6 +159,7 @@ var Configs =
},
reset: async function () {
if (confirm(chrome.i18n.getMessage("ClearSettingsDes"))) {
localStorage.clear();
await chrome.storage.local.clear();
}
},
Expand Down Expand Up @@ -197,10 +203,12 @@ var Configs =
upload: function () {
try {
let ariaNgOptionsValue = localStorage.getItem(AriaNgOptionsKey);
Configs.ariaNgOptions = JSON.parse(ariaNgOptionsValue);
if (typeof ariaNgOptionsValue === "string") {
Configs.ariaNgOptions = JSON.parse(ariaNgOptionsValue);
}
} catch {
delete Configs.ariaNgOptions;
console.warn("Upload: AriaNG options is invalid.");
Configs.ariaNgOptions = DefaultAriaNgOptions;
console.warn("Upload: Local AriaNG options is invalid, default is loaded.");
}
//check the validity of RPC list
if (!Configs.rpcList || !Configs.rpcList.length) {
Expand All @@ -217,30 +225,37 @@ var Configs =
/* There must be too much BT trackers in the Aria2 settings */
error.message = "Exceeded Quota (8KB). Please refine the Aria2 BT trackers."
}
Configs.notifySyncResult(str + error.message, "alert-danger", 5000);
Configs.notifySyncResult(`${str} (${error.message})`, "alert-danger", 5000);
});
},
download: function () {
chrome.storage.sync.get().then(async configs => {
if (configs) {
if (Object.keys(configs).length > 0) {
try {
if (typeof configs.ariaNgOptions === "string") {
configs.ariaNgOptions = JSON.parse(configs.ariaNgOptions);
}
localStorage.setItem(AriaNgOptionsKey, JSON.stringify(configs.ariaNgOptions));
const optionsLength = Object.keys(configs.ariaNgOptions).length;
const defaultLength = Object.keys(DefaultAriaNgOptions).length;
if (optionsLength >= defaultLength) {
localStorage.setItem(AriaNgOptionsKey, JSON.stringify(configs.ariaNgOptions));
} else {
throw new TypeError("Invalid AriaNG options");
}
} catch {
delete configs.ariaNgOptions;
console.warn("Download: AriaNG options is invalid.");
}
await chrome.storage.local.set(configs);
Object.assign(Configs, configs);
await chrome.storage.local.set(Configs);
let str = chrome.i18n.getMessage("downloadConfigSucceed");
Configs.notifySyncResult(str, "alert-success");
} else {
throw new Error("No valid configuration found.");
throw new TypeError("Invalid extension configs");
}
}).catch((error) => {
let str = chrome.i18n.getMessage("downloadConfigFailed");
Configs.notifySyncResult(str + error.message, "alert-danger", 5000);
Configs.notifySyncResult(str, "alert-danger", 5000);
});
},
notifySyncResult: function (msg, style, timeout = 2000) {
Expand All @@ -264,7 +279,7 @@ chrome.storage.onChanged.addListener((changes, areaName) => {
return;
}
Configs.init();
if (isRpcListChanged(changes)) {
if (isRpcListChanged(changes) && !changes.hasOwnProperty("ariaNgOptions")) {
let oldAriaNgOptions = localStorage[AriaNgOptionsKey];
let ariaNgOptions = null;
try {
Expand Down Expand Up @@ -304,7 +319,7 @@ window.onkeyup = function (e) {
}

function isRpcListChanged(changes) {
if (changes && changes.rpcList) {
if (changes && changes.rpcList && changes.rpcList.newValue) {
let oldList = changes.rpcList.oldValue;
let newList = changes.rpcList.newValue;
if (oldList?.length != newList?.length) {
Expand Down
39 changes: 3 additions & 36 deletions js/utils.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { DefaultAriaNgOptions } from "./config.js";

class Utils {
/**
* export rpc list to ariaNG options
Expand All @@ -7,44 +9,9 @@ class Utils {
* @return {object} The ariaNG options with new RPC list
*/
static exportRpcToAriaNg(rpcList, ariaNgOptions) {
const defaultAriaNgOptions = {
language: 'TBD',
theme: 'light',
title: '${downspeed}, ${upspeed} - ${title}',
titleRefreshInterval: 5000,
browserNotification: false,
browserNotificationSound: true,
browserNotificationFrequency: 'unlimited',
rpcAlias: '',
rpcHost: 'localhost',
rpcPort: '6800',
rpcInterface: 'jsonrpc',
protocol: 'ws',
httpMethod: 'POST',
rpcRequestHeaders: '',
rpcOptions: {},
secret: '',
extendRpcServers: [],
webSocketReconnectInterval: 5000,
globalStatRefreshInterval: 1000,
downloadTaskRefreshInterval: 1000,
keyboardShortcuts: true,
swipeGesture: true,
dragAndDropTasks: true,
rpcListDisplayOrder: 'recentlyUsed',
afterCreatingNewTask: 'task-list',
removeOldTaskAfterRetrying: true,
confirmTaskRemoval: true,
includePrefixWhenCopyingFromTaskDetails: false,
showPiecesInfoInTaskDetailPage: 'le10240',
afterRetryingTask: 'task-list-default',
displayOrder: 'default:asc',
fileListDisplayOrder: 'default:asc',
peerListDisplayOrder: 'default:asc'
}

if (!ariaNgOptions || !Object.keys(ariaNgOptions).length)
ariaNgOptions = defaultAriaNgOptions;
ariaNgOptions = DefaultAriaNgOptions;

ariaNgOptions.extendRpcServers = [];

Expand Down

0 comments on commit 7c79d35

Please sign in to comment.