Skip to content

Migrate messaging to component framework #2323

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 6 commits into from
Nov 6, 2019
Merged
Show file tree
Hide file tree
Changes from 5 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
32 changes: 23 additions & 9 deletions packages/messaging/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,41 +16,55 @@
*/

import firebase from '@firebase/app';
import '@firebase/installations';
import {
_FirebaseNamespace,
FirebaseServiceFactory
FirebaseService
} from '@firebase/app-types/private';
import { FirebaseMessaging } from '@firebase/messaging-types';

import { SwController } from './src/controllers/sw-controller';
import { WindowController } from './src/controllers/window-controller';
import { ErrorCode, errorFactory } from './src/models/errors';
import {
Component,
ComponentType,
ComponentContainer
} from '@firebase/component';

export function registerMessaging(instance: _FirebaseNamespace): void {
const messagingName = 'messaging';

const factoryMethod: FirebaseServiceFactory = app => {
const factoryMethod = (container: ComponentContainer): FirebaseService => {
/* Dependencies */
const app = container.getProvider('app').getImmediate();
const installations = container.getProvider('installations').getImmediate();
const analyticsProvider = container.getProvider('analytics-internal');

const firebaseServices = { app, installations, analyticsProvider };

if (!isSupported()) {
throw errorFactory.create(ErrorCode.UNSUPPORTED_BROWSER);
}

if (self && 'ServiceWorkerGlobalScope' in self) {
// Running in ServiceWorker context
return new SwController(app);
return new SwController(firebaseServices);
} else {
// Assume we are in the window context.
return new WindowController(app);
return new WindowController(firebaseServices);
}
};

const namespaceExports = {
isSupported
};

instance.INTERNAL.registerService(
messagingName,
factoryMethod,
namespaceExports
instance.INTERNAL.registerComponent(
new Component(
messagingName,
factoryMethod,
ComponentType.PUBLIC
).setServiceProps(namespaceExports)
);
}

Expand Down
1 change: 1 addition & 0 deletions packages/messaging/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"@firebase/installations": "0.3.2",
"@firebase/messaging-types": "0.3.4",
"@firebase/util": "0.2.31",
"@firebase/component": "0.1.0",
"tslib": "1.10.0"
},
"devDependencies": {
Expand Down
16 changes: 10 additions & 6 deletions packages/messaging/src/controllers/base-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import { ErrorCode, errorFactory } from '../models/errors';
import { SubscriptionManager } from '../models/subscription-manager';
import { TokenDetailsModel } from '../models/token-details-model';
import { VapidDetailsModel } from '../models/vapid-details-model';
import { FirebaseInternalServices } from '../interfaces/external-services';

export type BgMessageHandler = (
payload: MessagePayload
Expand All @@ -43,11 +44,14 @@ export const TOKEN_EXPIRATION_MILLIS = 7 * 24 * 60 * 60 * 1000; // 7 days

export abstract class BaseController implements FirebaseMessaging {
INTERNAL: FirebaseServiceInternals;
readonly app!: FirebaseApp;
private readonly tokenDetailsModel: TokenDetailsModel;
private readonly vapidDetailsModel = new VapidDetailsModel();
private readonly subscriptionManager = new SubscriptionManager();

constructor(readonly app: FirebaseApp) {
constructor(protected readonly services: FirebaseInternalServices) {
const { app } = services;
this.app = app;
if (
!app.options.messagingSenderId ||
typeof app.options.messagingSenderId !== 'string'
Expand All @@ -59,7 +63,7 @@ export abstract class BaseController implements FirebaseMessaging {
delete: () => this.delete()
};

this.tokenDetailsModel = new TokenDetailsModel(app);
this.tokenDetailsModel = new TokenDetailsModel(services);
}

async getToken(): Promise<string | null> {
Expand Down Expand Up @@ -147,15 +151,15 @@ export abstract class BaseController implements FirebaseMessaging {
try {
const updatedToken = await this.subscriptionManager.updateToken(
tokenDetails,
this.app,
this.services,
pushSubscription,
publicVapidKey
);

const allDetails: TokenDetails = {
swScope: swReg.scope,
vapidKey: publicVapidKey,
fcmSenderId: this.app.options.messagingSenderId!,
fcmSenderId: this.services.app.options.messagingSenderId!,
fcmToken: updatedToken,
createTime: Date.now(),
endpoint: pushSubscription.endpoint,
Expand All @@ -181,7 +185,7 @@ export abstract class BaseController implements FirebaseMessaging {
publicVapidKey: Uint8Array
): Promise<string> {
const newToken = await this.subscriptionManager.getToken(
this.app,
this.services,
pushSubscription,
publicVapidKey
);
Expand Down Expand Up @@ -228,7 +232,7 @@ export abstract class BaseController implements FirebaseMessaging {
*/
private async deleteTokenFromDB(token: string): Promise<void> {
const tokenDetails = await this.tokenDetailsModel.deleteToken(token);
await this.subscriptionManager.deleteToken(this.app, tokenDetails);
await this.subscriptionManager.deleteToken(this.services, tokenDetails);
}

// Visible for testing
Expand Down
8 changes: 3 additions & 5 deletions packages/messaging/src/controllers/sw-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,6 @@
*/

import './sw-types';

import { FirebaseApp } from '@firebase/app-types';

import {
MessagePayload,
NotificationDetails
Expand All @@ -30,6 +27,7 @@ import {
} from '../models/fcm-details';
import { InternalMessage, MessageType } from '../models/worker-page-message';
import { BaseController, BgMessageHandler } from './base-controller';
import { FirebaseInternalServices } from '../interfaces/external-services';

// Let TS know that this is a service worker
declare const self: ServiceWorkerGlobalScope;
Expand All @@ -39,8 +37,8 @@ const FCM_MSG = 'FCM_MSG';
export class SwController extends BaseController {
private bgMessageHandler: BgMessageHandler | null = null;

constructor(app: FirebaseApp) {
super(app);
constructor(services: FirebaseInternalServices) {
super(services);

self.addEventListener('push', e => {
this.onPush(e);
Expand Down
31 changes: 19 additions & 12 deletions packages/messaging/src/controllers/window-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
* limitations under the License.
*/

import { FirebaseApp } from '@firebase/app-types';
import { _FirebaseApp } from '@firebase/app-types/private';
import {
CompleteFn,
Expand All @@ -39,6 +38,7 @@ import {
} from '../models/fcm-details';
import { InternalMessage, MessageType } from '../models/worker-page-message';
import { BaseController } from './base-controller';
import { FirebaseInternalServices } from '../interfaces/external-services';

export class WindowController extends BaseController {
private registrationToUse: ServiceWorkerRegistration | null = null;
Expand All @@ -63,8 +63,8 @@ export class WindowController extends BaseController {
/**
* A service that provides a MessagingService instance.
*/
constructor(app: FirebaseApp) {
super(app);
constructor(services: FirebaseInternalServices) {
super(services);

this.setupSWMessageListener_();
}
Expand Down Expand Up @@ -308,16 +308,23 @@ export class WindowController extends BaseController {
// This message has a campaign id, meaning it was sent using the FN Console.
// Analytics is enabled on this message, so we should log it.
const eventType = getEventType(firebaseMessagingType);
(this.app as _FirebaseApp).INTERNAL.analytics.logEvent(
eventType,
/* eslint-disable camelcase */
{
message_name: data[FN_CAMPAIGN_NAME],
message_id: data[FN_CAMPAIGN_ID],
message_time: data[FN_CAMPAIGN_TIME],
message_device_time: Math.floor(Date.now() / 1000)
this.services.analyticsProvider.get().then(
analytics => {
analytics.logEvent(
eventType,
/* eslint-disable camelcase */
{
message_name: data[FN_CAMPAIGN_NAME],
message_id: data[FN_CAMPAIGN_ID],
message_time: data[FN_CAMPAIGN_TIME],
message_device_time: Math.floor(Date.now() / 1000)
}
/* eslint-enable camelcase */
);
},
() => {
/* it will never reject */
}
/* eslint-enable camelcase */
);
}
},
Expand Down
27 changes: 27 additions & 0 deletions packages/messaging/src/interfaces/external-services.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/**
* @license
* Copyright 2019 Google Inc.
*
* 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.
*/

import { FirebaseApp } from '@firebase/app-types';
import { FirebaseInstallations } from '@firebase/installations-types';
import { FirebaseAnalyticsInternal } from '@firebase/analytics-interop-types';
import { Provider } from '@firebase/component';

export interface FirebaseInternalServices {
app: FirebaseApp;
installations: FirebaseInstallations;
analyticsProvider: Provider<FirebaseAnalyticsInternal>;
}
10 changes: 5 additions & 5 deletions packages/messaging/src/models/clean-v1-undefined.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,12 @@
*/

import { SubscriptionManager } from './subscription-manager';
import { FirebaseApp } from '@firebase/app-types';
import { FirebaseInternalServices } from '../interfaces/external-services';

const OLD_DB_NAME = 'undefined';
const OLD_OBJECT_STORE_NAME = 'fcm_token_object_Store';

function handleDb(db: IDBDatabase, app: FirebaseApp): void {
function handleDb(db: IDBDatabase, services: FirebaseInternalServices): void {
if (!db.objectStoreNames.contains(OLD_OBJECT_STORE_NAME)) {
// We found a database with the name 'undefined', but our expected object
// store isn't defined.
Expand All @@ -59,7 +59,7 @@ function handleDb(db: IDBDatabase, app: FirebaseApp): void {
const tokenDetails = cursor.value;

// eslint-disable-next-line @typescript-eslint/no-floating-promises
subscriptionManager.deleteToken(app, tokenDetails);
subscriptionManager.deleteToken(services, tokenDetails);

cursor.continue();
} else {
Expand All @@ -69,13 +69,13 @@ function handleDb(db: IDBDatabase, app: FirebaseApp): void {
};
}

export function cleanV1(app: FirebaseApp): void {
export function cleanV1(services: FirebaseInternalServices): void {
const request: IDBOpenDBRequest = indexedDB.open(OLD_DB_NAME);
request.onerror = _event => {
// NOOP - Nothing we can do.
};
request.onsuccess = _event => {
const db = request.result;
handleDb(db, app);
handleDb(db, services);
};
}
26 changes: 14 additions & 12 deletions packages/messaging/src/models/subscription-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ import { isArrayBufferEqual } from '../helpers/is-array-buffer-equal';
import { ErrorCode, errorFactory } from './errors';
import { DEFAULT_PUBLIC_VAPID_KEY, ENDPOINT } from './fcm-details';
import { FirebaseApp } from '@firebase/app-types';
import '@firebase/installations';
import { TokenDetails } from '../interfaces/token-details';
import { FirebaseInternalServices } from '../interfaces/external-services';

interface ApiResponse {
token?: string;
Expand All @@ -39,11 +39,11 @@ interface TokenRequestBody {

export class SubscriptionManager {
async getToken(
app: FirebaseApp,
services: FirebaseInternalServices,
subscription: PushSubscription,
vapidKey: Uint8Array
): Promise<string> {
const headers = await getHeaders(app);
const headers = await getHeaders(services);
const body = getBody(subscription, vapidKey);

const subscribeOptions = {
Expand All @@ -54,7 +54,7 @@ export class SubscriptionManager {

let responseData: ApiResponse;
try {
const response = await fetch(getEndpoint(app), subscribeOptions);
const response = await fetch(getEndpoint(services.app), subscribeOptions);
responseData = await response.json();
} catch (err) {
throw errorFactory.create(ErrorCode.TOKEN_SUBSCRIBE_FAILED, {
Expand All @@ -81,11 +81,11 @@ export class SubscriptionManager {
*/
async updateToken(
tokenDetails: TokenDetails,
app: FirebaseApp,
services: FirebaseInternalServices,
subscription: PushSubscription,
vapidKey: Uint8Array
): Promise<string> {
const headers = await getHeaders(app);
const headers = await getHeaders(services);
const body = getBody(subscription, vapidKey);

const updateOptions = {
Expand All @@ -97,7 +97,7 @@ export class SubscriptionManager {
let responseData: ApiResponse;
try {
const response = await fetch(
`${getEndpoint(app)}/${tokenDetails.fcmToken}`,
`${getEndpoint(services.app)}/${tokenDetails.fcmToken}`,
updateOptions
);
responseData = await response.json();
Expand All @@ -122,11 +122,11 @@ export class SubscriptionManager {
}

async deleteToken(
app: FirebaseApp,
services: FirebaseInternalServices,
tokenDetails: TokenDetails
): Promise<void> {
// TODO: Add FIS header
const headers = await getHeaders(app);
const headers = await getHeaders(services);

const unsubscribeOptions = {
method: 'DELETE',
Expand All @@ -135,7 +135,7 @@ export class SubscriptionManager {

try {
const response = await fetch(
`${getEndpoint(app)}/${tokenDetails.fcmToken}`,
`${getEndpoint(services.app)}/${tokenDetails.fcmToken}`,
unsubscribeOptions
);
const responseData: ApiResponse = await response.json();
Expand All @@ -157,8 +157,10 @@ function getEndpoint(app: FirebaseApp): string {
return `${ENDPOINT}/projects/${app.options.projectId!}/registrations`;
}

async function getHeaders(app: FirebaseApp): Promise<Headers> {
const installations = app.installations();
async function getHeaders({
app,
installations
}: FirebaseInternalServices): Promise<Headers> {
const authToken = await installations.getToken();

return new Headers({
Expand Down
Loading