summaryrefslogtreecommitdiffstats
path: root/dom/presentation/tests/mochitest/PresentationSessionChromeScript1UA.js
blob: 82d7362b295839be50161a71deb408a584357875 (plain)
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */

'use strict';

const { classes: Cc, interfaces: Ci, manager: Cm, utils: Cu, results: Cr } = Components;

Cu.import('resource://gre/modules/XPCOMUtils.jsm');
Cu.import('resource://gre/modules/Services.jsm');

const uuidGenerator = Cc["@mozilla.org/uuid-generator;1"]
                      .getService(Ci.nsIUUIDGenerator);

function debug(str) {
  // dump('DEBUG -*- PresentationSessionChromeScript1UA -*-: ' + str + '\n');
}

const originalFactoryData = [];
var sessionId; // Store the uuid generated by PresentationRequest.
var triggerControlChannelError = false; // For simulating error during control channel establishment.

// control channel of sender
const mockControlChannelOfSender = {
  QueryInterface: XPCOMUtils.generateQI([Ci.nsIPresentationControlChannel]),
  set listener(listener) {
    // PresentationControllingInfo::SetControlChannel
    if (listener) {
      debug('set listener for mockControlChannelOfSender without null');
    } else {
      debug('set listener for mockControlChannelOfSender with null');
    }
    this._listener = listener;
  },
  get listener() {
    return this._listener;
  },
  notifyConnected: function() {
    // send offer after notifyConnected immediately
    this._listener
        .QueryInterface(Ci.nsIPresentationControlChannelListener)
        .notifyConnected();
  },
  notifyReconnected: function() {
    // send offer after notifyOpened immediately
    this._listener
        .QueryInterface(Ci.nsIPresentationControlChannelListener)
        .notifyReconnected();
  },
  sendOffer: function(offer) {
    Services.tm.mainThread.dispatch(() => {
      mockControlChannelOfReceiver.onOffer(offer);
    }, Ci.nsIThread.DISPATCH_NORMAL);
  },
  onAnswer: function(answer) {
    this._listener
        .QueryInterface(Ci.nsIPresentationControlChannelListener)
        .onAnswer(answer);
  },
  launch: function(presentationId, url) {
    sessionId = presentationId;
    sendAsyncMessage('sender-launch', url);
  },
  disconnect: function(reason) {
    if (!this._listener) {
      return;
    }
    this._listener
        .QueryInterface(Ci.nsIPresentationControlChannelListener)
        .notifyDisconnected(reason);
    mockControlChannelOfReceiver.disconnect();
  },
  terminate: function(presentationId) {
    sendAsyncMessage('sender-terminate');
  },
  reconnect: function(presentationId, url) {
    sendAsyncMessage('start-reconnect', url);
  },
  sendIceCandidate: function(candidate) {
    mockControlChannelOfReceiver.notifyIceCandidate(candidate);
  },
  notifyIceCandidate: function(candidate) {
    if (!this._listener) {
      return;
    }

    this._listener
        .QueryInterface(Ci.nsIPresentationControlChannelListener)
        .onIceCandidate(candidate);
  },
};

// control channel of receiver
const mockControlChannelOfReceiver = {
  QueryInterface: XPCOMUtils.generateQI([Ci.nsIPresentationControlChannel]),
  set listener(listener) {
    // PresentationPresentingInfo::SetControlChannel
    if (listener) {
      debug('set listener for mockControlChannelOfReceiver without null');
    } else {
      debug('set listener for mockControlChannelOfReceiver with null');
    }
    this._listener = listener;

    if (this._pendingOpened) {
      this._pendingOpened = false;
      this.notifyConnected();
    }
  },
  get listener() {
    return this._listener;
  },
  notifyConnected: function() {
    // do nothing
    if (!this._listener) {
      this._pendingOpened = true;
      return;
    }
    this._listener
        .QueryInterface(Ci.nsIPresentationControlChannelListener)
        .notifyConnected();
  },
  onOffer: function(offer) {
    this._listener
        .QueryInterface(Ci.nsIPresentationControlChannelListener)
        .onOffer(offer);
  },
  sendAnswer: function(answer) {
    Services.tm.mainThread.dispatch(() => {
      mockControlChannelOfSender.onAnswer(answer);
    }, Ci.nsIThread.DISPATCH_NORMAL);
  },
  disconnect: function(reason) {
    if (!this._listener) {
      return;
    }

    this._listener
        .QueryInterface(Ci.nsIPresentationControlChannelListener)
        .notifyDisconnected(reason);
    sendAsyncMessage('control-channel-receiver-closed', reason);
  },
  terminate: function(presentaionId) {
  },
  sendIceCandidate: function(candidate) {
    mockControlChannelOfReceiver.notifyIceCandidate(candidate);
  },
  notifyIceCandidate: function(candidate) {
    if (!this._listener) {
      return;
    }

    this._listener
        .QueryInterface(Ci.nsIPresentationControlChannelListener)
        .onIceCandidate(candidate);
  },
};

const mockDevice = {
  QueryInterface: XPCOMUtils.generateQI([Ci.nsIPresentationDevice]),
  id:   'id',
  name: 'name',
  type: 'type',
  establishControlChannel: function(url, presentationId) {
    if (triggerControlChannelError) {
      throw Cr.NS_ERROR_FAILURE;
    }
    sendAsyncMessage('control-channel-established');
    return mockControlChannelOfSender;
  },
  disconnect: function() {
    sendAsyncMessage('device-disconnected');
  },
  isRequestedUrlSupported: function(requestedUrl) {
    return true;
  },
};

const mockDevicePrompt = {
  QueryInterface: XPCOMUtils.generateQI([Ci.nsIPresentationDevicePrompt,
                                         Ci.nsIFactory]),
  createInstance: function(aOuter, aIID) {
    if (aOuter) {
      throw Components.results.NS_ERROR_NO_AGGREGATION;
    }
    return this.QueryInterface(aIID);
  },
  set request(request) {
    this._request = request;
  },
  get request() {
    return this._request;
  },
  promptDeviceSelection: function(request) {
    this._request = request;
    sendAsyncMessage('device-prompt');
  },
  simulateSelect: function() {
    this._request.select(mockDevice);
  },
  simulateCancel: function() {
    this._request.cancel();
  }
};

const mockRequestUIGlue = {
  QueryInterface: XPCOMUtils.generateQI([Ci.nsIPresentationRequestUIGlue,
                                         Ci.nsIFactory]),
  set promise(aPromise) {
    this._promise = aPromise
  },
  get promise() {
    return this._promise;
  },
  createInstance: function(aOuter, aIID) {
    if (aOuter) {
      throw Components.results.NS_ERROR_NO_AGGREGATION;
    }
    return this.QueryInterface(aIID);
  },
  sendRequest: function(aUrl, aSessionId) {
    return this.promise;
  },
};

function initMockAndListener() {

  function registerMockFactory(contractId, mockClassId, mockFactory) {
    var originalClassId, originalFactory;

    var registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar);
    if (!registrar.isCIDRegistered(mockClassId)) {
      try {
        originalClassId = registrar.contractIDToCID(contractId);
        originalFactory = Cm.getClassObject(Cc[contractId], Ci.nsIFactory);
      } catch (ex) {
        originalClassId = "";
        originalFactory = null;
      }
      if (originalFactory) {
        registrar.unregisterFactory(originalClassId, originalFactory);
      }
      registrar.registerFactory(mockClassId, "", contractId, mockFactory);
    }

    return { contractId: contractId,
             mockClassId: mockClassId,
             mockFactory: mockFactory,
             originalClassId: originalClassId,
             originalFactory: originalFactory };
  }
  // Register mock factories.
  const uuidGenerator = Cc["@mozilla.org/uuid-generator;1"]
                        .getService(Ci.nsIUUIDGenerator);
  originalFactoryData.push(registerMockFactory("@mozilla.org/presentation-device/prompt;1",
                                               uuidGenerator.generateUUID(),
                                               mockDevicePrompt));
  originalFactoryData.push(registerMockFactory("@mozilla.org/presentation/requestuiglue;1",
                                               uuidGenerator.generateUUID(),
                                               mockRequestUIGlue));

  addMessageListener('trigger-device-add', function() {
    debug('Got message: trigger-device-add');
    var deviceManager = Cc['@mozilla.org/presentation-device/manager;1']
                        .getService(Ci.nsIPresentationDeviceManager);
    deviceManager.QueryInterface(Ci.nsIPresentationDeviceListener)
                 .addDevice(mockDevice);
  });

  addMessageListener('trigger-device-prompt-select', function() {
    debug('Got message: trigger-device-prompt-select');
    mockDevicePrompt.simulateSelect();
  });

  addMessageListener('trigger-on-session-request', function(url) {
    debug('Got message: trigger-on-session-request');
    var deviceManager = Cc['@mozilla.org/presentation-device/manager;1']
                          .getService(Ci.nsIPresentationDeviceManager);
    deviceManager.QueryInterface(Ci.nsIPresentationDeviceListener)
                 .onSessionRequest(mockDevice,
                                   url,
                                   sessionId,
                                   mockControlChannelOfReceiver);
  });

  addMessageListener('trigger-on-terminate-request', function() {
    debug('Got message: trigger-on-terminate-request');
    var deviceManager = Cc['@mozilla.org/presentation-device/manager;1']
                          .getService(Ci.nsIPresentationDeviceManager);
    deviceManager.QueryInterface(Ci.nsIPresentationDeviceListener)
                 .onTerminateRequest(mockDevice,
                                     sessionId,
                                     mockControlChannelOfReceiver,
                                     false);
  });

  addMessageListener('trigger-control-channel-open', function(reason) {
    debug('Got message: trigger-control-channel-open');
    mockControlChannelOfSender.notifyConnected();
    mockControlChannelOfReceiver.notifyConnected();
  });

  addMessageListener('trigger-control-channel-error', function(reason) {
    debug('Got message: trigger-control-channel-open');
    triggerControlChannelError = true;
  });

  addMessageListener('trigger-reconnected-acked', function(url) {
    debug('Got message: trigger-reconnected-acked');
    mockControlChannelOfSender.notifyReconnected();
    var deviceManager = Cc['@mozilla.org/presentation-device/manager;1']
                          .getService(Ci.nsIPresentationDeviceManager);
    deviceManager.QueryInterface(Ci.nsIPresentationDeviceListener)
                 .onReconnectRequest(mockDevice,
                                     url,
                                     sessionId,
                                     mockControlChannelOfReceiver);
  });

  // Used to call sendAsyncMessage in chrome script from receiver.
  addMessageListener('forward-command', function(command_data) {
    let command = JSON.parse(command_data);
    sendAsyncMessage(command.name, command.data);
  });

  addMessageListener('teardown', teardown);

  var obs = Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService);
  obs.addObserver(function setupRequestPromiseHandler(aSubject, aTopic, aData) {
    debug('Got observer: setup-request-promise');
    obs.removeObserver(setupRequestPromiseHandler, aTopic);
    mockRequestUIGlue.promise = aSubject;
    sendAsyncMessage('promise-setup-ready');
  }, 'setup-request-promise', false);
}

function teardown() {

  function registerOriginalFactory(contractId, mockedClassId, mockedFactory, originalClassId, originalFactory) {
    if (originalFactory) {
      var registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar);
      registrar.unregisterFactory(mockedClassId, mockedFactory);
      registrar.registerFactory(originalClassId, "", contractId, originalFactory);
    }
  }

  mockRequestUIGlue.promise               = null;
  mockControlChannelOfSender.listener     = null;
  mockControlChannelOfReceiver.listener   = null;
  mockDevicePrompt.request                = null;

  var deviceManager = Cc['@mozilla.org/presentation-device/manager;1']
                      .getService(Ci.nsIPresentationDeviceManager);
  deviceManager.QueryInterface(Ci.nsIPresentationDeviceListener)
               .removeDevice(mockDevice);
  // Register original factories.
  for (var data of originalFactoryData) {
    registerOriginalFactory(data.contractId, data.mockClassId,
                            data.mockFactory, data.originalClassId,
                            data.originalFactory);
  }
  sendAsyncMessage('teardown-complete');
}

initMockAndListener();