Skip to content

Commit

Permalink
refactor: Simplifier le code source.
Browse files Browse the repository at this point in the history
  • Loading branch information
regseb committed Feb 1, 2020
1 parent 0678172 commit 167d4fe
Show file tree
Hide file tree
Showing 19 changed files with 210 additions and 144 deletions.
2 changes: 1 addition & 1 deletion .metalint/eslint.json
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@
"no-constructor-return": 2,
"no-div-regex": 2,
"no-else-return": [2, { "allowElseIf": false }],
"no-empty-function": 2,
"no-empty-function": [2, { "allow": ["arrowFunctions"] }],
"no-empty-pattern": 2,
"no-eq-null": 0,
"no-eval": 2,
Expand Down
1 change: 0 additions & 1 deletion .metalint/eslint_nodejs.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
"globals": {
"URL": "readonly",
"browser": "readonly",
"btoa": "readonly",
"DOMParser": "readonly",
"fetch": "readonly",
"WebSocket": "readonly"
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
"node-fetch": "^2.6.0",
"nyc": "^15.0.0",
"purgecss": "^2.0.5",
"sinon": "^8.1.0",
"standard-version": "^7.1.0",
"stylelint": "^13.0.0",
"stylelint-order": "^4.0.0",
Expand Down
13 changes: 9 additions & 4 deletions src/background/menu.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
*/

import { cast } from "../core/index.js";
import { notify } from "../core/notify.js";

/**
* Agrège les liens des différents points d'entrée.
Expand All @@ -13,9 +14,9 @@ import { cast } from "../core/index.js";
*/
const aggregate = async function (info) {
if ("bookmarkId" in info) {
const bookmark = await browser.bookmarks.get(info.bookmarkId);
return ["url" in bookmark[0] ? bookmark[0].url
: ""];
const bookmarks = await browser.bookmarks.get(info.bookmarkId);
return bookmarks.map((b) => ("url" in b ? b.url
: b.title));
}

return [
Expand All @@ -33,7 +34,11 @@ const click = async function (info) {
if ("send" === info.menuItemId || "insert" === info.menuItemId ||
"add" === info.menuItemId) {
const urls = await aggregate(info);
cast(info.menuItemId, urls);
try {
await cast(info.menuItemId, urls);
} catch (err) {
notify(err);
}
} else if (!info.wasChecked) {
browser.storage.local.set({
"server-active": parseInt(info.menuItemId, 10)
Expand Down
5 changes: 2 additions & 3 deletions src/core/i18n.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,9 @@ for (const element of walk()) {
element.textContent = value;
} else {
for (const node of element.childNodes) {
if ("#text" !== node.nodeName) {
continue;
if ("#text" === node.nodeName) {
node.nodeValue = node.nodeValue.replace("{}", value);
}
node.nodeValue = node.nodeValue.replace("{}", value);
}
}
} else {
Expand Down
66 changes: 47 additions & 19 deletions src/core/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,17 @@
* @module
*/

import { jsonrpc } from "./jsonrpc.js";
import { notify } from "./notify.js";
import { JSONRPC } from "./jsonrpc.js";
import { PebkacError } from "./pebkac.js";
import { extract } from "./scrapers.js";

/**
* Le client JSON-RPC pour contacter Kodi.
*
* @type {object}
*/
export const jsonrpc = new JSONRPC("");

/**
* Récupère le lien à analyser parmi les données récupérées.
*
Expand All @@ -30,41 +36,63 @@ export const mux = function (urls) {
(/^magnet:.*$/iu).test(url) ||
(/^acestream:.*$/iu).test(url));
} catch {
// Ignorer l'erreur provenant d'une URL invalide.
// Indiquer que la construction de l'URL a échouée.
return false;
}
});
};

/**
* Crée le client JSON-RPC pour contacter Kodi.
*
* @param {object} changes Les paramètres modifiés dans la configuration.
*/
const change = async function (changes) {
// Ignorer tous les changements sauf ceux liés au serveur.
if (!Object.entries(changes).some(([k, v]) => k.startsWith("server-") &&
"newValue" in v)) {
return;
}

const config = await browser.storage.local.get();
jsonrpc.close();
jsonrpc.host = config["server-list"][config["server-active"]].host;
jsonrpc.onChanged();
};

/**
* Diffuse un média sur Kodi.
*
* @function
* @param {string} action L'action à effectuer (<code>"send"</code>,
* <code>"insert"</code> ou <code>"add"</code>).
* @param {Array.<string>} urls La liste des éventuelles URLs.
* @returns {Promise.<void>} Une promesse tenue ou rejetée.
* @returns {Promise.<void>} Une promesse tenue vide.
*/
export const cast = async function (action, urls) {
const url = mux(urls);
if (undefined === url) {
return notify(1 === urls.length ? new PebkacError("noLink", urls[0])
: new PebkacError("noLinks"));
throw 1 === urls.length ? new PebkacError("noLink", urls[0])
: new PebkacError("noLinks");
}


try {
const file = await extract(new URL(url), { "depth": 0 });
switch (action) {
case "send": await jsonrpc.send(file); break;
case "insert": await jsonrpc.insert(file); break;
case "add": await jsonrpc.add(file); break;
default: return notify(new Error(action + " is not supported"));
}
const config = await browser.storage.local.get(["general-history"]);
return config["general-history"] ? browser.history.addUrl({ url })
: Promise.resolve();
} catch (err) {
return notify(err);
const file = await extract(new URL(url), { "depth": 0 });
switch (action) {
case "send": await jsonrpc.send(file); break;
case "insert": await jsonrpc.insert(file); break;
case "add": await jsonrpc.add(file); break;
default: throw new Error(action + " is not supported");
}

const config = await browser.storage.local.get(["general-history"]);
if (config["general-history"]) {
await browser.history.addUrl({ url });
}
};

// Simuler un changement de configuration pour se connecter au bon serveur. Ce
// bidouillage est utile quand ce fichier est chargé depuis les options ou la
// popin (dans le background, cette migration qui change la configuration).
change({ "server-": { "newValue": null } });
browser.storage.onChanged.addListener(change);
31 changes: 0 additions & 31 deletions src/core/jsonrpc.js
Original file line number Diff line number Diff line change
Expand Up @@ -516,34 +516,3 @@ export const JSONRPC = class {
});
}
};

/**
* Le client JSON-RPC pour contacter Kodi.
*
* @type {object}
*/
export const jsonrpc = new JSONRPC("");

/**
* Crée le client JSON-RPC pour contacter Kodi.
*
* @param {object} changes Les paramètres modifiés dans la configuration.
*/
const change = async function (changes) {
// Ignorer tous les changements sauf ceux liés au serveur.
if (!Object.entries(changes).some(([k, v]) => k.startsWith("server-") &&
"newValue" in v)) {
return;
}

const config = await browser.storage.local.get();
jsonrpc.close();
jsonrpc.host = config["server-list"][config["server-active"]].host;
jsonrpc.onChanged();
};

// Simuler un changement de configuration pour se connecter au bon serveur. Ce
// bidouillage est utile quand ce fichier est chargé depuis les options ou la
// popin (dans le background, cette migration qui change la configuration).
change({ "server-": { "newValue": null } });
browser.storage.onChanged.addListener(change);
2 changes: 0 additions & 2 deletions src/core/notify.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
*
* @function
* @param {object} err L'erreur affichée dans la notification.
* @returns {Promise.<void>} Une promesse rejetée contenant l'erreur.
*/
export const notify = function (err) {
browser.notifications.create(null, {
Expand All @@ -18,5 +17,4 @@ export const notify = function (err) {
: browser.i18n.getMessage("notifications_unknown_title"),
"message": err.message
});
return Promise.reject(err);
};
Loading

0 comments on commit 167d4fe

Please sign in to comment.