From 0eb6194bc6e4ece45487a7b7cead8a9547629487 Mon Sep 17 00:00:00 2001 From: ilyaigpetrov Date: Thu, 22 Aug 2024 15:26:44 +0500 Subject: [PATCH] Add js-logic to the popup's pacChooser form. Remove code related to CopyUnicodeUrls --- package.json | 3 +- src/bg/05-data-init-and-migrations.mjs | 17 ++--- src/bg/10-main.mjs | 76 ++++-------------- src/bg/index.mjs | 6 +- src/lib/copy-to-clipboard.mjs | 61 --------------- src/lib/offscreen-doc-for-copying.html | 3 - src/lib/offscreen-doc-for-copying.mjs | 74 ------------------ src/pages/options/index.html | 102 ++++++++++++++++--------- src/pages/options/index.mjs | 40 ++++++++++ 9 files changed, 127 insertions(+), 255 deletions(-) delete mode 100644 src/lib/copy-to-clipboard.mjs delete mode 100644 src/lib/offscreen-doc-for-copying.html delete mode 100644 src/lib/offscreen-doc-for-copying.mjs diff --git a/package.json b/package.json index 39af176..5968b9d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "runet-censorship-bypass", - "version": "0.2.0", + "version": "0.0.2", "description": "", "homepage": "https://github.com/ilyaigpetrov/copy-unicode-urls#readme", "main": "index.js", @@ -20,7 +20,6 @@ }, "license": "ISC", "dependencies": { - "punycode": "^2.1.1" }, "devDependencies": { "merge": "^2.1.1", diff --git a/src/bg/05-data-init-and-migrations.mjs b/src/bg/05-data-init-and-migrations.mjs index d729c78..5f80932 100644 --- a/src/bg/05-data-init-and-migrations.mjs +++ b/src/bg/05-data-init-and-migrations.mjs @@ -3,12 +3,8 @@ import { versions, storage } from '../lib/index.mjs'; globalThis.migrationPromise = new Promise(async (resolve) => { console.log('Checking for migrations...'); const dflts = { - options: [ - [ 'ifToDecode', true ], - [ 'ifToDecodeMultipleTimes', false ], - [ 'ifToEncodeUrlTerminators', true ], - ], - donateUrl: 'https://rebrand.ly/ilya-donate', + // TODO: Define defaults. + options: {}, }; const ifEmpty = await storage.isEmptyAsync(); if (ifEmpty) { @@ -23,21 +19,20 @@ globalThis.migrationPromise = new Promise(async (resolve) => { console.log(`Current extension version is ${versions.current}.`); const oldVersion = await storage.getAsync('version'); const ifNoNeedToMigrate = oldVersion === versions.current; - if (ifNoNeedToMigrate) {http://я.рф/яhttp://я.рф/я + if (ifNoNeedToMigrate) { console.log('No need for migration.'); return resolve(); } console.log(`Migrating to ${versions.current} from ${oldVersion || 'a very old version'}.`); switch(true) { case !oldVersion: { - // Update from version <= 0.0.18. - const ifSentence = await storage.getAsync('ifToEncodeSentenceTerminators'); + // Update from version <= 0.0.1. + const ifSentence = await storage.getAsync('SOME_KEY'); if (ifSentence !== undefined) { - console.log('Migrating to 0.0.18.'); + console.log('Migrating to 0.0.1.'); await storage.setAsync({ ifToEncodeUrlTerminators: ifSentence, }); - await storage.removeAsync('ifToEncodeSentenceTerminators') } }; // Fallthrough. case versions.isLeq(oldVersion, '0.0.18'): { diff --git a/src/bg/10-main.mjs b/src/bg/10-main.mjs index 6e56793..dd4ff5a 100644 --- a/src/bg/10-main.mjs +++ b/src/bg/10-main.mjs @@ -1,7 +1,13 @@ -import { toUnicode } from '../../node_modules/punycode/punycode.es6.js'; -import { copyToClipboardAsync } from '../lib/copy-to-clipboard.mjs'; import { storage } from '../lib/index.mjs'; +console.log('Main script starts...'); + +(async () => { + const theState = await storage.getAsync(); + console.log('The state is:', theState); +})(); + +/* const ID_TO_MENU_HANDLER = {}; const createMenuEntry = (id, type, title, handler, contexts, rest) => { @@ -27,63 +33,6 @@ const copyUrlInstalledPromise = (async () => { console.log('Migration is finished.'); const options = await storage.getAsync('options'); - const getOpt = (key) => (options.find((el) => el[0] === key)[1]); - console.log('Options are:', options); - - const localizeUrl = (url) => { - console.log('Localizing url:', url); - let u; - try { - u = new URL(url); - } catch { - u = new URL(`http://${url}`); - } - let newHref = u.href; - let oldHref; - do { - oldHref = newHref; - newHref = decodeURI( - newHref - .replace(u.hostname, toUnicode(u.hostname)) - /* - Don't decode `%25` to `%` because it causes errors while being put in GitHub URLs. - Test case: https://github.com/ilyaigpetrov/copy-unicode-urls/wiki/Test-%25-and-%3F - */ - .replaceAll('%25', '%2525'), - ) - // Encode whitespace. - .replace( - /\s/g, - (_, index, wholeString) => encodeURIComponent(wholeString.charAt(index)), - ); - } while (getOpt('ifToDecodeMultipleTimes') && oldHref !== newHref); - console.log('Localized:', newHref); - return newHref; - }; - - const copyUrl = async (url) => { - if (getOpt('ifToDecode')) { - url = localizeUrl(url); - } - if (getOpt('ifToEncodeUrlTerminators')) { - console.log('Encoding terminators...'); - /* - Issue #7. - Thunderbird sources: - https://searchfox.org/comm-central/source/mozilla/netwerk/streamconv/converters/mozTXTToHTMLConv.cpp#281 (mozTXTToHTMLConv::FindURLEnd) - These chars terminate the URL: ><"`}{)]` - These sequence doesn't terminate the URL: //[ (e.g. http://[1080::...) - These chars are not allowed at the end of the URL: .,;!?-:' - I apply slightly more strict rules below. - **/ - const toPercentCode = (char) => '%' + char.charCodeAt(0).toString(16).toUpperCase(); - url = url.replace( - /(?:[<>{}()[\]"`']|[.,;:!?-]$)/g, - (matchedChar, index, wholeString) => toPercentCode(matchedChar), - ); - } - copyToClipboardAsync(url); - }; // CheckBoxes const capitalizeFirstLetter = (str) => str @@ -137,12 +86,12 @@ const copyUrlInstalledPromise = (async () => { 'copyHighlightLink', 'normal', chrome.i18n.getMessage('CopyUnicodeLinkToHighlight'), (info) => { - copyUrl(`${info.pageUrl.replace(/#.*/g, '')}#:~:text=${info.selectionText}`); + copyUrl(`${info.pageUrl.replace(/#.*\/g, '')}#:~:text=${info.selectionText}`); }, ['selection'], ); - return copyUrl; + return Promise.resolve(); })(); @@ -162,5 +111,6 @@ chrome.action.onClicked.addListener(async ({ url: urlToBeCopied }) => { console.log('Main waits for listeners to be installed...'); const copyUrl = await copyUrlInstalledPromise; console.log('Action clicked with url:', urlToBeCopied); - copyUrl(urlToBeCopied); -}); \ No newline at end of file + //copyUrl(urlToBeCopied); +}); +*/ \ No newline at end of file diff --git a/src/bg/index.mjs b/src/bg/index.mjs index 09ba36a..c819307 100644 --- a/src/bg/index.mjs +++ b/src/bg/index.mjs @@ -1,5 +1,5 @@ -import "./00-start.mjs"; -import "./05-data-init-and-migrations.mjs"; -import "./10-main.mjs"; +import './00-start.mjs'; +import './05-data-init-and-migrations.mjs'; +import './10-main.mjs'; console.log('Background script finished loading.'); diff --git a/src/lib/copy-to-clipboard.mjs b/src/lib/copy-to-clipboard.mjs deleted file mode 100644 index f535f62..0000000 --- a/src/lib/copy-to-clipboard.mjs +++ /dev/null @@ -1,61 +0,0 @@ -let IF_ALREADY_PROMISE; // A global promise to avoid concurrency issues. -const OFFSCREEN_DOC_PATH = '/src/lib/offscreen-doc-for-copying.html'; - -export const copyToClipboardAsync = async (copyMe) => { - console.log('Going to copy this url:', copyMe); - try { - console.log('Trying `navigator.clipboard`...'); - return await navigator.clipboard.writeText(copyMe); - } catch(e) { - console.log('Got error while copying attempt:', e); - if (globalThis.document) { - console.log('Trying `globalThis.document`...'); - const area = document.createElement('textarea'); - area.value = copyMe; - document.body.appendChild(area); - area.select(); - document.execCommand('copy'); - document.body.removeChild(area); - return; - } - console.log('Trying `chrome.offscreen`...'); - - async function setupOffscreenDocument(path) { - // Check all windows controlled by the service worker to see if one - // of them is the offscreen document with the given path - const offscreenUrl = chrome.runtime.getURL(path); - const existingContexts = await chrome.runtime.getContexts({ - contextTypes: ['OFFSCREEN_DOCUMENT'], - documentUrls: [offscreenUrl], - }); - console.log('Existing contexts:', existingContexts); - - if (existingContexts.length > 0) { - console.log('Offscreen document already exists.'); - return; - } - - // create offscreen document - if (IF_ALREADY_PROMISE) { - return IF_ALREADY_PROMISE; - } - console.log('Creating new offscreen document for:', path); - IF_ALREADY_PROMISE = chrome.offscreen.createDocument({ - url: path, - reasons: [chrome.offscreen.Reason.CLIPBOARD], - justification: 'reason for needing the document', - }); - await IF_ALREADY_PROMISE; - console.log('New offscreen document created.'); - IF_ALREADY_PROMISE = null; - } - await setupOffscreenDocument(OFFSCREEN_DOC_PATH); - // Now that we have an offscreen document, we can dispatch the - // message. - chrome.runtime.sendMessage({ - type: 'copy-data-to-clipboard', - target: 'offscreen-doc', - data: copyMe, - }); - } -}; \ No newline at end of file diff --git a/src/lib/offscreen-doc-for-copying.html b/src/lib/offscreen-doc-for-copying.html deleted file mode 100644 index 757c426..0000000 --- a/src/lib/offscreen-doc-for-copying.html +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/src/lib/offscreen-doc-for-copying.mjs b/src/lib/offscreen-doc-for-copying.mjs deleted file mode 100644 index 5d12af0..0000000 --- a/src/lib/offscreen-doc-for-copying.mjs +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2023 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Once the message has been posted from the service worker, checks are made to -// confirm the message type and target before proceeding. This is so that the -// module can easily be adapted into existing workflows where secondary uses for -// the document (or alternate offscreen documents) might be implemented. - -// Registering this listener when the script is first executed ensures that the -// offscreen document will be able to receive messages when the promise returned -// by `offscreen.createDocument()` resolves. -chrome.runtime.onMessage.addListener(handleMessages); - -// This function performs basic filtering and error checking on messages before -// dispatching the -// message to a more specific message handler. -async function handleMessages(message) { - // Return early if this message isn't meant for the offscreen document. - if (message.target !== 'offscreen-doc') { - return; - } - - // Dispatch the message to an appropriate handler. - switch (message.type) { - case 'copy-data-to-clipboard': - handleClipboardWrite(message.data); - break; - default: - console.warn(`Unexpected message type received: '${message.type}'.`); - } -} - -// We use a