forked from mozilla-b2g/gaia
/
nfc_handover_manager.js
751 lines (689 loc) · 25 KB
/
nfc_handover_manager.js
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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
/* -*- Mode: js; js-indent-level: 2; indent-tabs-mode: nil -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/* Copyright © 2013, Deutsche Telekom, Inc. */
/* globals NDEFUtils, NfcConnectSystemDialog, LazyLoader,
NDEF, NfcUtils, NotificationHelper, BaseModule, Service */
'use strict';
/**
* NfcHandoverManager handles handovers from other Bluetooth devices according
* to the specification of the NFC Forum
* (Document: NFCForum-TS-ConnectionHandover_1_2.doc).
* @class NfcHandoverManager
*/
(function() {
var NfcHandoverManager = function() {};
NfcHandoverManager.STATES = [
'isHandoverInProgress'
];
NfcHandoverManager.SETTINGS = [
'nfc.debugging.enabled'
];
NfcHandoverManager.EVENTS = [
'bluetooth-available',
'bluetooth-unavailable',
'bluetooth-enabled',
'bluetooth-disabled',
'nfc-transfer-started',
'nfc-transfer-completed'
];
BaseModule.create(NfcHandoverManager, {
name: 'NfcHandoverManager',
/**
* Flag which turns on debuging messages
* @type {boolean}
* @memberof NfcHandoverManager.prototype
*/
DEBUG: true,
/**
* Default bluetooth adapter
* @type {Object}
* @memberof NfcHandoverManager.prototype
*/
_adapter: null,
/**
* Keeps a list of actions that need to be performed after
* Bluetooth is turned on.
* @type {Array}
* @memberof NfcHandoverManager.prototype
*/
actionQueue: [],
/**
* Keeps a list of send file requests made via peer.sendFile(blob).
* It will be inspected in the handling of Handover Select messages
* to distinguish between static and negotiated handovers.
* @type {Object}
* @memberof NfcHandoverManager.prototype
*/
sendFileQueue: [],
/**
* The length of the timeout in milliseconds to wait for an outstanding
* handover response.
* @type {Number}
* @memberof NfcHandoverManager.prototype
*/
responseTimeoutMillis: 9000,
/**
* Set whenever a timeout is defined while waiting for an outstanding
* handover response.
* @type {Object}
* @memberof NfcHandoverManager.prototype
*/
responseTimeoutFunction: null,
/**
* Set to true during a file transfer that was initiated by another device.
* @type {boolean}
* @memberof NfcHandoverManager.prototype
*/
incomingFileTransferInProgress: false,
/**
* Remembers whether Bluetooth was already saved during an earlier
* file transfer.
* @type {boolean}
* @memberof NfcHandoverManager.prototype
*/
bluetoothStatusSaved: false,
/**
* Remembers whether Bluetooth was enabled or automatically.
* @type {boolean}
* @memberof NfcHandoverManager.prototype
*/
bluetoothAutoEnabled: false,
/**
* Used to prevent triggering Settings multiple times.
* @memberof NfcHandoverManager.prototype
*/
settingsNotified: false,
/**
* Debug method
* @param {String} msg debug messages
* @param {Object} opObject object to printed after doing JSON.stringfy
* @memberof NfcHandoverManager.prototype
*/
_debug: function _debug(msg, optObject) {
if (this.DEBUG) {
this._logVisibly(msg, optObject);
}
},
_hasInititialized: false,
/**
* Logs message in logcat
* @param {String} msg debug messages
* @param {Object} opObject object to printed after doing JSON.stringfy
* @memberof NfcHandoverManager.prototype
*/
_logVisibly: function _logVisibly(msg, optObject) {
var output = '[NfcHandoverManager]: ' + msg;
if (optObject) {
output += JSON.stringify(optObject);
}
console.log(output);
},
'_observe_nfc.debugging.enabled': function(enabled) {
this.DEBUG = enabled;
},
/**
* Initializes event and message handlers, initializes properties.
* @memberof NfcHandoverManager.prototype
*/
_start: function _start() {
this.incomingFileTransferInProgress = false;
this.bluetoothStatusSaved = false;
this.bluetoothAutoEnabled = false;
window.navigator.mozSetMessageHandler('nfc-manager-send-file',
function(msg) {
this._debug('In New event nfc-manager-send-file' +
JSON.stringify(msg));
this.handleFileTransfer(msg.peer, msg.blob, msg.requestId);
}.bind(this));
},
'_handle_nfc-transfer-completed': function(evt) {
this.transferComplete(evt);
},
'_handle_nfc-transfer-started': function(evt) {
this._transferStarted(evt);
},
'_handle_bluetooth-available': function(evt) {
if (evt.detail && evt.detail.adapter) {
this._adapter = evt.detail.adapter;
this._debug('MAC address: ' + this._adapter.address);
this._debug('MAC name: ' + this._adapter.name);
} else {
this._debug('receive the wrong event format');
this._logVisibly('Failed to get bluetooth adapter');
}
},
'_handle_bluetooth-unavailable': function() {
this._debug('clean the bluetooth adapter');
this._adapter = null;
},
'_handle_bluetooth-disabled': function() {
this._debug('bluetooth-disabled');
this._clearBluetoothStatus();
},
'_handle_bluetooth-enabled': function() {
this._debug('bluetooth-enabled');
/*
* Call all actions that have queued up while Bluetooth
* was turned on.
*/
if (this._adapter) {
for (var i = 0; i < this.actionQueue.length; i++) {
var action = this.actionQueue[i];
action.callback.apply(this, action.args);
}
this.actionQueue = [];
}
},
/**
* Save the on/off status of Bluetooth.
* @memberof NfcHandoverManager.prototype
*/
_saveBluetoothStatus: function _saveBluetoothStatus() {
if (!this.bluetoothStatusSaved) {
this.bluetoothStatusSaved = true;
this.bluetoothAutoEnabled = !Service.query('Bluetooth.isEnabled');
}
},
/**
* Restore the Bluetooth status.
* @memberof NfcHandoverManager.prototype
*/
_restoreBluetoothStatus: function _restoreBluetoothStatus() {
if (!this.isHandoverInProgress() &&
Service.query('BluetoothTransfer.isSendFileQueueEmpty')) {
if (this.bluetoothAutoEnabled) {
this._debug('Disabling Bluetooth');
window.dispatchEvent(new CustomEvent('request-disable-bluetooth'));
this.bluetoothAutoEnabled = false;
}
this.bluetoothStatusSaved = false;
}
},
/**
* Forget a previously saved Bluetooth status.
* @memberof NfcHandoverManager.prototype
*/
_clearBluetoothStatus: function _clearBluetoothStatus() {
this.bluetoothStatusSaved = false;
},
/*
* Performs an action once Bluetooth is enabled. If Bluetooth is disabled,
* it is enabled and the action is queued. If Bluetooth is already enabled,
* performs the action directly.
* @param {Object} action action to be performed
* @param {function} action.callback function to be executed
* @param {Array} action.args arguments for the function
* @memberof NfcHandoverManager.prototype
*/
_doAction: function _doAction(action) {
if (!Service.query('Bluetooth.isEnabled')) {
this._debug('Bluetooth: not yet enabled');
this.actionQueue.push(action);
if (this.settingsNotified === false) {
window.dispatchEvent(new CustomEvent('request-enable-bluetooth'));
this.settingsNotified = true;
}
} else {
action.callback.apply(this, action.args);
}
},
/**
* Gets the data about other device taking part in handover proces
* from NDEF message
* @param {Array} ndef NDEF message
* @returns {Object} ssp - object containing info about other devices
* @returns {string} ssp.mac - mac addres of other devices
* @returns {string} ssp.localName - local name if present in NDEF message,
* null otherwise
* @memberof NfcHandoverManager.prototype
*/
_getBluetoothSSP: function _getBluetoothSSP(ndef) {
var handover = NDEFUtils.parseHandoverNDEF(ndef);
if (handover == null) {
// Bad handover message. Just ignore.
this._debug('Bad handover messsage');
return null;
}
var btsspRecord = NDEFUtils.searchForBluetoothAC(handover);
if (btsspRecord == null) {
// There is no Bluetooth Alternative Carrier record in the
// Handover Select message. Since we cannot handle WiFi Direct,
// just ignore.
this._debug('No BT AC');
return null;
}
return NDEFUtils.parseBluetoothSSP(btsspRecord);
},
/**
* Performs bluetooth pairing with other device
* @param {string} mac MAC address of the peer device
* @memberof NfcHandoverManager.prototype
*/
_doPairing: function _doPairing(mac) {
this._debug('doPairing: ' + mac);
if (this._adapter == null) {
// No BT
this._debug('No _adapter');
return;
}
var req = this._adapter.pair(mac);
var self = this;
req.onsuccess = function() {
self._debug('Pairing succeeded');
self._clearBluetoothStatus();
self._doConnect(mac);
};
req.onerror = function() {
self._logVisibly('Pairing failed');
self._restoreBluetoothStatus();
};
},
/**
* Show an error notification when file transfer failed.
* @param {String} msg Optional message.
* @memberof NfcHandoverManager.prototype
*/
_showFailedNotification: function _showFailedNotification(title, msg) {
var body = (msg !== undefined) ? msg : '';
var icon = 'style/bluetooth_transfer/images/icon_bluetooth.png';
NotificationHelper.send(title, {
body: body,
icon: icon
});
},
/**
* Show 'send failed, try again' notification.
*/
_showTryAgainNotification: function _showTryAgainNotification() {
var _ = navigator.mozL10n.get;
this._showFailedNotification('transferFinished-sentFailed-title',
_('transferFinished-try-again-description'));
},
/**
* This function will be called after a timeout when we did not receive the
* Hs record within three seconds. At this point we cancel the file
* transfer.
* @memberof NfcHandoverManager.prototype
*/
_cancelSendFileTransfer: function _cancelSendFileTransfer() {
this._debug('_cancelSendFileTransfer');
this.responseTimeoutFunction = null;
var job = this.sendFileQueue.pop();
job.onerror();
this._showFailedNotification('transferFinished-sentFailed-title',
job.blob.name);
this._restoreBluetoothStatus();
},
/**
* This function will be called after a timeout when we did not receive
* the Hs record within three seconds. At this point we cancel the file
* transfer.
* @memberof NfcHandoverManager.prototype
*/
_cancelIncomingFileTransfer: function _cancelIncomingFileTransfer() {
this._debug('_cancelIncomingFileTransfer');
this.responseTimeoutFunction = null;
this.incomingFileTransferInProgress = false;
this._showFailedNotification('transferFinished-receivedFailed-title');
this._restoreBluetoothStatus();
},
/**
* Performs bluetooth file transfer if this.sendFileRequest exists
* to other device
* @param {string} mac MAC address of the other device
* @memberof NfcHandoverManager.prototype
*/
_doFileTransfer: function _doFileTransfer(mac) {
this._debug('doFileTransfer');
if (this.sendFileQueue.length === 0) {
// Nothing to do
this._debug('sendFileQueue empty');
return;
}
this._debug('Send blob to ' + mac);
var blob = this.sendFileQueue[0].blob;
this.publish('bluetooth-sendfile-via-handover', {
mac: mac,
blob: blob
});
},
/**
* Performs tha actual handover request
* @param {Array} ndef NDEF message conating the handover request record
* @param {MozNFCPeer} MozNFCPeer object.
* @memberof NfcHandoverManager.prototype
*/
_doHandoverRequest: function _doHandoverRequest(ndef, nfcPeer) {
this._debug('doHandoverRequest');
if (this._getBluetoothSSP(ndef) == null) {
/*
* The handover request didn't contain a valid MAC address. Simply
* ignore the request.
*/
return;
}
if (nfcPeer.isLost) {
this._logVisibly('NFC peer went away during doHandoverRequest');
this._showFailedNotification('transferFinished-receivedFailed-title');
this._restoreBluetoothStatus();
return;
}
var cps = Service.query('Bluetooth.isEnabled') ?
NDEF.CPS_ACTIVE : NDEF.CPS_ACTIVATING;
var mac = this._adapter.address;
var hs = NDEFUtils.encodeHandoverSelect(mac, cps);
var promise = nfcPeer.sendNDEF(hs);
promise.then(() => {
this._debug('sendNDEF(hs) succeeded');
this.incomingFileTransferInProgress = true;
}).catch(e => {
this._logVisibly('sendNDEF(hs) failed : ' + e);
this._clearTimeout();
this._restoreBluetoothStatus();
});
this._clearTimeout();
this.responseTimeoutFunction =
setTimeout(this._cancelIncomingFileTransfer.bind(this),
this.responseTimeoutMillis);
},
/**
* Initiate a file transfer by sending a Handover Request to the
* remote device.
* @param {MozNFCPeer} An instance of MozNFCPeer object.
* @param {Blob} blob File to be sent.
* @param {String} requestId Request ID.
* @memberof NfcHandoverManager.prototype
*/
_initiateFileTransfer:
function _initiateFileTransfer(nfcPeer, blob, requestId) {
this._debug('initiateFileTransfer');
/*
* Initiate a file transfer by sending a Handover Request to the
* remote device.
*/
var self = this;
var onsuccess = function() {
self._dispatchSendFileStatus(0, requestId);
};
var onerror = function() {
self._dispatchSendFileStatus(1, requestId);
};
if (nfcPeer.isLost) {
this._logVisibly('NFC peer went away during initiateFileTransfer');
onerror();
this._restoreBluetoothStatus();
this._showFailedNotification('transferFinished-sentFailed-title',
blob.name);
return;
}
var job = {nfcPeer: nfcPeer, blob: blob, requestId: requestId,
onsuccess: onsuccess, onerror: onerror};
this.sendFileQueue.push(job);
var cps = Service.query('Bluetooth.isEnabled') ?
NDEF.CPS_ACTIVE : NDEF.CPS_ACTIVATING;
var mac = this._adapter.address;
var hr = NDEFUtils.encodeHandoverRequest(mac, cps);
var promise = nfcPeer.sendNDEF(hr);
promise.then(() => {
this._debug('sendNDEF(hr) succeeded');
}).catch(e => {
this._debug('sendNDEF(hr) failed : ' + e);
onerror();
this.sendFileQueue.pop();
this._clearTimeout();
this._restoreBluetoothStatus();
this._showFailedNotification('transferFinished-sentFailed-title',
blob.name);
});
this._clearTimeout();
this.responseTimeoutFunction =
setTimeout(this._cancelSendFileTransfer.bind(this),
this.responseTimeoutMillis);
},
/**
* Connects via bluetooth to the paired device.
* @param {string} mac MAC addres of the paired device
* @memberof NfcHandoverManager.prototype
*/
_doConnect: function _doConnect(mac) {
this._debug('doConnect with: ' + mac);
/*
* Bug 979427:
* After pairing we connect to the remote device. The only thing we
* know here is the MAC address, but the _adapter.connect()
* requires a BluetoothDevice argument. So we use getPairedDevices()
* to map the MAC to a BluetoothDevice instance.
*/
var req = this._adapter.getPairedDevices();
var self = this;
req.onsuccess = function() {
var devices = req.result;
self._debug('# devices: ' + devices.length);
var successCb = function() { self._debug('Connect succeeded'); };
var errorCb = function() { self._debug('Connect failed'); };
for (var i = 0; i < devices.length; i++) {
var device = devices[i];
self._debug('Address: ' + device.address);
self._debug('Connected: ' + device.connected);
if (device.address.toLowerCase() == mac.toLowerCase()) {
self._debug('Connecting to ' + mac);
var r = self._adapter.connect(device);
r.onsuccess = successCb;
r.onerror = errorCb;
}
}
};
req.onerror = function() {
self._logVisibly('Cannot get paired devices from adapter.');
};
},
/**
* Clears timeout that handles the case an outstanding handover message
* has not been received within a certain timeframe.
* @memberof NfcHandoverManager.prototype
*/
_clearTimeout: function _clearTimeout() {
this._debug('_clearTimeout');
if (this.responseTimeoutFunction != null) {
// Clear the timeout that handles error
this._debug('clearing timeout');
clearTimeout(this.responseTimeoutFunction);
this.responseTimeoutFunction = null;
}
},
/**
* Dispatches status of file sending to mozNfc.
* @param {number} status status of file send operation
* @param {string} request ID of the operation
* @memberof NfcHandoverManager.prototype
*/
_dispatchSendFileStatus:
function _dispatchSendFileStatus(status, requestId) {
this._debug('In dispatchSendFileStatus ' + status);
navigator.mozNfc.notifySendFileStatus(status, requestId);
},
/**
* Handles connection request by asking user for confirmation.
* @param {Object} btssp BT SSP (Secure Simple Pairing) data.
* @memberof NfcHandoverManager.prototype
*/
_onRequestConnect: function _onRequestConnect(btssp) {
var self = this;
var onconfirm = function() {
self._debug('Connect confirmed');
self._doAction({callback: self._doPairing, args: [btssp.mac]});
};
var onabort = function() {
self._debug('Connect aborted');
};
if (!this.nfcConnectSystemDialog) {
LazyLoader.load('js/system_nfc_connect_dialog.js', function() {
this.nfcConnectSystemDialog = new NfcConnectSystemDialog();
this.nfcConnectSystemDialog.show(btssp.localName, onconfirm, onabort);
}.bind(this));
} else {
this.nfcConnectSystemDialog.show(btssp.localName, onconfirm, onabort);
}
},
/**
* Handles simplified pairing record.
* @param {Array} ndef NDEF message containing simplified pairing record
* @memberof NfcHandoverManager.prototype
*/
_handleSimplifiedPairingRecord:
function _handleSimplifiedPairingRecord(ndef) {
this._debug('_handleSimplifiedPairingRecord');
var pairingRecord = ndef[0];
var btssp = NDEFUtils.parseBluetoothSSP(pairingRecord);
this._debug('Simplified pairing with: ' + btssp.mac);
this._onRequestConnect(btssp);
},
/**
* Handle NDEF Handover Select message.
* @param {Array} ndef NDEF message containing handover select record
* @memberof NfcHandoverManager.prototype
*/
_handleHandoverSelect: function _handleHandoverSelect(ndef) {
this._debug('_handleHandoverSelect');
this._clearTimeout();
var btssp = this._getBluetoothSSP(ndef);
if (btssp == null) {
if (this.sendFileQueue.length !== 0) {
// We tried to send a file but the other device gave us an empty AC
// record. This will happen if the other device is currently
// transferring a file. Show a 'try later' notification.
this._debug('Other device is transferring file. Aborting');
var job = this.sendFileQueue.shift();
job.onerror();
this._showTryAgainNotification();
}
return;
}
if (this.sendFileQueue.length !== 0) {
// This is the response to a file transfer request (negotiated handover)
this._doAction({callback: this._doFileTransfer, args: [btssp.mac]});
} else {
// This is a static handover
this._onRequestConnect(btssp);
}
},
/**
* Handles NDEF Handover Request message.
* @param {Array} ndef NDEF message containing handover request record
* @param {MozNFCPeer} MozNFCPeer object.
* @memberof NfcHandoverManager.prototype
*/
_handleHandoverRequest: function _handleHandoverRequest(ndef, nfcPeer) {
this._debug('_handleHandoverRequest');
if (Service.query('BluetoothTransfer.isFileTransferInProgress')) {
// We don't allow concurrent file transfers
this._debug('This device is currently transferring a file. ' +
'Aborting via empty Hs');
var hs = NDEFUtils.encodeEmptyHandoverSelect();
nfcPeer.sendNDEF(hs);
return;
}
this._saveBluetoothStatus();
this._doAction({
callback: this._doHandoverRequest,
args: [ndef, nfcPeer]
});
},
/**
* Checks if the first record of NDEF message is a handover record.
* If yes the NDEF message is handled according to handover record type.
* @param {Array} ndefMsg array of NDEF records
* @param {MozNFCPeer} MozNFCPeer object.
* @returns {boolean} true if handover record was found and handled, false
* if no handover record was found
* @memberof NfcHandoverManager.prototype
*/
tryHandover: function(ndefMsg, nfcPeer) {
this._debug('tryHandover: ', ndefMsg);
var nfcUtils = new NfcUtils();
if (!Array.isArray(ndefMsg) || !ndefMsg.length) {
return false;
}
var record = ndefMsg[0];
if (record.tnf === NDEF.TNF_WELL_KNOWN) {
if (nfcUtils.equalArrays(record.type, NDEF.RTD_HANDOVER_SELECT)) {
this._handleHandoverSelect(ndefMsg);
return true;
} else if (nfcUtils.equalArrays(
record.type, NDEF.RTD_HANDOVER_REQUEST)) {
this._handleHandoverRequest(ndefMsg, nfcPeer);
return true;
}
} else if ((record.tnf === NDEF.TNF_MIME_MEDIA) &&
nfcUtils.equalArrays(record.type, NDEF.MIME_BLUETOOTH_OOB)) {
this._handleSimplifiedPairingRecord(ndefMsg);
return true;
}
return false;
},
/**
* Trigger a file transfer with a remote device via BT.
* @param {MozNFCPeer} An instance of MozNFCPeer object.
* @param {Blob} blob File to be sent.
* @param {String} requestId Request ID.
* @memberof NfcHandoverManager.prototype
*/
handleFileTransfer: function handleFileTransfer(nfcPeer, blob, requestId) {
this._debug('handleFileTransfer');
if (Service.query('BluetoothTransfer.isFileTransferInProgress')) {
// We don't allow concurrent file transfers
this._debug('This device is already transferring a file. Aborting');
this._dispatchSendFileStatus(1, requestId);
this._showTryAgainNotification();
return;
}
this._saveBluetoothStatus();
this._doAction({
callback: this._initiateFileTransfer,
args: [nfcPeer, blob, requestId]});
},
/**
* Returns true if a handover is in progress.
* @returns {boolean} true if handover is in progress.
* @memberof NfcHandoverManager.prototype
*/
isHandoverInProgress: function isHandoverInProgress() {
return (this.sendFileQueue.length !== 0) ||
(this.incomingFileTransferInProgress === true);
},
/**
* BluetoothTransfer notifies us that a file transfer has started.
* @memberof NfcHandoverManager.prototype
*/
_transferStarted: function bt__transferStarted() {
this._clearTimeout();
},
/**
* Tells NfcHandoverManager that a BT file transfer
* has been completed.
* @param details succeeded True if file transfer was successfull.
* @memberof NfcHandoverManager.prototype
*/
transferComplete: function transferComplete(evt) {
var details = evt.detail;
this._debug('transferComplete: ' + JSON.stringify(details));
if (!details.received && details.viaHandover) {
// Completed an outgoing send file request. Call onsuccess/onerror
var job = this.sendFileQueue.shift();
if (details.success) {
job.onsuccess();
} else {
job.onerror();
}
}
if (details.received) {
// We know that a file was received but we do not know if that
// file was sent via a NFC handover. Clearing the
// incomingFileTransferInProgress flag here could lead to an
// unavoidable race condition
this.incomingFileTransferInProgress = false;
}
this._restoreBluetoothStatus();
}
});
}());