Skip to content

FCM Pre Modularization #3234

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 18 commits into from
Aug 11, 2020
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/strange-crabs-tell.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'firebase': minor
'@firebase/messaging': minor,
---

Add `getToken(options:{serviceWorkerRegistration, vapidKey})`,`onBackgroundMessage`.
Deprecate `setBackgroundHandler`, `onTokenRefresh`, `useVapidKey`, `useServiceWorker`, `getToken`.
51 changes: 51 additions & 0 deletions integration/messaging/test/static/helpers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/**
* @license
* Copyright 2020 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
*
* http://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.
*/

async function addPayloadToDb(payload) {
const dbOpenReq = indexedDB.open(TEST_DB);

dbOpenReq.onupgradeneeded = () => {
const db = dbOpenReq.result;

// store creation is a synchronized call
console.log('creating object store...');
db.createObjectStore(BACKGROUND_MESSAGES_OBJECT_STORE, {
keyPath: BACKGROUND_MESSAGES_OBJECT_STORE_PRIMARY_KEY
});
};

dbOpenReq.onsuccess = () => {
const db = dbOpenReq.result;

addPayloadToDbInternal(db, {
...payload,
// ndx is required as the primary key of the store. It doesn't have any other testing purpose
ndx: BACKGROUND_MESSAGES_OBJECT_STORE_DEFAULT_NDX
});
};
}

async function addPayloadToDbInternal(db, payload) {
// onsuccess might race with onupgradeneeded. Consequently causing "object stores was not found" error. Therefore, wait briefly for db.createObjectStore to complete
const delay = ms => new Promise(res => setTimeout(res, ms));
await delay(/* milliseconds= */ 30000);

tx = db.transaction(BACKGROUND_MESSAGES_OBJECT_STORE, 'readwrite');

console.log('adding message payload to db: ' + JSON.stringify(payload));
addReq = tx.objectStore(BACKGROUND_MESSAGES_OBJECT_STORE).add(payload);
}
38 changes: 2 additions & 36 deletions integration/messaging/test/static/sw-base.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
*/

importScripts('../constants.js');
importScripts('../helpers.js');

// HEAD targets served through express
importScripts('/firebase-app.js');
Expand All @@ -27,45 +28,10 @@ const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(payload => {
console.log(
TAG +
'a background message is received: ' +
'a background message is received in the background handler hook: ' +
JSON.stringify(payload) +
'. Storing it into idb for tests to read...'
);

addPayloadToDb(payload);
});

async function addPayloadToDb(payload) {
const dbOpenReq = indexedDB.open(TEST_DB);

dbOpenReq.onupgradeneeded = () => {
const db = dbOpenReq.result;

// store creation is a synchronized call
console.log('creating object store...');
db.createObjectStore(BACKGROUND_MESSAGES_OBJECT_STORE, {
keyPath: BACKGROUND_MESSAGES_OBJECT_STORE_PRIMARY_KEY
});
};

dbOpenReq.onsuccess = () => {
const db = dbOpenReq.result;

addPayloadToDbInternal(db, {
...payload,
// ndx is required as the primary key of the store. It doesn't have any other testing purpose
ndx: BACKGROUND_MESSAGES_OBJECT_STORE_DEFAULT_NDX
});
};
}

async function addPayloadToDbInternal(db, payload) {
// onsuccess might race with onupgradeneeded. Consequently causing " object stores was not found" error. Therefore, wait briefly for db.createObjectStore to complete
const delay = ms => new Promise(res => setTimeout(res, ms));
await delay(/* milliseconds= */ 30000);

tx = db.transaction(BACKGROUND_MESSAGES_OBJECT_STORE, 'readwrite');

console.log('adding message payload to db: ' + JSON.stringify(payload));
addReq = tx.objectStore(BACKGROUND_MESSAGES_OBJECT_STORE).add(payload);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<html>
<head>
<title>FCM Demo</title>
<meta name="viewport" content="width=device-width,initial-scale=1" />
</head>
<body>
<h1>Valid <strong>WITH</strong> VAPID Key - Modern SW</h1>

<script src="/firebase-app.js"></script>
<script src="/firebase-messaging.js"></script>
<script src="../app.js"></script>
<script src="../constants.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sinon.js/4.1.3/sinon.min.js"></script>
<script>
navigator.serviceWorker
.register('./sw.js')
.then(reg => {
window.__test = new window.DemoApp(FIREBASE_CONFIG, {
swReg: reg,
vapidKey: PUBLIC_VAPID_KEY
});
})
.catch(error => {
console.log('Error registering FCM SW: ' + error);
});
</script>
</body>
</html>
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,23 @@
* limitations under the License.
*/

import { MessagePayload } from './message-payload';
importScripts('../constants.js');
importScripts('../helpers.js');

export enum MessageType {
PUSH_RECEIVED = 'push-received',
NOTIFICATION_CLICKED = 'notification-clicked'
}
// HEAD targets served through express
importScripts('/firebase-app.js');
importScripts('/firebase-messaging.js');

export interface InternalMessage {
firebaseMessaging: {
type: MessageType;
payload: MessagePayload;
};
}
firebase.initializeApp(FIREBASE_CONFIG);
const messaging = firebase.messaging();

messaging.onBackgroundMessage(payload => {
console.log(
TAG +
'a background message is received in the onBackgroundMessage hook: ' +
JSON.stringify(payload) +
'. Storing it into idb for tests to read...'
);

addPayloadToDb(payload);
});
134 changes: 68 additions & 66 deletions integration/messaging/test/test-send.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ const getReceivedBackgroundMessages = require('./utils/getReceivedBackgroundMess
const openNewTab = require('./utils/openNewTab');
const createPermittedWebDriver = require('./utils/createPermittedWebDriver');

const TEST_DOMAIN = 'valid-vapid-key';
const TEST_DOMAINS = ['valid-vapid-key', 'valid-vapid-key-modern-sw'];
const TEST_PROJECT_SENDER_ID = '750970317741';
const DEFAULT_COLLAPSE_KEY_VALUE = 'do_not_collapse';
const FIELD_FROM = 'from';
Expand Down Expand Up @@ -58,69 +58,71 @@ describe('Starting Integration Test > Sending and Receiving ', function() {
return;
}

describe(`Testing browser: ${assistantBrowser.getPrettyName()} : ${TEST_DOMAIN}`, function() {
before(async function() {
globalWebDriver = createPermittedWebDriver(
/* browser= */ assistantBrowser.getId()
);
});

it('Background app can receive a {} empty message from sw', async function() {
this.timeout(TIMEOUT_BACKGROUND_MESSAGE_TEST_UNIT_MILLISECONDS);

// Clearing the cache and db data by killing the previously instantiated driver. Note that ideally this call is placed inside the after/before hooks. However, Mocha forbids operations longer than 2s in hooks. Hence, this clearing call needs to be inside the test unit.
await seleniumAssistant.killWebDriver(globalWebDriver);

globalWebDriver = createPermittedWebDriver(
/* browser= */ assistantBrowser.getId()
);

prepareBackgroundApp(globalWebDriver);

checkSendResponse(
await sendMessage({
to: await retrieveToken(globalWebDriver)
})
);

await wait(
WAIT_TIME_BEFORE_RETRIEVING_BACKGROUND_MESSAGES_MILLISECONDS
);

checkMessageReceived(
await getReceivedBackgroundMessages(globalWebDriver),
/* expectedNotificationPayload= */ null,
/* expectedDataPayload= */ null
);
});

it('Background app can receive a {"data"} message frow sw', async function() {
this.timeout(TIMEOUT_BACKGROUND_MESSAGE_TEST_UNIT_MILLISECONDS);

await seleniumAssistant.killWebDriver(globalWebDriver);

globalWebDriver = createPermittedWebDriver(
/* browser= */ assistantBrowser.getId()
);

prepareBackgroundApp(globalWebDriver);

checkSendResponse(
await sendMessage({
to: await retrieveToken(globalWebDriver),
data: getTestDataPayload()
})
);

await wait(
WAIT_TIME_BEFORE_RETRIEVING_BACKGROUND_MESSAGES_MILLISECONDS
);

checkMessageReceived(
await getReceivedBackgroundMessages(globalWebDriver),
/* expectedNotificationPayload= */ null,
/* expectedDataPayload= */ getTestDataPayload()
);
TEST_DOMAINS.forEach(domain => {
describe(`Testing browser: ${assistantBrowser.getPrettyName()} : ${domain}`, function() {
before(async function() {
globalWebDriver = createPermittedWebDriver(
/* browser= */ assistantBrowser.getId()
);
});

it('Background app can receive a {} empty message from sw', async function() {
this.timeout(TIMEOUT_BACKGROUND_MESSAGE_TEST_UNIT_MILLISECONDS);

// Clearing the cache and db data by killing the previously instantiated driver. Note that ideally this call is placed inside the after/before hooks. However, Mocha forbids operations longer than 2s in hooks. Hence, this clearing call needs to be inside the test unit.
await seleniumAssistant.killWebDriver(globalWebDriver);

globalWebDriver = createPermittedWebDriver(
/* browser= */ assistantBrowser.getId()
);

prepareBackgroundApp(globalWebDriver, domain);

checkSendResponse(
await sendMessage({
to: await retrieveToken(globalWebDriver)
})
);

await wait(
WAIT_TIME_BEFORE_RETRIEVING_BACKGROUND_MESSAGES_MILLISECONDS
);

checkMessageReceived(
await getReceivedBackgroundMessages(globalWebDriver),
/* expectedNotificationPayload= */ null,
/* expectedDataPayload= */ null
);
});

it('Background app can receive a {"data"} message frow sw', async function() {
this.timeout(TIMEOUT_BACKGROUND_MESSAGE_TEST_UNIT_MILLISECONDS);

await seleniumAssistant.killWebDriver(globalWebDriver);

globalWebDriver = createPermittedWebDriver(
/* browser= */ assistantBrowser.getId()
);

prepareBackgroundApp(globalWebDriver, domain);

checkSendResponse(
await sendMessage({
to: await retrieveToken(globalWebDriver),
data: getTestDataPayload()
})
);

await wait(
WAIT_TIME_BEFORE_RETRIEVING_BACKGROUND_MESSAGES_MILLISECONDS
);

checkMessageReceived(
await getReceivedBackgroundMessages(globalWebDriver),
/* expectedNotificationPayload= */ null,
/* expectedDataPayload= */ getTestDataPayload()
);
});
});
});
});
Expand Down Expand Up @@ -168,8 +170,8 @@ function getTestDataPayload() {
return { hello: 'world' };
}

async function prepareBackgroundApp(globalWebDriver) {
await globalWebDriver.get(`${testServer.serverAddress}/${TEST_DOMAIN}/`);
async function prepareBackgroundApp(globalWebDriver, domain) {
await globalWebDriver.get(`${testServer.serverAddress}/${domain}/`);

// TODO: remove the try/catch block once the underlying bug has been resolved.
// Shift window focus away from app window so that background messages can be received/processed
Expand Down
Loading