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
49 changed files with 9982925 additions and 369 deletions
85
gaia/apps/communications/contacts/js/action_menu.js
Executable file
85
gaia/apps/communications/contacts/js/action_menu.js
Executable file
|
|
@ -0,0 +1,85 @@
|
|||
/* exported ActionMenu */
|
||||
'use strict';
|
||||
|
||||
function ActionMenu(title) {
|
||||
var data;
|
||||
var contactActionMenu;
|
||||
var listContainer;
|
||||
var btnCancel;
|
||||
var titleId = title;
|
||||
|
||||
function init() {
|
||||
contactActionMenu = document.getElementById('action-menu');
|
||||
// Prevent submit in the form
|
||||
contactActionMenu.addEventListener('submit', function(evt) {
|
||||
evt.preventDefault();
|
||||
});
|
||||
|
||||
if (titleId) {
|
||||
contactActionMenu.querySelector('#org-title').setAttribute(
|
||||
'data-l10n-id', titleId);
|
||||
}
|
||||
listContainer = document.getElementById('value-menu');
|
||||
|
||||
data = {
|
||||
list: []
|
||||
};
|
||||
}
|
||||
|
||||
this.show = function() {
|
||||
render(this);
|
||||
contactActionMenu.classList.remove('hide');
|
||||
};
|
||||
|
||||
this.hide = function() {
|
||||
contactActionMenu.classList.add('hide');
|
||||
emptyList();
|
||||
listContainer.innerHTML = '';
|
||||
};
|
||||
|
||||
function render(self) {
|
||||
for (var i = 0, l = data.list.length; i < l; i++) {
|
||||
var button = document.createElement('button');
|
||||
navigator.mozL10n.setAttributes(button,
|
||||
data.list[i].labelL10n.id,
|
||||
data.list[i].labelL10n.args);
|
||||
|
||||
// Set callback function on each button element.
|
||||
var callback = data.list[i].callback;
|
||||
if (callback) {
|
||||
button.addEventListener('click', callback, false);
|
||||
}
|
||||
|
||||
listContainer.appendChild(button);
|
||||
}
|
||||
|
||||
btnCancel = document.createElement('button');
|
||||
btnCancel.setAttribute('data-l10n-id', 'cancel');
|
||||
|
||||
btnCancel.addEventListener('click', function() {
|
||||
self.hide();
|
||||
});
|
||||
|
||||
var lastButtonWrapper = document.createElement('span');
|
||||
lastButtonWrapper.className = 'last-button-container';
|
||||
listContainer.appendChild(lastButtonWrapper);
|
||||
lastButtonWrapper.appendChild(btnCancel);
|
||||
}
|
||||
|
||||
function emptyList() {
|
||||
data.list = [];
|
||||
}
|
||||
|
||||
this.addToList = function (labelL10n, callback) {
|
||||
var self = this;
|
||||
data.list.push({
|
||||
labelL10n: labelL10n,
|
||||
callback: function() {
|
||||
callback();
|
||||
self.hide();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
init();
|
||||
}
|
||||
370
gaia/apps/communications/contacts/js/activities.js
Executable file
370
gaia/apps/communications/contacts/js/activities.js
Executable file
|
|
@ -0,0 +1,370 @@
|
|||
/* globals ConfirmDialog, Contacts, LazyLoader, utils, ActionMenu, HeaderUI,
|
||||
ContactToVcardBlob, VcardFilename, VcardActivityHandler, MainNavigation */
|
||||
/* exported ActivityHandler */
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Per RFC 6350, text/vcard is the canonical MIME media type for vCards, but
|
||||
* there are also deprecated types as well. Whenever we disambiguate what an
|
||||
* activity is requesting based on its MIME media type, we need to check if it
|
||||
* is any of these, and not just text/vcard.
|
||||
*/
|
||||
const VCARD_MIME_TYPES = [
|
||||
'text/vcard',
|
||||
'text/x-vcard',
|
||||
'text/directory'
|
||||
];
|
||||
|
||||
var ActivityHandler = {
|
||||
_currentActivity: null,
|
||||
|
||||
_launchedAsInlineActivity: (window.location.search == '?pick'),
|
||||
|
||||
mozContactParam: null,
|
||||
|
||||
_actionMenu: null,
|
||||
|
||||
get currentlyHandling() {
|
||||
return !!this._currentActivity;
|
||||
},
|
||||
|
||||
get activityName() {
|
||||
if (!this._currentActivity) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return this._currentActivity.source.name;
|
||||
},
|
||||
|
||||
get activityDataType() {
|
||||
if (!this._currentActivity) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return this._currentActivity.source.data.type;
|
||||
},
|
||||
|
||||
get activityData() {
|
||||
if (!this._currentActivity) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return this._currentActivity.source.data;
|
||||
},
|
||||
|
||||
get activityContactProperties() {
|
||||
if (!this._currentActivity) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return this._currentActivity.source.data.contactProperties;
|
||||
},
|
||||
|
||||
/* checks first if we are handling an activity, then if it is
|
||||
* of the same type of any of the items from the list provided.
|
||||
* @param list Array with types of activities to be checked
|
||||
*/
|
||||
currentActivityIs: function(list) {
|
||||
return this.currentlyHandling && list.indexOf(this.activityName) !== -1;
|
||||
},
|
||||
|
||||
/* checks first if we are handling an activity, then checks that
|
||||
* it is NOT of the same type of any of the items from the list provided.
|
||||
* @param list Array with types of activities to be checked
|
||||
*/
|
||||
currentActivityIsNot: function(list) {
|
||||
return this.currentlyHandling && list.indexOf(this.activityName) === -1;
|
||||
},
|
||||
|
||||
isCancelable: function() {
|
||||
return new Promise(resolve => {
|
||||
resolve(!!this.currentlyHandling);
|
||||
});
|
||||
},
|
||||
|
||||
launch_activity: function ah_launch(activity, action) {
|
||||
if (this._launchedAsInlineActivity) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._currentActivity = activity;
|
||||
this.isCancelable().then(isCancelable => {
|
||||
HeaderUI.updateHeader(isCancelable);
|
||||
});
|
||||
|
||||
var hash = action;
|
||||
var param, params = [];
|
||||
if (activity.source &&
|
||||
activity.source.data &&
|
||||
activity.source.data.params) {
|
||||
var originalParams = activity.source.data.params;
|
||||
for (var i in originalParams) {
|
||||
param = originalParams[i];
|
||||
params.push(i + '=' + param);
|
||||
}
|
||||
hash += '?' + params.join('&');
|
||||
}
|
||||
document.location.hash = hash;
|
||||
},
|
||||
|
||||
handle: function ah_handle(activity) {
|
||||
const VCARD_DEPS = '/contacts/js/activities_vcard.js';
|
||||
switch (activity.source.name) {
|
||||
case 'new':
|
||||
this.launch_activity(activity, 'view-contact-form');
|
||||
break;
|
||||
case 'import':
|
||||
case 'open':
|
||||
LazyLoader.load(VCARD_DEPS, () => {
|
||||
VcardActivityHandler.handle(activity, this);
|
||||
});
|
||||
break;
|
||||
case 'update':
|
||||
this.launch_activity(activity, 'add-parameters');
|
||||
break;
|
||||
case 'pick':
|
||||
if (!this._launchedAsInlineActivity) {
|
||||
return;
|
||||
}
|
||||
this._currentActivity = activity;
|
||||
this.isCancelable().then(isCancelable => {
|
||||
HeaderUI.updateHeader(isCancelable);
|
||||
});
|
||||
MainNavigation.home();
|
||||
break;
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
importContactsFromFile: function ah_importContactFromVcard(activity) {
|
||||
var self = this;
|
||||
if (activity.source &&
|
||||
activity.source.data &&
|
||||
activity.source.data.blob) {
|
||||
LazyLoader.load([
|
||||
document.querySelector('#loading-overlay'),
|
||||
'/shared/js/contacts/import/utilities/import_from_vcard.js',
|
||||
'/shared/js/contacts/import/utilities/overlay.js'
|
||||
], function loaded() {
|
||||
Contacts.loadFacebook(function() {
|
||||
utils.importFromVcard(activity.source.data.blob,
|
||||
function imported(numberOfContacts, id) {
|
||||
if (numberOfContacts === 1) {
|
||||
activity.source.data.params = {id: id};
|
||||
self.launch_activity(activity, 'view-contact-details');
|
||||
} else {
|
||||
self.launch_activity(activity, 'view-contact-list');
|
||||
}
|
||||
}
|
||||
);
|
||||
});
|
||||
});
|
||||
} else {
|
||||
this._currentActivity.postError('wrong parameters');
|
||||
this._currentActivity = null;
|
||||
}
|
||||
},
|
||||
|
||||
dataPickHandler: function ah_dataPickHandler(theContact) {
|
||||
var type, dataSet, noDataStr;
|
||||
var result = {};
|
||||
var self = this;
|
||||
|
||||
// Keeping compatibility with previous implementation. If
|
||||
// we want to get the full contact, just pass the parameter
|
||||
// 'fullContact' equal true.
|
||||
if (this.activityDataType === 'webcontacts/contact' &&
|
||||
this.activityData.fullContact === true) {
|
||||
result = utils.misc.toMozContact(theContact);
|
||||
this.postPickSuccess(result);
|
||||
return;
|
||||
}
|
||||
|
||||
// Was this a request for vCard export as a blob? Check all supported MIME
|
||||
// types.
|
||||
var isVcardDataType = VCARD_MIME_TYPES.some((mime) => {
|
||||
return this.activityDataType.indexOf(mime) !== -1;
|
||||
});
|
||||
|
||||
if (isVcardDataType) {
|
||||
// Normalize the type to text/vcard so other places that check MIME types
|
||||
// (ex: the Facebook guards) experience a consistent MIME type.
|
||||
this._currentActivity.source.data.type = 'text/vcard';
|
||||
LazyLoader.load([
|
||||
'/shared/js/text_normalizer.js',
|
||||
'/shared/js/contact2vcard.js',
|
||||
'/shared/js/setImmediate.js'
|
||||
], function lvcard() {
|
||||
ContactToVcardBlob([theContact], function blobReady(vcardBlob) {
|
||||
VcardFilename(theContact).then(filename => {
|
||||
self.postPickSuccess({
|
||||
name: filename,
|
||||
blob: vcardBlob
|
||||
});
|
||||
});
|
||||
}, {
|
||||
// Some MMS gateways prefer this MIME type for vcards
|
||||
type: 'text/x-vcard'
|
||||
});
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
switch (this.activityDataType) {
|
||||
case 'webcontacts/tel':
|
||||
type = 'contact';
|
||||
dataSet = theContact.tel;
|
||||
noDataStr = 'no_contact_phones';
|
||||
break;
|
||||
case 'webcontacts/contact':
|
||||
type = 'number';
|
||||
dataSet = theContact.tel;
|
||||
noDataStr = 'no_contact_phones';
|
||||
break;
|
||||
case 'webcontacts/email':
|
||||
type = 'email';
|
||||
dataSet = theContact.email;
|
||||
noDataStr = 'no_contact_email';
|
||||
break;
|
||||
case 'webcontacts/select':
|
||||
type = 'select';
|
||||
var data = [];
|
||||
if (this.activityContactProperties.indexOf('tel') !== -1) {
|
||||
if (theContact.tel && theContact.tel.length) {
|
||||
data = data.concat(theContact.tel);
|
||||
}
|
||||
}
|
||||
if (this.activityContactProperties.indexOf('email') !== -1) {
|
||||
if (theContact.email && theContact.email.length) {
|
||||
data = data.concat(theContact.email);
|
||||
}
|
||||
}
|
||||
|
||||
dataSet = data;
|
||||
noDataStr = 'no_contact_data_available';
|
||||
break;
|
||||
}
|
||||
var hasData = dataSet && dataSet.length;
|
||||
var numOfData = hasData ? dataSet.length : 0;
|
||||
|
||||
|
||||
result.name = theContact.name;
|
||||
switch (numOfData) {
|
||||
case 0:
|
||||
// If no required type of data
|
||||
var dismiss = {
|
||||
title: 'ok',
|
||||
callback: function() {
|
||||
ConfirmDialog.hide();
|
||||
}
|
||||
};
|
||||
ConfirmDialog.show(null, noDataStr, dismiss);
|
||||
break;
|
||||
case 1:
|
||||
// if one required type of data
|
||||
if (this.activityDataType == 'webcontacts/tel' ||
|
||||
this.activityDataType == 'webcontacts/select') {
|
||||
result = this.pickContactsResult(theContact);
|
||||
} else {
|
||||
result[type] = dataSet[0].value;
|
||||
}
|
||||
|
||||
this.postPickSuccess(result);
|
||||
break;
|
||||
default:
|
||||
// if more than one required type of data
|
||||
LazyLoader.load('/contacts/js/action_menu.js', function() {
|
||||
if (!self._actionMenu) {
|
||||
self._actionMenu = new ActionMenu();
|
||||
} else {
|
||||
// To be sure that the action menu is empty
|
||||
self._actionMenu.hide();
|
||||
}
|
||||
|
||||
var itemData;
|
||||
var capture = function(itemData) {
|
||||
return function() {
|
||||
if (self.activityDataType == 'webcontacts/tel' ||
|
||||
self.activityDataType == 'webcontacts/select') {
|
||||
result = self.pickContactsResult(theContact, itemData);
|
||||
} else {
|
||||
result[type] = itemData;
|
||||
}
|
||||
self._actionMenu.hide();
|
||||
self.postPickSuccess(result);
|
||||
};
|
||||
};
|
||||
for (var i = 0, l = dataSet.length; i < l; i++) {
|
||||
itemData = dataSet[i].value;
|
||||
var carrier = dataSet[i].carrier || '';
|
||||
self._actionMenu.addToList(
|
||||
{
|
||||
id: 'pick_destination',
|
||||
args: {destination: itemData, carrier: carrier}
|
||||
},
|
||||
capture(itemData)
|
||||
);
|
||||
}
|
||||
self._actionMenu.show();
|
||||
});
|
||||
} // switch
|
||||
},
|
||||
|
||||
pickContactsResult:
|
||||
function ah_pickContactsResult(theContact, itemData) {
|
||||
var pickResult = {};
|
||||
var contact = utils.misc.toMozContact(theContact);
|
||||
|
||||
if (this.activityDataType == 'webcontacts/tel') {
|
||||
pickResult = contact;
|
||||
|
||||
if (itemData) {
|
||||
pickResult.tel = this.filterDestinationForActivity(
|
||||
itemData, pickResult.tel);
|
||||
}
|
||||
} else if (this.activityDataType == 'webcontacts/select') {
|
||||
pickResult.contact = contact;
|
||||
|
||||
if (!itemData) {
|
||||
pickResult.select = pickResult.contact.tel;
|
||||
|
||||
if (!pickResult.select || !pickResult.select.length) {
|
||||
pickResult.select = pickResult.contact.email;
|
||||
}
|
||||
} else {
|
||||
pickResult.select = this.filterDestinationForActivity(
|
||||
itemData, pickResult.contact.tel);
|
||||
|
||||
if (!pickResult.select || !pickResult.select.length) {
|
||||
pickResult.select = this.filterDestinationForActivity(
|
||||
itemData, pickResult.contact.email);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return pickResult;
|
||||
},
|
||||
|
||||
filterDestinationForActivity:
|
||||
function ah_filterDestinationForActivity(itemData, dataSet) {
|
||||
return dataSet.filter(function isSamePhone(item) {
|
||||
return item.value == itemData;
|
||||
});
|
||||
},
|
||||
|
||||
postNewSuccess: function ah_postNewSuccess(contact) {
|
||||
this._currentActivity.postResult({ contact: contact });
|
||||
this._currentActivity = null;
|
||||
},
|
||||
|
||||
postPickSuccess: function ah_postPickSuccess(result) {
|
||||
this._currentActivity.postResult(result);
|
||||
this._currentActivity = null;
|
||||
},
|
||||
|
||||
postCancel: function ah_postCancel() {
|
||||
this._currentActivity.postError('canceled');
|
||||
this._currentActivity = null;
|
||||
}
|
||||
};
|
||||
66
gaia/apps/communications/contacts/js/activities_vcard.js
Executable file
66
gaia/apps/communications/contacts/js/activities_vcard.js
Executable file
|
|
@ -0,0 +1,66 @@
|
|||
'use strict';
|
||||
/* global LazyLoader, VCardReader, Contacts */
|
||||
/* exported VcardActivityHandler */
|
||||
|
||||
var VcardActivityHandler = (function() {
|
||||
var handle = function(activity, parentHandler) {
|
||||
const DEPENDENCIES = '/shared/js/contacts/import/utilities/vcard_reader.js';
|
||||
LazyLoader.load(DEPENDENCIES, function () {
|
||||
getvCardReader(activity.source.data.blob).then(readvCard, (err) => {
|
||||
console.error('Error while getting vCard reader:', err);
|
||||
Contacts.cancel();
|
||||
});
|
||||
});
|
||||
|
||||
function getvCardReader(blob) {
|
||||
return new Promise((resolve, reject) => {
|
||||
var fileReader = new FileReader();
|
||||
fileReader.readAsText(blob);
|
||||
fileReader.onloadend = function() {
|
||||
resolve(new VCardReader(fileReader.result));
|
||||
};
|
||||
fileReader.onerror = function() {
|
||||
console.error('The blob could not be read as a file.');
|
||||
reject(fileReader.error);
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function readvCard(vCardReader) {
|
||||
var cursor = vCardReader.getAll();
|
||||
cursor.onsuccess = function(event) {
|
||||
var contact = event.target.result;
|
||||
render([contact], activity, cursor);
|
||||
};
|
||||
}
|
||||
|
||||
function getFileName(path) {
|
||||
var barIndex = path.lastIndexOf('/');
|
||||
if (barIndex > -1) {
|
||||
path = path.substring(barIndex + 1);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
function render(contacts, activity, cursor) {
|
||||
parentHandler.launch_activity(activity, 'multiple-select-view');
|
||||
const DEPENDENCIES = [
|
||||
'/contacts/js/views/multiple_select.js'
|
||||
];
|
||||
LazyLoader.load(DEPENDENCIES, function() {
|
||||
var name;
|
||||
if (activity.source.data.filename) {
|
||||
name = getFileName(activity.source.data.filename);
|
||||
} else {
|
||||
name = activity.source.data.src;
|
||||
}
|
||||
Contacts.MultipleSelect.init();
|
||||
Contacts.MultipleSelect.render(contacts, cursor, name);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
handle: handle
|
||||
};
|
||||
})();
|
||||
90
gaia/apps/communications/contacts/js/bootstrap.js
vendored
Executable file
90
gaia/apps/communications/contacts/js/bootstrap.js
vendored
Executable file
|
|
@ -0,0 +1,90 @@
|
|||
/* global Cache */
|
||||
/* global LazyLoader */
|
||||
/* global utils */
|
||||
|
||||
|
||||
'use strict';
|
||||
|
||||
(function(exports) {
|
||||
|
||||
/** Script loader **/
|
||||
|
||||
function loadScripts() {
|
||||
var dependencies = [
|
||||
'/contacts/services/contacts.js',
|
||||
'/contacts/js/activities.js',
|
||||
'/shared/js/contacts/utilities/event_listeners.js',
|
||||
'/contacts/js/navigation.js',
|
||||
'/contacts/js/main_navigation.js',
|
||||
'/contacts/js/views/list.js',
|
||||
'/contacts/js/header_ui.js'
|
||||
];
|
||||
|
||||
// If the cache is enabled, we push lazy loading l10n to the extreme,
|
||||
// cause we will be applying the transalations manually from the cached
|
||||
// content.
|
||||
// Otherwise, we load the l10n scripts along with the rest of the JS
|
||||
// scripts. This will avoid the non localized text to appear in the screen.
|
||||
if (!Cache.active) {
|
||||
dependencies.push('/shared/js/l10n.js');
|
||||
}
|
||||
|
||||
LazyLoader.load(dependencies, () => {
|
||||
['/shared/js/async_storage.js',
|
||||
'/shared/js/contacts/import/utilities/config.js',
|
||||
'/contacts/js/utilities/extract_params.js',
|
||||
'/contacts/js/utilities/cookie.js',
|
||||
'/shared/js/contact_photo_helper.js'].forEach((src) => {
|
||||
var scriptNode = document.createElement('script');
|
||||
scriptNode.src = src;
|
||||
scriptNode.setAttribute('defer', true);
|
||||
document.head.appendChild(scriptNode);
|
||||
});
|
||||
return LazyLoader.load('/contacts/js/contacts.js');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Bootstrap process
|
||||
* -----------------
|
||||
* In order to provide an acceptable start up time, the contacts app
|
||||
* keeps a cached version of the list view HTML in localStorage. We
|
||||
* initially load only the scripts that are needed to recover the cached
|
||||
* HTML from localStorage and to apply it as part of the contacts list view.
|
||||
* Once we have done this and have shown the cached version of the list in
|
||||
* the screen, we load the rest of required JS files and continue the normal
|
||||
* start up process.
|
||||
*
|
||||
* For now, the cache is evicted in the following scenarios:
|
||||
* - oncontactchange event (addition, edition or deletion of contacts).
|
||||
* - ICE contacts enabled/disabled.
|
||||
* - Facebook import enabled/disabled/sync.
|
||||
* - Import from external source (Gmail, Hotmail, Sdcard...).
|
||||
* - Favorites added/removed.
|
||||
* - Change in the way we display contacts (order by last name).
|
||||
* - Locale change (from RTL to LTR and viceversa).
|
||||
*/
|
||||
|
||||
window.addEventListener('DOMContentLoaded', function ondomloaded() {
|
||||
utils.PerformanceHelper.domLoaded();
|
||||
window.removeEventListener('DOMContentLoaded', ondomloaded);
|
||||
|
||||
var firstPaintFired = false;
|
||||
|
||||
Cache.apply('firstChunk').then(() => {
|
||||
// Once the first chunk is applied correctly, display the
|
||||
// list panel and fire the visually complete event.
|
||||
document.getElementById('view-contacts-list').classList.add('current');
|
||||
utils.PerformanceHelper.visuallyComplete();
|
||||
firstPaintFired = true;
|
||||
});
|
||||
|
||||
window.onload = () => {
|
||||
if (!firstPaintFired) {
|
||||
utils.PerformanceHelper.visuallyComplete();
|
||||
}
|
||||
loadScripts();
|
||||
};
|
||||
});
|
||||
|
||||
})(window);
|
||||
454
gaia/apps/communications/contacts/js/cache.js
Executable file
454
gaia/apps/communications/contacts/js/cache.js
Executable file
|
|
@ -0,0 +1,454 @@
|
|||
'use strict';
|
||||
|
||||
(function() {
|
||||
// Ideally we should store this value in the configuration file.
|
||||
// However, that means that we need to load two more script files and
|
||||
// read directly from the config.json file or from the cookie storing
|
||||
// the configuration data. This steals us ~150ms of startup time, so
|
||||
// we chose to hard code this value instead.
|
||||
const CACHE_ENABLED = true;
|
||||
const FIRST_CHUNK = 'firstChunk';
|
||||
|
||||
const l10nStrings = {
|
||||
'title': {
|
||||
query: 'gaia-header h1#app-title[data-l10n-id="contacts"]',
|
||||
container: 'textContent'
|
||||
},
|
||||
'search': {
|
||||
query: 'input[data-l10n-id="search-contact"]',
|
||||
container: 'placeholder'
|
||||
}
|
||||
};
|
||||
|
||||
var _observers = {};
|
||||
|
||||
function addObserver(aMessage, aCallback) {
|
||||
if (typeof aCallback !== 'function') {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!_observers[aMessage]) {
|
||||
_observers[aMessage] = [];
|
||||
}
|
||||
_observers[aMessage].push(aCallback);
|
||||
}
|
||||
|
||||
function notifyObservers(aMessage, aData) {
|
||||
var observers = _observers[aMessage];
|
||||
if (!observers) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (var callback in observers) {
|
||||
if (observers[callback]) {
|
||||
observers[callback](aData);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// So far we only cache the first chunk of contacts, but we may want to
|
||||
// extend the cache to a bigger or even the whole list in the future.
|
||||
var _caches = new Map();
|
||||
_caches.set(FIRST_CHUNK, {
|
||||
containerId: 'groups-list',
|
||||
active: false
|
||||
});
|
||||
|
||||
var _cachedContacts;
|
||||
var _cachedFavorites;
|
||||
var _cachedHeaders;
|
||||
var _cacheEvictionTimer;
|
||||
|
||||
function setCache(aCache) {
|
||||
if (!CACHE_ENABLED || !aCache.id ||
|
||||
!aCache.content || !aCache.lastOrderString ||
|
||||
!_caches.has(aCache.id)) {
|
||||
return;
|
||||
}
|
||||
|
||||
var l10n = {};
|
||||
Object.keys(l10nStrings).forEach(key => {
|
||||
var string = l10nStrings[key];
|
||||
var selector = document.querySelector(string.query);
|
||||
if (!selector || !selector[string.container]) {
|
||||
return;
|
||||
}
|
||||
l10n[key] = selector[string.container];
|
||||
});
|
||||
|
||||
localStorage.setItem(aCache.id, JSON.stringify({
|
||||
content: aCache.content,
|
||||
languageDirection: navigator.mozL10n.language.direction,
|
||||
languageCode: navigator.mozL10n.language.code,
|
||||
lastOrderString: aCache.lastOrderString,
|
||||
updated: Date.now(),
|
||||
// Because we lazy load l10n.js quite late, we need to cache the
|
||||
// localized strings to avoid showing the unlocalized text during
|
||||
// the start up process.
|
||||
l10n: l10n
|
||||
}));
|
||||
}
|
||||
|
||||
function deleteCache(aId) {
|
||||
if (!CACHE_ENABLED) {
|
||||
return;
|
||||
}
|
||||
localStorage.removeItem(aId);
|
||||
}
|
||||
|
||||
function getCachedContacts(aNodeList) {
|
||||
if (!CACHE_ENABLED || !aNodeList) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!_cachedContacts) {
|
||||
_cachedContacts = new Map();
|
||||
}
|
||||
|
||||
if (!_cachedFavorites) {
|
||||
_cachedFavorites = new Map();
|
||||
}
|
||||
|
||||
for (var i = 0; i < aNodeList.length; i++) {
|
||||
var cacheEntry = aNodeList[i];
|
||||
if (cacheEntry.parentNode.id == 'contact-list-ice') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (cacheEntry.parentNode.id == 'contacts-list-favorites') {
|
||||
_cachedFavorites.set(cacheEntry.dataset.uuid,
|
||||
cacheEntry.innerHTML);
|
||||
continue;
|
||||
}
|
||||
|
||||
_cachedContacts.set(cacheEntry.dataset.uuid,
|
||||
cacheEntry.innerHTML);
|
||||
}
|
||||
}
|
||||
|
||||
function appendNodesToContainer(aContainer, aNodeList) {
|
||||
if (!CACHE_ENABLED || !aNodeList.length) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
return new Promise((resolve) => {
|
||||
if (!_cachedHeaders) {
|
||||
_cachedHeaders = {};
|
||||
}
|
||||
var resolved = false;
|
||||
var fragment = document.createDocumentFragment();
|
||||
aNodeList.forEach((node) => {
|
||||
if (!node.elementName) {
|
||||
return;
|
||||
}
|
||||
var child = document.createElement(node.elementName);
|
||||
node.attributes && node.attributes.forEach((attribute) => {
|
||||
if (!attribute.name || !attribute.value) {
|
||||
return;
|
||||
}
|
||||
child.setAttribute(attribute.name, attribute.value);
|
||||
});
|
||||
if (node.innerHTML) {
|
||||
child.innerHTML = node.innerHTML;
|
||||
}
|
||||
fragment.appendChild(child);
|
||||
|
||||
var headerName = child.id.split('section-group-')[1];
|
||||
_cachedHeaders[headerName] =
|
||||
fragment.querySelector('ol#contacts-list-' + headerName);
|
||||
|
||||
if (!resolved) {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
getCachedContacts(fragment.querySelectorAll('li[data-cache=true]'));
|
||||
aContainer.appendChild(fragment);
|
||||
});
|
||||
}
|
||||
|
||||
function removeCacheFromContainer(aContainer) {
|
||||
if (!CACHE_ENABLED || !_cachedContacts) {
|
||||
return;
|
||||
}
|
||||
for (var id of _cachedContacts.keys()) {
|
||||
var items = aContainer.querySelectorAll('li[data-uuid=\"' + id + '\"]');
|
||||
Array.prototype.forEach.call(items, (item) => {
|
||||
var ol = item.parentNode;
|
||||
ol.removeChild(item);
|
||||
if (ol.children.length < 1) {
|
||||
var header = _cachedHeaders[ol.dataset.group];
|
||||
if (header) {
|
||||
var groupTitle = header.parentNode.children[0];
|
||||
groupTitle.classList.add('hide');
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function undoCache(aCacheId) {
|
||||
if (!CACHE_ENABLED || !_caches.has(aCacheId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
var _cache = _caches.get(aCacheId);
|
||||
|
||||
if (!_cache.containerId) {
|
||||
return;
|
||||
}
|
||||
|
||||
var container = document.getElementById(_cache.containerId);
|
||||
if (!container) {
|
||||
console.warning('Could not remove cached content from ' +
|
||||
_cache.containerId);
|
||||
return;
|
||||
}
|
||||
|
||||
removeCacheFromContainer(container);
|
||||
}
|
||||
|
||||
var Cache = {
|
||||
get active() {
|
||||
return CACHE_ENABLED && _caches.get(FIRST_CHUNK).active;
|
||||
},
|
||||
|
||||
get enabled() {
|
||||
return CACHE_ENABLED;
|
||||
},
|
||||
|
||||
get contacts() {
|
||||
return (CACHE_ENABLED && _cachedContacts) ? _cachedContacts.keys()
|
||||
: null;
|
||||
},
|
||||
|
||||
get favorites() {
|
||||
return (CACHE_ENABLED && _cachedFavorites) ? _cachedFavorites.keys()
|
||||
: null;
|
||||
},
|
||||
|
||||
get length() {
|
||||
return (CACHE_ENABLED && _cachedContacts) ?
|
||||
_cachedContacts.size + _cachedFavorites.size : 0;
|
||||
},
|
||||
|
||||
get headers() {
|
||||
return (CACHE_ENABLED && _cachedHeaders) ? _cachedHeaders
|
||||
: {};
|
||||
},
|
||||
|
||||
// We need to know the order string of the last contact in the cache
|
||||
// so we can insert externaly added contacts in the appropriate order.
|
||||
get lastOrderString() {
|
||||
return (CACHE_ENABLED && _caches.get(FIRST_CHUNK).lastOrderString);
|
||||
},
|
||||
|
||||
get updated() {
|
||||
return (CACHE_ENABLED && _caches.get(FIRST_CHUNK).updated);
|
||||
},
|
||||
|
||||
// For testing purposes only.
|
||||
get _rawContent() {
|
||||
return _caches.get(FIRST_CHUNK).content;
|
||||
},
|
||||
|
||||
set firstChunk(aFirstChunk) {
|
||||
if (!CACHE_ENABLED || !aFirstChunk ||
|
||||
!aFirstChunk.cache || !aFirstChunk.lastOrderString) {
|
||||
return;
|
||||
}
|
||||
setCache({
|
||||
id: FIRST_CHUNK,
|
||||
content: aFirstChunk.cache,
|
||||
lastOrderString: aFirstChunk.lastOrderString
|
||||
});
|
||||
},
|
||||
|
||||
set oneviction(aCallback) {
|
||||
if (!CACHE_ENABLED) {
|
||||
return;
|
||||
}
|
||||
addObserver('oneviction', aCallback);
|
||||
},
|
||||
|
||||
hasContact: function(aUuid) {
|
||||
if (!CACHE_ENABLED) {
|
||||
return;
|
||||
}
|
||||
return _cachedContacts && _cachedContacts.has(aUuid);
|
||||
},
|
||||
|
||||
hasFavorite: function(aUuid) {
|
||||
if (!CACHE_ENABLED) {
|
||||
return;
|
||||
}
|
||||
return _cachedFavorites && _cachedFavorites.has(aUuid);
|
||||
},
|
||||
|
||||
getContact: function(aUuid) {
|
||||
if (!CACHE_ENABLED || !this.hasContact(aUuid)) {
|
||||
return;
|
||||
}
|
||||
// We should get each contact once while rendering the contacts list
|
||||
// to see if what we have in the cache is different to what we have in
|
||||
// the contacts source (most likely mozContacts). Removing the contact
|
||||
// entry from the map allow us to easily check if we have any contact in
|
||||
// the cache that was deleted from the original source and so it needs
|
||||
// to be removed from the view.
|
||||
var contact = _cachedContacts.get(aUuid);
|
||||
_cachedContacts.delete(aUuid);
|
||||
return contact;
|
||||
},
|
||||
|
||||
getFavorite: function(aUuid) {
|
||||
if (!CACHE_ENABLED || !this.hasFavorite(aUuid)) {
|
||||
return;
|
||||
}
|
||||
var contact = _cachedFavorites.get(aUuid);
|
||||
_cachedFavorites.delete(aUuid);
|
||||
return contact;
|
||||
},
|
||||
|
||||
removeContact: function(aUuid) {
|
||||
if (!CACHE_ENABLED ||
|
||||
!this.hasContact(aUuid) ||
|
||||
!this.hasFavorite(aUuid)) {
|
||||
return;
|
||||
}
|
||||
if (_cachedContacts.has(aUuid)) {
|
||||
_cachedContacts.delete(aUuid);
|
||||
}
|
||||
if (_cachedFavorites.has(aUuid)) {
|
||||
_cachedFavorites.delete(aUuid);
|
||||
}
|
||||
},
|
||||
|
||||
_doEvict: function(aUndo) {
|
||||
_cacheEvictionTimer = null;
|
||||
if (aUndo) {
|
||||
undoCache(FIRST_CHUNK);
|
||||
}
|
||||
deleteCache(FIRST_CHUNK);
|
||||
this.cleanup();
|
||||
notifyObservers('oneviction');
|
||||
},
|
||||
|
||||
evict: function(aUndo, aInstant) {
|
||||
if (!CACHE_ENABLED) {
|
||||
return;
|
||||
}
|
||||
|
||||
// There are cases where we need to evict the cache
|
||||
// inmediately, like in web activities, where we can be closed
|
||||
// before doing the eviction.
|
||||
if (aInstant) {
|
||||
this._doEvict(aUndo);
|
||||
return;
|
||||
}
|
||||
|
||||
// Evicting the cache means accessing localStorage.
|
||||
// Use the following logic to evict the cache in a moderate pattern.
|
||||
// 1. When a request to evict the cache is received, start a timer.
|
||||
// 2. If another request is received while the timer is
|
||||
// running, reset it.
|
||||
// 3. Once the timer fires, evict the cache.
|
||||
|
||||
if (_cacheEvictionTimer) {
|
||||
clearTimeout(_cacheEvictionTimer);
|
||||
}
|
||||
|
||||
_cacheEvictionTimer = setTimeout(() => {
|
||||
this._doEvict(aUndo);
|
||||
}, 1000);
|
||||
},
|
||||
|
||||
maybeEvict: function() {
|
||||
if (!CACHE_ENABLED || !this.active) {
|
||||
return;
|
||||
}
|
||||
if ((_caches.get(FIRST_CHUNK).languageDirection !=
|
||||
navigator.mozL10n.language.direction) ||
|
||||
(_caches.get(FIRST_CHUNK).languageCode !=
|
||||
navigator.mozL10n.language.code)) {
|
||||
// If the language direction or code changed, we need to evict and also
|
||||
// undo the applied cache.
|
||||
this.evict(true /* remove applied cache from DOM */);
|
||||
}
|
||||
},
|
||||
|
||||
cleanup: function() {
|
||||
if (!CACHE_ENABLED) {
|
||||
return;
|
||||
}
|
||||
_caches.get(FIRST_CHUNK).active = false;
|
||||
_caches.get(FIRST_CHUNK).content = null;
|
||||
_cachedContacts = null;
|
||||
_cachedFavorites = null;
|
||||
_cachedHeaders = null;
|
||||
},
|
||||
|
||||
apply: function(aCacheId) {
|
||||
|
||||
if (!CACHE_ENABLED || !_caches.has(aCacheId)) {
|
||||
return Promise.reject();
|
||||
}
|
||||
|
||||
var _cache = _caches.get(aCacheId);
|
||||
|
||||
var cache = localStorage.getItem(aCacheId);
|
||||
if (!cache) {
|
||||
return Promise.reject();
|
||||
}
|
||||
|
||||
try {
|
||||
cache = JSON.parse(cache);
|
||||
_cache.content = cache.content;
|
||||
_cache.languageDirection = cache.languageDirection;
|
||||
_cache.languageCode = cache.languageCode;
|
||||
_cache.lastOrderString = cache.lastOrderString;
|
||||
_cache.updated = new Date(cache.updated);
|
||||
} catch(e) {
|
||||
console.error(e);
|
||||
return Promise.reject();
|
||||
}
|
||||
|
||||
if (!_cache.containerId) {
|
||||
return Promise.reject();
|
||||
}
|
||||
|
||||
if (cache.l10n) {
|
||||
Object.keys(cache.l10n).forEach(key => {
|
||||
if (!l10nStrings[key] || cache.l10n[key] === 'undefined') {
|
||||
return;
|
||||
}
|
||||
var string = l10nStrings[key];
|
||||
var selector = document.querySelector(string.query);
|
||||
if (!selector) {
|
||||
return;
|
||||
}
|
||||
selector[string.container] = cache.l10n[key];
|
||||
});
|
||||
}
|
||||
|
||||
if (cache.languageDirection) {
|
||||
var html = document.querySelector('html');
|
||||
html.setAttribute('dir', cache.languageDirection);
|
||||
}
|
||||
|
||||
var container = document.getElementById(_cache.containerId);
|
||||
if (!container) {
|
||||
console.warning('Could not apply cached content to ' +
|
||||
_cache.containerId);
|
||||
return Promise.reject();
|
||||
}
|
||||
|
||||
return appendNodesToContainer(container, _cache.content).then(() => {
|
||||
_cache.content = null;
|
||||
_cache.active = true;
|
||||
_caches.set(aCacheId, _cache);
|
||||
return Promise.resolve();
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
window.Cache = Cache;
|
||||
})();
|
||||
708
gaia/apps/communications/contacts/js/contacts.js
Executable file
708
gaia/apps/communications/contacts/js/contacts.js
Executable file
|
|
@ -0,0 +1,708 @@
|
|||
'use strict';
|
||||
/* global ActivityHandler */
|
||||
/* global Cache */
|
||||
/* global contacts */
|
||||
/* global DeferredActions */
|
||||
/* global fb */
|
||||
/* global fbLoader */
|
||||
/* global LazyLoader */
|
||||
/* global MainNavigation */
|
||||
/* global Loader */
|
||||
/* global TAG_OPTIONS */
|
||||
/* global utils */
|
||||
/* global HeaderUI */
|
||||
/* global Search */
|
||||
/* global ContactsService */
|
||||
|
||||
/* exported COMMS_APP_ORIGIN */
|
||||
/* exported SCALE_RATIO */
|
||||
|
||||
/* jshint nonew: false */
|
||||
|
||||
var COMMS_APP_ORIGIN = location.origin;
|
||||
|
||||
// Scale ratio for different devices
|
||||
var SCALE_RATIO = window.devicePixelRatio || 1;
|
||||
|
||||
var Contacts = (function() {
|
||||
|
||||
var goToForm = function edit() {
|
||||
var transition = ActivityHandler.currentlyHandling ? 'activity-popup'
|
||||
: 'fade-in';
|
||||
MainNavigation.go('view-contact-form', transition);
|
||||
};
|
||||
|
||||
var loadAsyncScriptsDeferred = {};
|
||||
loadAsyncScriptsDeferred.promise = new Promise((resolve) => {
|
||||
loadAsyncScriptsDeferred.resolve = resolve;
|
||||
});
|
||||
|
||||
var settingsReady = false;
|
||||
var detailsReady = false;
|
||||
var formReady = false;
|
||||
|
||||
var currentContact = {},
|
||||
currentFbContact;
|
||||
|
||||
var contactsList;
|
||||
var contactsDetails;
|
||||
var contactsForm;
|
||||
|
||||
// Shows the edit form for the current contact being in an update activity
|
||||
// It receives an array of two elements with the facebook data && values
|
||||
function showEditForm(facebookData, params) {
|
||||
contactsForm.render(currentContact, goToForm,
|
||||
facebookData, params.fromUpdateActivity);
|
||||
}
|
||||
|
||||
var checkUrl = function checkUrl() {
|
||||
var hasParams = window.location.hash.split('?');
|
||||
var hash = hasParams[0];
|
||||
var sectionId = hash.substr(1, hash.length) || '';
|
||||
var params = hasParams.length > 1 ?
|
||||
utils.extractParams(hasParams[1]) : -1;
|
||||
|
||||
switch (sectionId) {
|
||||
case 'view-contact-list':
|
||||
initContactsList();
|
||||
break;
|
||||
case 'view-contact-details':
|
||||
initContactsList();
|
||||
initDetails(function onInitDetails() {
|
||||
// At this point, a parameter is required
|
||||
if (params == -1) {
|
||||
console.error('Param missing');
|
||||
return;
|
||||
}
|
||||
|
||||
// If the parameter is an id, the corresponding contact is loaded
|
||||
// from the device.
|
||||
if ('id' in params) {
|
||||
var id = params.id;
|
||||
ContactsService.get(id, function onSuccess(savedContact) {
|
||||
currentContact = savedContact;
|
||||
|
||||
contactsDetails.render(currentContact);
|
||||
|
||||
MainNavigation.go(sectionId, 'right-left');
|
||||
}, function onError() {
|
||||
console.error('Error retrieving contact');
|
||||
});
|
||||
// If mozContactParam is true, we know there is a mozContact
|
||||
// attached to the activity, so we render it using contacts details'
|
||||
// read only mode. This is used when we receive an activity to open
|
||||
// a given contact with allowSave set to false.
|
||||
} else if (params.mozContactParam) {
|
||||
var contact = ActivityHandler.mozContactParam;
|
||||
contactsDetails.render(contact, null, true);
|
||||
MainNavigation.go(sectionId, 'activity-popup');
|
||||
}
|
||||
});
|
||||
break;
|
||||
case 'view-contact-form':
|
||||
initForm(function onInitForm() {
|
||||
if (params.mozContactParam) {
|
||||
contactsForm.render(ActivityHandler.mozContactParam, goToForm);
|
||||
ActivityHandler.mozContactParam = null;
|
||||
} else if (params == -1 || !(params.id)) {
|
||||
contactsForm.render(params, goToForm);
|
||||
} else {
|
||||
// Editing existing contact
|
||||
if (params.id) {
|
||||
var id = params.id;
|
||||
ContactsService.get(id, function onSuccess(savedContact) {
|
||||
currentContact = savedContact;
|
||||
// Check if we have extra parameters to render
|
||||
if ('extras' in params) {
|
||||
addExtrasToContact(params.extras);
|
||||
}
|
||||
if (fb.isFbContact(savedContact)) {
|
||||
var fbContact = new fb.Contact(savedContact);
|
||||
var req = fbContact.getDataAndValues();
|
||||
req.onsuccess = function() {
|
||||
showEditForm(req.result, params);
|
||||
};
|
||||
req.onerror = function() {
|
||||
console.error('Error retrieving FB information');
|
||||
showEditForm(null, params);
|
||||
};
|
||||
}
|
||||
else {
|
||||
showEditForm(null, params);
|
||||
}
|
||||
}, function onError() {
|
||||
console.error('Error retrieving contact to be edited');
|
||||
contactsForm.render(null, goToForm);
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
break;
|
||||
case 'add-parameters':
|
||||
initContactsList();
|
||||
initForm(function onInitForm() {
|
||||
MainNavigation.home();
|
||||
if (ActivityHandler.currentlyHandling) {
|
||||
selectList(params, true);
|
||||
}
|
||||
});
|
||||
break;
|
||||
case 'multiple-select-view':
|
||||
Loader.view('multiple_select', () => {
|
||||
MainNavigation.go('multiple-select-view', 'activity-popup');
|
||||
});
|
||||
break;
|
||||
case 'home':
|
||||
MainNavigation.home();
|
||||
break;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
var addExtrasToContact = function addExtrasToContact(extrasString) {
|
||||
try {
|
||||
var extras = JSON.parse(decodeURIComponent(extrasString));
|
||||
for (var type in extras) {
|
||||
var extra = extras[type];
|
||||
if (currentContact[type]) {
|
||||
if (Array.isArray(currentContact[type])) {
|
||||
var joinArray = currentContact[type].concat(extra);
|
||||
currentContact[type] = joinArray;
|
||||
} else {
|
||||
currentContact[type] = extra;
|
||||
}
|
||||
} else {
|
||||
currentContact[type] = Array.isArray(extra) ? extra : [extra];
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Extras malformed');
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
var onLocalized = function onLocalized() {
|
||||
init();
|
||||
|
||||
// We need to return the promise here for testing purposes
|
||||
return addAsyncScripts().then(() => {
|
||||
checkUrl();
|
||||
if (!ActivityHandler.currentlyHandling ||
|
||||
ActivityHandler.currentActivityIs(['pick', 'update'])) {
|
||||
initContactsList();
|
||||
} else {
|
||||
// Unregister here to avoid un-necessary list operations.
|
||||
ContactsService.removeListener('contactchange', oncontactchange);
|
||||
}
|
||||
|
||||
if (contactsList) {
|
||||
contactsList.initAlphaScroll();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
var loadDeferredActions = function loadDeferredActions() {
|
||||
window.removeEventListener('listRendered', loadDeferredActions);
|
||||
LazyLoader.load([
|
||||
'js/deferred_actions.js',
|
||||
'/contacts/js/fb_loader.js',
|
||||
'/contacts/js/fb/fb_init.js'
|
||||
], function() {
|
||||
DeferredActions.execute();
|
||||
});
|
||||
};
|
||||
|
||||
var init = function init() {
|
||||
window.addEventListener('hashchange', checkUrl);
|
||||
|
||||
window.addEventListener('listRendered', loadDeferredActions);
|
||||
|
||||
/* Tell the audio channel manager that we want to adjust the "notification"
|
||||
* channel when the user presses the volumeup/volumedown buttons. */
|
||||
if (navigator.mozAudioChannelManager) {
|
||||
navigator.mozAudioChannelManager.volumeControlChannel = 'notification';
|
||||
}
|
||||
};
|
||||
|
||||
var initContactsList = function initContactsList() {
|
||||
if (contactsList) {
|
||||
return;
|
||||
}
|
||||
contactsList = contactsList || contacts.List;
|
||||
var list = document.getElementById('groups-list');
|
||||
contactsList.init(list);
|
||||
getFirstContacts();
|
||||
contactsList.initAlphaScroll();
|
||||
contactsList.handleClick(contactListClickHandler);
|
||||
ActivityHandler.isCancelable().then(isCancelable => {
|
||||
HeaderUI.updateHeader(isCancelable);
|
||||
});
|
||||
};
|
||||
|
||||
var contactListClickHandler = function originalHandler(id) {
|
||||
initDetails(function onDetailsReady() {
|
||||
ContactsService.get(id, function findCb(contact, fbContact) {
|
||||
|
||||
currentContact = contact;
|
||||
currentFbContact = fbContact;
|
||||
|
||||
if (ActivityHandler.currentActivityIsNot(['import'])) {
|
||||
if (ActivityHandler.currentActivityIs(['pick'])) {
|
||||
ActivityHandler.dataPickHandler(currentFbContact || currentContact);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
contactsDetails.render(currentContact, currentFbContact);
|
||||
if (window.Search && Search.isInSearchMode()) {
|
||||
MainNavigation.go('view-contact-details', 'go-deeper-search');
|
||||
} else {
|
||||
MainNavigation.go('view-contact-details', 'go-deeper');
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
var updateContactDetail = function updateContactDetail(id) {
|
||||
ContactsService.get(id, function findCallback(contact) {
|
||||
currentContact = contact;
|
||||
contactsDetails.render(currentContact);
|
||||
});
|
||||
};
|
||||
|
||||
var selectList = function selectList(params, fromUpdateActivity) {
|
||||
HeaderUI.hideAddButton();
|
||||
contactsList.clearClickHandlers();
|
||||
contactsList.handleClick(function addToContactHandler(id) {
|
||||
var data = {};
|
||||
if (params.hasOwnProperty('tel')) {
|
||||
var phoneNumber = params.tel;
|
||||
data.tel = [{
|
||||
'value': phoneNumber,
|
||||
'carrier': null,
|
||||
'type': [TAG_OPTIONS['phone-type'][0].type]
|
||||
}];
|
||||
}
|
||||
if (params.hasOwnProperty('email')) {
|
||||
var email = params.email;
|
||||
data.email = [{
|
||||
'value': email,
|
||||
'type': [TAG_OPTIONS['email-type'][0].type]
|
||||
}];
|
||||
}
|
||||
var hash = '#view-contact-form?extras=' +
|
||||
encodeURIComponent(JSON.stringify(data)) + '&id=' + id;
|
||||
if (fromUpdateActivity) {
|
||||
hash += '&fromUpdateActivity=1';
|
||||
}
|
||||
window.location.hash = hash;
|
||||
});
|
||||
};
|
||||
|
||||
var handleBack = function handleBack(cb) {
|
||||
MainNavigation.back(cb);
|
||||
};
|
||||
|
||||
var handleCancel = function handleCancel() {
|
||||
//If in an activity, cancel it
|
||||
if (ActivityHandler.currentlyHandling) {
|
||||
ActivityHandler.postCancel();
|
||||
MainNavigation.home();
|
||||
} else {
|
||||
handleBack(function() {
|
||||
// TODO: remove all interaction with detail.js when it works
|
||||
// as an independent view
|
||||
if (MainNavigation.currentView() === 'view-contact-details') {
|
||||
contactsDetails.startNFC(currentContact);
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
var showAddContact = function showAddContact() {
|
||||
showForm();
|
||||
};
|
||||
|
||||
var loadFacebook = function loadFacebook(callback) {
|
||||
LazyLoader.load([
|
||||
'/contacts/js/fb_loader.js',
|
||||
'/contacts/js/fb/fb_init.js'
|
||||
], () => {
|
||||
if (!fbLoader.loaded) {
|
||||
fb.init(function onInitFb() {
|
||||
window.addEventListener('facebookLoaded', function onFbLoaded() {
|
||||
window.removeEventListener('facebookLoaded', onFbLoaded);
|
||||
callback();
|
||||
});
|
||||
fbLoader.load();
|
||||
});
|
||||
} else {
|
||||
callback();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
var initForm = function c_initForm(callback) {
|
||||
if (formReady) {
|
||||
callback();
|
||||
} else {
|
||||
initDetails(function onDetails() {
|
||||
LazyLoader.load([
|
||||
'/shared/js/contacts/import/utilities/misc.js',
|
||||
'/shared/js/contacts/utilities/image_thumbnail.js',
|
||||
'/contacts/js/match_service.js'],
|
||||
function() {
|
||||
Loader.view('Form', function viewLoaded() {
|
||||
formReady = true;
|
||||
contactsForm = contacts.Form;
|
||||
contactsForm.init(TAG_OPTIONS);
|
||||
callback();
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
var initSettings = function c_initSettings(callback) {
|
||||
if (settingsReady) {
|
||||
callback();
|
||||
} else {
|
||||
Loader.view('Settings', function viewLoaded() {
|
||||
LazyLoader.load(['/contacts/js/utilities/sim_dom_generator.js',
|
||||
'/contacts/js/utilities/normalizer.js',
|
||||
'/shared/js/contacts/import/utilities/misc.js',
|
||||
'/shared/js/mime_mapper.js',
|
||||
'/shared/js/contacts/import/utilities/vcard_parser.js',
|
||||
'/contacts/js/utilities/icc_handler.js',
|
||||
'/shared/js/contacts/import/utilities/sdcard.js',
|
||||
'/shared/elements/gaia_switch/script.js',
|
||||
'/shared/js/date_time_helper.js',
|
||||
'/shared/js/contacts/import/import_status_data.js'], function() {
|
||||
settingsReady = true;
|
||||
contacts.Settings.init();
|
||||
callback();
|
||||
});
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
var initDetails = function c_initDetails(callback) {
|
||||
if (detailsReady) {
|
||||
callback();
|
||||
} else {
|
||||
Loader.view('Details', function viewLoaded() {
|
||||
LazyLoader.load(
|
||||
['/shared/js/contacts/import/utilities/misc.js',
|
||||
'/dialer/js/telephony_helper.js',
|
||||
'/shared/js/contacts/sms_integration.js',
|
||||
'/shared/js/contacts/contacts_buttons.js',
|
||||
'/contacts/js/match_service.js',
|
||||
'/contacts/js/utilities/mozContact.js'],
|
||||
function() {
|
||||
detailsReady = true;
|
||||
contactsDetails = contacts.Details;
|
||||
contactsDetails.init();
|
||||
callback();
|
||||
});
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
var showForm = function c_showForm(edit, contact) {
|
||||
currentContact = contact || currentContact;
|
||||
initForm(function onInit() {
|
||||
doShowForm(edit);
|
||||
});
|
||||
};
|
||||
|
||||
var doShowForm = function c_doShowForm(edit) {
|
||||
var contact = edit ? currentContact : null;
|
||||
|
||||
if (contact && fb.isFbContact(contact)) {
|
||||
var fbContact = new fb.Contact(contact);
|
||||
var req = fbContact.getDataAndValues();
|
||||
|
||||
req.onsuccess = function() {
|
||||
contactsForm.render(contact, goToForm, req.result);
|
||||
};
|
||||
|
||||
req.onerror = function() {
|
||||
contactsForm.render(contact, goToForm);
|
||||
};
|
||||
}
|
||||
else {
|
||||
contactsForm.render(contact, goToForm);
|
||||
}
|
||||
};
|
||||
|
||||
var setCurrent = function c_setCurrent(contact) {
|
||||
currentContact = contact;
|
||||
|
||||
if (contacts.Details) {
|
||||
contacts.Details.setContact(contact);
|
||||
}
|
||||
};
|
||||
|
||||
var showOverlay = function c_showOverlay(messageId, progressClass, textId) {
|
||||
var out = utils.overlay.show(messageId, progressClass, textId);
|
||||
// When we are showing the overlay we are often performing other
|
||||
// significant work, such as importing. While performing this work
|
||||
// it would be nice to avoid the overhead of any accidental reflows
|
||||
// due to touching the list DOM. For example, importing incrementally
|
||||
// adds contacts to the list which triggers many reflows. Therefore,
|
||||
// minimize this impact by hiding the list while we are showing the
|
||||
// overlay.
|
||||
contacts.List.hide();
|
||||
return out;
|
||||
};
|
||||
|
||||
var hideOverlay = function c_hideOverlay() {
|
||||
Loader.utility('Overlay', function _loaded() {
|
||||
contacts.List.show();
|
||||
utils.overlay.hide();
|
||||
});
|
||||
};
|
||||
|
||||
var showSettings = function showSettings() {
|
||||
initSettings(function onSettingsReady() {
|
||||
// The number of FB Friends has to be recalculated
|
||||
contacts.Settings.refresh();
|
||||
MainNavigation.go('view-settings', 'fade-in');
|
||||
});
|
||||
};
|
||||
|
||||
var stopPropagation = function stopPropagation(evt) {
|
||||
evt.preventDefault();
|
||||
};
|
||||
|
||||
var enterSearchMode = function enterSearchMode(evt) {
|
||||
Loader.view('Search', function viewLoaded() {
|
||||
contacts.List.initSearch(function onInit() {
|
||||
Search.enterSearchMode(evt);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
var initEventListeners = function initEventListener() {
|
||||
// Definition of elements and handlers
|
||||
utils.listeners.add({
|
||||
'#add-contact-button': showAddContact,
|
||||
'#settings-button': showSettings, // Settings related
|
||||
'#search-start': [
|
||||
{
|
||||
event: 'click',
|
||||
handler: enterSearchMode
|
||||
}
|
||||
],
|
||||
// For screen reader users
|
||||
'#search-start > input': [
|
||||
{
|
||||
event: 'focus',
|
||||
handler: enterSearchMode
|
||||
}
|
||||
],
|
||||
'button[type="reset"]': stopPropagation
|
||||
});
|
||||
};
|
||||
|
||||
var getFirstContacts = function c_getFirstContacts() {
|
||||
var onerror = function() {
|
||||
console.error('Error getting first contacts');
|
||||
};
|
||||
contactsList = contactsList || contacts.List;
|
||||
|
||||
contactsList.getAllContacts(onerror);
|
||||
};
|
||||
|
||||
var addAsyncScripts = function addAsyncScripts() {
|
||||
|
||||
var lazyLoadFiles = [
|
||||
'/shared/js/contacts/utilities/templates.js',
|
||||
'/shared/js/contacts/contacts_shortcuts.js',
|
||||
'/contacts/js/contacts_tag.js',
|
||||
'/contacts/js/tag_options.js',
|
||||
'/contacts/js/loader.js',
|
||||
'/shared/js/text_normalizer.js',
|
||||
'/shared/js/contacts/import/utilities/status.js',
|
||||
'/shared/js/contacts/utilities/dom.js',
|
||||
'/shared/js/confirm.js',
|
||||
document.getElementById('confirmation-message')
|
||||
];
|
||||
|
||||
LazyLoader.load(lazyLoadFiles, function() {
|
||||
loadAsyncScriptsDeferred.resolve();
|
||||
});
|
||||
return loadAsyncScriptsDeferred.promise;
|
||||
};
|
||||
|
||||
var pendingChanges = {};
|
||||
|
||||
// This function is called when we finish a oncontactchange operation to
|
||||
// remove the op of the pending changes and check if we need to apply more
|
||||
// changes request over the same id.
|
||||
var checkPendingChanges = function checkPendingChanges(id) {
|
||||
var changes = pendingChanges[id];
|
||||
|
||||
if (!changes) {
|
||||
return;
|
||||
}
|
||||
|
||||
pendingChanges[id].shift();
|
||||
|
||||
if (pendingChanges[id].length >= 1) {
|
||||
performOnContactChange(pendingChanges[id][0]);
|
||||
}
|
||||
};
|
||||
|
||||
var oncontactchange = function oncontactchange(event) {
|
||||
if (typeof pendingChanges[event.contactID] !== 'undefined') {
|
||||
pendingChanges[event.contactID].push({
|
||||
contactID: event.contactID,
|
||||
reason: event.reason
|
||||
});
|
||||
} else {
|
||||
pendingChanges[event.contactID] = [{
|
||||
contactID: event.contactID,
|
||||
reason: event.reason
|
||||
}];
|
||||
}
|
||||
|
||||
// If there is already a pending request, don't do anything,
|
||||
// just wait to finish it in order
|
||||
if (pendingChanges[event.contactID].length > 1) {
|
||||
return;
|
||||
}
|
||||
|
||||
performOnContactChange(event);
|
||||
};
|
||||
|
||||
|
||||
ContactsService.addListener('contactchange', oncontactchange);
|
||||
|
||||
var performOnContactChange = function performOnContactChange(event) {
|
||||
// To be on the safe side for now we evict the cache everytime a
|
||||
// contact change event is received. In the future, we may want to check
|
||||
// if the change affects the cache or not, so we avoid evicting it when
|
||||
// is not needed.
|
||||
Cache.evict();
|
||||
initContactsList();
|
||||
var currView = MainNavigation.currentView();
|
||||
switch (event.reason) {
|
||||
case 'update':
|
||||
if (currView == 'view-contact-details' && currentContact != null &&
|
||||
currentContact.id == event.contactID) {
|
||||
ContactsService.get(event.contactID,
|
||||
function success(contact, enrichedContact) {
|
||||
currentContact = contact;
|
||||
if (contactsDetails) {
|
||||
contactsDetails.render(currentContact, enrichedContact);
|
||||
}
|
||||
if (contactsList) {
|
||||
contactsList.refresh(enrichedContact || currentContact,
|
||||
checkPendingChanges, event.reason);
|
||||
}
|
||||
notifyContactChanged(event.contactID, event.reason);
|
||||
});
|
||||
} else {
|
||||
refreshContactInList(event.contactID);
|
||||
}
|
||||
break;
|
||||
case 'create':
|
||||
refreshContactInList(event.contactID);
|
||||
break;
|
||||
case 'remove':
|
||||
if (currentContact != null && currentContact.id == event.contactID &&
|
||||
(currView == 'view-contact-details' ||
|
||||
currView == 'view-contact-form')) {
|
||||
MainNavigation.home();
|
||||
}
|
||||
contactsList.remove(event.contactID, event.reason);
|
||||
currentContact = {};
|
||||
checkPendingChanges(event.contactID);
|
||||
notifyContactChanged(event.contactID, event.reason);
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
// Refresh a contact in the list, and notifies of contact
|
||||
// changed to possible listeners.
|
||||
function refreshContactInList(id) {
|
||||
contactsList.refresh(id, function() {
|
||||
notifyContactChanged(id);
|
||||
checkPendingChanges(id);
|
||||
});
|
||||
}
|
||||
|
||||
// Send a custom event when we know that a contact changed and
|
||||
// the contact list was updated.
|
||||
// Used internally in places where the contact list is a reference
|
||||
function notifyContactChanged(id, reason) {
|
||||
document.dispatchEvent(new CustomEvent('contactChanged', {
|
||||
detail: {
|
||||
contactID: id,
|
||||
reason: reason
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
var close = function close() {
|
||||
window.removeEventListener('localized', initContacts);
|
||||
};
|
||||
|
||||
var initContacts = function initContacts(evt) {
|
||||
initEventListeners();
|
||||
HeaderUI.setNormalHeader();
|
||||
utils.PerformanceHelper.contentInteractive();
|
||||
utils.PerformanceHelper.chromeInteractive();
|
||||
window.setTimeout(Contacts && Contacts.onLocalized);
|
||||
if (window.navigator.mozSetMessageHandler && window.self == window.top) {
|
||||
LazyLoader.load(['/shared/js/contacts/import/utilities/misc.js',
|
||||
'/shared/js/contacts/import/utilities/vcard_reader.js',
|
||||
'/shared/js/contacts/import/utilities/vcard_parser.js'],
|
||||
function() {
|
||||
var actHandler = ActivityHandler.handle.bind(ActivityHandler);
|
||||
window.navigator.mozSetMessageHandler('activity', actHandler);
|
||||
});
|
||||
}
|
||||
|
||||
document.addEventListener('visibilitychange', function visibility(e) {
|
||||
if (document.hidden === false &&
|
||||
MainNavigation.currentView() === 'view-settings') {
|
||||
Loader.view('Settings', function viewLoaded() {
|
||||
contacts.Settings.updateTimestamps();
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
LazyLoader.load('/shared/js/l10n.js', () => {
|
||||
navigator.mozL10n.once(() => {
|
||||
initContacts();
|
||||
});
|
||||
navigator.mozL10n.ready(() => {
|
||||
Cache.maybeEvict();
|
||||
});
|
||||
});
|
||||
|
||||
window.addEventListener('DOMContentLoaded', function onLoad() {
|
||||
window.removeEventListener('DOMContentLoaded', onLoad);
|
||||
});
|
||||
|
||||
return {
|
||||
'goBack' : handleBack,
|
||||
'cancel': handleCancel,
|
||||
'showForm': showForm,
|
||||
'setCurrent': setCurrent,
|
||||
'onLocalized': onLocalized,
|
||||
'init': init,
|
||||
'showOverlay': showOverlay,
|
||||
'hideOverlay': hideOverlay,
|
||||
'showContactDetail': contactListClickHandler,
|
||||
'updateContactDetail': updateContactDetail,
|
||||
'loadFacebook': loadFacebook,
|
||||
'close': close,
|
||||
get asyncScriptsLoaded() {
|
||||
return loadAsyncScriptsDeferred.promise;
|
||||
}
|
||||
};
|
||||
})();
|
||||
108
gaia/apps/communications/contacts/js/contacts_bulk_delete.js
Executable file
108
gaia/apps/communications/contacts/js/contacts_bulk_delete.js
Executable file
|
|
@ -0,0 +1,108 @@
|
|||
/* globals Contacts, utils, contactsRemover, Promise,
|
||||
Search, ConfirmDialog, Loader */
|
||||
'use strict';
|
||||
|
||||
var contacts = window.contacts || {};
|
||||
|
||||
(function(exports) {
|
||||
|
||||
var cancelled = false;
|
||||
|
||||
/**
|
||||
* Loads the overlay class before showing
|
||||
*/
|
||||
function requireOverlay(callback) {
|
||||
Loader.utility('Overlay', callback);
|
||||
}
|
||||
|
||||
// Shows a dialog to confirm the bulk delete
|
||||
var showConfirm = function showConfirm(n) {
|
||||
return new Promise(function doShowConfirm(resolve, reject) {
|
||||
var cancelObject = {
|
||||
title: 'cancel',
|
||||
callback: function onCancel() {
|
||||
ConfirmDialog.hide();
|
||||
reject();
|
||||
}
|
||||
};
|
||||
|
||||
var removeObject = {
|
||||
title: 'delete',
|
||||
isDanger: true,
|
||||
callback: function onRemove() {
|
||||
ConfirmDialog.hide();
|
||||
resolve();
|
||||
}
|
||||
};
|
||||
|
||||
ConfirmDialog.show(null,
|
||||
{'id': 'ContactConfirmDel', 'args': {n: n}}, cancelObject,
|
||||
removeObject);
|
||||
});
|
||||
};
|
||||
|
||||
var doDelete = function doDelete(ids, done) {
|
||||
cancelled = false;
|
||||
var progress = utils.overlay.show('DeletingContacts', 'progressBar');
|
||||
progress.setTotal(ids.length);
|
||||
utils.overlay.showMenu();
|
||||
|
||||
utils.overlay.oncancel = function() {
|
||||
cancelled = true;
|
||||
contactsRemoverObj.finish();
|
||||
};
|
||||
|
||||
var contactsRemoverObj = new contactsRemover();
|
||||
contactsRemoverObj.init(ids, function onInitDone() {
|
||||
contactsRemoverObj.start();
|
||||
});
|
||||
|
||||
contactsRemoverObj.onDeleted = function onDeleted(currentId) {
|
||||
if (window.Search && Search.isInSearchMode()) {
|
||||
Search.invalidateCache();
|
||||
Search.removeContact(currentId);
|
||||
}
|
||||
contacts.List.remove(currentId);
|
||||
progress.update();
|
||||
};
|
||||
|
||||
contactsRemoverObj.onError = function onError() {
|
||||
Contacts.hideOverlay();
|
||||
utils.status.show({
|
||||
id: 'deleteError-general'
|
||||
});
|
||||
contacts.Settings.refresh();
|
||||
};
|
||||
|
||||
contactsRemoverObj.onFinished = function onFinished() {
|
||||
Contacts.hideOverlay();
|
||||
utils.status.show({
|
||||
id: 'DeletedTxt',
|
||||
args: {n: contactsRemoverObj.getDeletedCount()}
|
||||
});
|
||||
contacts.Settings.refresh();
|
||||
|
||||
if (typeof done === 'function') {
|
||||
done();
|
||||
}
|
||||
};
|
||||
|
||||
contactsRemoverObj.onCancelled = contactsRemoverObj.onFinished;
|
||||
|
||||
};
|
||||
// Start the delete of the contacts
|
||||
var performDelete = function performDelete(promise, done) {
|
||||
var self = this;
|
||||
requireOverlay(function onOverlay() {
|
||||
promise.onsuccess = function onSuccess(ids) {
|
||||
showConfirm(ids.length).then(self.doDelete.bind(null, ids, done));
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
exports.BulkDelete = {
|
||||
'performDelete': performDelete,
|
||||
'doDelete': doDelete
|
||||
};
|
||||
|
||||
})(window);
|
||||
106
gaia/apps/communications/contacts/js/contacts_remover.js
Executable file
106
gaia/apps/communications/contacts/js/contacts_remover.js
Executable file
|
|
@ -0,0 +1,106 @@
|
|||
/* globals mozContact, ContactsService */
|
||||
'use strict';
|
||||
|
||||
/*
|
||||
* Contacts Remover delete the contacts present in phone.
|
||||
* - start: To initiate the deleting process.
|
||||
* - finish: To cancel the deleting process.
|
||||
* - onDeleted: A Contact has been deleted
|
||||
* - onFinished: All Selected contacts have been deleted;
|
||||
* - onError: Error while deleting contacts.
|
||||
*/
|
||||
|
||||
function contactsRemover() {
|
||||
var totalRemoved = 0;
|
||||
var totalSelected = 0;
|
||||
var cancelled = false;
|
||||
/*jshint validthis:true */
|
||||
var self = this;
|
||||
var ids;
|
||||
|
||||
this.init = function(cIds, cb) {
|
||||
if (cIds === null || cIds.length === 0) {
|
||||
return;
|
||||
}
|
||||
ids = cIds;
|
||||
|
||||
if (cb && typeof cb === 'function') { cb(); }
|
||||
};
|
||||
|
||||
this.start = function() {
|
||||
totalRemoved = 0;
|
||||
cancelled = false;
|
||||
totalSelected = ids.length;
|
||||
continueCb(ids);
|
||||
};
|
||||
|
||||
this.finish = function() {
|
||||
cancelled = true;
|
||||
};
|
||||
|
||||
this.getDeletedCount = function() {
|
||||
return totalRemoved;
|
||||
};
|
||||
|
||||
function continueCb(ids) {
|
||||
var currentId = ids.shift();
|
||||
if (!currentId || cancelled) {
|
||||
if (totalRemoved === totalSelected) {
|
||||
notifyFinished();
|
||||
}
|
||||
else {
|
||||
notifyCancelled();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
deleteContact(
|
||||
currentId,
|
||||
function(e) {
|
||||
if (e) {
|
||||
notifyError();
|
||||
return;
|
||||
}
|
||||
totalRemoved++;
|
||||
notifyDeleted(currentId);
|
||||
continueCb(ids);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
function notifyError() {
|
||||
if (typeof self.onError === 'function') {
|
||||
self.onError();
|
||||
}
|
||||
}
|
||||
|
||||
function notifyCancelled() {
|
||||
if (typeof self.onCancelled === 'function') {
|
||||
window.setTimeout(self.onCancelled, 100);
|
||||
}
|
||||
}
|
||||
|
||||
function notifyFinished() {
|
||||
if (typeof self.onFinished === 'function') {
|
||||
window.setTimeout(self.onFinished, 100);
|
||||
}
|
||||
}
|
||||
|
||||
function notifyDeleted(currentId) {
|
||||
if (typeof self.onDeleted === 'function') {
|
||||
self.onDeleted(currentId);
|
||||
}
|
||||
}
|
||||
|
||||
function deleteContact(currentID, callback) {
|
||||
var contact = new mozContact();
|
||||
contact.id = currentID;
|
||||
|
||||
ContactsService.remove(
|
||||
contact,
|
||||
callback
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
window.contactsRemover = contactsRemover;
|
||||
163
gaia/apps/communications/contacts/js/contacts_tag.js
Executable file
163
gaia/apps/communications/contacts/js/contacts_tag.js
Executable file
|
|
@ -0,0 +1,163 @@
|
|||
'use strict';
|
||||
/* global utils */
|
||||
/* exported ContactsTag */
|
||||
|
||||
var ContactsTag = (function() {
|
||||
var originalTag = null;
|
||||
var selectedTag = null;
|
||||
var customTag = null;
|
||||
|
||||
var setCustomTag = function setCustomTag(element) {
|
||||
customTag = element;
|
||||
};
|
||||
|
||||
var setCustomTagVisibility = function setCustomTagVisibility(value) {
|
||||
if (!customTag) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (value) {
|
||||
customTag.classList.remove('hide');
|
||||
}
|
||||
else {
|
||||
customTag.classList.add('hide');
|
||||
}
|
||||
};
|
||||
|
||||
var unMarkTag = function unMarkTag(tag) {
|
||||
if (tag) {
|
||||
tag.classList.remove('icon');
|
||||
tag.classList.remove('icon-selected');
|
||||
|
||||
tag.removeAttribute('aria-selected');
|
||||
}
|
||||
};
|
||||
|
||||
var markTag = function markTag(tag) {
|
||||
if (tag) {
|
||||
tag.classList.add('icon');
|
||||
tag.classList.add('icon-selected');
|
||||
|
||||
tag.setAttribute('aria-selected', true);
|
||||
}
|
||||
};
|
||||
|
||||
var touchCustomTag = function touchCustomTag(callback) {
|
||||
unMarkTag(selectedTag);
|
||||
|
||||
selectedTag = null;
|
||||
|
||||
if (callback !== undefined && typeof callback === 'function') {
|
||||
callback();
|
||||
}
|
||||
};
|
||||
|
||||
var fillTagOptions = function fillTagOptions(target, _originalTag, options) {
|
||||
utils.dom.removeChildNodes(target);
|
||||
originalTag = _originalTag;
|
||||
|
||||
var selectedLink;
|
||||
/* jshint loopfunc:true */
|
||||
for (var option in options) {
|
||||
var tagLink = document.createElement('button');
|
||||
tagLink.dataset.index = option;
|
||||
tagLink.setAttribute('data-l10n-id', options[option].type);
|
||||
tagLink.setAttribute('data-value', options[option].type);
|
||||
tagLink.setAttribute('role', 'option');
|
||||
tagLink.classList.add('tagItem');
|
||||
|
||||
tagLink.addEventListener('click', function(event) {
|
||||
var tag = event.target;
|
||||
selectTag(tag);
|
||||
event.preventDefault();
|
||||
});
|
||||
|
||||
if (originalTag.dataset.value == options[option].type) {
|
||||
selectedLink = tagLink;
|
||||
}
|
||||
|
||||
var tagItem = document.createElement('li');
|
||||
tagItem.setAttribute('role', 'presentation');
|
||||
tagItem.appendChild(tagLink);
|
||||
target.appendChild(tagItem);
|
||||
}
|
||||
|
||||
customTag.value = '';
|
||||
if (!selectedLink && originalTag.textContent) {
|
||||
customTag.value = originalTag.textContent;
|
||||
}
|
||||
selectTag(selectedLink);
|
||||
};
|
||||
|
||||
var selectTag = function selectTag(tag) {
|
||||
if (tag == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
//Clean any trace of the custom tag
|
||||
customTag.value = '';
|
||||
|
||||
unMarkTag(selectedTag);
|
||||
|
||||
markTag(tag);
|
||||
|
||||
selectedTag = tag;
|
||||
};
|
||||
|
||||
var clickDone = function clickDone(callback) {
|
||||
if (selectedTag) {
|
||||
originalTag.textContent = selectedTag.textContent;
|
||||
originalTag.dataset.l10nId = selectedTag.dataset.l10nId;
|
||||
originalTag.dataset.value = selectedTag.dataset.value;
|
||||
} else if (customTag.value.length > 0) {
|
||||
originalTag.textContent = customTag.value;
|
||||
originalTag.dataset.value = customTag.value;
|
||||
}
|
||||
originalTag = null;
|
||||
|
||||
if (callback !== undefined && typeof callback === 'function') {
|
||||
callback();
|
||||
}
|
||||
};
|
||||
|
||||
// Filter tags to be shown when selecting an item type (work, birthday, etc)
|
||||
// This is particularly useful for dates as we cannot have multiple instances
|
||||
// of them (only one birthday, only one anniversary)
|
||||
function filterTags(type, currentNode, tags) {
|
||||
var element = document.querySelector(
|
||||
'[data-template]' + '.' + type + '-' + 'template');
|
||||
if (!element || !element.dataset.exclusive) {
|
||||
return tags;
|
||||
}
|
||||
|
||||
// If the type is exclusive the tag options are filtered according to
|
||||
// the existing ones
|
||||
var newOptions = tags.slice(0);
|
||||
|
||||
var sameType = document.querySelectorAll('.' + type + '-template');
|
||||
if (sameType.length > 1) {
|
||||
/* jshint loopfunc:true */
|
||||
for (var j = 0; j < sameType.length; j++) {
|
||||
var itemSame = sameType.item(j);
|
||||
var tagNode = itemSame.querySelector('[data-field="type"]');
|
||||
if (tagNode !== currentNode &&
|
||||
!itemSame.classList.contains('facebook')) {
|
||||
newOptions = newOptions.filter(function(ele) {
|
||||
return ele.type != tagNode.dataset.value;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return newOptions;
|
||||
}
|
||||
|
||||
return {
|
||||
'setCustomTag': setCustomTag,
|
||||
'touchCustomTag': touchCustomTag,
|
||||
'fillTagOptions': fillTagOptions,
|
||||
'clickDone': clickDone,
|
||||
'setCustomTagVisibility': setCustomTagVisibility,
|
||||
'filterTags': filterTags
|
||||
};
|
||||
})();
|
||||
119
gaia/apps/communications/contacts/js/deferred_actions.js
Executable file
119
gaia/apps/communications/contacts/js/deferred_actions.js
Executable file
|
|
@ -0,0 +1,119 @@
|
|||
'use strict';
|
||||
|
||||
/* global fb */
|
||||
/* global fbLoader */
|
||||
/* global ImportStatusData */
|
||||
/* global LazyLoader */
|
||||
/* global Migrator */
|
||||
/* global utils */
|
||||
|
||||
/* exported DeferredActions */
|
||||
|
||||
// Methods not related with the list rendering that must be executed after
|
||||
// render to not damage performance.
|
||||
var DeferredActions = (function() {
|
||||
var config;
|
||||
|
||||
var TOTAL_RETRIES = 4;
|
||||
|
||||
var execute = function execute() {
|
||||
config = utils.cookie.load();
|
||||
|
||||
if (!fbLoader.loaded) {
|
||||
window.addEventListener('facebookLoaded', doExecute);
|
||||
return;
|
||||
}
|
||||
doExecute();
|
||||
};
|
||||
|
||||
var doExecute = function doExecute() {
|
||||
window.removeEventListener('facebookLoaded', doExecute);
|
||||
|
||||
checkFacebookSynchronization(config);
|
||||
checkVersionMigration(config);
|
||||
checkFacebookSanity(config);
|
||||
};
|
||||
|
||||
// If FB Cleaning data was ongoing we finish it
|
||||
// This avoids keeping the contacts database inconsistent. See bug 1073684
|
||||
function checkFacebookSanity(config) {
|
||||
if (!config || !config.fbCleaningInProgress ||
|
||||
config.fbCleaningInProgress > TOTAL_RETRIES) {
|
||||
return;
|
||||
}
|
||||
|
||||
var req = fb.utils.clearFbData();
|
||||
req.onsuccess = function() {
|
||||
var cleaner = req.result;
|
||||
|
||||
cleaner.onsuccess = function() {
|
||||
console.log('Finished clean Fb data');
|
||||
fb.markFbCleaningInProgress(0);
|
||||
};
|
||||
cleaner.onerror = function() {
|
||||
console.error('FB Cleaner reported an error: ',
|
||||
req.error && req.error.name);
|
||||
fb.markFbCleaningInProgress(++config.fbCleaningInProgress);
|
||||
};
|
||||
};
|
||||
|
||||
req.onerror = function() {
|
||||
console.error('Unable to start cleaning', req.error && req.error.name);
|
||||
fb.markFbCleaningInProgress(++config.fbCleaningInProgress);
|
||||
};
|
||||
}
|
||||
|
||||
function checkFacebookSynchronization(config) {
|
||||
// Checks if we should set a fb sync alarm when fb sync has been done in ftu
|
||||
if (config && config.fbScheduleDone) {
|
||||
return;
|
||||
}
|
||||
|
||||
LazyLoader.load([
|
||||
'/facebook/js/fb_sync.js',
|
||||
'/shared/js/contacts/import/import_status_data.js'
|
||||
], performFbSync);
|
||||
}
|
||||
|
||||
function performFbSync() {
|
||||
var fbutils = fb.utils;
|
||||
|
||||
function neverExecuteAgain() {
|
||||
ImportStatusData.remove(fbutils.SCHEDULE_SYNC_KEY);
|
||||
utils.cookie.update({fbScheduleDone: true});
|
||||
navigator.removeIdleObserver(idleObserver);
|
||||
idleObserver = null;
|
||||
}
|
||||
|
||||
var idleObserver = {
|
||||
time: 3,
|
||||
onidle: function onidle() {
|
||||
ImportStatusData.get(fbutils.SCHEDULE_SYNC_KEY).then(function(date) {
|
||||
if (date) {
|
||||
fbutils.setLastUpdate(date, function() {
|
||||
var req = fb.sync.scheduleNextSync();
|
||||
req.onsuccess = neverExecuteAgain;
|
||||
req.onerror = neverExecuteAgain;
|
||||
});
|
||||
} else {
|
||||
neverExecuteAgain();
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
navigator.addIdleObserver(idleObserver);
|
||||
}
|
||||
|
||||
function checkVersionMigration(config) {
|
||||
if (!config || !config.fbMigrated || !config.accessTokenMigrated) {
|
||||
LazyLoader.load('js/migrator.js', function() {
|
||||
Migrator.start(config);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
'execute': execute
|
||||
};
|
||||
})();
|
||||
200
gaia/apps/communications/contacts/js/export/bt.js
Executable file
200
gaia/apps/communications/contacts/js/export/bt.js
Executable file
|
|
@ -0,0 +1,200 @@
|
|||
/* global getStorageIfAvailable, getUnusedFilename, ContactToVcardBlob,
|
||||
MozActivity, utils */
|
||||
|
||||
/* exported ContactsBTExport */
|
||||
'use strict';
|
||||
|
||||
var ContactsBTExport = function ContactsBTExport() {
|
||||
var contacts;
|
||||
var progressStep;
|
||||
var cancelled = false;
|
||||
var _ = navigator.mozL10n.get;
|
||||
|
||||
var _setContactsToExport = function btex_setContactsToExport(cts) {
|
||||
contacts = cts;
|
||||
};
|
||||
|
||||
var _hasDeterminativeProgress = function btex_hasDeterminativeProgress() {
|
||||
return false;
|
||||
};
|
||||
|
||||
var _getExportTitle = function btex_getExportTitle() {
|
||||
return 'btExport-title';
|
||||
};
|
||||
|
||||
var _setProgressStep = function btex_setProgressStep(p) {
|
||||
progressStep = p;
|
||||
};
|
||||
|
||||
var _getGivenName = function _getGivenName(contact) {
|
||||
return (Array.isArray(contact.givenName) && contact.givenName[0] &&
|
||||
contact.givenName[0].trim());
|
||||
};
|
||||
var _getLastName = function _getLastName(contact) {
|
||||
return (Array.isArray(contact.familyName) && contact.familyName[0] &&
|
||||
contact.familyName[0].trim());
|
||||
};
|
||||
var _getFileName = function _getFileName() {
|
||||
var filename = [];
|
||||
if (contacts && contacts.length === 1) {
|
||||
var contact = contacts[0],
|
||||
givenName = _getGivenName(contact),
|
||||
lastName = _getLastName(contact);
|
||||
if (givenName) {
|
||||
filename.push(givenName);
|
||||
}
|
||||
if (lastName) {
|
||||
filename.push(lastName);
|
||||
}
|
||||
if (filename.length === 0) {
|
||||
if (contact.org && contact.org.length > 0) {
|
||||
filename.push(contact.org[0]);
|
||||
} else if (contact.tel && contact.tel.length > 0) {
|
||||
filename.push(contact.tel[0].value);
|
||||
} else if (contact.email && contact.email.length > 0) {
|
||||
filename.push(contact.email[0].value);
|
||||
} else {
|
||||
filename.push(_('noName'));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
var today = new Date();
|
||||
filename.push(
|
||||
today.getFullYear(),
|
||||
today.getMonth() + 1,
|
||||
today.getDate(),
|
||||
contacts.length
|
||||
);
|
||||
}
|
||||
|
||||
return filename.join('_')
|
||||
.replace(/[^a-z0-9]/gi, '_')
|
||||
.toLowerCase() +
|
||||
'.vcf';
|
||||
};
|
||||
var _getStorage = function _getStorage(fileName, blob, callback) {
|
||||
if (typeof callback !== 'function') {
|
||||
throw new Error('getStorage requires a callback function');
|
||||
}
|
||||
getStorageIfAvailable('sdcard', blob.size,
|
||||
function onSuccess(storage) {
|
||||
// Get the final version of the proposed file name
|
||||
getUnusedFilename(storage, fileName, function onfilename(name) {
|
||||
callback(null, storage, name);
|
||||
});
|
||||
},
|
||||
callback //onerror
|
||||
);
|
||||
};
|
||||
var _saveToSdcard = function _saveToSdcard(storage, name, blob, callback) {
|
||||
if (typeof callback !== 'function') {
|
||||
throw new Error('saveToSDcard requires a callback function');
|
||||
}
|
||||
|
||||
var request = storage.addNamed(blob, name);
|
||||
request.onsuccess = function(evt) {
|
||||
callback(null, evt.target.result); // returns the full filepath
|
||||
};
|
||||
request.onerror = callback;
|
||||
};
|
||||
var _getFile = function _getFile(storage, filename, callback) {
|
||||
if (typeof callback !== 'function') {
|
||||
throw new Error('getFile requires a callback function');
|
||||
}
|
||||
var request = storage.get(filename);
|
||||
request.onsuccess = function() {
|
||||
callback(null, request.result); // returns a File object
|
||||
};
|
||||
request.onerror = callback;
|
||||
};
|
||||
|
||||
var cancelExport = function cancelExport() {
|
||||
cancelled = true;
|
||||
};
|
||||
|
||||
var _doExport = function btex_doExport(finishCallback) {
|
||||
if (typeof finishCallback !== 'function') {
|
||||
throw new Error('BT export requires a callback function');
|
||||
}
|
||||
|
||||
var checkError = function checkError(error) {
|
||||
if (error === null) {
|
||||
return false;
|
||||
}
|
||||
var reason = error;
|
||||
// numeric error means not enough space available
|
||||
if (parseInt(error, 10) >= 0) {
|
||||
reason = 'noSpace';
|
||||
}
|
||||
finishCallback({ 'reason': reason }, 0, false);
|
||||
return true;
|
||||
};
|
||||
|
||||
ContactToVcardBlob(contacts, function onContacts(blob) {
|
||||
if (cancelled) {
|
||||
finishCallback(null, 0, false);
|
||||
return;
|
||||
}
|
||||
_getStorage(_getFileName(), blob,
|
||||
function onStorage(error, storage, filename) {
|
||||
if (checkError(error)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (cancelled) {
|
||||
finishCallback(null, 0, false);
|
||||
return;
|
||||
}
|
||||
|
||||
utils.overlay.hideMenu();
|
||||
_saveToSdcard(storage, filename, blob,
|
||||
function onVcardSaved(error, filepath) {
|
||||
if (checkError(error)) {
|
||||
return;
|
||||
}
|
||||
|
||||
_getFile(storage, filepath, function onFileRetrieved(error, file) {
|
||||
if (checkError(error)) {
|
||||
return;
|
||||
}
|
||||
|
||||
var a = new MozActivity({
|
||||
name: 'share-via-bluetooth-only',
|
||||
data: {
|
||||
type: 'text/vcard',
|
||||
number: 1,
|
||||
blobs: [file],
|
||||
filenames: [filename],
|
||||
filepaths: [filepath]
|
||||
}
|
||||
});
|
||||
|
||||
a.onsuccess = function() {
|
||||
finishCallback(null, contacts.length);
|
||||
};
|
||||
|
||||
a.onerror = function(e) {
|
||||
if (a.error.name === 'NO_PROVIDER') {
|
||||
alert(_('share-noprovider'));
|
||||
} else {
|
||||
console.warn('share activity error:', a.error.name);
|
||||
}
|
||||
finishCallback({'reason': a.error}, 0, a.error.name);
|
||||
};
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
'setContactsToExport': _setContactsToExport,
|
||||
'shouldShowProgress': function btex_shouldShowProgress() { return true; },
|
||||
'hasDeterminativeProgress': _hasDeterminativeProgress,
|
||||
'getExportTitle': _getExportTitle,
|
||||
'setProgressStep': _setProgressStep,
|
||||
'doExport': _doExport,
|
||||
'cancelExport' : cancelExport,
|
||||
get name() { return 'BT';} // handling error messages on contacts_exporter
|
||||
};
|
||||
};
|
||||
197
gaia/apps/communications/contacts/js/export/contacts_exporter.js
Executable file
197
gaia/apps/communications/contacts/js/export/contacts_exporter.js
Executable file
|
|
@ -0,0 +1,197 @@
|
|||
/* global utils, ConfirmDialog, Contacts, ContactsService, Loader */
|
||||
'use strict';
|
||||
|
||||
//
|
||||
// Generic module to do contacts export.
|
||||
//
|
||||
// Once passed to this module an array of mozContacts objects
|
||||
// and setup the strategy (mechanism to export), will perform
|
||||
// the common steps taken place during the process of exporting
|
||||
// the information.
|
||||
|
||||
// Those steps are:
|
||||
|
||||
// - Preparation: (optional), may launch extra UI to setup some configuration
|
||||
// and transform the mozcontacts object to any extra format
|
||||
// - Export: Here is where the real import happens, could provide three known
|
||||
// scenarios:
|
||||
// - External handling of the export (web activity, ect.)
|
||||
// - Progress of the import:
|
||||
// - Defined progress activity
|
||||
// - Undefined progress
|
||||
// - Result of the export
|
||||
|
||||
window.ContactsExporter = function ContactsExporter(theStrategy) {
|
||||
|
||||
var contacts;
|
||||
var strategy = theStrategy;
|
||||
var hasProgress = false;
|
||||
var determinativeProgress = false;
|
||||
var progress;
|
||||
|
||||
// XXX: Bug 904623 since we cannot fetch a list of contacts by
|
||||
// contact id, we will need to fetch them all and filter
|
||||
var _init = function _init(theContacts, cb) {
|
||||
if (theContacts === null || theContacts.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
ContactsService.getAll(function(e, contactsFromAPI) {
|
||||
if (e) {
|
||||
cb();
|
||||
return;
|
||||
}
|
||||
contacts = [];
|
||||
contactsFromAPI.forEach(function onContact(ct) {
|
||||
if (theContacts.indexOf(ct.id) !== -1) {
|
||||
contacts.push(ct);
|
||||
}
|
||||
});
|
||||
if (cb) {
|
||||
cb(contacts);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
//
|
||||
// Checks if the export module has been properly configured
|
||||
// and start the process of exporting.
|
||||
//
|
||||
var _start = function _start() {
|
||||
if (!contacts || !strategy) {
|
||||
throw new Error('Not properly configured');
|
||||
}
|
||||
|
||||
strategy.setContactsToExport(contacts);
|
||||
|
||||
// Check if we have a 'Preparation step'
|
||||
if (typeof strategy.prepare === 'function') {
|
||||
strategy.prepare(_doExport);
|
||||
} else {
|
||||
_doExport();
|
||||
}
|
||||
};
|
||||
|
||||
var _doExport = function _doExport() {
|
||||
if (typeof strategy.shouldShowProgress === 'function' &&
|
||||
strategy.shouldShowProgress()) {
|
||||
hasProgress = true;
|
||||
_configureProgress();
|
||||
_displayProgress();
|
||||
}
|
||||
|
||||
strategy.doExport(_doHandleResult);
|
||||
};
|
||||
|
||||
/**
|
||||
* Callback invoked when the exporting process finished.
|
||||
*
|
||||
* @param {Object} error Not null in case an error happened
|
||||
* @param {Number} exported Number of contacts successfuly exported
|
||||
* @param {Boolean} isRecoverable In case of error, whether it is recoverable
|
||||
*/
|
||||
var _doHandleResult = function _doHandleResult(error, exported,
|
||||
isRecoverable) {
|
||||
if (hasProgress && !error) {
|
||||
utils.overlay.hide();
|
||||
}
|
||||
|
||||
if (error) {
|
||||
// If it was cancelled by the user we don't show the error screen.
|
||||
if (error.reason && error.reason.name === 'cancelled') {
|
||||
utils.overlay.hide();
|
||||
} else {
|
||||
var cancel = {
|
||||
title: 'cancel',
|
||||
callback: function() {
|
||||
utils.overlay.hide();
|
||||
ConfirmDialog.hide();
|
||||
_showStatus(exported, contacts.length);
|
||||
}
|
||||
};
|
||||
|
||||
var retry = {
|
||||
title: 'retry',
|
||||
isRecommend: true,
|
||||
callback: function() {
|
||||
utils.overlay.hide();
|
||||
ConfirmDialog.hide();
|
||||
// And now the action is reproduced one more time
|
||||
window.setTimeout(_doExport, 0);
|
||||
}
|
||||
};
|
||||
|
||||
if (isRecoverable === false) {
|
||||
retry = null;
|
||||
}
|
||||
|
||||
var errorString = 'exportError-' + strategy.name + '-';
|
||||
ConfirmDialog.show('exportErrorTitle',
|
||||
errorString + error.reason, cancel, retry);
|
||||
|
||||
Contacts.hideOverlay();
|
||||
|
||||
console.error('An error occurred during the export: ',
|
||||
error.reason.name || error.reason);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
_showStatus(exported, contacts.length);
|
||||
};
|
||||
|
||||
var _showStatus = function(exported, total) {
|
||||
// TODO: Better mechanism to show result
|
||||
var msgId = {
|
||||
id: 'contactsExported2',
|
||||
args: {
|
||||
'exported': exported,
|
||||
'total': total
|
||||
}
|
||||
};
|
||||
|
||||
utils.status.show(msgId);
|
||||
};
|
||||
|
||||
//
|
||||
// Based on the strategy configure the progress display to show a
|
||||
// determinative or indeterminate ui depending on the strategy
|
||||
//
|
||||
var _configureProgress = function _configureProgress() {
|
||||
determinativeProgress =
|
||||
strategy.hasDeterminativeProgress !== undefined &&
|
||||
strategy.hasDeterminativeProgress();
|
||||
};
|
||||
|
||||
//
|
||||
// Shows the progress dialog based on the
|
||||
//
|
||||
var _displayProgress = function _displayProgress() {
|
||||
var progressClass = determinativeProgress ? 'progressBar' : 'spinner';
|
||||
|
||||
Loader.utility('Overlay', function _loaded() {
|
||||
progress = utils.overlay.show(
|
||||
strategy.getExportTitle(),
|
||||
progressClass,
|
||||
null
|
||||
);
|
||||
utils.overlay.showMenu();
|
||||
utils.overlay.oncancel = function() {
|
||||
strategy.cancelExport();
|
||||
utils.overlay.hide();
|
||||
};
|
||||
|
||||
// Allow the strategy to setup the progress bar
|
||||
if (determinativeProgress) {
|
||||
progress.setTotal(contacts.length);
|
||||
strategy.setProgressStep(progress.update);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
'init': _init,
|
||||
'start': _start
|
||||
};
|
||||
|
||||
};
|
||||
168
gaia/apps/communications/contacts/js/export/sd.js
Executable file
168
gaia/apps/communications/contacts/js/export/sd.js
Executable file
|
|
@ -0,0 +1,168 @@
|
|||
/* globals _, ContactToVcard, getStorageIfAvailable, getUnusedFilename
|
||||
*/
|
||||
|
||||
/* exported ContactsSDExport */
|
||||
|
||||
'use strict';
|
||||
|
||||
var ContactsSDExport = function ContactsSDExport() {
|
||||
|
||||
var contacts;
|
||||
var progressStep;
|
||||
var cancelled = false;
|
||||
|
||||
var setContactsToExport = function setContactsToExport(cts) {
|
||||
contacts = cts;
|
||||
};
|
||||
|
||||
var hasDeterminativeProgress = function hasDeterminativeProgress() {
|
||||
return false;
|
||||
};
|
||||
|
||||
var setProgressStep = function setProgressStep(p) {
|
||||
progressStep = p;
|
||||
};
|
||||
|
||||
var getExportTitle = function getExportTitle() {
|
||||
return 'memoryCardExport-title';
|
||||
};
|
||||
|
||||
var hasGivenName = function hasGivenName(contact) {
|
||||
return (Array.isArray(contact.givenName) && contact.givenName[0] &&
|
||||
contact.givenName[0].trim());
|
||||
};
|
||||
|
||||
var hasFamilyName = function hasFamilyName(contact) {
|
||||
return (Array.isArray(contact.familyName) && contact.familyName[0] &&
|
||||
contact.familyName[0].trim());
|
||||
};
|
||||
|
||||
var getFileName = function getFileName() {
|
||||
var filename = [];
|
||||
if (contacts && contacts.length === 1) {
|
||||
var contact = contacts[0],
|
||||
hasName = false;
|
||||
if (hasGivenName(contact)) {
|
||||
filename.push(contact.givenName[0]);
|
||||
hasName = true;
|
||||
}
|
||||
if (hasFamilyName(contact)) {
|
||||
filename.push(contact.familyName[0]);
|
||||
hasName = true;
|
||||
}
|
||||
if (!hasName) {
|
||||
if (contact.org && contact.org.length > 0) {
|
||||
filename.push(contact.org[0]);
|
||||
} else if (contact.tel && contact.tel.length > 0) {
|
||||
filename.push(contact.tel[0].value);
|
||||
} else if (contact.email && contact.email.length > 0) {
|
||||
filename.push(contact.email[0].value);
|
||||
} else {
|
||||
filename.push(_('noName'));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
var today = new Date();
|
||||
filename.push(
|
||||
today.getFullYear(),
|
||||
today.getMonth() + 1,
|
||||
today.getDate(),
|
||||
contacts.length
|
||||
);
|
||||
}
|
||||
|
||||
return filename.join('_')
|
||||
.replace(/[^a-z0-9]/gi, '_')
|
||||
.toLowerCase() +
|
||||
'.vcf';
|
||||
};
|
||||
|
||||
var getStorage = function getStorage(fileName, blob, callback) {
|
||||
getStorageIfAvailable('sdcard', blob.size,
|
||||
function onSuccess(storage) {
|
||||
// Get the final version of the proposed file name
|
||||
getUnusedFilename(storage, fileName, function onFinalName(name) {
|
||||
callback(null, storage, name);
|
||||
});
|
||||
},
|
||||
function onError(type) {
|
||||
callback(type);
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
var cancelExport = function cancelExport() {
|
||||
cancelled = true;
|
||||
};
|
||||
|
||||
var doExport = function doExport(finishCallback) {
|
||||
/* XXX: We use a batch-conversion size of 2MiB. This ensures that the
|
||||
* process won't go out of memory even on low-end devices. This should be
|
||||
* revisited once append-to-file functionality becomes available. */
|
||||
var batchSize = 2 * 1024 * 1024;
|
||||
var count = 0;
|
||||
var pendingBatches = 0;
|
||||
var done = false;
|
||||
var cancelButton = document.querySelector('#cancel-overlay');
|
||||
|
||||
if (typeof finishCallback !== 'function') {
|
||||
throw new Error('SD export requires a callback function');
|
||||
}
|
||||
|
||||
ContactToVcard(contacts, function onContacts(vcards, nCards) {
|
||||
if (cancelled) {
|
||||
finishCallback(null, 0);
|
||||
return;
|
||||
}
|
||||
var blob = new Blob([vcards], {'type': 'text/vcard'});
|
||||
|
||||
pendingBatches++;
|
||||
|
||||
getStorage(getFileName(), blob,
|
||||
function onStorage(error, storage, finalName) {
|
||||
if (error !== null) {
|
||||
var reason = error;
|
||||
// numeric error means not enough space available
|
||||
if (parseInt(error, 10) >= 0) {
|
||||
reason = 'noSpace';
|
||||
}
|
||||
finishCallback({
|
||||
'reason': reason
|
||||
}, count, true);
|
||||
return;
|
||||
}
|
||||
if (cancelled) {
|
||||
finishCallback(null, 0);
|
||||
return;
|
||||
}
|
||||
cancelButton.disabled = true;
|
||||
var request = storage.addNamed(blob, finalName);
|
||||
request.onsuccess = function onSuccess() {
|
||||
count += nCards;
|
||||
pendingBatches--;
|
||||
|
||||
if (done && (pendingBatches === 0)) {
|
||||
finishCallback(null, count, false);
|
||||
}
|
||||
};
|
||||
request.onerror = function onError(e) {
|
||||
finishCallback({ 'reason': e }, count, true);
|
||||
};
|
||||
});
|
||||
}, function finish() {
|
||||
done = true;
|
||||
}, batchSize);
|
||||
};
|
||||
|
||||
return {
|
||||
'setContactsToExport': setContactsToExport,
|
||||
'shouldShowProgress': function shouldShowProgress() { return true; },
|
||||
'hasDeterminativeProgress': hasDeterminativeProgress,
|
||||
'getExportTitle': getExportTitle,
|
||||
'doExport': doExport,
|
||||
'setProgressStep': setProgressStep,
|
||||
'cancelExport': cancelExport,
|
||||
get name() { return 'SD'; } // handling error messages on contacts_exporter
|
||||
};
|
||||
|
||||
};
|
||||
195
gaia/apps/communications/contacts/js/export/sim.js
Executable file
195
gaia/apps/communications/contacts/js/export/sim.js
Executable file
|
|
@ -0,0 +1,195 @@
|
|||
/* exported ContactsSIMExport */
|
||||
/* global ContactsService */
|
||||
'use strict';
|
||||
|
||||
var ContactsSIMExport = function ContactsSIMExport(icc) {
|
||||
|
||||
var contacts;
|
||||
var progressStep;
|
||||
var exported;
|
||||
var notExported;
|
||||
var cancelled = false;
|
||||
|
||||
var ERRORS = {
|
||||
'NoFreeRecordFound': false,
|
||||
'CannotAccessPhoneBook': true
|
||||
};
|
||||
|
||||
var setContactsToExport = function setContactsToExport(cts) {
|
||||
contacts = cts;
|
||||
};
|
||||
|
||||
var hasDeterminativeProgress = function hasDeterminativeProgress() {
|
||||
return contacts.length > 1;
|
||||
};
|
||||
|
||||
var setProgressStep = function setProgressStep(p) {
|
||||
progressStep = p;
|
||||
};
|
||||
|
||||
var getExportTitle = function getExportTitle() {
|
||||
return 'simExport-title';
|
||||
};
|
||||
|
||||
var doExport = function doExport(finishCallback) {
|
||||
if (typeof finishCallback !== 'function') {
|
||||
throw new Error('SIM export requires a callback function');
|
||||
}
|
||||
|
||||
exported = [];
|
||||
notExported = [];
|
||||
|
||||
// We should control this state before doing the export
|
||||
// but a second check is healthy
|
||||
if (!icc) {
|
||||
finishCallback({
|
||||
'reason': 'Unavailable'
|
||||
}, 0, false);
|
||||
return;
|
||||
}
|
||||
|
||||
_doExport(0, finishCallback);
|
||||
};
|
||||
|
||||
// Returns the iccContactId to be used for exporting this contact
|
||||
// undefined if not iccContactId is found
|
||||
// url content is urn:uuid:<iccid>-icccontactid
|
||||
var _getIccContactId = function _getIccContactId(theContact) {
|
||||
var out;
|
||||
var contactUrl = theContact.url;
|
||||
if (!Array.isArray(contactUrl)) {
|
||||
return out;
|
||||
}
|
||||
|
||||
for (var j = 0; j < contactUrl.length; j++) {
|
||||
var aUrl = contactUrl[j];
|
||||
if (aUrl.type.indexOf('source') !== -1 &&
|
||||
aUrl.type.indexOf('sim') !== -1) {
|
||||
var value = aUrl.value.split(':')[2];
|
||||
var iccInfo = value.split('-');
|
||||
if (iccInfo[0] === _getIccId()) {
|
||||
out = iccInfo[1];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
var _generateIccContactUrl = function _generateIccContactUrl(contactid,
|
||||
iccId) {
|
||||
var urlValue = 'urn:' + 'uuid:' + (iccId || 'iccId') + '-' + contactid;
|
||||
return {
|
||||
type: ['source', 'sim'],
|
||||
value: urlValue
|
||||
};
|
||||
};
|
||||
|
||||
var _getIccId = function _getIccId() {
|
||||
return icc.iccInfo && icc.iccInfo.iccid;
|
||||
};
|
||||
|
||||
var _updateContactSimSource = function _updateContactSimSource(theContact,
|
||||
iccContact, cb, errorCb) {
|
||||
if (!iccContact) {
|
||||
window.console.warn('No Icc Contact provided');
|
||||
cb();
|
||||
return;
|
||||
}
|
||||
|
||||
theContact.url = theContact.url || [];
|
||||
theContact.url.push(_generateIccContactUrl(iccContact.id, _getIccId()));
|
||||
|
||||
ContactsService.save(
|
||||
theContact,
|
||||
function(e) {
|
||||
if (e) {
|
||||
errorCb(e);
|
||||
return;
|
||||
}
|
||||
cb();
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
var cancelExport = function cancelExport() {
|
||||
cancelled = true;
|
||||
};
|
||||
|
||||
var _doExport = function _doExport(step, finishCallback) {
|
||||
if (step == contacts.length || cancelled) {
|
||||
finishCallback(null, exported.length);
|
||||
return;
|
||||
}
|
||||
|
||||
var next = function next(success, contact) {
|
||||
var resultArray = success ? exported : notExported;
|
||||
resultArray.push(contact);
|
||||
if (progressStep) {
|
||||
progressStep();
|
||||
}
|
||||
step++;
|
||||
_doExport(step, finishCallback);
|
||||
};
|
||||
|
||||
var theContact = contacts[step];
|
||||
var originalContactId = theContact.id;
|
||||
var idToUpdate = _getIccContactId(theContact);
|
||||
if (!idToUpdate) {
|
||||
theContact.id = null;
|
||||
}
|
||||
else {
|
||||
theContact.id = idToUpdate;
|
||||
}
|
||||
|
||||
var request = icc.updateContact('adn', theContact);
|
||||
request.onsuccess = function onsuccess() {
|
||||
// Restoring the original contact.id to avoid duplicating it
|
||||
theContact.id = originalContactId;
|
||||
|
||||
if (idToUpdate) {
|
||||
next(true, theContact);
|
||||
return;
|
||||
}
|
||||
// Now it is needed to save the provided id in case we don't have one
|
||||
var iccContact = request.result;
|
||||
_updateContactSimSource(theContact, iccContact,
|
||||
function export_update_success() {
|
||||
next(true, theContact);
|
||||
}, function export_update_error(err) {
|
||||
window.console.error('Error while updating: ', err.name);
|
||||
next(true, theContact);
|
||||
});
|
||||
};
|
||||
|
||||
request.onerror = function onerror(e) {
|
||||
var error = e.target.error;
|
||||
window.console.error('Error while exporting: ', originalContactId,
|
||||
error.name);
|
||||
|
||||
var errorName = typeof ERRORS[error.name] === 'boolean' ?
|
||||
error.name : 'GenericError';
|
||||
|
||||
if (errorName !== 'GenericError') {
|
||||
finishCallback({
|
||||
'reason': errorName
|
||||
}, exported.length, ERRORS[error.name]);
|
||||
}
|
||||
else {
|
||||
next(false, theContact);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
return {
|
||||
'setContactsToExport': setContactsToExport,
|
||||
'shouldShowProgress': function() { return true; },
|
||||
'hasDeterminativeProgress': hasDeterminativeProgress,
|
||||
'getExportTitle': getExportTitle,
|
||||
'doExport': doExport,
|
||||
'setProgressStep': setProgressStep,
|
||||
'cancelExport' : cancelExport,
|
||||
get name() { return 'SIM';} // handling error messages on contacts_exporter
|
||||
};
|
||||
|
||||
};
|
||||
314
gaia/apps/communications/contacts/js/fb/datastore_migrator.js
Executable file
314
gaia/apps/communications/contacts/js/fb/datastore_migrator.js
Executable file
|
|
@ -0,0 +1,314 @@
|
|||
'use strict';
|
||||
|
||||
/* global LazyLoader, fb, contacts, utils */
|
||||
/* exported DatastoreMigration */
|
||||
|
||||
var DatastoreMigration = function(db) {
|
||||
var active = false;
|
||||
var ongoingMigration = false;
|
||||
var migrator;
|
||||
var idleObserver;
|
||||
var self = this;
|
||||
|
||||
// Only really needed for testing purposes
|
||||
Object.defineProperty(this, 'db', {
|
||||
set: function(val) {
|
||||
if (migrator) {
|
||||
migrator.db = val;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
var IdleObserver = function() {
|
||||
var self = this;
|
||||
|
||||
this._files = [
|
||||
'/shared/js/fb/fb_request.js',
|
||||
'/shared/js/contacts/import/facebook/fb_data.js'
|
||||
];
|
||||
|
||||
// 3 seconds idle time
|
||||
this.time = 3;
|
||||
|
||||
this.onidle = function() {
|
||||
LazyLoader.load(self._files, function() {
|
||||
onidle();
|
||||
});
|
||||
};
|
||||
|
||||
this.onactive = function() {
|
||||
LazyLoader.load(self._files, function() {
|
||||
onactive();
|
||||
});
|
||||
};
|
||||
};
|
||||
|
||||
function DatastoreMigrator(db) {
|
||||
var IDB_NAME = 'Gaia_Facebook_Friends';
|
||||
var objStoreName;
|
||||
|
||||
var SLICE_SIZE = 5;
|
||||
var initialized = false;
|
||||
|
||||
var database = db;
|
||||
|
||||
var self = this;
|
||||
|
||||
var existsDatabase = true;
|
||||
this.saveErrors = false;
|
||||
|
||||
// Only really needed for testing purposes
|
||||
Object.defineProperty(this, 'db', {
|
||||
set: function(val) {
|
||||
database = val;
|
||||
initialized = true;
|
||||
}
|
||||
});
|
||||
|
||||
function sliceEnd(hasMore) {
|
||||
if (!hasMore) {
|
||||
// No more records present
|
||||
window.console.info('FB Migration: All records have been migrated');
|
||||
// Close the database
|
||||
database.close();
|
||||
if (!self.saveErrors) {
|
||||
var req = window.indexedDB.deleteDatabase(IDB_NAME);
|
||||
req.onsuccess = function() {
|
||||
window.console.info('FB Migration: ',
|
||||
'Now the indexedDB has been deleted');
|
||||
};
|
||||
req.onerror = function() {
|
||||
window.console.error('FB Migration: ',
|
||||
'Error while deleting indexedDB: ',
|
||||
req.error.name);
|
||||
};
|
||||
}
|
||||
else {
|
||||
window.console.warn('There are save errors. ', 'DB not deleted');
|
||||
}
|
||||
}
|
||||
if (typeof self.onfinished === 'function') {
|
||||
self.onfinished(hasMore, self.saveErrors);
|
||||
}
|
||||
}
|
||||
|
||||
this.migrateSlice = function migrateSlice() {
|
||||
var toBeMigrated = [];
|
||||
var pendingRecords = true;
|
||||
var self = this;
|
||||
|
||||
openIndexedDB(function() {
|
||||
var transaction = database.transaction([objStoreName], 'readwrite');
|
||||
var objectStore = transaction.objectStore(objStoreName);
|
||||
|
||||
var req = objectStore.openCursor();
|
||||
|
||||
req.onsuccess = function(e) {
|
||||
var cursor = e.target.result;
|
||||
if (cursor && toBeMigrated.length < SLICE_SIZE) {
|
||||
var obj = cursor.value;
|
||||
toBeMigrated.push(obj);
|
||||
cursor.continue();
|
||||
}
|
||||
else {
|
||||
if (!cursor) {
|
||||
pendingRecords = false;
|
||||
}
|
||||
migrateRecords(toBeMigrated, function() {
|
||||
sliceEnd(pendingRecords);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
req.onerror = function() {
|
||||
window.console.error('FB Migration: ',
|
||||
'Error while requesting a cursor: ',
|
||||
req.error.name);
|
||||
if (typeof self.onerror === 'function') {
|
||||
self.onerror();
|
||||
}
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
this.reset = function() {
|
||||
existsDatabase = true;
|
||||
initialized = false;
|
||||
this.saveErrors = false;
|
||||
database = null;
|
||||
};
|
||||
|
||||
function migrateRecords(list, cb) {
|
||||
if (list.length === 0) {
|
||||
cb();
|
||||
return;
|
||||
}
|
||||
|
||||
var numResponses = 0;
|
||||
var migrateCb = function migratCb() {
|
||||
numResponses++;
|
||||
if (numResponses === list.length) {
|
||||
cb();
|
||||
}
|
||||
};
|
||||
for (var j = 0; j < list.length; j++) {
|
||||
migrateRecord(list[j], migrateCb);
|
||||
}
|
||||
}
|
||||
|
||||
function removeRecord(obj, cb) {
|
||||
// Now deleting from indexedDB
|
||||
var trans = database.transaction([objStoreName], 'readwrite');
|
||||
var objectStore = trans.objectStore(objStoreName);
|
||||
|
||||
var req = objectStore.delete(obj.uid);
|
||||
req.onsuccess = cb;
|
||||
req.onerror = function() {
|
||||
window.console.error('FB Migration: Error while deleting indexedDB: ',
|
||||
obj.uid, ': ', req.error.name);
|
||||
cb();
|
||||
};
|
||||
}
|
||||
|
||||
function migrateRecord(obj, cb) {
|
||||
var req = fb.contacts.save(obj);
|
||||
|
||||
req.onsuccess = function() {
|
||||
window.console.info('FB Migration: indexed DB Record migrated: ',
|
||||
obj.uid);
|
||||
contacts.List.refreshFb(obj.uid);
|
||||
removeRecord(obj, cb);
|
||||
};
|
||||
|
||||
req.onerror = function() {
|
||||
window.console.error('FB Migration: Error while saving to datastore: ',
|
||||
obj.uid, req.error.name);
|
||||
if (req.error.name === 'AlreadyExists') {
|
||||
// Then that record was already migrated and it is safe to delete it
|
||||
removeRecord(obj, cb);
|
||||
}
|
||||
else {
|
||||
self.saveErrors = true;
|
||||
cb();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function openIndexedDB(cb) {
|
||||
if (database) {
|
||||
cb();
|
||||
return;
|
||||
}
|
||||
|
||||
var req = window.indexedDB.open(IDB_NAME);
|
||||
|
||||
req.onupgradeneeded = function() {
|
||||
existsDatabase = false;
|
||||
};
|
||||
|
||||
req.onsuccess = function() {
|
||||
if (!existsDatabase) {
|
||||
// Delete it as indexedDB will have created it
|
||||
window.console.warn('FB Migration: The database does not exist');
|
||||
window.indexedDB.deleteDatabase(IDB_NAME);
|
||||
|
||||
if (typeof self.onfinished === 'function') {
|
||||
self.onfinished(false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
database = req.result;
|
||||
objStoreName = database.objectStoreNames[0];
|
||||
|
||||
cb();
|
||||
};
|
||||
|
||||
req.onerror = function() {
|
||||
window.console.error('Indexed DB cannot be opened: ', req.error.name);
|
||||
if (typeof self.onerror === 'function') {
|
||||
self.onerror();
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
var start = function start() {
|
||||
idleObserver = new IdleObserver();
|
||||
navigator.addIdleObserver(idleObserver);
|
||||
};
|
||||
|
||||
this.start = start;
|
||||
|
||||
var stop = function stop() {
|
||||
navigator.removeIdleObserver(idleObserver);
|
||||
if (migrator) {
|
||||
migrator.reset();
|
||||
}
|
||||
if (typeof self.onmigrationdone === 'function') {
|
||||
self.onmigrationdone();
|
||||
}
|
||||
};
|
||||
|
||||
this.stop = stop;
|
||||
|
||||
function onactive() {
|
||||
active = true;
|
||||
}
|
||||
|
||||
function sliceFinished(hasMore, saveErrors) {
|
||||
if (!hasMore && !saveErrors) {
|
||||
// And annotate in a cookie that migration was done
|
||||
utils.cookie.update({
|
||||
fbMigrated: true
|
||||
});
|
||||
stop();
|
||||
}
|
||||
else if (saveErrors && !hasMore) {
|
||||
// The process is finished for the moment though there are errors
|
||||
if (typeof self.onmigrationdone === 'function') {
|
||||
self.onmigrationdone(true);
|
||||
}
|
||||
ongoingMigration = false;
|
||||
}
|
||||
else {
|
||||
if (typeof self.onslicemigrated === 'function') {
|
||||
self.onslicemigrated();
|
||||
}
|
||||
if (!active) {
|
||||
ongoingMigration = true;
|
||||
// If still inactive next slice is migrated
|
||||
migrator.migrateSlice();
|
||||
}
|
||||
else {
|
||||
ongoingMigration = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var onidle = function onidle() {
|
||||
active = false;
|
||||
if (ongoingMigration) {
|
||||
return;
|
||||
}
|
||||
window.console.info('Idle event!!!. FB Migration about to start');
|
||||
ongoingMigration = true;
|
||||
if (!migrator) {
|
||||
migrator = new DatastoreMigrator(db);
|
||||
migrator.onfinished = sliceFinished;
|
||||
migrator.onerror = function() {
|
||||
ongoingMigration = false;
|
||||
migrator.reset();
|
||||
if (typeof self.onerror === 'function') {
|
||||
self.onerror({
|
||||
name: 'Migration Error'
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
migrator.saveErrors = false;
|
||||
migrator.migrateSlice();
|
||||
};
|
||||
|
||||
// Mainly needed for testing purposes
|
||||
this.onidle = onidle;
|
||||
};
|
||||
54
gaia/apps/communications/contacts/js/fb/fb_init.js
Executable file
54
gaia/apps/communications/contacts/js/fb/fb_init.js
Executable file
|
|
@ -0,0 +1,54 @@
|
|||
'use strict';
|
||||
|
||||
/* global utils */
|
||||
|
||||
var fb = window.fb || {};
|
||||
var config = window.config || {};
|
||||
|
||||
if (typeof fb.init === 'undefined') {
|
||||
(function() {
|
||||
var initialized = false;
|
||||
var initializing = false;
|
||||
var EV_FB_INIT = 'fb_init_initialized';
|
||||
|
||||
fb.isEnabled = false;
|
||||
|
||||
fb.init = function(callback) {
|
||||
if (initialized) {
|
||||
callback();
|
||||
return;
|
||||
}
|
||||
|
||||
if (initializing) {
|
||||
document.addEventListener(EV_FB_INIT, function handler(e) {
|
||||
initializing = false;
|
||||
document.removeEventListener(EV_FB_INIT, handler);
|
||||
callback();
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
initializing = true;
|
||||
utils.config.load('/contacts/config.json').then(
|
||||
function cLoaded(configData) {
|
||||
if (configData.facebookEnabled === true) {
|
||||
fb.isEnabled = true;
|
||||
}
|
||||
|
||||
fb.operationsTimeout = config.operationsTimeout =
|
||||
configData.operationsTimeout;
|
||||
fb.logLevel = configData.logLevel || 'none';
|
||||
fb.syncPeriod = configData.facebookSyncPeriod || 24;
|
||||
fb.testToken = configData.testToken;
|
||||
|
||||
initialized = true;
|
||||
|
||||
document.dispatchEvent(new CustomEvent(EV_FB_INIT));
|
||||
|
||||
callback();
|
||||
}, function loadError(err) {
|
||||
console.error('Error while loading config.json', err);
|
||||
});
|
||||
};
|
||||
})();
|
||||
}
|
||||
677
gaia/apps/communications/contacts/js/fb/fb_link.js
Executable file
677
gaia/apps/communications/contacts/js/fb/fb_link.js
Executable file
|
|
@ -0,0 +1,677 @@
|
|||
'use strict';
|
||||
|
||||
/* global Curtain, FacebookConnector, ImageLoader, Normalizer, utils,
|
||||
ImportStatusData, oauth2 */
|
||||
|
||||
var fb = window.fb || {};
|
||||
|
||||
if (!fb.link) {
|
||||
(function(document) {
|
||||
// parameter id for the linking contact
|
||||
var link = fb.link = {};
|
||||
var UI = link.ui = {};
|
||||
|
||||
link.CID_PARAM = 'contactid';
|
||||
|
||||
// Contact id that the user wants to be linked to
|
||||
var contactid;
|
||||
// The data of such a contact
|
||||
var cdata;
|
||||
|
||||
// Access token
|
||||
var access_token;
|
||||
|
||||
// Used to control the number of queries
|
||||
var numQueries = 0;
|
||||
|
||||
// The uid of the friend to be linked
|
||||
var friendUidToLink;
|
||||
|
||||
// Base query to search for contacts
|
||||
var SEARCH_QUERY = ['SELECT uid, name, email from user ',
|
||||
' WHERE uid IN (SELECT uid1 FROM friend WHERE uid2=me()) ',
|
||||
' AND (', null, ')', ' ORDER BY name'
|
||||
];
|
||||
|
||||
// Conditions
|
||||
var MAIL_COND, CELL_COND;
|
||||
/* jshint ignore:start */
|
||||
MAIL_COND = ['strpos(email, ' , "'", null, "'", ') >= 0'];
|
||||
CELL_COND = ['strpos(cell, ' , "'", null, "'", ') >= 0'];
|
||||
/* jshint ignore:end */
|
||||
|
||||
var ALL_QUERY = ['SELECT uid, name, last_name, first_name,',
|
||||
' middle_name, email from user ',
|
||||
' WHERE uid IN (SELECT uid1 FROM friend WHERE uid2=me()) ',
|
||||
' ORDER BY name'
|
||||
];
|
||||
|
||||
var COUNT_QUERY = 'SELECT uid FROM user WHERE uid IN ' +
|
||||
'(SELECT uid1 FROM friend WHERE uid2=me())';
|
||||
|
||||
var SEARCH_ACCENTS_FIELDS = {
|
||||
'last_name': 'familyName',
|
||||
'first_name': 'givenName',
|
||||
'middle_name': 'givenName'
|
||||
};
|
||||
|
||||
var friendsList;
|
||||
var viewButton, mainSection;
|
||||
|
||||
var currentRecommendation = null;
|
||||
var allFriends = null;
|
||||
// Enables cancelation
|
||||
var currentNetworkRequest = null;
|
||||
// State can be proposal or view All
|
||||
var state;
|
||||
var imgLoader;
|
||||
|
||||
// Only needed for testing purposes
|
||||
var completedCb;
|
||||
|
||||
function notifyParent(message) {
|
||||
parent.postMessage({
|
||||
type: message.type || '',
|
||||
data: message.data || ''
|
||||
}, fb.CONTACTS_APP_ORIGIN);
|
||||
}
|
||||
|
||||
// Builds the first query for finding a contact to be linked to
|
||||
function buildQuery(contact) {
|
||||
var filter = [];
|
||||
|
||||
if (contact.tel && contact.tel.length > 0) {
|
||||
contact.tel.forEach(function(tel) {
|
||||
CELL_COND[2] = tel.value.trim();
|
||||
filter.push(CELL_COND.join(''));
|
||||
filter.push(' OR ');
|
||||
});
|
||||
}
|
||||
|
||||
if (contact.email && contact.email.length > 0) {
|
||||
contact.email.forEach(function(email) {
|
||||
MAIL_COND[2] = email.value.trim();
|
||||
filter.push(MAIL_COND.join(''));
|
||||
filter.push(' OR ');
|
||||
});
|
||||
}
|
||||
|
||||
// Remove the last OR
|
||||
if (filter.length > 0) {
|
||||
filter[filter.length - 1] = null;
|
||||
}
|
||||
var filterStr = filter.join('');
|
||||
|
||||
var out;
|
||||
if (filterStr) {
|
||||
SEARCH_QUERY[3] = filterStr;
|
||||
out = SEARCH_QUERY.join('');
|
||||
}
|
||||
else {
|
||||
out = null;
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
// entry point for obtaining a remote proposal
|
||||
link.getRemoteProposal = function(acc_tk, contid) {
|
||||
var cid = contid || contactid;
|
||||
|
||||
var req = fb.utils.getContactData(cid);
|
||||
req.onsuccess = function() {
|
||||
if (req.result) {
|
||||
cdata = req.result;
|
||||
numQueries = 1;
|
||||
currentRecommendation = null;
|
||||
var query = buildQuery(cdata);
|
||||
// Check whether we have enough info for the first query
|
||||
// otherwise launch the getAll query
|
||||
if (query === null) {
|
||||
getRemoteProposalAll(acc_tk);
|
||||
return;
|
||||
}
|
||||
doGetRemoteProposal(acc_tk, cdata, query);
|
||||
}
|
||||
else {
|
||||
throw new Error(
|
||||
'FB: Contact to be linked not found in mozContacts: ' + cid);
|
||||
}
|
||||
};
|
||||
req.onerror = function(e) {
|
||||
window.console.error('FB: Error while retrieving contact data: ', cid);
|
||||
throw e;
|
||||
};
|
||||
};
|
||||
|
||||
function getRemoteProposalAll(acc_tk) {
|
||||
numQueries++;
|
||||
doGetRemoteProposal(acc_tk, null, ALL_QUERY.join(''), true);
|
||||
}
|
||||
|
||||
// This function deals with the response for a proposal
|
||||
// It takes care whether a response with the number of friends is present
|
||||
// and updates the cache accordingly
|
||||
function proposalReadyMultiple(done, error, response) {
|
||||
// If there is an error we just pass it upstream
|
||||
if (response.error) {
|
||||
done(response);
|
||||
return;
|
||||
} else if (!Array.isArray(response.data)) {
|
||||
error({
|
||||
name: 'QueryResponseError'
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
var friendList, totalFriends;
|
||||
if (response.data.length > 0 &&
|
||||
Array.isArray(response.data[0].fql_result_set)) {
|
||||
friendList = response.data[0].fql_result_set;
|
||||
if (response.data[1] &&
|
||||
Array.isArray(response.data[1].fql_result_set)) {
|
||||
totalFriends = response.data[1].fql_result_set.length;
|
||||
}
|
||||
}
|
||||
else {
|
||||
friendList = response.data;
|
||||
totalFriends = friendList.length;
|
||||
}
|
||||
|
||||
if (typeof totalFriends !== 'undefined') {
|
||||
fb.utils.setCachedNumFriends(totalFriends);
|
||||
}
|
||||
|
||||
done({
|
||||
data: friendList
|
||||
});
|
||||
}
|
||||
|
||||
// Performs all the work to obtain the remote proposal
|
||||
// the "isAll" parameter indicates that the query will get all friends
|
||||
function doGetRemoteProposal(acc_tk, contactData, query, isAll) {
|
||||
/*
|
||||
Phone.lookup was analysed but we were not happy about how it worked
|
||||
|
||||
var searchService = 'https://api.facebook.com/method/phonebook.lookup' +
|
||||
'?include_non_fb=false';
|
||||
var entries = [];
|
||||
entries.push(getEntry(contactData));
|
||||
var sentries = JSON.stringify(entries);
|
||||
|
||||
*/
|
||||
var theQuery = query;
|
||||
var callback = proposalReadyMultiple.bind(null, fb.link.proposalReady,
|
||||
fb.link.errorHandler);
|
||||
// If the query is not going to provide a full list of friends
|
||||
// We count all in order to refresh the total number of friends
|
||||
if (!isAll) {
|
||||
theQuery = JSON.stringify({
|
||||
query1: query,
|
||||
query2: COUNT_QUERY
|
||||
});
|
||||
}
|
||||
|
||||
state = 'proposal';
|
||||
currentNetworkRequest = fb.utils.runQuery(theQuery, {
|
||||
success: callback,
|
||||
error: fb.link.errorHandler,
|
||||
timeout: fb.link.timeoutHandler
|
||||
}, acc_tk);
|
||||
}
|
||||
|
||||
// Invoked when remoteAll is canceled
|
||||
function cancelCb(shouldNotifyParent) {
|
||||
if (currentNetworkRequest) {
|
||||
currentNetworkRequest.cancel();
|
||||
currentNetworkRequest = null;
|
||||
}
|
||||
|
||||
Curtain.hide(shouldNotifyParent ? notifyParent.bind(
|
||||
null, {type: 'abort'}) : null);
|
||||
}
|
||||
|
||||
// Obtains a proposal with all friends
|
||||
function getRemoteAll() {
|
||||
Curtain.oncancel = cancelCb;
|
||||
Curtain.show('wait', 'friends');
|
||||
|
||||
state = 'friends';
|
||||
|
||||
currentNetworkRequest = fb.utils.runQuery(ALL_QUERY.join(''), {
|
||||
success: fb.link.friendsReady,
|
||||
error: fb.link.errorHandler,
|
||||
timeout: fb.link.timeoutHandler
|
||||
}, access_token);
|
||||
}
|
||||
|
||||
// Obtains a linking proposal to be shown to the user
|
||||
link.getProposal = function(cid, acc_tk) {
|
||||
link.getRemoteProposal(acc_tk, cid);
|
||||
};
|
||||
|
||||
// Executed when the server response is available
|
||||
link.proposalReady = function(response) {
|
||||
if (typeof response.error !== 'undefined') {
|
||||
window.console.error('FB: Error while retrieving link data',
|
||||
response.error.code, response.error.message);
|
||||
|
||||
if (response.error.code != 190) {
|
||||
setCurtainHandlersErrorProposal();
|
||||
Curtain.show('error', 'proposal');
|
||||
}
|
||||
else {
|
||||
// access token problem. A new OAuth 2.0 flow has to start
|
||||
handleTokenError();
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (response.data.length === 0 && numQueries === 1) {
|
||||
getRemoteProposalAll(access_token);
|
||||
}
|
||||
else {
|
||||
var data = response.data;
|
||||
currentRecommendation = data;
|
||||
|
||||
var sortedByName = [];
|
||||
var numFriendsProposed = data.length;
|
||||
var searchAccentsArrays = {};
|
||||
var index = 0;
|
||||
|
||||
data.forEach(function(item) {
|
||||
if (!item.email) {
|
||||
item.email = '';
|
||||
}
|
||||
var box = utils.misc.getPreferredPictureBox();
|
||||
item.picwidth = box.width;
|
||||
item.picheight = box.height;
|
||||
|
||||
// Only do this if we need to prepare the search accents phase
|
||||
if (numQueries === 2) {
|
||||
// Saving the original order
|
||||
sortedByName.push(item);
|
||||
// Populate the arrays for doing the accents related search
|
||||
Object.keys(SEARCH_ACCENTS_FIELDS).forEach(function(field) {
|
||||
searchAccentsArrays[field] = searchAccentsArrays[field] || [];
|
||||
if (item[field]) {
|
||||
// The different words for each item
|
||||
var words = item[field].split(/[ ]+/);
|
||||
// The whole word itself is added
|
||||
words.push(item[field]);
|
||||
words.forEach(function(word) {
|
||||
var obj = {
|
||||
originalIndex: index
|
||||
};
|
||||
obj[field] = Normalizer.toAscii(word).toLowerCase();
|
||||
searchAccentsArrays[field].push(obj);
|
||||
});
|
||||
}
|
||||
});
|
||||
index++;
|
||||
}
|
||||
});
|
||||
|
||||
if (numQueries === 2) {
|
||||
var accentsProposal = searchAccents(searchAccentsArrays, cdata);
|
||||
if (accentsProposal.length === 0) {
|
||||
data = sortedByName;
|
||||
mainSection.classList.add('no-proposal');
|
||||
numFriendsProposed = 0;
|
||||
}
|
||||
else {
|
||||
currentRecommendation = [];
|
||||
accentsProposal.forEach(function(proposalIndex) {
|
||||
currentRecommendation.push(sortedByName[proposalIndex]);
|
||||
});
|
||||
numFriendsProposed = currentRecommendation.length;
|
||||
}
|
||||
} else {
|
||||
viewButton.setAttribute('data-l10n-id', 'viewAll');
|
||||
viewButton.onclick = UI.viewAllFriends;
|
||||
}
|
||||
|
||||
utils.templates.append('#friends-list', currentRecommendation);
|
||||
imgLoader.reload();
|
||||
|
||||
if (typeof completedCb === 'function') {
|
||||
completedCb();
|
||||
}
|
||||
|
||||
Curtain.hide(function onCurtainHide() {
|
||||
sendReadyEvent();
|
||||
window.addEventListener('message', function linkOnViewPort(e) {
|
||||
if (e.origin !== fb.CONTACTS_APP_ORIGIN) {
|
||||
return;
|
||||
}
|
||||
var data = e.data;
|
||||
if (data && data.type === 'dom_transition_end') {
|
||||
window.removeEventListener('message', linkOnViewPort);
|
||||
utils.status.show({
|
||||
id: 'linkProposal',
|
||||
args: {
|
||||
numFriends: numFriendsProposed
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
// This function needs to be called because link proposals through FB Query
|
||||
// do not work properly with words with special characters (bug 796714)
|
||||
function searchAccents(searchArrays, contactData) {
|
||||
var out = [];
|
||||
var searchFields = Object.keys(SEARCH_ACCENTS_FIELDS);
|
||||
|
||||
function compareItems(target, item) {
|
||||
var out;
|
||||
|
||||
if (typeof target === 'string') {
|
||||
out = target.localeCompare(item);
|
||||
if (out !== 0) {
|
||||
if (item.indexOf(target) === 0) {
|
||||
out = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return out;
|
||||
} // compareItems Function
|
||||
|
||||
searchFields.forEach(function(searchField) {
|
||||
// The array is ordered according to the search field
|
||||
// this enables an efficient binary search
|
||||
var searchArray = searchArrays[searchField].sort(function(a, b) {
|
||||
return a[searchField].localeCompare(b[searchField]);
|
||||
});
|
||||
|
||||
var fieldToSearch = contactData[SEARCH_ACCENTS_FIELDS[searchField]];
|
||||
if (fieldToSearch && fieldToSearch[0]) {
|
||||
// Splitting in the different words
|
||||
var dataToSearch = fieldToSearch[0].trim().split(/[ ]+/);
|
||||
|
||||
dataToSearch.forEach(function(aData) {
|
||||
var targetString = Normalizer.toAscii(aData).toLowerCase();
|
||||
var searchResult = utils.binarySearch(targetString, searchArray, {
|
||||
arrayField: searchField,
|
||||
compareFunction: compareItems
|
||||
});
|
||||
|
||||
searchResult.forEach(function(aResult) {
|
||||
var candidate = searchArray[aResult].originalIndex;
|
||||
// Avoiding to show two times the same result element
|
||||
if (out.indexOf(candidate) === -1) {
|
||||
out.push(candidate);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
function sendReadyEvent() {
|
||||
parent.postMessage({
|
||||
type: 'ready', data: ''
|
||||
}, fb.CONTACTS_APP_ORIGIN);
|
||||
}
|
||||
|
||||
function setCurtainHandlersErrorProposal() {
|
||||
Curtain.oncancel = function() {
|
||||
cancelCb(true);
|
||||
};
|
||||
|
||||
Curtain.onretry = function getRemoteProposal() {
|
||||
Curtain.oncancel = function() {
|
||||
cancelCb(true);
|
||||
};
|
||||
Curtain.show('wait', state);
|
||||
|
||||
link.getRemoteProposal(access_token, contactid);
|
||||
};
|
||||
}
|
||||
|
||||
link.baseHandler = function(type) {
|
||||
if (state === 'friends') {
|
||||
Curtain.onretry = getRemoteAll;
|
||||
Curtain.oncancel = Curtain.hide;
|
||||
} else if (state === 'proposal') {
|
||||
setCurtainHandlersErrorProposal();
|
||||
}
|
||||
else if (state === 'linking') {
|
||||
Curtain.onretry = function retry_link() {
|
||||
Curtain.show('message', 'linking');
|
||||
UI.selected({
|
||||
target: {
|
||||
dataset: {
|
||||
uuid: friendUidToLink
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
Curtain.oncancel = Curtain.hide;
|
||||
}
|
||||
|
||||
Curtain.show(type, state);
|
||||
};
|
||||
|
||||
link.timeoutHandler = function() {
|
||||
link.baseHandler('timeout');
|
||||
};
|
||||
|
||||
link.errorHandler = function() {
|
||||
link.baseHandler('error');
|
||||
};
|
||||
|
||||
/**
|
||||
* Clears the list of contacts
|
||||
*
|
||||
*/
|
||||
function clearList() {
|
||||
if (!friendsList) {
|
||||
friendsList = document.querySelector('#friends-list');
|
||||
}
|
||||
var template = friendsList.querySelector('[data-template]');
|
||||
|
||||
utils.dom.removeChildNodes(friendsList);
|
||||
friendsList.appendChild(template);
|
||||
}
|
||||
|
||||
link.friendsReady = function(response) {
|
||||
if (typeof response.error === 'undefined' && response.data) {
|
||||
viewButton.setAttribute('data-l10n-id', 'viewRecommend');
|
||||
viewButton.onclick = UI.viewRecommended;
|
||||
|
||||
allFriends = response;
|
||||
|
||||
fb.utils.setCachedNumFriends(response.data.length);
|
||||
|
||||
response.data.forEach(function(item) {
|
||||
if (!item.email) {
|
||||
item.email = '';
|
||||
}
|
||||
});
|
||||
|
||||
clearList();
|
||||
|
||||
var fragment = document.createDocumentFragment();
|
||||
utils.templates.append(friendsList, response.data, fragment);
|
||||
friendsList.appendChild(fragment);
|
||||
|
||||
imgLoader.reload();
|
||||
|
||||
Curtain.hide();
|
||||
}
|
||||
else {
|
||||
window.console.error('FB: Error while retrieving friends',
|
||||
response.error.code, response.error.message);
|
||||
|
||||
if (response.error.code !== 190) {
|
||||
Curtain.onretry = getRemoteAll;
|
||||
Curtain.oncancel = Curtain.hide;
|
||||
}
|
||||
else {
|
||||
// Error with the access token. It is very unlikely that this happens
|
||||
Curtain.onretry = handleTokenError;
|
||||
}
|
||||
Curtain.show('error', 'friends');
|
||||
}
|
||||
};
|
||||
|
||||
function setCurtainHandlers() {
|
||||
Curtain.oncancel = function curtain_cancel() {
|
||||
cancelCb(true);
|
||||
};
|
||||
}
|
||||
|
||||
link.start = function(contactId, acc_tk, endCb) {
|
||||
// Only needed for testing purposes
|
||||
completedCb = endCb;
|
||||
|
||||
access_token = acc_tk;
|
||||
contactid = contactId;
|
||||
|
||||
setCurtainHandlers();
|
||||
clearList();
|
||||
imgLoader = new ImageLoader('#mainContent',
|
||||
'li:not([data-uuid="#uid#"])');
|
||||
|
||||
if (!acc_tk) {
|
||||
oauth2.getAccessToken(function proposal_new_token(new_acc_tk) {
|
||||
access_token = new_acc_tk;
|
||||
link.getProposal(contactId, new_acc_tk);
|
||||
}, 'proposal', 'facebook');
|
||||
}
|
||||
else {
|
||||
link.getProposal(contactId, acc_tk);
|
||||
}
|
||||
};
|
||||
|
||||
link.init = function() {
|
||||
mainSection = document.querySelector('#main');
|
||||
viewButton = document.querySelector('#view-all');
|
||||
};
|
||||
|
||||
function retryOnErrorCb() {
|
||||
UI.selected({
|
||||
target: {
|
||||
dataset: {
|
||||
uuid: friendUidToLink
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function handleTokenError() {
|
||||
Curtain.hide(notifyParent.bind(null, {
|
||||
type: 'token_error'
|
||||
}));
|
||||
var cb = function() {
|
||||
allFriends = null;
|
||||
link.start(contactid);
|
||||
};
|
||||
ImportStatusData.remove(fb.utils.TOKEN_DATA_KEY).then(cb);
|
||||
}
|
||||
|
||||
UI.selected = function(event) {
|
||||
Curtain.show('message', 'linking');
|
||||
|
||||
var element = event.target.parentNode;
|
||||
friendUidToLink = element.dataset.uuid;
|
||||
|
||||
// First it is needed to check whether is an already imported friend
|
||||
var req = fb.contacts.get(friendUidToLink);
|
||||
req.onsuccess = function() {
|
||||
if (req.result) {
|
||||
window.setTimeout(function delay() {
|
||||
Curtain.hide(notifyParent.bind(null, {
|
||||
type: 'item_selected',
|
||||
data: {
|
||||
uid: friendUidToLink
|
||||
}
|
||||
}));
|
||||
}, 1000);
|
||||
}
|
||||
else {
|
||||
state = 'linking';
|
||||
var callbacks = { };
|
||||
|
||||
callbacks.success = function(data) {
|
||||
Curtain.hide(notifyParent.bind(null, {
|
||||
type: 'item_selected',
|
||||
data: data
|
||||
}));
|
||||
};
|
||||
|
||||
callbacks.error = function(e) {
|
||||
var error = e.target.error;
|
||||
window.console.error('FB: Error while importing friend data ',
|
||||
JSON.stringify(error));
|
||||
Curtain.oncancel = Curtain.hide;
|
||||
if (error.code != 190) {
|
||||
Curtain.onretry = retryOnErrorCb;
|
||||
}
|
||||
else {
|
||||
Curtain.onretry = handleTokenError;
|
||||
}
|
||||
Curtain.show('error', 'linking');
|
||||
};
|
||||
|
||||
callbacks.timeout = function() {
|
||||
link.baseHandler('timeout');
|
||||
};
|
||||
|
||||
imgLoader.unload(); // Removing listeners
|
||||
FacebookConnector.importContact(friendUidToLink, access_token,
|
||||
callbacks, 'not_match');
|
||||
}
|
||||
};
|
||||
|
||||
req.onerror = function() {
|
||||
window.console.error('FB: Error while importing friend data');
|
||||
Curtain.oncancel = Curtain.hide;
|
||||
Curtain.onretry = retryOnErrorCb;
|
||||
Curtain.show('error', 'linking');
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
UI.end = function(event) {
|
||||
var msg = {
|
||||
type: 'window_close',
|
||||
data: ''
|
||||
};
|
||||
|
||||
parent.postMessage(msg, fb.CONTACTS_APP_ORIGIN);
|
||||
};
|
||||
|
||||
UI.viewAllFriends = function(event) {
|
||||
if (!allFriends) {
|
||||
getRemoteAll();
|
||||
}
|
||||
else {
|
||||
link.friendsReady(allFriends);
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
UI.viewRecommended = function(event) {
|
||||
// event.target === viewButton
|
||||
event.target.onclick = UI.viewAllFriends;
|
||||
event.target.setAttribute('data-l10n-id', 'viewAll');
|
||||
|
||||
clearList();
|
||||
utils.templates.append(friendsList, currentRecommendation);
|
||||
imgLoader.reload();
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
})(document);
|
||||
}
|
||||
43
gaia/apps/communications/contacts/js/fb/fb_link_init.js
Executable file
43
gaia/apps/communications/contacts/js/fb/fb_link_init.js
Executable file
|
|
@ -0,0 +1,43 @@
|
|||
'use strict';
|
||||
|
||||
/* global fb, utils */
|
||||
|
||||
(function(document) {
|
||||
var cid = window.location.search.substring(fb.link.CID_PARAM.length + 2);
|
||||
|
||||
// Getting the timeout config from the parent
|
||||
if (parent.fb) {
|
||||
fb.operationsTimeout = parent.fb.operationsTimeout;
|
||||
}
|
||||
|
||||
utils.listeners.add({
|
||||
'#link-header': [
|
||||
{
|
||||
event: 'action',
|
||||
handler: fb.link.ui.end
|
||||
}
|
||||
],
|
||||
'#friends-list': fb.link.ui.selected
|
||||
});
|
||||
|
||||
fb.link.init();
|
||||
|
||||
// This event listener is added manually as it wil be changing dynamically
|
||||
document.querySelector('#view-all').onclick = fb.link.ui.viewAllFriends;
|
||||
|
||||
// Module fb.contacts is initialized just in case we need it
|
||||
fb.contacts.init(function fb_init() {
|
||||
window.addEventListener('message', function getAccessToken(e) {
|
||||
if (e.origin !== fb.CONTACTS_APP_ORIGIN) {
|
||||
return;
|
||||
}
|
||||
window.removeEventListener('message', getAccessToken);
|
||||
fb.link.start(cid, e.data.data);
|
||||
});
|
||||
|
||||
parent.postMessage({
|
||||
type: 'messaging_ready',
|
||||
data: ''
|
||||
}, fb.CONTACTS_APP_ORIGIN);
|
||||
});
|
||||
})(document);
|
||||
110
gaia/apps/communications/contacts/js/fb/fb_messaging.js
Executable file
110
gaia/apps/communications/contacts/js/fb/fb_messaging.js
Executable file
|
|
@ -0,0 +1,110 @@
|
|||
'use strict';
|
||||
|
||||
/* global LazyLoader */
|
||||
/* global oauth2 */
|
||||
/* global oauthflow */
|
||||
|
||||
var fb = window.fb || {};
|
||||
|
||||
if (typeof fb.msg === 'undefined') {
|
||||
LazyLoader.load('/shared/pages/import/js/parameters.js', () => {
|
||||
(function(document) {
|
||||
var Msg = fb.msg = {};
|
||||
var to;
|
||||
var message;
|
||||
var params = oauthflow.params.facebook;
|
||||
var appId = params.applicationId;
|
||||
var redirectURI = params.redirectMsg;
|
||||
|
||||
Msg.CID_PARAM = 'contactid';
|
||||
|
||||
// Only needed if we decide to craft our own UI
|
||||
Msg.wallPost = function(uid, msg) {
|
||||
to = uid || to;
|
||||
message = msg || message;
|
||||
oauth2.getAccessToken(doWallPost, 'wallPost', 'facebook');
|
||||
};
|
||||
|
||||
Msg.sendPrivate = function(uid, msg) {
|
||||
// TODO: To be implemented (if we decide to craft our custom UI)
|
||||
};
|
||||
|
||||
// This code is for posting to user's wall. Only will be necessary if
|
||||
// we decide to craft our own UI for posting to the wall
|
||||
function doWallPost(token) {
|
||||
var msgWallService = 'https://graph.facebook.com/#/feed?method=POST';
|
||||
|
||||
msgWallService = msgWallService.replace(/#/, to);
|
||||
|
||||
var params = [
|
||||
'access_token' + '=' + token,
|
||||
'message' + '=' + message,
|
||||
'callback' + '=' + 'fb.msg.ui.wallPosted'
|
||||
];
|
||||
|
||||
var q = params.join('&');
|
||||
|
||||
var jsonp = document.createElement('script');
|
||||
jsonp.src = msgWallService + '&' + q;
|
||||
|
||||
document.body.appendChild(jsonp);
|
||||
}
|
||||
|
||||
var UI = Msg.ui = {};
|
||||
|
||||
function getFbContactUid(contactId, callback) {
|
||||
var req = fb.utils.getContactData(contactId);
|
||||
|
||||
req.onsuccess = function() {
|
||||
var fbContact = new fb.Contact(req.result);
|
||||
callback(fbContact.uid);
|
||||
};
|
||||
|
||||
req.onerror = function() {
|
||||
window.console.error('Contacts: Contact not found!');
|
||||
callback(null);
|
||||
};
|
||||
}
|
||||
|
||||
function openMsgDialog(dialogURI, uid) {
|
||||
var params = [
|
||||
'app_id' + '=' + appId,
|
||||
'to' + '=' + uid,
|
||||
'redirect_uri' + '=' + encodeURIComponent(redirectURI)
|
||||
];
|
||||
|
||||
var target = dialogURI + params.join('&');
|
||||
window.open(fb.utils.getNonCacheableUrl(target), '', 'dialog');
|
||||
}
|
||||
|
||||
// Use the FB Dialogs functionality for posting to the wall
|
||||
UI.wallPost = function(contactId) {
|
||||
getFbContactUid(contactId, function ui_wallPost(uid) {
|
||||
if (uid) {
|
||||
var dialogURI = 'https://m.facebook.com/dialog/feed?';
|
||||
openMsgDialog(dialogURI, uid);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// Use a Web view from Facebook for sending private messages
|
||||
// TODO: Check with Facebook why the send message dialog seems not to be
|
||||
// working on mobile
|
||||
UI.sendPrivateMsg = function(contactId) {
|
||||
getFbContactUid(contactId, function ui_sendMsg(uid) {
|
||||
if (uid) {
|
||||
var url = 'https://m.facebook.com/compose_message/?uid=' + uid;
|
||||
window.open(fb.utils.getNonCacheableUrl(url),
|
||||
'', 'dialog');
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
UI.wallPosted = function(result) {
|
||||
UI.end();
|
||||
window.console.log(JSON.stringify(result));
|
||||
};
|
||||
|
||||
})(document);
|
||||
});
|
||||
}
|
||||
55
gaia/apps/communications/contacts/js/fb_loader.js
Executable file
55
gaia/apps/communications/contacts/js/fb_loader.js
Executable file
|
|
@ -0,0 +1,55 @@
|
|||
'use strict';
|
||||
/* global LazyLoader */
|
||||
/* exported fbLoader */
|
||||
|
||||
var fbLoader = (function() {
|
||||
|
||||
var loaded = false;
|
||||
|
||||
var loadFb = function loadFb() {
|
||||
if (loaded) {
|
||||
return;
|
||||
}
|
||||
|
||||
loaded = true;
|
||||
var iframesFragment = document.createDocumentFragment();
|
||||
|
||||
var oauth = document.createElement('iframe');
|
||||
oauth.id = 'iframe_oauth';
|
||||
oauth.hidden = true;
|
||||
iframesFragment.appendChild(oauth);
|
||||
|
||||
var extensions = document.createElement('iframe');
|
||||
extensions.id = 'iframe_extensions';
|
||||
iframesFragment.appendChild(extensions);
|
||||
|
||||
document.body.appendChild(iframesFragment);
|
||||
|
||||
var scripts = [
|
||||
'/shared/js/contacts/import/utilities/misc.js',
|
||||
'/shared/js/contacts/import/import_status_data.js',
|
||||
'/contacts/js/service_extensions.js',
|
||||
'/shared/pages/import/js/parameters.js',
|
||||
'/shared/js/fb/fb_request.js',
|
||||
'/shared/js/contacts/import/facebook/fb_data.js',
|
||||
'/shared/js/contacts/import/facebook/fb_utils.js',
|
||||
'/shared/js/contacts/import/facebook/fb_query.js',
|
||||
'/shared/js/fb/fb_reader_utils.js',
|
||||
'/shared/js/contacts/import/facebook/fb_contact_utils.js',
|
||||
'/shared/js/contacts/import/facebook/fb_contact.js',
|
||||
'/contacts/js/fb/fb_link.js',
|
||||
'/contacts/js/fb/fb_messaging.js'
|
||||
];
|
||||
|
||||
LazyLoader.load(scripts, function() {
|
||||
var event = new CustomEvent('facebookLoaded');
|
||||
window.dispatchEvent(event);
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
load: loadFb,
|
||||
get loaded() { return loaded; }
|
||||
};
|
||||
|
||||
})();
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue