Skip to content

Commit

Permalink
fix: multiple issues
Browse files Browse the repository at this point in the history
- service worker shuts down every 5 minutes (more or less works)
- extension doesn't work until you open the pop-up
- customize cURL timeouts
  • Loading branch information
Joel2B committed Jun 30, 2022
1 parent 7b16a75 commit bad8db5
Show file tree
Hide file tree
Showing 13 changed files with 207 additions and 56 deletions.
3 changes: 2 additions & 1 deletion src/extension/css/content-script.css
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@
font-size: 16px;
}

#line1, #line2 {
#line1,
#line2 {
width: 100%;
height: 50%;
}
Expand Down
2 changes: 1 addition & 1 deletion src/extension/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
}
],
"background": {
"service_worker": "background.js"
"service_worker": "js/background.js"
},
"permissions": ["activeTab", "storage", "tabs", "scripting"],
"host_permissions": ["*://*.youtube.com/*"],
Expand Down
53 changes: 51 additions & 2 deletions src/extension/modules/background.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,61 @@
import { getLocalStorage, setLocalStorage } from 'utils/chrome/storage';
import { onMessage } from 'utils/chrome/runtime';
import { onMessage, onInstalled, getAll, getManifest, executeScript, insertCSS } from 'utils/chrome/runtime';
import defaults from './defaults';

onMessage(async (request) => {
const id = request.id;
const value = request.value;

if (id == 'analytics') {
const data = await getLocalStorage(id);
data[value] += 1;
setLocalStorage(id, data);
}
}, true);
});

async function setDefaultSettings() {
const config = defaults;

for (const option in config) {
if ((await getLocalStorage(option)) !== undefined) {
continue;
}

setLocalStorage(option, config[option]);
}
}

async function init() {
await setDefaultSettings();

const navigatorWindows = await getAll();
const contentScripts = getManifest().content_scripts[0];
const match = contentScripts.matches[0].replaceAll('*', '.*').replaceAll('/', '\\/');
const regex = new RegExp(match);
const js = contentScripts.js[0];
const css = contentScripts.css[0];

navigatorWindows.forEach((window) => {
for (const tab of window.tabs) {
if (!regex.test(tab.url)) {
continue;
}

executeScript({
target: {
tabId: tab.id,
},
files: [js],
});

insertCSS({
target: {
tabId: tab.id,
},
files: [css],
});
}
});
}

onInstalled(init);
115 changes: 82 additions & 33 deletions src/extension/modules/content-script.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { onMessage } from 'utils/chrome/runtime';
import { onMessage, sendMessageBackground } from 'utils/chrome/runtime';
import { setOption, getAllOptions, getOption } from 'extension/modules/data';
import {
setupSubtitles,
Expand All @@ -13,32 +13,18 @@ let observer;

const tasks = {
captions: (value) => {
if (value) {
connectObserver();
} else {
disconnectObserver();
}
},
translateTo: () => {
translateSubtitles();
},
'created-translations': () => {
translateSubtitles();
(value ? connectObserver : disconnectObserver)();
},
translateTo: () => translateSubtitles(),
'created-translations': () => translateSubtitles(),
'auto-translate': () => {
if (!getOption('created-translations')) {
translateSubtitles();
}
},
'time-close-translation': () => {
removeTranslation();
if (!getOption('created-translations')) translateSubtitles();
},
'time-close-translation': () => removeTranslation(),
};

function performTask(id, value) {
if (tasks[id]) {
tasks[id](value);
}
if (tasks[id]) tasks[id](value);
}

async function connectObserver() {
Expand All @@ -55,8 +41,8 @@ async function connectObserver() {
continue;
}

if (mutation.type == 'childList' && classCss.includes('ytp-caption-segment')) {
if (line2 == '') {
if (mutation.type === 'childList' && classCss.includes('ytp-caption-segment')) {
if (line2 === '') {
line2 = text;
} else {
if (RegExp(escape(line2)).test(text)) {
Expand All @@ -67,11 +53,13 @@ async function connectObserver() {
if (captions) {
captions.style.display = 'none';
}

line1 = line2;
line2 = text;
}
}
}

document.querySelector('#line1').innerHTML = wordToSpan(line1);
document.querySelector('#line2').innerHTML = wordToSpan(line2);
}
Expand All @@ -82,28 +70,34 @@ async function connectObserver() {
return new Promise((resolve) => {
const timer = setInterval(() => {
console.log('[Extension] Trying to connect the observer');

const player = document.querySelector('#movie_player');

if (player) {
clearInterval(timer);
resolve(player);
}
}, 50);
setTimeout(() => {
const player = document.querySelector('#movie_player');

if (!player) {
clearInterval(timer);
console.log('[Extension] Observer error (time limit exceeded)');
clearInterval(timer);
resolve();
}
}, 10 * 1000);
});
};

const player = await playerAvailable();

if (!player) {
return;
}

await setupSubtitles(player);

const config = {
attributes: true,
childList: true,
Expand All @@ -115,55 +109,110 @@ async function connectObserver() {

observer = new MutationObserver(callback);
observer.observe(player, config);

console.log('[Extension] Observer connected');
}

function disconnectObserver() {
if (!observer) {
return;
}
if (!observer) return;

observer.disconnect();
deactivateSubtitles();

console.log('[Extension] Observer disconnected');
}

function restartExecution() {
setInterval(() => {
const timer = setInterval(() => {
if (!getId()) {
clearInterval(timer);
return;
}

const url = window.location.href;
if (getOption('curent-path') != url && url.includes('watch')) {

if (getOption('curent-path') !== url && url.includes('watch')) {
if (observer) {
disconnectObserver();
setOption('subtitlesActivated', false);
}

removeSubtitles();
connectObserver();
}
if (getOption('curent-path') != url) {

if (getOption('curent-path') !== url) {
setOption('curent-path', url);
}
}, 100);
}

function getId() {
// eslint-disable-next-line no-undef
return chrome.runtime.id;
}

function getDate() {
return Number(Date.now().toString().slice(0, 10));
}

async function app() {
if (!getId()) return;

if (process.env.NODE_ENV === 'development') {
console.log('Extension id:', getId());
}

await getAllOptions();

// TODO: provisional
const timeKeepAlive = getOption('timeKeepAlive');
let keepAlive = (getDate() + timeKeepAlive) * 1000;

const timer = setInterval(() => {
if (keepAlive < Date.now()) {
sendMessageBackground('');

keepAlive = (getDate() + timeKeepAlive) * 1000;

if (process.env.NODE_ENV === 'development') {
console.log('keep alive', keepAlive, Date.now());
}
}

if (getId()) return;

disconnectObserver();
removeSubtitles();

if (process.env.NODE_ENV === 'development') {
console.log('lost extension connection');
}

clearInterval(timer);
}, 1000);

if (!getOption('curent-path')) {
setOption('curent-path', window.location.href);
restartExecution();
}

onMessage((request) => {
if (!getId()) return;

const id = request.id;
if (id == 'analytics') {

if (id === 'analytics') {
return;
}

const value = request.value;

setOption(id, value);
performTask(id, value);
});

const captions = getOption('captions');
if (!captions) {
if (!getOption('captions')) {
return;
}

Expand Down
17 changes: 17 additions & 0 deletions src/extension/modules/defaults.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const defaults = {
captions: true,
subtitlesActivated: false,
'curent-path': '',
'auto-translate': true,
'created-translations': true,
'primary-language': 'Spanish#es',
'server-translate': 'Deepl*#deepl',
'time-close-translation': 3,
translateTo: 'English#en',
analytics: {
'translated-words': 0,
},
timeKeepAlive: 240,
};

export default defaults;
6 changes: 4 additions & 2 deletions src/extension/modules/subtitles.js
Original file line number Diff line number Diff line change
Expand Up @@ -182,15 +182,17 @@ async function translateWord(e) {
}

export function deactivateSubtitles() {
removeSubtitles();

if (!isSubtitlesEnabled()) {
return;
}

if (getSubtitleButton().getAttribute('aria-pressed') == 'true') {
getSubtitleButton().click();
}

setOption('subtitlesActivated', false);
removeSubtitles();
}

function createSubtitles() {
Expand Down Expand Up @@ -254,7 +256,7 @@ function dragSubtitles() {

export async function translateSubtitles() {
let translateTo = getOption('translateTo');
if (translateTo.includes('#')) {
if (translateTo && translateTo.includes('#')) {
translateTo = translateTo.split('#')[0];
}

Expand Down
4 changes: 2 additions & 2 deletions src/pop-up/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Auto Translate Youtube Subtitles</title>
<link rel="stylesheet" href="css/pop-up.css" />
<link rel="stylesheet" href="./css/pop-up.css" />
</head>
<body>
<div class="popup">
Expand Down Expand Up @@ -362,6 +362,6 @@
</div>
</div>
</div>
<script src="js/pop-up.js"></script>
<script src="./js/pop-up.js"></script>
</body>
</html>
1 change: 1 addition & 0 deletions src/pop-up/modules/input.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export async function setupNumberInput(numberInput) {
value = Number(input.value);
setValue(id, value);
}

input.value = value;

input.addEventListener(
Expand Down
9 changes: 2 additions & 7 deletions src/pop-up/modules/script.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,8 @@ import { setupNumberInput } from 'pop-up/modules/input';
import { sendMessage } from 'utils/chrome/runtime';

async function loadAnalytics() {
let analytics = await getLocalStorage('analytics');
if (!analytics) {
analytics = {
'translated-words': 0,
};
setLocalStorage('analytics', analytics);
}
const analytics = await getLocalStorage('analytics');

document.getElementById('translated-words').textContent = analytics['translated-words'];
}

Expand Down
Loading

0 comments on commit bad8db5

Please sign in to comment.