From 8e44bbb43789e585fab9fc1ce8becc94b45d566c Mon Sep 17 00:00:00 2001 From: wolfbeast Date: Mon, 17 Dec 2018 03:51:39 +0100 Subject: Stub out FxA context menu functions. Tag #812 --- .../basilisk/base/content/browser-fxaccounts.js | 82 +--------------------- 1 file changed, 2 insertions(+), 80 deletions(-) diff --git a/application/basilisk/base/content/browser-fxaccounts.js b/application/basilisk/base/content/browser-fxaccounts.js index cfd9758b6..e1d556bff 100644 --- a/application/basilisk/base/content/browser-fxaccounts.js +++ b/application/basilisk/base/content/browser-fxaccounts.js @@ -77,15 +77,6 @@ var gFxAccounts = { return Weave.Status.login == Weave.LOGIN_FAILED_LOGIN_REJECTED; }, - get sendTabToDeviceEnabled() { - return Services.prefs.getBoolPref("services.sync.sendTabToDevice.enabled"); - }, - - get remoteClients() { - return Weave.Service.clientsEngine.remoteClients - .sort((a, b) => a.name.localeCompare(b.name)); - }, - init: function () { // Bail out if we're already initialized and for pop-up windows. if (this._initialized || !window.toolbar.visible) { @@ -303,81 +294,12 @@ var gFxAccounts = { this.openAccountsPage("reauth", { entrypoint: entryPoint }); }, - sendTabToDevice: function (url, clientId, title) { - Weave.Service.clientsEngine.sendURIToClientForDisplay(url, clientId, title); - }, - - populateSendTabToDevicesMenu: function (devicesPopup, url, title) { - // remove existing menu items - while (devicesPopup.hasChildNodes()) { - devicesPopup.removeChild(devicesPopup.firstChild); - } - - const fragment = document.createDocumentFragment(); - - const onTargetDeviceCommand = (event) => { - const clientId = event.target.getAttribute("clientId"); - const clients = clientId - ? [clientId] - : this.remoteClients.map(client => client.id); - - clients.forEach(clientId => this.sendTabToDevice(url, clientId, title)); - } - - function addTargetDevice(clientId, name) { - const targetDevice = document.createElement("menuitem"); - targetDevice.addEventListener("command", onTargetDeviceCommand, true); - targetDevice.setAttribute("class", "sendtab-target"); - targetDevice.setAttribute("clientId", clientId); - targetDevice.setAttribute("label", name); - fragment.appendChild(targetDevice); - } - - const clients = this.remoteClients; - for (let client of clients) { - addTargetDevice(client.id, client.name); - } - - // "All devices" menu item - if (clients.length > 1) { - const separator = document.createElement("menuseparator"); - fragment.appendChild(separator); - const allDevicesLabel = this.strings.GetStringFromName("sendTabToAllDevices.menuitem"); - addTargetDevice("", allDevicesLabel); - } - - devicesPopup.appendChild(fragment); - }, - updateTabContextMenu: function (aPopupMenu) { - if (!this.sendTabToDeviceEnabled) { - return; - } - - const remoteClientPresent = this.remoteClients.length > 0; - ["context_sendTabToDevice", "context_sendTabToDevice_separator"] - .forEach(id => { document.getElementById(id).hidden = !remoteClientPresent }); + // STUB }, initPageContextMenu: function (contextMenu) { - if (!this.sendTabToDeviceEnabled) { - return; - } - - const remoteClientPresent = this.remoteClients.length > 0; - // showSendLink and showSendPage are mutually exclusive - const showSendLink = remoteClientPresent - && (contextMenu.onSaveableLink || contextMenu.onPlainTextLink); - const showSendPage = !showSendLink && remoteClientPresent - && !(contextMenu.isContentSelected || - contextMenu.onImage || contextMenu.onCanvas || - contextMenu.onVideo || contextMenu.onAudio || - contextMenu.onLink || contextMenu.onTextInput); - - ["context-sendpagetodevice", "context-sep-sendpagetodevice"] - .forEach(id => contextMenu.showItem(id, showSendPage)); - ["context-sendlinktodevice", "context-sep-sendlinktodevice"] - .forEach(id => contextMenu.showItem(id, showSendLink)); + // STUB } }; -- cgit v1.2.3 From 4c431486433428b18610c3578b693f3e1f1136eb Mon Sep 17 00:00:00 2001 From: wolfbeast Date: Wed, 13 Mar 2019 09:50:54 +0100 Subject: Remove CloudSync Tag #812 --- .../basilisk/base/content/browser-syncui.js | 11 - .../basilisk/base/content/sync/aboutSyncTabs.js | 14 - application/palemoon/configure.in | 4 - old-configure.in | 7 - services/cloudsync/CloudSync.jsm | 89 --- services/cloudsync/CloudSyncAdapters.jsm | 88 --- services/cloudsync/CloudSyncBookmarks.jsm | 795 --------------------- .../cloudsync/CloudSyncBookmarksFolderCache.jsm | 105 --- services/cloudsync/CloudSyncEventSource.jsm | 65 -- services/cloudsync/CloudSyncLocal.jsm | 87 --- services/cloudsync/CloudSyncPlacesWrapper.jsm | 375 ---------- services/cloudsync/CloudSyncTabs.jsm | 318 --------- services/cloudsync/docs/api.md | 234 ------ services/cloudsync/docs/architecture.rst | 54 -- services/cloudsync/docs/dataformat.rst | 77 -- services/cloudsync/docs/example.rst | 132 ---- services/cloudsync/docs/index.rst | 19 - services/cloudsync/moz.build | 21 - services/cloudsync/tests/mochitest/browser.ini | 5 - .../cloudsync/tests/mochitest/browser_tabEvents.js | 79 -- .../cloudsync/tests/mochitest/other_window.html | 7 - services/cloudsync/tests/xpcshell/head.js | 10 - .../cloudsync/tests/xpcshell/test_bookmarks.js | 73 -- services/cloudsync/tests/xpcshell/test_lazyload.js | 18 - services/cloudsync/tests/xpcshell/test_module.js | 19 - services/cloudsync/tests/xpcshell/test_tabs.js | 29 - services/cloudsync/tests/xpcshell/xpcshell.ini | 10 - services/moz.build | 3 - toolkit/modules/AppConstants.jsm | 7 - toolkit/modules/moz.build | 3 +- 30 files changed, 1 insertion(+), 2757 deletions(-) delete mode 100644 services/cloudsync/CloudSync.jsm delete mode 100644 services/cloudsync/CloudSyncAdapters.jsm delete mode 100644 services/cloudsync/CloudSyncBookmarks.jsm delete mode 100644 services/cloudsync/CloudSyncBookmarksFolderCache.jsm delete mode 100644 services/cloudsync/CloudSyncEventSource.jsm delete mode 100644 services/cloudsync/CloudSyncLocal.jsm delete mode 100644 services/cloudsync/CloudSyncPlacesWrapper.jsm delete mode 100644 services/cloudsync/CloudSyncTabs.jsm delete mode 100644 services/cloudsync/docs/api.md delete mode 100644 services/cloudsync/docs/architecture.rst delete mode 100644 services/cloudsync/docs/dataformat.rst delete mode 100644 services/cloudsync/docs/example.rst delete mode 100644 services/cloudsync/docs/index.rst delete mode 100644 services/cloudsync/moz.build delete mode 100644 services/cloudsync/tests/mochitest/browser.ini delete mode 100644 services/cloudsync/tests/mochitest/browser_tabEvents.js delete mode 100644 services/cloudsync/tests/mochitest/other_window.html delete mode 100644 services/cloudsync/tests/xpcshell/head.js delete mode 100644 services/cloudsync/tests/xpcshell/test_bookmarks.js delete mode 100644 services/cloudsync/tests/xpcshell/test_lazyload.js delete mode 100644 services/cloudsync/tests/xpcshell/test_module.js delete mode 100644 services/cloudsync/tests/xpcshell/test_tabs.js delete mode 100644 services/cloudsync/tests/xpcshell/xpcshell.ini diff --git a/application/basilisk/base/content/browser-syncui.js b/application/basilisk/base/content/browser-syncui.js index 3a57140f2..000c8f7b4 100644 --- a/application/basilisk/base/content/browser-syncui.js +++ b/application/basilisk/base/content/browser-syncui.js @@ -4,11 +4,6 @@ Cu.import("resource://gre/modules/XPCOMUtils.jsm"); -#ifdef MOZ_SERVICES_CLOUDSYNC -XPCOMUtils.defineLazyModuleGetter(this, "CloudSync", - "resource://gre/modules/CloudSync.jsm"); -#endif - XPCOMUtils.defineLazyModuleGetter(this, "fxAccounts", "resource://gre/modules/FxAccounts.jsm"); @@ -171,13 +166,7 @@ var gSyncUI = { document.getElementById("sync-setup-state").hidden = true; document.getElementById("sync-syncnow-state").hidden = true; -#ifdef MOZ_SERVICES_CLOUDSYNC - if (CloudSync && CloudSync.ready && CloudSync().adapters.count) { - document.getElementById("sync-syncnow-state").hidden = false; - } else if (loginFailed) { -#else if (loginFailed) { -#endif // unhiding this element makes the menubar show the login failure state. document.getElementById("sync-reauth-state").hidden = false; } else if (needsSetup) { diff --git a/application/basilisk/base/content/sync/aboutSyncTabs.js b/application/basilisk/base/content/sync/aboutSyncTabs.js index f4bb607ea..08986f73f 100644 --- a/application/basilisk/base/content/sync/aboutSyncTabs.js +++ b/application/basilisk/base/content/sync/aboutSyncTabs.js @@ -14,11 +14,6 @@ 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"); -#endif - var RemoteTabViewer = { _tabsList: null, @@ -183,16 +178,7 @@ var RemoteTabViewer = { } } -#ifdef MOZ_SERVICES_CLOUDSYNC - if (CloudSync && CloudSync.ready && CloudSync().tabsReady && CloudSync().tabs.hasRemoteTabs()) { - this._generateCloudSyncTabList() - .then(complete, complete); - } else { - complete(); - } -#else complete(); -#endif }, _clearTabList: function () { diff --git a/application/palemoon/configure.in b/application/palemoon/configure.in index 96f63781e..eb02af3c0 100644 --- a/application/palemoon/configure.in +++ b/application/palemoon/configure.in @@ -36,7 +36,3 @@ MOZ_ARG_DISABLE_BOOL(sync, MOZ_SERVICES_SYNC=, MOZ_SERVICES_SYNC=1) -if test -z "$MOZ_SERVICES_SYNC"; then - MOZ_SERVICES_CLOUDSYNC= -fi - diff --git a/old-configure.in b/old-configure.in index 7fadc2302..7cd8c4885 100644 --- a/old-configure.in +++ b/old-configure.in @@ -2246,7 +2246,6 @@ MOZ_DEVTOOLS= MOZ_PLACES=1 MOZ_SERVICES_HEALTHREPORT=1 MOZ_SERVICES_SYNC=1 -MOZ_SERVICES_CLOUDSYNC=1 MOZ_USERINFO=1 case "$target_os" in @@ -5006,12 +5005,6 @@ 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 ======================================================== if test "$MOZ_DEBUG"; then diff --git a/services/cloudsync/CloudSync.jsm b/services/cloudsync/CloudSync.jsm deleted file mode 100644 index 2c1057ea9..000000000 --- a/services/cloudsync/CloudSync.jsm +++ /dev/null @@ -1,89 +0,0 @@ -/* 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"); - -var API_VERSION = 1; - -var _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; - } -}); - -var _cloudSyncInternal = { - instance: null, - ready: false, -}; - -XPCOMUtils.defineLazyGetter(_cloudSyncInternal, "instance", function () { - _cloudSyncInternal.ready = true; - return new _CloudSync(); -}.bind(this)); diff --git a/services/cloudsync/CloudSyncAdapters.jsm b/services/cloudsync/CloudSyncAdapters.jsm deleted file mode 100644 index 16264a4f7..000000000 --- a/services/cloudsync/CloudSyncAdapters.jsm +++ /dev/null @@ -1,88 +0,0 @@ -/* 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 = { - -}; diff --git a/services/cloudsync/CloudSyncBookmarks.jsm b/services/cloudsync/CloudSyncBookmarks.jsm deleted file mode 100644 index bb2e48d59..000000000 --- a/services/cloudsync/CloudSyncBookmarks.jsm +++ /dev/null @@ -1,795 +0,0 @@ -/* 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/Task.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); -} - -var 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, -}; - -var 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; - -var 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.bind(Promise) - ); - 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.bind(Promise) - ); - 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.bind(Promise) - ); - 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(Task.spawn(function* () { - let localItem = (yield getLocalItemsById([item.id]))[0]; - let parent = yield PlacesWrapper.guidToLocalId(localItem.parent); - let index = item.index; - if (CS_FOLDER & item.type) { - folderCache.setParent(localId, parent); - } - yield PlacesWrapper.moveItem(localId, parent, 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 (let item of items) { - if (!item || 'object' !== typeof(item)) { - continue; - } - - let promise = exists(item).then(handleSortedItem, Promise.reject.bind(Promise)); - promises.push(promise); - } - - return Promise.all(promises); - } - - let processNewFolders = function () { - let newFolderGuids = Object.keys(newFolders); - let newFolderRoots = []; - - for (let guid of 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 (let guid of newFolderRoots) { - let root = newFolders[guid]; - let promise = Promise.resolve(); - promise = promise.then( - function () { - return _createItem(root); - }, - Promise.reject.bind(Promise) - ); - 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.bind(Promise) - ); - } - promises.push(promise); - } - - return Promise.all(promises); - } - - let processItems = function () { - let promises = []; - - for (let item of newItems) { - promises.push(_createItem(item)); - } - - for (let item of updatedItems) { - promises.push(_updateItem(item)); - } - - for (let item of 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, -}; diff --git a/services/cloudsync/CloudSyncBookmarksFolderCache.jsm b/services/cloudsync/CloudSyncBookmarksFolderCache.jsm deleted file mode 100644 index f3c3fc8f2..000000000 --- a/services/cloudsync/CloudSyncBookmarksFolderCache.jsm +++ /dev/null @@ -1,105 +0,0 @@ -/* 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. -var 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; diff --git a/services/cloudsync/CloudSyncEventSource.jsm b/services/cloudsync/CloudSyncEventSource.jsm deleted file mode 100644 index edb9c426b..000000000 --- a/services/cloudsync/CloudSyncEventSource.jsm +++ /dev/null @@ -1,65 +0,0 @@ -/* 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"); - -var EventSource = function (types, suspendFunc, resumeFunc) { - this.listeners = new Map(); - for (let type of 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; diff --git a/services/cloudsync/CloudSyncLocal.jsm b/services/cloudsync/CloudSyncLocal.jsm deleted file mode 100644 index 998c0c3c4..000000000 --- a/services/cloudsync/CloudSyncLocal.jsm +++ /dev/null @@ -1,87 +0,0 @@ -/* 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); - }, -}; - diff --git a/services/cloudsync/CloudSyncPlacesWrapper.jsm b/services/cloudsync/CloudSyncPlacesWrapper.jsm deleted file mode 100644 index dd8c5c52e..000000000 --- a/services/cloudsync/CloudSyncPlacesWrapper.jsm +++ /dev/null @@ -1,375 +0,0 @@ -/* 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"); - -var 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); - } -}; - -var 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; - }, - - 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 (let item of 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 (let item of 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 (let result of 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 (let name of 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(); diff --git a/services/cloudsync/CloudSyncTabs.jsm b/services/cloudsync/CloudSyncTabs.jsm deleted file mode 100644 index 7debc2678..000000000 --- a/services/cloudsync/CloudSyncTabs.jsm +++ /dev/null @@ -1,318 +0,0 @@ -/* 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; - -var 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; - } -}; - -var 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; - }, -}; - -var 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 (let tab of 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) { - if (PrivateBrowsingUtils.isBrowserPrivate(event.originalTarget.linkedBrowser) && - !PrivateBrowsingUtils.permanentPrivateBrowsing) { - return; - } - } - - eventSource.emit("change"); - }; - - let registerListenersForWindow = function (window) { - for (let topic of topics) { - window.addEventListener(topic, update, false); - } - window.addEventListener("unload", unregisterListeners, false); - }; - - let unregisterListenersForWindow = function (window) { - window.removeEventListener("unload", unregisterListeners, false); - for (let topic of 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; diff --git a/services/cloudsync/docs/api.md b/services/cloudsync/docs/api.md deleted file mode 100644 index bca3193a4..000000000 --- a/services/cloudsync/docs/api.md +++ /dev/null @@ -1,234 +0,0 @@ -### 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"); - } -); -```` \ No newline at end of file diff --git a/services/cloudsync/docs/architecture.rst b/services/cloudsync/docs/architecture.rst deleted file mode 100644 index a7a8aa7ba..000000000 --- a/services/cloudsync/docs/architecture.rst +++ /dev/null @@ -1,54 +0,0 @@ -.. _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. diff --git a/services/cloudsync/docs/dataformat.rst b/services/cloudsync/docs/dataformat.rst deleted file mode 100644 index 916581459..000000000 --- a/services/cloudsync/docs/dataformat.rst +++ /dev/null @@ -1,77 +0,0 @@ -.. _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 diff --git a/services/cloudsync/docs/example.rst b/services/cloudsync/docs/example.rst deleted file mode 100644 index 33d0f0531..000000000 --- a/services/cloudsync/docs/example.rst +++ /dev/null @@ -1,132 +0,0 @@ -.. _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); diff --git a/services/cloudsync/docs/index.rst b/services/cloudsync/docs/index.rst deleted file mode 100644 index d7951776d..000000000 --- a/services/cloudsync/docs/index.rst +++ /dev/null @@ -1,19 +0,0 @@ -.. _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 diff --git a/services/cloudsync/moz.build b/services/cloudsync/moz.build deleted file mode 100644 index 93197c9fe..000000000 --- a/services/cloudsync/moz.build +++ /dev/null @@ -1,21 +0,0 @@ -# -*- Mode: python; 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'] diff --git a/services/cloudsync/tests/mochitest/browser.ini b/services/cloudsync/tests/mochitest/browser.ini deleted file mode 100644 index c9eddbf71..000000000 --- a/services/cloudsync/tests/mochitest/browser.ini +++ /dev/null @@ -1,5 +0,0 @@ -[DEFAULT] -support-files= - other_window.html - -[browser_tabEvents.js] \ No newline at end of file diff --git a/services/cloudsync/tests/mochitest/browser_tabEvents.js b/services/cloudsync/tests/mochitest/browser_tabEvents.js deleted file mode 100644 index 9d80090a0..000000000 --- a/services/cloudsync/tests/mochitest/browser_tabEvents.js +++ /dev/null @@ -1,79 +0,0 @@ -/* 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/TabStateFlusher.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; - let nflushed = 0; - function handleTabChangeEvent () { - cloudSync.tabs.removeEventListener("change", handleTabChangeEvent); - ++ nevents; - info("tab change event " + nevents); - next(); - } - - 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); - - expected.forEach(function(url) { - let tab = gBrowser.addTab(url); - - function flush() { - tab.linkedBrowser.removeEventListener("load", flush, true); - local.TabStateFlusher.flush(tab.linkedBrowser).then(() => { - ++ nflushed; - info("flushed " + nflushed); - next(); - }); - } - - tab.linkedBrowser.addEventListener("load", flush, true); - - opentabs.push(tab); - }); - - function next() { - if (nevents == 1 && nflushed == expected.length) { - getLocalTabs(); - } - } - -} diff --git a/services/cloudsync/tests/mochitest/other_window.html b/services/cloudsync/tests/mochitest/other_window.html deleted file mode 100644 index a9ded2bd6..000000000 --- a/services/cloudsync/tests/mochitest/other_window.html +++ /dev/null @@ -1,7 +0,0 @@ - - - - diff --git a/services/cloudsync/tests/xpcshell/head.js b/services/cloudsync/tests/xpcshell/head.js deleted file mode 100644 index bd517cafa..000000000 --- a/services/cloudsync/tests/xpcshell/head.js +++ /dev/null @@ -1,10 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -var {classes: Cc, interfaces: Ci, results: Cr, utils: Cu} = Components; - -"use strict"; - -(function initCloudSyncTestingInfrastructure () { - do_get_profile(); -}).call(this); diff --git a/services/cloudsync/tests/xpcshell/test_bookmarks.js b/services/cloudsync/tests/xpcshell/test_bookmarks.js deleted file mode 100644 index d4e1d2b75..000000000 --- a/services/cloudsync/tests/xpcshell/test_bookmarks.js +++ /dev/null @@ -1,73 +0,0 @@ -/* 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(); -} - -function cleanup () { - -} - -add_task(function* test_merge_bookmarks_flat () { - try { - let rootFolder = yield CloudSync().bookmarks.getRootFolder("TEST"); - ok(rootFolder.id, "root folder id is ok"); - - let items = [ - {"id":"G_UL4ZhOyX8m","type":rootFolder.BOOKMARK,"title":"reddit: the front page of the internet 1","uri":"http://www.reddit.com",index:2}, - {"id":"G_UL4ZhOyX8n","type":rootFolder.BOOKMARK,"title":"reddit: the front page of the internet 2","uri":"http://www.reddit.com?1",index:1}, - ]; - yield rootFolder.mergeRemoteItems(items); - - let localItems = yield rootFolder.getLocalItems(); - equal(Object.keys(localItems).length, items.length, "found merged items"); - } finally { - yield CloudSync().bookmarks.deleteRootFolder("TEST"); - } -}); - -add_task(function* test_merge_bookmarks_in_folders () { - try { - let rootFolder = yield CloudSync().bookmarks.getRootFolder("TEST"); - ok(rootFolder.id, "root folder id is ok"); - - let items = [ - {"id":"G_UL4ZhOyX8m","type":rootFolder.BOOKMARK,"title":"reddit: the front page of the internet 1","uri":"http://www.reddit.com",index:2}, - {"id":"G_UL4ZhOyX8n","type":rootFolder.BOOKMARK,parent:"G_UL4ZhOyX8x","title":"reddit: the front page of the internet 2","uri":"http://www.reddit.com/?a=å%20ä%20ö",index:1}, - {"id":"G_UL4ZhOyX8x","type":rootFolder.FOLDER}, - ]; - yield rootFolder.mergeRemoteItems(items); - - let localItems = yield rootFolder.getLocalItems(); - equal(localItems.length, items.length, "found merged items"); - - localItems.forEach(function(item) { - ok(item.id == "G_UL4ZhOyX8m" || - item.id == "G_UL4ZhOyX8n" || - item.id == "G_UL4ZhOyX8x"); - if (item.id == "G_UL4ZhOyX8n") { - equal(item.parent, "G_UL4ZhOyX8x") - } else { - equal(item.parent, rootFolder.id); - } - }); - - let folder = (yield rootFolder.getLocalItemsById(["G_UL4ZhOyX8x"]))[0]; - equal(folder.id, "G_UL4ZhOyX8x"); - equal(folder.type, rootFolder.FOLDER); - - let bookmark = (yield rootFolder.getLocalItemsById(["G_UL4ZhOyX8n"]))[0]; - equal(bookmark.id, "G_UL4ZhOyX8n"); - equal(bookmark.parent, "G_UL4ZhOyX8x"); - equal(bookmark.title, "reddit: the front page of the internet 2"); - equal(bookmark.index, 0); - equal(bookmark.uri, "http://www.reddit.com/?a=%C3%A5%20%C3%A4%20%C3%B6"); - } finally { - yield CloudSync().bookmarks.deleteRootFolder("TEST"); - } -}); \ No newline at end of file diff --git a/services/cloudsync/tests/xpcshell/test_lazyload.js b/services/cloudsync/tests/xpcshell/test_lazyload.js deleted file mode 100644 index 5928875d5..000000000 --- a/services/cloudsync/tests/xpcshell/test_lazyload.js +++ /dev/null @@ -1,18 +0,0 @@ -/* 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"); -}); diff --git a/services/cloudsync/tests/xpcshell/test_module.js b/services/cloudsync/tests/xpcshell/test_module.js deleted file mode 100644 index 6d31345ed..000000000 --- a/services/cloudsync/tests/xpcshell/test_module.js +++ /dev/null @@ -1,19 +0,0 @@ -/* 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); -}); diff --git a/services/cloudsync/tests/xpcshell/test_tabs.js b/services/cloudsync/tests/xpcshell/test_tabs.js deleted file mode 100644 index 50f7a73de..000000000 --- a/services/cloudsync/tests/xpcshell/test_tabs.js +++ /dev/null @@ -1,29 +0,0 @@ -/* 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); -}); diff --git a/services/cloudsync/tests/xpcshell/xpcshell.ini b/services/cloudsync/tests/xpcshell/xpcshell.ini deleted file mode 100644 index 08d2eff3a..000000000 --- a/services/cloudsync/tests/xpcshell/xpcshell.ini +++ /dev/null @@ -1,10 +0,0 @@ -[DEFAULT] -head = head.js -tail = -firefox-appdir = browser -skip-if = toolkit == 'android' - -[test_module.js] -[test_tabs.js] -[test_bookmarks.js] -[test_lazyload.js] diff --git a/services/moz.build b/services/moz.build index 2109d512a..91f1e285e 100644 --- a/services/moz.build +++ b/services/moz.build @@ -14,6 +14,3 @@ if CONFIG['MOZ_WIDGET_TOOLKIT'] != 'android': if CONFIG['MOZ_SERVICES_SYNC']: DIRS += ['sync'] - -if CONFIG['MOZ_SERVICES_CLOUDSYNC']: - DIRS += ['cloudsync'] diff --git a/toolkit/modules/AppConstants.jsm b/toolkit/modules/AppConstants.jsm index 1e2204f7e..ae0eea1c4 100644 --- a/toolkit/modules/AppConstants.jsm +++ b/toolkit/modules/AppConstants.jsm @@ -102,13 +102,6 @@ MOZ_SAFE_BROWSING: false, #endif - MOZ_SERVICES_CLOUDSYNC: -#ifdef MOZ_SERVICES_CLOUDSYNC - true, -#else - false, -#endif - MOZ_UPDATER: #ifdef MOZ_UPDATER true, diff --git a/toolkit/modules/moz.build b/toolkit/modules/moz.build index e0acdb19e..8f66417c1 100644 --- a/toolkit/modules/moz.build +++ b/toolkit/modules/moz.build @@ -151,8 +151,7 @@ for var in ('ANDROID_PACKAGE_NAME', for var in ('MOZ_TOOLKIT_SEARCH', 'MOZ_SYSTEM_NSS', 'MOZ_UPDATER', - 'MOZ_SWITCHBOARD', - 'MOZ_SERVICES_CLOUDSYNC'): + 'MOZ_SWITCHBOARD'): if CONFIG[var]: DEFINES[var] = True -- cgit v1.2.3 From aa1a39311af0516dd6d2610a89b45221b60f3f20 Mon Sep 17 00:00:00 2001 From: wolfbeast Date: Wed, 13 Mar 2019 16:35:03 +0100 Subject: Remove some fxa tests. Tag #812 --- .../sync/tests/unit/test_fxa_node_reassignment.js | 321 --------------------- .../sync/tests/unit/test_fxa_service_cluster.js | 68 ----- services/sync/tests/unit/test_fxa_startOver.js | 63 ---- services/sync/tests/unit/xpcshell.ini | 5 - 4 files changed, 457 deletions(-) delete mode 100644 services/sync/tests/unit/test_fxa_node_reassignment.js delete mode 100644 services/sync/tests/unit/test_fxa_service_cluster.js delete mode 100644 services/sync/tests/unit/test_fxa_startOver.js diff --git a/services/sync/tests/unit/test_fxa_node_reassignment.js b/services/sync/tests/unit/test_fxa_node_reassignment.js deleted file mode 100644 index 2f61afd6f..000000000 --- a/services/sync/tests/unit/test_fxa_node_reassignment.js +++ /dev/null @@ -1,321 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -_("Test that node reassignment happens correctly using the FxA identity mgr."); -// The node-reassignment logic is quite different for FxA than for the legacy -// provider. In particular, there's no special request necessary for -// reassignment - it comes from the token server - so we need to ensure the -// Fxa cluster manager grabs a new token. - -Cu.import("resource://gre/modules/Log.jsm"); -Cu.import("resource://services-common/rest.js"); -Cu.import("resource://services-sync/constants.js"); -Cu.import("resource://services-sync/service.js"); -Cu.import("resource://services-sync/status.js"); -Cu.import("resource://services-sync/util.js"); -Cu.import("resource://testing-common/services/sync/rotaryengine.js"); -Cu.import("resource://services-sync/browserid_identity.js"); -Cu.import("resource://testing-common/services/sync/utils.js"); - -Service.engineManager.clear(); - -function run_test() { - Log.repository.getLogger("Sync.AsyncResource").level = Log.Level.Trace; - Log.repository.getLogger("Sync.ErrorHandler").level = Log.Level.Trace; - Log.repository.getLogger("Sync.Resource").level = Log.Level.Trace; - Log.repository.getLogger("Sync.RESTRequest").level = Log.Level.Trace; - Log.repository.getLogger("Sync.Service").level = Log.Level.Trace; - Log.repository.getLogger("Sync.SyncScheduler").level = Log.Level.Trace; - initTestLogging(); - - Service.engineManager.register(RotaryEngine); - - // Setup the FxA identity manager and cluster manager. - Status.__authManager = Service.identity = new BrowserIDManager(); - Service._clusterManager = Service.identity.createClusterManager(Service); - - // None of the failures in this file should result in a UI error. - function onUIError() { - do_throw("Errors should not be presented in the UI."); - } - Svc.Obs.add("weave:ui:login:error", onUIError); - Svc.Obs.add("weave:ui:sync:error", onUIError); - - run_next_test(); -} - - -// API-compatible with SyncServer handler. Bind `handler` to something to use -// as a ServerCollection handler. -function handleReassign(handler, req, resp) { - resp.setStatusLine(req.httpVersion, 401, "Node reassignment"); - resp.setHeader("Content-Type", "application/json"); - let reassignBody = JSON.stringify({error: "401inator in place"}); - resp.bodyOutputStream.write(reassignBody, reassignBody.length); -} - -let numTokenRequests = 0; - -function prepareServer(cbAfterTokenFetch) { - let config = makeIdentityConfig({username: "johndoe"}); - let server = new SyncServer(); - server.registerUser("johndoe"); - server.start(); - - // Set the token endpoint for the initial token request that's done implicitly - // via configureIdentity. - config.fxaccount.token.endpoint = server.baseURI + "1.1/johndoe"; - // And future token fetches will do magic around numReassigns. - let numReassigns = 0; - return configureIdentity(config).then(() => { - Service.identity._tokenServerClient = { - getTokenFromBrowserIDAssertion: function(uri, assertion, cb) { - // Build a new URL with trailing zeros for the SYNC_VERSION part - this - // will still be seen as equivalent by the test server, but different - // by sync itself. - numReassigns += 1; - let trailingZeros = new Array(numReassigns + 1).join('0'); - let token = config.fxaccount.token; - token.endpoint = server.baseURI + "1.1" + trailingZeros + "/johndoe"; - token.uid = config.username; - numTokenRequests += 1; - cb(null, token); - if (cbAfterTokenFetch) { - cbAfterTokenFetch(); - } - }, - }; - Service.clusterURL = config.fxaccount.token.endpoint; - return server; - }); -} - -function getReassigned() { - try { - return Services.prefs.getBoolPref("services.sync.lastSyncReassigned"); - } catch (ex if (ex.result == Cr.NS_ERROR_UNEXPECTED)) { - return false; - } catch (ex) { - do_throw("Got exception retrieving lastSyncReassigned: " + - Utils.exceptionStr(ex)); - } -} - -/** - * Make a test request to `url`, then watch the result of two syncs - * to ensure that a node request was made. - * Runs `between` between the two. This can be used to undo deliberate failure - * setup, detach observers, etc. - */ -function syncAndExpectNodeReassignment(server, firstNotification, between, - secondNotification, url) { - _("Starting syncAndExpectNodeReassignment\n"); - let deferred = Promise.defer(); - function onwards() { - let numTokenRequestsBefore; - function onFirstSync() { - _("First sync completed."); - Svc.Obs.remove(firstNotification, onFirstSync); - Svc.Obs.add(secondNotification, onSecondSync); - - do_check_eq(Service.clusterURL, ""); - - // Track whether we fetched a new token. - numTokenRequestsBefore = numTokenRequests; - - // Allow for tests to clean up error conditions. - between(); - } - function onSecondSync() { - _("Second sync completed."); - Svc.Obs.remove(secondNotification, onSecondSync); - Service.scheduler.clearSyncTriggers(); - - // Make absolutely sure that any event listeners are done with their work - // before we proceed. - waitForZeroTimer(function () { - _("Second sync nextTick."); - do_check_eq(numTokenRequests, numTokenRequestsBefore + 1, "fetched a new token"); - Service.startOver(); - server.stop(deferred.resolve); - }); - } - - Svc.Obs.add(firstNotification, onFirstSync); - Service.sync(); - } - - // Make sure that it works! - _("Making request to " + url + " which should 401"); - let request = new RESTRequest(url); - request.get(function () { - do_check_eq(request.response.status, 401); - Utils.nextTick(onwards); - }); - yield deferred.promise; -} - -add_task(function test_momentary_401_engine() { - _("Test a failure for engine URLs that's resolved by reassignment."); - let server = yield prepareServer(); - let john = server.user("johndoe"); - - _("Enabling the Rotary engine."); - let engine = Service.engineManager.get("rotary"); - engine.enabled = true; - - // We need the server to be correctly set up prior to experimenting. Do this - // through a sync. - let global = {syncID: Service.syncID, - storageVersion: STORAGE_VERSION, - rotary: {version: engine.version, - syncID: engine.syncID}} - john.createCollection("meta").insert("global", global); - - _("First sync to prepare server contents."); - Service.sync(); - - _("Setting up Rotary collection to 401."); - let rotary = john.createCollection("rotary"); - let oldHandler = rotary.collectionHandler; - rotary.collectionHandler = handleReassign.bind(this, undefined); - - // We want to verify that the clusterURL pref has been cleared after a 401 - // inside a sync. Flag the Rotary engine to need syncing. - john.collection("rotary").timestamp += 1000; - - function between() { - _("Undoing test changes."); - rotary.collectionHandler = oldHandler; - - function onLoginStart() { - // lastSyncReassigned shouldn't be cleared until a sync has succeeded. - _("Ensuring that lastSyncReassigned is still set at next sync start."); - Svc.Obs.remove("weave:service:login:start", onLoginStart); - do_check_true(getReassigned()); - } - - _("Adding observer that lastSyncReassigned is still set on login."); - Svc.Obs.add("weave:service:login:start", onLoginStart); - } - - yield syncAndExpectNodeReassignment(server, - "weave:service:sync:finish", - between, - "weave:service:sync:finish", - Service.storageURL + "rotary"); -}); - -// This test ends up being a failing info fetch *after we're already logged in*. -add_task(function test_momentary_401_info_collections_loggedin() { - _("Test a failure for info/collections after login that's resolved by reassignment."); - let server = yield prepareServer(); - - _("First sync to prepare server contents."); - Service.sync(); - - _("Arrange for info/collections to return a 401."); - let oldHandler = server.toplevelHandlers.info; - server.toplevelHandlers.info = handleReassign; - - function undo() { - _("Undoing test changes."); - server.toplevelHandlers.info = oldHandler; - } - - do_check_true(Service.isLoggedIn, "already logged in"); - - yield syncAndExpectNodeReassignment(server, - "weave:service:sync:error", - undo, - "weave:service:sync:finish", - Service.infoURL); -}); - -// This test ends up being a failing info fetch *before we're logged in*. -// In this case we expect to recover during the login phase - so the first -// sync succeeds. -add_task(function test_momentary_401_info_collections_loggedout() { - _("Test a failure for info/collections before login that's resolved by reassignment."); - - let oldHandler; - let sawTokenFetch = false; - - function afterTokenFetch() { - // After a single token fetch, we undo our evil handleReassign hack, so - // the next /info request returns the collection instead of a 401 - server.toplevelHandlers.info = oldHandler; - sawTokenFetch = true; - } - - let server = yield prepareServer(afterTokenFetch); - - // Return a 401 for the next /info request - it will be reset immediately - // after a new token is fetched. - oldHandler = server.toplevelHandlers.info - server.toplevelHandlers.info = handleReassign; - - do_check_false(Service.isLoggedIn, "not already logged in"); - - Service.sync(); - do_check_eq(Status.sync, SYNC_SUCCEEDED, "sync succeeded"); - // sync was successful - check we grabbed a new token. - do_check_true(sawTokenFetch, "a new token was fetched by this test.") - // and we are done. - Service.startOver(); - let deferred = Promise.defer(); - server.stop(deferred.resolve); - yield deferred.promise; -}); - -// This test ends up being a failing meta/global fetch *after we're already logged in*. -add_task(function test_momentary_401_storage_loggedin() { - _("Test a failure for any storage URL after login that's resolved by" + - "reassignment."); - let server = yield prepareServer(); - - _("First sync to prepare server contents."); - Service.sync(); - - _("Arrange for meta/global to return a 401."); - let oldHandler = server.toplevelHandlers.storage; - server.toplevelHandlers.storage = handleReassign; - - function undo() { - _("Undoing test changes."); - server.toplevelHandlers.storage = oldHandler; - } - - do_check_true(Service.isLoggedIn, "already logged in"); - - yield syncAndExpectNodeReassignment(server, - "weave:service:sync:error", - undo, - "weave:service:sync:finish", - Service.storageURL + "meta/global"); -}); - -// This test ends up being a failing meta/global fetch *before we've logged in*. -add_task(function test_momentary_401_storage_loggedout() { - _("Test a failure for any storage URL before login, not just engine parts. " + - "Resolved by reassignment."); - let server = yield prepareServer(); - - // Return a 401 for all storage requests. - let oldHandler = server.toplevelHandlers.storage; - server.toplevelHandlers.storage = handleReassign; - - function undo() { - _("Undoing test changes."); - server.toplevelHandlers.storage = oldHandler; - } - - do_check_false(Service.isLoggedIn, "already logged in"); - - yield syncAndExpectNodeReassignment(server, - "weave:service:login:error", - undo, - "weave:service:sync:finish", - Service.storageURL + "meta/global"); -}); - diff --git a/services/sync/tests/unit/test_fxa_service_cluster.js b/services/sync/tests/unit/test_fxa_service_cluster.js deleted file mode 100644 index f6f97184a..000000000 --- a/services/sync/tests/unit/test_fxa_service_cluster.js +++ /dev/null @@ -1,68 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -Cu.import("resource://services-sync/service.js"); -Cu.import("resource://services-sync/util.js"); -Cu.import("resource://testing-common/services/sync/fxa_utils.js"); -Cu.import("resource://testing-common/services/sync/utils.js"); - -add_task(function test_findCluster() { - _("Test FxA _findCluster()"); - - _("_findCluster() throws on 500 errors."); - initializeIdentityWithTokenServerResponse({ - status: 500, - headers: [], - body: "", - }); - - yield Service.identity.initializeWithCurrentIdentity(); - yield Assert.rejects(Service.identity.whenReadyToAuthenticate.promise, - "should reject due to 500"); - - Assert.throws(function() { - Service._clusterManager._findCluster(); - }); - - _("_findCluster() returns null on authentication errors."); - initializeIdentityWithTokenServerResponse({ - status: 401, - headers: {"content-type": "application/json"}, - body: "{}", - }); - - yield Service.identity.initializeWithCurrentIdentity(); - yield Assert.rejects(Service.identity.whenReadyToAuthenticate.promise, - "should reject due to 401"); - - cluster = Service._clusterManager._findCluster(); - Assert.strictEqual(cluster, null); - - _("_findCluster() works with correct tokenserver response."); - let endpoint = "http://example.com/something"; - initializeIdentityWithTokenServerResponse({ - status: 200, - headers: {"content-type": "application/json"}, - body: - JSON.stringify({ - api_endpoint: endpoint, - duration: 300, - id: "id", - key: "key", - uid: "uid", - }) - }); - - yield Service.identity.initializeWithCurrentIdentity(); - yield Service.identity.whenReadyToAuthenticate.promise; - cluster = Service._clusterManager._findCluster(); - // The cluster manager ensures a trailing "/" - Assert.strictEqual(cluster, endpoint + "/"); - - Svc.Prefs.resetBranch(""); -}); - -function run_test() { - initTestLogging(); - run_next_test(); -} diff --git a/services/sync/tests/unit/test_fxa_startOver.js b/services/sync/tests/unit/test_fxa_startOver.js deleted file mode 100644 index e27d86ea0..000000000 --- a/services/sync/tests/unit/test_fxa_startOver.js +++ /dev/null @@ -1,63 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -Cu.import("resource://testing-common/services/sync/utils.js"); -Cu.import("resource://services-sync/identity.js"); -Cu.import("resource://services-sync/browserid_identity.js"); -Cu.import("resource://services-sync/service.js"); - -function run_test() { - initTestLogging("Trace"); - run_next_test(); -} - -add_task(function* test_startover() { - let oldValue = Services.prefs.getBoolPref("services.sync-testing.startOverKeepIdentity", true); - Services.prefs.setBoolPref("services.sync-testing.startOverKeepIdentity", false); - - ensureLegacyIdentityManager(); - yield configureIdentity({username: "johndoe"}); - - // The boolean flag on the xpcom service should reflect a legacy provider. - let xps = Cc["@mozilla.org/weave/service;1"] - .getService(Components.interfaces.nsISupports) - .wrappedJSObject; - do_check_false(xps.fxAccountsEnabled); - - // we expect the "legacy" provider (but can't instanceof that, as BrowserIDManager - // extends it) - do_check_false(Service.identity instanceof BrowserIDManager); - - Service.serverURL = "https://localhost/"; - Service.clusterURL = Service.serverURL; - - Service.login(); - // We should have a cluster URL - do_check_true(Service.clusterURL.length > 0); - - // remember some stuff so we can reset it after. - let oldIdentity = Service.identity; - let oldClusterManager = Service._clusterManager; - let deferred = Promise.defer(); - Services.obs.addObserver(function observeStartOverFinished() { - Services.obs.removeObserver(observeStartOverFinished, "weave:service:start-over:finish"); - deferred.resolve(); - }, "weave:service:start-over:finish", false); - - Service.startOver(); - yield deferred.promise; // wait for the observer to fire. - - // the xpcom service should indicate FxA is enabled. - do_check_true(xps.fxAccountsEnabled); - // should have swapped identities. - do_check_true(Service.identity instanceof BrowserIDManager); - // should have clobbered the cluster URL - do_check_eq(Service.clusterURL, ""); - - // we should have thrown away the old identity provider and cluster manager. - do_check_neq(oldIdentity, Service.identity); - do_check_neq(oldClusterManager, Service._clusterManager); - - // reset the world. - Services.prefs.setBoolPref("services.sync-testing.startOverKeepIdentity", oldValue); -}); diff --git a/services/sync/tests/unit/xpcshell.ini b/services/sync/tests/unit/xpcshell.ini index 7e97835ac..28424129b 100644 --- a/services/sync/tests/unit/xpcshell.ini +++ b/services/sync/tests/unit/xpcshell.ini @@ -122,11 +122,6 @@ skip-if = os == "android" [test_syncscheduler.js] [test_upgrade_old_sync_key.js] -# Firefox Accounts specific tests -[test_fxa_startOver.js] -[test_fxa_service_cluster.js] -[test_fxa_node_reassignment.js] - # Finally, we test each engine. [test_addons_engine.js] run-sequentially = Hardcoded port in static files. -- cgit v1.2.3 From f999f544aad04069b03704d994a99352263f600b Mon Sep 17 00:00:00 2001 From: wolfbeast Date: Wed, 13 Mar 2019 16:36:55 +0100 Subject: Remove fxAccountsEnabled checks. Tag #812 --- .../basilisk/base/content/browser-syncui.js | 24 ++-------------- application/basilisk/base/content/sync/utils.js | 13 ++------- .../components/preferences/in-content/sync.js | 32 ++++++---------------- 3 files changed, 13 insertions(+), 56 deletions(-) diff --git a/application/basilisk/base/content/browser-syncui.js b/application/basilisk/base/content/browser-syncui.js index 000c8f7b4..b796e663b 100644 --- a/application/basilisk/base/content/browser-syncui.js +++ b/application/basilisk/base/content/browser-syncui.js @@ -93,14 +93,6 @@ var gSyncUI = { // Returns a promise that resolves with true if Sync needs to be configured, // false otherwise. _needsSetup() { - // If Sync is configured for FxAccounts then we do that promise-dance. - if (this.weaveService.fxAccountsEnabled) { - return fxAccounts.getSignedInUser().then(user => { - // We want to treat "account needs verification" as "needs setup". - return !(user && user.verified); - }); - } - // We are using legacy sync - check that. let firstSync = ""; try { firstSync = Services.prefs.getCharPref("services.sync.firstSync"); @@ -114,19 +106,9 @@ var gSyncUI = { // to Sync needs to be verified, false otherwise. _needsVerification() { // For callers who care about the distinction between "needs setup" and - // "needs verification" - if (this.weaveService.fxAccountsEnabled) { - return fxAccounts.getSignedInUser().then(user => { - // If there is no user, they can't be in a "needs verification" state. - if (!user) { - return false; - } - return !user.verified; - }); - } - - // Otherwise we are configured for legacy Sync, which has no verification - // concept. + // "needs verification". Only for fxAccounts. XXX: remove this check. + // Since we are configured for legacy Sync only, which has no verification + // concept, just return false. return Promise.resolve(false); }, diff --git a/application/basilisk/base/content/sync/utils.js b/application/basilisk/base/content/sync/utils.js index 92981f7b4..1422c1d15 100644 --- a/application/basilisk/base/content/sync/utils.js +++ b/application/basilisk/base/content/sync/utils.js @@ -14,13 +14,6 @@ var gSyncUtils = { return this.bundle = Services.strings.createBundle("chrome://browser/locale/syncSetup.properties"); }, - get fxAccountsEnabled() { - let service = Components.classes["@mozilla.org/weave/service;1"] - .getService(Components.interfaces.nsISupports) - .wrappedJSObject; - return service.fxAccountsEnabled; - }, - // opens in a new window if we're in a modal prefwindow world, in a new tab otherwise _openLink: function (url) { let thisDocEl = document.documentElement, @@ -78,8 +71,7 @@ var gSyncUtils = { }, get tosURL() { - let root = this.fxAccountsEnabled ? "fxa." : ""; - return Weave.Svc.Prefs.get(root + "termsURL"); + return Weave.Svc.Prefs.get("termsURL"); }, openToS: function () { @@ -87,8 +79,7 @@ var gSyncUtils = { }, get privacyPolicyURL() { - let root = this.fxAccountsEnabled ? "fxa." : ""; - return Weave.Svc.Prefs.get(root + "privacyURL"); + return Weave.Svc.Prefs.get("privacyURL"); }, openPrivacyPolicy: function () { diff --git a/application/basilisk/components/preferences/in-content/sync.js b/application/basilisk/components/preferences/in-content/sync.js index 2600677a8..32b94de86 100644 --- a/application/basilisk/components/preferences/in-content/sync.js +++ b/application/basilisk/components/preferences/in-content/sync.js @@ -92,19 +92,7 @@ var gSyncPane = { } catch (e) {} if (!username) { this.page = FXA_PAGE_LOGGED_OUT; - } else if (xps.fxAccountsEnabled) { - // Use cached values while we wait for the up-to-date values - let cachedComputerName; - try { - cachedComputerName = Services.prefs.getCharPref("services.sync.client.name"); - } - catch (e) { - cachedComputerName = ""; - } - document.getElementById("fxaEmailAddress1").textContent = username; - this._populateComputerName(cachedComputerName); - this.page = FXA_PAGE_LOGGED_IN; - } else { // Old Sync + } else { this.page = PAGE_HAS_ACCOUNT; } }, @@ -388,17 +376,13 @@ var gSyncPane = { .getService(Components.interfaces.nsISupports) .wrappedJSObject; - if (service.fxAccountsEnabled) { - this._openAboutAccounts(); - } else { - let win = Services.wm.getMostRecentWindow("Weave:AccountSetup"); - if (win) - win.focus(); - else { - window.openDialog("chrome://browser/content/sync/setup.xul", - "weaveSetup", "centerscreen,chrome,resizable=no", - wizardType); - } + let win = Services.wm.getMostRecentWindow("Weave:AccountSetup"); + if (win) + win.focus(); + else { + window.openDialog("chrome://browser/content/sync/setup.xul", + "weaveSetup", "centerscreen,chrome,resizable=no", + wizardType); } }, -- cgit v1.2.3 From 3e466a01e4185483895edb1243de032f25aa71e1 Mon Sep 17 00:00:00 2001 From: "Matt A. Tobin" Date: Sat, 30 Mar 2019 12:22:28 -0400 Subject: [BASILISK] Add configure option to disable sync --- application/basilisk/configure.in | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/application/basilisk/configure.in b/application/basilisk/configure.in index 4e7a06390..13f2ad54d 100644 --- a/application/basilisk/configure.in +++ b/application/basilisk/configure.in @@ -16,3 +16,10 @@ AC_SUBST(MC_BASILISK) dnl Optional parts of the build. +dnl ======================================================== +dnl = Disable Sync +dnl ======================================================== +MOZ_ARG_DISABLE_BOOL(sync, +[ --disable-sync Disable Sync], + MOZ_SERVICES_SYNC=, + MOZ_SERVICES_SYNC=1) \ No newline at end of file -- cgit v1.2.3 From 711c9cd6cd08f4fe10eb7544aa3a51dfb863bfeb Mon Sep 17 00:00:00 2001 From: "Matt A. Tobin" Date: Sat, 30 Mar 2019 13:28:49 -0400 Subject: [BASILISK] Remove FxA Synced Tabs Sidebar --- .../basilisk/base/content/browser-menubar.inc | 3 - application/basilisk/base/content/browser-sets.inc | 4 - application/basilisk/base/content/browser.xul | 53 -- application/basilisk/components/moz.build | 1 - .../components/syncedtabs/EventEmitter.jsm | 45 -- .../syncedtabs/SyncedTabsDeckComponent.js | 169 ------ .../components/syncedtabs/SyncedTabsDeckStore.js | 60 --- .../components/syncedtabs/SyncedTabsDeckView.js | 116 ----- .../components/syncedtabs/SyncedTabsListStore.js | 235 --------- .../components/syncedtabs/TabListComponent.js | 138 ----- .../basilisk/components/syncedtabs/TabListView.js | 568 --------------------- application/basilisk/components/syncedtabs/jar.mn | 7 - .../basilisk/components/syncedtabs/moz.build | 17 - .../basilisk/components/syncedtabs/sidebar.js | 30 -- .../basilisk/components/syncedtabs/sidebar.xhtml | 114 ----- application/basilisk/components/syncedtabs/util.js | 23 - .../locales/en-US/chrome/browser/browser.dtd | 25 - application/basilisk/themes/linux/jar.mn | 1 - .../basilisk/themes/linux/syncedtabs/sidebar.css | 69 --- application/basilisk/themes/osx/jar.mn | 1 - .../basilisk/themes/osx/syncedtabs/sidebar.css | 154 ------ .../themes/shared/syncedtabs/sidebar.inc.css | 234 --------- application/basilisk/themes/windows/jar.mn | 1 - .../basilisk/themes/windows/syncedtabs/sidebar.css | 132 ----- 24 files changed, 2200 deletions(-) delete mode 100644 application/basilisk/components/syncedtabs/EventEmitter.jsm delete mode 100644 application/basilisk/components/syncedtabs/SyncedTabsDeckComponent.js delete mode 100644 application/basilisk/components/syncedtabs/SyncedTabsDeckStore.js delete mode 100644 application/basilisk/components/syncedtabs/SyncedTabsDeckView.js delete mode 100644 application/basilisk/components/syncedtabs/SyncedTabsListStore.js delete mode 100644 application/basilisk/components/syncedtabs/TabListComponent.js delete mode 100644 application/basilisk/components/syncedtabs/TabListView.js delete mode 100644 application/basilisk/components/syncedtabs/jar.mn delete mode 100644 application/basilisk/components/syncedtabs/moz.build delete mode 100644 application/basilisk/components/syncedtabs/sidebar.js delete mode 100644 application/basilisk/components/syncedtabs/sidebar.xhtml delete mode 100644 application/basilisk/components/syncedtabs/util.js delete mode 100644 application/basilisk/themes/linux/syncedtabs/sidebar.css delete mode 100644 application/basilisk/themes/osx/syncedtabs/sidebar.css delete mode 100644 application/basilisk/themes/shared/syncedtabs/sidebar.inc.css delete mode 100644 application/basilisk/themes/windows/syncedtabs/sidebar.css diff --git a/application/basilisk/base/content/browser-menubar.inc b/application/basilisk/base/content/browser-menubar.inc index 0549ad915..5b89875fd 100644 --- a/application/basilisk/base/content/browser-menubar.inc +++ b/application/basilisk/base/content/browser-menubar.inc @@ -195,9 +195,6 @@ key="key_gotoHistory" observes="viewHistorySidebar" label="&historyButton.label;"/> - diff --git a/application/basilisk/base/content/browser-sets.inc b/application/basilisk/base/content/browser-sets.inc index 6ea057d93..47fd1547c 100644 --- a/application/basilisk/base/content/browser-sets.inc +++ b/application/basilisk/base/content/browser-sets.inc @@ -169,10 +169,6 @@