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
25901 changed files with 9982925 additions and 369 deletions
|
|
@ -0,0 +1,29 @@
|
|||
/* exported console */
|
||||
'use strict';
|
||||
|
||||
(function Console(exports) {
|
||||
|
||||
function getString(a) {
|
||||
var out = '';
|
||||
for (var c = 0; c < a.length; c++) {
|
||||
out += a[c];
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
exports.console = {
|
||||
'error': function() {
|
||||
self.postMessage({
|
||||
type: 'error',
|
||||
data: getString(arguments)
|
||||
});
|
||||
},
|
||||
'log': function() {
|
||||
self.postMessage({
|
||||
type: 'trace',
|
||||
data: getString(arguments)
|
||||
});
|
||||
}
|
||||
};
|
||||
})(self);
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
;;'use strict';var fb=window.fb||{};if(!fb.sync){(function(){var Sync=fb.sync={};var theWorker;var fbContactsById;var totalToChange=0,changed=0;var nextTimestamp;var completionCallback,errorCallback;var fbFriendsDataByUid;var logLevel=fb.logLevel||parent.fb.logLevel||'DEBUG';var isDebug=(logLevel==='DEBUG');var alarmFrame=null,currentAlarmRequest=null;var DELAY_ALARM_SCHED=5000;function debug(){if(isDebug){var theArgs=['<<FBSync>>'];for(var c=0;c<arguments.length;c++){theArgs.push(arguments[c]);}
|
||||
window.console.log.apply(window.console,theArgs);}}
|
||||
function startWorker(){theWorker=new Worker('/facebook/js/sync_worker.js');theWorker.onmessage=function(e){workerMessage(e.data);};theWorker.onerror=function(e){window.console.error('Worker Error',e.message,e.lineno,e.column);if(typeof errorCallback==='function'){errorCallback({type:'default_error'});}};}
|
||||
function workerMessage(m){switch(m.type){case'query_error':var error=m.data||{};window.console.error('FB: Error reported by the worker',JSON.stringify(error));if(typeof errorCallback==='function'){errorCallback({name:'defaultError'});}
|
||||
break;case'token_error':debug('FB: Token error reported by the worker');if(typeof errorCallback==='function'){errorCallback({name:'invalidToken'});}
|
||||
break;case'timeout_error':debug('Timeout error reported by the worker');if(typeof errorCallback==='function'){errorCallback({name:'timeout'});}
|
||||
break;case'trace':debug(m.data);break;case'friendRemoved':removeFbFriend(m.data.contactId);break;case'friendUpdated':updateFbFriend(m.data.contactId,fb.friend2mozContact(m.data.updatedFbData));break;case'totals':changed=0;totalToChange=m.data.totalToChange;nextTimestamp=m.data.queryTimestamp;var newFriendNumber=m.data.newFriendNumber;if(newFriendNumber){debug('New friend number: ',newFriendNumber);fb.utils.setCachedNumFriends(newFriendNumber);}
|
||||
debug('Total to be changed: ',totalToChange);checkTotals();break;case'friendImgReady':debug('Friend Img Data ready: ',m.data.contactId);updateFbFriendWhenImageReady(m.data);break;}}
|
||||
function updateFbFriendWhenImageReady(data){var contact=fbContactsById[data.contactId];var uid=fb.getFriendUid(contact);var updatedFbData=fbFriendsDataByUid[uid];if(!data.photo){updateFbFriend(data.contactId,updatedFbData);return;}
|
||||
utils.thumbnailImage(data.photo,function gotTumbnail(thumbnail){var fbInfo={};fbInfo.photo=[data.photo,thumbnail];fb.setFriendPictureUrl(fbInfo,updatedFbData.pic_big);updatedFbData.fbInfo=fbInfo;updateFbFriend(data.contactId,updatedFbData);});}
|
||||
function onsuccessCb(){changed++;checkTotals();}
|
||||
function updateFbFriend(contactId,cfdata){fb.friend2mozContact(cfdata);cfdata.fbInfo=cfdata.fbInfo||{};cfdata.fbInfo.org=[fb.getWorksAt(cfdata)];var birthDate=null;if(cfdata.birthday_date&&cfdata.birthday_date.length>0){birthDate=fb.getBirthDate(cfdata.birthday_date);}
|
||||
cfdata.fbInfo.bday=birthDate;var address=fb.getAddresses(cfdata);if(address){cfdata.fbInfo.adr=address;}
|
||||
if(cfdata.shortTelephone){cfdata.fbInfo.shortTelephone=cfdata.shortTelephone;delete cfdata.shortTelephone;}
|
||||
var fbContact=new fb.Contact(fbContactsById[contactId]);var fbReq=fbContact.update(cfdata);fbReq.onsuccess=function(){debug('Friend updated correctly',cfdata.uid);onsuccessCb();};fbReq.onerror=function(){window.console.error('FB: Error while saving contact data: ',cfdata.uid);changed++;checkTotals();};}
|
||||
function removeFbFriend(contactId){debug('Removing Friend: ',contactId);var removedFriend=fbContactsById[contactId];var fbContact=new fb.Contact(removedFriend);if(fb.isFbLinked(removedFriend)){debug('Friend is linked: ',contactId);var req=fbContact.unlink('hard');req.onsuccess=onsuccessCb;req.onerror=function(){window.console.error('FB. Error while hard unlinking friend: ',contactId);changed++;checkTotals();};}
|
||||
else{debug('Friend is not linked: ',contactId);var fbContactReq=fbContact.remove();fbContactReq.onsuccess=onsuccessCb;fbContactReq.onerror=function(){window.console.error('FB. Error while removing contact: ',contactId);changed++;checkTotals();};}}
|
||||
function checkTotals(){if(changed===totalToChange){debug('Sync process finished!');if(window.contacts&&window.contacts.List){window.setTimeout(window.contacts.List.load,0);}
|
||||
fb.utils.setLastUpdate(nextTimestamp,function sync_end(){completionCallback(totalToChange);});if(theWorker){theWorker.terminate();theWorker=null;}}}
|
||||
Sync.start=function(params){if(params){completionCallback=params.success;errorCallback=params.error;}
|
||||
totalToChange=0;changed=0;var req=fb.utils.getAllFbContacts();req.onsuccess=function(){var uids={};var fbContacts=req.result;if(fbContacts.length===0){debug('Nothing to be synchronized. No FB Contacts present');return;}
|
||||
startWorker();fbContactsById={};var forceUpdate={};fbContacts.forEach(function(contact){fbContactsById[contact.id]=contact;var pictureUrl=fb.getFriendPictureUrl(contact);var uid=fb.getFriendUid(contact);uids[uid]={contactId:contact.id,photoUrl:pictureUrl};if(!pictureUrl){forceUpdate[uid]={contactId:contact.id};}});fb.utils.getLastUpdate(function run_worker(ts){fb.utils.getCachedAccessToken(function(access_token){theWorker.postMessage({type:'start',data:{uids:uids,imgNeedsUpdate:forceUpdate,timestamp:ts,access_token:access_token,operationsTimeout:fb.operationsTimeout,targetPictureSize:utils.misc.getPreferredPictureDetail()}});});});};req.onerror=function(){window.console.error('FB: Error while getting friends on the device',req.error.name);if(typeof errorCallback==='function'){errorCallback({name:'defaultError'});}};};Sync.scheduleNextSync=function(){currentAlarmRequest=new fb.utils.Request();window.setTimeout(function(){alarmFrame=document.createElement('iframe');alarmFrame.src='/facebook/fb_sync.html';alarmFrame.width=1;alarmFrame.height=1;alarmFrame.style.display='none';document.body.appendChild(alarmFrame);},0);return currentAlarmRequest;};function cleanAlarmSchedFrame(){alarmFrame.src=null;document.body.removeChild(alarmFrame);alarmFrame=null;}
|
||||
Sync.onAlarmScheduled=function(date){debug('Next synch scheduled at: ',date);if(alarmFrame){window.setTimeout(cleanAlarmSchedFrame,DELAY_ALARM_SCHED);}
|
||||
currentAlarmRequest.done(date);};Sync.onAlarmError=function(e){if(alarmFrame){window.setTimeout(cleanAlarmSchedFrame,DELAY_ALARM_SCHED);}
|
||||
window.console.error('<<FB Sync>> Error while scheduling a new sync: ',e);currentAlarmRequest.failed(e);};Sync.debug=function(){debug.apply(this,arguments);};Sync.startWithData=function(contactList,myFriendsByUid,callbacks){completionCallback=callbacks.success;errorCallback=callbacks.error;nextTimestamp=Date.now();changed=0;totalToChange=Number.MAX_VALUE;debug('Starting Synchronization with data');fbFriendsDataByUid=myFriendsByUid;var toBeUpdated={};fb.utils.getLastUpdate(function import_updates(lastUpdate){var toBeChanged=0;var lastUpdateTime=Math.round(lastUpdate/1000);debug('Last update time: ',lastUpdateTime);fbContactsById={};contactList.forEach(function(aContact){fbContactsById[aContact.id]=aContact;var uid=fb.getFriendUid(aContact);var friendData=fbFriendsDataByUid[uid];if(friendData){var friendUpdate=friendData.profile_update_time;debug('Friend update Time ',friendUpdate,'for UID: ',uid);var profileImgUrl=fb.getFriendPictureUrl(aContact);if(friendUpdate>lastUpdateTime||profileImgUrl!==friendData.pic_big){debug('Friend changed!! : ',uid);if(profileImgUrl!==friendData.pic_big){debug('Profile img changed: ',profileImgUrl);toBeUpdated[uid]={contactId:aContact.id};}
|
||||
else{debug('Updating friend: ',friendData.uid);toBeChanged++;updateFbFriend(aContact.id,friendData);}}
|
||||
else{debug('Friend has not changed',uid);}}
|
||||
else{debug('Removing friend: ',aContact.id);toBeChanged++;removeFbFriend(aContact.id);}});debug('First pass of Updates and removed finished');var toBeUpdatedList=Object.keys(toBeUpdated);if(toBeUpdatedList.length>0){totalToChange=toBeChanged+toBeUpdatedList.length;debug('Starting worker for updating img data');startWorker();fb.utils.getCachedAccessToken(function(access_token){theWorker.postMessage({type:'startWithData',data:{access_token:access_token,uids:toBeUpdated,operationsTimeout:fb.operationsTimeout,targetPictureSize:utils.misc.getPreferredPictureDetail()}});});}
|
||||
else{totalToChange=toBeChanged;checkTotals();}});};})();}
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
;'use strict';var fb=window.fb||{};var Sync=fb.sync||{};fb.sync=Sync;(function(){var Alarm=Sync.alarm={};var ALARM_ID_KEY=fb.utils.ALARM_ID_KEY;var isSyncOngoing=false;var DEFAULT_RETRY_PERIOD=1;var RETRY_PERIOD_TIMEOUT=0.25;var CLOSE_DELAY=5000;var FB_TRAY_ICON='/contacts/style/images/f_logo.png';var FB_SYNC_ERROR_PARAM='isSyncError';Alarm.init=function(){fb.init(function fb_alarm_init(){if(navigator.mozHasPendingMessage('alarm')){fb.sync.debug('Alarm System Message Received!!!!!');navigator.mozSetMessageHandler('alarm',handleAlarm);}
|
||||
else if(parent.location===window.location){fb.sync.debug('Fb Sync woke up. Alarm ok. mozHasPendingMsg failed');window.setTimeout(function(){handleAlarm({data:{sync:true}});},0);}
|
||||
else{setNextAlarm(true,fb.syncPeriod);}});};function syncSuccess(){fb.sync.debug('Sync finished ok at ',new Date());isSyncOngoing=false;setNextAlarm(false,fb.syncPeriod,function(){closeApp();});}
|
||||
function syncError(error){isSyncOngoing=false;var theError=error;if(!theError||theError.name==='undefined'){theError={name:'defaultError'};}
|
||||
switch(theError.name){case'invalidToken':fb.sync.debug('Invalid token!!!. Notifying the user');showNotification({title:'facebook',body:'notificationLogin',iconURL:FB_TRAY_ICON+'?'+FB_SYNC_ERROR_PARAM+'=1',callback:handleInvalidToken});break;case'timeout':fb.sync.debug('Timeout in sync. Next sync scheduled in 15 minutes');scheduleAt(RETRY_PERIOD_TIMEOUT,closeApp);break;case'defaultError':window.console.error('Error reported in synchronization: ',JSON.stringify(theError));showNotification({title:'facebook',body:'syncError',iconURL:FB_TRAY_ICON+'?'+FB_SYNC_ERROR_PARAM+'=1',callback:function(){scheduleAt(fb.syncPeriod,closeApp);}});break;}}
|
||||
function handleAlarm(message){if(message.data&&message.data.sync===true&&isSyncOngoing===false&&navigator.onLine===true){isSyncOngoing=true;fb.sync.debug('Starting sync at: ',new Date());ackAlarm(function alarm_process(){fb.sync.start({success:syncSuccess,error:syncError});});}
|
||||
else if(isSyncOngoing===true){fb.sync.debug('There is an ongoing synchronization. Trying it later');scheduleAt(DEFAULT_RETRY_PERIOD,closeApp);}
|
||||
else if(navigator.onLine===false){fb.sync.debug('Navigator is not online. Setting an alarm for next hour');scheduleAt(DEFAULT_RETRY_PERIOD,closeApp);}
|
||||
else{fb.sync.debug('Alarm message but apparently was not a sync message');closeApp();}}
|
||||
function alarmSetErrorCb(notifyParent,e){if(notifyParent){window.setTimeout(function(){parent.fb.sync.onAlarmError(e.target.error);},0);}
|
||||
else{window.console.error('<<FBSync>> Error while setting next alarm: ',e.target.error.name);}}
|
||||
function scheduleAt(hours,callback){var nextUpdate=Date.now()+hours*60*60*1000;var scheduledDate=new Date(nextUpdate);fb.sync.debug('Forcing scheduling an alarm at: ',scheduledDate);var req=addAlarm(scheduledDate);req.onsuccess=function(){fb.sync.debug('--> Next Sync forced to happen at: ',scheduledDate);if(typeof callback==='function'){callback();}};req.onerror=function(e){alarmSetErrorCb(false,e);};}
|
||||
function ackAlarm(callback){window.asyncStorage.removeItem(ALARM_ID_KEY,callback,callback);}
|
||||
function addAlarm(at){var outReq=new fb.utils.Request();window.setTimeout(function do_add_alarm(){window.asyncStorage.getItem(ALARM_ID_KEY,function set_alarm(id){if(id){navigator.mozAlarms.remove(Number(id));}
|
||||
var req=navigator.mozAlarms.add(at,'honorTimezone',{sync:true});req.onsuccess=function(){window.asyncStorage.setItem(ALARM_ID_KEY,String(req.result),function success_store(){outReq.done(req.result);},function error_store(e){var errorParam={target:{error:e||{name:'AsyncStorageError'}}};outReq.failed(errorParam);});};req.onerror=function(e){outReq.failed(e);};});},0);return outReq;}
|
||||
function setNextAlarm(notifyParent,hours,callback){fb.utils.getLastUpdate(function(timestamp){var nextUpdate=timestamp+hours*60*60*1000;var scheduledDate=new Date(nextUpdate);fb.sync.debug('Going to set a new alarm at: ',scheduledDate);var req=addAlarm(scheduledDate);req.onsuccess=function(){if(notifyParent===true){window.setTimeout(function(){parent.fb.sync.onAlarmScheduled(scheduledDate);},0);}
|
||||
fb.sync.debug('--> Next Sync will happen at: ',scheduledDate);if(typeof callback==='function'){callback();}};req.onerror=function(e){alarmSetErrorCb(notifyParent,e);};});}
|
||||
function showNotification(params){navigator.mozApps.getSelf().onsuccess=function(evt){var app=evt.target.result;var iconURL=app.installOrigin+params.iconURL;var options={body:params.body,icon:iconURL};NotificationHelper.send(params.title,options).then(notification=>{if(typeof params.callback==='function'){params.callback();}});};}
|
||||
function closeApp(){window.setTimeout(window.close,CLOSE_DELAY);}
|
||||
function handleInvalidToken(){closeApp();}
|
||||
Alarm.init();})();
|
||||
|
|
@ -0,0 +1,384 @@
|
|||
/* globals fb */
|
||||
'use strict';
|
||||
|
||||
importScripts('/shared/js/fb/fb_request.js',
|
||||
'/shared/js/contacts/import/facebook/fb_query.js',
|
||||
'/shared/js/contacts/import/facebook/fb_contact_utils.js',
|
||||
'/shared/js/fb/fb_reader_utils.js',
|
||||
'console.js');
|
||||
|
||||
(function(wutils) {
|
||||
|
||||
var uids,
|
||||
timestamp,
|
||||
access_token,
|
||||
forceUpdateUids,
|
||||
targetPictureSize;
|
||||
|
||||
wutils.addEventListener('message', processMessage);
|
||||
|
||||
debug('Worker up and running ....');
|
||||
|
||||
// Query to know what friends need to be updated
|
||||
var UPDATED_QUERY = [
|
||||
'SELECT uid, name, first_name, last_name, ' ,
|
||||
'middle_name, birthday_date, email, current_location, ' ,
|
||||
'work, phones, hometown_location, pic_big ' ,
|
||||
' FROM user' ,
|
||||
' WHERE uid ',
|
||||
' IN (SELECT uid1 FROM friend WHERE uid2=me()',
|
||||
' AND uid1 IN (',
|
||||
null,
|
||||
') )',
|
||||
' AND profile_update_time > ',
|
||||
null,
|
||||
' OR uid IN (',
|
||||
null,
|
||||
')'
|
||||
];
|
||||
|
||||
// Query to know what friends need to be removed
|
||||
var REMOVED_QUERY = [
|
||||
'SELECT target_id FROM ',
|
||||
'connection where source_id = me() ',
|
||||
' AND target_type = "user" AND is_deleted="true"',
|
||||
' AND target_id IN (',
|
||||
null,
|
||||
')'
|
||||
];
|
||||
|
||||
// Query to know the total amount of friends
|
||||
var COUNT_QUERY = 'SELECT uid FROM user WHERE uid IN ' +
|
||||
'(SELECT uid1 FROM friend WHERE uid2=me())';
|
||||
|
||||
// Indicates whether the worker started with or without data
|
||||
var withData = false;
|
||||
|
||||
function debug() {
|
||||
function getString(a) {
|
||||
var out = '';
|
||||
for (var c = 0; c < a.length; c++) {
|
||||
out += a[c];
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
self.console.log(getString(arguments));
|
||||
}
|
||||
|
||||
function errorQueryCb(e) {
|
||||
self.console.error('<<FB Sync>>: Error while trying to sync', e);
|
||||
postError({
|
||||
type: 'query_error',
|
||||
data: {}
|
||||
});
|
||||
}
|
||||
|
||||
function timeoutQueryCb(e) {
|
||||
postError({
|
||||
type: 'timeout_error'
|
||||
});
|
||||
}
|
||||
|
||||
function postError(e) {
|
||||
// Message type to propagate to the worker parent
|
||||
var type = 'query_error';
|
||||
if (e && e.code === 190) {
|
||||
self.console.log('This is a token error. Notifying worker parent');
|
||||
type = 'token_error';
|
||||
}
|
||||
else if (e && e.type === 'timeout_error') {
|
||||
self.console.log('This is a timeout error. Notifying worker parent');
|
||||
type = e.type;
|
||||
}
|
||||
wutils.postMessage({
|
||||
type: type,
|
||||
data: e
|
||||
});
|
||||
}
|
||||
|
||||
function buildQueries(ts, uids, forcedUids) {
|
||||
var uidsFilter = uids.join(',');
|
||||
|
||||
// The index at which the timestamp is set
|
||||
var IDX_TS = 10;
|
||||
UPDATED_QUERY[IDX_TS] = Math.round(ts / 1000);
|
||||
|
||||
// The index at which uids filter is set
|
||||
var IDX_UIDS = 7;
|
||||
UPDATED_QUERY[IDX_UIDS] = uidsFilter;
|
||||
|
||||
// The index at which those uids forced to be updated is set
|
||||
var IDX_FORCE = 12;
|
||||
var forceUpdateUidsFilter = '';
|
||||
|
||||
if (forcedUids && forcedUids.length > 0) {
|
||||
forceUpdateUidsFilter = forcedUids.join(',');
|
||||
}
|
||||
UPDATED_QUERY[IDX_FORCE] = forceUpdateUidsFilter;
|
||||
|
||||
var R_IDX_UIDS = 4;
|
||||
REMOVED_QUERY[R_IDX_UIDS] = uidsFilter;
|
||||
|
||||
// Two queries launched at the same time
|
||||
var outQueries = {
|
||||
query1: UPDATED_QUERY.join(''),
|
||||
query2: REMOVED_QUERY.join('')
|
||||
};
|
||||
|
||||
// In any sync without data (periodic one) we also request the total amount
|
||||
// of friends in order to update it
|
||||
// Please take into account that that cannot be done with a friend_count
|
||||
// query as it also returns those friends who are deactivated
|
||||
// See https://bugzilla.mozilla.org/show_bug.cgi?id=838605
|
||||
if (!withData) {
|
||||
outQueries.query3 = COUNT_QUERY;
|
||||
}
|
||||
|
||||
return JSON.stringify(outQueries);
|
||||
}
|
||||
|
||||
function processMessage(e) {
|
||||
var message = e.data;
|
||||
|
||||
if (message.type === 'start') {
|
||||
withData = false;
|
||||
|
||||
uids = message.data.uids;
|
||||
access_token = message.data.access_token;
|
||||
timestamp = message.data.timestamp;
|
||||
forceUpdateUids = message.data.imgNeedsUpdate;
|
||||
fb.operationsTimeout = message.data.operationsTimeout;
|
||||
targetPictureSize = message.data.targetPictureSize;
|
||||
|
||||
debug('Worker acks contacts to check: ', Object.keys(uids).length);
|
||||
|
||||
if (forceUpdateUids && forceUpdateUids.length > 0) {
|
||||
debug('These friends are forced to be updated: ' ,
|
||||
JSON.stringify(forceUpdateUids));
|
||||
}
|
||||
|
||||
getFriendsToBeUpdated(Object.keys(uids), Object.keys(forceUpdateUids));
|
||||
}
|
||||
else if (message.type === 'startWithData') {
|
||||
withData = true;
|
||||
debug('worker Acks start with data');
|
||||
|
||||
fb.operationsTimeout = message.data.operationsTimeout;
|
||||
uids = message.data.uids;
|
||||
access_token = message.data.access_token;
|
||||
targetPictureSize = message.data.targetPictureSize;
|
||||
|
||||
getNewImgsForFriends(Object.keys(uids), access_token);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Launch a multiple query to obtain friends to be updated and deleted
|
||||
function getFriendsToBeUpdated(uids, forcedUids) {
|
||||
var query = buildQueries(timestamp, uids, forcedUids);
|
||||
var callbacks = {
|
||||
success: friendsReady,
|
||||
error: errorQueryCb,
|
||||
timeout: timeoutQueryCb
|
||||
};
|
||||
|
||||
fb.utils.runQuery(query, callbacks, access_token);
|
||||
}
|
||||
|
||||
// Callback executed when data is ready
|
||||
function friendsReady(response) {
|
||||
// Timestamp is captured right now to avoid problems
|
||||
// with updates in between
|
||||
var qts = Date.now();
|
||||
if (typeof response.error === 'undefined') {
|
||||
var updateList = response.data[0].fql_result_set;
|
||||
var removeList = response.data[1].fql_result_set;
|
||||
// removeList = [{target_id: '100001127136581'}];
|
||||
|
||||
var theData = {
|
||||
totalToChange: updateList.length + removeList.length,
|
||||
queryTimestamp: qts
|
||||
};
|
||||
|
||||
if (!withData) {
|
||||
if (response.data[2] &&
|
||||
Array.isArray(response.data[2].fql_result_set)) {
|
||||
var friendCount = response.data[2].fql_result_set.length;
|
||||
theData.newFriendNumber = friendCount;
|
||||
}
|
||||
}
|
||||
|
||||
wutils.postMessage({
|
||||
type: 'totals',
|
||||
data: theData
|
||||
});
|
||||
|
||||
syncUpdatedFriends(updateList);
|
||||
syncRemovedFriends(removeList);
|
||||
}
|
||||
else {
|
||||
postError(response.error);
|
||||
}
|
||||
}
|
||||
|
||||
function syncRemovedFriends(removedFriends) {
|
||||
debug('Friends to be removed: ', removedFriends.length);
|
||||
|
||||
// Simply an iteration over the collection is done and a message passed
|
||||
removedFriends.forEach(function(aremoved) {
|
||||
var removedRef = uids[aremoved.target_id];
|
||||
|
||||
if (removedRef) {
|
||||
wutils.postMessage({
|
||||
type: 'friendRemoved',
|
||||
data: {
|
||||
uid: aremoved.target_id,
|
||||
contactId: removedRef.contactId
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}); // forEach
|
||||
}
|
||||
|
||||
|
||||
function syncUpdatedFriends(updatedFriends) {
|
||||
debug('Friends to be updated: ', updatedFriends.length);
|
||||
|
||||
// Friends which image has to be updated
|
||||
var friendsImgToBeUpdated = {};
|
||||
|
||||
updatedFriends.forEach(function(afriend) {
|
||||
var friendInfo = forceUpdateUids[afriend.uid] || uids[afriend.uid];
|
||||
|
||||
if (!friendInfo) {
|
||||
debug('The uid provided is unknown. Doing nothing');
|
||||
return;
|
||||
}
|
||||
|
||||
if (afriend.pic_big !== friendInfo.photoUrl) {
|
||||
// Photo changed
|
||||
debug('Contact Photo Changed!!! for ', afriend.uid);
|
||||
friendsImgToBeUpdated[afriend.uid] = afriend;
|
||||
}
|
||||
else {
|
||||
debug('Contact Photo unchanged for ', afriend.uid);
|
||||
wutils.postMessage({
|
||||
type: 'friendUpdated',
|
||||
data: {
|
||||
updatedFbData: afriend,
|
||||
contactId: friendInfo.contactId
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
debug('Worker terminated processing updates');
|
||||
|
||||
var friendImgList = Object.keys(friendsImgToBeUpdated);
|
||||
|
||||
if (friendImgList.length > 0) {
|
||||
debug('Now starting synch for ', friendImgList.length, ' images');
|
||||
|
||||
// Now it is time to download the images needed
|
||||
var imgSync = new ImgSynchronizer(friendImgList);
|
||||
|
||||
imgSync.start();
|
||||
|
||||
// Once an image is ready friend update is notified
|
||||
imgSync.onimageready = function(uid, blob) {
|
||||
var friendData;
|
||||
if (blob) {
|
||||
debug('Image retrieved correctly for ', uid);
|
||||
|
||||
friendData = friendsImgToBeUpdated[uid];
|
||||
friendData.fbInfo = {};
|
||||
friendData.fbInfo.photo = [blob];
|
||||
fb.setFriendPictureUrl(friendData.fbInfo, friendData.pic_big);
|
||||
}
|
||||
else {
|
||||
self.console.error('Img for UID', uid, ' could not be retrieved ');
|
||||
// This friend has to be marked in a special state just to be
|
||||
// synced later on
|
||||
friendData = friendsImgToBeUpdated[uid];
|
||||
friendData.fbInfo = {};
|
||||
friendData.fbInfo.photo = [];
|
||||
// TODO: This should only remove the URL of the profile picture
|
||||
friendData.fbInfo.url = [];
|
||||
}
|
||||
|
||||
var contact = uids[uid] || forceUpdateUids[uid];
|
||||
|
||||
wutils.postMessage({
|
||||
type: 'friendUpdated',
|
||||
data: {
|
||||
updatedFbData: friendData,
|
||||
contactId: contact.contactId
|
||||
}
|
||||
});
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// For dealing with the case that only new imgs have to be retrieved
|
||||
function getNewImgsForFriends(friendList) {
|
||||
debug('Getting new imgs for friends', JSON.stringify(friendList));
|
||||
|
||||
var imgSync = new ImgSynchronizer(friendList);
|
||||
|
||||
imgSync.start();
|
||||
|
||||
// Once an image is ready friend update is notified
|
||||
imgSync.onimageready = function(uid, blob) {
|
||||
self.console.log('Img Ready from worker');
|
||||
|
||||
if (!blob) {
|
||||
self.console.error('Img for UID: ', uid, ' could not be retrieved ');
|
||||
}
|
||||
|
||||
wutils.postMessage({
|
||||
type: 'friendImgReady',
|
||||
data: {
|
||||
photo: blob,
|
||||
contactId: uids[uid].contactId
|
||||
}
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
var ImgSynchronizer = function(friends) {
|
||||
var next = 0;
|
||||
var self = this;
|
||||
|
||||
this.friends = friends;
|
||||
|
||||
this.start = function() {
|
||||
retrieveImg(this.friends[next]);
|
||||
};
|
||||
|
||||
function imgRetrieved(blob) {
|
||||
if (typeof self.onimageready === 'function') {
|
||||
var uid = self.friends[next];
|
||||
|
||||
wutils.setTimeout(function() {
|
||||
self.onimageready(uid, blob);
|
||||
},0);
|
||||
}
|
||||
|
||||
// And lets go for the next
|
||||
next++;
|
||||
if (next < self.friends.length) {
|
||||
retrieveImg(self.friends[next]);
|
||||
}
|
||||
}
|
||||
|
||||
function retrieveImg(uid) {
|
||||
fb.utils.getFriendPicture(uid, imgRetrieved, access_token,
|
||||
targetPictureSize);
|
||||
}
|
||||
};
|
||||
|
||||
})(self);
|
||||
Loading…
Reference in a new issue