Publish Vulpes Preview 15 sources for desktop, Android and Tundra
Share Gaia assets and adapters, keep private profiles and development documents local, and update both public READMEs.
This commit is contained in:
parent
93e3a48004
commit
b38dea0597
60 changed files with 9982925 additions and 369 deletions
688
gaia/apps/settings/js/modules/addon_manager.js
Executable file
688
gaia/apps/settings/js/modules/addon_manager.js
Executable file
|
|
@ -0,0 +1,688 @@
|
|||
define(function(require) {
|
||||
'use strict';
|
||||
|
||||
var mozApps = require('modules/navigator/mozApps');
|
||||
var App = require('modules/app');
|
||||
var AppsCache = require('modules/apps_cache');
|
||||
var ObservableArray = require('modules/mvvm/observable_array');
|
||||
var MatchPattern = require('shared/addons/match_pattern');
|
||||
|
||||
/**
|
||||
* AddonManager is a singleton with methods for querying the currently
|
||||
* installed addons, enabling, disabling, and uninstalling addons, and
|
||||
* for obtaining a list of apps targeted by a specified add-on. The changes to
|
||||
* installed addons are propagated via an observable array.
|
||||
*
|
||||
* AddonManager uses the AppsCache module for efficient access to the full
|
||||
* list of installed apps.
|
||||
*
|
||||
* @class AddonManager
|
||||
* @requires module:modules/navigator/mozApps
|
||||
* @requires module:modules/apps_cache
|
||||
* @requires module:modules/mvvm/observable_array
|
||||
* @returns {AddonManager}
|
||||
*/
|
||||
function AddonManager() {
|
||||
this._addons = ObservableArray([]);
|
||||
this._bindEvents();
|
||||
|
||||
AppsCache.apps().then((apps) => {
|
||||
apps.some((app) => {
|
||||
if (this._isAddon(app)) {
|
||||
this._addons.push(App(app));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
AddonManager.prototype = {
|
||||
/**
|
||||
* Bind to install and uninstall events.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf AddonManager.prototype
|
||||
*/
|
||||
_bindEvents: function() {
|
||||
var _boundUpdateAddons = this._updateAddons.bind(this);
|
||||
// Bug 1215546 & 1218298
|
||||
// The 'oninstall' event is fired when user started installing the
|
||||
// app, but manifest is not available yet. In order to get the
|
||||
// manifest, we need to listen to 'downloadsuccess' on the app
|
||||
// (not mozApps.mgmt), and that's when manifest will be ready.
|
||||
AppsCache.addEventListener('oninstall', (evt) => {
|
||||
var app = evt && evt.application;
|
||||
// Bug 1220195
|
||||
// If installed via WebIDE, _isAddon will return true, and we should
|
||||
// run _boundUpdateAddons immediately because 'downloadsuccess' would
|
||||
// never fire. If installed from Marketplace we need to wait for the
|
||||
// 'downloadsuccess' event and run _boundUpdateAddons later.
|
||||
if (this._isAddon(app)) {
|
||||
_boundUpdateAddons(evt);
|
||||
} else {
|
||||
app.addEventListener('downloadsuccess', _boundUpdateAddons);
|
||||
}
|
||||
});
|
||||
AppsCache.addEventListener('onuninstall', _boundUpdateAddons);
|
||||
mozApps.mgmt.addEventListener('enabledstatechange', _boundUpdateAddons);
|
||||
},
|
||||
|
||||
/**
|
||||
* We have to update the addon array based on incoming evt.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf AddonManager.prototype
|
||||
* @param {Object} evt
|
||||
*/
|
||||
_updateAddons: function(evt) {
|
||||
var app = evt && evt.application;
|
||||
var type = evt.type;
|
||||
var index;
|
||||
|
||||
if (this._isAddon(app)) {
|
||||
if ((type === 'downloadsuccess' || type === 'install') &&
|
||||
!this._alreadyExists(app)) {
|
||||
this._addons.push(App(app));
|
||||
} else if (type === 'uninstall') {
|
||||
index = this._findAddonIndex(app);
|
||||
if (index !== -1) {
|
||||
this._addons.splice(index, 1);
|
||||
}
|
||||
} else if (type === 'enabledstatechange') {
|
||||
index = this._findAddonIndex(app);
|
||||
if (index !== -1) {
|
||||
this._addons.get(index)._enabled = app.enabled;
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Check if an addon already exists.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf AddonManager.prototype
|
||||
* @param {DOMApplication} addon
|
||||
* @returns {Boolean}
|
||||
*/
|
||||
_alreadyExists: function(addon) {
|
||||
return this._findAddonIndex(addon) !== -1;
|
||||
},
|
||||
|
||||
/**
|
||||
* Get the index of an addon.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf AddonManager.prototype
|
||||
* @param {DOMApplication} addon
|
||||
* @returns {Number}
|
||||
*/
|
||||
_findAddonIndex: function(addon) {
|
||||
return this._addons.array.findIndex((elem) => {
|
||||
return addon.manifestURL === elem.instance.manifestURL;
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Addons can only apply to apps with the same or lower privilege. Returns
|
||||
* a bloolean indicating whether the addon can be applied on the app.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf AddonManager.prototype
|
||||
* @param {DOMApplication} addon
|
||||
* @param {DOMApplication} app
|
||||
* @returns {Boolean}
|
||||
*/
|
||||
_privilegeCheck: function(addon, app) {
|
||||
var addonManifest = this._getManifest(addon);
|
||||
var appManifest = this._getManifest(app);
|
||||
return addonManifest.type === appManifest.type ||
|
||||
addonManifest.type === 'certified' ||
|
||||
addonManifest.type === 'privileged';
|
||||
},
|
||||
|
||||
/**
|
||||
* Get the manifest.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf AddonManager.prototype
|
||||
* @param {DOMApplication} app
|
||||
* @returns {Object}
|
||||
*/
|
||||
_getManifest: function(app) {
|
||||
return app.manifest || app.updateManifest;
|
||||
},
|
||||
|
||||
/**
|
||||
* Check whether reboot is required when disabling the addon.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf AddonManager.prototype
|
||||
* @param {DOMApplication} app
|
||||
* @param {Array} contentScripts
|
||||
* @returns {Boolean}
|
||||
*/
|
||||
_needsReboot: function({app, contentScripts}) {
|
||||
var manifest = this._getManifest(app);
|
||||
var role = manifest.role;
|
||||
// If the addon affects a system app
|
||||
if (role === 'system' || role === 'homescreen') {
|
||||
// and the app is customized with a script, then we need reboot
|
||||
return contentScripts.some(c => c.js.length > 0);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Check whether restart is required when disabling the addon.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf AddonManager.prototype
|
||||
* @param {DOMApplication} app
|
||||
* @param {Array} contentScripts
|
||||
* @returns {Boolean}
|
||||
*/
|
||||
_needsRestart: function({app, contentScripts}) {
|
||||
return contentScripts.some(c => c.js.length > 0);
|
||||
},
|
||||
|
||||
/**
|
||||
* Check whether this app is an addon.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf AddonManager.prototype
|
||||
* @param {DOMApplication} app
|
||||
* @returns {Boolean}
|
||||
*/
|
||||
_isAddon: function(app) {
|
||||
var manifest = this._getManifest(app);
|
||||
return manifest && manifest.role === 'addon';
|
||||
},
|
||||
|
||||
/**
|
||||
* This internal utility function returns an array of objects describing
|
||||
* the apps that are affected by the given addon.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf AddonManager.prototype
|
||||
* @param {DOMApplication} addon
|
||||
* @returns {Boolean}
|
||||
*/
|
||||
_getAffectedApps: function(addon) {
|
||||
if (!this._isAddon(addon)) {
|
||||
return Promise.reject('not an addon');
|
||||
}
|
||||
|
||||
var manifest = this._getManifest(addon);
|
||||
var customizations = manifest && manifest.customizations;
|
||||
// content_scripts field is internally copied from manifest.json to
|
||||
// manifest.webapp
|
||||
var contentScripts = manifest && manifest.content_scripts;
|
||||
|
||||
// If the addon specifies customizations, then it is obsolete and does not
|
||||
// work
|
||||
if (customizations) {
|
||||
return Promise.resolve([]);
|
||||
}
|
||||
|
||||
// If there are no content scripts or content scripts list is empty, the
|
||||
// addon does not affect any apps.
|
||||
if (!contentScripts || contentScripts.length === 0) {
|
||||
return Promise.resolve([]);
|
||||
}
|
||||
|
||||
return AppsCache.apps()
|
||||
.then(apps => apps.filter(app => {
|
||||
var manifest = this._getManifest(app);
|
||||
// Ignore apps that are themselves add-ons or if the addon doesn't
|
||||
// have high enough privileges to affect this app then we can just
|
||||
// return now.
|
||||
return manifest.role !== 'addon' &&
|
||||
this._privilegeCheck(addon, app);
|
||||
}))
|
||||
// Match apps based on add-on's content sctipts.
|
||||
.then(apps => {
|
||||
var matches = [];
|
||||
apps.forEach(app => {
|
||||
var matched;
|
||||
if ((matched = this._matchContentScripts(contentScripts, app))) {
|
||||
matches.push({ app: app, contentScripts: matched });
|
||||
}
|
||||
});
|
||||
return matches;
|
||||
})
|
||||
.catch(() => []);
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns a list of content scripts (from an addon manifest), if available,
|
||||
* that affect the app by a given addon. We implement getAddonTargets()
|
||||
* using this information , derive the 'reboot' and 'restart' return
|
||||
* values of disableAddon() from it and also use this function to apply
|
||||
* addon filters.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf AddonManager.prototype
|
||||
* @param {DOMApplication} addon
|
||||
* @param {DOMApplication} app
|
||||
* @returns {Array?} appliedContentScripts if available
|
||||
*/
|
||||
_matchContentScripts: function(contentScripts, app) {
|
||||
var manifest = this._getManifest(app);
|
||||
// Get the URL of the app origin plus its launch path to
|
||||
// compare against each of the filters.
|
||||
// XXX: Note that we and do not check the paths used by
|
||||
// activity handlers or any other paths in the manifest.
|
||||
var launchPath = manifest.launch_path || '';
|
||||
var launchURL = new URL(launchPath, app.origin);
|
||||
|
||||
// For each content script, compile the pattern string MatchPattern
|
||||
var patterns = contentScripts.map(contentScript => {
|
||||
return {
|
||||
matches: new MatchPattern(contentScript.matches),
|
||||
excludeMatches: new MatchPattern(contentScript.exclude_matches)
|
||||
};
|
||||
});
|
||||
|
||||
var appliedContentScripts = [];
|
||||
|
||||
// Now loop through the patterns to see what content scripts are applied
|
||||
// to this app
|
||||
for(var i = 0; i < patterns.length; i++) {
|
||||
var pattern = patterns[i];
|
||||
if (!pattern.excludeMatches.matches(launchURL) &&
|
||||
pattern.matches.matches(launchURL)) {
|
||||
appliedContentScripts.push(contentScripts[i]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// If any content scripts were applied to this app, return the list of
|
||||
// appliedContentScripts
|
||||
if (appliedContentScripts.length > 0) {
|
||||
return appliedContentScripts;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Convert exported add-on into an Array Buffer.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf AddonManager.prototype
|
||||
* @param {Blob} blob
|
||||
* @returns {Promise}
|
||||
*/
|
||||
_blobToArrayBuffer: function(blob) {
|
||||
return new Promise(function(resolve, reject) {
|
||||
var fileReader = new FileReader();
|
||||
fileReader.onload = function() {
|
||||
resolve(fileReader.result);
|
||||
};
|
||||
fileReader.onerror = function(reason) {
|
||||
reject(reason);
|
||||
};
|
||||
fileReader.readAsArrayBuffer(blob);
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Upack an add-on script.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf AddonManager.prototype
|
||||
* @param {ArrayBuffer} arrayBuffer
|
||||
* @returns {Promise}
|
||||
*/
|
||||
_unpackScript: function(arrayBuffer) {
|
||||
return this._JSZip.then(JSZip => {
|
||||
var zip = new JSZip();
|
||||
zip.load(arrayBuffer);
|
||||
|
||||
var applicationZipFile = zip.file('application.zip');
|
||||
if (!applicationZipFile) { return; }
|
||||
|
||||
var applicationZip = new JSZip();
|
||||
applicationZip.load(applicationZipFile.asArrayBuffer());
|
||||
|
||||
var scriptFile = applicationZip.file('main.js');
|
||||
if (!scriptFile) { return; }
|
||||
|
||||
return(scriptFile.asText());
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Generate a new add-on.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf AddonManager.prototype
|
||||
* @param {JSON} manifest add-on manifest
|
||||
* @param {String} script add-on script
|
||||
* @returns {Promise}
|
||||
*/
|
||||
_generate: function(manifest, script) {
|
||||
return this._JSZip.then(JSZip => {
|
||||
var id = 'addon' + Math.round(Math.random() * 100000000);
|
||||
var applicationZip = new JSZip();
|
||||
|
||||
// Ensure that we are creating an addon with a new id.
|
||||
manifest.role = 'addon';
|
||||
manifest.type = 'certified';
|
||||
manifest.origin = 'app://' + id + '.gaiamobile.org';
|
||||
manifest.activities = manifest.activities || {};
|
||||
|
||||
applicationZip.file('manifest.webapp', JSON.stringify(manifest));
|
||||
applicationZip.file('main.js', script);
|
||||
|
||||
var packageZip = new JSZip();
|
||||
packageZip.file('metadata.json', JSON.stringify({
|
||||
installOrigin: 'http://gaiamobile.org',
|
||||
manifestURL: 'app://' + id + '.gaiamobile.org/update.webapp',
|
||||
version: 1
|
||||
}));
|
||||
packageZip.file('update.webapp', JSON.stringify({
|
||||
name: manifest.name,
|
||||
package_path: '/application.zip'
|
||||
}));
|
||||
packageZip.file('application.zip',
|
||||
applicationZip.generate({ type: 'arraybuffer' }));
|
||||
|
||||
return new Blob([packageZip.generate({ type: 'arraybuffer' })],
|
||||
{ type: 'application/zip' });
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Lazily require jszip. It is currently used only for renaming Add-ons.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf AddonManager.prototype
|
||||
* @returns {Promise}
|
||||
*/
|
||||
get _JSZip() {
|
||||
return new Promise(resolve => { require(['vendor/jszip'], resolve); });
|
||||
},
|
||||
|
||||
/**
|
||||
* Install add-on, but importing it using a memory-backed blob.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf AddonManager.prototype
|
||||
* @param {Blob} blob add-on blob
|
||||
* @returns {Promise}
|
||||
*/
|
||||
_install: function(blob) {
|
||||
return navigator.mozApps.mgmt.import(blob).then(addon => {
|
||||
// Enable the addon by default.
|
||||
var app = { instance: addon };
|
||||
this.enableAddon(app);
|
||||
return app;
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Check whether an addon is enabled.
|
||||
*
|
||||
* @access public
|
||||
* @memberOf AddonManager.prototype
|
||||
* @param {App} addon
|
||||
* @returns {Boolean}
|
||||
*/
|
||||
isEnabled: function(addon) {
|
||||
return this._isAddon(addon.instance) && addon.instance.enabled === true;
|
||||
},
|
||||
|
||||
/**
|
||||
* Check whether an addon can be deleted.
|
||||
*
|
||||
* @access public
|
||||
* @memberOf AddonManager.prototype
|
||||
* @param {App} addon
|
||||
* @returns {Boolean}
|
||||
*/
|
||||
canDelete: function(addon) {
|
||||
return this._isAddon(addon.instance) && addon.instance.removable === true;
|
||||
},
|
||||
|
||||
/**
|
||||
* Enable an addon
|
||||
*
|
||||
* @access public
|
||||
* @memberOf AddonManager.prototype
|
||||
* @param {App} addon
|
||||
*/
|
||||
enableAddon: function(addon) {
|
||||
if (this._isAddon(addon.instance) && !addon.instance.enabled) {
|
||||
mozApps.mgmt.setEnabled(addon.instance, true);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Disable an addon. Returns a string indicating whether reboot or restart
|
||||
* required for disabling the addon completely.
|
||||
*
|
||||
* @access public
|
||||
* @memberOf AddonManager.prototype
|
||||
* @param {App} addon
|
||||
*/
|
||||
disableAddon: function(addon) {
|
||||
if (this._isAddon(addon.instance) && addon.instance.enabled) {
|
||||
mozApps.mgmt.setEnabled(addon.instance, false);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Delete an addon.
|
||||
*
|
||||
* @access public
|
||||
* @memberOf AddonManager.prototype
|
||||
* @param {App} addon
|
||||
* @returns {Promise}
|
||||
*/
|
||||
deleteAddon: function(addon) {
|
||||
if (!this._isAddon(addon.instance)) {
|
||||
return Promise.reject('not an addon');
|
||||
}
|
||||
|
||||
if (!addon.instance.removable) {
|
||||
return Promise.reject('addon is not deletable');
|
||||
}
|
||||
|
||||
return new Promise(function(resolve, reject) {
|
||||
var request = mozApps.mgmt.uninstall(addon.instance);
|
||||
request.onsuccess = function() {
|
||||
resolve();
|
||||
};
|
||||
request.onerror = function() {
|
||||
reject();
|
||||
};
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Rename an addon.
|
||||
*
|
||||
* @access public
|
||||
* @memberOf AddonManager.prototype
|
||||
* @param {App} addon
|
||||
* @param {String} name addon name
|
||||
* @returns {Promise}
|
||||
*/
|
||||
renameAddon: function(addon, name) {
|
||||
if (!name) {
|
||||
return Promise.reject('no name given');
|
||||
}
|
||||
|
||||
if (!this._isAddon(addon.instance)) {
|
||||
return Promise.reject('not an addon');
|
||||
}
|
||||
|
||||
var manifest = this._getManifest(addon.instance);
|
||||
if (name === manifest.name) {
|
||||
return Promise.reject('name is unchanged');
|
||||
}
|
||||
|
||||
var newManifest, addonBlob;
|
||||
// To rename an addon we are creating a new DOMApplication that will have
|
||||
// an updated name. Other manifest attributes are preserved.
|
||||
// Export an add-on as a blob.
|
||||
return addon.instance.export().then(blob => {
|
||||
addonBlob = blob;
|
||||
// Copy over manifest object.
|
||||
newManifest = Object.assign({}, manifest);
|
||||
newManifest.name = name;
|
||||
// Delete original add-on.
|
||||
return this.deleteAddon(addon);
|
||||
}).then(() => {
|
||||
// Convert exported add-on into an Array Buffer.
|
||||
return this._blobToArrayBuffer(addonBlob);
|
||||
}).then(this._unpackScript.bind(this)).then(script => {
|
||||
// Generate a new add-on using the original manifest and a new name.
|
||||
return this._generate(newManifest, script);
|
||||
}).then(this._install.bind(this));
|
||||
},
|
||||
|
||||
/**
|
||||
* Share an addon.
|
||||
*
|
||||
* @access public
|
||||
* @memberOf AddonManager.prototype
|
||||
* @param {App} addon
|
||||
* @returns {Promise}
|
||||
*/
|
||||
shareAddon: function(addon) {
|
||||
if (!this._isAddon(addon.instance)) {
|
||||
return Promise.reject('not an addon');
|
||||
}
|
||||
|
||||
return new Promise(function(resolve, reject) {
|
||||
var activity = new window.MozActivity({
|
||||
name: 'share',
|
||||
data: {
|
||||
type: 'app',
|
||||
app: addon.instance.manifestURL
|
||||
}
|
||||
});
|
||||
|
||||
activity.onsuccess = function() {
|
||||
resolve();
|
||||
};
|
||||
activity.onerror = function() {
|
||||
reject((activity.error && activity.error.name) || 'activity error');
|
||||
};
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Return an array of the apps that are targeted by any of this
|
||||
* addon's content scripts. Note, however, that addons can also target
|
||||
* arbitrary web pages and hosted apps. This test only applies to
|
||||
* installed packaged apps and so may be of limited utility.
|
||||
*
|
||||
* @access public
|
||||
* @memberOf AddonManager.prototype
|
||||
* @param {App} addon
|
||||
* @returns {Promise}
|
||||
*/
|
||||
getAddonTargets: function(addon) {
|
||||
return this._getAffectedApps(addon.instance).then((affectedApps) => {
|
||||
return affectedApps.map((x) => x.app);
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Return a string indicating whether reboot or restart is required for
|
||||
* disabling the addon.
|
||||
*
|
||||
* @access public
|
||||
* @memberOf AddonManager.prototype
|
||||
* @param {App} addon
|
||||
* @returns {Promise.<String>}
|
||||
*/
|
||||
getAddonDisableType: function(addon) {
|
||||
return this._getAffectedApps(addon.instance).then((affectedApps) => {
|
||||
var needsReboot = affectedApps.some(this._needsReboot.bind(this));
|
||||
if (needsReboot) {
|
||||
return 'reboot';
|
||||
}
|
||||
|
||||
var needsRestart = affectedApps.some(this._needsRestart.bind(this));
|
||||
if (needsRestart) {
|
||||
return 'restart';
|
||||
}
|
||||
|
||||
return '';
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Return the App object that matches the given manifest url.
|
||||
*
|
||||
* @access public
|
||||
* @memberOf AddonManager.prototype
|
||||
* @param {String} manifestURL
|
||||
* @returns {Promise.<App>}
|
||||
*/
|
||||
findAddonByManifestURL: function(manifestURL) {
|
||||
return AppsCache.apps().then(() => {
|
||||
return this._addons.array.find((addon) => {
|
||||
return addon.instance.manifestURL === manifestURL;
|
||||
});
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns a promise for a boolean flag indicating whether an addon affects
|
||||
* an application or not..
|
||||
*
|
||||
* @access public
|
||||
* @memberOf AddonManager.prototype
|
||||
* @param {DOMApplication} addon addon to check
|
||||
* @param {String} manifestURL app manifest URL to check
|
||||
* @returns {Promise.<Boolean>}
|
||||
*/
|
||||
addonAffectsApp: function(addon, manifestURL) {
|
||||
if (!manifestURL) {
|
||||
return Promise.reject('No manifestURL given for an app');
|
||||
}
|
||||
if (!this._isAddon(addon.instance)) {
|
||||
return Promise.reject('not an addon');
|
||||
}
|
||||
|
||||
var manifest = this._getManifest(addon.instance);
|
||||
var customizations = manifest && manifest.customizations;
|
||||
// content_scripts field is internally copied from manifest.json to
|
||||
// manifest.webapp
|
||||
var contentScripts = manifest && manifest.content_scripts;
|
||||
|
||||
// If the addon specifies customizations, then it is obsolete and does not
|
||||
// work
|
||||
if (customizations) {
|
||||
return Promise.resolve(false);
|
||||
}
|
||||
|
||||
// If there are no content scripts or content scripts list is empty, the
|
||||
// addon does not affect any apps.
|
||||
if (!contentScripts || contentScripts.length === 0) {
|
||||
return Promise.resolve(false);
|
||||
}
|
||||
|
||||
return AppsCache.apps()
|
||||
.then(apps => apps.find(app => app.manifestURL === manifestURL))
|
||||
.then(app => app ?
|
||||
this._matchContentScripts(contentScripts, app) : undefined)
|
||||
.then(appliedContentScripts => !!appliedContentScripts)
|
||||
.catch(() => false);
|
||||
},
|
||||
|
||||
get length() {
|
||||
return this._addons.length;
|
||||
},
|
||||
|
||||
get addons() {
|
||||
return this._addons;
|
||||
}
|
||||
};
|
||||
|
||||
return new AddonManager();
|
||||
});
|
||||
52
gaia/apps/settings/js/modules/apn/apn_const.js
Executable file
52
gaia/apps/settings/js/modules/apn/apn_const.js
Executable file
|
|
@ -0,0 +1,52 @@
|
|||
/**
|
||||
* The apn constants
|
||||
*/
|
||||
define(function(require) {
|
||||
'use strict';
|
||||
|
||||
var APN_TYPES = ['default', 'mms', 'supl', 'dun', 'ims', 'fota'];
|
||||
|
||||
var CP_APN_KEY = 'ril.data.cp.apns';
|
||||
var DEFAULT_APN_KEY = 'ril.data.default.apns';
|
||||
|
||||
// Used for detecting if a new icc card has been inserted.
|
||||
var CACHED_ICCIDS_KEY = 'apn.cached.iccids';
|
||||
|
||||
var APN_LIST_KEY = 'apn.list';
|
||||
var APN_SELECTIONS_KEY = 'apn.selections';
|
||||
var APN_SETTINGS_KEY = 'ril.data.apnSettings';
|
||||
var DEFAULT_APN_SETTINGS_KEY = 'ril.data.default.apnSettings';
|
||||
|
||||
var MCC_SETTINGS_KEY = 'operatorvariant.mcc';
|
||||
var MNC_SETTINGS_KEY = 'operatorvariant.mnc';
|
||||
|
||||
var EU_ROAMING_ENABLED_KEY = 'eu-roaming.enabled';
|
||||
var EU_ROAMING_FILE_PATH = '/resources/eu-roaming.json';
|
||||
|
||||
var APN_PROPS = [
|
||||
'carrier', 'apn', 'user', 'passwd', 'httpproxyhost', 'httpproxyport',
|
||||
'mmsc', 'mmsproxy', 'mmsport', 'authtype', 'types', 'protocol',
|
||||
'roaming_protocol', 'mtu',
|
||||
/**
|
||||
* _id is an internal property for identifying apn items received via
|
||||
* client provisioning.
|
||||
*/
|
||||
'_id'
|
||||
];
|
||||
|
||||
return {
|
||||
get APN_TYPES() { return APN_TYPES; },
|
||||
get CP_APN_KEY() { return CP_APN_KEY; },
|
||||
get DEFAULT_APN_KEY() { return DEFAULT_APN_KEY; },
|
||||
get CACHED_ICCIDS_KEY() { return CACHED_ICCIDS_KEY; },
|
||||
get APN_LIST_KEY() { return APN_LIST_KEY; },
|
||||
get APN_SELECTIONS_KEY() { return APN_SELECTIONS_KEY; },
|
||||
get APN_SETTINGS_KEY() { return APN_SETTINGS_KEY; },
|
||||
get DEFAULT_APN_SETTINGS_KEY() { return DEFAULT_APN_SETTINGS_KEY; },
|
||||
get MCC_SETTINGS_KEY() { return MCC_SETTINGS_KEY; },
|
||||
get MNC_SETTINGS_KEY() { return MNC_SETTINGS_KEY; },
|
||||
get EU_ROAMING_ENABLED_KEY() { return EU_ROAMING_ENABLED_KEY; },
|
||||
get EU_ROAMING_FILE_PATH() { return EU_ROAMING_FILE_PATH; },
|
||||
get APN_PROPS() { return APN_PROPS; }
|
||||
};
|
||||
});
|
||||
46
gaia/apps/settings/js/modules/apn/apn_item.js
Executable file
46
gaia/apps/settings/js/modules/apn/apn_item.js
Executable file
|
|
@ -0,0 +1,46 @@
|
|||
/**
|
||||
* ApnItem is a wrapper of apn objects.
|
||||
*
|
||||
* @module modules/apn/apn_item
|
||||
*/
|
||||
define(function(require) {
|
||||
'use strict';
|
||||
|
||||
var APN_CATEGORY = {
|
||||
PRESET: 'preset',
|
||||
CUSTOM: 'custom',
|
||||
EU: 'eu'
|
||||
};
|
||||
|
||||
/**
|
||||
* @class ApnItem
|
||||
* @params {String} id
|
||||
* @params {String} category
|
||||
* @params {Object} apn
|
||||
* @returns {ApnItem}
|
||||
*/
|
||||
function ApnItem(id, category, apn) {
|
||||
this._id = id;
|
||||
this._category = category;
|
||||
this._apn = apn;
|
||||
}
|
||||
|
||||
ApnItem.prototype = {
|
||||
get id() {
|
||||
return this._id;
|
||||
},
|
||||
get category() {
|
||||
return this._category;
|
||||
},
|
||||
get apn() {
|
||||
return this._apn;
|
||||
}
|
||||
};
|
||||
|
||||
var constructor = function ctor_apn_item(id, category, apn) {
|
||||
return new ApnItem(id, category, apn);
|
||||
};
|
||||
constructor.APN_CATEGORY = APN_CATEGORY;
|
||||
|
||||
return constructor;
|
||||
});
|
||||
266
gaia/apps/settings/js/modules/apn/apn_list.js
Executable file
266
gaia/apps/settings/js/modules/apn/apn_list.js
Executable file
|
|
@ -0,0 +1,266 @@
|
|||
/**
|
||||
* ApnList stores ApnItem objects representing apns come from the apn.json
|
||||
* database, client provisioning messages, and user's creation. Each ApnItem has
|
||||
* an id assigned upon the creation. The id is used to recored users' apn
|
||||
* selection.
|
||||
*
|
||||
* @module modules/apn/apn_list
|
||||
*/
|
||||
define(function(require) {
|
||||
'use strict';
|
||||
|
||||
var AsyncStorage = require('modules/async_storage');
|
||||
var ApnUtils = require('modules/apn/apn_utils');
|
||||
var ApnItem = require('modules/apn/apn_item');
|
||||
|
||||
/**
|
||||
* @class ApnList
|
||||
* @requires module:modules/async_storage
|
||||
* @requires module:modules/apn/apn_utils
|
||||
* @requires module:modules/apn/apn_item
|
||||
* @returns {ApnList}
|
||||
*/
|
||||
function ApnList(key) {
|
||||
this._key = key;
|
||||
this._apnItems = null;
|
||||
this._pendingTaskCount = 0;
|
||||
this._promiseChain = Promise.resolve();
|
||||
}
|
||||
|
||||
ApnList.prototype = {
|
||||
/**
|
||||
* As the operations should not be performed concurrently. We use this
|
||||
* function to enusre the operations are performed one by one.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf ApnList.prototype
|
||||
* @param {Function} task
|
||||
* @returns {Promise}
|
||||
*/
|
||||
_schedule: function al__schedule(task) {
|
||||
var that = this;
|
||||
this._promiseChain = this._promiseChain.then(function() {
|
||||
that._pendingTaskCount++;
|
||||
return task().then(function(result) {
|
||||
that._pendingTaskCount--;
|
||||
if (that._pendingTaskCount === 0) {
|
||||
return that._commit().then(function() {
|
||||
return result;
|
||||
});
|
||||
} else {
|
||||
return result;
|
||||
}
|
||||
});
|
||||
});
|
||||
return this._promiseChain;
|
||||
},
|
||||
|
||||
/**
|
||||
* _apnItems are wrapped apn items. The function unwraps the items so
|
||||
* that they can be stored to async storage.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf ApnList.prototype
|
||||
* @returns {Array}
|
||||
*/
|
||||
_export: function al__export() {
|
||||
return this._apnItems.map(function(apnItem) {
|
||||
// Convert the apn items to static objects for storing.
|
||||
var apnClone = ApnUtils.clone(apnItem.apn);
|
||||
apnClone.id = apnItem.id;
|
||||
apnClone.category = apnItem.category;
|
||||
return apnClone;
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Stores the current copy of apn items to async storage.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf ApnList.prototype
|
||||
* @returns {Promise}
|
||||
*/
|
||||
_commit: function al__commit() {
|
||||
if (!this._apnItems) {
|
||||
return Promise.resolve();
|
||||
} else {
|
||||
var apns = this._export();
|
||||
return AsyncStorage.setItem(this._key, apns);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* The internal add function.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf ApnList.prototype
|
||||
* @params {Object} apn
|
||||
* @params {ApnItem.APN_CATEGORY} category
|
||||
* @returns {Promise.<String>} The apn id
|
||||
*/
|
||||
_add: function al__add(apn, category) {
|
||||
return this.items().then(function(apnItems) {
|
||||
if (!apnItems) {
|
||||
// set default apn items
|
||||
this._apnItems = apnItems = [];
|
||||
}
|
||||
|
||||
// Set carrier to _custom_ if the category is custom for backward
|
||||
// compatibility
|
||||
category = category || ApnItem.APN_CATEGORY.CUSTOM;
|
||||
if (category === ApnItem.APN_CATEGORY.CUSTOM) {
|
||||
apn.carrier = '_custom_';
|
||||
}
|
||||
var apnItem = ApnItem(ApnUtils.generateId(), category, apn);
|
||||
|
||||
apnItems.unshift(apnItem);
|
||||
return apnItem.id;
|
||||
}.bind(this));
|
||||
},
|
||||
|
||||
/**
|
||||
* The internal remove function.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf ApnList.prototype
|
||||
* @params {String} id
|
||||
* @returns {Promise}
|
||||
*/
|
||||
_remove: function al__remove(id) {
|
||||
return this.items().then(function(apnItems) {
|
||||
if (!apnItems) {
|
||||
return Promise.reject('no apn items');
|
||||
}
|
||||
|
||||
var index = apnItems.findIndex((apnItem) => apnItem.id === id);
|
||||
if (index >= 0) {
|
||||
apnItems = apnItems.splice(index, 1);
|
||||
} else {
|
||||
return Promise.reject('apn not found');
|
||||
}
|
||||
}.bind(this));
|
||||
},
|
||||
|
||||
/**
|
||||
* The internal update function.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf ApnList.prototype
|
||||
* @params {String} id
|
||||
* @params {Object} apn
|
||||
* @returns {Promise}
|
||||
*/
|
||||
_update: function al__update(id, apn) {
|
||||
return this.items().then(function(apnItems) {
|
||||
if (!apnItems) {
|
||||
return Promise.reject('no apn items');
|
||||
}
|
||||
|
||||
var index = apnItems.findIndex((apnItem) => apnItem.id === id);
|
||||
if (index >= 0) {
|
||||
var currentApn = apnItems[index].apn;
|
||||
for (var p in apn) {
|
||||
// id and category are not allowed to be changed
|
||||
if (p === 'id' || p === 'category') {
|
||||
continue;
|
||||
}
|
||||
currentApn[p] = apn[p];
|
||||
}
|
||||
} else {
|
||||
return Promise.reject('apn not found');
|
||||
}
|
||||
}.bind(this));
|
||||
},
|
||||
|
||||
/**
|
||||
* Get all apn items of the list.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf ApnList.prototype
|
||||
* @returns {Promise.<Array.<ApnItem>>}
|
||||
*/
|
||||
items: function al_items() {
|
||||
// Because add/remove/update depend on this function so we should not
|
||||
// schedule it or we will get a dead lock. We return the current copy of
|
||||
// apn items.
|
||||
if (this._apnItems) {
|
||||
return Promise.resolve(this._apnItems);
|
||||
} else {
|
||||
return AsyncStorage.getItem(this._key).then(function(apns) {
|
||||
if (apns) {
|
||||
this._apnItems = apns.map(function(apn) {
|
||||
return ApnItem(apn.id, apn.category, apn);
|
||||
});
|
||||
return this._apnItems;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}.bind(this));
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Get the apn item with a specified id.
|
||||
*
|
||||
* @access public
|
||||
* @memberOf ApnList.prototype
|
||||
* @returns {Promise.<ApnItem>}
|
||||
*/
|
||||
item: function al_item(id) {
|
||||
// Return the apn item based on the current copy if apn items.
|
||||
return this.items().then(function(apnItems) {
|
||||
if (!apnItems || !id) {
|
||||
return null;
|
||||
} else {
|
||||
return apnItems.find((apnItem) => apnItem.id === id);
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Add an apn to the list with specified category. Returns the id of the
|
||||
* newly added apn.
|
||||
*
|
||||
* @access public
|
||||
* @memberOf ApnList.prototype
|
||||
* @params {Object} apn
|
||||
* @params {ApnItem.APN_CATEGORY} category
|
||||
* @returns {Promise.<String>} The apn id
|
||||
*/
|
||||
add: function al_apns(apn, category) {
|
||||
var apnClone = ApnUtils.clone(apn);
|
||||
return this._schedule(this._add.bind(this, apnClone, category));
|
||||
},
|
||||
|
||||
/**
|
||||
* Remove an apn from the list.
|
||||
*
|
||||
* @access public
|
||||
* @memberOf ApnList.prototype
|
||||
* @params {String} id
|
||||
* @returns {Promise}
|
||||
*/
|
||||
remove: function al_remove(id) {
|
||||
return this._schedule(this._remove.bind(this, id));
|
||||
},
|
||||
|
||||
/**
|
||||
* Update an apn. All properties expect for "id" and "category" will be
|
||||
* overwritten based on the passed apn object.
|
||||
*
|
||||
* @access public
|
||||
* @memberOf ApnList.prototype
|
||||
* @params {String} id
|
||||
* @params {Object} apn
|
||||
* @returns {Promise}
|
||||
*/
|
||||
update: function al_update(id, apn) {
|
||||
var apnClone = ApnUtils.clone(apn);
|
||||
return this._schedule(this._update.bind(this, id, apnClone));
|
||||
}
|
||||
};
|
||||
|
||||
return function ctor_apn_list(key) {
|
||||
return new ApnList(key);
|
||||
};
|
||||
});
|
||||
192
gaia/apps/settings/js/modules/apn/apn_selections.js
Executable file
192
gaia/apps/settings/js/modules/apn/apn_selections.js
Executable file
|
|
@ -0,0 +1,192 @@
|
|||
/**
|
||||
* ApnSelections stores the id of the apn being used on each apn type. The
|
||||
* selections are provided in terms of Observable. Changes to the selection
|
||||
* can be observed and then be saved to the settings database.
|
||||
* Implementation details please refer to {@link ApnSelections}.
|
||||
*
|
||||
* @module modules/apn/apn_selections
|
||||
*/
|
||||
define(function(require) {
|
||||
'use strict';
|
||||
|
||||
var Observable = require('modules/mvvm/observable');
|
||||
var SettingsCache = require('modules/settings_cache');
|
||||
var ApnConst = require('modules/apn/apn_const');
|
||||
|
||||
var ICC_COUNT = navigator.mozMobileConnections.length;
|
||||
var APN_TYPES = ApnConst.APN_TYPES;
|
||||
var APN_SELECTIONS_KEY = ApnConst.APN_SELECTIONS_KEY;
|
||||
|
||||
/**
|
||||
* @class ApnSelections
|
||||
* @requires module:modules/mvvm/observable
|
||||
* @requires module:modules/settings_cache
|
||||
* @requires module:modules/apn/apn_const
|
||||
* @returns {ApnSelections}
|
||||
*/
|
||||
function ApnSelections() {
|
||||
this._readyPromise = null;
|
||||
this._apnSelections = [];
|
||||
}
|
||||
|
||||
ApnSelections.prototype = {
|
||||
/**
|
||||
* Converts the apn selections to static objects for storing.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf ApnSelections.prototype
|
||||
* @returns {Promise.<Array>}
|
||||
*/
|
||||
_export: function as__export() {
|
||||
return this._apnSelections.map(function(apnSelection) {
|
||||
var obj = {};
|
||||
APN_TYPES.forEach(function(apnType) {
|
||||
obj[apnType] = apnSelection[apnType];
|
||||
});
|
||||
return obj;
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Stores the current selection to the settings database.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf ApnSelections.prototype
|
||||
* @returns {Promise}
|
||||
*/
|
||||
_commit: function as__commit() {
|
||||
return new Promise(function(resolve) {
|
||||
var obj = {};
|
||||
obj[APN_SELECTIONS_KEY] = this._export();
|
||||
var req = navigator.mozSettings.createLock().set(obj);
|
||||
req.onsuccess = function() { resolve(); };
|
||||
req.onerror = function() {
|
||||
console.error('write apn selections failed');
|
||||
resolve();
|
||||
};
|
||||
}.bind(this));
|
||||
},
|
||||
|
||||
/**
|
||||
* Registers observers so that we can save the selection when it changes.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf ApnSelections.prototype
|
||||
*/
|
||||
_observeApnSelections: function as__observeApnSelections(apnSelection) {
|
||||
APN_TYPES.forEach(function(apnType) {
|
||||
apnSelection.observe(apnType, this._commit.bind(this));
|
||||
}, this);
|
||||
},
|
||||
|
||||
/**
|
||||
* Creates empty selections.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf ApnSelections.prototype
|
||||
* @returns {Promise}
|
||||
*/
|
||||
_createEmptySelections: function as__createEmptySelections() {
|
||||
var emptySelections = [];
|
||||
var emptySelection = {};
|
||||
APN_TYPES.forEach((apnType) => emptySelection[apnType] = null);
|
||||
|
||||
for (var i = 0; i < ICC_COUNT; i++) {
|
||||
emptySelections.push(emptySelection);
|
||||
}
|
||||
|
||||
return new Promise(function(resolve, reject) {
|
||||
var obj = {};
|
||||
obj[APN_SELECTIONS_KEY] = emptySelections;
|
||||
var req = navigator.mozSettings.createLock().set(obj);
|
||||
req.onsuccess = req.onerror =
|
||||
function() { resolve(emptySelections); };
|
||||
}.bind(this));
|
||||
},
|
||||
|
||||
/**
|
||||
* Initializes the selections based on the values stored in the settings
|
||||
* database.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf ApnSelections.prototype
|
||||
* @returns {Promise}
|
||||
*/
|
||||
_ready: function as__ready() {
|
||||
// This ensures that the ready process being executed only once.
|
||||
if (!this._readyPromise) {
|
||||
var that = this;
|
||||
this._readyPromise = new Promise(function(resolve) {
|
||||
SettingsCache.getSettings(function(results) {
|
||||
resolve(results[APN_SELECTIONS_KEY]);
|
||||
});
|
||||
}).then(function(apnSelections) {
|
||||
if (apnSelections) {
|
||||
return apnSelections;
|
||||
} else {
|
||||
return that._createEmptySelections();
|
||||
}
|
||||
}).then(function(apnSelections) {
|
||||
// Turn the selections to observables
|
||||
apnSelections.forEach(function(selection, index) {
|
||||
var observableApnSelection = Observable(selection);
|
||||
that._observeApnSelections(observableApnSelection);
|
||||
that._apnSelections[index] = observableApnSelection;
|
||||
});
|
||||
|
||||
// Clear the entire apn selection states when the selections are
|
||||
// cleared by other apps (usually the wap push app).
|
||||
navigator.mozSettings.addObserver(APN_SELECTIONS_KEY,
|
||||
function(event) {
|
||||
if (event.settingValue === null) {
|
||||
that._readyPromise = null;
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
return this._readyPromise;
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns the apn selection of a sim slot. The selection object is an
|
||||
* Observable in which the apn types and apn ids are stored as key-value
|
||||
* pairs.
|
||||
*
|
||||
* @access public
|
||||
* @memberOf ApnSelections.prototype
|
||||
* @params {Number} serviceId
|
||||
* @returns {Promise.<Observable>}
|
||||
*/
|
||||
get: function as_get(serviceId) {
|
||||
return this._ready().then(function() {
|
||||
return this._apnSelections[serviceId];
|
||||
}.bind(this));
|
||||
},
|
||||
|
||||
/**
|
||||
* Reset the apn selection to null.
|
||||
*
|
||||
* @access public
|
||||
* @memberOf ApnSelections.prototype
|
||||
* @params {Number} serviceId
|
||||
* @returns {Promise}
|
||||
*/
|
||||
clear: function as_clear(serviceId) {
|
||||
var apnSelection = this._apnSelections[serviceId];
|
||||
if (!apnSelection) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
return this._ready().then(function() {
|
||||
APN_TYPES.forEach(function(apnType) {
|
||||
apnSelection[apnType] = null;
|
||||
});
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
return function() {
|
||||
return new ApnSelections();
|
||||
};
|
||||
});
|
||||
245
gaia/apps/settings/js/modules/apn/apn_settings.js
Executable file
245
gaia/apps/settings/js/modules/apn/apn_settings.js
Executable file
|
|
@ -0,0 +1,245 @@
|
|||
/**
|
||||
* ApnSettings provides functions for manipulating the apn settings in the
|
||||
* settings database.
|
||||
* Implementation details please refer to {@link ApnSettings}.
|
||||
*
|
||||
* @module modules/apn/apn_settings
|
||||
*/
|
||||
define(function(require) {
|
||||
'use strict';
|
||||
|
||||
var SettingsCache = require('modules/settings_cache');
|
||||
var ApnUtils = require('modules/apn/apn_utils');
|
||||
var ApnConst = require('modules/apn/apn_const');
|
||||
|
||||
var APN_SETTINGS_KEY = ApnConst.APN_SETTINGS_KEY;
|
||||
var DEFAULT_APN_SETTINGS_KEY = ApnConst.DEFAULT_APN_SETTINGS_KEY;
|
||||
|
||||
/**
|
||||
* @class ApnSettings
|
||||
* @returns {ApnSettings}
|
||||
*/
|
||||
function ApnSettings() {
|
||||
this._isReady = false;
|
||||
this._readyPromise = null;
|
||||
this._isWritingDB = false;
|
||||
this._isDirty = false;
|
||||
this._apnSettings = null;
|
||||
this._promiseChain = Promise.resolve();
|
||||
}
|
||||
|
||||
ApnSettings.prototype = {
|
||||
/**
|
||||
* As the operations should not be performed concurrently. We use this
|
||||
* function to enusre the operations are performed one by one.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf ApnSettings.prototype
|
||||
* @param {Function} task
|
||||
* @returns {Promise}
|
||||
*/
|
||||
_schedule: function al__schedule(task) {
|
||||
var that = this;
|
||||
this._promiseChain = this._promiseChain.then(function() {
|
||||
return task().then(function() {
|
||||
return that._commit();
|
||||
});
|
||||
});
|
||||
return this._promiseChain;
|
||||
},
|
||||
|
||||
/**
|
||||
* Stores the current copy of apn settings to the settings database.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf ApnSettings.prototype
|
||||
* @returns {Promise}
|
||||
*/
|
||||
_commit: function al__commit() {
|
||||
if (!this._isDirty) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
var that = this;
|
||||
return new Promise(function(resolve) {
|
||||
that._isWritingDB = true;
|
||||
var obj = {};
|
||||
obj[APN_SETTINGS_KEY] = that._apnSettings;
|
||||
var req = navigator.mozSettings.createLock().set(obj);
|
||||
req.onsuccess = req.onerror = function() {
|
||||
that._isDirty = false;
|
||||
that._isWritingDB = false;
|
||||
resolve();
|
||||
};
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Registers an observer on setting changes because ril.data.apnSettings
|
||||
* could be changed by other apps (system and wap).
|
||||
*
|
||||
* @access private
|
||||
* @memberOf ApnSettings.prototype
|
||||
*/
|
||||
_addObservers: function as__registerListeners() {
|
||||
var mozSettings = window.navigator.mozSettings;
|
||||
if (!mozSettings) {
|
||||
return;
|
||||
}
|
||||
mozSettings.addObserver(APN_SETTINGS_KEY, function(event) {
|
||||
if (!this._isWritingDB) {
|
||||
// Do not reflect the change during the committing.
|
||||
this._apnSettings = event.settingValue || [];
|
||||
}
|
||||
}.bind(this));
|
||||
},
|
||||
|
||||
/**
|
||||
* Initializes the settings based on the values stored in the settings
|
||||
* database.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf ApnSettings.prototype
|
||||
* @returns {Promise}
|
||||
*/
|
||||
_ready: function as__ready() {
|
||||
if (this._isReady) {
|
||||
return Promise.resolve();
|
||||
} else {
|
||||
// This ensures that the ready process being executed only once.
|
||||
if (!this._readyPromise) {
|
||||
var that = this;
|
||||
this._readyPromise = new Promise(function(resolve) {
|
||||
SettingsCache.getSettings(function(results) {
|
||||
that._isReady = true;
|
||||
that._apnSettings = results[APN_SETTINGS_KEY] || [];
|
||||
that._addObservers();
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
return this._readyPromise;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* The internal update function.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf ApnSettings.prototype
|
||||
* @params {Number} serviceId
|
||||
* @params {String} apnType
|
||||
* @params {Object} newApn
|
||||
* @returns {Promise}
|
||||
*/
|
||||
_update: function as__update(serviceId, apnType, newApn) {
|
||||
return this._ready().then(function() {
|
||||
var apns = this._apnSettings[serviceId];
|
||||
if (!apns) {
|
||||
apns = this._apnSettings[serviceId] = [];
|
||||
}
|
||||
|
||||
var index = apns.findIndex(function(apn) {
|
||||
return apn.types.some((type) => apnType === type);
|
||||
});
|
||||
|
||||
if (index === -1) {
|
||||
if (newApn) {
|
||||
this._isDirty = true;
|
||||
apns.push(newApn);
|
||||
}
|
||||
} else {
|
||||
if (newApn) {
|
||||
if (!ApnUtils.isMatchedApn(apns[index], newApn)) {
|
||||
this._isDirty = true;
|
||||
apns[index] = newApn;
|
||||
}
|
||||
} else {
|
||||
this._isDirty = true;
|
||||
apns.splice(index, 1);
|
||||
}
|
||||
}
|
||||
}.bind(this));
|
||||
},
|
||||
|
||||
/**
|
||||
* Get all apns with of a sim card.
|
||||
*
|
||||
* @access public
|
||||
* @memberOf ApnSettings.prototype
|
||||
* @params {Number} serviceId
|
||||
* @returns {Promise.<Array>}
|
||||
*/
|
||||
getAll: function as_getAll(serviceId) {
|
||||
return this._ready().then(function() {
|
||||
return this._apnSettings[serviceId];
|
||||
}.bind(this));
|
||||
},
|
||||
|
||||
/**
|
||||
* Get the apn of the specified apn type.
|
||||
*
|
||||
* @access public
|
||||
* @memberOf ApnSettings.prototype
|
||||
* @params {Number} serviceId
|
||||
* @params {String} apnType
|
||||
* @returns {Promise.<Object>}
|
||||
*/
|
||||
get: function as_get(serviceId, apnType) {
|
||||
return this._ready().then(function() {
|
||||
var apns = this._apnSettings[serviceId];
|
||||
if (apns) {
|
||||
return apns.find((apn) => apn.types.indexOf(apnType) >= 0);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}.bind(this));
|
||||
},
|
||||
|
||||
/**
|
||||
* Update an apn and the change will be saved into the settings database.
|
||||
*
|
||||
* @access public
|
||||
* @memberOf ApnSettings.prototype
|
||||
* @params {Number} serviceId
|
||||
* @params {String} apnType
|
||||
* @params {Object} apn
|
||||
* @returns {Promise}
|
||||
*/
|
||||
update: function as_update(serviceId, apnType, apn) {
|
||||
var apnClone = ApnUtils.clone(apn);
|
||||
return this._schedule(
|
||||
this._update.bind(this, serviceId, apnType, apnClone));
|
||||
},
|
||||
|
||||
/**
|
||||
* Restore the apn settings to the default value determined in
|
||||
* system/js/operator_variants.js.
|
||||
*
|
||||
* @access public
|
||||
* @memberOf ApnSettings.prototype
|
||||
* @params {String} serviceId
|
||||
* @returns {Promise}
|
||||
*/
|
||||
restore: function as_restore(serviceId) {
|
||||
var that = this;
|
||||
return this._ready().then(function() {
|
||||
return new Promise(function(resolve) {
|
||||
SettingsCache.getSettings(function(results) {
|
||||
resolve(results[DEFAULT_APN_SETTINGS_KEY] || []);
|
||||
});
|
||||
});
|
||||
}).then(function(defaultApnSettings) {
|
||||
return that._schedule(function() {
|
||||
that._isDirty = true;
|
||||
that._apnSettings[serviceId] = defaultApnSettings[serviceId];
|
||||
return Promise.resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
return function ctor_apn_settings() {
|
||||
return new ApnSettings();
|
||||
};
|
||||
});
|
||||
482
gaia/apps/settings/js/modules/apn/apn_settings_manager.js
Executable file
482
gaia/apps/settings/js/modules/apn/apn_settings_manager.js
Executable file
|
|
@ -0,0 +1,482 @@
|
|||
/**
|
||||
* ApnSettingsManager provides functions for managing apn items. When an item
|
||||
* is selected to be used, ApnSettingsManager also helps convert the selection
|
||||
* to the real settings expected by the platform.
|
||||
* ApnSettingsManager does its task by coordinating the following objects:
|
||||
* - ApnList
|
||||
* There is an ApnList object for each sim. ApnList stores ApnItem objects
|
||||
* representing apns come from the apn.json database, client provisioning
|
||||
* messages, and user's creation. Each ApnItem has an id assigned upon
|
||||
* the creation. The id is used to recored users' apn selection.
|
||||
* - ApnSelections
|
||||
* ApnSelections stores the id of the apn being used on each apn
|
||||
* type.
|
||||
* - ApnSettings
|
||||
* ApnSettings wraps the apn settings stored in the moz settings database
|
||||
* and provides simple interface for manipulation.
|
||||
* Implementation details please refer to {@link ApnSettingsManager}.
|
||||
*
|
||||
* @module modules/apn/apn_settings_manager
|
||||
*/
|
||||
define(function(require) {
|
||||
'use strict';
|
||||
|
||||
var AsyncStorage = require('modules/async_storage');
|
||||
var ApnConst = require('modules/apn/apn_const');
|
||||
var ApnUtils = require('modules/apn/apn_utils');
|
||||
var ApnItem = require('modules/apn/apn_item');
|
||||
var ApnSettings = require('modules/apn/apn_settings');
|
||||
var ApnList = require('modules/apn/apn_list');
|
||||
var ApnSelections = require('modules/apn/apn_selections');
|
||||
|
||||
var APN_TYPES = ApnConst.APN_TYPES;
|
||||
var APN_LIST_KEY = ApnConst.APN_LIST_KEY;
|
||||
var CACHED_ICCIDS_KEY = ApnConst.CACHED_ICCIDS_KEY;
|
||||
|
||||
var RESTORE_MODE = {
|
||||
ALL: 0,
|
||||
ONLY_APN_ITEMS: 1,
|
||||
};
|
||||
|
||||
/**
|
||||
* @class ApnSettingsManager
|
||||
* @requires module:modules/async_storage
|
||||
* @requires module:modules/apn/apn_const
|
||||
* @requires module:modules/apn/apn_utils
|
||||
* @requires module:modules/apn/apn_item
|
||||
* @requires module:modules/apn/apn_settings
|
||||
* @requires module:modules/apn/apn_list
|
||||
* @requires module:modules/apn/apn_selections
|
||||
* @returns {ApnSettingsManager}
|
||||
*/
|
||||
function ApnSettingsManager() {
|
||||
this._apnLists = {};
|
||||
this._apnSelections = ApnSelections();
|
||||
this._apnSettings = ApnSettings();
|
||||
|
||||
this._readyPromises = {};
|
||||
|
||||
Object.defineProperty(this, 'RESTORE_MODE', {
|
||||
configurable: false,
|
||||
get: function() {
|
||||
return RESTORE_MODE;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
ApnSettingsManager.prototype = {
|
||||
/**
|
||||
* Ensures the current apn items are up-to-date. When the current apn
|
||||
* id does not equal to the cached apn id, we should restore the apn items.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf ApnSettingsManager.prototype
|
||||
* @param {Number} serviceId
|
||||
* @returns {Promise}
|
||||
*/
|
||||
_ready: function asc_fromItems(serviceId) {
|
||||
if (!this._readyPromises[serviceId]) {
|
||||
// Check if a new icc card is detected.
|
||||
this._readyPromises[serviceId] = AsyncStorage.getItem(CACHED_ICCIDS_KEY)
|
||||
.then((cachedIccIds) => {
|
||||
var cachedIccId = cachedIccIds && cachedIccIds[serviceId];
|
||||
var curIccId = navigator.mozMobileConnections[serviceId].iccId;
|
||||
if (!curIccId || curIccId === cachedIccId) {
|
||||
return;
|
||||
}
|
||||
|
||||
cachedIccIds = cachedIccIds || {};
|
||||
cachedIccIds[serviceId] = curIccId;
|
||||
// Get the default preset apns by restoring.
|
||||
return Promise.all([
|
||||
// In this case we only restore apn items but not apn settings.
|
||||
this.restore(serviceId, RESTORE_MODE.ONLY_APN_ITEMS),
|
||||
AsyncStorage.setItem(CACHED_ICCIDS_KEY, cachedIccIds)
|
||||
]);
|
||||
});
|
||||
}
|
||||
return this._readyPromises[serviceId];
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns the id of the first preset apn item.
|
||||
*
|
||||
* @param {Number} serviceId
|
||||
* @param {String} apnType
|
||||
* @returns {Promise.<String>}
|
||||
*/
|
||||
_deriveActiveApnIdFromItems: function asc_fromItems(serviceId, apnType) {
|
||||
return this._apnItems(serviceId, apnType).then(function(apnItems) {
|
||||
if (apnItems.length) {
|
||||
return apnItems.sort(ApnUtils.sortByCategory)[0].id;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns the id of the apn item that matches the current apn setting of
|
||||
* the specified apn type.
|
||||
*
|
||||
* @param {Number} serviceId
|
||||
* @param {String} apnType
|
||||
* @returns {Promise.<String>}
|
||||
*/
|
||||
_deriveActiveApnIdFromSettings:
|
||||
function asc_deriveFromSettings(serviceId, apnType) {
|
||||
return Promise.all([
|
||||
this._apnItems(serviceId, apnType),
|
||||
this._apnSettings.get(serviceId, apnType)
|
||||
]).then(function(results) {
|
||||
var apnItems = results[0];
|
||||
var apnInUse = results[1];
|
||||
// apnInUse is the apn that RIL is currently using.
|
||||
if (apnInUse) {
|
||||
var matchedApnItem = apnItems.find(function(apnItem) {
|
||||
return ApnUtils.isMatchedApn(apnItem.apn, apnInUse);
|
||||
});
|
||||
if (matchedApnItem) {
|
||||
// Has matched apn in the existing apns.
|
||||
return matchedApnItem.id;
|
||||
} else {
|
||||
var category = (apnInUse.carrier === '_custom_') ?
|
||||
ApnItem.APN_CATEGORY.CUSTOM : ApnItem.APN_CATEGORY.PRESET;
|
||||
return this.addApn(serviceId, apnInUse, category);
|
||||
}
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}.bind(this));
|
||||
},
|
||||
|
||||
/**
|
||||
* Return the apn type an apn that is actively being used for.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf ApnSettingsManager.prototype
|
||||
* @param {Number} serviceId
|
||||
* @param {String} apnId
|
||||
* id of the apn being checked.
|
||||
* @returns {Promise.<String>}
|
||||
*/
|
||||
_getApnAppliedType: function asc_getApnAppliedType(serviceId, apnId) {
|
||||
return this._apnSelections.get(serviceId).then(function(apnSelection) {
|
||||
return APN_TYPES.find((apnType) => apnSelection[apnType] === apnId);
|
||||
}.bind(this));
|
||||
},
|
||||
|
||||
/**
|
||||
* Store the current apn selection to apn settings to the settings database.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf ApnSettingsManager.prototype
|
||||
* @param {Number} serviceId
|
||||
* @param {String} apnType
|
||||
*/
|
||||
_storeApnSettingByType: function asc_storeApnByType(serviceId, apnType) {
|
||||
return this._apnSelections.get(serviceId).then(function(apnSelection) {
|
||||
var apnList = this._apnList(serviceId);
|
||||
var apnId = apnSelection[apnType];
|
||||
if (apnId) {
|
||||
// Get the apn item of apnType.
|
||||
return apnList.item(apnId);
|
||||
}
|
||||
}.bind(this)).then(function(apnItem) {
|
||||
if (apnItem) {
|
||||
return this._apnSettings.update(serviceId, apnType, apnItem.apn);
|
||||
} else {
|
||||
return this._apnSettings.update(serviceId, apnType, null);
|
||||
}
|
||||
}.bind(this));
|
||||
},
|
||||
|
||||
/**
|
||||
* Get the apn item list of a sim slot.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf ApnSettingsManager.prototype
|
||||
* @param {Number} serviceId
|
||||
* @returns {ApnList} The apn item list.
|
||||
*/
|
||||
_apnList: function asc_apnList(serviceId) {
|
||||
var apnList = this._apnLists[serviceId];
|
||||
if (!apnList) {
|
||||
this._apnLists[serviceId] = apnList = ApnList(APN_LIST_KEY + serviceId);
|
||||
}
|
||||
return apnList;
|
||||
},
|
||||
|
||||
/**
|
||||
* Get the apn items of an apn type for a sim slot.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf ApnSettingsManager.prototype
|
||||
* @param {Number} serviceId
|
||||
* @param {String} apnType
|
||||
* @returns {Promise.<Array.<ApnItem>>} The apn items.
|
||||
*/
|
||||
_apnItems: function asc_apnItems(serviceId, apnType) {
|
||||
return this._ready(serviceId).then(() => {
|
||||
return this._apnList(serviceId).items();
|
||||
}).then((apnItems) => {
|
||||
return apnItems &&
|
||||
apnItems.filter(ApnUtils.apnTypeFilter.bind(null, apnType)) || [];
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Restore the apn items of a category.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf ApnSettingsManager.prototype
|
||||
* @param {ApnList} apnList
|
||||
* @param {Array<Object>} apnsForRestoring
|
||||
* The function use this to restore the apn items.
|
||||
* @param {ApnItem.APN_CATEGORY} category
|
||||
* The category of the items to be resotred.
|
||||
* @returns {Promise.<Array.<String>>} The id of the restored apn items.
|
||||
*/
|
||||
_restoreApnItemsOfCategory:
|
||||
function asc_restoreApnItems(apnList, apnsForRestoring, category) {
|
||||
return apnList.items().then(function(apnItems) {
|
||||
// Remove all existing preset apns.
|
||||
apnItems = apnItems || [];
|
||||
var promises = [];
|
||||
apnItems.filter(function(apnItem) {
|
||||
if (apnItem.category === category) {
|
||||
return true;
|
||||
}
|
||||
}).forEach(function(apnItem) {
|
||||
promises.push(apnList.remove(apnItem.id));
|
||||
});
|
||||
|
||||
return Promise.all(promises);
|
||||
}).then(function() {
|
||||
// Add default preset apns.
|
||||
var promises = [];
|
||||
apnsForRestoring.forEach(function(apns) {
|
||||
promises.push(apnList.add(apns, category));
|
||||
});
|
||||
return Promise.all(promises);
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Restore the apn items and apn settings to the default. Only apn items of
|
||||
* the category ApnItem.APN_CATEGORY.PRESET and ApnItem.APN_CATEGORY.EU are
|
||||
* restored. User created apn items (custom apns) will not be affected. The
|
||||
* preset apn items are from the apn.json database and client provisioning
|
||||
* messages.
|
||||
*
|
||||
* @access public
|
||||
* @memberOf ApnSettingsManager.prototype
|
||||
* @param {String} serviceId
|
||||
* @param {Number} mode
|
||||
* The possible values are defined in RESTORE_MODE. We
|
||||
* restore both apn items and apn settings by default. Only
|
||||
* apn items are restored when mode is
|
||||
* RESTORE_MODE.ONLY_APN_ITEMS.
|
||||
* @returns {Promise}
|
||||
*/
|
||||
restore: function asc_restore(serviceId, mode) {
|
||||
var mobileConnection = navigator.mozMobileConnections[serviceId];
|
||||
var networkType = mobileConnection.data.type;
|
||||
var apnList = this._apnList(serviceId);
|
||||
var that = this;
|
||||
|
||||
return Promise.all([
|
||||
ApnUtils.getOperatorCode(serviceId, 'mcc'),
|
||||
ApnUtils.getOperatorCode(serviceId, 'mnc')
|
||||
]).then(function(values) {
|
||||
// Get default apns and client provisioning apns matching the mcc/mnc
|
||||
// codes.
|
||||
var mcc = values[0];
|
||||
var mnc = values[1];
|
||||
|
||||
return Promise.all([
|
||||
ApnUtils.getEuApns(),
|
||||
ApnUtils.getDefaultApns(mcc, mnc, networkType),
|
||||
ApnUtils.getCpApns(mcc, mnc, networkType)
|
||||
]);
|
||||
}).then(function(results) {
|
||||
// Restore preset and eu apns.
|
||||
var euApns = ApnUtils.separateApnsByType(results[0]);
|
||||
var presetApns = ApnUtils.separateApnsByType(
|
||||
Array.prototype.concat.apply([], results.slice(1)));
|
||||
|
||||
return that._restoreApnItemsOfCategory(
|
||||
apnList, euApns, ApnItem.APN_CATEGORY.EU)
|
||||
.then(function() {
|
||||
return that._restoreApnItemsOfCategory(
|
||||
apnList, presetApns, ApnItem.APN_CATEGORY.PRESET);
|
||||
});
|
||||
}).then(function() {
|
||||
// We simply clear the apn selections. The selections will be restored
|
||||
// based on the current apn settings when it is being queried.
|
||||
return that._apnSelections.clear(serviceId);
|
||||
}).then(function() {
|
||||
if (mode !== RESTORE_MODE.ONLY_APN_ITEMS) {
|
||||
return that._apnSettings.restore(serviceId);
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Query apn items matching the mcc/mnc codes in the apn.json
|
||||
* database and the one received through client provisioning messages.
|
||||
*
|
||||
* @access public
|
||||
* @memberOf ApnSettingsManager.prototype
|
||||
* @param {Number} serviceId
|
||||
* @param {String} apnType
|
||||
* @returns {Promise.<Array.<ApnItem>>} The apn items
|
||||
*/
|
||||
queryApns: function asc_queryApns(serviceId, apnType) {
|
||||
return this.getActiveApnId(serviceId, apnType)
|
||||
.then(function(activeApnId) {
|
||||
return this._apnItems(serviceId, apnType).then(function(items) {
|
||||
items.forEach(function(apnItem) {
|
||||
apnItem.active = (apnItem.id === activeApnId);
|
||||
});
|
||||
return items;
|
||||
});
|
||||
}.bind(this));
|
||||
},
|
||||
|
||||
/**
|
||||
* Add an apn to a sim slot.
|
||||
*
|
||||
* @access public
|
||||
* @memberOf ApnSettingsManager.prototype
|
||||
* @param {Number} serviceId
|
||||
* @param {Object} apn
|
||||
* @param {ApnItem.APN_CATEGORY} category
|
||||
* @returns {Promise}
|
||||
*/
|
||||
addApn: function asc_addApn(serviceId, apn, category) {
|
||||
return this._ready(serviceId).then(() => {
|
||||
return this._apnList(serviceId).add(apn,
|
||||
category || ApnItem.APN_CATEGORY.CUSTOM);
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Remove an apn from a sim slot.
|
||||
*
|
||||
* @access public
|
||||
* @memberOf ApnSettingsManager.prototype
|
||||
* @param {Number} serviceId
|
||||
* @param {String} id
|
||||
* id of the apn item to be added.
|
||||
* @returns {Promise}
|
||||
*/
|
||||
removeApn: function asc_removeApn(serviceId, id) {
|
||||
return this._ready(serviceId).then(() => {
|
||||
return this._apnList(serviceId).remove(id);
|
||||
}).then(() => {
|
||||
// check if the removed apn is actively being used.
|
||||
return this._getApnAppliedType(serviceId, id);
|
||||
}).then((matchedApnType) => {
|
||||
if (matchedApnType) {
|
||||
return this._deriveActiveApnIdFromItems(serviceId, matchedApnType)
|
||||
.then((activeApnId) => {
|
||||
return this.setActiveApnId(serviceId, matchedApnType, activeApnId);
|
||||
});
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Update an apn item.
|
||||
*
|
||||
* @access public
|
||||
* @memberOf ApnSettingsManager.prototype
|
||||
* @param {Number} serviceId
|
||||
* @param {String} id
|
||||
* id of the apn item to be updated.
|
||||
* @param {Object} apn
|
||||
* @returns {Promise}
|
||||
*/
|
||||
updateApn: function asc_updateApn(serviceId, id, apn) {
|
||||
return this._ready(serviceId).then(() => {
|
||||
return this._apnList(serviceId).update(id, apn);
|
||||
}).then(() => {
|
||||
// check if the updated apn is actively being used.
|
||||
return this._getApnAppliedType(serviceId, id);
|
||||
}).then((matchedApnType) => {
|
||||
if (matchedApnType) {
|
||||
return this._storeApnSettingByType(serviceId, matchedApnType);
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Get the id of the apn that is actively being used for an apn type.
|
||||
*
|
||||
* @access public
|
||||
* @memberOf ApnSettingsManager.prototype
|
||||
* @param {Number} serviceId
|
||||
* @param {String} apnType
|
||||
* @returns {Promise.<String>}
|
||||
*/
|
||||
getActiveApnId: function asc_getActiveApnId(serviceId, apnType) {
|
||||
var that = this;
|
||||
return this._ready(serviceId).then(function() {
|
||||
return that._apnSelections.get(serviceId);
|
||||
}).then(function(apnSelection) {
|
||||
return apnSelection && apnSelection[apnType];
|
||||
}).then(function(activeApnId) {
|
||||
if (activeApnId) {
|
||||
return activeApnId;
|
||||
} else {
|
||||
// If there is no existing active apn id, try to derive the id from
|
||||
// the current apn settings.
|
||||
return that._deriveActiveApnIdFromSettings(serviceId, apnType)
|
||||
.then(function(apnId) {
|
||||
// Set the id as the active apn id.
|
||||
that.setActiveApnId(serviceId, apnType, apnId);
|
||||
return apnId;
|
||||
});
|
||||
}
|
||||
}).then(function(activeApnId) {
|
||||
// If there is still no active apn id, means that the apn settings have
|
||||
// not been set and we need to derive a default id from the current apn
|
||||
// items (stored in the apn list).
|
||||
if (activeApnId) {
|
||||
return activeApnId;
|
||||
} else {
|
||||
return that._deriveActiveApnIdFromItems(serviceId, apnType)
|
||||
.then(function(apnId) {
|
||||
// Set the id as the active apn id.
|
||||
that.setActiveApnId(serviceId, apnType, apnId);
|
||||
return apnId;
|
||||
});
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Set the id of an apn that is to be used for an apn type.
|
||||
*
|
||||
* @access public
|
||||
* @memberOf ApnSettingsManager.prototype
|
||||
* @param {Number} serviceId
|
||||
* @param {String} apnType
|
||||
* @param {String} id
|
||||
* @returns {Promise}
|
||||
*/
|
||||
setActiveApnId: function asc_setActiveApnId(serviceId, apnType, id) {
|
||||
return this._ready(serviceId).then(() => {
|
||||
return this._apnSelections.get(serviceId);
|
||||
}).then((apnSelection) => {
|
||||
if (apnSelection[apnType] !== id) {
|
||||
apnSelection[apnType] = id;
|
||||
return this._storeApnSettingByType(serviceId, apnType);
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
return new ApnSettingsManager();
|
||||
});
|
||||
200
gaia/apps/settings/js/modules/apn/apn_utils.js
Executable file
200
gaia/apps/settings/js/modules/apn/apn_utils.js
Executable file
|
|
@ -0,0 +1,200 @@
|
|||
/**
|
||||
* The apn utilities
|
||||
*/
|
||||
define(function(require) {
|
||||
'use strict';
|
||||
|
||||
var SettingsCache = require('modules/settings_cache');
|
||||
var ApnHelper = require('shared/apn_helper');
|
||||
var ApnConst = require('modules/apn/apn_const');
|
||||
var ApnItem = require('modules/apn/apn_item');
|
||||
var LazyLoader = require('shared/lazy_loader');
|
||||
|
||||
var CP_APN_KEY = ApnConst.CP_APN_KEY;
|
||||
var DEFAULT_APN_KEY = ApnConst.DEFAULT_APN_KEY;
|
||||
var MCC_SETTINGS_KEY = ApnConst.MCC_SETTINGS_KEY;
|
||||
var MNC_SETTINGS_KEY = ApnConst.MNC_SETTINGS_KEY;
|
||||
var APN_PROPS = ApnConst.APN_PROPS;
|
||||
var EU_ROAMING_FILE_PATH = ApnConst.EU_ROAMING_FILE_PATH;
|
||||
|
||||
function _getOperatorCode(serviceId, type) {
|
||||
var value;
|
||||
var key;
|
||||
|
||||
if (type === 'mcc') {
|
||||
value = '000';
|
||||
key = MCC_SETTINGS_KEY;
|
||||
} else if (type === 'mnc') {
|
||||
value = '00';
|
||||
key = MNC_SETTINGS_KEY;
|
||||
} else {
|
||||
return Promise.reject('invalid type');
|
||||
}
|
||||
|
||||
return new Promise(function(resolve, reject) {
|
||||
SettingsCache.getSettings(function(results) {
|
||||
var values = results[key];
|
||||
if (values && Array.isArray(values) && values[serviceId]) {
|
||||
value = values[serviceId];
|
||||
}
|
||||
resolve(value);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function. Filter APNs by apn type.
|
||||
*
|
||||
* @param {String} type
|
||||
* The apn type we would like to include.
|
||||
* @param {ApnItem} apnItem
|
||||
*/
|
||||
function _apnTypeFilter(type, apnItem) {
|
||||
if (!type || !apnItem || !apnItem.apn.types) {
|
||||
return false;
|
||||
} else if (type === '*') {
|
||||
return true;
|
||||
}
|
||||
return apnItem.apn.types.indexOf(type) != -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Query <apn> elements matching the mcc/mnc arguments in the apn.json
|
||||
* database
|
||||
*
|
||||
* @param {String} mcc
|
||||
* @param {String} mnc
|
||||
* @param {String} networkType
|
||||
* The network type which the APN must be compatible with.
|
||||
*/
|
||||
function _getDefaultApns(mcc, mnc, networkType) {
|
||||
// XXX: should fallback to the JSON file if we don't get the apns
|
||||
return new Promise(function(resolve, reject) {
|
||||
SettingsCache.getSettings(function(results) {
|
||||
var apns = results[DEFAULT_APN_KEY] || {};
|
||||
resolve(ApnHelper.getCompatible(apns, mcc, mnc, networkType));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Query <apn> elements matching the mcc/mnc arguments in the database
|
||||
* received through client provisioning messages.
|
||||
*
|
||||
* @param {String} mcc
|
||||
* @param {String} mnc
|
||||
* @param {String} networkType
|
||||
* The network type which the APN must be compatible with.
|
||||
*/
|
||||
function _getCpApns(mcc, mnc, networkType) {
|
||||
return new Promise(function(resolve, reject) {
|
||||
SettingsCache.getSettings(function(results) {
|
||||
var apns = results[CP_APN_KEY] || {};
|
||||
resolve(ApnHelper.getCompatible(apns, mcc, mnc, networkType));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
var _euApnChecked = false;
|
||||
var _euApns = null;
|
||||
/**
|
||||
* Return the EU apns for roaming.
|
||||
*/
|
||||
function _getEuApns() {
|
||||
if (_euApnChecked) {
|
||||
return Promise.resolve(_euApns);
|
||||
} else {
|
||||
return LazyLoader.getJSON(EU_ROAMING_FILE_PATH).then(function(result) {
|
||||
_euApnChecked = true;
|
||||
// Only return eu apns when both home and foreign operators are
|
||||
// specified.
|
||||
if (result.home && result.foreign &&
|
||||
Object.keys(result.home).length > 0 &&
|
||||
Object.keys(result.foreign).length > 0) {
|
||||
_euApns = result.defaultApns;
|
||||
}
|
||||
return _euApns;
|
||||
}).catch(function() {
|
||||
_euApnChecked = true;
|
||||
return null;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function _generateId() {
|
||||
// should refine this
|
||||
return Math.random().toString(36).substr(2, 9);
|
||||
}
|
||||
|
||||
function _cloneApn(apn) {
|
||||
var newApn = {};
|
||||
for (var p in apn) {
|
||||
newApn[p] = apn[p];
|
||||
}
|
||||
return newApn;
|
||||
}
|
||||
|
||||
function _separateApnsByType(apns) {
|
||||
if (!apns) {
|
||||
return [];
|
||||
}
|
||||
return apns.reduce(function(result, apn) {
|
||||
// separate the apn by type
|
||||
apn.types.forEach(function(type) {
|
||||
var cloneApn = _cloneApn(apn);
|
||||
cloneApn.types = [type];
|
||||
result.push(cloneApn);
|
||||
});
|
||||
return result;
|
||||
}, []);
|
||||
}
|
||||
|
||||
function _isMatchedApn(apn1, apn2) {
|
||||
if (apn1 == null || apn2 == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if the type of apn1 is the subset of apn2
|
||||
if (!apn1.types.every(function(type) {
|
||||
return (apn2.types.indexOf(type) !== -1);
|
||||
})) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return APN_PROPS.every(function(prop) {
|
||||
if (prop === 'types') {
|
||||
// we've already check this property
|
||||
return true;
|
||||
} else {
|
||||
return apn1[prop] === apn2[prop];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function _sortByCategory(apn1, apn2) {
|
||||
if (apn1.category === ApnItem.APN_CATEGORY.PRESET) {
|
||||
return true;
|
||||
} else if (apn2.category === ApnItem.APN_CATEGORY.PRESET) {
|
||||
return false;
|
||||
} else {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
function _clone(apn) {
|
||||
return JSON.parse(JSON.stringify(apn));
|
||||
}
|
||||
|
||||
return {
|
||||
getOperatorCode: _getOperatorCode,
|
||||
apnTypeFilter: _apnTypeFilter,
|
||||
getDefaultApns: _getDefaultApns,
|
||||
getCpApns: _getCpApns,
|
||||
getEuApns: _getEuApns,
|
||||
generateId: _generateId,
|
||||
separateApnsByType: _separateApnsByType,
|
||||
isMatchedApn: _isMatchedApn,
|
||||
sortByCategory: _sortByCategory,
|
||||
clone: _clone
|
||||
};
|
||||
});
|
||||
25
gaia/apps/settings/js/modules/app.js
Executable file
25
gaia/apps/settings/js/modules/app.js
Executable file
|
|
@ -0,0 +1,25 @@
|
|||
define(function(require) {
|
||||
'use strict';
|
||||
|
||||
var Module = require('modules/base/module');
|
||||
var Observable = require('modules/mvvm/observable');
|
||||
|
||||
var App = Module.create(function App(app) {
|
||||
this.super(Observable).call(this);
|
||||
this._app = app;
|
||||
this._enabled = app.enabled;
|
||||
}).extend(Observable);
|
||||
|
||||
Observable.defineObservableProperty(App.prototype, 'enabled', {
|
||||
readonly: true
|
||||
});
|
||||
|
||||
Object.defineProperty(App.prototype, 'instance', {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return this._app;
|
||||
}
|
||||
});
|
||||
|
||||
return App;
|
||||
});
|
||||
92
gaia/apps/settings/js/modules/app_storage.js
Executable file
92
gaia/apps/settings/js/modules/app_storage.js
Executable file
|
|
@ -0,0 +1,92 @@
|
|||
/**
|
||||
* AppStorage is a singleton that caches app storage values for
|
||||
* app storage and root panel fast access
|
||||
*/
|
||||
define(function(require) {
|
||||
'use strict';
|
||||
|
||||
var Module = require('modules/base/module');
|
||||
var Observable = require('modules/mvvm/observable');
|
||||
|
||||
/**
|
||||
* @class AppStorage
|
||||
* @requires module:modules/base/module
|
||||
* @requires module:modules/mvvm/observable
|
||||
* @returns {AppStorage}
|
||||
*/
|
||||
var AppStorage = Module.create(function AppStorage() {
|
||||
this.super(Observable).call(this);
|
||||
this._appStorage = navigator.getDeviceStorage('apps');
|
||||
|
||||
this._attachListeners();
|
||||
this._getSpaceInfo();
|
||||
}).extend(Observable);
|
||||
|
||||
Observable.defineObservableProperty(AppStorage.prototype,
|
||||
'usedPercentage', {
|
||||
readonly: true,
|
||||
value: 0
|
||||
});
|
||||
|
||||
Observable.defineObservableProperty(AppStorage.prototype,
|
||||
'totalSize', {
|
||||
readonly: true,
|
||||
value: 0
|
||||
});
|
||||
|
||||
Observable.defineObservableProperty(AppStorage.prototype,
|
||||
'usedSize', {
|
||||
readonly: true,
|
||||
value: 0
|
||||
});
|
||||
|
||||
Observable.defineObservableProperty(AppStorage.prototype,
|
||||
'freeSize', {
|
||||
readonly: true,
|
||||
value: 0
|
||||
});
|
||||
|
||||
|
||||
AppStorage.prototype.updateInfo = function as_updateInfo() {
|
||||
this._getSpaceInfo();
|
||||
};
|
||||
|
||||
AppStorage.prototype._attachListeners = function as_attachListeners() {
|
||||
this._appStorage.addEventListener('change', this);
|
||||
};
|
||||
|
||||
AppStorage.prototype.handleEvent = function as_handler(evt) {
|
||||
switch (evt.type) {
|
||||
case 'change':
|
||||
this._getSpaceInfo();
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
AppStorage.prototype._getSpaceInfo = function as_getSpaceInfo() {
|
||||
var deviceStorage = this._appStorage;
|
||||
|
||||
if (!deviceStorage) {
|
||||
console.error('Cannot get DeviceStorage for: app');
|
||||
return;
|
||||
}
|
||||
deviceStorage.freeSpace().onsuccess = (e) => {
|
||||
this._freeSize = e.target.result;
|
||||
deviceStorage.usedSpace().onsuccess = (e) => {
|
||||
this._usedSize = e.target.result;
|
||||
// calculate the percentage to show a space usage bar
|
||||
this._totalSize =
|
||||
this._usedSize + this._freeSize;
|
||||
var usedPercentage = (this._totalSize === 0) ?
|
||||
0 : (this._usedSize * 100 / this._totalSize);
|
||||
if (usedPercentage > 100) {
|
||||
usedPercentage = 100;
|
||||
}
|
||||
this._usedPercentage = usedPercentage;
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
return AppStorage();
|
||||
});
|
||||
|
||||
166
gaia/apps/settings/js/modules/apps_cache.js
Executable file
166
gaia/apps/settings/js/modules/apps_cache.js
Executable file
|
|
@ -0,0 +1,166 @@
|
|||
/**
|
||||
* AppsCache is a singleton that will encapsulate mozApps.mgmt inside and
|
||||
* expose neede API to callers. The reason why we need this is because
|
||||
* mozApps.mgmt.getAll() costs a lot and the better way to do so is cache
|
||||
* them inside this AppManager and automatically update it when install /
|
||||
* uninstall event is received.
|
||||
*
|
||||
* API:
|
||||
*
|
||||
* AppsCache.apps().then(function(apps) {
|
||||
* // installed apps in FxOS
|
||||
* });
|
||||
*
|
||||
* @module AppsCache
|
||||
*/
|
||||
define(function(require) {
|
||||
'use strict';
|
||||
|
||||
var mozApps = window.navigator.mozApps;
|
||||
var mozAppsMgmt = mozApps && mozApps.mgmt;
|
||||
|
||||
var AppsCache = function() {
|
||||
this._initPromise = null;
|
||||
this._apps = [];
|
||||
this._eventHandlers = {};
|
||||
this._eventHandlers.oninstall = [];
|
||||
this._eventHandlers.onuninstall = [];
|
||||
};
|
||||
|
||||
AppsCache.prototype = {
|
||||
/**
|
||||
* apps is a method that would return a promise that would return
|
||||
* cached apps.
|
||||
*
|
||||
* @access public
|
||||
* @memberOf AppsCache
|
||||
* @return {Promise}
|
||||
*/
|
||||
apps: function am_apps() {
|
||||
var self = this;
|
||||
return this._init().then(function() {
|
||||
return self._apps;
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Entry point
|
||||
*
|
||||
* @access private
|
||||
* @memberOf AppsCache
|
||||
* @return {Promise}
|
||||
*/
|
||||
_init: function am__init() {
|
||||
var self = this;
|
||||
if (!this._initPromise) {
|
||||
this._initPromise = this._initApps().then(function() {
|
||||
self._initEvents();
|
||||
});
|
||||
}
|
||||
return this._initPromise;
|
||||
},
|
||||
|
||||
/**
|
||||
* Init needed events
|
||||
*
|
||||
* @access private
|
||||
* @memberOf AppsCache
|
||||
*/
|
||||
_initEvents: function am__initEvents() {
|
||||
var self = this;
|
||||
|
||||
mozAppsMgmt.oninstall = function(evt) {
|
||||
var newApp = evt.application;
|
||||
var existing = false;
|
||||
self._apps.some((app, i) => {
|
||||
if (app.manifestURL === newApp.manifestURL) {
|
||||
self._apps[i] = newApp;
|
||||
existing = true;
|
||||
return true;
|
||||
}
|
||||
});
|
||||
|
||||
if (!existing) {
|
||||
self._apps.push(newApp);
|
||||
}
|
||||
self._eventHandlers.oninstall.forEach(function(eventHandler) {
|
||||
eventHandler(evt);
|
||||
});
|
||||
};
|
||||
|
||||
mozAppsMgmt.onuninstall = function(evt) {
|
||||
var manifestURL = evt.application.manifestURL;
|
||||
var appRemoved = false;
|
||||
self._apps = self._apps.filter(app => {
|
||||
if (app.manifestURL === manifestURL) {
|
||||
appRemoved = true;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
if (appRemoved) {
|
||||
self._eventHandlers.onuninstall.forEach(function(eventHandler) {
|
||||
eventHandler(evt);
|
||||
});
|
||||
}
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
* Init apps
|
||||
*
|
||||
* @access private
|
||||
* @memberOf AppsCache
|
||||
*/
|
||||
_initApps: function am__initApps() {
|
||||
var self = this;
|
||||
var promise = new Promise(function(resolve, reject) {
|
||||
var req = mozAppsMgmt.getAll();
|
||||
req.onsuccess = function success(evt) {
|
||||
self._apps = evt.target.result;
|
||||
resolve(self._apps);
|
||||
};
|
||||
req.onerror = function error(evt) {
|
||||
console.log('failed to get installed apps');
|
||||
reject(req.error);
|
||||
};
|
||||
});
|
||||
return promise;
|
||||
},
|
||||
|
||||
/**
|
||||
* Caller can add events when app is installed/uninstalled
|
||||
*
|
||||
* @access public
|
||||
* @param {String} eventName
|
||||
* @param {Function} callback
|
||||
* @memberOf AppsCache
|
||||
*/
|
||||
addEventListener: function am_addEventListener(eventName, callback) {
|
||||
if (this._eventHandlers[eventName]) {
|
||||
this._eventHandlers[eventName].push(callback);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Caller can remove events when app is installed/uninstalled
|
||||
*
|
||||
* @access public
|
||||
* @param {String} eventName
|
||||
* @param {Function} callback
|
||||
* @memberOf AppsCache
|
||||
*/
|
||||
removeEventListener: function am_removeEventListener(eventName, callback) {
|
||||
if (this._eventHandlers[eventName]) {
|
||||
var index = this._eventHandlers[eventName].indexOf(callback);
|
||||
if (index >= 0) {
|
||||
this._eventHandlers[eventName].splice(index, 1);
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
var appsCache = new AppsCache();
|
||||
return appsCache;
|
||||
});
|
||||
21
gaia/apps/settings/js/modules/async_storage.js
Executable file
21
gaia/apps/settings/js/modules/async_storage.js
Executable file
|
|
@ -0,0 +1,21 @@
|
|||
/**
|
||||
* The promise version of async storage.
|
||||
*/
|
||||
define(function(require) {
|
||||
'use strict';
|
||||
|
||||
var AsyncStorage = require('shared/async_storage');
|
||||
|
||||
return {
|
||||
getItem: function as_getItem(key) {
|
||||
return new Promise(function(resolve, reject) {
|
||||
AsyncStorage.getItem(key, resolve);
|
||||
});
|
||||
},
|
||||
setItem: function as_setItem(key, value) {
|
||||
return new Promise(function(resolve, reject) {
|
||||
AsyncStorage.setItem(key, value, resolve);
|
||||
});
|
||||
}
|
||||
};
|
||||
});
|
||||
137
gaia/apps/settings/js/modules/base/dependency_graph.js
Executable file
137
gaia/apps/settings/js/modules/base/dependency_graph.js
Executable file
|
|
@ -0,0 +1,137 @@
|
|||
/**
|
||||
* DependencyGraph is a basic data structure that helps decide the evaluation
|
||||
* order of a certain node.
|
||||
*
|
||||
* @module modules/base/dependency_graph
|
||||
*/
|
||||
define(function(require) {
|
||||
'use strict';
|
||||
|
||||
var Module = require('modules/base/module');
|
||||
|
||||
/**
|
||||
* @class DependencyGraph
|
||||
* @requires module:modules/base/module
|
||||
* @params {DependencyGraph} dpGraph
|
||||
* The newly created graph will be initialized using
|
||||
* dpGraph.
|
||||
* @returns {DependencyGraph}
|
||||
*/
|
||||
var DependencyGraph = Module.create(function DependencyGraph(dpGraph) {
|
||||
this._nodes = dpGraph ? JSON.parse(JSON.stringify(dpGraph._nodes)) : {};
|
||||
});
|
||||
|
||||
/**
|
||||
* Print the content of the nodes for debugging.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf DependencyGraph.prototype
|
||||
*/
|
||||
DependencyGraph.prototype._printNodes = function dg_printNodes() {
|
||||
Object.keys(this._nodes).forEach((name) => {
|
||||
var node = this._nodes[name];
|
||||
console.log('name: ' + name);
|
||||
console.log('children: ' +
|
||||
node.children.reduce((result, name) => {
|
||||
return result + ' ' + name;
|
||||
}, ''));
|
||||
console.log('dependent nodes: ' +
|
||||
node.dependentNodes.reduce((result, name) => {
|
||||
return result + ' ' + name;
|
||||
}, ''));
|
||||
console.log('======================');
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Traverse the tree and add the dependent nodes to all nodes in the path.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf DependencyGraph.prototype
|
||||
* @param {Object} node
|
||||
* The node that we have new dependent nodes to add to.
|
||||
* @param {Array} dependentNodes
|
||||
* New dependent nodes to add.
|
||||
*/
|
||||
DependencyGraph.prototype._addDependentNodes =
|
||||
function dg_addDependentNodes(node, dependentNodes, traversedNodes) {
|
||||
traversedNodes = traversedNodes || [];
|
||||
if (traversedNodes.indexOf(node.name) >= 0) {
|
||||
traversedNodes.push(node.name);
|
||||
var error = traversedNodes.join(' -> ');
|
||||
this.throw('circular dependency detected! ' + error);
|
||||
}
|
||||
|
||||
if (dependentNodes) {
|
||||
// add all nodes in "dependendNodes" to the current node
|
||||
dependentNodes.forEach((name) => {
|
||||
if (node.dependentNodes.indexOf(name) < 0) {
|
||||
node.dependentNodes.push(name);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
// Nothing to add, prepare the nodes to be added to the children.
|
||||
dependentNodes = Array.prototype.slice.call(node.dependentNodes);
|
||||
}
|
||||
|
||||
dependentNodes.push(node.name);
|
||||
traversedNodes.push(node.name);
|
||||
node.children.forEach((name) => {
|
||||
this._addDependentNodes(this._nodes[name], dependentNodes,
|
||||
traversedNodes);
|
||||
});
|
||||
dependentNodes.pop();
|
||||
traversedNodes.pop();
|
||||
};
|
||||
|
||||
/**
|
||||
* Add dependency. Calling to this function adds a dependency from the first
|
||||
* parameter towards the second one.
|
||||
*
|
||||
* @access public
|
||||
* @memberOf DependencyGraph.prototype
|
||||
* @param {String} name1
|
||||
* The name that depends on the other.
|
||||
* @param {String} name2
|
||||
* The name that is being depended on.
|
||||
*/
|
||||
DependencyGraph.prototype.addDependency = function dg_addDep(name1, name2) {
|
||||
var node1 = this._nodes[name1];
|
||||
var node2 = this._nodes[name2];
|
||||
|
||||
if (!node1) {
|
||||
node1 = this._nodes[name1] = {
|
||||
name: name1,
|
||||
children: [],
|
||||
dependentNodes: []
|
||||
};
|
||||
}
|
||||
|
||||
if (!node2) {
|
||||
node2 = this._nodes[name2] = {
|
||||
name: name2,
|
||||
children: [],
|
||||
dependentNodes: []
|
||||
};
|
||||
}
|
||||
|
||||
if (node1.children.indexOf(name2) < 0) {
|
||||
node1.children.push(name2);
|
||||
this._addDependentNodes(node1);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Get all dependent names of a name.
|
||||
*
|
||||
* @access public
|
||||
* @memberOf DependencyGraph.prototype
|
||||
* @param {String} name
|
||||
*/
|
||||
DependencyGraph.prototype.getAllDependent = function dg_getAllDep(name) {
|
||||
var node = this._nodes[name];
|
||||
return node && node.dependentNodes;
|
||||
};
|
||||
|
||||
return DependencyGraph;
|
||||
});
|
||||
137
gaia/apps/settings/js/modules/base/event_emitter.js
Executable file
137
gaia/apps/settings/js/modules/base/event_emitter.js
Executable file
|
|
@ -0,0 +1,137 @@
|
|||
define(function(require) {
|
||||
'use strict';
|
||||
|
||||
var Module = require('modules/base/module');
|
||||
|
||||
/**
|
||||
* EventEmitter implements basic event emitting logics. It also provides
|
||||
* function that augments the ability to other objects.
|
||||
*
|
||||
* @example
|
||||
* var eventEmitter = EventEmitter(['event1', 'event2']);
|
||||
* var eventHandler = function(event) {
|
||||
* console.log(event.detail);
|
||||
* };
|
||||
* var obj = {
|
||||
* handleEvent: function(event) {
|
||||
* console.log(event.detail);
|
||||
* }
|
||||
* };
|
||||
*
|
||||
* eventEmitter.addEventListener('event1', eventHandler);
|
||||
* eventEmitter.addEventListener('event2', obj);
|
||||
*
|
||||
* eventEmitter._emitEvent('event1', 'value1'); // value1
|
||||
* eventEmitter._emitEvent('event2', 'value2'); // value2
|
||||
*
|
||||
* Extending from EventEmitter:
|
||||
* @example
|
||||
* var NewModule = Module.create(function() {
|
||||
* this.super(EventEmitter).call(this, ['event1', 'event2']);
|
||||
* }).extend(EventEmitter);
|
||||
*
|
||||
* var module = NewModule();
|
||||
*
|
||||
* @class EventEmitter
|
||||
* @returns {EventEmitter}
|
||||
*/
|
||||
var EventEmitter = Module.create(function EventEmitter(eventNames) {
|
||||
if (eventNames && eventNames.length) {
|
||||
this._eventListeners = eventNames.reduce((result, eventName) => {
|
||||
result[eventName] = [];
|
||||
return result;
|
||||
}, {});
|
||||
} else {
|
||||
this.throw('no valid registered events');
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Emit an event of a specific type and a given value.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf EventEmitter.prototype
|
||||
* @param {String} eventName
|
||||
* @param {Object} value
|
||||
*/
|
||||
EventEmitter.prototype._emitEvent = function(eventName, value) {
|
||||
var listeners = this._eventListeners[eventName];
|
||||
if (!listeners) {
|
||||
this.throw('invalid event name: ' + eventName);
|
||||
}
|
||||
|
||||
this.debug('_emitEvent:' + eventName + ' ' + value);
|
||||
var eventObj = {
|
||||
type: eventName,
|
||||
detail: value
|
||||
};
|
||||
listeners.forEach((listener) => {
|
||||
listener.call(this, eventObj);
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Add an event listener on an event. If listener is an object,
|
||||
* object.handleEvent is called when the event emits.
|
||||
*
|
||||
* @access public
|
||||
* @memberOf EventEmitter.prototype
|
||||
* @param {String} eventName
|
||||
* @param {(Function|Object)} listener
|
||||
*/
|
||||
EventEmitter.prototype.addEventListener = function(eventName, listener) {
|
||||
var listeners = this._eventListeners[eventName];
|
||||
if (listener && listeners) {
|
||||
switch (typeof listener) {
|
||||
case 'function':
|
||||
break;
|
||||
case 'object':
|
||||
if (typeof listener.handleEvent === 'function') {
|
||||
listener = listener.handleEvent;
|
||||
} else {
|
||||
listener = null;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
listener = null;
|
||||
break;
|
||||
}
|
||||
if (listener && listeners.indexOf(listener) < 0) {
|
||||
listeners.push(listener);
|
||||
}
|
||||
} else {
|
||||
this.error('addEventListener: invalid listener for ' + eventName);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Remove the event listener from an event.
|
||||
*
|
||||
* @access public
|
||||
* @memberOf EventEmitter.prototype
|
||||
* @param {String} eventName
|
||||
* @param {(Function|Object)} listener
|
||||
*/
|
||||
EventEmitter.prototype.removeEventListener = function(eventName, listener) {
|
||||
var listeners = this._eventListeners[eventName];
|
||||
if (listener && listeners) {
|
||||
var index = -1;
|
||||
var type = typeof listener;
|
||||
switch (type) {
|
||||
case 'function':
|
||||
index = listeners.indexOf(listener);
|
||||
break;
|
||||
case 'object':
|
||||
index = listeners.indexOf(listener.handleEvent);
|
||||
break;
|
||||
}
|
||||
if (index >= 0) {
|
||||
listeners.splice(index, 1);
|
||||
}
|
||||
} else {
|
||||
this.error('removeEventListener: invalid listener for ' + eventName);
|
||||
}
|
||||
};
|
||||
|
||||
return EventEmitter;
|
||||
});
|
||||
152
gaia/apps/settings/js/modules/base/module.js
Executable file
152
gaia/apps/settings/js/modules/base/module.js
Executable file
|
|
@ -0,0 +1,152 @@
|
|||
/**
|
||||
* Module provides methods to create a new module. Any module created here has
|
||||
* the ability of being extended by other modules. Existing properties are
|
||||
* overridden.
|
||||
*
|
||||
* Creating a module
|
||||
* @example
|
||||
* var NewModule = Module.create(function() {
|
||||
* this.value = 100;
|
||||
* });
|
||||
* NewModule.prototype.print = function() { console.log(this.value); };
|
||||
*
|
||||
* var instance = NewModule();
|
||||
* instance.print(); // 100
|
||||
*
|
||||
* Extending a module
|
||||
* @example
|
||||
* var AnotherModule = Module.create();
|
||||
* AnotherModule.prototype.inc = function() { this.value++; };
|
||||
* var ExtendingModule = NewModule.extend(AnotherModule);
|
||||
*
|
||||
* var instance = ExtendingModule();
|
||||
* instance.inc();
|
||||
* instance.print(); // 101
|
||||
*
|
||||
* @module modules/base/module
|
||||
*/
|
||||
define(function() {
|
||||
'use strict';
|
||||
|
||||
const LOG_LEVEL = {
|
||||
NONE: 0,
|
||||
DEBUG: 1,
|
||||
INFO: 2,
|
||||
WARN: 3,
|
||||
ERROR: 4,
|
||||
ALL: 5
|
||||
};
|
||||
|
||||
var _constructorMap = (function() {
|
||||
var _ctorMap = new Map();
|
||||
var _getConstructor = function(Module) {
|
||||
return _ctorMap.get(Module) || function() {};
|
||||
};
|
||||
var _registerConstructor = function(Module, constructor) {
|
||||
_ctorMap.set(Module, constructor || function() {});
|
||||
};
|
||||
return {
|
||||
getConstructor: _getConstructor,
|
||||
registerConstructor: _registerConstructor
|
||||
};
|
||||
})();
|
||||
|
||||
var _emptyFunction = function() {};
|
||||
var _createLogger = function(name) {
|
||||
switch (name) {
|
||||
case 'DEBUG':
|
||||
return function(msg) {
|
||||
console.log(this._msgPrefix + msg);
|
||||
};
|
||||
case 'INFO':
|
||||
return function(msg) {
|
||||
console.info(this._msgPrefix + msg);
|
||||
};
|
||||
case 'WARN':
|
||||
return function(msg) {
|
||||
console.warn(this._msgPrefix + msg);
|
||||
};
|
||||
case 'ERROR':
|
||||
return function(msg) {
|
||||
console.error(this._msgPrefix + msg);
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
var ModulePrototype = {
|
||||
get _msgPrefix() {
|
||||
return '[' + this.$name + ']: ';
|
||||
},
|
||||
debug: _emptyFunction,
|
||||
info: _emptyFunction,
|
||||
warn: _emptyFunction,
|
||||
error: _emptyFunction,
|
||||
throw: function(msg) {
|
||||
throw new Error(this._msgPrefix + msg);
|
||||
},
|
||||
set _logLevel(value) {
|
||||
Object.keys(LOG_LEVEL).forEach((name) => {
|
||||
var level = LOG_LEVEL[name];
|
||||
if (value >= level && value > 0) {
|
||||
this[name.toLowerCase()] = _createLogger(name);
|
||||
}
|
||||
});
|
||||
},
|
||||
super: _constructorMap.getConstructor
|
||||
};
|
||||
|
||||
var _extend = function() {
|
||||
switch (arguments.length) {
|
||||
case 0:
|
||||
break;
|
||||
case 1:
|
||||
var Module = arguments[0];
|
||||
for (var prop in Module.prototype) {
|
||||
if (prop === '$name') {
|
||||
continue;
|
||||
}
|
||||
var pd = Object.getOwnPropertyDescriptor(Module.prototype, prop);
|
||||
if (pd) {
|
||||
Object.defineProperty(this.prototype, prop, pd);
|
||||
}
|
||||
}
|
||||
break;
|
||||
default:
|
||||
Array.prototype.forEach.call(arguments, (Module) => {
|
||||
_extend.call(this, Module);
|
||||
});
|
||||
break;
|
||||
}
|
||||
return this;
|
||||
};
|
||||
|
||||
// Returns a module function. The function returns an instance of the
|
||||
// module when it is called. The passed constructor is called using the
|
||||
// instance as "this".
|
||||
function _create(constructor) {
|
||||
if (constructor && typeof constructor !== 'function') {
|
||||
throw new Error('[Module]: Invalid constructor');
|
||||
}
|
||||
|
||||
var ModuleFunc = function() {};
|
||||
ModuleFunc.prototype = Object.create(ModulePrototype);
|
||||
ModuleFunc.prototype.$name = constructor && constructor.name || '';
|
||||
|
||||
var Module = function() {
|
||||
var instance = new ModuleFunc();
|
||||
if (constructor) {
|
||||
constructor.apply(instance, arguments);
|
||||
}
|
||||
return instance;
|
||||
};
|
||||
_constructorMap.registerConstructor(Module, constructor);
|
||||
Module.extend = _extend;
|
||||
Module.prototype = ModuleFunc.prototype;
|
||||
return Module;
|
||||
}
|
||||
|
||||
return {
|
||||
LOG_LEVEL: LOG_LEVEL,
|
||||
create: _create
|
||||
};
|
||||
});
|
||||
147
gaia/apps/settings/js/modules/base/task_scheduler.js
Executable file
147
gaia/apps/settings/js/modules/base/task_scheduler.js
Executable file
|
|
@ -0,0 +1,147 @@
|
|||
/**
|
||||
* TaskScheduler helps manage tasks and ensures they are executed in
|
||||
* sequential order. When a task of a certain type is enqueued, all pending
|
||||
* tasks of the same type in the queue are removed. This avoids redundant
|
||||
* queries and improves user perceived performance.
|
||||
*
|
||||
* @module modules/base/task_scheduler
|
||||
*/
|
||||
define(function(require) {
|
||||
'use strict';
|
||||
|
||||
var Defer = require('modules/defer');
|
||||
var Module = require('modules/base/module');
|
||||
var Observable = require('modules/mvvm/observable');
|
||||
|
||||
/**
|
||||
* @class TaskScheduler
|
||||
* @returns {TaskScheduler}
|
||||
*/
|
||||
var TaskScheduler = Module.create(function TaskScheduler() {
|
||||
this.super(Observable).call(this);
|
||||
this.isLocked = false;
|
||||
this._tasks = [];
|
||||
}).extend(Observable);
|
||||
|
||||
Observable.defineObservableProperty(TaskScheduler.prototype, 'isLocked', {
|
||||
value: false
|
||||
});
|
||||
|
||||
const TASK_TYPE = {
|
||||
GENERAL: 0
|
||||
};
|
||||
|
||||
/**
|
||||
* We will keep some constants here as a static variable
|
||||
*
|
||||
* @access public
|
||||
* @memberOf TaskScheduler
|
||||
*/
|
||||
Object.defineProperty(TaskScheduler, 'TASK_TYPE', {
|
||||
enumerable: true,
|
||||
configurable: false,
|
||||
get: function() {
|
||||
return TASK_TYPE;
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Change the internal state to make sure we are locked.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf TaskScheduler
|
||||
*/
|
||||
TaskScheduler.prototype._lock = function() {
|
||||
this.isLocked = true;
|
||||
};
|
||||
|
||||
/**
|
||||
* Change the internal state to unlocked and execute next task.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf TaskScheduler
|
||||
*/
|
||||
TaskScheduler.prototype._unlock = function() {
|
||||
this.isLocked = false;
|
||||
this._executeNextTask();
|
||||
};
|
||||
|
||||
/**
|
||||
* We will remove any redundant same-type tasks and keep the remaining ones
|
||||
* including the others which are not cancelable (general use task).
|
||||
*
|
||||
* @access private
|
||||
* @memberOf TaskScheduler
|
||||
* @param {String} type
|
||||
* @return {Array} array of tasks
|
||||
*/
|
||||
TaskScheduler.prototype._removeRedundantTasks = function(type) {
|
||||
return this._tasks.filter((task) => {
|
||||
if (!task.cancelable) {
|
||||
return true;
|
||||
} else {
|
||||
return task.type !== type;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Execute the next task when unlocked.
|
||||
*
|
||||
* @access private
|
||||
* @returns {Promise}
|
||||
* @memberOf TaskScheduler
|
||||
*/
|
||||
TaskScheduler.prototype._executeNextTask = function() {
|
||||
if (this.isLocked) {
|
||||
return;
|
||||
}
|
||||
var nextTask = this._tasks.shift();
|
||||
if (nextTask) {
|
||||
this._lock();
|
||||
return nextTask.func().then((result) => {
|
||||
nextTask.defer.resolve(result);
|
||||
this._unlock();
|
||||
}, () => {
|
||||
nextTask.defer.reject();
|
||||
this._unlock();
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* This is the only entry point for caller, and we will enqueue all tasks
|
||||
* one by one and execute them in order.
|
||||
*
|
||||
* @access public
|
||||
* @memberOf TaskScheduler
|
||||
* @param {Object} task
|
||||
* @param {String} task.type
|
||||
* @param {Function} task.func - make sure the func would return a promise
|
||||
* @param {Boolean} task.cancelable
|
||||
* @return {Promise}
|
||||
*/
|
||||
TaskScheduler.prototype.enqueue = function(task) {
|
||||
var defer = Defer();
|
||||
|
||||
// if there is no func, let's directly resolve this task
|
||||
if (!task.func) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
if (!task.type) {
|
||||
// copy the task and make sure we won't change the previous one
|
||||
task = Object.assign({}, task);
|
||||
task.type = TaskScheduler.TASK_TYPE.GENERAL;
|
||||
}
|
||||
|
||||
task.defer = defer;
|
||||
this._tasks = this._removeRedundantTasks(task.type);
|
||||
this._tasks.push(task);
|
||||
this._executeNextTask();
|
||||
|
||||
return defer.promise;
|
||||
};
|
||||
|
||||
return TaskScheduler;
|
||||
});
|
||||
121
gaia/apps/settings/js/modules/battery.js
Executable file
121
gaia/apps/settings/js/modules/battery.js
Executable file
|
|
@ -0,0 +1,121 @@
|
|||
/**
|
||||
* Battery is an Observable that wraps the platform battery object. It has two
|
||||
* observable properties: level and state.
|
||||
*
|
||||
* @module modules/battery
|
||||
*/
|
||||
define(function(require) {
|
||||
'use strict';
|
||||
|
||||
var NavigatorBattery = require('modules/navigator/battery');
|
||||
var Module = require('modules/base/module');
|
||||
var Observable = require('modules/mvvm/observable');
|
||||
|
||||
/**
|
||||
* @class Battery
|
||||
* @requires module:modules/navigator/battery
|
||||
* @requires module:modules/base/module
|
||||
* @requires module:modules/mvvm/observable
|
||||
* @returns {Battery}
|
||||
*/
|
||||
var Battery = Module.create(function Battery() {
|
||||
this.super(Observable).call(this);
|
||||
|
||||
this._level = this._getLevel();
|
||||
this._state = this._getState();
|
||||
this._chargingTime = this._getChargingTime();
|
||||
this._dischargingTime = this._getDischargingTime();
|
||||
NavigatorBattery.addEventListener('levelchange', () => {
|
||||
this._level = this._getLevel();
|
||||
});
|
||||
NavigatorBattery.addEventListener('chargingchange', () => {
|
||||
this._state = this._getState();
|
||||
this._chargingTime = this._getChargingTime();
|
||||
this._dischargingTime = this._getDischargingTime();
|
||||
});
|
||||
NavigatorBattery.addEventListener('chargingtimechange', () => {
|
||||
this._chargingTime = this._getChargingTime();
|
||||
});
|
||||
NavigatorBattery.addEventListener('dischargingtimechange', () => {
|
||||
this._dischargingTime = this._getDischargingTime();
|
||||
});
|
||||
}).extend(Observable);
|
||||
|
||||
/**
|
||||
* An observable property indicating the current battery level.
|
||||
*
|
||||
* @access public
|
||||
* @readonly
|
||||
* @memberOf Battery.prototype
|
||||
* @type {String}
|
||||
*/
|
||||
Observable.defineObservableProperty(Battery.prototype,
|
||||
'level', {
|
||||
readonly: true,
|
||||
value: ''
|
||||
});
|
||||
|
||||
/**
|
||||
* An observable property indicating the current battery state.
|
||||
*
|
||||
* @access public
|
||||
* @readonly
|
||||
* @memberOf Battery.prototype
|
||||
* @type {String}
|
||||
*/
|
||||
Observable.defineObservableProperty(Battery.prototype,
|
||||
'state', {
|
||||
readonly: true,
|
||||
value: ''
|
||||
});
|
||||
|
||||
/**
|
||||
* An observable property indicating the current charging time.
|
||||
*
|
||||
* @access public
|
||||
* @readonly
|
||||
* @memberOf Battery.prototype
|
||||
* @type {String}
|
||||
*/
|
||||
Observable.defineObservableProperty(Battery.prototype,
|
||||
'chargingTime', {
|
||||
readonly: true,
|
||||
value: ''
|
||||
});
|
||||
|
||||
/**
|
||||
* An observable property indicating the current discharging time.
|
||||
*
|
||||
* @access public
|
||||
* @readonly
|
||||
* @memberOf Battery.prototype
|
||||
* @type {String}
|
||||
*/
|
||||
Observable.defineObservableProperty(Battery.prototype,
|
||||
'dischargingTime', {
|
||||
readonly: true,
|
||||
value: ''
|
||||
});
|
||||
|
||||
Battery.prototype._getLevel = function() {
|
||||
return Math.min(100, Math.round(NavigatorBattery.level * 100));
|
||||
};
|
||||
|
||||
Battery.prototype._getState = function() {
|
||||
if (NavigatorBattery.charging) {
|
||||
return (this._getLevel() == 100) ? 'charged' : 'charging';
|
||||
} else {
|
||||
return 'unplugged';
|
||||
}
|
||||
};
|
||||
|
||||
Battery.prototype._getChargingTime = function() {
|
||||
return NavigatorBattery.chargingTime;
|
||||
};
|
||||
|
||||
Battery.prototype._getDischargingTime = function() {
|
||||
return NavigatorBattery.dischargingTime;
|
||||
};
|
||||
|
||||
return Battery();
|
||||
});
|
||||
111
gaia/apps/settings/js/modules/bluetooth/bluetooth_adapter_manager.js
Executable file
111
gaia/apps/settings/js/modules/bluetooth/bluetooth_adapter_manager.js
Executable file
|
|
@ -0,0 +1,111 @@
|
|||
/**
|
||||
* BluetoothAdapterManager:
|
||||
* - BluetoothAdapterManager is an Observable that wraps the platform
|
||||
* Bluetooth object for construct default adapter.
|
||||
* - It has only one observable properties: defaultAdapter
|
||||
* BluetoothAdapterManager only update state and does not involve in any UI
|
||||
* logic.
|
||||
*
|
||||
* @module BluetoothAdapterManager
|
||||
*/
|
||||
define(function(require) {
|
||||
'use strict';
|
||||
|
||||
var NavigatorBluetooth = require('modules/navigator/mozBluetooth');
|
||||
var Observable = require('modules/mvvm/observable');
|
||||
|
||||
var _debug = false;
|
||||
var debug = function() {};
|
||||
if (_debug) {
|
||||
debug = function btam_debug(msg) {
|
||||
console.log('--> [BluetoothAdapterManager]: ' + msg);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @alias module:modules/bluetooth/BluetoothAdapterManager
|
||||
* @requires module:modules/navigator/mozBluetooth
|
||||
* @requires module:modules/mvvm/observable
|
||||
* @return {BluetoothAdapterManager}
|
||||
*/
|
||||
var BluetoothAdapterManager = {
|
||||
/**
|
||||
* The default adapter used to connect to the remote bluetooth devices.
|
||||
*
|
||||
* @readonly
|
||||
* @memberOf BluetoothAdapterManager
|
||||
* @type {Object}
|
||||
*/
|
||||
defaultAdapter: null,
|
||||
|
||||
/**
|
||||
* Init Bluetooth module.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf BluetoothAdapterManager
|
||||
*/
|
||||
_init: function btam__init() {
|
||||
// Early return while there is no navigator.mozBluetooth module.
|
||||
if (!NavigatorBluetooth) {
|
||||
return;
|
||||
}
|
||||
|
||||
// watch BluetoothManager event
|
||||
this._watchMozBluetoothAttributechanged();
|
||||
|
||||
// init default adapter
|
||||
this._initDefaultAdapter();
|
||||
},
|
||||
|
||||
/**
|
||||
* Watch 'attributechanged' event from mozBluetooth for updating default
|
||||
* adapter information.
|
||||
*
|
||||
* 'attributechanged' event description:
|
||||
* A handler to trigger when bluetooth manager's only property
|
||||
* defaultAdapter has changed.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf BluetoothAdapterManager
|
||||
*/
|
||||
_watchMozBluetoothAttributechanged:
|
||||
function btam__watchMozBluetoothAttributechanged() {
|
||||
NavigatorBluetooth.addEventListener('attributechanged', (evt) => {
|
||||
for (var i in evt.attrs) {
|
||||
switch (evt.attrs[i]) {
|
||||
case 'defaultAdapter':
|
||||
// Default adapter attribute change.
|
||||
// Usually, it means that we reach new default adapter.
|
||||
this.defaultAdapter = NavigatorBluetooth.defaultAdapter;
|
||||
debug('_watchMozBluetoothAttributechanged(): ' +
|
||||
'this.defaultAdapter = ' + this.defaultAdapter);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
/* Reach default adapter from platform Bluetooth.
|
||||
*
|
||||
* If the property is accessed on platform in the first time, it will
|
||||
* trigger Gecko::Bluetooth to get default adapter from the chipset.
|
||||
* So the value would be null.
|
||||
* Then we will receive 'attributechanged' event later.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf BluetoothAdapterManager
|
||||
*/
|
||||
_initDefaultAdapter: function btam__initDefaultAdapter() {
|
||||
this.defaultAdapter = NavigatorBluetooth.defaultAdapter;
|
||||
debug('_initDefaultAdapter(): this.defaultAdapter = ' +
|
||||
this.defaultAdapter);
|
||||
}
|
||||
};
|
||||
|
||||
// Create the observable object using the prototype.
|
||||
var bluetoothAdapterManager = Observable(BluetoothAdapterManager);
|
||||
bluetoothAdapterManager._init();
|
||||
return bluetoothAdapterManager;
|
||||
});
|
||||
198
gaia/apps/settings/js/modules/bluetooth/bluetooth_cod_mapper.js
Executable file
198
gaia/apps/settings/js/modules/bluetooth/bluetooth_cod_mapper.js
Executable file
|
|
@ -0,0 +1,198 @@
|
|||
/**
|
||||
* BluetoothClassOfDeviceMapper:
|
||||
* - BluetoothClassOfDeviceMapper is a mapper that helps settings/bluetooth
|
||||
* apps to decide the icon type. Since platform exposed the 'number' type
|
||||
* for class of device(Major Service Classes, Major Device Classes,
|
||||
* Minor Device Classes), the helper will map the input number to specific
|
||||
* device type. And the decision is referenced from Baseband.
|
||||
* (Assigned numbers for Baseband identifies the Inquiry Access codes
|
||||
* and Class of Device/Service (CoD) fields.)[3]
|
||||
* According to the specifications described, we define the device type in
|
||||
* Gaia side entirely. And the naming of device type we given is also
|
||||
* mapping to CSS style sheet.
|
||||
*
|
||||
* - [1] Bluetooth API v1, BluetoothDevice icon property:
|
||||
* https://developer.mozilla.org/en-US/docs/Web/API/BluetoothDevice.icon
|
||||
* - [2] Bluetooth API v2, BluetoothClassOfDevice object:
|
||||
* https://wiki.mozilla.org/B2G/Bluetooth/WebBluetooth-v2/
|
||||
* BluetoothClassOfDevice
|
||||
* - [3] Bluetooth Class of Device Reference:
|
||||
* https://www.bluetooth.org/en-us/specification/assigned-numbers/baseband
|
||||
* - We can update the mapper if the specifications Baseband is updated.
|
||||
*
|
||||
* @module BluetoothClassOfDeviceMapper
|
||||
*/
|
||||
define(function() {
|
||||
'use strict';
|
||||
|
||||
var _debug = false;
|
||||
var debug = function() {};
|
||||
if (_debug) {
|
||||
debug = function btcodm_debug(msg) {
|
||||
console.log('--> [BluetoothCODMapper]: ' + msg);
|
||||
};
|
||||
}
|
||||
|
||||
var MinorDeviceClasses = {
|
||||
Computer: {
|
||||
0: 'computer', // Uncategorized, code for device not assigned
|
||||
1: 'computer', // Desktop workstation
|
||||
2: 'computer', // Server-class computer
|
||||
3: 'computer', // Laptop
|
||||
4: 'pda', // Handheld PC/PDA (clamshell)
|
||||
5: 'pda', // Palm-size PC/PDA
|
||||
6: 'computer', // Wearable computer (watch size)
|
||||
7: 'computer', // Tablet
|
||||
reserved: 'computer' // All other values reserved. Default type
|
||||
// 'computer' given for reserved case.
|
||||
},
|
||||
|
||||
Phone: {
|
||||
0: 'phone', // Uncategorized, code for device not assigned
|
||||
1: 'phone', // Cellular
|
||||
2: 'phone', // Cordless
|
||||
3: 'phone', // Smartphone
|
||||
4: 'modem', // Wired modem or voice gateway
|
||||
5: 'phone', // Common ISDN access
|
||||
reserved: 'phone' // All other values reserved. Default type
|
||||
// 'phone' given for reserved case.
|
||||
},
|
||||
|
||||
AudioVideo: {
|
||||
0: 'audio-card', // Uncategorized, code not assigned
|
||||
1: 'audio-card', // Wearable Headset Device
|
||||
2: 'audio-card', // Hands-free Device
|
||||
4: 'audio-input-microphone', // Microphone
|
||||
5: 'audio-card', // Loudspeaker
|
||||
6: 'audio-card', // Headphones
|
||||
7: 'audio-card', // Portable Audio
|
||||
8: 'audio-card', // Car audio
|
||||
9: 'audio-card', // Set-top box
|
||||
10: 'audio-card', // HiFi Audio Device
|
||||
11: 'camera-video', // VCR
|
||||
12: 'camera-video', // Video Camera
|
||||
13: 'camera-video', // Camcorder
|
||||
14: 'video-display', // Video Monitor
|
||||
15: 'video-display', // Video Display and Loudspeaker
|
||||
16: 'video-display', // Video Conferencing
|
||||
18: 'audio-card', // Gameing/Toy
|
||||
reserved: 'audio-card' // All other values reserved. Default type
|
||||
// 'audio-card' given for reserved case.
|
||||
},
|
||||
|
||||
Peripheral: {
|
||||
1: 'input-gaming', // Joystick
|
||||
2: 'input-gaming', // Gamepad
|
||||
16: 'input-keyboard', // Keyboard
|
||||
17: 'input-keyboard', // Keyboard
|
||||
18: 'input-keyboard', // Keyboard
|
||||
19: 'input-keyboard', // Keyboard
|
||||
20: 'input-keyboard', // Keyboard
|
||||
21: 'input-keyboard', // Keyboard
|
||||
22: 'input-keyboard', // Keyboard
|
||||
23: 'input-keyboard', // Keyboard
|
||||
24: 'input-keyboard', // Keyboard
|
||||
25: 'input-keyboard', // Keyboard
|
||||
26: 'input-keyboard', // Keyboard
|
||||
27: 'input-keyboard', // Keyboard
|
||||
28: 'input-keyboard', // Keyboard
|
||||
29: 'input-keyboard', // Keyboard
|
||||
30: 'input-keyboard', // Keyboard
|
||||
31: 'input-keyboard', // Keyboard
|
||||
32: 'input-mouse', // Pointing device
|
||||
33: 'input-mouse', // Pointing device
|
||||
34: 'input-mouse', // Pointing device
|
||||
35: 'input-mouse', // Pointing device
|
||||
36: 'input-mouse', // Pointing device
|
||||
37: 'input-tablet', // Digitizer tablet
|
||||
38: 'input-mouse', // Pointing device
|
||||
39: 'input-mouse', // Pointing device
|
||||
40: 'input-mouse', // Pointing device
|
||||
41: 'input-mouse', // Pointing device
|
||||
42: 'input-mouse', // Pointing device
|
||||
43: 'input-mouse', // Pointing device
|
||||
44: 'input-mouse', // Pointing device
|
||||
45: 'input-mouse', // Pointing device
|
||||
46: 'input-mouse', // Pointing device
|
||||
47: 'input-mouse' // Pointing device
|
||||
},
|
||||
|
||||
Imaging: {
|
||||
4: 'video-display', // Display, bit: XXX1XX
|
||||
8: 'camera-photo', // Camera, bit: XX1XXX
|
||||
16: 'scanner', // Scanner, bit: X1XXXX
|
||||
32: 'printer' // Printer, bit: 1XXXXX
|
||||
}
|
||||
};
|
||||
|
||||
var MajorDeviceClasses = {
|
||||
1: MinorDeviceClasses.Computer,
|
||||
2: MinorDeviceClasses.Phone,
|
||||
3: 'network-wireless', // LAN/Network Access Point Major Class
|
||||
4: MinorDeviceClasses.AudioVideo,
|
||||
5: MinorDeviceClasses.Peripheral,
|
||||
6: MinorDeviceClasses.Imaging
|
||||
};
|
||||
|
||||
var BluetoothClassOfDeviceMapper = {
|
||||
/**
|
||||
* The string indicating which kind of icon could be used to represent
|
||||
* the device.
|
||||
*
|
||||
* @access public
|
||||
* @memberOf BluetoothClassOfDeviceMapper
|
||||
* @param {BluetoothClassOfDevice} cod
|
||||
* @return {String}
|
||||
*/
|
||||
getDeviceType: function btcodm_getDeviceType(cod) {
|
||||
debug('cod.majorDeviceClass = ' + cod.majorDeviceClass);
|
||||
debug('cod.majorServiceClass = ' + cod.majorServiceClass);
|
||||
debug('cod.minorDeviceClass = ' + cod.minorDeviceClass);
|
||||
// Given an empty string to be default type.
|
||||
// Then, we won't show any icon for empty type.
|
||||
var deviceType = '';
|
||||
var majorDeviceClass = MajorDeviceClasses[cod.majorDeviceClass];
|
||||
debug('majorDeviceClass = ' + majorDeviceClass);
|
||||
if (typeof(majorDeviceClass) === 'object') {
|
||||
// drop in other Major Class
|
||||
deviceType = majorDeviceClass[cod.minorDeviceClass] ||
|
||||
majorDeviceClass.reserved || '';
|
||||
debug('return in minor class, type = ' + deviceType);
|
||||
return deviceType;
|
||||
} else if (typeof(majorDeviceClass) === 'string') {
|
||||
// drop in LAN/Network Access Point Major Class
|
||||
debug('return in major class, type = network-wireless');
|
||||
return majorDeviceClass;
|
||||
} else if (cod.majorServiceClass & 0x100) {
|
||||
// Not in any Major Device Class which is defined in Gaia.
|
||||
// Ex: Wearable, Toy, Health.
|
||||
|
||||
// Since there is no icon to display wearable, toy, health devices,
|
||||
// file a bug 1163479[2] to define them for specification needed.
|
||||
// But some of these devices probably service 'Audio' per Bluetooth
|
||||
// specification[1].
|
||||
// Property 'type' may be missed due to CoD of major class is TOY(0x08).
|
||||
// But we need to assign 'type' as 'audio-card' if service class
|
||||
// is 'Audio'. This is for PTS test case TC_AG_COD_BV_02_I.
|
||||
// As HFP specification defines that service class is 'Audio' can
|
||||
// be considered as HFP HF.
|
||||
// [1]: HFP_SPEC_V16.pdf: A device implementing the HF role of HFP shall
|
||||
// set the "Audio" bit in the Service Class field.
|
||||
// [2]: Bug 1163479 - [Gaia][Bluetooth] Device icon definition for
|
||||
// wearable, toy, health(Major Device Class) devices.
|
||||
// (https://bugzilla.mozilla.org/show_bug.cgi?id=1163479)
|
||||
|
||||
// Major Service Class: Audio(Speaker, Microphone, Headset service, ...)
|
||||
deviceType = 'audio-card';
|
||||
debug('return in major service class, type = audio-card');
|
||||
return deviceType;
|
||||
} else {
|
||||
// Not in any Class which is defined in Gaia.
|
||||
debug('not mapping in any class, return type = ' + deviceType);
|
||||
return deviceType;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return BluetoothClassOfDeviceMapper;
|
||||
});
|
||||
953
gaia/apps/settings/js/modules/bluetooth/bluetooth_connection_manager.js
Executable file
953
gaia/apps/settings/js/modules/bluetooth/bluetooth_connection_manager.js
Executable file
|
|
@ -0,0 +1,953 @@
|
|||
/**
|
||||
* BluetoothConnectionManager:
|
||||
* BluetoothConnectionManager only update state and does not involve in any UI
|
||||
* logic.
|
||||
*
|
||||
* @module BluetoothConnectionManager
|
||||
*/
|
||||
define(function(require) {
|
||||
'use strict';
|
||||
|
||||
var AdapterManager = require('modules/bluetooth/bluetooth_adapter_manager');
|
||||
var AsyncStorage = require('shared/async_storage');
|
||||
|
||||
var _debug = false;
|
||||
var debug = function() {};
|
||||
if (_debug) {
|
||||
debug = function btam_debug(msg) {
|
||||
console.log('--> [BluetoothConnectionManager]: ' + msg);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @alias module:modules/bluetooth/BluetoothConnectionManager
|
||||
* @requires module:modules/bluetooth/bluetooth_adapter_manager
|
||||
* @requires module:shared/async_storage
|
||||
* @return {BluetoothConnectionManager}
|
||||
*/
|
||||
var BluetoothConnectionManager = {
|
||||
/**
|
||||
* The profiles of connected device that we are defined here.
|
||||
*
|
||||
* @public
|
||||
* @memberOf BluetoothConnectionManager
|
||||
* @type {Object}
|
||||
*/
|
||||
Profiles: {
|
||||
'hfp': 0x111E, // Handsfree
|
||||
'a2dp': 0x110D // Advanced Audio Distribution Devices
|
||||
},
|
||||
|
||||
/**
|
||||
* The address of device that we are trying to connect.
|
||||
*
|
||||
* @public
|
||||
* @memberOf BluetoothConnectionManager
|
||||
* @type {String}
|
||||
*/
|
||||
connectingAddress: null,
|
||||
|
||||
/**
|
||||
* A object that we cache the connected devices information(address, device,
|
||||
* connectedProfiles). It will be inited while default adapter is ready.
|
||||
* And these information is coming from profile events.
|
||||
* Each connected device is hashed by device address.
|
||||
*
|
||||
* EX:
|
||||
* _connectedDevicesInfo = {
|
||||
* 'AA:BB:CC:00:11:22': {
|
||||
* 'device': DeviceObject,
|
||||
* 'connectedProfiles': {
|
||||
* 'hfp': true,
|
||||
* 'a2dp': false
|
||||
* }
|
||||
* }
|
||||
* };
|
||||
*
|
||||
* @private
|
||||
* @memberOf BluetoothConnectionManager
|
||||
* @type {Object}
|
||||
*/
|
||||
_connectedDevicesInfo: {},
|
||||
|
||||
/**
|
||||
* An instance to maintain that we have created a promise to get connected
|
||||
* devices.
|
||||
*
|
||||
* @access public
|
||||
* @memberOf BluetoothConnectionManager
|
||||
* @return {Promise}
|
||||
*/
|
||||
_getConnectedDevicesPromise: null,
|
||||
|
||||
/**
|
||||
* The object maintains listeners' callback per property name.
|
||||
* Each listener would be called as following definition.
|
||||
* 'connecting' - be called when device is connecting.
|
||||
* 'connected': - be called when device is connected.
|
||||
* 'disconnected': - be called when device is disconnected.
|
||||
* 'profileChanged': - be called when profile is changed.
|
||||
*
|
||||
* @memberOf BluetoothConnectionManager
|
||||
* @type {Object}
|
||||
*/
|
||||
_listeners: {
|
||||
'connecting': [],
|
||||
'connected': [],
|
||||
'disconnected': [],
|
||||
'profileChanged': []
|
||||
},
|
||||
|
||||
/**
|
||||
* Default adapter of Bluetooth.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf BluetoothConnectionManager
|
||||
* @type {BluetoothAdapter}
|
||||
*/
|
||||
_defaultAdapter: null,
|
||||
|
||||
/**
|
||||
* Init BluetoothConnectionManager module.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf BluetoothConnectionManager
|
||||
*/
|
||||
_init: function btcm__init() {
|
||||
// Observe 'defaultAdapter' property for reaching default adapter.
|
||||
AdapterManager.observe('defaultAdapter',
|
||||
this._onDefaultAdapterChanged.bind(this));
|
||||
this._onDefaultAdapterChanged(AdapterManager.defaultAdapter);
|
||||
},
|
||||
|
||||
/**
|
||||
* 'defaultAdapter' change event handler from adapter manager for
|
||||
* updating adapter immediately.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf BluetoothConnectionManager
|
||||
* @param {BluetoothAdapter} newAdapter
|
||||
* @param {BluetoothAdapter} oldAdapter
|
||||
*/
|
||||
_onDefaultAdapterChanged:
|
||||
function btcm__onDefaultAdapterChanged(newAdapter, oldAdapter) {
|
||||
debug('_onDefaultAdapterChanged(): newAdapter = ' + newAdapter);
|
||||
debug('_onDefaultAdapterChanged(): oldAdapter = ' + oldAdapter);
|
||||
|
||||
// save default adapter
|
||||
this._defaultAdapter = newAdapter;
|
||||
|
||||
if (oldAdapter) {
|
||||
// unwatch event since the old adapter is no longer usefull
|
||||
this._unwatchProfilesStatuschanged(oldAdapter);
|
||||
this._unwatchDefaultAdapterOnattributechanged(oldAdapter);
|
||||
}
|
||||
|
||||
if (newAdapter) {
|
||||
// watch event since the new adapter is ready to access
|
||||
this._watchProfilesStatuschanged(newAdapter);
|
||||
this._watchDefaultAdapterOnattributechanged(newAdapter);
|
||||
// restore connection
|
||||
if (newAdapter.state === 'enabled') {
|
||||
this._restoreConnection();
|
||||
}
|
||||
} else {
|
||||
// reset properties only
|
||||
this._resetConnectionInfo();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Return the cache of connected devices in ConnectionManager.
|
||||
*
|
||||
* @access public
|
||||
* @memberOf BluetoothConnectionManager
|
||||
* @return {Promise}
|
||||
*/
|
||||
getConnectedDevices: function btcm_getConnectedDevices() {
|
||||
if (!this._getConnectedDevicesPromise) {
|
||||
this._getConnectedDevicesPromise =
|
||||
this._initConnectedDevicesInfo().then(() => {
|
||||
debug('getConnectedDevices(): resolved with latest cache = ' +
|
||||
JSON.stringify(this._connectedDevicesInfo));
|
||||
return this._connectedDevicesInfo;
|
||||
}, (reason) => {
|
||||
debug('getConnectedDevices(): rejected with reason = ' + reason);
|
||||
this._getConnectedDevicesPromise = null;
|
||||
});
|
||||
}
|
||||
return this._getConnectedDevicesPromise;
|
||||
},
|
||||
|
||||
/**
|
||||
* Init cache of connected device and save it in cache.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf BluetoothConnectionManager
|
||||
* @return {Promise}
|
||||
*/
|
||||
_initConnectedDevicesInfo: function btcm__initConnectedDevicesInfo() {
|
||||
if (!this._defaultAdapter) {
|
||||
return Promise.reject('default adapter is not existed!!');
|
||||
}
|
||||
// Init connection status and profile from platform.
|
||||
// Then, save these connected device information in cache.
|
||||
return this._getConnectedDevicesFromPlatform().then(
|
||||
(connectedDevicesByProfile) => {
|
||||
this._constructDeviceItemsMap(connectedDevicesByProfile);
|
||||
}, (reason) => {
|
||||
debug('_initConnectedDevicesInfo(): rejected in ' +
|
||||
'_getConnectedDevicesFromPlatform');
|
||||
return Promise.reject(reason);
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* The method will update each device item in maintaining map.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf BluetoothConnectionManager
|
||||
* @param {Object} connectedDevices
|
||||
*/
|
||||
_constructDeviceItemsMap:
|
||||
function btcm__constructDeviceItemsMap(connectedDevices) {
|
||||
debug('_constructDeviceItemsMap(): connectedDevices = ' +
|
||||
JSON.stringify(connectedDevices));
|
||||
if (!connectedDevices) {
|
||||
// Return empty object while there is no any connected devices.
|
||||
debug('_constructDeviceItemsMap(): early return with empty object');
|
||||
return;
|
||||
}
|
||||
|
||||
Object.keys(this.Profiles).map((profileID) => {
|
||||
connectedDevices[profileID].forEach((connectedDevice) => {
|
||||
var connectionDeviceInfo = {
|
||||
address: connectedDevice.address,
|
||||
connected: true,
|
||||
profileID: profileID,
|
||||
device: connectedDevice
|
||||
};
|
||||
debug('_constructDeviceItemsMap(): connectionDeviceInfo = ' +
|
||||
JSON.stringify(connectionDeviceInfo));
|
||||
this._initConnectedDevicesCache(connectionDeviceInfo);
|
||||
});
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Init the cache which is maintained for connection devices.
|
||||
* And the input is gotten from platform API adapter.getConnectedDevices().
|
||||
*
|
||||
* @access private
|
||||
* @memberOf BluetoothConnectionManager
|
||||
* @param {Object} options
|
||||
* @param {String} options.address - address of the device
|
||||
* @param {Boolean} options.connected - is connected or not
|
||||
* @param {Object} options.profileID - profile ID of the connection type
|
||||
* @param {Object} options.device - connect device, Bluetooth Object
|
||||
*/
|
||||
_initConnectedDevicesCache:
|
||||
function btcm__initConnectedDevicesCache(options) {
|
||||
debug('_initConnectedDevicesCache(): options = ' +
|
||||
JSON.stringify(options));
|
||||
// hash by device address
|
||||
var info = this._connectedDevicesInfo[options.address];
|
||||
if (info) {
|
||||
// Already have profiles, update it for other profile.
|
||||
info.connectedProfiles[options.profileID] = options.connected;
|
||||
} else {
|
||||
// Not have profiles yet, create for it.
|
||||
// If options.device is existed, save the connected device.
|
||||
// Otherwise, given null in this property.
|
||||
var connectedDevice = (options.device) ? options.device : null;
|
||||
info = {
|
||||
'device': connectedDevice,
|
||||
'connectedProfiles': {}
|
||||
};
|
||||
info.connectedProfiles[options.profileID] = options.connected;
|
||||
}
|
||||
// Save the device/profile in map.
|
||||
this._connectedDevicesInfo[options.address] = info;
|
||||
|
||||
// If there is no profile connected,
|
||||
// remove the device item from cache since it is already disconnected.
|
||||
var dataToCheckConnectedProfile = {
|
||||
address: options.address,
|
||||
connectedDevices: this._connectedDevicesInfo
|
||||
};
|
||||
if (!this._hasConnectedProfileByAddress(dataToCheckConnectedProfile)) {
|
||||
delete this._connectedDevicesInfo[options.address];
|
||||
}
|
||||
// Return the latest cache which is just updated here.
|
||||
debug('_initConnectedDevicesCache(): this._connectedDevicesInfo = ' +
|
||||
JSON.stringify(this._connectedDevicesInfo));
|
||||
return this._connectedDevicesInfo;
|
||||
},
|
||||
|
||||
/**
|
||||
* Update the cache which is maintained for connection devices.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf BluetoothConnectionManager
|
||||
* @param {Object} options
|
||||
* @param {String} options.address - address of the device
|
||||
* @param {Boolean} options.connected - is connected or not
|
||||
* @param {Object} options.profileID - profile ID of the connection type
|
||||
* @param {Object} options.device - connect device, Bluetooth Object
|
||||
*/
|
||||
_updateConnectedDevices:
|
||||
function btcm__updateConnectedDevices(options) {
|
||||
return this.getConnectedDevices().then((connectedDevicesInfo) => {
|
||||
debug('_updateConnectedDevices(): connectedDevicesInfo = ' +
|
||||
JSON.stringify(connectedDevicesInfo));
|
||||
|
||||
// hash by device address
|
||||
var info =
|
||||
(connectedDevicesInfo) ? connectedDevicesInfo[options.address] : null;
|
||||
if (info) {
|
||||
// Already have profiles, update it for other profile.
|
||||
info.connectedProfiles[options.profileID] = options.connected;
|
||||
} else {
|
||||
// Not have profiles yet, create for it.
|
||||
// If options.device is existed, save the connected device.
|
||||
// Otherwise, given null in this property.
|
||||
var connectedDevice = (options.device) ? options.device : null;
|
||||
info = {
|
||||
'device': connectedDevice,
|
||||
'connectedProfiles': {}
|
||||
};
|
||||
info.connectedProfiles[options.profileID] = options.connected;
|
||||
}
|
||||
// Save the device/profile in map.
|
||||
this._connectedDevicesInfo[options.address] = info;
|
||||
|
||||
// If there is no profile connected,
|
||||
// remove the device item from cache since it is already disconnected.
|
||||
var dataToCheckConnectedProfile = {
|
||||
address: options.address,
|
||||
connectedDevices: this._connectedDevicesInfo
|
||||
};
|
||||
if (!this._hasConnectedProfileByAddress(dataToCheckConnectedProfile)) {
|
||||
delete this._connectedDevicesInfo[options.address];
|
||||
}
|
||||
// Return the latest cache which is just updated here.
|
||||
debug('_updateConnectedDevices(): this._connectedDevicesInfo = ' +
|
||||
JSON.stringify(this._connectedDevicesInfo));
|
||||
return Promise.resolve(this._connectedDevicesInfo);
|
||||
}, () => {
|
||||
debug('_updateConnectedDevices(): rejected with some exception');
|
||||
return Promise.reject('rejected with some exception');
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Only reset properties since there is no available default adapter.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf BluetoothConnectionManager
|
||||
*/
|
||||
_resetConnectionInfo: function btcm__resetConnectionInfo() {
|
||||
// Reset connection status.
|
||||
this.connectingAddress = null;
|
||||
// Clean up the instance to get connected devices
|
||||
// while new adapter is ready.
|
||||
this._getConnectedDevicesPromise = null;
|
||||
},
|
||||
|
||||
/**
|
||||
* Watch 'onattributechanged' event from default adapter for watching
|
||||
* adapter enabled/disabled status.
|
||||
*
|
||||
* Description of 'onattributechanged' event:
|
||||
* A handler to trigger when one of the local bluetooth adapter's properties
|
||||
* has changed. Note access to the changed property in this event handler
|
||||
* would get the updated value.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf BluetoothConnectionManager
|
||||
* @param {BluetoothAdapter} adapter
|
||||
*/
|
||||
_watchDefaultAdapterOnattributechanged:
|
||||
function btcm__watchDefaultAdapterOnattributechanged(adapter) {
|
||||
adapter.addEventListener('attributechanged',
|
||||
this._onAdapterAttributeChanged.bind(this, adapter));
|
||||
},
|
||||
|
||||
/**
|
||||
* Unwatch 'onattributechanged' event from default adapter since adapter is
|
||||
* removed.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf BluetoothConnectionManager
|
||||
* @param {BluetoothAdapter} adapter
|
||||
*/
|
||||
_unwatchDefaultAdapterOnattributechanged:
|
||||
function btcm__unwatchDefaultAdapterOnattributechanged(adapter) {
|
||||
adapter.removeEventListener('attributechanged',
|
||||
this._onAdapterAttributeChanged);
|
||||
},
|
||||
|
||||
/**
|
||||
* 'onattributechanged' event handler from default adapter for reaching
|
||||
* adapter enabled/disabled status.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf BluetoothConnectionManager
|
||||
* @param {BluetoothAdapter} adapter
|
||||
* @param {event} evt
|
||||
*/
|
||||
_onAdapterAttributeChanged:
|
||||
function btcm__onAdapterAttributeChanged(adapter, evt) {
|
||||
for (var i in evt.attrs) {
|
||||
debug('_onAdapterAttributeChanged(): ' + evt.attrs[i]);
|
||||
switch (evt.attrs[i]) {
|
||||
case 'state':
|
||||
if (adapter.state === 'enabled') {
|
||||
// Restore connection while default adapter state is enabled.
|
||||
this._restoreConnection();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Watch every of profile events('onhfpstatuschanged','ona2dpstatuschanged')
|
||||
* from default adapter for updating device connected status immediately.
|
||||
*
|
||||
* Description of 'onhfpstatuschanged' event:
|
||||
* Specifies an event listener to receive hfpstatuschanged events.
|
||||
* Those events occur when an HFP connection status changes.
|
||||
*
|
||||
* Description of 'ona2dpstatuschanged' event:
|
||||
* Specifies an event listener to receive a2dpstatuschanged events.
|
||||
* Those events occur when an A2DP connection status changes.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf BluetoothConnectionManager
|
||||
* @param {BluetoothAdapter} adapter
|
||||
*/
|
||||
_watchProfilesStatuschanged:
|
||||
function btcm__watchProfilesStatuschanged(adapter) {
|
||||
var eventName;
|
||||
for (var profileID in this.Profiles) {
|
||||
eventName = 'on' + profileID + 'statuschanged';
|
||||
adapter[eventName] =
|
||||
this._onProfileStatuschangeHandler.bind(this, profileID);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Unwatch every of profile events('onhfpstatuschanged',
|
||||
* 'ona2dpstatuschanged') from default adapter since adapter is removed.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf BluetoothConnectionManager
|
||||
* @param {BluetoothAdapter} adapter
|
||||
*/
|
||||
_unwatchProfilesStatuschanged:
|
||||
function btc__unwatchProfilesStatuschanged(adapter) {
|
||||
var eventName;
|
||||
for (var profileID in this.Profiles) {
|
||||
eventName = 'on' + profileID + 'statuschanged';
|
||||
adapter[eventName] = null;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* 'onhfpstatuschanged', 'ona2dpstatuschanged' events handler from
|
||||
* default adapter for updating device connected status.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf BluetoothConnectionManager
|
||||
* @param {String} profileID
|
||||
* @param {event} evt
|
||||
*/
|
||||
_onProfileStatuschangeHandler:
|
||||
function btcm__onProfileStatuschangeHandler(profileID, evt) {
|
||||
debug('_onProfileStatuschangeHandler(): profileID = ' + profileID +
|
||||
', evt.address = ' + evt.address + ', evt.status = ' + evt.status);
|
||||
var options = {
|
||||
address: evt.address,
|
||||
connected: evt.status,
|
||||
profileID: profileID
|
||||
};
|
||||
// Update connection status.
|
||||
this._updateConnectionStatus(options);
|
||||
},
|
||||
|
||||
/**
|
||||
* Query async storage to restore connection.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf BluetoothConnectionManager
|
||||
*/
|
||||
_restoreConnection: function btcm__restoreConnection() {
|
||||
if (!this._defaultAdapter) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Reconnect the one kept in the async storage.
|
||||
AsyncStorage.getItem('device.connected', (address) => {
|
||||
if (!address) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Make sure the restore device is already connected or not.
|
||||
this.getConnectedDevices().then((connectedDevices) => {
|
||||
if (connectedDevices && connectedDevices[address]) {
|
||||
// Do an early return since the restore device is connected already.
|
||||
debug('_restoreConnection(): early return cause connected already');
|
||||
return;
|
||||
}
|
||||
|
||||
// Get the device which is wanted to connect from paired devices.
|
||||
var restoreDevice = this._getPairedDeviceByAddress(address);
|
||||
if (restoreDevice) {
|
||||
this.connectingAddress = restoreDevice.address;
|
||||
// Fire 'connecting' event.
|
||||
var event = {
|
||||
type: 'connecting',
|
||||
detail: {
|
||||
address: restoreDevice.address
|
||||
}
|
||||
};
|
||||
this._emitEvent(event);
|
||||
this._connect(restoreDevice).then(() => {
|
||||
debug('_restoreConnection(): restore connection successfully');
|
||||
}, (reason) => {
|
||||
debug('_restoreConnection(): restore connection failed, ' +
|
||||
'reason = ' + reason);
|
||||
// No available profiles are connected. Reset connecting address.
|
||||
this.connectingAddress = null;
|
||||
// Then, fire 'disconnected' event.
|
||||
event = {
|
||||
type: 'disconnected',
|
||||
detail: {
|
||||
address: restoreDevice.address
|
||||
}
|
||||
};
|
||||
this._emitEvent(event);
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Record connected device so if Bluetooth is turned off and then on
|
||||
* we can restore the connection.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf BluetoothConnectionManager
|
||||
* @param {String} action - to set or remove item for recording connection
|
||||
* @param {String} address - the address of connected device
|
||||
*/
|
||||
_recordConnection: function btcm__recordConnection(action, address) {
|
||||
if (action === 'set') {
|
||||
// record connected device so if Bluetooth is turned off and then on
|
||||
// we can restore the connection
|
||||
AsyncStorage.setItem('device.connected', address);
|
||||
debug('_recordConnection(): set item');
|
||||
} else if ((action === 'remove') &&
|
||||
(this._defaultAdapter.state === 'enabled')) {
|
||||
// Clean up the connected device from async storage
|
||||
// which is recorded before.
|
||||
// Only remove the record while Bluetooth state is enabled.
|
||||
// Because the request also comes while Bluetooth is turned off.
|
||||
AsyncStorage.removeItem('device.connected');
|
||||
debug('_recordConnection(): remove item');
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Update connection status.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf BluetoothConnectionManager
|
||||
* @param {Object} options
|
||||
* @param {String} options.address - address of the device
|
||||
* @param {Boolean} options.connected - is connected or not
|
||||
* @param {Object} options.profileID - profile ID of the connection type
|
||||
*/
|
||||
_updateConnectionStatus: function btcm___updateConnectionStatus(options) {
|
||||
debug('_updateConnectionStatus(): address = ' + options.address +
|
||||
', connected = ' + options.connected +
|
||||
', profileID = ' + options.profileID);
|
||||
this.connectingAddress = null;
|
||||
|
||||
// Update the profile in the cache of connected device info.
|
||||
this._updateConnectedDevices(options).then((connectedDevicesInfo) => {
|
||||
debug('_updateConnectionStatus(): _updateConnectedDevices() ' +
|
||||
'resolved with connectedDevicesInfo = ' +
|
||||
JSON.stringify(connectedDevicesInfo));
|
||||
// Prepare latest data to check connected profile.
|
||||
var dataToCheckConnectedProfile = {
|
||||
address: options.address,
|
||||
connectedDevices: connectedDevicesInfo
|
||||
};
|
||||
// Fire 'connected'/'disconnected' event according to
|
||||
// the connection profile. Then, record connection.
|
||||
var event;
|
||||
if (options.connected) {
|
||||
// Fire 'connected' event.
|
||||
event = {
|
||||
type: 'connected',
|
||||
detail: {
|
||||
address: options.address
|
||||
}
|
||||
};
|
||||
this._emitEvent(event);
|
||||
// Record connection.
|
||||
this._recordConnection('set', options.address);
|
||||
} else {
|
||||
// If there is no profile connected,
|
||||
// we have to remove the record connection.
|
||||
// And fire 'disconnected' event for outer modules.
|
||||
if (!this._hasConnectedProfileByAddress(
|
||||
dataToCheckConnectedProfile)) {
|
||||
// Record connection. Only remove the record while Bluetooth state
|
||||
// is enabled. Because the event also comes while Bluetooth is
|
||||
// turned off.
|
||||
if (this._defaultAdapter.state === 'enabled') {
|
||||
this._recordConnection('remove');
|
||||
}
|
||||
// Fire 'disconnected' event.
|
||||
event = {
|
||||
type: 'disconnected',
|
||||
detail: {
|
||||
address: options.address
|
||||
}
|
||||
};
|
||||
this._emitEvent(event);
|
||||
}
|
||||
}
|
||||
|
||||
// Fire 'profileChanged' event.
|
||||
var newProfiles;
|
||||
if (!this._hasConnectedProfileByAddress(dataToCheckConnectedProfile)) {
|
||||
newProfiles = null;
|
||||
} else {
|
||||
newProfiles = connectedDevicesInfo[options.address].connectedProfiles;
|
||||
}
|
||||
event = {
|
||||
type: 'profileChanged',
|
||||
detail: {
|
||||
address: options.address,
|
||||
profiles: newProfiles
|
||||
}
|
||||
};
|
||||
this._emitEvent(event);
|
||||
}, (reason) => {
|
||||
debug('_updateConnectionStatus(): miss to update in rejected case, ' +
|
||||
'reason = ' + reason);
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* It provides a convenient function for panel to connect with a device.
|
||||
* And the panel no need to care about connected device currently.
|
||||
* The method will disconnect current connected device first.
|
||||
* Then, it will start connecting a paired device with the device's adapter.
|
||||
*
|
||||
* @access public
|
||||
* @memberOf BluetoothConnectionManager
|
||||
* @param {BluetoothDevice} device
|
||||
* @return {Promise}
|
||||
*/
|
||||
connect: function btcm_connect(device) {
|
||||
if (!this._defaultAdapter) {
|
||||
return Promise.reject('default adapter is not existed!!');
|
||||
}
|
||||
|
||||
// Disconnect current connected device first.
|
||||
debug('connect(): Want to connect device address = ' + device.address +
|
||||
', name = ' + device.name);
|
||||
|
||||
var connectedDevices = [];
|
||||
return this.getConnectedDevices().then((connectedDevicesInfo) => {
|
||||
for (var address in connectedDevicesInfo) {
|
||||
if (connectedDevicesInfo[address].device !== null) {
|
||||
connectedDevices.push(connectedDevicesInfo[address].device);
|
||||
debug('connect(): push device cache in queue = ' +
|
||||
JSON.stringify(connectedDevices));
|
||||
} else {
|
||||
var regetPairedDevice = this._getPairedDeviceByAddress(address);
|
||||
connectedDevices.push(regetPairedDevice);
|
||||
debug('connect(): push _getPairedDeviceByAddress in queue = ' +
|
||||
JSON.stringify(regetPairedDevice));
|
||||
}
|
||||
}
|
||||
|
||||
debug('connect(): Will disconnect these connected devices = ' +
|
||||
JSON.stringify(connectedDevices));
|
||||
|
||||
// Disconnect these connected device before
|
||||
// service to connect with new device.
|
||||
return Promise.all(connectedDevices.map((connectedDevice) => {
|
||||
return this.disconnect(connectedDevice);
|
||||
})).then(() => {
|
||||
// All connected devices is disconnected.
|
||||
// We can start to connect the new request.
|
||||
debug('connect(): Start to connect with wanted device address = ' +
|
||||
device.address);
|
||||
return this._connect(device).then(() => {
|
||||
debug('connect(): Resolved');
|
||||
}, (reason) => {
|
||||
debug('connect(): reason = ' + reason);
|
||||
return Promise.reject(reason);
|
||||
});
|
||||
});
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* The method will connect the input device with the device's adapter.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf BluetoothConnectionManager
|
||||
* @param {BluetoothDevice} device
|
||||
* @returns {Promise}
|
||||
*/
|
||||
_connect: function btcm__connect(device) {
|
||||
if (!this._defaultAdapter) {
|
||||
return Promise.reject('default adapter is not existed!!');
|
||||
}
|
||||
|
||||
// Save the connecting address
|
||||
this.connectingAddress = device.address;
|
||||
// Fire 'connecting' event.
|
||||
var event = {
|
||||
type: 'connecting',
|
||||
detail: {
|
||||
address: device.address
|
||||
}
|
||||
};
|
||||
this._emitEvent(event);
|
||||
debug('_connect(): before start to connect, stop discovery first');
|
||||
|
||||
// Note on Bluedroid stack, discovery has to be stopped before connect
|
||||
// (i.e., call stopDiscovery() before connect())
|
||||
// otherwise stack callbacks with connect failure.
|
||||
return this._defaultAdapter.stopDiscovery().then(() => {
|
||||
debug('_connect(): start connecting device, ' +
|
||||
'address = ' + device.address);
|
||||
return this._defaultAdapter.connect(device).then(() => {
|
||||
debug('_connect(): resolve, already connected with address = ' +
|
||||
device.address);
|
||||
}, () => {
|
||||
// No available profiles are connected. Reset connecting address.
|
||||
this.connectingAddress = null;
|
||||
// Fire 'disconnected' event.
|
||||
event = {
|
||||
type: 'disconnected',
|
||||
detail: {
|
||||
address: device.address
|
||||
}
|
||||
};
|
||||
this._emitEvent(event);
|
||||
debug('_connect(): reject with connection failed');
|
||||
return Promise.reject('connection failed');
|
||||
});
|
||||
}, () => {
|
||||
// Cannot connect with the device since stopDiscovery failed.
|
||||
this.connectingAddress = null;
|
||||
// Fire 'disconnected' event.
|
||||
event = {
|
||||
type: 'disconnected',
|
||||
detail: {
|
||||
address: device.address
|
||||
}
|
||||
};
|
||||
this._emitEvent(event);
|
||||
debug('_connect(): reject with stop discovery failed');
|
||||
return Promise.reject('stop discovery failed');
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* The method will disconnect the input device with the device's adapter.
|
||||
*
|
||||
* @access public
|
||||
* @memberOf BluetoothConnectionManager
|
||||
* @param {BluetoothDevice} device
|
||||
* @returns {Promise}
|
||||
*/
|
||||
disconnect: function btcm_disconnect(device) {
|
||||
if (!this._defaultAdapter) {
|
||||
return Promise.reject('default adapter is not existed!!');
|
||||
}
|
||||
|
||||
return this._defaultAdapter.disconnect(device).then(() => {
|
||||
debug('disconnect(): onsuccess(): resolve');
|
||||
}, () => {
|
||||
debug('disconnect(): onerror(): reject with disconnect failed');
|
||||
return Promise.reject('disconnect failed');
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* The method will get all connected devices profiles
|
||||
* which we are interested in. Profile: HFP, A2DP.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf BluetoothConnectionManager
|
||||
* @returns {Promise} resolve: connectedDevices
|
||||
* @returns {Promise} reject: reason
|
||||
*/
|
||||
_getConnectedDevicesFromPlatform:
|
||||
function btcm__getConnectedDevicesFromPlatform() {
|
||||
// Get connected device via profiles HFP, A2DP
|
||||
return Promise.all(Object.keys(this.Profiles).map((profile) => {
|
||||
return this._getConnectedDevicesByProfile(this.Profiles[profile]);
|
||||
})).then((connectedDevices) => {
|
||||
// Update each connected devices in map.
|
||||
var collectedConnectedDevicesByProfile = {};
|
||||
Object.keys(this.Profiles).forEach((profile, index) => {
|
||||
collectedConnectedDevicesByProfile[profile] = connectedDevices[index];
|
||||
});
|
||||
debug('_getConnectedDevicesFromPlatform(): ' +
|
||||
'collectedConnectedDevicesByProfile = ' +
|
||||
JSON.stringify(collectedConnectedDevicesByProfile));
|
||||
return Promise.resolve(collectedConnectedDevicesByProfile);
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* The method will get connected device by inputed profile.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf BluetoothConnectionManager
|
||||
* @param {String} profileID
|
||||
* @returns {Promise} resolve: the connected devices in array
|
||||
* @returns {Promise} reject: reason
|
||||
*/
|
||||
_getConnectedDevicesByProfile:
|
||||
function btcm__getConnectedDevicesByProfile(profileID) {
|
||||
if (!this._defaultAdapter) {
|
||||
debug('_getConnectedDevicesByProfile(): reject with no adapter');
|
||||
return Promise.reject('default adapter is not existed!!');
|
||||
}
|
||||
|
||||
if (this._defaultAdapter.state === 'disabled') {
|
||||
debug('_getConnectedDevicesByProfile(): resolve with empty array ' +
|
||||
'since it is impossible to connect with any device');
|
||||
return Promise.reject('getConnectedDevices in disabled state');
|
||||
}
|
||||
|
||||
return this._defaultAdapter.getConnectedDevices(profileID).then(
|
||||
(connectedDevice) => {
|
||||
debug('_getConnectedDevicesByProfile(): resolved with ' +
|
||||
'connectedDevice = ' + JSON.stringify(connectedDevice));
|
||||
return Promise.resolve(connectedDevice || []);
|
||||
}, (reason) => {
|
||||
debug('_getConnectedDevicesByProfile(): rejected with ' +
|
||||
'reason = ' + reason);
|
||||
return Promise.reject(reason);
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Get device from paired devices by address.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf BluetoothConnectionManager
|
||||
* @param {String} address
|
||||
*/
|
||||
_getPairedDeviceByAddress:
|
||||
function btcm__getPairedDeviceByAddress(address) {
|
||||
if (!this._defaultAdapter) {
|
||||
return null;
|
||||
}
|
||||
|
||||
var pairedDevices = this._defaultAdapter.getPairedDevices();
|
||||
if (pairedDevices.length === 0) {
|
||||
return null;
|
||||
} else {
|
||||
for (var i in pairedDevices) {
|
||||
if (pairedDevices[i].address === address) {
|
||||
return pairedDevices[i];
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Find out there is any profile still connected.
|
||||
*
|
||||
* @access private
|
||||
* @memberOf BluetoothConnectionManager
|
||||
* @param {Object} options
|
||||
* @param {String} options.connectedDevices - connected devices info
|
||||
* @param {String} options.address - the address of device
|
||||
*/
|
||||
_hasConnectedProfileByAddress:
|
||||
function btcm__hasConnectedProfileByAddress(options) {
|
||||
if (!options.connectedDevices[options.address]) {
|
||||
return false;
|
||||
}
|
||||
|
||||
var hasConnectedProfile = false;
|
||||
for (var profileID in this.Profiles) {
|
||||
var connectedProfiles =
|
||||
options.connectedDevices[options.address].connectedProfiles;
|
||||
if (connectedProfiles && (connectedProfiles[profileID] === true)) {
|
||||
hasConnectedProfile = true;
|
||||
}
|
||||
}
|
||||
return hasConnectedProfile;
|
||||
},
|
||||
|
||||
/**
|
||||
* A function to emit event to each registered listener by the input type.
|
||||
*
|
||||
* @memberOf BluetoothConnectionManager
|
||||
* @param {Object} options
|
||||
* @param {String} options.type - type of event name
|
||||
* @param {Object} options.detail - the object pass to the listener
|
||||
*/
|
||||
_emitEvent: function btcm__emitEvent(options) {
|
||||
this._listeners[options.type].forEach(function(listener) {
|
||||
listener(options);
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* The method will provide event listener for outer modules to regist.
|
||||
*
|
||||
* @access public
|
||||
* @memberOf BluetoothConnectionManager
|
||||
* @param {String} eventName
|
||||
* @param {Function} callback
|
||||
*/
|
||||
addEventListener: function btcm_addEventListener(eventName, callback) {
|
||||
if (callback && (this._listeners.hasOwnProperty(eventName))) {
|
||||
this._listeners[eventName].push(callback);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* The method will provide event listener for outer modules to un-regist.
|
||||
*
|
||||
* @access public
|
||||
* @memberOf BluetoothConnectionManager
|
||||
* @param {String} eventName
|
||||
* @param {Function} callback
|
||||
*/
|
||||
removeEventListener:
|
||||
function btcm_removeEventListener(eventName, callback) {
|
||||
if (callback && (this._listeners.hasOwnProperty(eventName))) {
|
||||
var index = this._listeners[eventName].indexOf(callback);
|
||||
if (index >= 0) {
|
||||
this._listeners[eventName].splice(index, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
BluetoothConnectionManager._init();
|
||||
return BluetoothConnectionManager;
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue