Fork me on GitHub

WhatsApp Clone with Meteor and Ionic 2 CLI

Ionic 3 Version (Last Update: 2017-06-15)

Privacy & Subscriptions

Note: If you skipped ahead to this section, click here to download a zip of the tutorial at this point.

In this step we gonna take care of the app's security and encapsulation, since we don't want the users to do whatever they want, and we don't want them to be able to see content which is irrelevant for them.

We gonna start by removing a Meteor package named insecure. This package provides the client with the ability to run collection mutation methods. This is a behavior we are not interested in since removing data and creating data should be done in the server and only after certain validations. Meteor includes this package by default only for development purposes and it should be removed once our app is ready for production. As said, we will remove this package by typing the following command:

api$ meteor remove insecure

Secure Mutations

Since we enabled restrictions to run certain operations on data-collections directly from the client, we will need to define a method on the server which will handle each of these. By calling these methods, we will be able to manipulate the data the way we want, but not directly. The first method we're going to take care of would be the removeChat method, which will handle, obviously, chat removals by given ID:

9.2 Add removeChat method on server side api/server/methods.ts
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
 
    Chats.insert(chat);
  },
  removeChat(chatId: string): void {
    if (!this.userId) {
      throw new Meteor.Error('unauthorized',
        'User must be logged-in to remove chat');
    }
 
    check(chatId, nonEmptyString);
 
    const chatExists = !!Chats.collection.find(chatId).count();
 
    if (!chatExists) {
      throw new Meteor.Error('chat-not-exists',
        'Chat doesn\'t exist');
    }
 
    Chats.remove(chatId);
  },
  updateProfile(profile: Profile): void {
    if (!this.userId) throw new Meteor.Error('unauthorized',
      'User must be logged-in to create a new chat');

We will carefully replace the removal method invocation in the ChatsPage with the method we've just defined:

9.3 Use removeChat on client side src/pages/chats/chats.ts
1
2
3
4
5
6
7
 
18
19
20
21
22
23
24
25
 
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
import { Component, OnInit } from '@angular/core';
import { Chats, Messages, Users } from 'api/collections';
import { Chat, Message } from 'api/models';
import { NavController, PopoverController, ModalController, AlertController } from 'ionic-angular';
import { MeteorObservable } from 'meteor-rxjs';
import { Observable, Subscriber } from 'rxjs';
import { MessagesPage } from '../messages/messages';
...some lines skipped...
  constructor(
    private navCtrl: NavController,
    private popoverCtrl: PopoverController,
    private modalCtrl: ModalController,
    private alertCtrl: AlertController) {
    this.senderId = Meteor.userId();
  }
 
...some lines skipped...
  }
 
  removeChat(chat: Chat): void {
    MeteorObservable.call('removeChat', chat._id).subscribe({
      error: (e: Error) => {
        if (e) {
          this.handleError(e);
        }
      }
    });
  }
 
  handleError(e: Error): void {
    console.error(e);
 
    const alert = this.alertCtrl.create({
      buttons: ['OK'],
      message: e.message,
      title: 'Oops!'
    });
 
    alert.present();
  }
 
  showOptions(): void {

In the MessagesPage we have options icon presented as three periods at the right side of the navigation bar. We will now implement this option menu which should pop-over once clicked. We will start by implementing its corresponding component called MessagesOptionsComponent, along with its view-template, style-sheet, and necessary importations:

9.4 Add message options component src/pages/messages/messages-options.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import { Component } from '@angular/core';
import { AlertController, NavController, NavParams, ViewController } from 'ionic-angular';
import { MeteorObservable } from 'meteor-rxjs';
import { ChatsPage } from '../chats/chats';
 
@Component({
  selector: 'messages-options',
  templateUrl: 'messages-options.html'
})
export class MessagesOptionsComponent {
  constructor(
    public alertCtrl: AlertController,
    public navCtrl: NavController,
    public params: NavParams,
    public viewCtrl: ViewController
  ) {}
 
  remove(): void {
    const alert = this.alertCtrl.create({
      title: 'Remove',
      message: 'Are you sure you would like to proceed?',
      buttons: [
        {
          text: 'Cancel',
          role: 'cancel'
        },
        {
          text: 'Yes',
          handler: () => {
            this.handleRemove(alert);
            return false;
          }
        }
      ]
    });
 
    this.viewCtrl.dismiss().then(() => {
      alert.present();
    });
  }
 
  private handleRemove(alert): void {
    MeteorObservable.call('removeChat', this.params.get('chat')._id).subscribe({
      next: () => {
        alert.dismiss().then(() => {
          this.navCtrl.setRoot(ChatsPage, {}, {
            animate: true
          });
        });
      },
      error: (e: Error) => {
        alert.dismiss().then(() => {
          if (e) {
            return this.handleError(e);
          }
 
          this.navCtrl.setRoot(ChatsPage, {}, {
            animate: true
          });
        });
      }
    });
  }
 
  private handleError(e: Error): void {
    console.error(e);
 
    const alert = this.alertCtrl.create({
      title: 'Oops!',
      message: e.message,
      buttons: ['OK']
    });
 
    alert.present();
  }
}
9.5 Add messages options template src/pages/messages/messages-options.html
1
2
3
4
5
6
7
8
<ion-content class="chats-options-page-content">
  <ion-list class="options">
    <button ion-item class="option option-remove" (click)="remove()">
      <ion-icon name="trash" class="option-icon"></ion-icon>
      <div class="option-name">Remove</div>
    </button>
  </ion-list>
</ion-content>
9.6 Add message options styles src/pages/messages/messages-options.scss
1
2
3
4
5
6
7
8
9
10
11
12
13
.chats-options-page-content {
  .options {
    margin: 0;
  }
 
  .option-name {
    float: left;
  }
 
  .option-icon {
    float: right;
  }
}
9.7 Import messages options component src/app/app.module.ts
9
10
11
12
13
14
15
 
24
25
26
27
28
29
30
31
 
41
42
43
44
45
46
47
48
import { ChatsOptionsComponent } from '../pages/chats/chats-options';
import { LoginPage } from '../pages/login/login';
import { MessagesPage } from '../pages/messages/messages';
import { MessagesOptionsComponent } from '../pages/messages/messages-options';
import { ProfilePage } from '../pages/profile/profile';
import { VerificationPage } from '../pages/verification/verification';
import { PhoneService } from '../services/phone';
...some lines skipped...
    VerificationPage,
    ProfilePage,
    ChatsOptionsComponent,
    NewChatComponent,
    MessagesOptionsComponent
  ],
  imports: [
    BrowserModule,
...some lines skipped...
    VerificationPage,
    ProfilePage,
    ChatsOptionsComponent,
    NewChatComponent,
    MessagesOptionsComponent
  ],
  providers: [
    StatusBar,

Now that the component is ready, we will implement the handler in the MessagesPage which will actually show it, using the PopoverController:

9.8 Implemente showOptions method src/pages/messages/messages.ts
1
2
3
4
5
6
7
8
9
10
11
 
23
24
25
26
27
28
29
30
 
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import { Component, OnInit, OnDestroy, ElementRef } from '@angular/core';
import { NavParams, PopoverController } from 'ionic-angular';
import { Chat, Message, MessageType } from 'api/models';
import { Messages } from 'api/collections';
import { MeteorObservable } from 'meteor-rxjs';
import * as moment from 'moment';
import * as _ from 'lodash';
import { MessagesOptionsComponent } from './messages-options';
 
@Component({
  selector: 'messages-page',
...some lines skipped...
 
  constructor(
    navParams: NavParams,
    private el: ElementRef,
    private popoverCtrl: PopoverController
  ) {
    this.selectedChat = <Chat>navParams.get('chat');
    this.title = this.selectedChat.title;
...some lines skipped...
    this.messagesDayGroups = this.findMessagesDayGroups();
  }
 
  showOptions(): void {
    const popover = this.popoverCtrl.create(MessagesOptionsComponent, {
      chat: this.selectedChat
    }, {
      cssClass: 'options-popover messages-options-popover'
    });
 
    popover.present();
  }
 
  findMessagesDayGroups() {
    return Messages.find({
      chatId: this.selectedChat._id

And we will bind the handler for the view so any time we press on the options button the event will be trigger the handler:

9.9 Bind showOptions to messages options button src/pages/messages/messages.html
8
9
10
11
12
13
14
 
    <ion-buttons end>
      <button ion-button icon-only class="attach-button"><ion-icon name="attach"></ion-icon></button>
      <button ion-button icon-only class="options-button" (click)="showOptions()"><ion-icon name="more"></ion-icon></button>
    </ion-buttons>
  </ion-navbar>
</ion-header>

Right now all the chats are published to all the clients which is not very good for privacy, and it's inefficient since the entire data-base is being fetched automatically rather than fetching only the data which is necessary for the current view. This behavior occurs because of a Meteor package, which is installed by default for development purposes, called autopublish. To get rid of the auto-publishing behavior we will need to get rid of the autopublish package as well:

api$ meteor remove autopublish

This requires us to explicitly define our publications. We will start with the users publication which will be used in the NewChatComponent to fetch all the users who we can potentially chat with:

9.11 Add users publication api/server/publications.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { User } from './models';
import { Users } from './collections/users';
 
Meteor.publish('users', function(): Mongo.Cursor<User> {
  if (!this.userId) {
    return;
  }
 
  return Users.collection.find({}, {
    fields: {
      profile: 1
    }
  });
});

The second publication we're going to implement would be the messages publication which will be used in the MessagesPage:

9.12 Publish messages api/server/publications.ts
1
2
3
4
5
6
 
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import { User, Message } from './models';
import { Users } from './collections/users';
import { Messages } from './collections/messages';
 
Meteor.publish('users', function(): Mongo.Cursor<User> {
  if (!this.userId) {
...some lines skipped...
    }
  });
});
 
Meteor.publish('messages', function(chatId: string): Mongo.Cursor<Message> {
  if (!this.userId || !chatId) {
    return;
  }
 
  return Messages.collection.find({
    chatId
  }, {
    sort: { createdAt: -1 }
  });
});

As you see, all our publications so far are only focused on fetching data from a single collection. We will now add the publish-composite package which will help us implement joined collection publications:

api$ meteor add reywood:publish-composite

We will install the package's declarations as well so the compiler can recognize the extensions made in Meteor's API:

$ npm install --save-dev @types/meteor-publish-composite

And we will import the declarations by adding the following field in the tsconfig file:

9.15 Import @types/meteor-publish-composite api/tsconfig.json
17
18
19
20
21
22
23
24
    "noImplicitAny": false,
    "types": [
      "@types/meteor",
      "@types/meteor-accounts-phone",
      "@types/meteor-publish-composite"
    ]
  },
  "exclude": [

Now we will implement our first composite-publication, called chats. Why exactly does the chats publication has to count on multiple collections? That's because we're relying on multiple collections when presenting the data in the ChatsPage:

  • ChatsCollection - Used to retrieve the actual information for each chat.
  • MessagesCollection - Used to retrieve the last message for the corresponding chat.
  • UsersCollection - Used to retrieve the receiver's information for the corresponding chat.

To implement this composite publication we will use the Meteor.publishComposite method:

9.16 Implement chats publication api/server/publications.ts
1
2
3
4
5
6
7
 
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import { User, Message, Chat } from './models';
import { Users } from './collections/users';
import { Messages } from './collections/messages';
import { Chats } from './collections/chats';
 
Meteor.publish('users', function(): Mongo.Cursor<User> {
  if (!this.userId) {
...some lines skipped...
    sort: { createdAt: -1 }
  });
});
 
Meteor.publishComposite('chats', function(): PublishCompositeConfig<Chat> {
  if (!this.userId) {
    return;
  }
 
  return {
    find: () => {
      return Chats.collection.find({ memberIds: this.userId });
    },
 
    children: [
      <PublishCompositeConfig1<Chat, Message>> {
        find: (chat) => {
          return Messages.collection.find({ chatId: chat._id }, {
            sort: { createdAt: -1 },
            limit: 1
          });
        }
      },
      <PublishCompositeConfig1<Chat, User>> {
        find: (chat) => {
          return Users.collection.find({
            _id: { $in: chat.memberIds }
          }, {
            fields: { profile: 1 }
          });
        }
      }
    ]
  };
});

The chats publication is made out of several nodes, which are structured according to the list above.

We finished with all the necessary publications for now, all is left to do is using them. The usages of these publications are called subscriptions, so whenever we subscribe to a publication, we will fetch the data exported by it, and then we can run queries of this data in our client, as we desire.

The first subscription we're going to make would be the users subscription in the NewChatComponent, so whenever we open the dialog a subscription should be made:

9.17 Subscribe to users src/pages/chats/new-chat.ts
40
41
42
43
44
45
46
47
48
49
50
51
52
  }
 
  loadUsers(): void {
    // Fetch all users matching search pattern
    const subscription = MeteorObservable.subscribe('users');
    const autorun = MeteorObservable.autorun();
 
    Observable.merge(subscription, autorun).subscribe(() => {
      this.users = this.findUsers();
    });
  }
 
  findUsers(): Observable<User[]> {

The second subscription we're going to define would be the chats subscription in the ChatsPage, this way we will have the necessary data to work with when presenting the users we're chatting with:

9.18 Subscribe to chats src/pages/chats/chats.ts
29
30
31
32
33
34
35
36
37
38
39
  }
 
  ngOnInit() {
    MeteorObservable.subscribe('chats').subscribe(() => {
      MeteorObservable.autorun().subscribe(() => {
        this.chats = this.findChats();
      });
    });
  }
 
  findChats(): Observable<Chat[]> {

The messages publication is responsible for bringing all the relevant messages for a certain chat. Unlike the other two publications, this publication is actually parameterized and it requires us to pass a chat id during subscription. Let's subscribe to the messages publication in the MessagesPage, and pass the current active chat ID provided to us by the navigation parameters:

9.19 Subscribe to messages src/pages/messages/messages.ts
6
7
8
9
10
11
12
 
21
22
23
24
25
26
27
28
 
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
 
139
140
141
142
143
144
145
146
147
148
149
import * as moment from 'moment';
import * as _ from 'lodash';
import { MessagesOptionsComponent } from './messages-options';
import { Subscription } from 'rxjs';
 
@Component({
  selector: 'messages-page',
...some lines skipped...
  autoScroller: MutationObserver;
  scrollOffset = 0;
  senderId: string;
  loadingMessages: boolean;
  messagesComputation: Subscription;
 
  constructor(
    navParams: NavParams,
...some lines skipped...
    this.autoScroller.disconnect();
  }
 
  // Subscribes to the relevant set of messages
  subscribeMessages(): void {
    // A flag which indicates if there's a subscription in process
    this.loadingMessages = true;
    // A custom offset to be used to re-adjust the scrolling position once
    // new dataset is fetched
    this.scrollOffset = this.scroller.scrollHeight;
 
    MeteorObservable.subscribe('messages',
      this.selectedChat._id
    ).subscribe(() => {
      // Keep tracking changes in the dataset and re-render the view
      if (!this.messagesComputation) {
        this.messagesComputation = this.autorunMessages();
      }
 
      // Allow incoming subscription requests
      this.loadingMessages = false;
    });
  }
 
  // Detects changes in the messages dataset and re-renders the view
  autorunMessages(): Subscription {
    return MeteorObservable.autorun().subscribe(() => {
      this.messagesDayGroups = this.findMessagesDayGroups();
    });
  }
 
  showOptions(): void {
...some lines skipped...
  }
 
  scrollDown(): void {
    // Don't scroll down if messages subscription is being loaded
    if (this.loadingMessages) {
      return;
    }
 
    // Scroll down and apply specified offset
    this.scroller.scrollTop = this.scroller.scrollHeight - this.scrollOffset;
    // Zero offset for next invocation