Skip to content

Commit

Permalink
Merge pull request #21 from sammacbeth/spanan
Browse files Browse the repository at this point in the history
Use spanan for message passing
  • Loading branch information
sammacbeth authored Aug 1, 2018
2 parents 2820121 + 4e4bdfa commit 66a91d0
Show file tree
Hide file tree
Showing 12 changed files with 1,730 additions and 1,749 deletions.
24 changes: 14 additions & 10 deletions addon/content_script.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,18 @@ function postMessage(message) {
const listeners = [];

port.onMessage.addListener((response) => {
listeners.forEach(fn => fn(JSON.stringify(response)));
response.source = 'datfox-api-response';
window.postMessage(response, '*');
console.log('recv', response.uuid, response.action, response.response);
});

function addListener(fn) {
listeners.push(fn)
}

// expose communication channel to background for datArchive API
exportFunction(postMessage, window, { defineAs: '_datfoxPostMessage' });
exportFunction(addListener, window, { defineAs: '_datfoxAddListener' });
window.addEventListener('message', (event) => {
if (event.source === window && event.data &&
event.data.source === 'datfox-api') {
console.log('send', event.data.uuid, event.data.action, ...event.data.args);
port.postMessage(event.data);
}
});

// inject datArchive script into the page
const scriptTag = document.createElement('script');
Expand All @@ -44,5 +46,7 @@ function rewriteDatImageUrls() {

rewriteDatImageUrls();
// rewrite images on the fly
const observer = new MutationObserver(rewriteDatImageUrls);
observer.observe(document.body, { childList:true, subtree:true });
document.onload = () => {
const observer = new MutationObserver(rewriteDatImageUrls);
observer.observe(document.body, { childList:true, subtree:true });
}
9 changes: 7 additions & 2 deletions addon/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"description": "Makes the dat:// protocol available",
"manifest_version": 2,
"name": "Dat P2P Protocol",
"version": "0.1.3",
"version": "0.1.4",
"applications": {
"gecko": {
"id": "{acc91f3f-2194-4f88-b25a-84ec4ea65683}",
Expand Down Expand Up @@ -38,5 +38,10 @@
"options_ui": {
"page": "pages/options.html",
"browser_style": false
}
},
"content_scripts": [{
"matches": ["http://*/*"],
"js": ["content_script.js"],
"run_at": "document_start"
}]
}
2 changes: 1 addition & 1 deletion addon/pages/setup.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ async function testGateway(setLabel) {

async function testVersion(setLabel) {
setLabel('Checking helper version...');
const version = await bridge.postMessage({ action: 'getVersion' });
const version = await bridge.api.getVersion();
const wantedVersion = '0.0.5';
if (version < wantedVersion) {
setLabel(`Helper version ${version} not up-to-date. Latest is ${wantedVersion}`);
Expand Down
31 changes: 14 additions & 17 deletions background/background.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,9 @@ global.resetBridge = async () => {
}
await bridge.connect();
console.log('bridge is ready');
useNativeBridge(bridge);
useNativeBridge(bridge.api);
const port = 3000 + Math.floor(Math.random() * 500);
await bridge.postMessage({
action: 'startGateway',
port: port,
});
await bridge.api.startGateway({ port });
setGatewayAddress(`http://localhost:${port}`);
// add actions which the helper API supports
['resolveName', 'getInfo', 'stat', 'readdir', 'history', 'readFile', 'writeFile', 'mkdir',
Expand All @@ -41,14 +38,14 @@ global.resetBridge = async () => {
});
// manage open archives
setInterval(async () => {
const library = new Set((await bridge.postMessage({ action: 'listLibrary' })).map(({ url }) => url));
const archives = await bridge.postMessage({ action: 'getOpenArchives' });
const library = new Set((await bridge.api.listLibrary()).map(({ url }) => url));
const archives = await bridge.api.getOpenArchives();
// 5 mins inactivity -> close
const ageCutoff = Date.now() - (5 * 60 * 1000);
const closeArchives = archives.filter(({ url, lastUsed }) => !library.has(url) && lastUsed < ageCutoff);
if (closeArchives.length > 0) {
console.log('closing dats:', closeArchives.map(({ url }) => url));
await closeArchives.map(({ url }) => bridge.postMessage({ action: 'closeArchive', url }));
await closeArchives.map(({ url }) => bridge.api.closeArchive({ url }));
}
}, 60000);
return port;
Expand Down Expand Up @@ -76,31 +73,31 @@ const handlers = {

browser.runtime.onConnect.addListener((port) => {
port.onMessage.addListener((message) => {
const { id, action } = message;
const { uuid, action, args } = message;
if (passthroughActions.has(action)) {
bridge.postMessage(message).then(
result => ({ id, action, result }),
error => ({ id, action, error })
bridge.api[action](...args).then(
response => ({ uuid, action, response }),
error => ({ uuid, action, error })
).then(response => {
port.postMessage(response);
});
} else if (handlers[action]) {
handlers[action](message).then((result) => {
handlers[action](message).then((response) => {
port.postMessage({
id,
uuid,
action,
result,
response,
});
}, (error) => {
port.postMessage({
id,
uuid,
action,
error: error,
});
});
} else {
port.postMessage({
id,
uuid,
error: 'unsupported action',
});
}
Expand Down
58 changes: 32 additions & 26 deletions background/native-bridge.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,44 @@
import Spanan from 'spanan';

function wrapMessage(message) {
const compatMessage = {
action: message.action,
id: message.uuid,
};
if (message.args && message.args[0]) {
const args = message.args[0];
Object.keys(args).forEach((k) => {
compatMessage[k] = args[k];
});
}
return compatMessage;
}

function unwrapMessage(message) {
message.uuid = message.id;
if (message.result) {
message.response = message.result;
} else if (!message.error) {
message.response = undefined;
}
return message;
}

export default class {

constructor() {
this.messageIdx = 0;
this.waitingForResponse = new Map();
this.connected = false;
}

connect() {
this.port = browser.runtime.connectNative('dathelper');
this.port.onMessage.addListener(this.onMessage.bind(this));
this.messageWrapper = new Spanan((message) => {
this.port.postMessage(wrapMessage(message));
});
this.port.onMessage.addListener((message) => {
this.messageWrapper.handleMessage(unwrapMessage(message));
});
this.api = this.messageWrapper.createProxy();

return new Promise((resolve, reject) => {
// wait 2s to see if launch of the subprocess was successful
Expand All @@ -26,29 +55,6 @@ export default class {
});
}

onMessage(response) {
if (this.waitingForResponse.has(response.id)) {
const { resolve, reject } = this.waitingForResponse.get(response.id);
this.waitingForResponse.delete(response.id);
if (response.error) {
reject(response.error);
} else {
resolve(response.result);
}
}
}

postMessage(message) {
return new Promise((resolve, reject) => {
message.id = this.messageIdx++;
this.waitingForResponse.set(message.id, {
resolve,
reject,
});
this.port.postMessage(message);
});
}

disconnect() {
this.connected = false;
this.port.disconnect();
Expand Down
19 changes: 7 additions & 12 deletions background/protocol.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,19 +32,14 @@ function init() {
urls: ['http://dat.localhost/*'],
}, ['blocking']);

// insert contentscript on dat pages
browser.webRequest.onCompleted.addListener((details) => {
const host = details.url.split('/')[2];
if (datSites.has(host) || datUrlMatcher.test(host)) {
browser.tabs.executeScript(details.tabId, {
file: browser.extension.getURL('content_script.js'),
runAt: 'document_start',
});
showDatSecureIcon(details.tabId);
// trigger dat secure page action for dat pages
browser.tabs.onUpdated.addListener((tabId, changeInfo) => {
if (changeInfo.url && changeInfo.url.startsWith('http')) {
const host = changeInfo.url.split('/')[2];
if (datSites.has(host) || datUrlMatcher.test(host)) {
showDatSecureIcon(tabId);
}
}
}, {
urls: ['http://*/*'],
types: ['main_frame']
});
}

Expand Down
Loading

0 comments on commit 66a91d0

Please sign in to comment.