Skip to content

Commit

Permalink
feat: add method to check if global postage batch is enabled (#122) (#…
Browse files Browse the repository at this point in the history
…128)

* feat: add method to check if global postage batch is enabled (#122)

* test: add test for enabled global postage batch
  • Loading branch information
tomicvladan authored Jul 1, 2022
1 parent bbfd653 commit b56536f
Show file tree
Hide file tree
Showing 11 changed files with 139 additions and 33 deletions.
36 changes: 36 additions & 0 deletions src/background/feeder/postage-batch.feeder.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { InterceptorReqMessageFormat, ResponseMessageFormat } from '../../utils/message/message-handler'
import { getItem } from '../../utils/storage'

export class PostageBatchFeeder {
constructor() {
this.serveEvents()
}
serveEvents(): void {
console.log('Register PostageBatchFeeder event listeners...')

chrome.runtime.onMessage.addListener((message: InterceptorReqMessageFormat<string>, sender, sendResponse) => {
if (message.key === 'isGlobalPostageBatchEnabled') {
console.log('PostageBatchFeeder:isGlobalPostageBatchEnabled got aimed message from content script', message)

const response: ResponseMessageFormat = {
key: message.key,
sender: 'background',
target: 'content',
}

getItem('globalPostageBatch')
.then(value => {
response.answer = Boolean(value)
})
.catch(e => {
response.error = String(e)
})
.finally(() => {
sendResponse(response)
})

return true
}
})
}
}
2 changes: 2 additions & 0 deletions src/background/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { DappSessionManager } from './dapp-session.manager'
import { DappSessionFeeder } from './feeder/dapp-session.feeder'
import { LocalStorageFeeder } from './feeder/local-storage.feeder'
import { Web2HelperFeeder } from './feeder/web2-helper.feeder'
import { PostageBatchFeeder } from './feeder/postage-batch.feeder'
import { BeeApiListener } from './listener/bee-api.listener'
import { DebugListener } from './listener/debug.listener'
import { setupLiveReload } from './live-reload/live-reload'
Expand All @@ -15,5 +16,6 @@ new DappSessionFeeder(dappSessionManager)
new LocalStorageFeeder(dappSessionManager)
new DebugListener()
new Web2HelperFeeder(beeApiListener)
new PostageBatchFeeder()

if (process.env.SWARM_DEVELOPMENT) setupLiveReload()
2 changes: 2 additions & 0 deletions src/contentscript/swarm-library/index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import * as BzzLink from './bzz-link'
import { localStorage } from './local-storage'
import { postageBatch } from './postage-batch'
import { web2HelperContent } from './web2-helper.content'

window.swarm = {
...window.swarm,
web2Helper: web2HelperContent,
localStorage,
bzzLink: BzzLink,
postageBatch: postageBatch,
}

console.log('window.swarm has been inited')
35 changes: 34 additions & 1 deletion src/contentscript/swarm-library/messenger.inpage.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { InterceptorResMessageFormat } from '../../utils/message/message-handler'
import { InpageReqMessageFormat, InterceptorResMessageFormat } from '../../utils/message/message-handler'

export class MessengerInpage {
protected readonly contentPageOrigin = window.origin
Expand All @@ -17,4 +17,37 @@ export class MessengerInpage {

return false
}

protected messageHandler<Response>(
message: InpageReqMessageFormat<unknown>,
handlerClass: string,
): Promise<Response> {
return new Promise<Response>((resolve, reject) => {
const handler = (response: MessageEvent<InterceptorResMessageFormat<Response>>) => {
if (!this.validMessage(response, message.eventId)) return

// Remove listener since this was the response that we were looking for at this point
window.removeEventListener('message', handler)

// handle message
if (response.data.error) reject(response.data.error)

if (response.data.answer === undefined) {
const errorMessage = `${handlerClass} inpage request failed. It didn't get any answer. ID: ${response.data.eventId}`
console.error(errorMessage, response)
reject(errorMessage)
} else {
resolve(response.data.answer)
}
}

window.addEventListener('message', handler)
/**
* TODO: target by app origin
* origin is null because of the sandbox
*/
const origin = '*'
window.postMessage(message, origin)
})
}
}
22 changes: 22 additions & 0 deletions src/contentscript/swarm-library/postage-batch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { nanoid } from 'nanoid'
import { InpageReqMessageFormat } from '../../utils/message/message-handler'
import { PostageBatchMessage } from '../../utils/message/postage-batch/postage-batch.message'
import { MessengerInpage } from './messenger.inpage'

export class PostageBatch extends MessengerInpage implements PostageBatchMessage {
/**
* Checks whether the global postage batch is enabled or not
*/
public isGlobalPostageBatchEnabled(): Promise<string> {
const message: InpageReqMessageFormat<undefined> = {
key: 'isGlobalPostageBatchEnabled',
eventId: nanoid(),
sender: 'inpage',
target: 'content',
}

return this.messageHandler(message, 'PostageBatch')
}
}

export const postageBatch = new PostageBatch()
33 changes: 2 additions & 31 deletions src/contentscript/swarm-library/web2-helper.content.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,35 +6,6 @@ import { appendSwarmSessionIdToUrl } from '../../utils/swarm-session-id'
import { MessengerInpage } from './messenger.inpage'

export class Web2HelperContent extends MessengerInpage implements IWeb2HelperMessage {
private messageHandler<Response>(message: InpageReqMessageFormat<unknown>) {
return new Promise<Response>((resolve, reject) => {
const handler = (response: MessageEvent<InterceptorResMessageFormat<Response>>) => {
if (!this.validMessage(response, message.eventId)) return

// Remove listener since this was the response that we were looking for at this point
window.removeEventListener('message', handler)

// handle message
if (response.data.error) reject(response.data.error)

if (response.data.answer === undefined) {
const errorMessage = `Web2Helper inpage request failed. It didn't get any answer. ID: ${response.data.eventId}`
console.error(errorMessage, response)
reject(errorMessage)
} else {
resolve(response.data.answer)
}
}

window.addEventListener('message', handler)
/**
* TODO: target by app origin
* origin is null because of the sandbox
*/
const origin = '*'
window.postMessage(message, origin)
})
}
/** The real Bee API address that shouldn't be called directly by dApps */
public beeApiUrl(): Promise<string> {
const message: InpageReqMessageFormat<undefined> = {
Expand All @@ -44,7 +15,7 @@ export class Web2HelperContent extends MessengerInpage implements IWeb2HelperMes
target: 'content',
}

return this.messageHandler<string>(message)
return this.messageHandler<string>(message, 'Web2Helper')
}

/**
Expand All @@ -58,7 +29,7 @@ export class Web2HelperContent extends MessengerInpage implements IWeb2HelperMes
target: 'content',
}

return this.messageHandler<boolean>(message)
return this.messageHandler<boolean>(message, 'Web2Helper')
}

/**
Expand Down
3 changes: 3 additions & 0 deletions src/utils/message/postage-batch/postage-batch.message.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export interface PostageBatchMessage {
isGlobalPostageBatchEnabled(): Promise<string>
}
22 changes: 21 additions & 1 deletion test/bzz-protocol.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -195,12 +195,22 @@ describe('BZZ protocol', () => {
done()
})

test('Check if global postage batch is enabled', async done => {
await page.click('#button-check-global-postage-batch-enabled')
const placeHolderSelector = '#global-postage-batch-placeholder[complete="true"]'
await page.waitForSelector(placeHolderSelector)
const value = await page.$eval(placeHolderSelector, e => e.innerHTML)
expect(value).toBe('false') //default value of Bee API URL in the extension

done()
})

test('Check Real Bee API is available', async done => {
await page.click('#button-check-real-bee-api-available')
const placeHolderSelector = '#bee-api-available-placeholder[complete="true"]'
await page.waitForSelector(placeHolderSelector)
const value = await page.$eval(placeHolderSelector, e => e.innerHTML)
expect(value).toBe('true') //default value of Bee API URL in the extension
expect(value).toBe('true')

done()
})
Expand All @@ -225,6 +235,16 @@ describe('BZZ protocol', () => {
done()
})

test('Check if global postage batch is enabled', async done => {
await page.click('#button-check-global-postage-batch-enabled')
const placeHolderSelector = '#global-postage-batch-placeholder[complete="true"]'
await page.waitForSelector(placeHolderSelector)
const value = await page.$eval(placeHolderSelector, e => e.innerHTML)
expect(value).toBe('true')

done()
})

test('Upload file through Fake URL', async done => {
page = await global.__BROWSER__.newPage()
await page.goto(`${BEE_API_URL}/bzz/${rootFolderReference}`, { waitUntil: 'networkidle0' })
Expand Down
5 changes: 5 additions & 0 deletions test/bzz-test-page/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,11 @@ <h4>Fetch Real Bee API URL</h4>
<button id="button-fetch-real-bee-api-url" onclick="fetchBeeApiUrl()">Fetch</button>
<label id="bee-api-url-placeholder">[Bee API URL Placeholder]</label>
</div>
<div>
<h4>Check if Globa Postage Batch is enabled</h4>
<button id="button-check-global-postage-batch-enabled" onclick="fetchGlobalPostageBatch()">Fetch</button>
<label id="global-postage-batch-placeholder">[Globa Postage Batch Enabled Placeholder]</label>
</div>
<div>
<h4>Check if Real Bee API is available</h4>
<button id="button-check-real-bee-api-available" onclick="checkBeeApiAvailable()">Fetch</button>
Expand Down
10 changes: 10 additions & 0 deletions test/bzz-test-page/index.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,19 @@
const web2Helper = window.swarm.web2Helper
const postageBatch = window.swarm.postageBatch

function fetchBeeApiUrl() {
web2Helper.beeApiUrl().then(url => (document.getElementById('bee-api-url-placeholder').innerHTML = url))
}

function fetchGlobalPostageBatch() {
const placeholderElement = document.getElementById('global-postage-batch-placeholder')
placeholderElement.setAttribute('complete', 'false')
postageBatch.isGlobalPostageBatchEnabled().then(enabled => {
placeholderElement.innerHTML = enabled
placeholderElement.setAttribute('complete', 'true')
})
}

function checkBeeApiAvailable() {
web2Helper.isBeeApiAvailable().then(available => {
const placeholderElement = document.getElementById('bee-api-available-placeholder')
Expand Down
2 changes: 2 additions & 0 deletions types/index.d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type puppeteer from 'puppeteer'
import type { LocalStorage } from '../src/contentscript/swarm-library/local-storage'
import type { PostageBatch } from '../src/contentscript/swarm-library/postage-batch'
import type { Web2HelperContent } from '../src/contentscript/swarm-library/web2-helper.content'
export {} //indicate it is a module type declaration

Expand All @@ -15,6 +16,7 @@ declare global {
localStorage: LocalStorage
sessionId: string
bzzLink: typeof import('../src/contentscript/swarm-library/bzz-link')
postageBatch: PostageBatch
}
}
}

0 comments on commit b56536f

Please sign in to comment.