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
210 changed files with 9982925 additions and 369 deletions
23
gaia/shared/js/accessibility_helper.js
Executable file
23
gaia/shared/js/accessibility_helper.js
Executable file
|
|
@ -0,0 +1,23 @@
|
|||
'use strict';
|
||||
|
||||
(function(exports) {
|
||||
|
||||
var AccessibilityHelper = {
|
||||
/**
|
||||
* For a set of tab elements, set aria-selected attribute in accordance with
|
||||
* the current selection.
|
||||
* @param {Object} selectedTab a tab to select object.
|
||||
* @param {Array} tabs an array of tabs.
|
||||
*/
|
||||
setAriaSelected: function ah_setAriaSelected(selectedTab, tabs) {
|
||||
// In case tabs is a NodeList, that does not have forEach.
|
||||
Array.prototype.forEach.call(tabs, function setAriaSelectedAttr(tab) {
|
||||
tab.setAttribute('aria-selected',
|
||||
tab === selectedTab ? 'true' : 'false');
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
exports.AccessibilityHelper = AccessibilityHelper;
|
||||
|
||||
})(window);
|
||||
182
gaia/shared/js/achievements-service.js
Executable file
182
gaia/shared/js/achievements-service.js
Executable file
|
|
@ -0,0 +1,182 @@
|
|||
/* Taken from https://github.com/fxos/achievements-service and in particular,
|
||||
built from https://github.com/fxos/achievements-service/blob/master/
|
||||
achievements-service.js */
|
||||
|
||||
(function(exports) {
|
||||
'use strict';
|
||||
|
||||
var _toArray = function (arr) {
|
||||
return Array.isArray(arr) ? arr : Array.from(arr);
|
||||
};
|
||||
|
||||
/* global Notification, console */
|
||||
|
||||
var DEFAULT_IMAGE_SIZE = 64;
|
||||
var MOZ_SETTINGS_NOT_AVAILABLE_MSG = 'navigator.mozSettings is not available';
|
||||
|
||||
var ImageHelper = (function () {
|
||||
var ImageHelper = function ImageHelper() {};
|
||||
|
||||
ImageHelper.getImage = function (aSrc) {
|
||||
return new Promise(function (resolve, reject) {
|
||||
var image = new Image();
|
||||
image.src = aSrc;
|
||||
image.onload = function () {
|
||||
return resolve(image);
|
||||
};
|
||||
image.onerror = function (reason) {
|
||||
return reject(reason);
|
||||
};
|
||||
})['catch'](function (reason) {
|
||||
return console.warn('Could not load an achievement image:', reason);
|
||||
});
|
||||
};
|
||||
|
||||
ImageHelper.generateImageDataURL = function (aSrc) {
|
||||
return ImageHelper.getImage(aSrc).then(function (image) {
|
||||
try {
|
||||
var canvas = document.createElement('canvas');
|
||||
canvas.height = canvas.width = DEFAULT_IMAGE_SIZE;
|
||||
var context = canvas.getContext('2d');
|
||||
var dataUrl;
|
||||
|
||||
context.drawImage(image, 0, 0, DEFAULT_IMAGE_SIZE,
|
||||
DEFAULT_IMAGE_SIZE);
|
||||
dataUrl = canvas.toDataURL();
|
||||
|
||||
// Clean up.
|
||||
canvas.width = canvas.height = 0;
|
||||
canvas = null;
|
||||
|
||||
return dataUrl;
|
||||
} catch (e) {
|
||||
return Promise.reject('Could not convert image to Data URL.');
|
||||
}
|
||||
})['catch'](function (reason) {
|
||||
return console.warn(reason);
|
||||
});
|
||||
};
|
||||
|
||||
return ImageHelper;
|
||||
})();
|
||||
|
||||
var SettingsHelper = (function () {
|
||||
var SettingsHelper = function SettingsHelper() {};
|
||||
|
||||
SettingsHelper.get = function (name, defaultValue) {
|
||||
if (!name) {
|
||||
return Promise.reject('Setting name is missing');
|
||||
}
|
||||
|
||||
if (!navigator.mozSettings) {
|
||||
console.warn(MOZ_SETTINGS_NOT_AVAILABLE_MSG);
|
||||
return Promise.reject(MOZ_SETTINGS_NOT_AVAILABLE_MSG);
|
||||
}
|
||||
|
||||
return new Promise(function (resolve, reject) {
|
||||
var setting = navigator.mozSettings.createLock().get(name,
|
||||
defaultValue);
|
||||
setting.onsuccess = function () {
|
||||
var settingValue = setting.result[name] || defaultValue;
|
||||
resolve(settingValue);
|
||||
};
|
||||
setting.onerror = function () {
|
||||
reject(setting.error);
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
SettingsHelper.set = function (settings) {
|
||||
if (!settings) {
|
||||
return Promise.reject('Settings are missing');
|
||||
}
|
||||
|
||||
if (!navigator.mozSettings) {
|
||||
console.warn(MOZ_SETTINGS_NOT_AVAILABLE_MSG);
|
||||
return Promise.reject(MOZ_SETTINGS_NOT_AVAILABLE_MSG);
|
||||
}
|
||||
|
||||
return new Promise(function (resolve, reject) {
|
||||
var result = navigator.mozSettings.createLock().set(settings);
|
||||
result.onsuccess = function () {
|
||||
resolve(result.result);
|
||||
};
|
||||
result.onerror = function () {
|
||||
reject(result.error);
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
return SettingsHelper;
|
||||
})();
|
||||
|
||||
var AchievementsService = (function () {
|
||||
var AchievementsService = function AchievementsService() {};
|
||||
|
||||
AchievementsService.prototype.reward = function (_ref) {
|
||||
var criteria = _ref.criteria;
|
||||
var evidence = _ref.evidence;
|
||||
var name = _ref.name;
|
||||
var description = _ref.description;
|
||||
var image = _ref.image;
|
||||
if (!evidence) {
|
||||
return Promise.reject('Evidence is not provided.');
|
||||
}
|
||||
|
||||
var issuedOn;
|
||||
return SettingsHelper.get('achievements', []).then(
|
||||
function (achievements) {
|
||||
var achievement = achievements.find(function (achievement) {
|
||||
return achievement.criteria === criteria;
|
||||
});
|
||||
|
||||
if (!achievement) {
|
||||
return Promise.reject('Achievement is not registered.');
|
||||
}
|
||||
if (achievement.evidence) {
|
||||
return Promise.reject('Achievement is already awarded.');
|
||||
}
|
||||
|
||||
achievement.evidence = evidence;
|
||||
achievement.uid = 'achievement' +
|
||||
Math.round(Math.random() * 100000000);
|
||||
achievement.issuedOn = issuedOn = Date.now();
|
||||
achievement.recipient = {}; // TODO
|
||||
|
||||
return achievements;
|
||||
}).then(function (achievements) {
|
||||
return Promise.all([ImageHelper.generateImageDataURL(image),
|
||||
SettingsHelper.set({ achievements: achievements })]);
|
||||
}).then(function (_ref2) {
|
||||
var _ref3 = _toArray(_ref2);
|
||||
|
||||
var image = _ref3[0];
|
||||
// Send a Notification via WebAPI to be handled by the Gaia::System
|
||||
var notification = new Notification(name, {
|
||||
body: description,
|
||||
icon: image,
|
||||
tag: issuedOn
|
||||
});
|
||||
|
||||
notification.onclick = function () {
|
||||
var activity = new window.MozActivity({
|
||||
name: 'configure',
|
||||
data: {
|
||||
target: 'device',
|
||||
section: 'achievements'
|
||||
}
|
||||
});
|
||||
activity.onsuccess = activity.onerror = function () {
|
||||
notification.close();
|
||||
};
|
||||
};
|
||||
})['catch'](function (reason) {
|
||||
return console.warn(reason);
|
||||
});
|
||||
};
|
||||
|
||||
return AchievementsService;
|
||||
})();
|
||||
|
||||
exports.AchievementsService = AchievementsService;
|
||||
})(window);
|
||||
141
gaia/shared/js/addons/match_pattern.js
Executable file
141
gaia/shared/js/addons/match_pattern.js
Executable file
|
|
@ -0,0 +1,141 @@
|
|||
'use strict';
|
||||
|
||||
(function(exports) {
|
||||
|
||||
/**
|
||||
* Match pattern is ported from
|
||||
* https://mxr.mozilla.org/mozilla-central/source/toolkit/modules/addons
|
||||
* /MatchPattern.jsm
|
||||
* which in itself implements pattern matching based on Chrome Apps Platform
|
||||
* API https://developer.chrome.com/extensions/match_patterns
|
||||
*
|
||||
* MatchPattern is used by the add-on manager to match add-ons to apps that
|
||||
* they affect.
|
||||
*/
|
||||
|
||||
const PERMITTED_SCHEMES = ['http', 'https', 'file', 'ftp', 'app'];
|
||||
|
||||
// This function converts a glob pattern (containing * and possibly ?
|
||||
// as wildcards) to a regular expression.
|
||||
function globToRegexp(pat, allowQuestion) {
|
||||
// Escape everything except ? and *.
|
||||
pat = pat.replace(/[.+^${}()|[\]\\]/g, '\\$&');
|
||||
|
||||
if (allowQuestion) {
|
||||
pat = pat.replace(/\?/g, '.');
|
||||
} else {
|
||||
pat = pat.replace(/\?/g, '\\?');
|
||||
}
|
||||
pat = pat.replace(/\*/g, '.*');
|
||||
return new RegExp('^' + pat + '$');
|
||||
}
|
||||
|
||||
// These patterns follow the syntax in
|
||||
// https://developer.chrome.com/extensions/match_patterns
|
||||
function SingleMatchPattern(pat) {
|
||||
if (pat == '<all_urls>') {
|
||||
this.scheme = PERMITTED_SCHEMES;
|
||||
this.host = '*';
|
||||
this.path = new RegExp('.*');
|
||||
} else if (!pat) {
|
||||
this.scheme = [];
|
||||
} else {
|
||||
var re = new RegExp(
|
||||
'^(http|https|file|ftp|app|\\*)://(\\*|\\*\\.[^*/]+|[^*/]+|)(/.*)$');
|
||||
var match = re.exec(pat);
|
||||
if (!match) {
|
||||
console.error(`Invalid match pattern: '${pat}'`);
|
||||
this.scheme = [];
|
||||
return;
|
||||
}
|
||||
|
||||
if (match[1] == '*') {
|
||||
this.scheme = ['http', 'https'];
|
||||
} else {
|
||||
this.scheme = [match[1]];
|
||||
}
|
||||
this.host = match[2];
|
||||
this.path = globToRegexp(match[3], false);
|
||||
|
||||
// We allow the host to be empty for file URLs.
|
||||
if (this.host === '' && this.scheme[0] !== 'file') {
|
||||
console.error(`Invalid match pattern: '${pat}'`);
|
||||
this.scheme = [];
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SingleMatchPattern.prototype = {
|
||||
matches(uri, ignorePath = false) {
|
||||
if (this.scheme.indexOf(uri.protocol.slice(0, -1)) == -1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// This code ignores the port, as Chrome does.
|
||||
if (this.host == '*') {
|
||||
// Don't check anything.
|
||||
} else if (this.host[0] == '*') {
|
||||
// It must be *.foo. We also need to allow foo by itself.
|
||||
var suffix = this.host.substr(2);
|
||||
if (uri.hostname != suffix && !uri.hostname.endsWith('.' + suffix)) {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
if (this.host != uri.hostname) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (!ignorePath && !this.path.test(uri.pathname)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Match Pattern allows to match patterns based on set of URLs
|
||||
* @class MatchPattern
|
||||
* @returns {MatchPattern}
|
||||
*/
|
||||
function MatchPattern(pat) {
|
||||
this.pat = pat;
|
||||
if (!pat) {
|
||||
this.matchers = [];
|
||||
} else if (pat instanceof String || typeof(pat) === 'string') {
|
||||
this.matchers = [new SingleMatchPattern(pat)];
|
||||
} else {
|
||||
this.matchers = Array.from(pat, p => new SingleMatchPattern(p));
|
||||
}
|
||||
}
|
||||
|
||||
MatchPattern.prototype = {
|
||||
// |uri| should be an nsIURI.
|
||||
matches(uri) {
|
||||
for (var matcher of this.matchers) {
|
||||
if (matcher.matches(uri)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
},
|
||||
|
||||
matchesIgnoringPath(uri) {
|
||||
for (var matcher of this.matchers) {
|
||||
if (matcher.matches(uri, true)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
},
|
||||
|
||||
serialize() {
|
||||
return this.pat;
|
||||
},
|
||||
};
|
||||
|
||||
exports.MatchPattern = MatchPattern;
|
||||
|
||||
})(window);
|
||||
182
gaia/shared/js/advanced_telemetry_helper.js
Executable file
182
gaia/shared/js/advanced_telemetry_helper.js
Executable file
|
|
@ -0,0 +1,182 @@
|
|||
/*
|
||||
* This module is a helper for recording telemetry data in Gecko’s telemetry
|
||||
* system. Currently, only data from certified apps will be recorded.
|
||||
*
|
||||
* There are three different types of metrics that can be used here:
|
||||
* Counter: This is a simple counter that increments by 1 each time it's
|
||||
* called.
|
||||
*
|
||||
* Linear: This type of metric creates a linear distributed set of buckets
|
||||
* which range between the min and max. You can specify the number
|
||||
* of buckets as well as the min and max.
|
||||
*
|
||||
* Exponential: This type of metric creates an exponential distributed set of
|
||||
* buckets ranging between min and max. You can specify the min,
|
||||
* max, and buckets.
|
||||
*
|
||||
* App Setup:
|
||||
* 1) Add the following to the app (e.g. index.html):
|
||||
* <script defer src="/shared/js/advanced_telemetry_helper.js"></script>
|
||||
* <script defer src="/shared/js/settings_listener.js"></script>
|
||||
* 2) Include AdvancedTelemetryHelper in the globals.
|
||||
*
|
||||
* Counter Metric Usage Example:
|
||||
* // This creates the histogram counter on this metric called
|
||||
* // 'mycount'
|
||||
* var count = new AdvancedTelemetryHelper(ATH.HISTOGRAM_COUNT, 'mycount');
|
||||
* count.add(); //Increment the count. The count of the histogram is now 1.
|
||||
* // DO SOMETHING
|
||||
* count.add(); //Increment the count. The count of the histogram is now 2.
|
||||
*
|
||||
* Linear Metric Usage Example:
|
||||
* // This creates a linear histogram called 'mylinear' with minimum
|
||||
* // of 1 (0 not allowed as a minimum), max of 1000, with 10 buckets.
|
||||
* var linear = new AdvancedTelemetryHelper(ATH.HISTOGRAM_LINEAR, 'mylinear',
|
||||
* 1, 1000, 10);
|
||||
* // This adds the value 15 to the histogram 'mylinear'
|
||||
* linear.add(15);
|
||||
* // DO SOMETHING
|
||||
* // This adds to the existing histogram a value of 800.
|
||||
* linear.add(800); // The histogram now has two values, one in the 15 bucket
|
||||
* // and one in the bucket that holds the value 800
|
||||
*
|
||||
* Exponential Metric Usage Example:
|
||||
* // This creates an exponential histogram called 'myexp' with minimum
|
||||
* // of 1 (0 not allowed as a minimum), max of 1000, with 10 buckets.
|
||||
* var exp = new AdvancedTelemetryHelper(ATH.HISTOGRAM_EXPONENTIAL, 'myexp',
|
||||
* 1, 1000, 10);
|
||||
* // This adds the value 15 to the histogram 'myexp'
|
||||
* exp.add(15);
|
||||
* // DO SOMETHING
|
||||
* // This adds to the existing histogram a value of 800.
|
||||
* exp.add(800); // The histogram now has two values, one in the 15 bucket
|
||||
* // and one in the bucket that holds the value 800
|
||||
*
|
||||
* Caveats:
|
||||
* Note that after a histogram is created, it's not possible to change the type
|
||||
* of the histogram from one type to the other. It's necessary to create a new
|
||||
* Histogram.
|
||||
*
|
||||
* Each histogram should have a unique name.
|
||||
*
|
||||
*/
|
||||
|
||||
/* globals SettingsListener */
|
||||
(function(exports) {
|
||||
'use strict';
|
||||
|
||||
const APP_TELEMETRY_LOG_PREFIX = 'telemetry';
|
||||
const ATH = AdvancedTelemetryHelper;
|
||||
// Export Histogram types so they can be used by apps
|
||||
ATH.HISTOGRAM_COUNT = 4;
|
||||
ATH.HISTOGRAM_EXP = 0;
|
||||
ATH.HISTOGRAM_LINEAR = 1;
|
||||
// This is exposed for unit testing purposes
|
||||
ATH.TELEMETRY_LEVEL_KEY = 'metrics.selectedMetrics.level';
|
||||
ATH.SETTINGS_INITIALIZED = false;
|
||||
|
||||
// API for an exponential histogram entry. This function creates the
|
||||
// histogram in the system and prepares it subsequent .log(value) calls
|
||||
// against it.
|
||||
// <type>: One of ATH.HISTOGRAM_COUNT, ATH.HISTOGRAM_EXP,
|
||||
// or ATH.HISTOGRAM_LINEAR.
|
||||
// <name>: Unique name of the metric
|
||||
// <min>: [Required for linear and exponential only]The minimum (non-zero)
|
||||
// numeric value for this histogram.
|
||||
// <max>: [Required for linear and exponential only]The maximum numeric
|
||||
// value for this histogram.
|
||||
// <buckets>: [Required for linear and exponential only]The total number of
|
||||
// buckets for this histogram.
|
||||
function AdvancedTelemetryHelper(type, name, min, max, buckets) {
|
||||
if (!ATH.SETTINGS_INITIALIZED) {
|
||||
ATH.SETTINGS_INITIALIZED = true;
|
||||
ATH.init();
|
||||
}
|
||||
|
||||
if (typeof type !== 'undefined' && typeof name !== 'undefined') {
|
||||
if (type === ATH.HISTOGRAM_COUNT) {
|
||||
this.createHistogram(name, ATH.HISTOGRAM_COUNT, 0, 0, 0);
|
||||
} else if (type === ATH.HISTOGRAM_EXP || type === ATH.HISTOGRAM_LINEAR) {
|
||||
this.createHistogram(name, type, min, max, buckets);
|
||||
} else {
|
||||
console.warn('Must pass a Histogram type and a unique Histogram name.');
|
||||
}
|
||||
} else {
|
||||
console.warn('Must pass a Histogram type and a unique Histogram name.');
|
||||
}
|
||||
}
|
||||
|
||||
AdvancedTelemetryHelper.init = function init() {
|
||||
ATH.telemetryEnabledListener = function telemetryEnabledListener(enabled) {
|
||||
if (enabled === 'Enhanced') {
|
||||
ATH.TELEMETRY_LEVEL = true;
|
||||
} else {
|
||||
ATH.TELEMETRY_LEVEL = false;
|
||||
}
|
||||
}.bind(this);
|
||||
|
||||
SettingsListener.observe(ATH.TELEMETRY_LEVEL_KEY,
|
||||
false, ATH.telemetryEnabledListener);
|
||||
};
|
||||
|
||||
AdvancedTelemetryHelper.prototype.createHistogram =
|
||||
function(name, type, min, max, buckets) {
|
||||
if (typeof ATH.TELEMETRY_LEVEL === 'undefined' || ATH.TELEMETRY_LEVEL) {
|
||||
if (typeof this.metricType !== 'undefined') {
|
||||
console.warn('Cannot redefine histogram. Must create a new object');
|
||||
return;
|
||||
}
|
||||
|
||||
this.metricType = type;
|
||||
if (typeof name !== 'undefined') {
|
||||
var varCount = 2;
|
||||
var re = /_/g;
|
||||
var message = APP_TELEMETRY_LOG_PREFIX;
|
||||
// Disallow underscores so telemetry system can parse it.
|
||||
this.metricName = name.replace(re, '-');
|
||||
message += '|' + this.metricName;
|
||||
message += '|' + type + '|';
|
||||
if (typeof min !== 'undefined') { varCount++; }
|
||||
if (typeof max !== 'undefined') { varCount++; }
|
||||
if (typeof buckets !== 'undefined') { varCount++; }
|
||||
|
||||
if (varCount != 5) {
|
||||
console.warn('createHistogram must have 5 params.');
|
||||
return;
|
||||
}
|
||||
|
||||
if (min < 1) {
|
||||
min = 1;
|
||||
}
|
||||
message += min + '|' + max + '|' + buckets;
|
||||
console.info(message);
|
||||
} else {
|
||||
console.warn('A telemetry log entry requires a name.');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// API for logging against a pre-existing histogram. This records the value
|
||||
// for this particular histogram in the histogram system.
|
||||
// <value>: The value to record against this histogram.
|
||||
// For a counter histogram, this can be empty or 1 can be passed.
|
||||
// For an exponential or linear histogram a valid value > 0 must be passed.
|
||||
AdvancedTelemetryHelper.prototype.add = function(value) {
|
||||
if (typeof ATH.TELEMETRY_LEVEL === 'undefined' || ATH.TELEMETRY_LEVEL) {
|
||||
if (this.metricType == ATH.HISTOGRAM_COUNT) {
|
||||
value = 1;
|
||||
}
|
||||
|
||||
if (typeof value === 'undefined' || !value || value < 1) {
|
||||
console.warn('A valid value is required to log a histogram.');
|
||||
return;
|
||||
}
|
||||
|
||||
var message = APP_TELEMETRY_LOG_PREFIX + '|' + this.metricName +
|
||||
'|' + value;
|
||||
console.info(message);
|
||||
}
|
||||
};
|
||||
|
||||
exports.AdvancedTelemetryHelper = AdvancedTelemetryHelper;
|
||||
}(window));
|
||||
56
gaia/shared/js/advanced_timer.js
Executable file
56
gaia/shared/js/advanced_timer.js
Executable file
|
|
@ -0,0 +1,56 @@
|
|||
/* exported advanced_timer */
|
||||
|
||||
'use strict';
|
||||
|
||||
var advanced_timer = {
|
||||
/**
|
||||
* Maps between user Ids and navigator ones
|
||||
*/
|
||||
timers: {},
|
||||
|
||||
/**
|
||||
* Register a new timer with the user's timerId
|
||||
*/
|
||||
start: function(timerId, timeout, callback) {
|
||||
if (typeof(callback) != 'function') {
|
||||
callback = function() {};
|
||||
}
|
||||
|
||||
var self = this;
|
||||
var _id = setTimeout(function advTimer() {
|
||||
var realUsedTime = new Date().getTime() - self.timers[timerId].timestamp;
|
||||
delete(self.timers[timerId]);
|
||||
callback(realUsedTime);
|
||||
}, timeout);
|
||||
this.timers[timerId] = {
|
||||
'timeout': timeout,
|
||||
'internalTimerId': _id,
|
||||
'timestamp': new Date().getTime()
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
* Stops timer and returns the pending time
|
||||
*/
|
||||
stop: function(timerId) {
|
||||
var timer = this.timers[timerId];
|
||||
if (!timer) {
|
||||
return 0;
|
||||
}
|
||||
clearTimeout(timer.internalTimerId);
|
||||
var pendingTime = this.queryPendingTime();
|
||||
delete(this.timers[timerId]);
|
||||
return pendingTime;
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns the pending time to timeout the timer
|
||||
*/
|
||||
queryPendingTime: function(timerId) {
|
||||
var timer = this.timers[timerId];
|
||||
if (!timer) {
|
||||
return 0;
|
||||
}
|
||||
return timer.timeout - (new Date().getTime() - timer.timestamp);
|
||||
}
|
||||
};
|
||||
112
gaia/shared/js/airplane_mode_helper.js
Executable file
112
gaia/shared/js/airplane_mode_helper.js
Executable file
|
|
@ -0,0 +1,112 @@
|
|||
/* exported AirplaneModeHelper */
|
||||
|
||||
/*
|
||||
* AirplaneModeHelper is a helper that makes apps enable / disable
|
||||
* airplane mode easily. It will expose few methods for you :
|
||||
*
|
||||
* 1. AirplaneModeHelper.ready();
|
||||
* 2. AirplaneModeHelper.setEnabled();
|
||||
* 3. AirplaneModeHelper.getStatus();
|
||||
* 4. AirplaneModeHelper.addEventListener('statechange', callback)
|
||||
* 5. AirplaneModeHelper.removeEventListener('statechange', callback)
|
||||
*
|
||||
* If you want to call getStatus(), please make sure to put them inside
|
||||
* an anonymous function in AirplaneModeHelper.ready() because this is
|
||||
* an async call.
|
||||
*
|
||||
* Like this:
|
||||
*
|
||||
* AirplaneModeHelper.ready(function() {
|
||||
* var status = AirplaneModeHelper.getStatus();
|
||||
* });
|
||||
*/
|
||||
|
||||
(function(exports) {
|
||||
'use strict';
|
||||
// constants
|
||||
const kEventName = 'statechange';
|
||||
const kCommunicationKey = 'airplaneMode.enabled';
|
||||
const kStatusKey = 'airplaneMode.status';
|
||||
|
||||
// main
|
||||
var AirplaneModeHelper = {
|
||||
_mozSettings: window.navigator.mozSettings,
|
||||
_callbacks: [],
|
||||
_cachedStatus: '',
|
||||
ready: function(cb) {
|
||||
if (this._cachedStatus === '') {
|
||||
var self = this;
|
||||
this.addEventListener(kEventName, function onChangeEvent() {
|
||||
// make sure _cachedStatus is definitely not ''
|
||||
if (self._cachedStatus !== '') {
|
||||
self.removeEventListener(kEventName, onChangeEvent);
|
||||
cb();
|
||||
}
|
||||
});
|
||||
} else {
|
||||
cb();
|
||||
}
|
||||
},
|
||||
getStatus: function() {
|
||||
return this._cachedStatus;
|
||||
},
|
||||
addEventListener: function(eventName, callback) {
|
||||
if (eventName === kEventName) {
|
||||
this._callbacks.push(callback);
|
||||
}
|
||||
},
|
||||
removeEventListener: function(eventName, callback) {
|
||||
if (eventName === kEventName) {
|
||||
var index = this._callbacks.indexOf(callback);
|
||||
if (index >= 0) {
|
||||
this._callbacks.splice(index, 1);
|
||||
}
|
||||
}
|
||||
},
|
||||
setEnabled: function(enabled) {
|
||||
this.ready(function() {
|
||||
var status = this.getStatus();
|
||||
|
||||
if (status === 'enabling' || status === 'disabling') {
|
||||
// do nothing when transition
|
||||
} else {
|
||||
if (enabled && status === 'enabled' ||
|
||||
!enabled && status === 'disabled') {
|
||||
return;
|
||||
}
|
||||
|
||||
var setObj = {};
|
||||
setObj[kCommunicationKey] = enabled;
|
||||
this._mozSettings.createLock().set(setObj);
|
||||
}
|
||||
}.bind(this));
|
||||
},
|
||||
init: function() {
|
||||
var self = this;
|
||||
|
||||
// init _cachedStatus
|
||||
var lock = window.navigator.mozSettings.createLock();
|
||||
var req = lock.get(kStatusKey);
|
||||
req.onsuccess = function() {
|
||||
self._cachedStatus = req.result[kStatusKey];
|
||||
self._callbacks.forEach(function(callback) {
|
||||
callback(self._cachedStatus);
|
||||
});
|
||||
};
|
||||
|
||||
this._mozSettings.addObserver(kStatusKey, function(evt) {
|
||||
var currentStatus = evt.settingValue;
|
||||
self._cachedStatus = currentStatus;
|
||||
self._callbacks.forEach(function(callback) {
|
||||
callback(currentStatus);
|
||||
});
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
exports.AirplaneModeHelper = AirplaneModeHelper;
|
||||
|
||||
// by default, we will add observer immediately for you right after
|
||||
// you include this helper
|
||||
AirplaneModeHelper.init();
|
||||
})(this);
|
||||
84
gaia/shared/js/apn_helper.js
Executable file
84
gaia/shared/js/apn_helper.js
Executable file
|
|
@ -0,0 +1,84 @@
|
|||
/**
|
||||
* @fileoverview This file provides common helper functions used to manipulate
|
||||
* access point names (APNs)
|
||||
*/
|
||||
|
||||
/* exported ApnHelper */
|
||||
|
||||
(function(exports) {
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* List of data network types, see source/dom/system/gonk/ril_consts.js in
|
||||
* mozilla-central. Those match the equivalent Android integer types.
|
||||
*/
|
||||
var NETWORK_TYPES = [
|
||||
null,
|
||||
'gprs',
|
||||
'edge',
|
||||
'umts',
|
||||
'is95a',
|
||||
'is95b',
|
||||
'1xrtt',
|
||||
'evdo0',
|
||||
'evdoa',
|
||||
'hsdpa',
|
||||
'hsupa',
|
||||
'hspa',
|
||||
'evdob',
|
||||
'ehrpd',
|
||||
'lte',
|
||||
'hspa+',
|
||||
'gsm'
|
||||
];
|
||||
|
||||
/**
|
||||
* Filter a list of APNs by network type. This involves comparing the bearer
|
||||
* field if present to the data network type and checking if they match. If
|
||||
* the bearer value of an APN is not defined or is set to 0 then we consider
|
||||
* the APN compatible with any network.
|
||||
*
|
||||
* @param {Array} apns An array of APNs
|
||||
* @param {String} type The network type which the APNs must be compatible
|
||||
* with
|
||||
*/
|
||||
function ah_filterByBearer(apns, type) {
|
||||
var typeIdx = NETWORK_TYPES.indexOf(type);
|
||||
|
||||
for (var i = 0; i < apns.length; i++) {
|
||||
var bearer = apns[i].bearer ? +apns[i].bearer : 0;
|
||||
|
||||
if (bearer && (bearer !== typeIdx)) {
|
||||
// This APN is incompatible, remove it from the array
|
||||
apns.splice(i, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an APN from the specified list which is compatible with the specified
|
||||
* MCC, MNC and connection type
|
||||
*
|
||||
* @param {Object} list The global APN list, the format should be the same as
|
||||
* the one used in apn.json
|
||||
* @param {Integer} mcc The mobile country code
|
||||
* @param {Integer} mnc The mobile network code
|
||||
* @param {String} type The network type which the filtered APNs must be
|
||||
* compatible with
|
||||
*
|
||||
* @return {Array} A list of compatible APNs
|
||||
*/
|
||||
function ah_getCompatible(list, mcc, mnc, type) {
|
||||
var apns = list[mcc] ? (list[mcc][mnc] || []) : [];
|
||||
|
||||
ah_filterByBearer(apns, type);
|
||||
|
||||
return apns;
|
||||
}
|
||||
|
||||
var ApnHelper = {
|
||||
getCompatible: ah_getCompatible
|
||||
};
|
||||
|
||||
exports.ApnHelper = ApnHelper;
|
||||
})(this);
|
||||
61
gaia/shared/js/async_semaphore.js
Executable file
61
gaia/shared/js/async_semaphore.js
Executable file
|
|
@ -0,0 +1,61 @@
|
|||
'use strict';
|
||||
|
||||
(function(exports) {
|
||||
var AsyncSemaphore = function as_contructor() {
|
||||
if (!(this instanceof AsyncSemaphore)) {
|
||||
return new AsyncSemaphore();
|
||||
}
|
||||
this._init();
|
||||
};
|
||||
|
||||
// Do not call '_init' and '_execute' directly from outside of AsyncSemaphore
|
||||
AsyncSemaphore.prototype = {
|
||||
_init: function as_init() {
|
||||
// Please don't modify these value directly from outside of AsyncSemaphore
|
||||
this.pendingTasks = [];
|
||||
this.semaphore = 0;
|
||||
},
|
||||
_execute: function as_execute() {
|
||||
var task,
|
||||
context;
|
||||
if (this.semaphore <= 0) {
|
||||
while (this.pendingTasks.length > 0) {
|
||||
task = this.pendingTasks.shift();
|
||||
context = task.context || this;
|
||||
if (task && task.callback && typeof task.callback === 'function') {
|
||||
task.callback.call(context, task.args);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
v: function as_v(num) {
|
||||
if (!num) {
|
||||
num = 1;
|
||||
}
|
||||
this.semaphore += num;
|
||||
},
|
||||
p: function as_p() {
|
||||
this.semaphore -= 1;
|
||||
if (this.semaphore < 0) {
|
||||
this.semaphore = 0;
|
||||
}
|
||||
this._execute();
|
||||
},
|
||||
wait: function as_wait(callback, context, args) {
|
||||
this.pendingTasks.push({
|
||||
callback: callback,
|
||||
context: context,
|
||||
args: args
|
||||
});
|
||||
this._execute();
|
||||
},
|
||||
getValue: function as_getValue() {
|
||||
return this.semaphore;
|
||||
},
|
||||
getTasksLength: function as_getTasksLength() {
|
||||
return this.pendingTasks.length;
|
||||
}
|
||||
};
|
||||
|
||||
exports.AsyncSemaphore = AsyncSemaphore;
|
||||
}(window));
|
||||
180
gaia/shared/js/async_storage.js
Executable file
180
gaia/shared/js/async_storage.js
Executable file
|
|
@ -0,0 +1,180 @@
|
|||
/* globals indexedDB */
|
||||
/**
|
||||
* This file defines an asynchronous version of the localStorage API, backed by
|
||||
* an IndexedDB database. It creates a global asyncStorage object that has
|
||||
* methods like the localStorage object.
|
||||
*
|
||||
* To store a value use setItem:
|
||||
*
|
||||
* asyncStorage.setItem('key', 'value');
|
||||
*
|
||||
* If you want confirmation that the value has been stored, pass a callback
|
||||
* function as the third argument:
|
||||
*
|
||||
* asyncStorage.setItem('key', 'newvalue', function() {
|
||||
* console.log('new value stored');
|
||||
* });
|
||||
*
|
||||
* To read a value, call getItem(), but note that you must supply a callback
|
||||
* function that the value will be passed to asynchronously:
|
||||
*
|
||||
* asyncStorage.getItem('key', function(value) {
|
||||
* console.log('The value of key is:', value);
|
||||
* });
|
||||
*
|
||||
* Note that unlike localStorage, asyncStorage does not allow you to store and
|
||||
* retrieve values by setting and querying properties directly. You cannot just
|
||||
* write asyncStorage.key; you have to explicitly call setItem() or getItem().
|
||||
*
|
||||
* removeItem(), clear(), length(), and key() are like the same-named methods of
|
||||
* localStorage, but, like getItem() and setItem() they take a callback
|
||||
* argument.
|
||||
*
|
||||
* The asynchronous nature of getItem() makes it tricky to retrieve multiple
|
||||
* values. But unlike localStorage, asyncStorage does not require the values you
|
||||
* store to be strings. So if you need to save multiple values and want to
|
||||
* retrieve them together, in a single asynchronous operation, just group the
|
||||
* values into a single object. The properties of this object may not include
|
||||
* DOM elements, but they may include things like Blobs and typed arrays.
|
||||
*
|
||||
* Unit tests are in apps/gallery/test/unit/asyncStorage_test.js
|
||||
*/
|
||||
|
||||
this.asyncStorage = (function() {
|
||||
'use strict';
|
||||
|
||||
var DBNAME = 'asyncStorage';
|
||||
var DBVERSION = 1;
|
||||
var STORENAME = 'keyvaluepairs';
|
||||
var db = null;
|
||||
|
||||
function withDatabase(f) {
|
||||
if (db) {
|
||||
f();
|
||||
} else {
|
||||
var openreq = indexedDB.open(DBNAME, DBVERSION);
|
||||
openreq.onerror = function withStoreOnError() {
|
||||
console.error('asyncStorage: can\'t open database:',
|
||||
openreq.error.name);
|
||||
};
|
||||
openreq.onupgradeneeded = function withStoreOnUpgradeNeeded() {
|
||||
// First time setup: create an empty object store
|
||||
openreq.result.createObjectStore(STORENAME);
|
||||
};
|
||||
openreq.onsuccess = function withStoreOnSuccess() {
|
||||
db = openreq.result;
|
||||
f();
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function withStore(type, callback, oncomplete) {
|
||||
withDatabase(function() {
|
||||
var transaction = db.transaction(STORENAME, type);
|
||||
if (oncomplete) {
|
||||
transaction.oncomplete = oncomplete;
|
||||
}
|
||||
callback(transaction.objectStore(STORENAME));
|
||||
});
|
||||
}
|
||||
|
||||
function getItem(key, callback) {
|
||||
var req;
|
||||
withStore('readonly', function getItemBody(store) {
|
||||
req = store.get(key);
|
||||
req.onerror = function getItemOnError() {
|
||||
console.error('Error in asyncStorage.getItem(): ', req.error.name);
|
||||
};
|
||||
}, function onComplete() {
|
||||
var value = req.result;
|
||||
if (value === undefined) {
|
||||
value = null;
|
||||
}
|
||||
callback(value);
|
||||
});
|
||||
}
|
||||
|
||||
function setItem(key, value, callback) {
|
||||
withStore('readwrite', function setItemBody(store) {
|
||||
var req = store.put(value, key);
|
||||
req.onerror = function setItemOnError() {
|
||||
console.error('Error in asyncStorage.setItem(): ', req.error.name);
|
||||
};
|
||||
}, callback);
|
||||
}
|
||||
|
||||
function removeItem(key, callback) {
|
||||
withStore('readwrite', function removeItemBody(store) {
|
||||
var req = store.delete(key);
|
||||
req.onerror = function removeItemOnError() {
|
||||
console.error('Error in asyncStorage.removeItem(): ', req.error.name);
|
||||
};
|
||||
}, callback);
|
||||
}
|
||||
|
||||
function clear(callback) {
|
||||
withStore('readwrite', function clearBody(store) {
|
||||
var req = store.clear();
|
||||
req.onerror = function clearOnError() {
|
||||
console.error('Error in asyncStorage.clear(): ', req.error.name);
|
||||
};
|
||||
}, callback);
|
||||
}
|
||||
|
||||
function length(callback) {
|
||||
var req;
|
||||
withStore('readonly', function lengthBody(store) {
|
||||
req = store.count();
|
||||
req.onerror = function lengthOnError() {
|
||||
console.error('Error in asyncStorage.length(): ', req.error.name);
|
||||
};
|
||||
}, function onComplete() {
|
||||
callback(req.result);
|
||||
});
|
||||
}
|
||||
|
||||
function key(n, callback) {
|
||||
if (n < 0) {
|
||||
callback(null);
|
||||
return;
|
||||
}
|
||||
|
||||
var req;
|
||||
withStore('readonly', function keyBody(store) {
|
||||
var advanced = false;
|
||||
req = store.openCursor();
|
||||
req.onsuccess = function keyOnSuccess() {
|
||||
var cursor = req.result;
|
||||
if (!cursor) {
|
||||
// this means there weren't enough keys
|
||||
return;
|
||||
}
|
||||
if (n === 0 || advanced) {
|
||||
// Either 1) we have the first key, return it if that's what they
|
||||
// wanted, or 2) we've got the nth key.
|
||||
return;
|
||||
}
|
||||
|
||||
// Otherwise, ask the cursor to skip ahead n records
|
||||
advanced = true;
|
||||
cursor.advance(n);
|
||||
};
|
||||
req.onerror = function keyOnError() {
|
||||
console.error('Error in asyncStorage.key(): ', req.error.name);
|
||||
};
|
||||
}, function onComplete() {
|
||||
var cursor = req.result;
|
||||
callback(cursor ? cursor.key : null);
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
getItem: getItem,
|
||||
setItem: setItem,
|
||||
removeItem: removeItem,
|
||||
clear: clear,
|
||||
length: length,
|
||||
key: key
|
||||
};
|
||||
}());
|
||||
|
||||
137
gaia/shared/js/basket_client.js
Executable file
137
gaia/shared/js/basket_client.js
Executable file
|
|
@ -0,0 +1,137 @@
|
|||
/* global Promise */
|
||||
/* exported Basket */
|
||||
'use strict';
|
||||
|
||||
// Simple Javascript client for Mozilla Basket newsletters
|
||||
var Basket = {
|
||||
DATASTORE_NAME: 'Basket_Newsletter',
|
||||
basketUrl: 'https://basket.mozilla.org/news/subscribe/',
|
||||
newsletterId: 'firefox-os',
|
||||
callback: null,
|
||||
xhr: null,
|
||||
// https://github.com/mozilla/basket-client/blob/master/basket/errors.py
|
||||
errors: {
|
||||
NETWORK_FAILURE: 1,
|
||||
INVALID_EMAIL: 2,
|
||||
UNKNOWN_EMAIL: 3,
|
||||
UNKNOWN_TOKEN: 4,
|
||||
USAGE_ERROR: 5,
|
||||
EMAIL_PROVIDER_AUTH_FAILURE: 6,
|
||||
AUTH_ERROR: 7,
|
||||
SSL_REQUIRED: 8,
|
||||
INVALID_NEWSLETTER: 9,
|
||||
INVALID_LANGUAGE: 10,
|
||||
EMAIL_NOT_CHANGED: 11,
|
||||
CHANGE_REQUEST_NOT_FOUND: 12,
|
||||
UNKNOWN_ERROR: 99
|
||||
},
|
||||
|
||||
responseHandler: function b_responseHandler() {
|
||||
if (this.xhr.readyState === 4) {
|
||||
if (this.xhr.status === 200) {
|
||||
if (typeof this.callback === 'function') {
|
||||
this.callback(null, JSON.parse(this.xhr.responseText));
|
||||
}
|
||||
} else {
|
||||
if (typeof this.callback === 'function') {
|
||||
if (this.xhr.responseText) {
|
||||
this.callback(JSON.parse(this.xhr.responseText));
|
||||
} else {
|
||||
this.callback('Unknown error');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
timeoutHandler: function b_timeoutHandler() {
|
||||
this.callback('Timeout');
|
||||
},
|
||||
|
||||
/**
|
||||
* Send data to Mozilla Basket.
|
||||
*
|
||||
* @param {String} [email] email we want to add to the newsletter.
|
||||
*
|
||||
* @param {Function} [callback] first argument is error, second
|
||||
* is result of operation or null
|
||||
* in the error case.
|
||||
*/
|
||||
send: function b_send(email, callback) {
|
||||
var self = this;
|
||||
var params = 'email=' + encodeURIComponent(email) +
|
||||
'&newsletters=' + self.newsletterId;
|
||||
self.callback = callback;
|
||||
self.xhr = new XMLHttpRequest({mozSystem: true});
|
||||
self.xhr.onreadystatechange = self.responseHandler.bind(self);
|
||||
self.xhr.open('POST', self.basketUrl, true);
|
||||
self.xhr.setRequestHeader('Content-type',
|
||||
'application/x-www-form-urlencoded');
|
||||
self.xhr.setRequestHeader('Connection', 'close');
|
||||
self.xhr.timeout = 5000; // 5 seconds
|
||||
self.xhr.ontimeout = self.timeoutHandler.bind(self);
|
||||
self.getLanguage(function do_send(language) {
|
||||
if (language) {
|
||||
params += '&lang=' + language;
|
||||
}
|
||||
self.xhr.setRequestHeader('Content-length', params.length);
|
||||
self.xhr.send(params);
|
||||
});
|
||||
},
|
||||
|
||||
getDataStore: function() {
|
||||
var self = this;
|
||||
return new Promise(function (resolve, reject) {
|
||||
navigator.getDataStores(self.DATASTORE_NAME).then(function(stores) {
|
||||
// check it's not empty
|
||||
if (!stores.length) {
|
||||
reject(new Error('DataStore not loaded'));
|
||||
} else {
|
||||
var dataStore = stores[0];
|
||||
// check ownership of the DS
|
||||
if (dataStore.owner === 'app://ftu.gaiamobile.org/manifest.webapp') {
|
||||
resolve(dataStore);
|
||||
} else {
|
||||
reject(new Error('Wrong DataStore'));
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
},
|
||||
|
||||
store: function b_store(email, callback) {
|
||||
this.getDataStore().then(function loaded(store) {
|
||||
// Store the email address
|
||||
store.add({ 'newsletter_email': email }).then(function(id) {
|
||||
if (callback) {
|
||||
callback(false, id);
|
||||
}
|
||||
});
|
||||
}).catch(function error(err) {
|
||||
console.error('Something went wrong: ' + err);
|
||||
callback(err);
|
||||
});
|
||||
},
|
||||
|
||||
getLanguage: function b_getLanguage(callback) {
|
||||
var settings = window.navigator.mozSettings;
|
||||
if (!settings || !settings.createLock) {
|
||||
callback();
|
||||
return;
|
||||
}
|
||||
|
||||
var s_name = 'language.current';
|
||||
var req = settings.createLock().get(s_name);
|
||||
|
||||
req.onsuccess = function _onsuccess() {
|
||||
callback(req.result[s_name]);
|
||||
};
|
||||
|
||||
req.onerror = function _onerror() {
|
||||
console.error('Error getting setting: ' + s_name);
|
||||
callback();
|
||||
};
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
124
gaia/shared/js/binary_search.js
Executable file
124
gaia/shared/js/binary_search.js
Executable file
|
|
@ -0,0 +1,124 @@
|
|||
'use strict';
|
||||
/* exported utils */
|
||||
var utils = window.utils || {};
|
||||
|
||||
/**
|
||||
* This function performs a binary search over an already sorted array
|
||||
* target is the target item to search for
|
||||
* array is the sorted array
|
||||
* options is an optional object which may contain
|
||||
* the start and end position (from, to)
|
||||
* an optional arrayField which indicates the object property that contains the
|
||||
* comparable item and transform and compare functions
|
||||
*
|
||||
* Returns an array with the positions on which the target item was found
|
||||
*
|
||||
*/
|
||||
utils.binarySearch = function(target, array, options) {
|
||||
var arrayField = options.arrayField,
|
||||
transformFunction = options.transformFunction,
|
||||
compareFunction = options.compareFunction;
|
||||
|
||||
// Obtains the comparable item by transforming if necessary
|
||||
function getItem(array, index) {
|
||||
var item = array[index];
|
||||
if (arrayField) {
|
||||
item = item[arrayField];
|
||||
if (typeof transformFunction === 'function') {
|
||||
item = transformFunction(item);
|
||||
}
|
||||
}
|
||||
return item;
|
||||
}
|
||||
|
||||
// Compares the target with an array item
|
||||
function compare(target, item) {
|
||||
var out;
|
||||
if (typeof compareFunction === 'function') {
|
||||
out = compareFunction(target, item);
|
||||
}
|
||||
else {
|
||||
if (typeof target === 'string') {
|
||||
out = target.localeCompare(item);
|
||||
}
|
||||
else {
|
||||
out = target.toString().localeCompare(item);
|
||||
}
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
var from = options.from;
|
||||
if (typeof from === 'undefined') {
|
||||
from = 0;
|
||||
}
|
||||
var to = options.to;
|
||||
if (typeof to === 'undefined') {
|
||||
to = array.length - 1;
|
||||
}
|
||||
|
||||
if (to < from) {
|
||||
// Not found
|
||||
return [];
|
||||
}
|
||||
|
||||
var middleIndex = Math.floor((to - from) / 2);
|
||||
var item = getItem(array, from + middleIndex);
|
||||
|
||||
var compareResult = compare(target, item);
|
||||
|
||||
if (compareResult === 0) {
|
||||
// Once a result is found let's iterate in both directions to get the rest
|
||||
// Just in case there are more than one result
|
||||
var results = [from + middleIndex];
|
||||
|
||||
var next = from + middleIndex + 1;
|
||||
var finish = false;
|
||||
while (next <= (array.length - 1) && !finish) {
|
||||
item = getItem(array, next);
|
||||
|
||||
if (compare(target, item) === 0) {
|
||||
results.push(next);
|
||||
}
|
||||
else {
|
||||
finish = true;
|
||||
}
|
||||
next++;
|
||||
}
|
||||
|
||||
finish = false;
|
||||
next = from + middleIndex - 1;
|
||||
|
||||
while (next >= 0 && !finish) {
|
||||
item = getItem(array, next);
|
||||
|
||||
if (compare(target, item) === 0) {
|
||||
results.push(next);
|
||||
}
|
||||
else {
|
||||
finish = true;
|
||||
}
|
||||
next--;
|
||||
}
|
||||
return results;
|
||||
}
|
||||
else if (compareResult < 0) {
|
||||
return utils.binarySearch(target, array, {
|
||||
from: from,
|
||||
to: to - middleIndex - 1,
|
||||
arrayField: arrayField,
|
||||
transformFunction: transformFunction,
|
||||
compareFunction: compareFunction
|
||||
});
|
||||
}
|
||||
else {
|
||||
return utils.binarySearch(target, array, {
|
||||
from: from + middleIndex + 1,
|
||||
to: to,
|
||||
arrayField: arrayField,
|
||||
transformFunction: transformFunction,
|
||||
compareFunction: compareFunction
|
||||
});
|
||||
}
|
||||
};
|
||||
430
gaia/shared/js/blobview.js
Executable file
430
gaia/shared/js/blobview.js
Executable file
|
|
@ -0,0 +1,430 @@
|
|||
/* exported BlobView */
|
||||
'use strict';
|
||||
|
||||
var BlobView = (function() {
|
||||
function fail(msg) {
|
||||
throw Error(msg);
|
||||
}
|
||||
|
||||
var decoderCache = {};
|
||||
function getDecoder(encoding) {
|
||||
if (encoding in decoderCache) {
|
||||
return decoderCache[encoding];
|
||||
}
|
||||
var decoder = decoderCache[encoding] = new TextDecoder(encoding);
|
||||
return decoder;
|
||||
}
|
||||
|
||||
// This constructor is for internal use only.
|
||||
// Use the BlobView.get() factory function or the getMore instance method
|
||||
// to obtain a BlobView object.
|
||||
function BlobView(blob, sliceOffset, sliceLength, slice,
|
||||
viewOffset, viewLength, littleEndian)
|
||||
{
|
||||
this.blob = blob; // The parent blob that the data is from
|
||||
this.sliceOffset = sliceOffset; // The start address within the blob
|
||||
this.sliceLength = sliceLength; // How long the slice is
|
||||
this.slice = slice; // The ArrayBuffer of slice data
|
||||
this.viewOffset = viewOffset; // The start of the view within the slice
|
||||
this.viewLength = viewLength; // The length of the view
|
||||
this.littleEndian = littleEndian; // Read little endian by default?
|
||||
|
||||
// DataView wrapper around the ArrayBuffer
|
||||
this.view = new DataView(slice, viewOffset, viewLength);
|
||||
|
||||
// These fields mirror those of DataView
|
||||
this.buffer = slice;
|
||||
this.byteLength = viewLength;
|
||||
this.byteOffset = viewOffset;
|
||||
|
||||
this.index = 0; // The read methods keep track of the read position
|
||||
}
|
||||
|
||||
// Async factory function
|
||||
BlobView.get = function(blob, offset, length, callback, littleEndian) {
|
||||
if (offset < 0) {
|
||||
fail('negative offset');
|
||||
}
|
||||
if (length < 0) {
|
||||
fail('negative length');
|
||||
}
|
||||
if (offset > blob.size) {
|
||||
fail('offset larger than blob size');
|
||||
}
|
||||
// Don't fail if the length is too big; just reduce the length
|
||||
if (offset + length > blob.size) {
|
||||
length = blob.size - offset;
|
||||
}
|
||||
var slice = blob.slice(offset, offset + length);
|
||||
var reader = new FileReader();
|
||||
reader.readAsArrayBuffer(slice);
|
||||
reader.onloadend = function() {
|
||||
var result = null;
|
||||
if (reader.result) {
|
||||
result = new BlobView(blob, offset, length, reader.result,
|
||||
0, length, littleEndian || false);
|
||||
}
|
||||
callback(result, reader.error);
|
||||
};
|
||||
};
|
||||
|
||||
// Synchronous factory function for use when you have an array buffer and want
|
||||
// to treat it as a BlobView (e.g. to use the readXYZ functions). We need
|
||||
// this for the music app, which uses an array buffer to hold
|
||||
// de-unsynchronized ID3 frames.
|
||||
BlobView.getFromArrayBuffer = function(buffer, offset, length, littleEndian) {
|
||||
return new BlobView(null, offset, length, buffer, offset, length,
|
||||
littleEndian);
|
||||
};
|
||||
|
||||
BlobView.prototype = {
|
||||
constructor: BlobView,
|
||||
|
||||
// This instance method is like the BlobView.get() factory method,
|
||||
// but it is here because if the current buffer includes the requested
|
||||
// range of bytes, they can be passed directly to the callback without
|
||||
// going back to the blob to read them
|
||||
getMore: function(offset, length, callback) {
|
||||
// If we made this BlobView from an array buffer, there's no blob backing
|
||||
// it, and so it's impossible to get more data.
|
||||
if (!this.blob) {
|
||||
fail('no blob backing this BlobView');
|
||||
}
|
||||
|
||||
if (offset >= this.sliceOffset &&
|
||||
offset + length <= this.sliceOffset + this.sliceLength) {
|
||||
// The quick case: we already have that region of the blob
|
||||
callback(new BlobView(this.blob,
|
||||
this.sliceOffset, this.sliceLength, this.slice,
|
||||
offset - this.sliceOffset, length,
|
||||
this.littleEndian));
|
||||
}
|
||||
else {
|
||||
// Otherwise, we have to do an async read to get more bytes
|
||||
BlobView.get(this.blob, offset, length, callback, this.littleEndian);
|
||||
}
|
||||
},
|
||||
|
||||
// Set the default endianness for the other methods
|
||||
littleEndian: function() {
|
||||
this.littleEndian = true;
|
||||
},
|
||||
bigEndian: function() {
|
||||
this.littleEndian = false;
|
||||
},
|
||||
|
||||
// These "get" methods are just copies of the DataView methods, except
|
||||
// that they honor the default endianness
|
||||
getUint8: function(offset) {
|
||||
return this.view.getUint8(offset);
|
||||
},
|
||||
getInt8: function(offset) {
|
||||
return this.view.getInt8(offset);
|
||||
},
|
||||
getUint16: function(offset, le) {
|
||||
return this.view.getUint16(offset,
|
||||
le !== undefined ? le : this.littleEndian);
|
||||
},
|
||||
getInt16: function(offset, le) {
|
||||
return this.view.getInt16(offset,
|
||||
le !== undefined ? le : this.littleEndian);
|
||||
},
|
||||
getUint32: function(offset, le) {
|
||||
return this.view.getUint32(offset,
|
||||
le !== undefined ? le : this.littleEndian);
|
||||
},
|
||||
getInt32: function(offset, le) {
|
||||
return this.view.getInt32(offset,
|
||||
le !== undefined ? le : this.littleEndian);
|
||||
},
|
||||
getFloat32: function(offset, le) {
|
||||
return this.view.getFloat32(offset,
|
||||
le !== undefined ? le : this.littleEndian);
|
||||
},
|
||||
getFloat64: function(offset, le) {
|
||||
return this.view.getFloat64(offset,
|
||||
le !== undefined ? le : this.littleEndian);
|
||||
},
|
||||
|
||||
// These "read" methods read from the current position in the view and
|
||||
// update that position accordingly
|
||||
readByte: function() {
|
||||
return this.view.getInt8(this.index++);
|
||||
},
|
||||
readUnsignedByte: function() {
|
||||
return this.view.getUint8(this.index++);
|
||||
},
|
||||
readShort: function(le) {
|
||||
var val = this.view.getInt16(this.index,
|
||||
le !== undefined ? le : this.littleEndian);
|
||||
this.index += 2;
|
||||
return val;
|
||||
},
|
||||
readUnsignedShort: function(le) {
|
||||
var val = this.view.getUint16(this.index,
|
||||
le !== undefined ? le : this.littleEndian);
|
||||
this.index += 2;
|
||||
return val;
|
||||
},
|
||||
readInt: function(le) {
|
||||
var val = this.view.getInt32(this.index,
|
||||
le !== undefined ? le : this.littleEndian);
|
||||
this.index += 4;
|
||||
return val;
|
||||
},
|
||||
readUnsignedInt: function(le) {
|
||||
var val = this.view.getUint32(this.index,
|
||||
le !== undefined ? le : this.littleEndian);
|
||||
this.index += 4;
|
||||
return val;
|
||||
},
|
||||
readFloat: function(le) {
|
||||
var val = this.view.getFloat32(this.index,
|
||||
le !== undefined ? le : this.littleEndian);
|
||||
this.index += 4;
|
||||
return val;
|
||||
},
|
||||
readDouble: function(le) {
|
||||
var val = this.view.getFloat64(this.index,
|
||||
le !== undefined ? le : this.littleEndian);
|
||||
this.index += 8;
|
||||
return val;
|
||||
},
|
||||
|
||||
// Methods to get and set the current position
|
||||
tell: function() {
|
||||
return this.index;
|
||||
},
|
||||
remaining: function() {
|
||||
return this.byteLength - this.index;
|
||||
},
|
||||
seek: function(index) {
|
||||
if (index < 0) {
|
||||
fail('negative index');
|
||||
}
|
||||
if (index > this.byteLength) {
|
||||
fail('index greater than buffer size');
|
||||
}
|
||||
this.index = index;
|
||||
},
|
||||
advance: function(n) {
|
||||
var index = this.index + n;
|
||||
if (index < 0) {
|
||||
fail('advance past beginning of buffer');
|
||||
}
|
||||
// It's usual that when we finished reading one target view,
|
||||
// the index is advanced to the start(previous end + 1) of next view,
|
||||
// and the new index will be equal to byte length(the last index + 1),
|
||||
// we will not fail on it because it means the reading is finished,
|
||||
// or do we have to warn here?
|
||||
if (index > this.byteLength) {
|
||||
fail('advance past end of buffer');
|
||||
}
|
||||
this.index = index;
|
||||
},
|
||||
|
||||
// Additional methods to read other useful things
|
||||
getUnsignedByteArray: function(offset, n) {
|
||||
return new Uint8Array(this.buffer, offset + this.viewOffset, n);
|
||||
},
|
||||
|
||||
// Additional methods to read other useful things
|
||||
readUnsignedByteArray: function(n) {
|
||||
var val = new Uint8Array(this.buffer, this.index + this.viewOffset, n);
|
||||
this.index += n;
|
||||
return val;
|
||||
},
|
||||
|
||||
getBit: function(offset, bit) {
|
||||
var byte = this.view.getUint8(offset);
|
||||
return (byte & (1 << bit)) !== 0;
|
||||
},
|
||||
|
||||
getUint24: function(offset, le) {
|
||||
var b1, b2, b3;
|
||||
if (le !== undefined ? le : this.littleEndian) {
|
||||
b1 = this.view.getUint8(offset);
|
||||
b2 = this.view.getUint8(offset + 1);
|
||||
b3 = this.view.getUint8(offset + 2);
|
||||
}
|
||||
else { // big end first
|
||||
b3 = this.view.getUint8(offset);
|
||||
b2 = this.view.getUint8(offset + 1);
|
||||
b1 = this.view.getUint8(offset + 2);
|
||||
}
|
||||
|
||||
return (b3 << 16) + (b2 << 8) + b1;
|
||||
},
|
||||
|
||||
readUint24: function(le) {
|
||||
var value = this.getUint24(this.index, le);
|
||||
this.index += 3;
|
||||
return value;
|
||||
},
|
||||
|
||||
// There are lots of ways to read strings. We support binary (raw 8-bit
|
||||
// codepoints), Latin-1, UTF-8, and UTF-16. For the latter three, we also
|
||||
// support null-terminated versions.
|
||||
|
||||
getBinaryText: function(offset, len) {
|
||||
var bytes = new Uint8Array(this.buffer, offset + this.viewOffset, len);
|
||||
return String.fromCharCode.apply(String, bytes);
|
||||
},
|
||||
|
||||
readBinaryText: function(len) {
|
||||
var s = this.getBinaryText(this.index, len);
|
||||
this.index += len;
|
||||
return s;
|
||||
},
|
||||
|
||||
getLatin1Text: function(offset, len) {
|
||||
var bytes = new Uint8Array(this.buffer, offset + this.viewOffset, len);
|
||||
return getDecoder('latin1').decode(bytes);
|
||||
},
|
||||
|
||||
readLatin1Text: function(len) {
|
||||
var s = this.getLatin1Text(this.index, len);
|
||||
this.index += len;
|
||||
return s;
|
||||
},
|
||||
|
||||
getUTF8Text: function(offset, len) {
|
||||
var bytes = new Uint8Array(this.buffer, offset + this.viewOffset, len);
|
||||
return getDecoder('utf-8').decode(bytes);
|
||||
},
|
||||
|
||||
readUTF8Text: function(len) {
|
||||
var s = this.getUTF8Text(this.index, len);
|
||||
this.index += len;
|
||||
return s;
|
||||
},
|
||||
|
||||
// Get UTF16 text. If le is not specified, expect a BOM to define
|
||||
// endianness. If le is true, read UTF16LE, if false, UTF16BE.
|
||||
getUTF16Text: function(offset, len, le) {
|
||||
if (len % 2) {
|
||||
fail('len must be a multiple of two');
|
||||
}
|
||||
|
||||
var bytes = new Uint8Array(this.buffer, offset + this.viewOffset, len);
|
||||
|
||||
if (le === null || le === undefined) {
|
||||
var BOM = (bytes[0] << 8) + bytes[1];
|
||||
|
||||
if (BOM === 0xFEFF) {
|
||||
bytes = bytes.subarray(2);
|
||||
le = false;
|
||||
} else if (BOM === 0xFFFE) {
|
||||
bytes = bytes.subarray(2);
|
||||
le = true;
|
||||
} else {
|
||||
le = true;
|
||||
}
|
||||
}
|
||||
|
||||
var encoding = le ? 'utf-16le' : 'utf-16be';
|
||||
return getDecoder(encoding).decode(bytes);
|
||||
},
|
||||
|
||||
readUTF16Text: function(len, le) {
|
||||
var s = this.getUTF16Text(this.index, len, le);
|
||||
this.index += len;
|
||||
return s;
|
||||
},
|
||||
|
||||
// Read 4 bytes, ignore the high bit and combine them into a 28-bit
|
||||
// big-endian unsigned integer.
|
||||
// This format is used by the ID3v2 metadata.
|
||||
getID3Uint28BE: function(offset) {
|
||||
var b1 = this.view.getUint8(offset) & 0x7f;
|
||||
var b2 = this.view.getUint8(offset + 1) & 0x7f;
|
||||
var b3 = this.view.getUint8(offset + 2) & 0x7f;
|
||||
var b4 = this.view.getUint8(offset + 3) & 0x7f;
|
||||
return (b1 << 21) | (b2 << 14) | (b3 << 7) | b4;
|
||||
},
|
||||
|
||||
readID3Uint28BE: function() {
|
||||
var value = this.getID3Uint28BE(this.index);
|
||||
this.index += 4;
|
||||
return value;
|
||||
},
|
||||
|
||||
// Read bytes up to and including a null terminator, but never
|
||||
// more than size bytes. And return as a Latin1 string. If advance_by_size
|
||||
// is true, this will always seek ahead by `size` bytes, even if a null
|
||||
// character was found earlier.
|
||||
readNullTerminatedLatin1Text: function(size, advance_by_size = false) {
|
||||
var bytes = new Uint8Array(this.buffer, this.viewOffset + this.index,
|
||||
size);
|
||||
|
||||
var nil = bytes.indexOf(0);
|
||||
if (nil !== -1) {
|
||||
bytes = bytes.subarray(0, nil);
|
||||
}
|
||||
|
||||
var s = getDecoder('latin1').decode(bytes);
|
||||
if (nil === -1 || advance_by_size) {
|
||||
this.index += size;
|
||||
} else {
|
||||
this.index += nil + 1;
|
||||
}
|
||||
return s;
|
||||
},
|
||||
|
||||
// Read bytes up to and including a null terminator, but never
|
||||
// more than size bytes. And return as a UTF8 string. If advance_by_size
|
||||
// is true, this will always seek ahead by `size` bytes, even if a null
|
||||
// character was found earlier.
|
||||
readNullTerminatedUTF8Text: function(size, advance_by_size = false) {
|
||||
var bytes = new Uint8Array(this.buffer, this.viewOffset + this.index,
|
||||
size);
|
||||
|
||||
var nil = bytes.indexOf(0);
|
||||
if (nil !== -1) {
|
||||
bytes = bytes.subarray(0, nil);
|
||||
}
|
||||
|
||||
var s = getDecoder('utf-8').decode(bytes);
|
||||
if (nil === -1 || advance_by_size) {
|
||||
this.index += size;
|
||||
} else {
|
||||
this.index += nil + 1;
|
||||
}
|
||||
return s;
|
||||
},
|
||||
|
||||
// Read UTF16 text. If le is not specified, expect a BOM to define
|
||||
// endianness. If le is true, read UTF16LE, if false, UTF16BE
|
||||
// Read until we find a null-terminator, but never more than size bytes.
|
||||
// If advance_by_size is true, this will always seek ahead by `size` bytes,
|
||||
// even if a null character was found earlier.
|
||||
readNullTerminatedUTF16Text: function(size, le, advance_by_size = false) {
|
||||
if (size % 2) {
|
||||
fail('size must be a multiple of two');
|
||||
}
|
||||
|
||||
for (var len = 0; len < size; len += 2) {
|
||||
if (this.getUint16(this.index + len, le) === 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
var s = this.getUTF16Text(this.index, len, le);
|
||||
if (len === size || advance_by_size) {
|
||||
this.index += size;
|
||||
} else {
|
||||
this.index += len + 2;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
};
|
||||
|
||||
// We don't want users of this library to accidentally call the constructor
|
||||
// instead of using one of the factory functions, so we return a dummy object
|
||||
// instead of the real constructor. If someone really needs to get at the
|
||||
// real constructor, the contructor property of the prototype refers to it.
|
||||
return {
|
||||
get: BlobView.get,
|
||||
getFromArrayBuffer: BlobView.getFromArrayBuffer
|
||||
};
|
||||
}());
|
||||
322
gaia/shared/js/bluetooth_helper.js
Executable file
322
gaia/shared/js/bluetooth_helper.js
Executable file
|
|
@ -0,0 +1,322 @@
|
|||
/* exported BluetoothHelper */
|
||||
|
||||
'use strict';
|
||||
|
||||
var BluetoothHelper = function() {
|
||||
var profiles = {
|
||||
'HFP': 0x111E,
|
||||
'A2DP': 0x110D
|
||||
};
|
||||
|
||||
var _bluetooth = window.navigator.mozBluetooth;
|
||||
var _isReady = false;
|
||||
var _callbacks = [];
|
||||
|
||||
var _adapter = null;
|
||||
var _oldAdapter = null; // The varaible is accessed for v1 only.
|
||||
var _v2 = true;
|
||||
|
||||
var _ready = function(callback) {
|
||||
if (!callback || !_bluetooth) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (_isReady) {
|
||||
callback();
|
||||
} else {
|
||||
_callbacks.push(callback);
|
||||
}
|
||||
};
|
||||
|
||||
var _handleRequest = function(request, callback, errorcb) {
|
||||
request.onsuccess = function() {
|
||||
if (callback) {
|
||||
callback(request.result);
|
||||
}
|
||||
};
|
||||
|
||||
request.onerror = function() {
|
||||
console.log('Error handling bluetooth request');
|
||||
if (errorcb) {
|
||||
errorcb();
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
// run callbacks when adapter is ready
|
||||
var _processCallbacks = function() {
|
||||
if (_adapter) {
|
||||
_isReady = true;
|
||||
|
||||
_callbacks.forEach(function(callback) {
|
||||
callback();
|
||||
});
|
||||
// clean up the _callback queue
|
||||
_callbacks = [];
|
||||
} else {
|
||||
// We can do nothing without default adapter.
|
||||
console.log('BluetoothHelper(): connot get default adapter yet');
|
||||
}
|
||||
};
|
||||
|
||||
// API v2 get adapter via bluetooth
|
||||
var _fetchAdapterV2 = function() {
|
||||
// need time to get bluetooth adapter at first run
|
||||
_bluetooth.onattributechanged = function onManagerAttributeChanged(evt) {
|
||||
for (var i in evt.attrs) {
|
||||
switch (evt.attrs[i]) {
|
||||
case 'defaultAdapter':
|
||||
console.log('defaultAdapter changed. address:',
|
||||
_bluetooth.defaultAdapter.address);
|
||||
_adapter = _bluetooth.defaultAdapter;
|
||||
_processCallbacks();
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
_adapter = _bluetooth.defaultAdapter;
|
||||
if (_adapter) {
|
||||
_processCallbacks();
|
||||
}
|
||||
};
|
||||
|
||||
// API v1 get adapter via bluetooth
|
||||
var _fetchAdapter = function() {
|
||||
var req = _bluetooth.getDefaultAdapter();
|
||||
if (req) {
|
||||
req.onsuccess = function() {
|
||||
if (_adapter) {
|
||||
_oldAdapter = _adapter;
|
||||
}
|
||||
|
||||
_isReady = true;
|
||||
_adapter = req.result;
|
||||
|
||||
// Put the callback function of onpairedstatuschanged to the new adapter
|
||||
// because the new adapter won't remember those callback function which
|
||||
// is registered before. In other word, we get a new adpater after
|
||||
// turned on/off Bluetooth. The new adapter have no registered callback.
|
||||
if (_oldAdapter && _oldAdapter.onpairedstatuschanged) {
|
||||
_adapter.onpairedstatuschanged = _oldAdapter.onpairedstatuschanged;
|
||||
}
|
||||
|
||||
_callbacks.forEach(function(callback) {
|
||||
callback();
|
||||
});
|
||||
// clean up the _callback queue
|
||||
_callbacks = [];
|
||||
};
|
||||
|
||||
req.onerror = function() {
|
||||
// We can do nothing without default adapter.
|
||||
console.log('BluetoothHelper(): connot get default adapter!!!');
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
var _getAdapter = function() {
|
||||
if (_v2) {
|
||||
_fetchAdapterV2();
|
||||
} else {
|
||||
_fetchAdapter();
|
||||
}
|
||||
};
|
||||
|
||||
var _resetAdapter = function() {
|
||||
if (_adapter) {
|
||||
_oldAdapter = _adapter;
|
||||
}
|
||||
// clean up state and adapter
|
||||
_isReady = false;
|
||||
_adapter = null;
|
||||
};
|
||||
|
||||
// init
|
||||
if (_bluetooth) {
|
||||
// detect API version
|
||||
if (typeof(_bluetooth.onattributechanged) === 'undefined') {
|
||||
_v2 = false;
|
||||
}
|
||||
|
||||
if (_v2) {
|
||||
_bluetooth.onadapteradded = function onAdapterAdded(evt) {
|
||||
_getAdapter();
|
||||
};
|
||||
} else {
|
||||
_bluetooth.addEventListener('enabled', _getAdapter);
|
||||
_bluetooth.addEventListener('adapteradded', _getAdapter);
|
||||
_bluetooth.addEventListener('disabled', _resetAdapter);
|
||||
}
|
||||
_getAdapter();
|
||||
}
|
||||
|
||||
return {
|
||||
profiles: profiles,
|
||||
|
||||
answerWaitingCall: function() {
|
||||
_ready(function() {
|
||||
_adapter.answerWaitingCall();
|
||||
});
|
||||
},
|
||||
|
||||
ignoreWaitingCall: function() {
|
||||
_ready(function() {
|
||||
_adapter.ignoreWaitingCall();
|
||||
});
|
||||
},
|
||||
|
||||
toggleCalls: function() {
|
||||
_ready(function() {
|
||||
_adapter.toggleCalls();
|
||||
});
|
||||
},
|
||||
|
||||
getConnectedDevicesByProfile: function(profileID, cb) {
|
||||
_ready(function() {
|
||||
_handleRequest(_adapter.getConnectedDevices(profileID), cb);
|
||||
});
|
||||
},
|
||||
|
||||
connectSco: function(cb) {
|
||||
_ready(function() {
|
||||
_handleRequest(_adapter.connectSco(), cb);
|
||||
});
|
||||
},
|
||||
|
||||
disconnectSco: function(cb) {
|
||||
_ready(function() {
|
||||
_handleRequest(_adapter.disconnectSco(), cb);
|
||||
});
|
||||
},
|
||||
|
||||
getPairedDevices: function(cb) {
|
||||
_ready(function() {
|
||||
_handleRequest(_adapter.getPairedDevices(), cb);
|
||||
});
|
||||
},
|
||||
|
||||
getAddress: function(cb) {
|
||||
if (_v2) {
|
||||
console.log('getAddress function is deprecated');
|
||||
return;
|
||||
}
|
||||
|
||||
_ready(function() {
|
||||
var address = _adapter.address;
|
||||
cb(address);
|
||||
});
|
||||
},
|
||||
|
||||
setPairingConfirmation: function(address, confirmed) {
|
||||
if (_v2) {
|
||||
console.log('setPairingConfirmation API is deprecated');
|
||||
return;
|
||||
}
|
||||
|
||||
_ready(function() {
|
||||
_adapter.setPairingConfirmation(address, confirmed);
|
||||
});
|
||||
},
|
||||
|
||||
setPinCode: function(address, pincode) {
|
||||
if (_v2) {
|
||||
console.log('setPairingConfirmation API is deprecated');
|
||||
return;
|
||||
}
|
||||
|
||||
_ready(function() {
|
||||
_adapter.setPinCode(address, pincode);
|
||||
});
|
||||
},
|
||||
|
||||
setPasskey: function(address, key) {
|
||||
if (_v2) {
|
||||
console.log('setPairingConfirmation API is deprecated');
|
||||
return;
|
||||
}
|
||||
|
||||
_ready(function() {
|
||||
_adapter.setPasskey(address, key);
|
||||
});
|
||||
},
|
||||
|
||||
isScoConnected: function(cb, errorcb) {
|
||||
_ready(function() {
|
||||
_handleRequest(_adapter.isScoConnected(), cb, errorcb);
|
||||
});
|
||||
},
|
||||
|
||||
sendMediaMetaData: function(metadata, cb, errorcb) {
|
||||
_ready(function() {
|
||||
_handleRequest(_adapter.sendMediaMetaData(metadata), cb, errorcb);
|
||||
});
|
||||
},
|
||||
|
||||
sendMediaPlayStatus: function(metadata, cb, errorcb) {
|
||||
_ready(function() {
|
||||
_handleRequest(_adapter.sendMediaPlayStatus(metadata), cb, errorcb);
|
||||
});
|
||||
},
|
||||
|
||||
set onhfpstatuschanged(callback) {
|
||||
_ready(function() {
|
||||
_adapter.onhfpstatuschanged = callback;
|
||||
});
|
||||
},
|
||||
|
||||
set onscostatuschanged(callback) {
|
||||
_ready(function() {
|
||||
_adapter.onscostatuschanged = callback;
|
||||
});
|
||||
},
|
||||
|
||||
set ona2dpstatuschanged(callback) {
|
||||
_ready(function() {
|
||||
_adapter.ona2dpstatuschanged = callback;
|
||||
});
|
||||
},
|
||||
|
||||
set onrequestmediaplaystatus(callback) {
|
||||
_ready(function() {
|
||||
_adapter.onrequestmediaplaystatus = callback;
|
||||
});
|
||||
},
|
||||
|
||||
set onpairedstatuschanged(callback) {
|
||||
if (_v2) {
|
||||
console.log('onpairedstatuschanged API is deprecated');
|
||||
return;
|
||||
}
|
||||
|
||||
_ready(function() {
|
||||
_adapter.onpairedstatuschanged = callback;
|
||||
});
|
||||
},
|
||||
|
||||
v2: _v2, // expose API version for app reference
|
||||
|
||||
// bypass the enable/disable state if works in APIv1
|
||||
enable: function() {
|
||||
if (_v2) {
|
||||
_ready(function() {
|
||||
_adapter.enable();
|
||||
});
|
||||
} else {
|
||||
console.log('enable is not support in v1 API!');
|
||||
}
|
||||
},
|
||||
|
||||
disable: function() {
|
||||
if (_v2) {
|
||||
_ready(function() {
|
||||
_adapter.disable();
|
||||
});
|
||||
} else {
|
||||
console.log('disable is not support in v1 API!');
|
||||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
287
gaia/shared/js/bookmarks_database.js
Executable file
287
gaia/shared/js/bookmarks_database.js
Executable file
|
|
@ -0,0 +1,287 @@
|
|||
|
||||
'use strict';
|
||||
|
||||
/* global Promise */
|
||||
|
||||
(function(exports) {
|
||||
|
||||
var datastore;
|
||||
|
||||
// Datastore name declared on the manifest.webapp
|
||||
var DATASTORE_NAME = 'bookmarks_store';
|
||||
|
||||
// Indicates the initialization state
|
||||
var readyState;
|
||||
|
||||
// Event listeners
|
||||
var listeners = Object.create(null);
|
||||
|
||||
function init() {
|
||||
return new Promise(function doInit(resolve, reject) {
|
||||
if (readyState === 'initialized') {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
|
||||
if (readyState === 'initializing') {
|
||||
document.addEventListener('ds-initialized', function oninitalized() {
|
||||
document.removeEventListener('ds-initialized', oninitalized);
|
||||
resolve();
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
readyState = 'initializing';
|
||||
|
||||
if (!navigator.getDataStores) {
|
||||
console.error('Bookmark store: DataStore API is not working');
|
||||
reject({ name: 'NO_DATASTORE' });
|
||||
readyState = 'failed';
|
||||
return;
|
||||
}
|
||||
|
||||
navigator.getDataStores(DATASTORE_NAME).then(function(ds) {
|
||||
if (ds.length < 1) {
|
||||
console.error('Bookmark store: Cannot get access to the Store');
|
||||
reject({ name: 'NO_ACCESS_TO_DATASTORE' });
|
||||
readyState = 'failed';
|
||||
return;
|
||||
}
|
||||
|
||||
datastore = ds[0];
|
||||
datastore.addEventListener('change', onchangeHandler);
|
||||
readyState = 'initialized';
|
||||
document.dispatchEvent(new CustomEvent('ds-initialized'));
|
||||
resolve();
|
||||
}, reject);
|
||||
});
|
||||
}
|
||||
|
||||
function doGetAll(resolve, reject) {
|
||||
var result = Object.create(null);
|
||||
var cursor = datastore.sync();
|
||||
|
||||
function cursorResolve(task) {
|
||||
switch (task.operation) {
|
||||
case 'update':
|
||||
case 'add':
|
||||
result[task.data.id] = task.data;
|
||||
break;
|
||||
|
||||
case 'remove':
|
||||
delete result[task.data.id];
|
||||
break;
|
||||
|
||||
case 'clear':
|
||||
result = Object.create(null);
|
||||
break;
|
||||
|
||||
case 'done':
|
||||
resolve(result);
|
||||
return;
|
||||
}
|
||||
|
||||
cursor.next().then(cursorResolve, reject);
|
||||
}
|
||||
|
||||
cursor.next().then(cursorResolve, reject);
|
||||
}
|
||||
|
||||
function get(id) {
|
||||
return new Promise(function doGet(resolve, reject) {
|
||||
init().then(function onInitialized() {
|
||||
datastore.get(id).then(resolve, reject);
|
||||
}, reject);
|
||||
});
|
||||
}
|
||||
|
||||
function getAll() {
|
||||
return new Promise(function doGet(resolve, reject) {
|
||||
init().then(doGetAll.bind(null, resolve, reject), reject);
|
||||
});
|
||||
}
|
||||
|
||||
function onchangeHandler(event) {
|
||||
var operation = event.operation;
|
||||
var callbacks = listeners[operation];
|
||||
callbacks && callbacks.forEach(function iterCallback(callback) {
|
||||
datastore.get(event.id).then(function got(result) {
|
||||
callback.method.call(callback.context || this, {
|
||||
type: operation,
|
||||
target: result || event
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function addEventListener(type, callback) {
|
||||
var context;
|
||||
if (!(type in listeners)) {
|
||||
listeners[type] = [];
|
||||
}
|
||||
|
||||
var cb = callback;
|
||||
if (typeof cb === 'object') {
|
||||
context = cb;
|
||||
cb = cb.handleEvent;
|
||||
}
|
||||
|
||||
if (cb) {
|
||||
listeners[type].push({
|
||||
method: cb,
|
||||
context: context
|
||||
});
|
||||
init();
|
||||
}
|
||||
}
|
||||
|
||||
function removeEventListener(type, callback) {
|
||||
if (!(type in listeners)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
var callbacks = listeners[type];
|
||||
var length = callbacks.length;
|
||||
for (var i = 0; i < length; i++) {
|
||||
|
||||
var thisCallback = callback;
|
||||
if (typeof thisCallback === 'object') {
|
||||
thisCallback = callback.handleEvent;
|
||||
}
|
||||
|
||||
if (callbacks[i] && callbacks[i].method === thisCallback) {
|
||||
callbacks.splice(i, 1);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function add(data) {
|
||||
return new Promise(function doAdd(resolve, reject) {
|
||||
init().then(function onInitialized() {
|
||||
var id = data.url;
|
||||
|
||||
Object.defineProperty(data, 'id', {
|
||||
enumerable: true,
|
||||
configurable: false,
|
||||
writable: false,
|
||||
value: id
|
||||
});
|
||||
|
||||
datastore.add(data, id).then(function add_success() {
|
||||
resolve(true); // Bookmark was added
|
||||
}, function add_error() {
|
||||
datastore.put(data, id).then(function put_success() {
|
||||
resolve(); // Bookmark was updated
|
||||
}, reject);
|
||||
});
|
||||
}, reject);
|
||||
});
|
||||
}
|
||||
|
||||
function getRevisionId() {
|
||||
return new Promise(function doGet(resolve, reject) {
|
||||
init().then(function onInitialized() {
|
||||
resolve(datastore.revisionId);
|
||||
}, reject);
|
||||
});
|
||||
}
|
||||
|
||||
function put(data) {
|
||||
return new Promise(function doAdd(resolve, reject) {
|
||||
init().then(function onInitialized() {
|
||||
datastore.put(data, data.id).then(function success() {
|
||||
resolve(); // Bookmark was updated
|
||||
}, reject);
|
||||
}, reject);
|
||||
});
|
||||
}
|
||||
|
||||
function remove(id) {
|
||||
return new Promise(function doRemove(resolve, reject) {
|
||||
init().then(function onInitialized() {
|
||||
datastore.remove(id).then(resolve, reject);
|
||||
}, reject);
|
||||
});
|
||||
}
|
||||
|
||||
function clear() {
|
||||
return new Promise(function doClear(resolve, reject) {
|
||||
init().then(function onInitialized() {
|
||||
datastore.clear().then(resolve, reject);
|
||||
}, reject);
|
||||
});
|
||||
}
|
||||
|
||||
exports.BookmarksDatabase = {
|
||||
/*
|
||||
* This method returns a bookmark object
|
||||
*
|
||||
* @param{String} String param that represents an identifier
|
||||
*/
|
||||
get: get,
|
||||
|
||||
/*
|
||||
* This method returns an object of bookmarks indexed by id
|
||||
*/
|
||||
getAll: getAll,
|
||||
|
||||
/*
|
||||
* Returns the latest revision UUID
|
||||
*/
|
||||
getRevisionId: getRevisionId,
|
||||
|
||||
/*
|
||||
* Method registers the specified listener on the API
|
||||
*
|
||||
* @param{String} A string representing the event type to listen for
|
||||
*
|
||||
* @param{Function} The method that receives a notification when an event of
|
||||
* the specified type occurs
|
||||
*
|
||||
*/
|
||||
addEventListener: addEventListener,
|
||||
|
||||
/*
|
||||
* Method removes the specified listener on the API
|
||||
*
|
||||
* @param{String} A string representing the event type to listen for
|
||||
*
|
||||
* @param{Function} The method that received a notification when an event of
|
||||
* the specified type occurs
|
||||
*
|
||||
*/
|
||||
removeEventListener: removeEventListener,
|
||||
|
||||
/*
|
||||
* This method adds a bookmark in the datastore
|
||||
*
|
||||
* @param{Object} The bookmark's data
|
||||
*/
|
||||
add: add,
|
||||
|
||||
/*
|
||||
* This method updates a bookmark in the datastore
|
||||
*
|
||||
* @param{Object} The bookmark's data
|
||||
*/
|
||||
put: put,
|
||||
|
||||
/*
|
||||
* This method removes a bookmark from the datastore
|
||||
*
|
||||
* @param{String} The bookmark's id
|
||||
*/
|
||||
remove: remove,
|
||||
|
||||
/*
|
||||
*
|
||||
* This method clears the entire datastore, removing all entries.
|
||||
*
|
||||
*/
|
||||
clear: clear
|
||||
};
|
||||
|
||||
}(window));
|
||||
45
gaia/shared/js/component_utils.js
Executable file
45
gaia/shared/js/component_utils.js
Executable file
|
|
@ -0,0 +1,45 @@
|
|||
|
||||
(function(exports) {
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* ComponentUtils is a utility which allows us to use web components earlier
|
||||
* than we should be able to by polyfilling and fixing platform deficiencies.
|
||||
*/
|
||||
exports.ComponentUtils = {
|
||||
|
||||
/**
|
||||
* Injects a style.css into both the shadow root and outside the shadow
|
||||
* root so we can style projected content. Bug 992249.
|
||||
*/
|
||||
style: function(baseUrl) { if (window.VulpesCompat) { window.VulpesCompat.componentStyle(this, baseUrl).catch(console.error); return; }
|
||||
var style = document.createElement('style');
|
||||
var url = baseUrl + 'style.css';
|
||||
var self = this;
|
||||
|
||||
style.setAttribute('scoped', '');
|
||||
style.innerHTML = '@import url(' + url + ');';
|
||||
this.appendChild(style);
|
||||
|
||||
this.style.visibility = 'hidden';
|
||||
|
||||
// Wait for the stylesheet to load before injecting
|
||||
// it into the shadow-dom. This is to work around
|
||||
// bug 1003294, let's review once landed.
|
||||
style.addEventListener('load', function() {
|
||||
|
||||
// Put a clone of the stylesheet into the shadow-dom.
|
||||
// We have to use two <style> nodes, to work around
|
||||
// the lack of `:host` (bug 992245) and `:content`
|
||||
// (bug 992249) selectors. Once we have those we
|
||||
// can do all our styling from a single style-sheet
|
||||
// within the shadow-dom.
|
||||
if (self.shadowRoot) {
|
||||
self.shadowRoot.appendChild(style.cloneNode(true));
|
||||
}
|
||||
|
||||
self.style.visibility = '';
|
||||
});
|
||||
}
|
||||
};
|
||||
}(window));
|
||||
200
gaia/shared/js/confirm.js
Executable file
200
gaia/shared/js/confirm.js
Executable file
|
|
@ -0,0 +1,200 @@
|
|||
/* exported ConfirmDialog */
|
||||
'use strict';
|
||||
|
||||
var ConfirmDialog = (function() {
|
||||
var isAnimationPlaying = false;
|
||||
var isShown = false;
|
||||
var doc = document; try { if (!document.getElementById("confirmation-message")) doc = parent.document; } catch (_) {}
|
||||
var screen = doc.getElementById('confirmation-message');
|
||||
var titleNode = screen.querySelector('h1');
|
||||
var messageNode = screen.querySelector('p');
|
||||
var action1Node = screen.querySelector('button:nth-of-type(1)');
|
||||
var action1Callback;
|
||||
var action2Node = screen.querySelector('button:nth-of-type(2)');
|
||||
var action2Callback;
|
||||
var oldzIndex;
|
||||
|
||||
var callBackAndPreventDefault = function callBackAndPreventDefault(ev) {
|
||||
if (ev.target === action1Node) {
|
||||
action1Callback();
|
||||
ev.preventDefault();
|
||||
return false;
|
||||
} else if (ev.target === action2Node) {
|
||||
action2Callback();
|
||||
ev.preventDefault();
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
var _hide = function _hide() {
|
||||
// Reset the 'confirmation-message' element and its children to their
|
||||
// initial values and hide it.
|
||||
if (!isShown) {
|
||||
return;
|
||||
}
|
||||
|
||||
titleNode.removeAttribute('data-l10n-id');
|
||||
titleNode.className = '';
|
||||
messageNode.removeAttribute('data-l10n-id');
|
||||
messageNode.className = '';
|
||||
action1Node.removeAttribute('data-l10n-id');
|
||||
action1Node.onclick = null;
|
||||
action2Node.removeAttribute('data-l10n-id');
|
||||
action2Node.onclick = null;
|
||||
screen.classList.remove('fade-in');
|
||||
screen.classList.add('fade-out');
|
||||
isAnimationPlaying = true;
|
||||
// Custom event that can be used to apply (screen reader) visibility
|
||||
// changes.
|
||||
window.dispatchEvent(new CustomEvent('confirmdialoghiding'));
|
||||
screen.addEventListener('animationend', function cd_fadeOut(ev) {
|
||||
action1Node.className = '';
|
||||
action2Node.className = '';
|
||||
isAnimationPlaying = false;
|
||||
screen.removeEventListener('animationend', cd_fadeOut);
|
||||
screen.classList.add('no-opacity');
|
||||
screen.classList.add('hide');
|
||||
isShown = false;
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Method that shows the dialog
|
||||
* @param {String} title the title of the dialog. null or empty for
|
||||
* no title.
|
||||
* @param {String} msg message for the dialog.
|
||||
* @param {Object} action1 {title, isDanger, callback} object.
|
||||
* @param {Object} action2 {title, isDanger, callback} object.
|
||||
*/
|
||||
var _show = function _show(title, msg, action1, action2, options) {
|
||||
|
||||
var setL10nAttributes = function (element, options){
|
||||
if ('string' === typeof options) {
|
||||
document.l10n.setAttributes(element, options);
|
||||
}
|
||||
|
||||
if(options.id) {
|
||||
document.l10n.setAttributes(element, options.id, options.args);
|
||||
}
|
||||
};
|
||||
|
||||
if (options && options.zIndex) {
|
||||
oldzIndex = screen.style.zIndex;
|
||||
screen.style.zIndex = options.zIndex;
|
||||
}
|
||||
else {
|
||||
oldzIndex = null;
|
||||
}
|
||||
if (title) {
|
||||
setL10nAttributes(titleNode, title);
|
||||
} else {
|
||||
titleNode.classList.add('hide');
|
||||
}
|
||||
if (msg) {
|
||||
setL10nAttributes(messageNode, msg);
|
||||
} else {
|
||||
messageNode.classList.add('hide');
|
||||
}
|
||||
if (action1) {
|
||||
if (action1.title) {
|
||||
setL10nAttributes(action1Node, action1.title);
|
||||
}
|
||||
if (action1.isDanger) {
|
||||
action1Node.classList.add('danger');
|
||||
}
|
||||
if (action1.isRecommend) {
|
||||
action1Node.classList.add('recommend');
|
||||
}
|
||||
if (action1.callback) {
|
||||
action1Callback = action1.callback;
|
||||
action1Node.onclick = callBackAndPreventDefault;
|
||||
}
|
||||
if (!action2) {
|
||||
action2Node.classList.add('hide');
|
||||
action1Node.classList.add('full');
|
||||
}
|
||||
}
|
||||
if (action2) {
|
||||
if (action2.title) {
|
||||
setL10nAttributes(action2Node, action2.title);
|
||||
}
|
||||
if (action2.isDanger) {
|
||||
action2Node.classList.add('danger');
|
||||
}
|
||||
if (action2.isRecommend) {
|
||||
action2Node.classList.add('recommend');
|
||||
}
|
||||
if (action2.callback) {
|
||||
action2Callback = action2.callback;
|
||||
action2Node.onclick = callBackAndPreventDefault;
|
||||
}
|
||||
if (!action1) {
|
||||
action1Node.classList.add('hide');
|
||||
action2Node.classList.add('full');
|
||||
}
|
||||
}
|
||||
if (isShown) {
|
||||
return;
|
||||
}
|
||||
|
||||
screen.classList.remove('hide');
|
||||
screen.classList.remove('fade-out');
|
||||
screen.classList.add('fade-in');
|
||||
isAnimationPlaying = true;
|
||||
// Custom event that can be used to apply (screen reader) visibility
|
||||
// changes.
|
||||
window.dispatchEvent(new CustomEvent('confirmdialogshowing'));
|
||||
screen.addEventListener('animationend', function cd_fadeIn(ev) {
|
||||
isAnimationPlaying = false;
|
||||
screen.removeEventListener('animationend', cd_fadeIn);
|
||||
screen.classList.remove('no-opacity');
|
||||
isShown = true;
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
hide: function dialog_hide() {
|
||||
// Reset the 'confirmation-message' element and its children to their
|
||||
// initial values and hide it.
|
||||
if (oldzIndex) {
|
||||
screen.style.zIndex = oldzIndex;
|
||||
oldzIndex = null;
|
||||
}
|
||||
|
||||
if (!isAnimationPlaying) {
|
||||
_hide();
|
||||
return;
|
||||
}
|
||||
|
||||
screen.addEventListener('animationend',
|
||||
function cd_hideWhenFinished(ev) {
|
||||
screen.removeEventListener('animationend', cd_hideWhenFinished);
|
||||
_hide();
|
||||
}
|
||||
);
|
||||
},
|
||||
|
||||
/**
|
||||
* Method that shows the dialog
|
||||
* @param {String} title the title of the dialog. null or empty for
|
||||
* no title.
|
||||
* @param {String} msg message for the dialog.
|
||||
* @param {Object} action1 {title, isDanger, callback} object.
|
||||
* @param {Object} action2 {title, isDanger, callback} object.
|
||||
*/
|
||||
show: function dialog_show(title, msg, action1, action2, options) {
|
||||
if (!isAnimationPlaying) {
|
||||
_show(title, msg, action1, action2, options);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
screen.addEventListener('animationend',
|
||||
function cd_showWhenFinished(ev) {
|
||||
screen.removeEventListener('animationend', cd_showWhenFinished);
|
||||
_show(title, msg, action1, action2, options);
|
||||
}
|
||||
);
|
||||
}
|
||||
};
|
||||
}());
|
||||
386
gaia/shared/js/contact2vcard.js
Executable file
386
gaia/shared/js/contact2vcard.js
Executable file
|
|
@ -0,0 +1,386 @@
|
|||
/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- /
|
||||
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
|
||||
|
||||
/* globals setImmediate, Normalizer */
|
||||
|
||||
/**
|
||||
* ContactToVcard provides the functionality necessary to export from
|
||||
* MozContacts to vCard 3.0 (https://www.ietf.org/rfc/rfc2426.txt). The reason
|
||||
* to choose the 3.0 standard instead of the 4.0 one is that some systems
|
||||
* most notoriously Android 4.x don't seem to be able to import vCard 4.0.
|
||||
*/
|
||||
(function(exports) {
|
||||
'use strict';
|
||||
|
||||
/** Mapping between contact fields and equivalent vCard fields */
|
||||
var VCARD_MAP = {
|
||||
'fax' : 'FAX',
|
||||
'faxoffice' : 'FAX,WORK',
|
||||
'faxhome' : 'FAX,HOME',
|
||||
'faxother' : 'FAX',
|
||||
'home' : 'HOME',
|
||||
'mobile' : 'CELL',
|
||||
'pager' : 'PAGER',
|
||||
'personal' : 'HOME',
|
||||
'pref' : 'PREF',
|
||||
'text' : 'TEXT',
|
||||
'textphone' : 'TEXTPHONE',
|
||||
'voice' : 'VOICE',
|
||||
'work' : 'WORK'
|
||||
};
|
||||
|
||||
var CRLF = '\r\n';
|
||||
|
||||
/** Field list to be skipped when converting to vCard */
|
||||
var VCARD_SKIP_FIELD = ['fb_profile_photo'];
|
||||
var VCARD_VERSION = '3.0';
|
||||
var HEADER = 'BEGIN:VCARD' + CRLF + 'VERSION:' + VCARD_VERSION + CRLF;
|
||||
var FOOTER = 'END:VCARD' + CRLF;
|
||||
|
||||
function blobToBase64(blob, cb) {
|
||||
var reader = new FileReader();
|
||||
|
||||
reader.onload = function() {
|
||||
var dataUrl = reader.result;
|
||||
var base64 = dataUrl.split(',')[1];
|
||||
cb(base64);
|
||||
};
|
||||
|
||||
reader.readAsDataURL(blob);
|
||||
}
|
||||
|
||||
function ISODateString(d) {
|
||||
if (typeof d === 'string') {
|
||||
d = new Date(d);
|
||||
}
|
||||
|
||||
var str = d.toISOString();
|
||||
|
||||
// Remove the milliseconds field
|
||||
return str.slice(0, str.indexOf('.')) + 'Z';
|
||||
}
|
||||
|
||||
/**
|
||||
* Given an array with contact fields (usually containing only one field),
|
||||
* returns the equivalent vcard field
|
||||
*
|
||||
* @param {Array} sourceField source field from a MozContact
|
||||
* @param {String} vcardField vCard field name
|
||||
* @return {Array} Array of vCard string entries
|
||||
*/
|
||||
function fromContactField(sourceField, vcardField) {
|
||||
if (!sourceField || !sourceField.length) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// Goes to the entries in the given field (usually only one but potentially
|
||||
// more) and transforms them into string-based, vCard ones.
|
||||
return sourceField.map(function(field) {
|
||||
var str = vcardField;
|
||||
/**
|
||||
* If the field doesn't have an equivalent in vcard standard.
|
||||
* Incompatible fields are stored in `VCARD_SKIP_FIELD`.
|
||||
*
|
||||
* @type {boolean}
|
||||
*/
|
||||
var skipField = false;
|
||||
var types = [];
|
||||
|
||||
// Checks existing types and converts them to vcard types if necessary
|
||||
// and fill `types` array with the final types.
|
||||
if (Array.isArray(field.type)) {
|
||||
var fieldType = field.type.map(function(aType) {
|
||||
var out = '';
|
||||
if (aType) {
|
||||
aType = aType.trim().toLowerCase();
|
||||
if (VCARD_SKIP_FIELD.indexOf(aType) !== -1) {
|
||||
skipField = true;
|
||||
}
|
||||
out = VCARD_MAP[aType] || aType;
|
||||
}
|
||||
return out;
|
||||
});
|
||||
|
||||
types = types.concat(fieldType);
|
||||
}
|
||||
|
||||
if (skipField) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (field.pref && field.pref === true) {
|
||||
types.push('PREF');
|
||||
}
|
||||
|
||||
if (types.length) {
|
||||
str += ';TYPE=' + types.join(',');
|
||||
}
|
||||
|
||||
return str + ':' + (field.value || '');
|
||||
});
|
||||
}
|
||||
|
||||
function fromStringArray(sourceField, vcardField) {
|
||||
if (!sourceField) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return vcardField + ':' + sourceField.join(',');
|
||||
}
|
||||
|
||||
function joinFields(fields) {
|
||||
return fields.filter(function(f) { return !!f; }).join(CRLF);
|
||||
}
|
||||
|
||||
function toBlob(vcard, type) {
|
||||
return new Blob([vcard], {'type': type});
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience function that converts an array of contacts into a text/vcard
|
||||
* blob. The blob is passed to the callback once the conversion is done.
|
||||
*
|
||||
* @param {Array} contacts An array of mozContact objects.
|
||||
* @param {Function} callback A function invoked with the generated blob.
|
||||
*/
|
||||
function ContactToVcardBlob(contacts, callback, options) {
|
||||
var targetType = options && options.type || 'text/vcard';
|
||||
if(targetType.indexOf('charset') === -1) {
|
||||
targetType += '; charset=utf-8';
|
||||
}
|
||||
|
||||
if (typeof callback !== 'function') {
|
||||
throw Error('callback() is undefined or not a function');
|
||||
}
|
||||
|
||||
var str = '';
|
||||
|
||||
ContactToVcard(contacts, function append(vcards, nCards) {
|
||||
str += vcards;
|
||||
}, function success() {
|
||||
str = str ? toBlob(str) : null;
|
||||
callback(toBlob(str, targetType));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts an array of contacts to a string of vCards. The conversion is
|
||||
* done in batches. For every batch the append callback is invoked with a
|
||||
* string of vCards and the number of contacts in the batch. Once all
|
||||
* contacts have been processed the success callback is invoked.
|
||||
*
|
||||
* @param {Array} contacts An array of mozContact objects.
|
||||
* @param {Function} append A function taking two parameters, the first one
|
||||
* will be passed a string of vCards and the second an integer
|
||||
* representing the number of contacts in the string.
|
||||
* @param {Function} success A function with no parameters that will be
|
||||
* invoked once all the contacts have been processed.
|
||||
* @param {Number} batchSize An optional parameter specifying the maximum
|
||||
* number of characters that should be added to the output string
|
||||
* before invoking the append callback. If this paramter is not
|
||||
* provided a default value of 1MiB will be used instead.
|
||||
*/
|
||||
function ContactToVcard(contacts, append, success, batchSize, skipPhoto) {
|
||||
var vCardsString = '';
|
||||
var nextIndex = 0;
|
||||
var cardsInBatch = 0;
|
||||
|
||||
batchSize = batchSize || (1024 * 1024);
|
||||
|
||||
if (typeof append !== 'function') {
|
||||
throw Error('append() is undefined or not a function');
|
||||
}
|
||||
|
||||
if (typeof success !== 'function') {
|
||||
throw Error('append() is undefined or not a function');
|
||||
}
|
||||
|
||||
/**
|
||||
* Append the vCard obtained by converting the contact to the string of
|
||||
* vCards and if necessary pass the string to the user-specified callback
|
||||
* function. If we're not done processing all the contacts start processing
|
||||
* the following one.
|
||||
*
|
||||
* @param {String} vcard The string obtained from the previously processed
|
||||
* contact.
|
||||
*/
|
||||
function appendVCard(vcard) {
|
||||
if (vcard.length > 0) {
|
||||
vCardsString += HEADER + vcard + CRLF + FOOTER;
|
||||
}
|
||||
|
||||
nextIndex++;
|
||||
cardsInBatch++;
|
||||
|
||||
/* Invoke the user-provided callback if we've filled the current batch or
|
||||
* if we don't have more contacts to process. */
|
||||
if ((vCardsString.length > batchSize) ||
|
||||
(nextIndex === contacts.length)) {
|
||||
append(vCardsString, cardsInBatch);
|
||||
cardsInBatch = 0;
|
||||
vCardsString = '';
|
||||
}
|
||||
|
||||
if (nextIndex < contacts.length) {
|
||||
processContact(contacts[nextIndex]);
|
||||
} else {
|
||||
success();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process a contact and invokes appendVCard with the resulting vCard
|
||||
* string.
|
||||
*
|
||||
* @param {Object} contacts A mozContact object.
|
||||
*/
|
||||
function processContact(ct) {
|
||||
if (navigator.mozContact && !(ct instanceof navigator.mozContact)) {
|
||||
console.error('An instance of mozContact was expected');
|
||||
setImmediate(function() { appendVCard(''); });
|
||||
return;
|
||||
}
|
||||
|
||||
/*
|
||||
* N TYPE
|
||||
* The structured type value corresponds, in
|
||||
* sequence, to the Family Name, Given Name, Additional Names, Honorific
|
||||
* Prefixes, and Honorific Suffixes. The text components are separated
|
||||
* by the SEMI-COLON character (ASCII decimal 59). Individual text
|
||||
* components can include multiple text values (e.g., multiple
|
||||
* Additional Names) separated by the COMMA character (ASCII decimal
|
||||
* 44). This type is based on the semantics of the X.520 individual name
|
||||
* attributes. The property MUST be present in the vCard object.
|
||||
**/
|
||||
var n = 'n:' + ([
|
||||
ct.familyName,
|
||||
ct.givenName,
|
||||
ct.additionalName,
|
||||
ct.honorificPrefix,
|
||||
ct.honorificSuffix
|
||||
].map(function(f) {
|
||||
f = f || [''];
|
||||
return f.join(',') + ';';
|
||||
}).join(''));
|
||||
|
||||
// vCard standard does not accept contacts without 'n' or 'fn' fields.
|
||||
if (n === 'n:;;;;;' || !ct.name) {
|
||||
setImmediate(function() { appendVCard(''); });
|
||||
return;
|
||||
}
|
||||
|
||||
var allFields = [
|
||||
n,
|
||||
fromStringArray(ct.name, 'FN'),
|
||||
fromStringArray(ct.nickname, 'NICKNAME'),
|
||||
fromStringArray(ct.category, 'CATEGORY'),
|
||||
fromStringArray(ct.org, 'ORG'),
|
||||
fromStringArray(ct.jobTitle, 'TITLE'),
|
||||
fromStringArray(ct.note, 'NOTE'),
|
||||
fromStringArray(ct.key, 'KEY')
|
||||
];
|
||||
|
||||
if (ct.bday) {
|
||||
allFields.push('BDAY:' + ISODateString(ct.bday));
|
||||
}
|
||||
if (ct.anniversary) {
|
||||
allFields.push('ANNIVERSARY:' + ISODateString(ct.anniversary));
|
||||
}
|
||||
|
||||
allFields.push.apply(allFields, fromContactField(ct.email, 'EMAIL'));
|
||||
allFields.push.apply(allFields, fromContactField(ct.url, 'URL'));
|
||||
allFields.push.apply(allFields, fromContactField(ct.tel, 'TEL'));
|
||||
|
||||
var adrs = fromContactField(ct.adr, 'ADR');
|
||||
allFields.push.apply(allFields, adrs.map(function(adrStr, i) {
|
||||
var orig = ct.adr[i];
|
||||
return adrStr + ([
|
||||
'',
|
||||
'',
|
||||
orig.streetAddress || '', orig.locality || '', orig.region || '',
|
||||
orig.postalCode || '', orig.countryName || ''].join(';'));
|
||||
}));
|
||||
|
||||
/**
|
||||
* PHOTO TYPE
|
||||
* The encoding MUST be reset to "b" using the ENCODING
|
||||
* parameter in order to specify inline, encoded binary data. If the
|
||||
* value is referenced by a URI value, then the default encoding of 8bit
|
||||
* is used and no explicit ENCODING parameter is needed.
|
||||
|
||||
* Type value: A single value. The default is binary value. It can also
|
||||
* be reset to uri value. The uri value can be used to specify a value
|
||||
* outside of this MIME entity.
|
||||
|
||||
* Type special notes: The type can include the type parameter "TYPE" to
|
||||
* specify the graphic image format type. The TYPE parameter values MUST
|
||||
* be one of the IANA registered image formats or a non-standard image
|
||||
* format.
|
||||
*/
|
||||
if (
|
||||
(
|
||||
typeof skipPhoto == 'undefined' ||
|
||||
skipPhoto === false
|
||||
) &&
|
||||
ct.photo &&
|
||||
ct.photo.length
|
||||
) {
|
||||
var photoMeta = ['PHOTO', 'ENCODING=b'];
|
||||
var blob = ct.photo[0];
|
||||
|
||||
blobToBase64(blob, function(b64) {
|
||||
if (blob.type) {
|
||||
photoMeta.push('TYPE=' + blob.type);
|
||||
}
|
||||
allFields.push(photoMeta.join(';') + ':' + b64);
|
||||
appendVCard(joinFields(allFields));
|
||||
});
|
||||
} else {
|
||||
setImmediate(function() { appendVCard(joinFields(allFields)); });
|
||||
}
|
||||
}
|
||||
|
||||
processContact(contacts[0]);
|
||||
}
|
||||
|
||||
// Generates a name for the contact returned as a vcard
|
||||
function getVcardFilename(theContact) {
|
||||
var out = '';
|
||||
|
||||
var givenName = Array.isArray(theContact.givenName) &&
|
||||
theContact.givenName[0];
|
||||
var familyName = Array.isArray(theContact.familyName) &&
|
||||
theContact.familyName[0];
|
||||
|
||||
if (givenName) {
|
||||
out = givenName;
|
||||
}
|
||||
|
||||
if (familyName) {
|
||||
if (out) {
|
||||
out += '_';
|
||||
}
|
||||
out += familyName;
|
||||
}
|
||||
|
||||
out = out || (Array.isArray(theContact.org) && theContact.org[0]);
|
||||
|
||||
out = out || (Array.isArray(theContact.tel) && theContact.tel[0] &&
|
||||
( 'c' + '_' + theContact.tel[0].value) );
|
||||
|
||||
out = out || (Array.isArray(theContact.email) && theContact.email[0] &&
|
||||
theContact.email[0].value);
|
||||
|
||||
out = Normalizer.toAscii(out).replace(/[\s+@#&?\+\$]/g, '');
|
||||
|
||||
if (out) {
|
||||
return Promise.resolve(out + '.vcf');
|
||||
}
|
||||
|
||||
return navigator.mozL10n.formatValue('noName').then(name => name + '.vcf');
|
||||
}
|
||||
|
||||
exports.ContactToVcard = ContactToVcard;
|
||||
exports.ContactToVcardBlob = ContactToVcardBlob;
|
||||
exports.VcardFilename = getVcardFilename;
|
||||
})(this);
|
||||
71
gaia/shared/js/contact_photo_helper.js
Executable file
71
gaia/shared/js/contact_photo_helper.js
Executable file
|
|
@ -0,0 +1,71 @@
|
|||
/* -*- Mode: js; js-indent-level: 2; indent-tabs-mode: nil -*- */
|
||||
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
|
||||
|
||||
(function(exports) {
|
||||
'use strict';
|
||||
|
||||
function getThumbnail(contact) {
|
||||
return getOnePhoto(contact, 'begin');
|
||||
}
|
||||
|
||||
function getFullResolution(contact) {
|
||||
return getOnePhoto(contact, 'end');
|
||||
}
|
||||
|
||||
function getOnePhoto(contact, position) {
|
||||
if (!contact || !contact.photo || !contact.photo.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (contact.photo.length === 1) {
|
||||
return contact.photo[0];
|
||||
}
|
||||
|
||||
// For FB Linked contacts we need to give preference to the local photo
|
||||
// [0] is the full resolution photo and [1] is the thumbnail
|
||||
var photos = contact.photo;
|
||||
var category = contact.category;
|
||||
if (Array.isArray(category) && category.indexOf('fb_linked') !== -1) {
|
||||
// Check whether we have a new linked contact or a legacy contact
|
||||
if (photos.length >= 4) {
|
||||
return photos[(position == 'begin') ? 1 : 0];
|
||||
}
|
||||
// In the case of a legacy contact we always return full resolution
|
||||
// in order to ensure we are always giving preference to local photo
|
||||
return photos[0];
|
||||
}
|
||||
|
||||
photos = photosBySize(contact);
|
||||
var index = (position == 'begin') ? 0 : photos.length - 1;
|
||||
return photos[index];
|
||||
}
|
||||
|
||||
function photosBySize(contact) {
|
||||
var photos = contact.photo.slice(0);
|
||||
photos.sort(function(p1, p2) {
|
||||
if (size(p1) < size(p2)) {
|
||||
return -1;
|
||||
}
|
||||
if (size(p1) > size(p2)) {
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
});
|
||||
|
||||
return photos;
|
||||
}
|
||||
|
||||
// For legacy purpose we support data URLs and blobs
|
||||
function size(photo) {
|
||||
if (typeof photo == 'string') {
|
||||
return photo.length; // length of the data URL
|
||||
}
|
||||
|
||||
return photo.size; // size of the blob in bytes
|
||||
}
|
||||
|
||||
exports.ContactPhotoHelper = {
|
||||
getThumbnail: getThumbnail,
|
||||
getFullResolution: getFullResolution
|
||||
};
|
||||
})(window);
|
||||
222
gaia/shared/js/contacts/contacts_buttons.js
Executable file
222
gaia/shared/js/contacts/contacts_buttons.js
Executable file
|
|
@ -0,0 +1,222 @@
|
|||
'use strict';
|
||||
|
||||
/* exported ContactsButtons */
|
||||
|
||||
/* globals LazyLoader, MozActivity, MultiSimActionButton, Normalizer,
|
||||
SmsIntegration, TelephonyHelper, utils */
|
||||
|
||||
var ContactsButtons = {
|
||||
DEFAULT_TEL_TYPE: 'other',
|
||||
DEFAULT_EMAIL_TYPE: 'other',
|
||||
|
||||
_listContainer: null,
|
||||
_contactDetails: null,
|
||||
|
||||
_activityHandler: null,
|
||||
|
||||
init: function init(listContainer, contactDetails, activityHandler) {
|
||||
this._listContainer = listContainer;
|
||||
this._contactDetails = contactDetails;
|
||||
this._activityHandler = activityHandler;
|
||||
},
|
||||
|
||||
_enableCalls: function enableCalls() {
|
||||
this._contactDetails.classList.remove('calls-disabled');
|
||||
},
|
||||
|
||||
_disableCalls: function disableCalls() {
|
||||
this._contactDetails.classList.add('calls-disabled');
|
||||
},
|
||||
|
||||
_call: function call(phoneNumber, cardIndex) {
|
||||
this._disableCalls();
|
||||
var enableCalls = this._enableCalls.bind(this);
|
||||
LazyLoader.load('/dialer/js/telephony_helper.js', () => {
|
||||
TelephonyHelper.call(phoneNumber, cardIndex, enableCalls, enableCalls,
|
||||
enableCalls, enableCalls);
|
||||
});
|
||||
},
|
||||
|
||||
/* For security reasons we cannot directly call MmiManager.send() thus we
|
||||
* need to special-case MMI numbers. This function detects MMI numbers in
|
||||
* their most common form; other forms (such as short-string MMI codes)
|
||||
* don't make sense for the contacts app and thus aren't considered. */
|
||||
_isMMI: function _isMMI(number) {
|
||||
return number.charAt(number.length - 1) === '#';
|
||||
},
|
||||
|
||||
// Check current situation and setup different listener for the button
|
||||
_setupPhoneButtonListener: function setupPhoneButtonListener(button, number) {
|
||||
var self = this;
|
||||
|
||||
if (this._activityHandler &&
|
||||
this._activityHandler.currentActivityIsNot(['open'])) {
|
||||
button.addEventListener('click', this._onPickNumber.bind(this));
|
||||
} else if (this._isMMI(number)) {
|
||||
button.addEventListener('click', this._onMMICode.bind(this));
|
||||
} else if (navigator.mozTelephony) {
|
||||
LazyLoader.load(['/shared/js/multi_sim_action_button.js'], function() {
|
||||
/* jshint nonew: false */
|
||||
new MultiSimActionButton(button, self._call.bind(self),
|
||||
'ril.telephony.defaultServiceId',
|
||||
() => number);
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
// If we are currently handing an activity, send the phone
|
||||
// number as result of clicking in the phone button.
|
||||
_onPickNumber: function onPickNumber(evt) {
|
||||
var number = evt.target.dataset.tel;
|
||||
if (this._activityHandler) {
|
||||
this._activityHandler.postPickSuccess({ number: number });
|
||||
}
|
||||
},
|
||||
|
||||
// If the phone number stored in a contact is a MMI code,
|
||||
// launch the dialer with that specific code.
|
||||
_onMMICode: function onMMICode(evt) {
|
||||
var number = evt.target.dataset.tel;
|
||||
// For security reasons we cannot directly call MmiManager.send(). We
|
||||
// need to show the MMI number in the dialer instead.
|
||||
/* jshint nonew: false */
|
||||
new MozActivity({
|
||||
name: 'dial',
|
||||
data: {
|
||||
type: 'webtelephony/number',
|
||||
number: number
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
_onSendSmsClicked: function onSendSmsClicked(evt) {
|
||||
var tel = evt.target.dataset.tel;
|
||||
LazyLoader.load('/shared/js/contacts/sms_integration.js', () => {
|
||||
SmsIntegration.sendSms(tel);
|
||||
});
|
||||
},
|
||||
|
||||
_onEmailOrPickClick: function onEmailOrPickClick(evt) {
|
||||
evt.preventDefault();
|
||||
var email = evt.target.dataset.email;
|
||||
this.sendEmailOrPick(email);
|
||||
return false;
|
||||
},
|
||||
|
||||
renderPhones: function cd_renderPhones(contact) {
|
||||
if (!contact.tel) {
|
||||
return;
|
||||
}
|
||||
var telLength = this._getLength(contact.tel);
|
||||
for (var tel = 0; tel < telLength; tel++) {
|
||||
var currentTel = contact.tel[tel];
|
||||
var typeKey = currentTel.type;
|
||||
var escapedType = Normalizer.escapeHTML(currentTel.type, true).trim();
|
||||
var carrier = Normalizer.escapeHTML(currentTel.carrier || '', true) || '';
|
||||
|
||||
if (!escapedType) {
|
||||
typeKey = this.DEFAULT_TEL_TYPE;
|
||||
}
|
||||
|
||||
var telField = {
|
||||
value: Normalizer.escapeHTML(currentTel.value, true) || '',
|
||||
type: escapedType,
|
||||
'type_l10n_id': typeKey,
|
||||
carrier: carrier,
|
||||
i: tel
|
||||
};
|
||||
|
||||
var phonesTemplate =
|
||||
document.querySelector('#phone-details-template-\\#i\\#');
|
||||
var template = utils.templates.render(phonesTemplate, telField);
|
||||
|
||||
// Add event listeners to the phone template components
|
||||
var sendSmsButton = template.querySelector('#send-sms-button-' + tel);
|
||||
sendSmsButton.dataset.tel = telField.value;
|
||||
sendSmsButton.addEventListener('click',
|
||||
this._onSendSmsClicked.bind(this));
|
||||
|
||||
var callOrPickButton = template.querySelector('#call-or-pick-' + tel);
|
||||
callOrPickButton.dataset.tel = telField.value;
|
||||
this._setupPhoneButtonListener(callOrPickButton, telField.value);
|
||||
|
||||
if (carrier) {
|
||||
var carrierWrapperElt = template.querySelector('.carrier-wrapper');
|
||||
carrierWrapperElt.hidden = false;
|
||||
}
|
||||
|
||||
this._listContainer.appendChild(template);
|
||||
}
|
||||
},
|
||||
|
||||
renderEmails: function cd_renderEmails(contact) {
|
||||
if (!contact.email) {
|
||||
return;
|
||||
}
|
||||
var emailLength = this._getLength(contact.email);
|
||||
for (var email = 0; email < emailLength; email++) {
|
||||
var currentEmail = contact.email[email];
|
||||
var emailField = {
|
||||
value: Normalizer.escapeHTML(currentEmail.value, true) || '',
|
||||
'type_l10n_id': currentEmail.type,
|
||||
i: email
|
||||
};
|
||||
var emailsTemplate =
|
||||
document.querySelector('#email-details-template-\\#i\\#');
|
||||
var template = utils.templates.render(emailsTemplate, emailField);
|
||||
|
||||
// Send MMS to the email address
|
||||
var sendSmsButton =
|
||||
template.querySelector('#send-sms-to-email-button-' + email);
|
||||
sendSmsButton.dataset.tel = emailField.value;
|
||||
sendSmsButton.addEventListener('click',
|
||||
this._onSendSmsClicked.bind(this));
|
||||
|
||||
// Add event listeners to the phone template components
|
||||
var emailButton = template.querySelector('#email-or-pick-' + email);
|
||||
emailButton.dataset.email = emailField.value;
|
||||
emailButton.addEventListener('click',
|
||||
this._onEmailOrPickClick.bind(this));
|
||||
|
||||
this._listContainer.appendChild(template);
|
||||
}
|
||||
},
|
||||
|
||||
reMark: function(field, value, remarkClass) {
|
||||
var selector = '[data-' + field + '="' + value + '"]';
|
||||
var elements = this._listContainer.querySelectorAll(selector);
|
||||
|
||||
if (typeof remarkClass === 'undefined') {
|
||||
remarkClass = 'remark';
|
||||
}
|
||||
|
||||
for (var i = 0; i < elements.length; i++) {
|
||||
elements[i].classList.add(remarkClass);
|
||||
}
|
||||
},
|
||||
|
||||
_getLength: function(prop) {
|
||||
if (!prop || !prop.length) {
|
||||
return 0;
|
||||
}
|
||||
return prop.length;
|
||||
},
|
||||
|
||||
sendEmailOrPick: function(address) {
|
||||
try {
|
||||
// We don't check the email format, lets the email
|
||||
// app do that
|
||||
/* jshint nonew: false */
|
||||
new MozActivity({
|
||||
name: 'new',
|
||||
data: {
|
||||
type: 'mail',
|
||||
URI: 'mailto:' + address
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('WebActivities unavailable? : ' + e);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
113
gaia/shared/js/contacts/contacts_cleaner.js
Executable file
113
gaia/shared/js/contacts/contacts_cleaner.js
Executable file
|
|
@ -0,0 +1,113 @@
|
|||
'use strict';
|
||||
/* global utils */
|
||||
|
||||
window.ContactsCleaner = function(contacts) {
|
||||
this.lcontacts = contacts;
|
||||
var total = contacts.length;
|
||||
var next = 0;
|
||||
var self = this;
|
||||
var CHUNK_SIZE = 5;
|
||||
var numResponses = 0;
|
||||
var notifyClean = false;
|
||||
|
||||
var mustHold = false;
|
||||
var holded = false;
|
||||
var mustFinish = false;
|
||||
|
||||
this.start = function() {
|
||||
mustHold = holded = mustFinish = false;
|
||||
|
||||
if (total > 0) {
|
||||
cleanContacts(0);
|
||||
}
|
||||
else if (typeof self.onsuccess === 'function') {
|
||||
window.setTimeout(self.onsuccess, 0);
|
||||
}
|
||||
};
|
||||
|
||||
this.hold = function() {
|
||||
mustHold = true;
|
||||
};
|
||||
|
||||
this.finish = function() {
|
||||
mustFinish = true;
|
||||
|
||||
if (holded) {
|
||||
notifySuccess();
|
||||
}
|
||||
};
|
||||
|
||||
this.resume = function() {
|
||||
mustHold = holded = mustFinish = false;
|
||||
|
||||
window.setTimeout(function resume_clean() {
|
||||
cleanContacts(next);
|
||||
});
|
||||
};
|
||||
|
||||
this.performClean = function(contact, number, cbs) {
|
||||
var req = navigator.mozContacts.remove(utils.misc.toMozContact(contact));
|
||||
req.number = number;
|
||||
req.onsuccess = cbs.success;
|
||||
req.onerror = function(e) {
|
||||
errorHandler(contact.id, e.target.error);
|
||||
};
|
||||
};
|
||||
|
||||
function successHandler(e) {
|
||||
if (notifyClean || typeof self.oncleaned === 'function') {
|
||||
notifyClean = true;
|
||||
// Avoiding race condition so the cleaned element is cached
|
||||
var cleaned = e.target.number;
|
||||
window.setTimeout(function() {
|
||||
self.oncleaned(cleaned);
|
||||
},0);
|
||||
}
|
||||
continueCb();
|
||||
}
|
||||
|
||||
function errorHandler(contactid, error) {
|
||||
if (typeof self.onerror === 'function') {
|
||||
self.onerror(contactid, error);
|
||||
}
|
||||
|
||||
continueCb();
|
||||
}
|
||||
|
||||
function cleanContacts(from) {
|
||||
for (var idx = from; idx < (from + CHUNK_SIZE) && idx < total; idx++) {
|
||||
var contact = contacts[idx];
|
||||
self.performClean(contact, idx, {
|
||||
success: successHandler
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function notifySuccess() {
|
||||
if (typeof self.onsuccess === 'function') {
|
||||
window.setTimeout(self.onsuccess);
|
||||
}
|
||||
}
|
||||
|
||||
function continueCb() {
|
||||
next++;
|
||||
numResponses++;
|
||||
if (next < total && numResponses === CHUNK_SIZE) {
|
||||
numResponses = 0;
|
||||
if (!mustHold && !mustFinish) {
|
||||
cleanContacts(next);
|
||||
}
|
||||
else if (mustFinish && !holded) {
|
||||
notifySuccess();
|
||||
}
|
||||
|
||||
if (mustHold) {
|
||||
holded = true;
|
||||
}
|
||||
}
|
||||
else if (next >= total) {
|
||||
// End has been reached
|
||||
notifySuccess();
|
||||
}
|
||||
} // function
|
||||
}; // ContactsCleaner
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue