Bug 993584 - Initial landing for CloudSync. r=rnewman

This commit is contained in:
Alan K 2014-09-04 21:44:00 +02:00
parent e18af3bc41
commit 635f49e75e
28 changed files with 2821 additions and 53 deletions

View File

@ -4,10 +4,22 @@
const Cu = Components.utils;
Cu.import("resource://services-common/utils.js");
Cu.import("resource://services-sync/main.js");
Cu.import("resource:///modules/PlacesUIUtils.jsm");
Cu.import("resource://gre/modules/PlacesUtils.jsm", this);
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "Promise",
"resource://gre/modules/Promise.jsm");
#ifdef MOZ_SERVICES_CLOUDSYNC
XPCOMUtils.defineLazyModuleGetter(this, "CloudSync",
"resource://gre/modules/CloudSync.jsm");
#else
let CloudSync = null;
#endif
let RemoteTabViewer = {
_tabsList: null,
@ -16,6 +28,8 @@ let RemoteTabViewer = {
Services.obs.addObserver(this, "weave:service:login:finish", false);
Services.obs.addObserver(this, "weave:engine:sync:finish", false);
Services.obs.addObserver(this, "cloudsync:tabs:update", false);
this._tabsList = document.getElementById("tabsList");
this.buildList(true);
@ -24,63 +38,62 @@ let RemoteTabViewer = {
uninit: function () {
Services.obs.removeObserver(this, "weave:service:login:finish");
Services.obs.removeObserver(this, "weave:engine:sync:finish");
Services.obs.removeObserver(this, "cloudsync:tabs:update");
},
buildList: function(force) {
if (!Weave.Service.isLoggedIn || !this._refetchTabs(force))
return;
//XXXzpao We should say something about not being logged in & not having data
// or tell the appropriate condition. (bug 583344)
this._generateTabList();
},
createItem: function(attrs) {
createItem: function (attrs) {
let item = document.createElement("richlistitem");
// Copy the attributes from the argument into the item
for (let attr in attrs)
// Copy the attributes from the argument into the item.
for (let attr in attrs) {
item.setAttribute(attr, attrs[attr]);
}
if (attrs["type"] == "tab")
if (attrs["type"] == "tab") {
item.label = attrs.title != "" ? attrs.title : attrs.url;
}
return item;
},
filterTabs: function(event) {
filterTabs: function (event) {
let val = event.target.value.toLowerCase();
let numTabs = this._tabsList.getRowCount();
let clientTabs = 0;
let currentClient = null;
for (let i = 0;i < numTabs;i++) {
for (let i = 0; i < numTabs; i++) {
let item = this._tabsList.getItemAtIndex(i);
let hide = false;
if (item.getAttribute("type") == "tab") {
if (!item.getAttribute("url").toLowerCase().contains(val) &&
!item.getAttribute("title").toLowerCase().contains(val))
!item.getAttribute("title").toLowerCase().contains(val)) {
hide = true;
else
} else {
clientTabs++;
}
}
else if (item.getAttribute("type") == "client") {
if (currentClient) {
if (clientTabs == 0)
if (clientTabs == 0) {
currentClient.hidden = true;
}
}
currentClient = item;
clientTabs = 0;
}
item.hidden = hide;
}
if (clientTabs == 0)
if (clientTabs == 0) {
currentClient.hidden = true;
}
},
openSelected: function() {
openSelected: function () {
let items = this._tabsList.selectedItems;
let urls = [];
for (let i = 0;i < items.length;i++) {
for (let i = 0; i < items.length; i++) {
if (items[i].getAttribute("type") == "tab") {
urls.push(items[i].getAttribute("url"));
let index = this._tabsList.getIndexOfItem(items[i]);
@ -93,7 +106,7 @@ let RemoteTabViewer = {
}
},
bookmarkSingleTab: function() {
bookmarkSingleTab: function () {
let item = this._tabsList.selectedItems[0];
let uri = Weave.Utils.makeURI(item.getAttribute("url"));
let title = item.getAttribute("title");
@ -108,14 +121,15 @@ let RemoteTabViewer = {
}, window.top);
},
bookmarkSelectedTabs: function() {
bookmarkSelectedTabs: function () {
let items = this._tabsList.selectedItems;
let URIs = [];
for (let i = 0;i < items.length;i++) {
for (let i = 0; i < items.length; i++) {
if (items[i].getAttribute("type") == "tab") {
let uri = Weave.Utils.makeURI(items[i].getAttribute("url"));
if (!uri)
if (!uri) {
continue;
}
URIs.push(uri);
}
@ -133,7 +147,7 @@ let RemoteTabViewer = {
try {
let iconURI = Weave.Utils.makeURI(iconUri);
return PlacesUtils.favicons.getFaviconLinkForIcon(iconURI).spec;
} catch(ex) {
} catch (ex) {
// Do nothing.
}
@ -141,16 +155,58 @@ let RemoteTabViewer = {
return defaultIcon || PlacesUtils.favicons.defaultFavicon.spec;
},
_generateTabList: function() {
let engine = Weave.Service.engineManager.get("tabs");
_waitingForBuildList: false,
_buildListRequested: false,
buildList: function (force) {
if (this._waitingForBuildList) {
this._buildListRequested = true;
return;
}
this._waitingForBuildList = true;
this._buildListRequested = false;
this._clearTabList();
if (Weave.Service.isLoggedIn && this._refetchTabs(force)) {
this._generateWeaveTabList();
} else {
//XXXzpao We should say something about not being logged in & not having data
// or tell the appropriate condition. (bug 583344)
}
function complete() {
this._waitingForBuildList = false;
if (this._buildListRequested) {
CommonUtils.nextTick(this.buildList, this);
}
}
if (CloudSync && CloudSync.ready && CloudSync().tabsReady && CloudSync().tabs.hasRemoteTabs()) {
this._generateCloudSyncTabList()
.then(complete, complete);
} else {
complete();
}
},
_clearTabList: function () {
let list = this._tabsList;
// clear out existing richlistitems
// Clear out existing richlistitems.
let count = list.getRowCount();
if (count > 0) {
for (let i = count - 1; i >= 0; i--)
for (let i = count - 1; i >= 0; i--) {
list.removeItemAt(i);
}
}
},
_generateWeaveTabList: function () {
let engine = Weave.Service.engineManager.get("tabs");
let list = this._tabsList;
let seenURLs = new Set();
let localURLs = engine.getOpenURLs();
@ -189,7 +245,37 @@ let RemoteTabViewer = {
}
},
adjustContextMenu: function(event) {
_generateCloudSyncTabList: function () {
let updateTabList = function (remoteTabs) {
let list = this._tabsList;
for each (let client in remoteTabs) {
let clientAttrs = {
type: "client",
clientName: client.name,
};
let clientEnt = this.createItem(clientAttrs);
list.appendChild(clientEnt);
for (let tab of client.tabs) {
let tabAttrs = {
type: "tab",
title: tab.title,
url: tab.url,
icon: this.getIcon(tab.icon),
};
let tabEnt = this.createItem(tabAttrs);
list.appendChild(tabEnt);
}
}
}.bind(this);
return CloudSync().tabs.getRemoteTabs()
.then(updateTabList, Promise.reject);
},
adjustContextMenu: function (event) {
let mode = "all";
switch (this._tabsList.selectedItems.length) {
case 0:
@ -201,33 +287,40 @@ let RemoteTabViewer = {
mode = "multiple";
break;
}
let menu = document.getElementById("tabListContext");
let el = menu.firstChild;
while (el) {
let showFor = el.getAttribute("showFor");
if (showFor)
if (showFor) {
el.hidden = showFor != mode && showFor != "all";
}
el = el.nextSibling;
}
},
_refetchTabs: function(force) {
_refetchTabs: function (force) {
if (!force) {
// Don't bother refetching tabs if we already did so recently
let lastFetch = 0;
try {
lastFetch = Services.prefs.getIntPref("services.sync.lastTabFetch");
}
catch (e) { /* Just use the default value of 0 */ }
let now = Math.floor(Date.now() / 1000);
if (now - lastFetch < 30)
return false;
catch (e) {
/* Just use the default value of 0 */
}
// if Clients hasn't synced yet this session, need to sync it as well
if (Weave.Service.clientsEngine.lastSync == 0)
let now = Math.floor(Date.now() / 1000);
if (now - lastFetch < 30) {
return false;
}
}
// if Clients hasn't synced yet this session, we need to sync it as well.
if (Weave.Service.clientsEngine.lastSync == 0) {
Weave.Service.clientsEngine.sync();
}
// Force a sync only for the tabs engine
let engine = Weave.Service.engineManager.get("tabs");
@ -239,21 +332,26 @@ let RemoteTabViewer = {
return true;
},
observe: function(subject, topic, data) {
observe: function (subject, topic, data) {
switch (topic) {
case "weave:service:login:finish":
this.buildList(true);
break;
case "weave:engine:sync:finish":
if (subject == "tabs")
this._generateTabList();
if (subject == "tabs") {
this.buildList(false);
}
break;
case "cloudsync:tabs:update":
this.buildList(false);
break;
}
},
handleClick: function(event) {
if (event.target.getAttribute("type") != "tab")
handleClick: function (event) {
if (event.target.getAttribute("type") != "tab") {
return;
}
if (event.button == 1) {
let url = event.target.getAttribute("url");

View File

@ -111,7 +111,7 @@ browser.jar:
content/browser/pageinfo/security.js (content/pageinfo/security.js)
#ifdef MOZ_SERVICES_SYNC
content/browser/sync/aboutSyncTabs.xul (content/sync/aboutSyncTabs.xul)
content/browser/sync/aboutSyncTabs.js (content/sync/aboutSyncTabs.js)
* content/browser/sync/aboutSyncTabs.js (content/sync/aboutSyncTabs.js)
content/browser/sync/aboutSyncTabs.css (content/sync/aboutSyncTabs.css)
content/browser/sync/aboutSyncTabs-bindings.xml (content/sync/aboutSyncTabs-bindings.xml)
* content/browser/sync/setup.xul (content/sync/setup.xul)

View File

@ -19,6 +19,13 @@ XPCOMUtils.defineLazyModuleGetter(this, "PluralForm",
XPCOMUtils.defineLazyModuleGetter(this, "PrivateBrowsingUtils",
"resource://gre/modules/PrivateBrowsingUtils.jsm");
#ifdef MOZ_SERVICES_CLOUDSYNC
XPCOMUtils.defineLazyModuleGetter(this, "CloudSync",
"resource://gre/modules/CloudSync.jsm");
#else
let CloudSync = null;
#endif
#ifdef MOZ_SERVICES_SYNC
XPCOMUtils.defineLazyModuleGetter(this, "Weave",
"resource://services-sync/main.js");
@ -1002,17 +1009,18 @@ this.PlacesUIUtils = {
},
shouldShowTabsFromOtherComputersMenuitem: function() {
// If Sync isn't configured yet, then don't show the menuitem.
return Weave.Status.checkSetup() != Weave.CLIENT_NOT_CONFIGURED &&
let weaveOK = Weave.Status.checkSetup() != Weave.CLIENT_NOT_CONFIGURED &&
Weave.Svc.Prefs.get("firstSync", "") != "notReady";
let cloudSyncOK = CloudSync && CloudSync.ready && CloudSync().tabsReady && CloudSync().tabs.hasRemoteTabs();
return weaveOK || cloudSyncOK;
},
shouldEnableTabsFromOtherComputersMenuitem: function() {
// The tabs engine might never be inited (if services.sync.registerEngines
// is modified), so make sure we avoid undefined errors.
return Weave.Service.isLoggedIn &&
let weaveEnabled = Weave.Service.isLoggedIn &&
Weave.Service.engineManager.get("tabs") &&
Weave.Service.engineManager.get("tabs").enabled;
let cloudSyncEnabled = CloudSync && CloudSync.ready && CloudSync().tabsReady && CloudSync().tabs.hasRemoteTabs();
return weaveEnabled || cloudSyncEnabled;
},
};

View File

@ -8336,6 +8336,12 @@ if test -n "$MOZ_SERVICES_SYNC"; then
AC_DEFINE(MOZ_SERVICES_SYNC)
fi
dnl Build Services/CloudSync if required
AC_SUBST(MOZ_SERVICES_CLOUDSYNC)
if test -n "$MOZ_SERVICES_CLOUDSYNC"; then
AC_DEFINE(MOZ_SERVICES_CLOUDSYNC)
fi
dnl Build Captive Portal Detector if required
AC_SUBST(MOZ_CAPTIVEDETECT)
if test -n "$MOZ_CAPTIVEDETECT"; then

View File

@ -0,0 +1,89 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
this.EXPORTED_SYMBOLS = ["CloudSync"];
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "Adapters",
"resource://gre/modules/CloudSyncAdapters.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "Local",
"resource://gre/modules/CloudSyncLocal.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "Bookmarks",
"resource://gre/modules/CloudSyncBookmarks.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "Tabs",
"resource://gre/modules/CloudSyncTabs.jsm");
let API_VERSION = 1;
let _CloudSync = function () {
};
_CloudSync.prototype = {
_adapters: null,
get adapters () {
if (!this._adapters) {
this._adapters = new Adapters();
}
return this._adapters;
},
_bookmarks: null,
get bookmarks () {
if (!this._bookmarks) {
this._bookmarks = new Bookmarks();
}
return this._bookmarks;
},
_local: null,
get local () {
if (!this._local) {
this._local = new Local();
}
return this._local;
},
_tabs: null,
get tabs () {
if (!this._tabs) {
this._tabs = new Tabs();
}
return this._tabs;
},
get tabsReady () {
return this._tabs ? true: false;
},
get version () {
return API_VERSION;
},
};
this.CloudSync = function CloudSync () {
return _cloudSyncInternal.instance;
};
Object.defineProperty(CloudSync, "ready", {
get: function () {
return _cloudSyncInternal.ready;
}
});
let _cloudSyncInternal = {
instance: null,
ready: false,
};
XPCOMUtils.defineLazyGetter(_cloudSyncInternal, "instance", function () {
_cloudSyncInternal.ready = true;
return new _CloudSync();
}.bind(this));

View File

@ -0,0 +1,88 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
this.EXPORTED_SYMBOLS = ["Adapters"];
Components.utils.import("resource://gre/modules/Services.jsm");
Components.utils.import("resource://gre/modules/CloudSyncEventSource.jsm");
this.Adapters = function () {
let eventTypes = [
"sync",
];
let suspended = true;
let suspend = function () {
if (!suspended) {
Services.obs.removeObserver(observer, "cloudsync:user-sync", false);
suspended = true;
}
}.bind(this);
let resume = function () {
if (suspended) {
Services.obs.addObserver(observer, "cloudsync:user-sync", false);
suspended = false;
}
}.bind(this);
let eventSource = new EventSource(eventTypes, suspend, resume);
let registeredAdapters = new Map();
function register (name, opts) {
opts = opts || {};
registeredAdapters.set(name, opts);
}
function unregister (name) {
if (!registeredAdapters.has(name)) {
throw new Error("adapter is not registered: " + name)
}
registeredAdapters.delete(name);
}
function getAdapterNames () {
let result = [];
for (let name of registeredAdapters.keys()) {
result.push(name);
}
return result;
}
function getAdapter (name) {
if (!registeredAdapters.has(name)) {
throw new Error("adapter is not registered: " + name)
}
return registeredAdapters.get(name);
}
function countAdapters () {
return registeredAdapters.size;
}
let observer = {
observe: function (subject, topic, data) {
switch (topic) {
case "cloudsync:user-sync":
eventSource.emit("sync");
break;
}
}
};
this.addEventListener = eventSource.addEventListener;
this.removeEventListener = eventSource.removeEventListener;
this.register = register.bind(this);
this.get = getAdapter.bind(this);
this.unregister = unregister.bind(this);
this.__defineGetter__("names", getAdapterNames);
this.__defineGetter__("count", countAdapters);
};
Adapters.prototype = {
};

View File

@ -0,0 +1,787 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
this.EXPORTED_SYMBOLS = ["Bookmarks"];
const Cu = Components.utils;
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://services-common/utils.js");
Cu.import("resource://services-crypto/utils.js");
Cu.import("resource://gre/modules/PlacesUtils.jsm");
Cu.import("resource:///modules/PlacesUIUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "NetUtil",
"resource://gre/modules/NetUtil.jsm");
Cu.import("resource://gre/modules/Promise.jsm");
Cu.import("resource://gre/modules/CloudSyncPlacesWrapper.jsm");
Cu.import("resource://gre/modules/CloudSyncEventSource.jsm");
Cu.import("resource://gre/modules/CloudSyncBookmarksFolderCache.jsm");
const ITEM_TYPES = [
"NULL",
"BOOKMARK",
"FOLDER",
"SEPARATOR",
"DYNAMIC_CONTAINER", // no longer used by Places, but this ID should not be used for future item types
];
const CS_UNKNOWN = 0x1;
const CS_FOLDER = 0x1 << 1;
const CS_SEPARATOR = 0x1 << 2;
const CS_QUERY = 0x1 << 3;
const CS_LIVEMARK = 0x1 << 4;
const CS_BOOKMARK = 0x1 << 5;
const EXCLUDE_BACKUP_ANNO = "places/excludeFromBackup";
const DATA_VERSION = 1;
function asyncCallback(ctx, func, args) {
function invoke() {
func.apply(ctx, args);
}
CommonUtils.nextTick(invoke);
}
let Record = function (params) {
this.id = params.guid;
this.parent = params.parent || null;
this.index = params.position;
this.title = params.title;
this.dateAdded = Math.floor(params.dateAdded/1000);
this.lastModified = Math.floor(params.lastModified/1000);
this.uri = params.url;
let annos = params.annos || {};
Object.defineProperty(this, "annos", {
get: function () {
return annos;
},
enumerable: false
});
switch (params.type) {
case PlacesUtils.bookmarks.TYPE_FOLDER:
if (PlacesUtils.LMANNO_FEEDURI in annos) {
this.type = CS_LIVEMARK;
this.feed = annos[PlacesUtils.LMANNO_FEEDURI];
this.site = annos[PlacesUtils.LMANNO_SITEURI];
} else {
this.type = CS_FOLDER;
}
break;
case PlacesUtils.bookmarks.TYPE_BOOKMARK:
if (this.uri.startsWith("place:")) {
this.type = CS_QUERY;
} else {
this.type = CS_BOOKMARK;
}
break;
case PlacesUtils.bookmarks.TYPE_SEPARATOR:
this.type = CS_SEPARATOR;
break;
default:
this.type = CS_UNKNOWN;
}
};
Record.prototype = {
version: DATA_VERSION,
};
let Bookmarks = function () {
let createRootFolder = function (name) {
let ROOT_FOLDER_ANNO = "cloudsync/rootFolder/" + name;
let ROOT_SHORTCUT_ANNO = "cloudsync/rootShortcut/" + name;
let deferred = Promise.defer();
let placesRootId = PlacesUtils.placesRootId;
let rootFolderId;
let rootShortcutId;
function createAdapterShortcut(result) {
rootFolderId = result;
let uri = "place:folder=" + rootFolderId;
return PlacesWrapper.insertBookmark(PlacesUIUtils.allBookmarksFolderId, uri,
PlacesUtils.bookmarks.DEFAULT_INDEX, name);
}
function setRootFolderCloudSyncAnnotation(result) {
rootShortcutId = result;
return PlacesWrapper.setItemAnnotation(rootFolderId, ROOT_FOLDER_ANNO,
1, 0, PlacesUtils.annotations.EXPIRE_NEVER);
}
function setRootShortcutCloudSyncAnnotation() {
return PlacesWrapper.setItemAnnotation(rootShortcutId, ROOT_SHORTCUT_ANNO,
1, 0, PlacesUtils.annotations.EXPIRE_NEVER);
}
function setRootFolderExcludeFromBackupAnnotation() {
return PlacesWrapper.setItemAnnotation(rootFolderId, EXCLUDE_BACKUP_ANNO,
1, 0, PlacesUtils.annotations.EXPIRE_NEVER);
}
function finish() {
deferred.resolve(rootFolderId);
}
Promise.resolve(PlacesUtils.bookmarks.createFolder(placesRootId, name, PlacesUtils.bookmarks.DEFAULT_INDEX))
.then(createAdapterShortcut)
.then(setRootFolderCloudSyncAnnotation)
.then(setRootShortcutCloudSyncAnnotation)
.then(setRootFolderExcludeFromBackupAnnotation)
.then(finish, deferred.reject);
return deferred.promise;
};
let getRootFolder = function (name) {
let ROOT_FOLDER_ANNO = "cloudsync/rootFolder/" + name;
let ROOT_SHORTCUT_ANNO = "cloudsync/rootShortcut/" + name;
let deferred = Promise.defer();
function checkRootFolder(folderIds) {
if (!folderIds.length) {
return createRootFolder(name);
}
return Promise.resolve(folderIds[0]);
}
function createFolderObject(folderId) {
return new RootFolder(folderId, name);
}
PlacesWrapper.getLocalIdsWithAnnotation(ROOT_FOLDER_ANNO)
.then(checkRootFolder, deferred.reject)
.then(createFolderObject)
.then(deferred.resolve, deferred.reject);
return deferred.promise;
};
let deleteRootFolder = function (name) {
let ROOT_FOLDER_ANNO = "cloudsync/rootFolder/" + name;
let ROOT_SHORTCUT_ANNO = "cloudsync/rootShortcut/" + name;
let deferred = Promise.defer();
let placesRootId = PlacesUtils.placesRootId;
function getRootShortcutId() {
return PlacesWrapper.getLocalIdsWithAnnotation(ROOT_SHORTCUT_ANNO);
}
function deleteShortcut(shortcutIds) {
if (!shortcutIds.length) {
return Promise.resolve();
}
return PlacesWrapper.removeItem(shortcutIds[0]);
}
function getRootFolderId() {
return PlacesWrapper.getLocalIdsWithAnnotation(ROOT_FOLDER_ANNO);
}
function deleteFolder(folderIds) {
let deleteFolderDeferred = Promise.defer();
if (!folderIds.length) {
return Promise.resolve();
}
let rootFolderId = folderIds[0];
PlacesWrapper.removeFolderChildren(rootFolderId).then(
function () {
return PlacesWrapper.removeItem(rootFolderId);
}
).then(deleteFolderDeferred.resolve, deleteFolderDeferred.reject);
return deleteFolderDeferred.promise;
}
getRootShortcutId().then(deleteShortcut)
.then(getRootFolderId)
.then(deleteFolder)
.then(deferred.resolve, deferred.reject);
return deferred.promise;
};
/* PUBLIC API */
this.getRootFolder = getRootFolder.bind(this);
this.deleteRootFolder = deleteRootFolder.bind(this);
};
this.Bookmarks = Bookmarks;
let RootFolder = function (rootId, rootName) {
let suspended = true;
let ignoreAll = false;
let suspend = function () {
if (!suspended) {
PlacesUtils.bookmarks.removeObserver(observer);
suspended = true;
}
}.bind(this);
let resume = function () {
if (suspended) {
PlacesUtils.bookmarks.addObserver(observer, false);
suspended = false;
}
}.bind(this);
let eventTypes = [
"add",
"remove",
"change",
"move",
];
let eventSource = new EventSource(eventTypes, suspend, resume);
let folderCache = new FolderCache;
folderCache.insert(rootId, null);
let getCachedFolderIds = function (cache, roots) {
let nodes = [...roots];
let results = [];
while (nodes.length) {
let node = nodes.shift();
results.push(node);
let children = cache.getChildren(node);
nodes = nodes.concat([...children]);
}
return results;
};
let getLocalItems = function () {
let deferred = Promise.defer();
let folders = getCachedFolderIds(folderCache, folderCache.getChildren(rootId));
function getFolders(ids) {
let types = [
PlacesUtils.bookmarks.TYPE_FOLDER,
];
return PlacesWrapper.getItemsById(ids, types);
}
function getContents(parents) {
parents.push(rootId);
let types = [
PlacesUtils.bookmarks.TYPE_BOOKMARK,
PlacesUtils.bookmarks.TYPE_SEPARATOR,
];
return PlacesWrapper.getItemsByParentId(parents, types)
}
function getParentGuids(results) {
results = Array.prototype.concat.apply([], results);
let promises = [];
results.map(function (result) {
let promise = PlacesWrapper.localIdToGuid(result.parent).then(
function (guidResult) {
result.parent = guidResult;
return Promise.resolve(result);
},
Promise.reject
);
promises.push(promise);
});
return Promise.all(promises);
}
function getAnnos(results) {
results = Array.prototype.concat.apply([], results);
let promises = [];
results.map(function (result) {
let promise = PlacesWrapper.getItemAnnotationsForLocalId(result.id).then(
function (annos) {
result.annos = annos;
return Promise.resolve(result);
},
Promise.reject
);
promises.push(promise);
});
return Promise.all(promises);
}
let promises = [
getFolders(folders),
getContents(folders),
];
Promise.all(promises)
.then(getParentGuids)
.then(getAnnos)
.then(function (results) {
results = results.map((result) => new Record(result));
deferred.resolve(results);
},
deferred.reject);
return deferred.promise;
};
let getLocalItemsById = function (guids) {
let deferred = Promise.defer();
let types = [
PlacesUtils.bookmarks.TYPE_BOOKMARK,
PlacesUtils.bookmarks.TYPE_FOLDER,
PlacesUtils.bookmarks.TYPE_SEPARATOR,
PlacesUtils.bookmarks.TYPE_DYNAMIC_CONTAINER,
];
function getParentGuids(results) {
let promises = [];
results.map(function (result) {
let promise = PlacesWrapper.localIdToGuid(result.parent).then(
function (guidResult) {
result.parent = guidResult;
return Promise.resolve(result);
},
Promise.reject
);
promises.push(promise);
});
return Promise.all(promises);
}
PlacesWrapper.getItemsByGuid(guids, types)
.then(getParentGuids)
.then(function (results) {
results = results.map((result) => new Record(result));
deferred.resolve(results);
},
deferred.reject);
return deferred.promise;
};
let _createItem = function (item) {
let deferred = Promise.defer();
function getFolderId() {
if (item.parent) {
return PlacesWrapper.guidToLocalId(item.parent);
}
return Promise.resolve(rootId);
}
function create(folderId) {
let deferred = Promise.defer();
if (!folderId) {
folderId = rootId;
}
let index = item.hasOwnProperty("index") ? item.index : PlacesUtils.bookmarks.DEFAULT_INDEX;
function complete(localId) {
folderCache.insert(localId, folderId);
deferred.resolve(localId);
}
switch (item.type) {
case CS_BOOKMARK:
case CS_QUERY:
PlacesWrapper.insertBookmark(folderId, item.uri, index, item.title, item.id)
.then(complete, deferred.reject);
break;
case CS_FOLDER:
PlacesWrapper.createFolder(folderId, item.title, index, item.id)
.then(complete, deferred.reject);
break;
case CS_SEPARATOR:
PlacesWrapper.insertSeparator(folderId, index, item.id)
.then(complete, deferred.reject);
break;
case CS_LIVEMARK:
let livemark = {
title: item.title,
parentId: folderId,
index: item.index,
feedURI: item.feed,
siteURI: item.site,
guid: item.id,
};
PlacesUtils.livemarks.addLivemark(livemark)
.then(complete, deferred.reject);
break;
default:
deferred.reject("invalid item type: " + item.type);
}
return deferred.promise;
}
getFolderId().then(create)
.then(deferred.resolve, deferred.reject);
return deferred.promise;
};
let _deleteItem = function (item) {
let deferred = Promise.defer();
PlacesWrapper.guidToLocalId(item.id).then(
function (localId) {
folderCache.remove(localId);
return PlacesWrapper.removeItem(localId);
}
).then(deferred.resolve, deferred.reject);
return deferred.promise;
};
let _updateItem = function (item) {
let deferred = Promise.defer();
PlacesWrapper.guidToLocalId(item.id).then(
function (localId) {
let promises = [];
if (item.hasOwnProperty("dateAdded")) {
promises.push(PlacesWrapper.setItemDateAdded(localId, item.dateAdded));
}
if (item.hasOwnProperty("lastModified")) {
promises.push(PlacesWrapper.setItemLastModified(localId, item.lastModified));
}
if ((CS_BOOKMARK | CS_FOLDER) & item.type && item.hasOwnProperty("title")) {
promises.push(PlacesWrapper.setItemTitle(localId, item.title));
}
if (CS_BOOKMARK & item.type && item.hasOwnProperty("uri")) {
promises.push(PlacesWrapper.changeBookmarkURI(localId, item.uri));
}
if (item.hasOwnProperty("parent")) {
let deferred = Promise.defer();
PlacesWrapper.guidToLocalId(item.parent)
.then(
function (parent) {
let index = item.hasOwnProperty("index") ? item.index : PlacesUtils.bookmarks.DEFAULT_INDEX;
if (CS_FOLDER & item.type) {
folderCache.setParent(localId, parent);
}
return PlacesWrapper.moveItem(localId, parent, index);
}
)
.then(deferred.resolve, deferred.reject);
promises.push(deferred.promise);
}
if (item.hasOwnProperty("index") && !item.hasOwnProperty("parent")) {
promises.push(PlacesWrapper.bookmarks.setItemIndex(localId, item.index));
}
Promise.all(promises)
.then(deferred.resolve, deferred.reject);
}
);
return deferred.promise;
};
let mergeRemoteItems = function (items) {
ignoreAll = true;
let deferred = Promise.defer();
let newFolders = {};
let newItems = [];
let updatedItems = [];
let deletedItems = [];
let sortItems = function () {
let promises = [];
let exists = function (item) {
let existsDeferred = Promise.defer();
if (!item.id) {
Object.defineProperty(item, "__exists__", {
value: false,
enumerable: false
});
existsDeferred.resolve(item);
} else {
PlacesWrapper.guidToLocalId(item.id).then(
function (localId) {
Object.defineProperty(item, "__exists__", {
value: localId ? true : false,
enumerable: false
});
existsDeferred.resolve(item);
},
existsDeferred.reject
);
}
return existsDeferred.promise;
}
let handleSortedItem = function (item) {
if (!item.__exists__ && !item.deleted) {
if (CS_FOLDER == item.type) {
newFolders[item.id] = item;
item._children = [];
} else {
newItems.push(item);
}
} else if (item.__exists__ && item.deleted) {
deletedItems.push(item);
} else if (item.__exists__) {
updatedItems.push(item);
}
}
for each (let item in items) {
if (!item || 'object' !== typeof(item)) {
continue;
}
let promise = exists(item).then(handleSortedItem, Promise.reject);
promises.push(promise);
}
return Promise.all(promises);
}
let processNewFolders = function () {
let newFolderGuids = Object.keys(newFolders);
let newFolderRoots = [];
let promises = [];
for each (let guid in newFolderGuids) {
let item = newFolders[guid];
if (item.parent && newFolderGuids.indexOf(item.parent) >= 0) {
let parent = newFolders[item.parent];
parent._children.push(item.id);
} else {
newFolderRoots.push(guid);
}
};
let promises = [];
for each (let guid in newFolderRoots) {
let root = newFolders[guid];
let promise = Promise.resolve();
promise = promise.then(
function () {
return _createItem(root);
},
Promise.reject
);
let items = [].concat(root._children);
while (items.length) {
let item = newFolders[items.shift()];
items = items.concat(item._children);
promise = promise.then(
function () {
return _createItem(item);
},
Promise.reject
);
}
promises.push(promise);
}
return Promise.all(promises);
}
let processItems = function () {
let promises = [];
for each (let item in newItems) {
promises.push(_createItem(item));
}
for each (let item in updatedItems) {
promises.push(_updateItem(item));
}
for each (let item in deletedItems) {
_deleteItem(item);
}
return Promise.all(promises);
}
sortItems().then(processNewFolders)
.then(processItems)
.then(function () {
ignoreAll = false;
deferred.resolve(items);
},
function (err) {
ignoreAll = false;
deferred.reject(err);
});
return deferred.promise;
};
let ignore = function (id, parent) {
if (ignoreAll) {
return true;
}
if (rootId == parent || folderCache.has(parent)) {
return false;
}
return true;
};
let handleItemAdded = function (id, parent, index, type, uri, title, dateAdded, guid, parentGuid) {
let deferred = Promise.defer();
if (PlacesUtils.bookmarks.TYPE_FOLDER == type) {
folderCache.insert(id, parent);
}
eventSource.emit("add", guid);
deferred.resolve();
return deferred.promise;
};
let handleItemRemoved = function (id, parent, index, type, uri, guid, parentGuid) {
let deferred = Promise.defer();
if (PlacesUtils.bookmarks.TYPE_FOLDER == type) {
folderCache.remove(id);
}
eventSource.emit("remove", guid);
deferred.resolve();
return deferred.promise;
};
let handleItemChanged = function (id, property, isAnnotation, newValue, lastModified, type, parent, guid, parentGuid) {
let deferred = Promise.defer();
eventSource.emit('change', guid);
deferred.resolve();
return deferred.promise;
};
let handleItemMoved = function (id, oldParent, oldIndex, newParent, newIndex, type, guid, oldParentGuid, newParentGuid) {
let deferred = Promise.defer();
function complete() {
eventSource.emit('move', guid);
deferred.resolve();
}
if (PlacesUtils.bookmarks.TYPE_FOLDER != type) {
complete();
return deferred.promise;
}
if (folderCache.has(oldParent) && folderCache.has(newParent)) {
// Folder move inside cloudSync root, so just update parents/children.
folderCache.setParent(id, newParent);
complete();
} else if (!folderCache.has(oldParent)) {
// Folder moved in from ouside cloudSync root.
PlacesWrapper.updateCachedFolderIds(folderCache, newParent)
.then(complete, complete);
} else if (!folderCache.has(newParent)) {
// Folder moved out from inside cloudSync root.
PlacesWrapper.updateCachedFolderIds(folderCache, oldParent)
.then(complete, complete);
}
return deferred.promise;
};
let observer = {
onBeginBatchUpdate: function () {
},
onEndBatchUpdate: function () {
},
onItemAdded: function (id, parent, index, type, uri, title, dateAdded, guid, parentGuid) {
if (ignore(id, parent)) {
return;
}
asyncCallback(this, handleItemAdded, Array.prototype.slice.call(arguments));
},
onItemRemoved: function (id, parent, index, type, uri, guid, parentGuid) {
if (ignore(id, parent)) {
return;
}
asyncCallback(this, handleItemRemoved, Array.prototype.slice.call(arguments));
},
onItemChanged: function (id, property, isAnnotation, newValue, lastModified, type, parent, guid, parentGuid) {
if (ignore(id, parent)) {
return;
}
asyncCallback(this, handleItemChanged, Array.prototype.slice.call(arguments));
},
onItemMoved: function (id, oldParent, oldIndex, newParent, newIndex, type, guid, oldParentGuid, newParentGuid) {
if (ignore(id, oldParent) && ignore(id, newParent)) {
return;
}
asyncCallback(this, handleItemMoved, Array.prototype.slice.call(arguments));
}
};
/* PUBLIC API */
this.addEventListener = eventSource.addEventListener;
this.removeEventListener = eventSource.removeEventListener;
this.getLocalItems = getLocalItems.bind(this);
this.getLocalItemsById = getLocalItemsById.bind(this);
this.mergeRemoteItems = mergeRemoteItems.bind(this);
let rootGuid = null; // resolved before becoming ready (below)
this.__defineGetter__("id", function () {
return rootGuid;
});
this.__defineGetter__("name", function () {
return rootName;
});
let deferred = Promise.defer();
let getGuidForRootFolder = function () {
return PlacesWrapper.localIdToGuid(rootId);
}
PlacesWrapper.updateCachedFolderIds(folderCache, rootId)
.then(getGuidForRootFolder, getGuidForRootFolder)
.then(function (guid) {
rootGuid = guid;
deferred.resolve(this);
}.bind(this),
deferred.reject);
return deferred.promise;
};
RootFolder.prototype = {
BOOKMARK: CS_BOOKMARK,
FOLDER: CS_FOLDER,
SEPARATOR: CS_SEPARATOR,
QUERY: CS_QUERY,
LIVEMARK: CS_LIVEMARK,
};

View File

@ -0,0 +1,105 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
this.EXPORTED_SYMBOLS = ["FolderCache"];
// Cache for bookmarks folder heirarchy.
let FolderCache = function () {
this.cache = new Map();
}
FolderCache.prototype = {
has: function (id) {
return this.cache.has(id);
},
insert: function (id, parentId) {
if (this.cache.has(id)) {
return;
}
if (parentId && !(this.cache.has(parentId))) {
throw new Error("insert :: parentId not found in cache: " + parentId);
}
this.cache.set(id, {
parent: parentId || null,
children: new Set(),
});
if (parentId) {
this.cache.get(parentId).children.add(id);
}
},
remove: function (id) {
if (!(this.cache.has(id))) {
throw new Error("remote :: id not found in cache: " + id);
}
let parentId = this.cache.get(id).parent;
if (parentId) {
this.cache.get(parentId).children.delete(id);
}
for (let child of this.cache.get(id).children) {
this.cache.get(child).parent = null;
}
this.cache.delete(id);
},
setParent: function (id, parentId) {
if (!(this.cache.has(id))) {
throw new Error("setParent :: id not found in cache: " + id);
}
if (parentId && !(this.cache.has(parentId))) {
throw new Error("setParent :: parentId not found in cache: " + parentId);
}
let oldParent = this.cache.get(id).parent;
if (oldParent) {
this.cache.get(oldParent).children.delete(id);
}
this.cache.get(id).parent = parentId;
this.cache.get(parentId).children.add(id);
return true;
},
getParent: function (id) {
if (this.cache.has(id)) {
return this.cache.get(id).parent;
}
throw new Error("getParent :: id not found in cache: " + id);
},
getChildren: function (id) {
if (this.cache.has(id)) {
return this.cache.get(id).children;
}
throw new Error("getChildren :: id not found in cache: " + id);
},
setChildren: function (id, children) {
for (let child of children) {
if (!this.cache.has(child)) {
this.insert(child, id);
} else {
this.setParent(child, id);
}
}
},
dump: function () {
dump("FolderCache: " + JSON.stringify(this.cache) + "\n");
},
};
this.FolderCache = FolderCache;

View File

@ -0,0 +1,65 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
this.EXPORTED_SYMBOLS = ["EventSource"];
Components.utils.import("resource://services-common/utils.js");
let EventSource = function (types, suspendFunc, resumeFunc) {
this.listeners = new Map();
for each (let type in types) {
this.listeners.set(type, new Set());
}
this.suspend = suspendFunc || function () {};
this.resume = resumeFunc || function () {};
this.addEventListener = this.addEventListener.bind(this);
this.removeEventListener = this.removeEventListener.bind(this);
};
EventSource.prototype = {
addEventListener: function (type, listener) {
if (!this.listeners.has(type)) {
return;
}
this.listeners.get(type).add(listener);
this.resume();
},
removeEventListener: function (type, listener) {
if (!this.listeners.has(type)) {
return;
}
this.listeners.get(type).delete(listener);
if (!this.hasListeners()) {
this.suspend();
}
},
hasListeners: function () {
for (let l of this.listeners.values()) {
if (l.size > 0) {
return true;
}
}
return false;
},
emit: function (type, arg) {
if (!this.listeners.has(type)) {
return;
}
CommonUtils.nextTick(
function () {
for (let listener of this.listeners.get(type)) {
listener.call(undefined, arg);
}
},
this
);
},
};
this.EventSource = EventSource;

View File

@ -0,0 +1,87 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
this.EXPORTED_SYMBOLS = ["Local"];
const Cu = Components.utils;
const Cc = Components.classes;
const Ci = Components.interfaces;
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://services-common/stringbundle.js");
Cu.import("resource://services-common/utils.js");
Cu.import("resource://services-crypto/utils.js");
Cu.import("resource://gre/modules/Preferences.jsm");
function lazyStrings(name) {
let bundle = "chrome://weave/locale/services/" + name + ".properties";
return () => new StringBundle(bundle);
}
this.Str = {};
XPCOMUtils.defineLazyGetter(Str, "errors", lazyStrings("errors"));
XPCOMUtils.defineLazyGetter(Str, "sync", lazyStrings("sync"));
function makeGUID() {
return CommonUtils.encodeBase64URL(CryptoUtils.generateRandomBytes(9));
}
this.Local = function () {
let prefs = new Preferences("services.cloudsync.");
this.__defineGetter__("prefs", function () {
return prefs;
});
};
Local.prototype = {
get id() {
let clientId = this.prefs.get("client.GUID", "");
return clientId == "" ? this.id = makeGUID(): clientId;
},
set id(value) {
this.prefs.set("client.GUID", value);
},
get name() {
let clientName = this.prefs.get("client.name", "");
if (clientName != "") {
return clientName;
}
// Generate a client name if we don't have a useful one yet
let env = Cc["@mozilla.org/process/environment;1"]
.getService(Ci.nsIEnvironment);
let user = env.get("USER") || env.get("USERNAME");
let appName;
let brand = new StringBundle("chrome://branding/locale/brand.properties");
let brandName = brand.get("brandShortName");
try {
let syncStrings = new StringBundle("chrome://browser/locale/sync.properties");
appName = syncStrings.getFormattedString("sync.defaultAccountApplication", [brandName]);
} catch (ex) {
}
appName = appName || brandName;
let system =
// 'device' is defined on unix systems
Cc["@mozilla.org/system-info;1"].getService(Ci.nsIPropertyBag2).get("device") ||
// hostname of the system, usually assigned by the user or admin
Cc["@mozilla.org/system-info;1"].getService(Ci.nsIPropertyBag2).get("host") ||
// fall back on ua info string
Cc["@mozilla.org/network/protocol;1?name=http"].getService(Ci.nsIHttpProtocolHandler).oscpu;
return this.name = Str.sync.get("client.name2", [user, appName, system]);
},
set name(value) {
this.prefs.set("client.name", value);
},
};

View File

@ -0,0 +1,392 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
this.EXPORTED_SYMBOLS = ["PlacesWrapper"];
const {interfaces: Ci, utils: Cu} = Components;
const REASON_ERROR = Ci.mozIStorageStatementCallback.REASON_ERROR;
Cu.import("resource://gre/modules/Promise.jsm");
Cu.import("resource://gre/modules/PlacesUtils.jsm");
Cu.import("resource:///modules/PlacesUIUtils.jsm");
Cu.import("resource://services-common/utils.js");
let PlacesQueries = function () {
}
PlacesQueries.prototype = {
cachedStmts: {},
getQuery: function (queryString) {
if (queryString in this.cachedStmts) {
return this.cachedStmts[queryString];
}
let db = PlacesUtils.history.QueryInterface(Ci.nsPIPlacesDatabase).DBConnection;
return this.cachedStmts[queryString] = db.createAsyncStatement(queryString);
}
};
let PlacesWrapper = function () {
}
PlacesWrapper.prototype = {
placesQueries: new PlacesQueries(),
guidToLocalId: function (guid) {
let deferred = Promise.defer();
let stmt = "SELECT id AS item_id " +
"FROM moz_bookmarks " +
"WHERE guid = :guid";
let query = this.placesQueries.getQuery(stmt);
function getLocalId(results) {
let result = results[0] && results[0]["item_id"];
return Promise.resolve(result);
}
query.params.guid = guid.toString();
this.asyncQuery(query, ["item_id"])
.then(getLocalId, deferred.reject)
.then(deferred.resolve, deferred.reject);
return deferred.promise;
},
localIdToGuid: function (id) {
let deferred = Promise.defer();
let stmt = "SELECT guid " +
"FROM moz_bookmarks " +
"WHERE id = :item_id";
let query = this.placesQueries.getQuery(stmt);
function getGuid(results) {
let result = results[0] && results[0]["guid"];
return Promise.resolve(result);
}
query.params.item_id = id;
this.asyncQuery(query, ["guid"])
.then(getGuid, deferred.reject)
.then(deferred.resolve, deferred.reject);
return deferred.promise;
},
setGuidForLocalId: function (localId, guid) {
let deferred = Promise.defer();
let stmt = "UPDATE moz_bookmarks " +
"SET guid = :guid " +
"WHERE id = :item_id";
let query = this.placesQueries.getQuery(stmt);
query.params.guid = guid;
query.params.item_id = localId;
this.asyncQuery(query)
.then(deferred.resolve, deferred.reject);
return deferred.promise;
},
getItemsById: function (ids, types) {
let deferred = Promise.defer();
let stmt = "SELECT b.id, b.type, b.parent, b.position, b.title, b.guid, b.dateAdded, b.lastModified, p.url " +
"FROM moz_bookmarks b " +
"LEFT JOIN moz_places p ON b.fk = p.id " +
"WHERE b.id in (" + ids.join(",") + ") AND b.type in (" + types.join(",") + ")";
let db = PlacesUtils.history.QueryInterface(Ci.nsPIPlacesDatabase).DBConnection;
let query = db.createAsyncStatement(stmt);
this.asyncQuery(query, ["id", "type", "parent", "position", "title", "guid", "dateAdded", "lastModified", "url"])
.then(deferred.resolve, deferred.reject);
return deferred.promise;
},
getItemsByParentId: function (parents, types) {
let deferred = Promise.defer();
let stmt = "SELECT b.id, b.type, b.parent, b.position, b.title, b.guid, b.dateAdded, b.lastModified, p.url " +
"FROM moz_bookmarks b " +
"LEFT JOIN moz_places p ON b.fk = p.id " +
"WHERE b.parent in (" + parents.join(",") + ") AND b.type in (" + types.join(",") + ")";
let db = PlacesUtils.history.QueryInterface(Ci.nsPIPlacesDatabase).DBConnection;
let query = db.createAsyncStatement(stmt);
this.asyncQuery(query, ["id", "type", "parent", "position", "title", "guid", "dateAdded", "lastModified", "url"])
.then(deferred.resolve, deferred.reject);
return deferred.promise;
},
getItemsByGuid: function (guids, types) {
let deferred = Promise.defer();
guids = guids.map(JSON.stringify);
let stmt = "SELECT b.id, b.type, b.parent, b.position, b.title, b.guid, b.dateAdded, b.lastModified, p.url " +
"FROM moz_bookmarks b " +
"LEFT JOIN moz_places p ON b.fk = p.id " +
"WHERE b.guid in (" + guids.join(",") + ") AND b.type in (" + types.join(",") + ")";
let db = PlacesUtils.history.QueryInterface(Ci.nsPIPlacesDatabase).DBConnection;
let query = db.createAsyncStatement(stmt);
this.asyncQuery(query, ["id", "type", "parent", "position", "title", "guid", "dateAdded", "lastModified", "url"])
.then(deferred.resolve, deferred.reject);
return deferred.promise;
},
updateCachedFolderIds: function (folderCache, folder) {
let deferred = Promise.defer();
let stmt = "SELECT id, guid " +
"FROM moz_bookmarks " +
"WHERE parent = :parent_id AND type = :item_type";
let query = this.placesQueries.getQuery(stmt);
query.params.parent_id = folder;
query.params.item_type = PlacesUtils.bookmarks.TYPE_FOLDER;
this.asyncQuery(query, ["id", "guid"]).then(
function (items) {
let previousIds = folderCache.getChildren(folder);
let currentIds = new Set();
for each (let item in items) {
currentIds.add(item.id);
}
let newIds = new Set();
let missingIds = new Set();
for (let currentId of currentIds) {
if (!previousIds.has(currentId)) {
newIds.add(currentId);
}
}
for (let previousId of previousIds) {
if (!currentIds.has(previousId)) {
missingIds.add(previousId);
}
}
folderCache.setChildren(folder, currentIds);
let promises = [];
for (let newId of newIds) {
promises.push(this.updateCachedFolderIds(folderCache, newId));
}
Promise.all(promises)
.then(deferred.resolve, deferred.reject);
for (let missingId of missingIds) {
folderCache.remove(missingId);
}
}.bind(this)
);
return deferred.promise;
},
getLocalIdsWithAnnotation: function (anno) {
let deferred = Promise.defer();
let stmt = "SELECT a.item_id " +
"FROM moz_anno_attributes n " +
"JOIN moz_items_annos a ON n.id = a.anno_attribute_id " +
"WHERE n.name = :anno_name";
let query = this.placesQueries.getQuery(stmt);
query.params.anno_name = anno.toString();
this.asyncQuery(query, ["item_id"])
.then(function (items) {
let results = [];
for each(let item in items) {
results.push(item.item_id);
}
deferred.resolve(results);
},
deferred.reject);
return deferred.promise;
},
getItemAnnotationsForLocalId: function (id) {
let deferred = Promise.defer();
let stmt = "SELECT a.name, b.content " +
"FROM moz_anno_attributes a " +
"JOIN moz_items_annos b ON a.id = b.anno_attribute_id " +
"WHERE b.item_id = :item_id";
let query = this.placesQueries.getQuery(stmt);
query.params.item_id = id;
this.asyncQuery(query, ["name", "content"])
.then(function (results) {
let annos = {};
for each(let result in results) {
annos[result.name] = result.content;
}
deferred.resolve(annos);
},
deferred.reject);
return deferred.promise;
},
insertBookmark: function (parent, uri, index, title, guid) {
let parsedURI;
try {
parsedURI = CommonUtils.makeURI(uri)
} catch (e) {
return Promise.reject("unable to parse URI '" + uri + "': " + e);
}
try {
let id = PlacesUtils.bookmarks.insertBookmark(parent, parsedURI, index, title, guid);
return Promise.resolve(id);
} catch (e) {
return Promise.reject("unable to insert bookmark " + JSON.stringify(arguments) + ": " + e);
}
},
setItemAnnotation: function (item, anno, value, flags, exp) {
try {
return Promise.resolve(PlacesUtils.annotations.setItemAnnotation(item, anno, value, flags, exp));
} catch (e) {
return Promise.reject(e);
}
},
itemHasAnnotation: function (item, anno) {
try {
return Promise.resolve(PlacesUtils.annotations.itemHasAnnotation(item, anno));
} catch (e) {
return Promise.reject(e);
}
},
createFolder: function (parent, name, index, guid) {
try {
return Promise.resolve(PlacesUtils.bookmarks.createFolder(parent, name, index, guid));
} catch (e) {
return Promise.reject("unable to create folder ['" + name + "']: " + e);
}
},
removeFolderChildren: function (folder) {
try {
PlacesUtils.bookmarks.removeFolderChildren(folder);
return Promise.resolve();
} catch (e) {
return Promise.reject(e);
}
},
insertSeparator: function (parent, index, guid) {
try {
return Promise.resolve(PlacesUtils.bookmarks.insertSeparator(parent, index, guid));
} catch (e) {
return Promise.reject(e);
}
},
removeItem: function (item) {
try {
return Promise.resolve(PlacesUtils.bookmarks.removeItem(item));
} catch (e) {
return Promise.reject(e);
}
},
setItemDateAdded: function (item, dateAdded) {
try {
return Promise.resolve(PlacesUtils.bookmarks.setItemDateAdded(item, dateAdded));
} catch (e) {
return Promise.reject(e);
}
},
setItemLastModified: function (item, lastModified) {
try {
return Promise.resolve(PlacesUtils.bookmarks.setItemLastModified(item, lastModified));
} catch (e) {
return Promise.reject(e);
}
},
setItemTitle: function (item, title) {
try {
return Promise.resolve(PlacesUtils.bookmarks.setItemTitle(item, title));
} catch (e) {
return Promise.reject(e);
}
},
changeBookmarkURI: function (item, uri) {
try {
uri = CommonUtils.makeURI(uri);
return Promise.resolve(PlacesUtils.bookmarks.changeBookmarkURI(item, uri));
} catch (e) {
return Promise.reject(e);
}
},
moveItem: function (item, parent, index) {
try {
return Promise.resolve(PlacesUtils.bookmarks.moveItem(item, parent, index));
} catch (e) {
return Promise.reject(e);
}
},
setItemIndex: function (item, index) {
try {
return Promise.resolve(PlacesUtils.bookmarks.setItemIndex(item, index));
} catch (e) {
return Promise.reject(e);
}
},
asyncQuery: function (query, names) {
let deferred = Promise.defer();
let storageCallback = {
results: [],
handleResult: function (results) {
if (!names) {
return;
}
let row;
while ((row = results.getNextRow()) != null) {
let item = {};
for each (let name in names) {
item[name] = row.getResultByName(name);
}
this.results.push(item);
}
},
handleError: function (error) {
deferred.reject(error);
},
handleCompletion: function (reason) {
if (REASON_ERROR == reason) {
return;
}
deferred.resolve(this.results);
}
};
query.executeAsync(storageCallback);
return deferred.promise;
},
};
this.PlacesWrapper = new PlacesWrapper();

View File

@ -0,0 +1,319 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
this.EXPORTED_SYMBOLS = ["Tabs"];
const Cu = Components.utils;
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/CloudSyncEventSource.jsm");
Cu.import("resource://gre/modules/Promise.jsm");
Cu.import("resource://services-common/observers.js");
XPCOMUtils.defineLazyModuleGetter(this, "PrivateBrowsingUtils", "resource://gre/modules/PrivateBrowsingUtils.jsm");
XPCOMUtils.defineLazyServiceGetter(this, "Session", "@mozilla.org/browser/sessionstore;1", "nsISessionStore");
const DATA_VERSION = 1;
let ClientRecord = function (params) {
this.id = params.id;
this.name = params.name || "?";
this.tabs = new Set();
}
ClientRecord.prototype = {
version: DATA_VERSION,
update: function (params) {
if (this.id !== params.id) {
throw new Error("expected " + this.id + " to equal " + params.id);
}
this.name = params.name;
}
};
let TabRecord = function (params) {
this.url = params.url || "";
this.update(params);
};
TabRecord.prototype = {
version: DATA_VERSION,
update: function (params) {
if (this.url && this.url !== params.url) {
throw new Error("expected " + this.url + " to equal " + params.url);
}
if (params.lastUsed && params.lastUsed < this.lastUsed) {
return;
}
this.title = params.title || "";
this.icon = params.icon || "";
this.lastUsed = params.lastUsed || 0;
},
};
let TabCache = function () {
this.tabs = new Map();
this.clients = new Map();
};
TabCache.prototype = {
merge: function (client, tabs) {
if (!client || !client.id) {
return;
}
if (!tabs) {
return;
}
let cRecord;
if (this.clients.has(client.id)) {
try {
cRecord = this.clients.get(client.id);
} catch (e) {
throw new Error("unable to update client: " + e);
}
} else {
cRecord = new ClientRecord(client);
this.clients.set(cRecord.id, cRecord);
}
for each (let tab in tabs) {
if (!tab || 'object' !== typeof(tab)) {
continue;
}
let tRecord;
if (this.tabs.has(tab.url)) {
tRecord = this.tabs.get(tab.url);
try {
tRecord.update(tab);
} catch (e) {
throw new Error("unable to update tab: " + e);
}
} else {
tRecord = new TabRecord(tab);
this.tabs.set(tRecord.url, tRecord);
}
if (tab.deleted) {
cRecord.tabs.delete(tRecord);
} else {
cRecord.tabs.add(tRecord);
}
}
},
clear: function (client) {
if (client) {
this.clients.delete(client.id);
} else {
this.clients = new Map();
this.tabs = new Map();
}
},
get: function () {
let results = [];
for (let client of this.clients.values()) {
results.push(client);
}
return results;
},
isEmpty: function () {
return 0 == this.clients.size;
},
};
this.Tabs = function () {
let suspended = true;
let topics = [
"pageshow",
"TabOpen",
"TabClose",
"TabSelect",
];
let update = function (event) {
if (event.originalTarget.linkedBrowser) {
let win = event.originalTarget.linkedBrowser.contentWindow;
if (PrivateBrowsingUtils.isWindowPrivate(win) &&
!PrivateBrowsingUtils.permanentPrivateBrowsing) {
return;
}
}
eventSource.emit("change");
};
let registerListenersForWindow = function (window) {
for each (let topic in topics) {
window.addEventListener(topic, update, false);
}
window.addEventListener("unload", unregisterListeners, false);
};
let unregisterListenersForWindow = function (window) {
window.removeEventListener("unload", unregisterListeners, false);
for each (let topic in topics) {
window.removeEventListener(topic, update, false);
}
};
let unregisterListeners = function (event) {
unregisterListenersForWindow(event.target);
};
let observer = {
observe: function (subject, topic, data) {
switch (topic) {
case "domwindowopened":
let onLoad = () => {
subject.removeEventListener("load", onLoad, false);
// Only register after the window is done loading to avoid unloads.
registerListenersForWindow(subject);
};
// Add tab listeners now that a window has opened.
subject.addEventListener("load", onLoad, false);
break;
}
}
};
let resume = function () {
if (suspended) {
Observers.add("domwindowopened", observer);
let wins = Services.wm.getEnumerator("navigator:browser");
while (wins.hasMoreElements()) {
registerListenersForWindow(wins.getNext());
}
}
}.bind(this);
let suspend = function () {
if (!suspended) {
Observers.remove("domwindowopened", observer);
let wins = Services.wm.getEnumerator("navigator:browser");
while (wins.hasMoreElements()) {
unregisterListenersForWindow(wins.getNext());
}
}
}.bind(this);
let eventTypes = [
"change",
];
let eventSource = new EventSource(eventTypes, suspend, resume);
let tabCache = new TabCache();
let getWindowEnumerator = function () {
return Services.wm.getEnumerator("navigator:browser");
};
let shouldSkipWindow = function (win) {
return win.closed ||
PrivateBrowsingUtils.isWindowPrivate(win);
};
let getTabState = function (tab) {
return JSON.parse(Session.getTabState(tab));
};
let getLocalTabs = function (filter) {
let deferred = Promise.defer();
filter = (undefined === filter) ? true : filter;
let filteredUrls = new RegExp("^(about:.*|chrome://weave/.*|wyciwyg:.*|file:.*)$"); // FIXME: should be a pref (B#1044304)
let allTabs = [];
let currentState = JSON.parse(Session.getBrowserState());
currentState.windows.forEach(function (window) {
if (window.isPrivate) {
return;
}
window.tabs.forEach(function (tab) {
if (!tab.entries.length) {
return;
}
// Get only the latest entry
// FIXME: support full history (B#1044306)
let entry = tab.entries[tab.index - 1];
if (!entry.url || filter && filteredUrls.test(entry.url)) {
return;
}
allTabs.push(new TabRecord({
title: entry.title,
url: entry.url,
icon: tab.attributes && tab.attributes.image || "",
lastUsed: tab.lastAccessed,
}));
});
});
deferred.resolve(allTabs);
return deferred.promise;
};
let mergeRemoteTabs = function (client, tabs) {
let deferred = Promise.defer();
deferred.resolve(tabCache.merge(client, tabs));
Observers.notify("cloudsync:tabs:update");
return deferred.promise;
};
let clearRemoteTabs = function (client) {
let deferred = Promise.defer();
deferred.resolve(tabCache.clear(client));
Observers.notify("cloudsync:tabs:update");
return deferred.promise;
};
let getRemoteTabs = function () {
let deferred = Promise.defer();
deferred.resolve(tabCache.get());
return deferred.promise;
};
let hasRemoteTabs = function () {
return !tabCache.isEmpty();
};
/* PUBLIC API */
this.addEventListener = eventSource.addEventListener;
this.removeEventListener = eventSource.removeEventListener;
this.getLocalTabs = getLocalTabs.bind(this);
this.mergeRemoteTabs = mergeRemoteTabs.bind(this);
this.clearRemoteTabs = clearRemoteTabs.bind(this);
this.getRemoteTabs = getRemoteTabs.bind(this);
this.hasRemoteTabs = hasRemoteTabs.bind(this);
};
Tabs.prototype = {
};
this.Tabs = Tabs;

View File

@ -0,0 +1,234 @@
### Importing the JS module
````
Cu.import("resource://gre/modules/CloudSync.jsm");
let cloudSync = CloudSync();
console.log(cloudSync); // Module is imported
````
### cloudSync.local
#### id
Local device ID. Is unique.
````
let localId = cloudSync.local.id;
````
#### name
Local device name.
````
let localName = cloudSync.local.name;
````
### CloudSync.tabs
#### addEventListener(type, callback)
Add an event handler for Tabs events. Valid type is `change`. The callback receives no arguments.
````
function handleTabChange() {
// Tabs have changed.
}
cloudSync.tabs.addEventListener("change", handleTabChange);
````
Change events are emitted when a tab is opened or closed, when a tab is selected, or when the page changes for an open tab.
#### removeEventListener(type, callback)
Remove an event handler. Pass the type and function that were passed to addEventListener.
````
cloudSync.tabs.removeEventListener("change", handleTabChange);
````
#### mergeRemoteTabs(client, tabs)
Merge remote tabs from upstream by updating existing items, adding new tabs, and deleting existing tabs. Accepts a client and a list of tabs. Returns a promise.
````
let remoteClient = {
id: "fawe78",
name: "My Firefox client",
};
let remoteTabs = [
{title: "Google",
url: "https://www.google.com",
icon: "https://www.google.com/favicon.ico",
lastUsed: 1400799296192},
{title: "Reddit",
url: "http://www.reddit.com",
icon: "http://www.reddit.com/favicon.ico",
lastUsed: 1400799296192
deleted: true},
];
cloudSync.tabs.mergeRemoteTabs(client, tabs).then(
function() {
console.log("merge complete");
}
);
````
#### getLocalTabs()
Returns a promise. Passes a list of local tabs when complete.
````
cloudSync.tabs.getLocalTabs().then(
function(tabs) {
console.log(JSON.stringify(tabs));
}
);
````
#### clearRemoteTabs(client)
Clears all tabs for a remote client.
````
let remoteClient = {
id: "fawe78",
name: "My Firefox client",
};
cloudSync.tabs.clearRemoteTabs(client);
````
### cloudSync.bookmarks
#### getRootFolder(name)
Gets the named root folder, creating it if it doesn't exist. The root folder object has a number of methods (see the next section for details).
````
cloudSync.bookmarks.getRootFolder("My Bookmarks").then(
function(rootFolder) {
console.log(rootFolder);
}
);
````
### cloudSync.bookmarks.RootFolder
This is a root folder object for bookmarks, created by `cloudSync.bookmarks.getRootFolder`.
#### BOOKMARK
Bookmark type. Used in results objects.
````
let bookmarkType = rootFolder.BOOKMARK;
````
#### FOLDER
Folder type. Used in results objects.
````
let folderType = rootFolder.FOLDER;
````
#### SEPARATOR
Separator type. Used in results objects.
````
let separatorType = rootFolder.SEPARATOR;
````
#### addEventListener(type, callback)
Add an event handler for Tabs events. Valid types are `add, remove, change, move`. The callback receives an ID corresponding to the target item.
````
function handleBoookmarkEvent(id) {
console.log("event for id:", id);
}
rootFolder.addEventListener("add", handleBookmarkEvent);
rootFolder.addEventListener("remove", handleBookmarkEvent);
rootFolder.addEventListener("change", handleBookmarkEvent);
rootFolder.addEventListener("move", handleBookmarkEvent);
````
#### removeEventListener(type, callback)
Remove an event handler. Pass the type and function that were passed to addEventListener.
````
rootFolder.removeEventListener("add", handleBookmarkEvent);
rootFolder.removeEventListener("remove", handleBookmarkEvent);
rootFolder.removeEventListener("change", handleBookmarkEvent);
rootFolder.removeEventListener("move", handleBookmarkEvent);
````
#### getLocalItems()
Callback receives a list of items on the local client. Results have the following form:
````
{
id: "faw8e7f", // item guid
parent: "f7sydf87y", // parent folder guid
dateAdded: 1400799296192, // timestamp
lastModified: 1400799296192, // timestamp
uri: "https://www.google.ca", // null for FOLDER and SEPARATOR
title: "Google"
type: rootFolder.BOOKMARK, // should be one of rootFolder.{BOOKMARK, FOLDER, SEPARATOR},
index: 0 // must be unique among folder items
}
````
````
rootFolder.getLocalItems().then(
function(items) {
console.log(JSON.stringify(items));
}
);
````
#### getLocalItemsById([...])
Callback receives a list of items, specified by ID, on the local client. Results have the same form as `getLocalItems()` above.
````
rootFolder.getLocalItemsById(["213r23f", "f22fy3f3"]).then(
function(items) {
console.log(JSON.stringify(items));
}
);
````
#### mergeRemoteItems([...])
Merge remote items from upstream by updating existing items, adding new items, and deleting existing items. Folders are created first so that subsequent operations will succeed. Items have the same form as `getLocalItems()` above. Items that do not have an ID will have an ID generated for them. The results structure will contain this generated ID.
````
rootFolder.mergeRemoteItems([
{
id: 'f2398f23',
type: rootFolder.FOLDER,
title: 'Folder 1',
parent: '9f8237f928'
},
{
id: '9f8237f928',
type: rootFolder.FOLDER,
title: 'Folder 0',
}
]).then(
function(items) {
console.log(items); // any generated IDs are filled in now
console.log("merge completed");
}
);
````

View File

@ -0,0 +1,54 @@
.. _cloudsync_architecture:
============
Architecture
============
CloudSync offers functionality similar to Firefox Sync for data sources. Third-party addons
(sync adapters) consume local data, send and receive updates from the cloud, and merge remote data.
Files
=====
CloudSync.jsm
Main module; Includes other modules and exposes them.
CloudSyncAdapters.jsm
Provides an API for addons to register themselves. Will be used to
list available adapters and to notify adapters when sync operations
are requested manually by the user.
CloudSyncBookmarks.jsm
Provides operations for interacting with bookmarks.
CloudSyncBookmarksFolderCache.jsm
Implements a cache used to store folder hierarchy for filtering bookmark events.
CloudSyncEventSource.jsm
Implements an event emitter. Used to provide addEventListener and removeEventListener
for tabs and bookmarks.
CloudSyncLocal.jsm
Provides information about the local device, such as name and a unique id.
CloudSyncPlacesWrapper.jsm
Wraps parts of the Places API in promises. Some methods are implemented to be asynchronous
where they are not in the places API.
CloudSyncTabs.jsm
Provides operations for fetching local tabs and for populating the about:sync-tabs page.
Data Sources
============
CloudSync provides data for tabs and bookmarks. For tabs, local open pages can be enumerated and
remote tabs can be merged for displaying in about:sync-tabs. For bookmarks, updates are tracked
for a named folder (given by each adapter) and handled by callbacks registered using addEventListener,
and remote changes can be merged into the local database.
Versioning
==========
The API carries an integer version number (clouySync.version). Data records are versioned separately and individually.

View File

@ -0,0 +1,77 @@
.. _cloudsync_dataformat:
=========
Data Format
=========
All fields are required unless noted otherwise.
Bookmarks
=========
Record
------
type:
record type; one of CloudSync.bookmarks.{BOOKMARK, FOLDER, SEPARATOR, QUERY, LIVEMARK}
id:
GUID for this bookmark item
parent:
id of parent folder
index:
item index in parent folder; should be unique and contiguous, or they will be adjusted internally
title:
bookmark or folder title; not meaningful for separators
dateAdded:
timestamp (in milliseconds) for item added
lastModified:
timestamp (in milliseconds) for last modification
uri:
bookmark URI; not meaningful for folders or separators
version:
data layout version
Tabs
====
ClientRecord
------------
id:
GUID for this client
name:
name for this client; not guaranteed to be unique
tabs:
list of tabs open on this client; see TabRecord
version:
data layout version
TabRecord
---------
title:
name for this tab
url:
URL for this tab; only one tab for each URL is stored
icon:
favicon URL for this tab; optional
lastUsed:
timetamp (in milliseconds) for last use
version:
data layout version

View File

@ -0,0 +1,132 @@
.. _cloudsync_example:
=======
Example
=======
.. code-block:: javascript
Cu.import("resource://gre/modules/CloudSync.jsm");
let HelloWorld = {
onLoad: function() {
let cloudSync = CloudSync();
console.log("CLOUDSYNC -- hello world", cloudSync.local.id, cloudSync.local.name, cloudSync.adapters);
cloudSync.adapters.register('helloworld', {});
console.log("CLOUDSYNC -- " + JSON.stringify(cloudSync.adapters.getAdapterNames()));
cloudSync.tabs.addEventListener("change", function() {
console.log("tab change");
cloudSync.tabs.getLocalTabs().then(
function(records) {
console.log(JSON.stringify(records));
}
);
});
cloudSync.tabs.getLocalTabs().then(
function(records) {
console.log(JSON.stringify(records));
}
);
let remoteClient = {
id: "001",
name: "FakeClient",
};
let remoteTabs1 = [
{url:"https://www.google.ca",title:"Google",icon:"https://www.google.ca/favicon.ico",lastUsed:Date.now()},
];
let remoteTabs2 = [
{url:"https://www.google.ca",title:"Google Canada",icon:"https://www.google.ca/favicon.ico",lastUsed:Date.now()},
{url:"http://www.reddit.com",title:"Reddit",icon:"http://www.reddit.com/favicon.ico",lastUsed:Date.now()},
];
cloudSync.tabs.mergeRemoteTabs(remoteClient, remoteTabs1).then(
function() {
return cloudSync.tabs.mergeRemoteTabs(remoteClient, remoteTabs2);
}
).then(
function() {
return cloudSync.tabs.getRemoteTabs();
}
).then(
function(tabs) {
console.log("remote tabs:", tabs);
}
);
cloudSync.bookmarks.getRootFolder("Hello World").then(
function(rootFolder) {
console.log(rootFolder.name, rootFolder.id);
rootFolder.addEventListener("add", function(guid) {
console.log("CLOUDSYNC -- bookmark item added: " + guid);
rootFolder.getLocalItemsById([guid]).then(
function(items) {
console.log("CLOUDSYNC -- items: " + JSON.stringify(items));
}
);
});
rootFolder.addEventListener("remove", function(guid) {
console.log("CLOUDSYNC -- bookmark item removed: " + guid);
rootFolder.getLocalItemsById([guid]).then(
function(items) {
console.log("CLOUDSYNC -- items: " + JSON.stringify(items));
}
);
});
rootFolder.addEventListener("change", function(guid) {
console.log("CLOUDSYNC -- bookmark item changed: " + guid);
rootFolder.getLocalItemsById([guid]).then(
function(items) {
console.log("CLOUDSYNC -- items: " + JSON.stringify(items));
}
);
});
rootFolder.addEventListener("move", function(guid) {
console.log("CLOUDSYNC -- bookmark item moved: " + guid);
rootFolder.getLocalItemsById([guid]).then(
function(items) {
console.log("CLOUDSYNC -- items: " + JSON.stringify(items));
}
);
});
function logLocalItems() {
return rootFolder.getLocalItems().then(
function(items) {
console.log("CLOUDSYNC -- local items: " + JSON.stringify(items));
}
);
}
let items = [
{"id":"9fdoci2KOME6","type":rootFolder.FOLDER,"parent":rootFolder.id,"title":"My Bookmarks 1"},
{"id":"1fdoci2KOME5","type":rootFolder.FOLDER,"parent":rootFolder.id,"title":"My Bookmarks 2"},
{"id":"G_UL4ZhOyX8m","type":rootFolder.BOOKMARK,"parent":"1fdoci2KOME5","title":"reddit: the front page of the internet","uri":"http://www.reddit.com/"},
];
function mergeSomeItems() {
return rootFolder.mergeRemoteItems(items);
}
logLocalItems().then(
mergeSomeItems
).then(
function(processedItems) {
console.log("!!!", processedItems);
console.log("merge complete");
},
function(error) {
console.log("merge failed:", error);
}
).then(
logLocalItems
);
}
);
},
};
window.addEventListener("load", function(e) { HelloWorld.onLoad(e); }, false);

View File

@ -0,0 +1,19 @@
.. _cloudsync:
=====================
CloudSync
=====================
CloudSync is a service that provides access to tabs and bookmarks data
for third-party sync addons. Addons can read local bookmarks and tabs.
Bookmarks and tab data can be merged from remote devices.
Addons are responsible for maintaining an upstream representation, as
well as sending and receiving data over the network.
.. toctree::
:maxdepth: 1
architecture
dataformat
example

View File

@ -0,0 +1,21 @@
# -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
# vim: set filetype=python:
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
SPHINX_TREES['cloudsync'] = 'docs'
EXTRA_JS_MODULES += [
'CloudSync.jsm',
'CloudSyncAdapters.jsm',
'CloudSyncBookmarks.jsm',
'CloudSyncBookmarksFolderCache.jsm',
'CloudSyncEventSource.jsm',
'CloudSyncLocal.jsm',
'CloudSyncPlacesWrapper.jsm',
'CloudSyncTabs.jsm',
]
XPCSHELL_TESTS_MANIFESTS += ['tests/xpcshell/xpcshell.ini']
BROWSER_CHROME_MANIFESTS += ['tests/mochitest/browser.ini']

View File

@ -0,0 +1,5 @@
[DEFAULT]
support-files=
other_window.html
[browser_tabEvents.js]

View File

@ -0,0 +1,72 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
function test() {
let local = {};
Components.utils.import("resource://gre/modules/CloudSync.jsm", local);
Components.utils.import("resource:///modules/sessionstore/TabState.jsm", local);
let cloudSync = local.CloudSync();
let opentabs = [];
waitForExplicitFinish();
let testURL = "chrome://mochitests/content/browser/services/cloudsync/tests/mochitest/other_window.html";
let expected = [
testURL,
testURL+"?x=1",
testURL+"?x=%20a",
// testURL+"?x=å",
];
let nevents = 0;
function handleTabChangeEvent () {
cloudSync.tabs.removeEventListener("change", handleTabChangeEvent);
++ nevents;
}
function getLocalTabs() {
cloudSync.tabs.getLocalTabs().then(
function (tabs) {
for (let tab of tabs) {
ok(expected.indexOf(tab.url) >= 0, "found an expected tab");
}
is(tabs.length, expected.length, "found the right number of tabs");
opentabs.forEach(function (tab) {
gBrowser.removeTab(tab);
});
is(nevents, 1, "expected number of change events");
finish();
}
)
}
cloudSync.tabs.addEventListener("change", handleTabChangeEvent);
let nflushed = 0;
expected.forEach(function(url) {
let tab = gBrowser.addTab(url);
function flush() {
tab.linkedBrowser.removeEventListener("load", flush);
local.TabState.flush(tab.linkedBrowser);
++ nflushed;
if (nflushed == expected.length) {
getLocalTabs();
}
}
tab.linkedBrowser.addEventListener("load", flush, true);
opentabs.push(tab);
});
}

View File

@ -0,0 +1,7 @@
<!--
Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/
-->
<!DOCTYPE HTML>
<html>
</html>

View File

@ -0,0 +1,10 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
const {classes: Cc, interfaces: Ci, results: Cr, utils: Cu} = Components;
"use strict";
(function initCloudSyncTestingInfrastructure () {
do_get_profile();
}).call(this);

View File

@ -0,0 +1,15 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
"use strict";
Cu.import("resource://gre/modules/CloudSync.jsm");
function run_test () {
run_next_test();
}
add_task(function test_get_remote_tabs () {
let rootFolder = yield CloudSync().bookmarks.getRootFolder("TEST");
ok(rootFolder.id);
});

View File

@ -0,0 +1,18 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
"use strict";
Cu.import("resource://gre/modules/CloudSync.jsm");
function run_test() {
run_next_test();
}
add_task(function test_lazyload() {
ok(!CloudSync.ready, "CloudSync.ready is false before CloudSync() invoked");
let cs1 = CloudSync();
ok(CloudSync.ready, "CloudSync.ready is true after CloudSync() invoked");
let cs2 = CloudSync();
ok(cs1 === cs2, "CloudSync() returns the same instance on multiple invocations");
});

View File

@ -0,0 +1,19 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
"use strict";
Cu.import("resource://gre/modules/CloudSync.jsm");
function run_test () {
run_next_test();
}
add_task(function test_module_load () {
ok(CloudSync);
let cloudSync = CloudSync();
ok(cloudSync.adapters);
ok(cloudSync.bookmarks);
ok(cloudSync.local);
ok(cloudSync.tabs);
});

View File

@ -0,0 +1,29 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
"use strict";
Cu.import("resource://gre/modules/CloudSync.jsm");
function run_test () {
run_next_test();
}
add_task(function test_get_remote_tabs () {
let cloudSync = CloudSync();
let clients = yield cloudSync.tabs.getRemoteTabs();
equal(clients.length, 0);
yield cloudSync.tabs.mergeRemoteTabs({
id: "001",
name: "FakeClient",
},[
{url:"https://www.google.ca?a=å%20ä%20ö",title:"Google Canada",icon:"https://www.google.ca/favicon.ico",lastUsed:0},
{url:"http://www.reddit.com",title:"Reddit",icon:"http://www.reddit.com/favicon.ico",lastUsed:1},
]);
ok(cloudSync.tabs.hasRemoteTabs());
clients = yield cloudSync.tabs.getRemoteTabs();
equal(clients.length, 1);
equal(clients[0].tabs.size, 2);
});

View File

@ -0,0 +1,9 @@
[DEFAULT]
head = head.js
tail =
firefox-appdir = browser
[test_module.js]
[test_tabs.js]
[test_bookmarks.js]
[test_lazyload.js]

View File

@ -28,4 +28,7 @@ if CONFIG['MOZ_SERVICES_SYNC']:
if CONFIG['MOZ_B2G']:
DIRS += ['mobileid']
if CONFIG['MOZ_SERVICES_CLOUDSYNC']:
DIRS += ['cloudsync']
SPHINX_TREES['services'] = 'docs'