--- a/.eslintignore
+++ b/.eslintignore
@@ -179,16 +179,22 @@ mobile/android/components/Snippets.js
# Bug 1178739: Ignore this file as a quick fix for "Illegal yield expression"
mobile/android/modules/HomeProvider.jsm
# services/ exclusions
# Uses `#filter substitution`
services/sync/modules/constants.js
+# Third party services
+services/sync/tps/extensions/mozmill/resource/stdlib/json2.js
+services/common/kinto-http-client.js
+services/common/kinto-offline-client.js
+services/sync/tps/extensions/mozmill
+
# toolkit/ exclusions
# Not part of the default build
toolkit/components/help/**
# Intentionally invalid JS
toolkit/components/workerloader/tests/moduleF-syntax-error.js
new file mode 100644
--- /dev/null
+++ b/services/.eslintrc.js
@@ -0,0 +1,29 @@
+"use strict";
+
+module.exports = {
+ "extends": [
+ "../toolkit/.eslintrc.js"
+ ],
+ rules: {
+ /* These rules are only set to warn temporarily
+ until they get fixed, at which point their
+ respective line in this file should be removed. */
+ "brace-style": "warn",
+ "consistent-return": "warn",
+ "no-cond-assign": "warn",
+ "no-else-return": "warn",
+ "no-empty": "warn",
+ "no-ex-assign": "warn",
+ "no-func-assign": "warn",
+ "no-irregular-whitespace": "warn",
+ "no-mixed-spaces-and-tabs": "warn",
+ "no-native-reassign": "warn",
+ "no-nested-ternary": "warn",
+ "no-octal": "warn",
+ "no-redeclare": "warn",
+ "no-unreachable": "warn",
+ "no-unsafe-finally": "warn",
+ "no-unused-vars": "warn",
+ "no-useless-call": "warn"
+ }
+};
--- a/services/cloudsync/CloudSync.jsm
+++ b/services/cloudsync/CloudSync.jsm
@@ -14,76 +14,76 @@ XPCOMUtils.defineLazyModuleGetter(this,
"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 () {
+var _CloudSync = function() {
};
_CloudSync.prototype = {
_adapters: null,
- get adapters () {
+ get adapters() {
if (!this._adapters) {
this._adapters = new Adapters();
}
return this._adapters;
},
_bookmarks: null,
- get bookmarks () {
+ get bookmarks() {
if (!this._bookmarks) {
this._bookmarks = new Bookmarks();
}
return this._bookmarks;
},
_local: null,
- get local () {
+ get local() {
if (!this._local) {
this._local = new Local();
}
return this._local;
},
_tabs: null,
- get tabs () {
+ get tabs() {
if (!this._tabs) {
this._tabs = new Tabs();
}
return this._tabs;
},
- get tabsReady () {
- return this._tabs ? true: false;
+ get tabsReady() {
+ return this._tabs ? true : false;
},
- get version () {
+ get version() {
return API_VERSION;
},
};
-this.CloudSync = function CloudSync () {
+this.CloudSync = function CloudSync() {
return _cloudSyncInternal.instance;
};
Object.defineProperty(CloudSync, "ready", {
- get: function () {
+ get() {
return _cloudSyncInternal.ready;
}
});
var _cloudSyncInternal = {
instance: null,
ready: false,
};
-XPCOMUtils.defineLazyGetter(_cloudSyncInternal, "instance", function () {
+XPCOMUtils.defineLazyGetter(_cloudSyncInternal, "instance", function() {
_cloudSyncInternal.ready = true;
return new _CloudSync();
-}.bind(this));
+});
--- a/services/cloudsync/CloudSyncAdapters.jsm
+++ b/services/cloudsync/CloudSyncAdapters.jsm
@@ -4,73 +4,73 @@
"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 () {
+this.Adapters = function() {
let eventTypes = [
"sync",
];
let suspended = true;
- let suspend = function () {
+ let suspend = function() {
if (!suspended) {
Services.obs.removeObserver(observer, "cloudsync:user-sync");
suspended = true;
}
- }.bind(this);
+ };
- let resume = function () {
+ 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) {
+ function register(name, opts) {
opts = opts || {};
registeredAdapters.set(name, opts);
}
- function unregister (name) {
+ function unregister(name) {
if (!registeredAdapters.has(name)) {
throw new Error("adapter is not registered: " + name)
}
registeredAdapters.delete(name);
}
- function getAdapterNames () {
+ function getAdapterNames() {
let result = [];
for (let name of registeredAdapters.keys()) {
result.push(name);
}
return result;
}
- function getAdapter (name) {
+ function getAdapter(name) {
if (!registeredAdapters.has(name)) {
throw new Error("adapter is not registered: " + name)
}
return registeredAdapters.get(name);
}
- function countAdapters () {
+ function countAdapters() {
return registeredAdapters.size;
}
let observer = {
- observe: function (subject, topic, data) {
+ observe(subject, topic, data) {
switch (topic) {
case "cloudsync:user-sync":
eventSource.emit("sync");
break;
}
}
};
--- a/services/cloudsync/CloudSyncBookmarks.jsm
+++ b/services/cloudsync/CloudSyncBookmarks.jsm
@@ -44,28 +44,28 @@ const DATA_VERSION = 1;
function asyncCallback(ctx, func, args) {
function invoke() {
func.apply(ctx, args);
}
CommonUtils.nextTick(invoke);
}
-var Record = function (params) {
+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.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 () {
+ get() {
return annos;
},
enumerable: false
});
switch (params.type) {
case PlacesUtils.bookmarks.TYPE_FOLDER:
if (PlacesUtils.LMANNO_FEEDURI in annos) {
@@ -90,18 +90,18 @@ var Record = function (params) {
this.type = CS_UNKNOWN;
}
};
Record.prototype = {
version: DATA_VERSION,
};
-var Bookmarks = function () {
- let createRootFolder = function (name) {
+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;
@@ -137,17 +137,17 @@ var Bookmarks = function () {
.then(setRootFolderCloudSyncAnnotation)
.then(setRootShortcutCloudSyncAnnotation)
.then(setRootFolderExcludeFromBackupAnnotation)
.then(finish, deferred.reject);
return deferred.promise;
};
- let getRootFolder = function (name) {
+ 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);
}
@@ -161,17 +161,17 @@ var Bookmarks = function () {
PlacesWrapper.getLocalIdsWithAnnotation(ROOT_FOLDER_ANNO)
.then(checkRootFolder, deferred.reject)
.then(createFolderObject)
.then(deferred.resolve, deferred.reject);
return deferred.promise;
};
- let deleteRootFolder = function (name) {
+ 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);
@@ -192,17 +192,17 @@ var Bookmarks = function () {
let deleteFolderDeferred = Promise.defer();
if (!folderIds.length) {
return Promise.resolve();
}
let rootFolderId = folderIds[0];
PlacesWrapper.removeFolderChildren(rootFolderId).then(
- function () {
+ function() {
return PlacesWrapper.removeItem(rootFolderId);
}
).then(deleteFolderDeferred.resolve, deleteFolderDeferred.reject);
return deleteFolderDeferred.promise;
}
getRootShortcutId().then(deleteShortcut)
@@ -216,60 +216,60 @@ var Bookmarks = function () {
/* PUBLIC API */
this.getRootFolder = getRootFolder.bind(this);
this.deleteRootFolder = deleteRootFolder.bind(this);
};
this.Bookmarks = Bookmarks;
-var RootFolder = function (rootId, rootName) {
+var RootFolder = function(rootId, rootName) {
let suspended = true;
let ignoreAll = false;
- let suspend = function () {
+ let suspend = function() {
if (!suspended) {
PlacesUtils.bookmarks.removeObserver(observer);
suspended = true;
}
- }.bind(this);
+ };
- let resume = function () {
+ 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 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 getLocalItems = function() {
let deferred = Promise.defer();
let folders = getCachedFolderIds(folderCache, folderCache.getChildren(rootId));
function getFolders(ids) {
let types = [
PlacesUtils.bookmarks.TYPE_FOLDER,
];
@@ -283,35 +283,35 @@ var RootFolder = function (rootId, rootN
PlacesUtils.bookmarks.TYPE_SEPARATOR,
];
return PlacesWrapper.getItemsByParentId(parents, types)
}
function getParentGuids(results) {
results = Array.prototype.concat.apply([], results);
let promises = [];
- results.map(function (result) {
+ results.map(function(result) {
let promise = PlacesWrapper.localIdToGuid(result.parent).then(
- function (guidResult) {
+ 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) {
+ results.map(function(result) {
let promise = PlacesWrapper.getItemAnnotationsForLocalId(result.id).then(
- function (annos) {
+ function(annos) {
result.annos = annos;
return Promise.resolve(result);
},
Promise.reject.bind(Promise)
);
promises.push(promise);
});
return Promise.all(promises);
@@ -320,62 +320,62 @@ var RootFolder = function (rootId, rootN
let promises = [
getFolders(folders),
getContents(folders),
];
Promise.all(promises)
.then(getParentGuids)
.then(getAnnos)
- .then(function (results) {
+ .then(function(results) {
results = results.map((result) => new Record(result));
deferred.resolve(results);
},
deferred.reject);
return deferred.promise;
};
- let getLocalItemsById = function (guids) {
+ 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) {
+ results.map(function(result) {
let promise = PlacesWrapper.localIdToGuid(result.parent).then(
- function (guidResult) {
+ 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) {
+ .then(function(results) {
results = results.map((result) => new Record(result));
deferred.resolve(results);
},
deferred.reject);
return deferred.promise;
};
- let _createItem = function (item) {
+ let _createItem = function(item) {
let deferred = Promise.defer();
function getFolderId() {
if (item.parent) {
return PlacesWrapper.guidToLocalId(item.parent);
}
return Promise.resolve(rootId);
}
@@ -427,34 +427,34 @@ var RootFolder = function (rootId, rootN
}
getFolderId().then(create)
.then(deferred.resolve, deferred.reject);
return deferred.promise;
};
- let _deleteItem = function (item) {
+ let _deleteItem = function(item) {
let deferred = Promise.defer();
PlacesWrapper.guidToLocalId(item.id).then(
- function (localId) {
+ function(localId) {
folderCache.remove(localId);
return PlacesWrapper.removeItem(localId);
}
).then(deferred.resolve, deferred.reject);
return deferred.promise;
};
- let _updateItem = function (item) {
+ let _updateItem = function(item) {
let deferred = Promise.defer();
PlacesWrapper.guidToLocalId(item.id).then(
- function (localId) {
+ 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));
@@ -467,17 +467,17 @@ var RootFolder = function (rootId, rootN
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) {
+ 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);
@@ -499,52 +499,52 @@ var RootFolder = function (rootId, rootN
Promise.all(promises)
.then(deferred.resolve, deferred.reject);
}
);
return deferred.promise;
};
- let mergeRemoteItems = function (items) {
+ let mergeRemoteItems = function(items) {
ignoreAll = true;
let deferred = Promise.defer();
let newFolders = {};
let newItems = [];
let updatedItems = [];
let deletedItems = [];
- let sortItems = function () {
+ let sortItems = function() {
let promises = [];
- let exists = function (item) {
+ 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) {
+ function(localId) {
Object.defineProperty(item, "__exists__", {
value: localId ? true : false,
enumerable: false
});
existsDeferred.resolve(item);
},
existsDeferred.reject
);
}
return existsDeferred.promise;
}
- let handleSortedItem = function (item) {
+ 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) {
@@ -561,59 +561,59 @@ var RootFolder = function (rootId, rootN
let promise = exists(item).then(handleSortedItem, Promise.reject.bind(Promise));
promises.push(promise);
}
return Promise.all(promises);
}
- let processNewFolders = function () {
+ 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 () {
+ 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 () {
+ function() {
return _createItem(item);
},
Promise.reject.bind(Promise)
);
}
promises.push(promise);
}
return Promise.all(promises);
}
- let processItems = function () {
+ let processItems = function() {
let promises = [];
for (let item of newItems) {
promises.push(_createItem(item));
}
for (let item of updatedItems) {
promises.push(_updateItem(item));
@@ -623,76 +623,76 @@ var RootFolder = function (rootId, rootN
_deleteItem(item);
}
return Promise.all(promises);
}
sortItems().then(processNewFolders)
.then(processItems)
- .then(function () {
+ .then(function() {
ignoreAll = false;
deferred.resolve(items);
},
- function (err) {
+ function(err) {
ignoreAll = false;
deferred.reject(err);
});
return deferred.promise;
};
- let ignore = function (id, parent) {
+ 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 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 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 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 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) {
@@ -713,77 +713,77 @@ var RootFolder = function (rootId, rootN
PlacesWrapper.updateCachedFolderIds(folderCache, oldParent)
.then(complete, complete);
}
return deferred.promise;
};
let observer = {
- onBeginBatchUpdate: function () {
+ onBeginBatchUpdate() {
},
- onEndBatchUpdate: function () {
+ onEndBatchUpdate() {
},
- onItemAdded: function (id, parent, index, type, uri, title, dateAdded, guid, parentGuid) {
+ onItemAdded(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) {
+ onItemRemoved(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) {
+ onItemChanged(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) {
+ onItemMoved(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 () {
+ this.__defineGetter__("id", function() {
return rootGuid;
});
- this.__defineGetter__("name", function () {
+ this.__defineGetter__("name", function() {
return rootName;
});
let deferred = Promise.defer();
- let getGuidForRootFolder = function () {
+ let getGuidForRootFolder = function() {
return PlacesWrapper.localIdToGuid(rootId);
}
PlacesWrapper.updateCachedFolderIds(folderCache, rootId)
.then(getGuidForRootFolder, getGuidForRootFolder)
- .then(function (guid) {
+ .then(function(guid) {
rootGuid = guid;
deferred.resolve(this);
}.bind(this),
deferred.reject);
return deferred.promise;
};
RootFolder.prototype = {
--- a/services/cloudsync/CloudSyncBookmarksFolderCache.jsm
+++ b/services/cloudsync/CloudSyncBookmarksFolderCache.jsm
@@ -2,26 +2,26 @@
* 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 () {
+var FolderCache = function() {
this.cache = new Map();
}
FolderCache.prototype = {
- has: function (id) {
+ has(id) {
return this.cache.has(id);
},
- insert: function (id, parentId) {
+ insert(id, parentId) {
if (this.cache.has(id)) {
return;
}
if (parentId && !(this.cache.has(parentId))) {
throw new Error("insert :: parentId not found in cache: " + parentId);
}
@@ -30,34 +30,34 @@ FolderCache.prototype = {
children: new Set(),
});
if (parentId) {
this.cache.get(parentId).children.add(id);
}
},
- remove: function (id) {
+ remove(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) {
+ setParent(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);
}
@@ -66,40 +66,40 @@ FolderCache.prototype = {
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) {
+ getParent(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) {
+ getChildren(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) {
+ setChildren(id, children) {
for (let child of children) {
if (!this.cache.has(child)) {
this.insert(child, id);
} else {
this.setParent(child, id);
}
}
},
- dump: function () {
+ dump() {
dump("FolderCache: " + JSON.stringify(this.cache) + "\n");
},
};
this.FolderCache = FolderCache;
--- a/services/cloudsync/CloudSyncEventSource.jsm
+++ b/services/cloudsync/CloudSyncEventSource.jsm
@@ -1,63 +1,63 @@
/* 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) {
+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.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) {
+ addEventListener(type, listener) {
if (!this.listeners.has(type)) {
return;
}
this.listeners.get(type).add(listener);
this.resume();
},
- removeEventListener: function (type, listener) {
+ removeEventListener(type, listener) {
if (!this.listeners.has(type)) {
return;
}
this.listeners.get(type).delete(listener);
if (!this.hasListeners()) {
this.suspend();
}
},
- hasListeners: function () {
+ hasListeners() {
for (let l of this.listeners.values()) {
if (l.size > 0) {
return true;
}
}
return false;
},
- emit: function (type, arg) {
+ emit(type, arg) {
if (!this.listeners.has(type)) {
return;
}
CommonUtils.nextTick(
- function () {
+ function() {
for (let listener of this.listeners.get(type)) {
listener.call(undefined, arg);
}
},
this
);
},
};
--- a/services/cloudsync/CloudSyncLocal.jsm
+++ b/services/cloudsync/CloudSyncLocal.jsm
@@ -24,27 +24,27 @@ function lazyStrings(name) {
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 () {
+this.Local = function() {
let prefs = new Preferences("services.cloudsync.");
- this.__defineGetter__("prefs", function () {
+ this.__defineGetter__("prefs", function() {
return prefs;
});
};
Local.prototype = {
get id() {
let clientId = this.prefs.get("client.GUID", "");
- return clientId == "" ? this.id = makeGUID(): clientId;
+ return clientId == "" ? this.id = makeGUID() : clientId;
},
set id(value) {
this.prefs.set("client.GUID", value);
},
get name() {
let clientName = this.prefs.get("client.name", "");
--- a/services/cloudsync/CloudSyncPlacesWrapper.jsm
+++ b/services/cloudsync/CloudSyncPlacesWrapper.jsm
@@ -9,39 +9,39 @@ 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 () {
+var PlacesQueries = function() {
}
PlacesQueries.prototype = {
cachedStmts: {},
- getQuery: function (queryString) {
+ getQuery(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 () {
+var PlacesWrapper = function() {
}
PlacesWrapper.prototype = {
placesQueries: new PlacesQueries(),
- guidToLocalId: function (guid) {
+ guidToLocalId(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) {
@@ -53,17 +53,17 @@ PlacesWrapper.prototype = {
this.asyncQuery(query, ["item_id"])
.then(getLocalId, deferred.reject)
.then(deferred.resolve, deferred.reject);
return deferred.promise;
},
- localIdToGuid: function (id) {
+ localIdToGuid(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) {
@@ -75,74 +75,74 @@ PlacesWrapper.prototype = {
this.asyncQuery(query, ["guid"])
.then(getGuid, deferred.reject)
.then(deferred.resolve, deferred.reject);
return deferred.promise;
},
- getItemsById: function (ids, types) {
+ getItemsById(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) {
+ getItemsByParentId(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) {
+ getItemsByGuid(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) {
+ updateCachedFolderIds(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) {
+ 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();
@@ -170,200 +170,200 @@ PlacesWrapper.prototype = {
folderCache.remove(missingId);
}
}.bind(this)
);
return deferred.promise;
},
- getLocalIdsWithAnnotation: function (anno) {
+ getLocalIdsWithAnnotation(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) {
+ .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) {
+ getItemAnnotationsForLocalId(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) {
+ .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) {
+ insertBookmark(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) {
+ setItemAnnotation(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) {
+ itemHasAnnotation(item, anno) {
try {
return Promise.resolve(PlacesUtils.annotations.itemHasAnnotation(item, anno));
} catch (e) {
return Promise.reject(e);
}
},
- createFolder: function (parent, name, index, guid) {
+ createFolder(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) {
+ removeFolderChildren(folder) {
try {
PlacesUtils.bookmarks.removeFolderChildren(folder);
return Promise.resolve();
} catch (e) {
return Promise.reject(e);
}
},
- insertSeparator: function (parent, index, guid) {
+ insertSeparator(parent, index, guid) {
try {
return Promise.resolve(PlacesUtils.bookmarks.insertSeparator(parent, index, guid));
} catch (e) {
return Promise.reject(e);
}
},
- removeItem: function (item) {
+ removeItem(item) {
try {
return Promise.resolve(PlacesUtils.bookmarks.removeItem(item));
} catch (e) {
return Promise.reject(e);
}
},
- setItemDateAdded: function (item, dateAdded) {
+ setItemDateAdded(item, dateAdded) {
try {
return Promise.resolve(PlacesUtils.bookmarks.setItemDateAdded(item, dateAdded));
} catch (e) {
return Promise.reject(e);
}
},
- setItemLastModified: function (item, lastModified) {
+ setItemLastModified(item, lastModified) {
try {
return Promise.resolve(PlacesUtils.bookmarks.setItemLastModified(item, lastModified));
} catch (e) {
return Promise.reject(e);
}
},
- setItemTitle: function (item, title) {
+ setItemTitle(item, title) {
try {
return Promise.resolve(PlacesUtils.bookmarks.setItemTitle(item, title));
} catch (e) {
return Promise.reject(e);
}
},
- changeBookmarkURI: function (item, uri) {
+ changeBookmarkURI(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) {
+ moveItem(item, parent, index) {
try {
return Promise.resolve(PlacesUtils.bookmarks.moveItem(item, parent, index));
} catch (e) {
return Promise.reject(e);
}
},
- setItemIndex: function (item, index) {
+ setItemIndex(item, index) {
try {
return Promise.resolve(PlacesUtils.bookmarks.setItemIndex(item, index));
} catch (e) {
return Promise.reject(e);
}
},
- asyncQuery: function (query, names) {
+ asyncQuery(query, names) {
let deferred = Promise.defer();
let storageCallback = {
results: [],
- handleResult: function (results) {
+ handleResult(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) {
+ handleError(error) {
deferred.reject(error);
},
- handleCompletion: function (reason) {
+ handleCompletion(reason) {
if (REASON_ERROR == reason) {
return;
}
deferred.resolve(this.results);
}
};
--- a/services/cloudsync/CloudSyncTabs.jsm
+++ b/services/cloudsync/CloudSyncTabs.jsm
@@ -14,64 +14,64 @@ Cu.import("resource://gre/modules/CloudS
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) {
+var ClientRecord = function(params) {
this.id = params.id;
this.name = params.name || "?";
this.tabs = new Set();
}
ClientRecord.prototype = {
version: DATA_VERSION,
- update: function (params) {
+ update(params) {
if (this.id !== params.id) {
throw new Error("expected " + this.id + " to equal " + params.id);
}
this.name = params.name;
}
};
-var TabRecord = function (params) {
+var TabRecord = function(params) {
this.url = params.url || "";
this.update(params);
};
TabRecord.prototype = {
version: DATA_VERSION,
- update: function (params) {
+ update(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 () {
+var TabCache = function() {
this.tabs = new Map();
this.clients = new Map();
};
TabCache.prototype = {
- merge: function (client, tabs) {
+ merge(client, tabs) {
if (!client || !client.id) {
return;
}
if (!tabs) {
return;
}
@@ -108,150 +108,150 @@ TabCache.prototype = {
if (tab.deleted) {
cRecord.tabs.delete(tRecord);
} else {
cRecord.tabs.add(tRecord);
}
}
},
- clear: function (client) {
+ clear(client) {
if (client) {
this.clients.delete(client.id);
} else {
this.clients = new Map();
this.tabs = new Map();
}
},
- get: function () {
+ get() {
let results = [];
for (let client of this.clients.values()) {
results.push(client);
}
return results;
},
- isEmpty: function () {
+ isEmpty() {
return 0 == this.clients.size;
},
};
-this.Tabs = function () {
+this.Tabs = function() {
let suspended = true;
let topics = [
"pageshow",
"TabOpen",
"TabClose",
"TabSelect",
];
- let update = function (event) {
+ let update = function(event) {
if (event.originalTarget.linkedBrowser) {
if (PrivateBrowsingUtils.isBrowserPrivate(event.originalTarget.linkedBrowser) &&
!PrivateBrowsingUtils.permanentPrivateBrowsing) {
return;
}
}
eventSource.emit("change");
};
- let registerListenersForWindow = function (window) {
+ let registerListenersForWindow = function(window) {
for (let topic of topics) {
window.addEventListener(topic, update, false);
}
window.addEventListener("unload", unregisterListeners, false);
};
- let unregisterListenersForWindow = function (window) {
+ let unregisterListenersForWindow = function(window) {
window.removeEventListener("unload", unregisterListeners, false);
for (let topic of topics) {
window.removeEventListener(topic, update, false);
}
};
- let unregisterListeners = function (event) {
+ let unregisterListeners = function(event) {
unregisterListenersForWindow(event.target);
};
let observer = {
- observe: function (subject, topic, data) {
+ observe(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 () {
+ 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 () {
+ 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 () {
+ let getWindowEnumerator = function() {
return Services.wm.getEnumerator("navigator:browser");
};
- let shouldSkipWindow = function (win) {
+ let shouldSkipWindow = function(win) {
return win.closed ||
PrivateBrowsingUtils.isWindowPrivate(win);
};
- let getTabState = function (tab) {
+ let getTabState = function(tab) {
return JSON.parse(Session.getTabState(tab));
};
- let getLocalTabs = function (filter) {
+ 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) {
+ currentState.windows.forEach(function(window) {
if (window.isPrivate) {
return;
}
- window.tabs.forEach(function (tab) {
+ 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];
@@ -268,43 +268,43 @@ this.Tabs = function () {
});
});
deferred.resolve(allTabs);
return deferred.promise;
};
- let mergeRemoteTabs = function (client, tabs) {
+ 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 clearRemoteTabs = function(client) {
let deferred = Promise.defer();
deferred.resolve(tabCache.clear(client));
Observers.notify("cloudsync:tabs:update");
return deferred.promise;
};
- let getRemoteTabs = function () {
+ let getRemoteTabs = function() {
let deferred = Promise.defer();
deferred.resolve(tabCache.get());
return deferred.promise;
};
- let hasRemoteTabs = function () {
+ 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);
--- a/services/cloudsync/tests/mochitest/browser_tabEvents.js
+++ b/services/cloudsync/tests/mochitest/browser_tabEvents.js
@@ -12,40 +12,40 @@ function test() {
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=1",
+ testURL + "?x=%20a",
// testURL+"?x=å",
];
let nevents = 0;
let nflushed = 0;
- function handleTabChangeEvent () {
+ function handleTabChangeEvent() {
cloudSync.tabs.removeEventListener("change", handleTabChangeEvent);
- ++ nevents;
+ ++nevents;
info("tab change event " + nevents);
next();
}
function getLocalTabs() {
cloudSync.tabs.getLocalTabs().then(
- function (tabs) {
+ 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) {
+ opentabs.forEach(function(tab) {
gBrowser.removeTab(tab);
});
is(nevents, 1, "expected number of change events");
finish();
}
)
@@ -54,17 +54,17 @@ function test() {
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;
+ ++nflushed;
info("flushed " + nflushed);
next();
});
}
tab.linkedBrowser.addEventListener("load", flush, true);
opentabs.push(tab);
--- a/services/cloudsync/tests/xpcshell/head.js
+++ b/services/cloudsync/tests/xpcshell/head.js
@@ -1,10 +1,10 @@
/* 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 () {
+(function initCloudSyncTestingInfrastructure() {
do_get_profile();
}).call(this);
--- a/services/cloudsync/tests/xpcshell/test_bookmarks.js
+++ b/services/cloudsync/tests/xpcshell/test_bookmarks.js
@@ -1,50 +1,50 @@
/* 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 () {
+function run_test() {
run_next_test();
}
-function cleanup () {
+function cleanup() {
}
-add_task(function* test_merge_bookmarks_flat () {
+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},
+ {"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 () {
+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},
+ {"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" ||
@@ -65,9 +65,9 @@ add_task(function* test_merge_bookmarks_
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
+});
--- a/services/cloudsync/tests/xpcshell/test_module.js
+++ b/services/cloudsync/tests/xpcshell/test_module.js
@@ -1,19 +1,19 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
"use strict";
Cu.import("resource://gre/modules/CloudSync.jsm");
-function run_test () {
+function run_test() {
run_next_test();
}
-add_task(function test_module_load () {
+add_task(function test_module_load() {
ok(CloudSync);
let cloudSync = CloudSync();
ok(cloudSync.adapters);
ok(cloudSync.bookmarks);
ok(cloudSync.local);
ok(cloudSync.tabs);
});
--- a/services/cloudsync/tests/xpcshell/test_tabs.js
+++ b/services/cloudsync/tests/xpcshell/test_tabs.js
@@ -1,29 +1,29 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
"use strict";
Cu.import("resource://gre/modules/CloudSync.jsm");
-function run_test () {
+function run_test() {
run_next_test();
}
-add_task(function* test_get_remote_tabs () {
+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},
+ }, [
+ {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);
});
--- a/services/common/async.js
+++ b/services/common/async.js
@@ -221,16 +221,16 @@ this.Async = {
storageCallback.names = names;
storageCallback.syncCb = Async.makeSyncCallback();
query.executeAsync(storageCallback);
return Async.waitForSyncCallback(storageCallback.syncCb);
},
promiseSpinningly(promise) {
let cb = Async.makeSpinningCallback();
- promise.then(result => {
+ promise.then(result => {
cb(null, result);
}, err => {
cb(err || new Error("Promise rejected without explicit error"));
});
return cb.wait();
},
};
--- a/services/common/blocklist-clients.js
+++ b/services/common/blocklist-clients.js
@@ -87,17 +87,17 @@ function fetchRemoteCollection(collectio
* URL and bucket name. It uses the `FirefoxAdapter` which relies on SQLite to
* persist the local DB.
*/
function kintoClient(connection, bucket) {
let base = Services.prefs.getCharPref(PREF_SETTINGS_SERVER);
let config = {
remote: base,
- bucket: bucket,
+ bucket,
adapter: FirefoxAdapter,
adapterOptions: {sqliteHandle: connection},
};
return new Kinto(config);
}
@@ -275,17 +275,17 @@ function* updatePinningList(records) {
.getService(Ci.nsISiteSecurityService);
// clear the current preload list
siteSecurityService.clearPreloads();
// write each KeyPin entry to the preload list
for (let item of records) {
try {
- const {pinType, pins=[], versions} = item;
+ const {pinType, pins = [], versions} = item;
if (versions.indexOf(appInfo.version) != -1) {
if (pinType == "KeyPin" && pins.length) {
siteSecurityService.setKeyPins(item.hostName,
item.includeSubdomains,
item.expires,
pins.length,
pins, true);
}
@@ -296,18 +296,16 @@ function* updatePinningList(records) {
}
}
} catch (e) {
// prevent errors relating to individual preload entries from causing
// sync to fail. We will accumulate telemetry for such failures in bug
// 1254099.
}
}
- } else {
- return;
}
}
/**
* Write list of records into JSON file, and notify nsBlocklistService.
*
* @param {String} filename path relative to profile dir.
* @param {Object} records current records in the local db.
@@ -315,19 +313,19 @@ function* updatePinningList(records) {
function* updateJSONBlocklist(filename, records) {
// Write JSON dump for synchronous load at startup.
const path = OS.Path.join(OS.Constants.Path.profileDir, filename);
const serialized = JSON.stringify({data: records}, null, 2);
try {
yield OS.File.writeAtomic(path, serialized, {tmpPath: path + ".tmp"});
// Notify change to `nsBlocklistService`
- const eventData = {filename: filename};
+ const eventData = {filename};
Services.cpmm.sendAsyncMessage("Blocklist:reload-from-disk", eventData);
- } catch(e) {
+ } catch (e) {
Cu.reportError(e);
}
}
this.OneCRLBlocklistClient = new BlocklistClient(
Services.prefs.getCharPref(PREF_BLOCKLIST_ONECRL_COLLECTION),
PREF_BLOCKLIST_ONECRL_CHECKED_SECONDS,
updateCertBlocklist,
--- a/services/common/hawkclient.js
+++ b/services/common/hawkclient.js
@@ -109,19 +109,19 @@ this.HawkClient.prototype = {
* Construct an error message for a response. Private.
*
* @param restResponse
* A RESTResponse object from a RESTRequest
*
* @param error
* A string or object describing the error
*/
- _constructError: function(restResponse, error) {
+ _constructError(restResponse, error) {
let errorObj = {
- error: error,
+ error,
// This object is likely to be JSON.stringify'd, but neither Error()
// objects nor Components.Exception objects do the right thing there,
// so we add a new element which is simply the .toString() version of
// the error object, so it does appear in JSON'd values.
errorString: error.toString(),
message: restResponse.statusText,
code: restResponse.status,
errno: restResponse.status,
@@ -151,22 +151,22 @@ this.HawkClient.prototype = {
* easier, even though the value will not have millisecond accuracy.
*
* @param dateString
* An RFC 1123 date string (e.g., "Mon, 13 Jan 2014 21:45:06 GMT")
*
* For HAWK clock skew and replay protection, see
* https://github.com/hueniverse/hawk#replay-protection
*/
- _updateClockOffset: function(dateString) {
+ _updateClockOffset(dateString) {
try {
let serverDateMsec = Date.parse(dateString);
this._localtimeOffsetMsec = serverDateMsec - this.now();
log.debug("Clock offset vs " + this.host + ": " + this._localtimeOffsetMsec);
- } catch(err) {
+ } catch (err) {
log.warn("Bad date header in server response: " + dateString);
}
},
/*
* Get the current clock offset in milliseconds.
*
* The offset is the number of milliseconds that must be added to the client
@@ -175,17 +175,17 @@ this.HawkClient.prototype = {
*/
get localtimeOffsetMsec() {
return this._localtimeOffsetMsec;
},
/*
* return current time in milliseconds
*/
- now: function() {
+ now() {
return Date.now();
},
/* A general method for sending raw RESTRequest calls authorized using HAWK
*
* @param path
* API endpoint path
* @param method
@@ -198,18 +198,18 @@ this.HawkClient.prototype = {
* @param extraHeaders
* An object with header/value pairs to send with the request.
* @return Promise
* Returns a promise that resolves to the response of the API call,
* or is rejected with an error. If the server response can be parsed
* as JSON and contains an 'error' property, the promise will be
* rejected with this JSON-parsed response.
*/
- request: function(path, method, credentials=null, payloadObj={}, extraHeaders = {},
- retryOK=true) {
+ request(path, method, credentials = null, payloadObj = {}, extraHeaders = {},
+ retryOK = true) {
method = method.toLowerCase();
let deferred = Promise.defer();
let uri = this.host + path;
let self = this;
function _onComplete(error) {
// |error| can be either a normal caught error or an explicitly created
@@ -258,29 +258,29 @@ this.HawkClient.prototype = {
//
// In the case of a 401, in which we are probably being rejected for a
// bad timestamp, retry exactly once, during which time clock offset will
// be adjusted.
let jsonResponse = {};
try {
jsonResponse = JSON.parse(restResponse.body);
- } catch(notJSON) {}
+ } catch (notJSON) {}
let okResponse = (200 <= status && status < 300);
if (!okResponse || jsonResponse.error) {
if (jsonResponse.error) {
return deferred.reject(jsonResponse);
}
return deferred.reject(self._constructError(restResponse, "Request failed"));
}
// It's up to the caller to know how to decode the response.
// We just return the whole response.
deferred.resolve(this.response);
- };
+ }
function onComplete(error) {
try {
// |this| is the RESTRequest object and we need to ensure _onComplete
// gets the same one.
_onComplete.call(this, error);
} catch (ex) {
log.error("Unhandled exception processing response", ex);
@@ -314,17 +314,17 @@ this.HawkClient.prototype = {
* allows the handler of notifications to be sure they are handling
* notifications for the service they expect.
*
* If not set, no notifications will be sent.
*/
observerPrefix: null,
// Given an optional header value, notify that a backoff has been requested.
- _maybeNotifyBackoff: function (response, headerName) {
+ _maybeNotifyBackoff(response, headerName) {
if (!this.observerPrefix || !response.headers) {
return;
}
let headerVal = response.headers[headerName];
if (!headerVal) {
return;
}
let backoffInterval;
@@ -334,13 +334,13 @@ this.HawkClient.prototype = {
log.error("hawkclient response had invalid backoff value in '" +
headerName + "' header: " + headerVal);
return;
}
Observers.notify(this.observerPrefix + ":backoff:interval", backoffInterval);
},
// override points for testing.
- newHAWKAuthenticatedRESTRequest: function(uri, credentials, extra) {
+ newHAWKAuthenticatedRESTRequest(uri, credentials, extra) {
return new HAWKAuthenticatedRESTRequest(uri, credentials, extra);
},
}
--- a/services/common/hawkrequest.js
+++ b/services/common/hawkrequest.js
@@ -48,17 +48,17 @@ const Prefs = new Preferences("services.
*
* extra.localtimeOffsetMsec is the value in milliseconds that must be added to
* the local clock to make it agree with the server's clock. For instance, if
* the local clock is two minutes ahead of the server, the time offset in
* milliseconds will be -120000.
*/
this.HAWKAuthenticatedRESTRequest =
- function HawkAuthenticatedRESTRequest(uri, credentials, extra={}) {
+ function HawkAuthenticatedRESTRequest(uri, credentials, extra = {}) {
RESTRequest.call(this, uri);
this.credentials = credentials;
this.now = extra.now || Date.now();
this.localtimeOffsetMsec = extra.localtimeOffsetMsec || 0;
this._log.trace("local time, offset: " + this.now + ", " + (this.localtimeOffsetMsec));
this.extraHeaders = extra.headers || {};
@@ -74,17 +74,17 @@ HAWKAuthenticatedRESTRequest.prototype =
contentType = "application/json";
}
if (this.credentials) {
let options = {
now: this.now,
localtimeOffsetMsec: this.localtimeOffsetMsec,
credentials: this.credentials,
payload: data && JSON.stringify(data) || "",
- contentType: contentType,
+ contentType,
};
let header = CryptoUtils.computeHAWK(this.uri, method, options);
this.setHeader("Authorization", header.field);
this._log.trace("hawk auth header: " + header.field);
}
for (let header in this.extraHeaders) {
this.setHeader(header, this.extraHeaders[header]);
@@ -152,29 +152,29 @@ this.Intl = function Intl() {
this._accepted = "";
this._everRead = false;
this._log = Log.repository.getLogger("Services.common.RESTRequest");
this._log.level = Log.Level[Prefs.get("log.logger.rest.request")];
this.init();
};
this.Intl.prototype = {
- init: function() {
+ init() {
Services.prefs.addObserver("intl.accept_languages", this, false);
},
- uninit: function() {
+ uninit() {
Services.prefs.removeObserver("intl.accept_languages", this);
},
- observe: function(subject, topic, data) {
+ observe(subject, topic, data) {
this.readPref();
},
- readPref: function() {
+ readPref() {
this._everRead = true;
try {
this._accepted = Services.prefs.getComplexValue(
"intl.accept_languages", Ci.nsIPrefLocalizedString).data;
} catch (err) {
this._log.error("Error reading intl.accept_languages pref", err);
}
},
--- a/services/common/kinto-storage-adapter.js
+++ b/services/common/kinto-storage-adapter.js
@@ -324,35 +324,35 @@ class FirefoxAdapter extends Kinto.adapt
*/
loadDump(records) {
const connection = this._connection;
const collection_name = this.collection;
return Task.spawn(function* () {
yield connection.executeTransaction(function* doImport() {
for (let record of records) {
const params = {
- collection_name: collection_name,
+ collection_name,
record_id: record.id,
record: JSON.stringify(record),
};
yield connection.execute(statements.importData, params);
}
const lastModified = Math.max(...records.map(record => record.last_modified));
const params = {
- collection_name: collection_name,
+ collection_name,
};
const previousLastModified = yield connection.execute(
statements.getLastModified, params).then(result => {
return result.length > 0
? result[0].getResultByName("last_modified")
: -1;
});
if (lastModified > previousLastModified) {
const params = {
- collection_name: collection_name,
+ collection_name,
last_modified: lastModified,
};
yield connection.execute(statements.saveLastModified, params);
}
});
return records;
});
}
@@ -388,25 +388,24 @@ class FirefoxAdapter extends Kinto.adapt
// We're going to use execute instead of executeCached, so build
// in our own sanity check
if (!this._connection) {
throw new Error("The storage adapter is not open");
}
return this._connection.executeTransaction(function* (conn) {
const promises = [];
- yield conn.execute(statements.scanAllRecords, null, function (row) {
+ yield conn.execute(statements.scanAllRecords, null, function(row) {
const record = JSON.parse(row.getResultByName("record"));
const record_id = row.getResultByName("record_id");
const collection_name = row.getResultByName("collection_name");
if (record._status === "deleted") {
// Garbage collect deleted records.
promises.push(conn.execute(statements.deleteData, { collection_name, record_id }));
- }
- else {
+ } else {
const newRecord = Object.assign({}, record, {
_status: "created",
last_modified: undefined,
});
promises.push(conn.execute(statements.updateData, {
record: JSON.stringify(newRecord),
record_id,
collection_name,
--- a/services/common/modules-testing/storageserver.js
+++ b/services/common/modules-testing/storageserver.js
@@ -270,17 +270,17 @@ ServerBSO.prototype = {
* @param acceptNew
* If true, POSTs to this collection URI will result in new BSOs being
* created and wired in on the fly.
* @param timestamp
* An optional timestamp value to initialize the modified time of the
* collection. This should be in the format returned by new_timestamp().
*/
this.StorageServerCollection =
- function StorageServerCollection(bsos, acceptNew, timestamp=new_timestamp()) {
+ function StorageServerCollection(bsos, acceptNew, timestamp = new_timestamp()) {
this._bsos = bsos || {};
this.acceptNew = acceptNew || false;
/*
* Track modified timestamp.
* We can't just use the timestamps of contained BSOs: an empty collection
* has a modified time.
*/
@@ -572,17 +572,17 @@ StorageServerCollection.prototype = {
} else {
failed[record.id] = "no bso configured";
}
} catch (ex) {
this._log.info("Exception when processing BSO", ex);
failed[record.id] = "Exception when processing.";
}
}
- return {success: success, failed: failed};
+ return {success, failed};
},
delete: function delete_(options) {
options = options || {};
// Protocol 2.0 only allows the "ids" query string argument.
let keys = Object.keys(options).filter(function(k) {
return k != "ids";
@@ -800,17 +800,17 @@ StorageServerCollection.prototype = {
response.setStatusLine(request.httpVersion, 204, "No Content");
},
handler: function handler() {
let self = this;
return function(request, response) {
- switch(request.method) {
+ switch (request.method) {
case "GET":
return self.getHandler(request, response);
case "POST":
return self.postHandler(request, response);
case "DELETE":
return self.deleteHandler(request, response);
@@ -840,19 +840,19 @@ StorageServerCollection.prototype = {
this._log.info("Conditional request rejected because client time older " +
"than collection timestamp.");
response.setStatusLine(request.httpVersion, 412, "Precondition Failed");
return true;
},
};
-//===========================================================================//
+// ===========================================================================//
// httpd.js-based Storage server. //
-//===========================================================================//
+// ===========================================================================//
/**
* In general, the preferred way of using StorageServer is to directly
* introspect it. Callbacks are available for operations which are hard to
* verify through introspection, such as deletions.
*
* One of the goals of this server is to provide enough hooks for test code to
* find out what it needs without monkeypatching. Use this object as your
@@ -941,17 +941,17 @@ StorageServer.prototype = {
/**
* Start the server synchronously.
*
* @param port
* The numeric port on which to start. The default is to choose
* any available port.
*/
- startSynchronous: function startSynchronous(port=-1) {
+ startSynchronous: function startSynchronous(port = -1) {
let cb = Async.makeSpinningCallback();
this.start(port, cb);
cb.wait();
},
/**
* Stop the StorageServer's HTTP server.
*
@@ -991,17 +991,17 @@ StorageServer.prototype = {
}
if (!isFinite(parseInt(username))) {
throw new Error("Usernames must be numeric: " + username);
}
this._log.info("Registering new user with server: " + username);
this.users[username] = {
- password: password,
+ password,
collections: {},
quota: this.DEFAULT_QUOTA,
};
return this.user(username);
},
userExists: function userExists(username) {
return username in this.users;
@@ -1181,28 +1181,28 @@ StorageServer.prototype = {
* u.collection("bookmarks").bso("abcdefg").payload; // Etc.
*
* @return a proxy for the user data stored in this server.
*/
user: function user(username) {
let collection = this.getCollection.bind(this, username);
let createCollection = this.createCollection.bind(this, username);
let createContents = this.createContents.bind(this, username);
- let modified = function (collectionName) {
+ let modified = function(collectionName) {
return collection(collectionName).timestamp;
}
let deleteCollections = this.deleteCollections.bind(this, username);
let quota = this.getQuota.bind(this, username);
return {
- collection: collection,
- createCollection: createCollection,
- createContents: createContents,
- deleteCollections: deleteCollections,
- modified: modified,
- quota: quota,
+ collection,
+ createCollection,
+ createContents,
+ deleteCollections,
+ modified,
+ quota,
};
},
_pruneExpired: function _pruneExpired() {
let now = Date.now();
for (let username in this.users) {
let user = this.users[username];
--- a/services/common/observers.js
+++ b/services/common/observers.js
@@ -28,17 +28,17 @@ this.Observers = {
* the callback; an Object that implements nsIObserver or a Function
* that gets called when the notification occurs
*
* @param thisObject {Object} [optional]
* the object to use as |this| when calling a Function callback
*
* @returns the observer
*/
- add: function(topic, callback, thisObject) {
+ add(topic, callback, thisObject) {
let observer = new Observer(topic, callback, thisObject);
this._cache.push(observer);
this._service.addObserver(observer, topic, true);
return observer;
},
/**
@@ -48,23 +48,23 @@ this.Observers = {
* the topic being observed
*
* @param callback {Object}
* the callback doing the observing
*
* @param thisObject {Object} [optional]
* the object being used as |this| when calling a Function callback
*/
- remove: function(topic, callback, thisObject) {
+ remove(topic, callback, thisObject) {
// This seems fairly inefficient, but I'm not sure how much better
// we can make it. We could index by topic, but we can't index by callback
// or thisObject, as far as I know, since the keys to JavaScript hashes
// (a.k.a. objects) can apparently only be primitive values.
- let [observer] = this._cache.filter(v => v.topic == topic &&
- v.callback == callback &&
+ let [observer] = this._cache.filter(v => v.topic == topic &&
+ v.callback == callback &&
v.thisObject == thisObject);
if (observer) {
this._service.removeObserver(observer, topic);
this._cache.splice(this._cache.indexOf(observer), 1);
}
},
/**
@@ -78,19 +78,19 @@ this.Observers = {
*
* @param data {String} [optional] [deprecated]
* some more information about the topic; deprecated as the subject
* is sufficient to pass all needed information to the JS observers
* that this module targets; if you have multiple values to pass to
* the observer, wrap them in an object and pass them via the subject
* parameter (i.e.: { foo: 1, bar: "some string", baz: myObject })
*/
- notify: function(topic, subject, data) {
+ notify(topic, subject, data) {
subject = (typeof subject == "undefined") ? null : new Subject(subject);
- data = (typeof data == "undefined") ? null : data;
+ data = (typeof data == "undefined") ? null : data;
this._service.notifyObservers(subject, topic, data);
},
_service: Cc["@mozilla.org/observer-service;1"].
getService(Ci.nsIObserverService),
/**
* A cache of observers that have been added.
@@ -109,42 +109,41 @@ this.Observers = {
function Observer(topic, callback, thisObject) {
this.topic = topic;
this.callback = callback;
this.thisObject = thisObject;
}
Observer.prototype = {
QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver, Ci.nsISupportsWeakReference]),
- observe: function(subject, topic, data) {
+ observe(subject, topic, data) {
// Extract the wrapped object for subjects that are one of our wrappers
// around a JS object. This way we support both wrapped subjects created
// using this module and those that are real XPCOM components.
if (subject && typeof subject == "object" &&
("wrappedJSObject" in subject) &&
("observersModuleSubjectWrapper" in subject.wrappedJSObject))
subject = subject.wrappedJSObject.object;
if (typeof this.callback == "function") {
if (this.thisObject)
this.callback.call(this.thisObject, subject, data);
else
this.callback(subject, data);
- }
- else // typeof this.callback == "object" (nsIObserver)
+ } else // typeof this.callback == "object" (nsIObserver)
this.callback.observe(subject, topic, data);
}
}
function Subject(object) {
// Double-wrap the object and set a property identifying the wrappedJSObject
// as one of our wrappers to distinguish between subjects that are one of our
// wrappers (which we should unwrap when notifying our observers) and those
// that are real JS XPCOM components (which we should pass through unaltered).
- this.wrappedJSObject = { observersModuleSubjectWrapper: true, object: object };
+ this.wrappedJSObject = { observersModuleSubjectWrapper: true, object };
}
Subject.prototype = {
QueryInterface: XPCOMUtils.generateQI([]),
- getScriptableHelper: function() {},
- getInterfaces: function() {}
+ getScriptableHelper() {},
+ getInterfaces() {}
};
--- a/services/common/rest.js
+++ b/services/common/rest.js
@@ -97,17 +97,17 @@ RESTRequest.prototype = {
_logName: "Services.Common.RESTRequest",
QueryInterface: XPCOMUtils.generateQI([
Ci.nsIBadCertListener2,
Ci.nsIInterfaceRequestor,
Ci.nsIChannelEventSink
]),
- /*** Public API: ***/
+ /** * Public API: ***/
/**
* A constant boolean that indicates whether this object will automatically
* utf-8 encode request bodies passed as an object. Used for feature detection
* so, eg, loop can use the same source code for old and new Firefox versions.
*/
willUTF8EncodeObjectRequests: true,
@@ -288,17 +288,17 @@ RESTRequest.prototype = {
this.channel.cancel(Cr.NS_BINDING_ABORTED);
if (this.timeoutTimer) {
// Clear the abort timer now that the channel is done.
this.timeoutTimer.clear();
}
},
- /*** Implementation stuff ***/
+ /** * Implementation stuff ***/
dispatch: function dispatch(method, data, onComplete, onProgress) {
if (this.status != this.NOT_SENT) {
throw "Request has already been sent!";
}
this.method = method;
if (onComplete) {
@@ -407,17 +407,17 @@ RESTRequest.prototype = {
if (!this.onComplete) {
this._log.error("Unexpected error: onComplete not defined in " +
"abortTimeout.");
return;
}
this.onComplete(error);
},
- /*** nsIStreamListener ***/
+ /** * nsIStreamListener ***/
onStartRequest: function onStartRequest(channel) {
if (this.status == this.ABORTED) {
this._log.trace("Not proceeding with onStartRequest, request was aborted.");
return;
}
try {
@@ -568,23 +568,23 @@ RESTRequest.prototype = {
this.onComplete(ex);
this.onComplete = this.onProgress = null;
return;
}
this.delayTimeout();
},
- /*** nsIInterfaceRequestor ***/
+ /** * nsIInterfaceRequestor ***/
- getInterface: function(aIID) {
+ getInterface(aIID) {
return this.QueryInterface(aIID);
},
- /*** nsIBadCertListener2 ***/
+ /** * nsIBadCertListener2 ***/
notifyCertProblem: function notifyCertProblem(socketInfo, sslStatus, targetHost) {
this._log.warn("Invalid HTTPS certificate encountered!");
// Suppress invalid HTTPS certificate warnings in the UI.
// (The request will still fail.)
return true;
},
@@ -596,17 +596,17 @@ RESTRequest.prototype = {
shouldCopyOnRedirect: function shouldCopyOnRedirect(oldChannel, newChannel, flags) {
let isInternal = !!(flags & Ci.nsIChannelEventSink.REDIRECT_INTERNAL);
let isSameURI = newChannel.URI.equals(oldChannel.URI);
this._log.debug("Channel redirect: " + oldChannel.URI.spec + ", " +
newChannel.URI.spec + ", internal = " + isInternal);
return isInternal && isSameURI;
},
- /*** nsIChannelEventSink ***/
+ /** * nsIChannelEventSink ***/
asyncOnChannelRedirect:
function asyncOnChannelRedirect(oldChannel, newChannel, flags, callback) {
let oldSpec = (oldChannel && oldChannel.URI) ? oldChannel.URI.spec : "<undefined>";
let newSpec = (newChannel && newChannel.URI) ? newChannel.URI.spec : "<undefined>";
this._log.debug("Channel redirect: " + oldSpec + ", " + newSpec + ", " + flags);
try {
@@ -702,17 +702,17 @@ RESTResponse.prototype = {
/**
* Object containing HTTP headers (keyed as lower case)
*/
get headers() {
let headers = {};
try {
this._log.trace("Processing response headers.");
let channel = this.request.channel.QueryInterface(Ci.nsIHttpChannel);
- channel.visitResponseHeaders(function (header, value) {
+ channel.visitResponseHeaders(function(header, value) {
headers[header.toLowerCase()] = value;
});
} catch (ex) {
this._log.debug("Caught exception processing response headers", ex);
return null;
}
Object.defineProperty(this, "headers", {value: headers});
--- a/services/common/stringbundle.js
+++ b/services/common/stringbundle.js
@@ -40,18 +40,17 @@ StringBundle.prototype = {
* @type nsILocale
* @private
*/
get _appLocale() {
try {
return Cc["@mozilla.org/intl/nslocaleservice;1"].
getService(Ci.nsILocaleService).
getApplicationLocale();
- }
- catch(ex) {
+ } catch (ex) {
return null;
}
},
/**
* the wrapped nsIStringBundle
* @type nsIStringBundle
* @private
@@ -85,30 +84,30 @@ StringBundle.prototype = {
*
* @param key {String}
* the identifier of the string to get
* @param args {array} [optional]
* an array of arguments that replace occurrences of %S in the string
*
* @returns {String} the value of the string
*/
- get: function(key, args) {
+ get(key, args) {
if (args)
return this.stringBundle.formatStringFromName(key, args, args.length);
else
return this.stringBundle.GetStringFromName(key);
},
/**
* Get all the strings in the bundle.
*
* @returns {Array}
* an array of objects with key and value properties
*/
- getAll: function() {
+ getAll() {
let strings = [];
// FIXME: for performance, return an enumerable array that wraps the string
// bundle's nsISimpleEnumerator (does JavaScript already support this?).
let enumerator = this.stringBundle.getSimpleEnumeration();
while (enumerator.hasMoreElements()) {
@@ -165,33 +164,33 @@ StringBundle.prototype = {
* @deprecated use |get| instead
*
* @param key {String}
* the identifier of the string to get
*
* @returns {String}
* the value of the string
*/
- getString: function(key) {
+ getString(key) {
return this.get(key);
},
/**
* Get a formatted string from the bundle.
* @deprecated use |get| instead
*
* @param key {string}
* the identifier of the string to get
* @param args {array}
* an array of arguments that replace occurrences of %S in the string
*
* @returns {String}
* the formatted value of the string
*/
- getFormattedString: function(key, args) {
+ getFormattedString(key, args) {
return this.get(key, args);
},
/**
* Get an enumeration of the strings in the bundle.
* @deprecated use |getAll| instead
*
* @returns {nsISimpleEnumerator}
--- a/services/common/tests/unit/head_helpers.js
+++ b/services/common/tests/unit/head_helpers.js
@@ -64,17 +64,17 @@ function do_check_throws_message(aFunc,
* Any number of arguments to print out
* @usage _("Hello World") -> prints "Hello World"
* @usage _(1, 2, 3) -> prints "1 2 3"
*/
var _ = function(some, debug, text, to) {
print(Array.slice(arguments).join(" "));
};
-function httpd_setup (handlers, port=-1) {
+function httpd_setup(handlers, port = -1) {
let server = new HttpServer();
for (let path in handlers) {
server.registerPathHandler(path, handlers[path]);
}
try {
server.start(port);
} catch (ex) {
_("==========================================");
--- a/services/common/tests/unit/test_async_chain.js
+++ b/services/common/tests/unit/test_async_chain.js
@@ -2,27 +2,27 @@
* http://creativecommons.org/publicdomain/zero/1.0/ */
Cu.import("resource://services-common/async.js");
function run_test() {
_("Chain a few async methods, making sure the 'this' object is correct.");
let methods = {
- save: function(x, callback) {
+ save(x, callback) {
this.x = x;
callback(x);
},
- addX: function(x, callback) {
+ addX(x, callback) {
callback(x + this.x);
},
- double: function(x, callback) {
+ double(x, callback) {
callback(x * 2);
},
- neg: function(x, callback) {
+ neg(x, callback) {
callback(-x);
}
};
methods.chain = Async.chain;
// ((1 + 1 + 1) * (-1) + 1) * 2 + 1 = -3
methods.chain(methods.save, methods.addX, methods.addX, methods.neg,
methods.addX, methods.double, methods.addX, methods.save)(1);
--- a/services/common/tests/unit/test_async_querySpinningly.js
+++ b/services/common/tests/unit/test_async_querySpinningly.js
@@ -80,20 +80,20 @@ function run_test() {
_("Grabbing fewer fields than queried is fine");
let r10 = querySpinningly("SELECT value, fieldname FROM moz_formhistory", ["fieldname"]);
do_check_eq(r10.length, 3);
_("Generate an execution error");
let query = "INSERT INTO moz_formhistory (fieldname, value) VALUES ('one', NULL)";
let stmt = Svc.Form.DBConnection.createStatement(query);
- let r11, except; ;
+ let r11, except;
try {
r11 = Async.querySpinningly(stmt);
- } catch(e) {
+ } catch (e) {
except = e;
}
stmt.finalize()
do_check_true(!!except);
do_check_eq(except.result, SQLITE_CONSTRAINT_VIOLATION);
_("Cleaning up");
querySpinningly("DELETE FROM moz_formhistory");
--- a/services/common/tests/unit/test_blocklist_certificates.js
+++ b/services/common/tests/unit/test_blocklist_certificates.js
@@ -26,25 +26,25 @@ function do_get_kinto_collection(collect
};
return new Kinto(config).collection(collectionName);
}
// Some simple tests to demonstrate that the logic inside maybeSync works
// correctly and that simple kinto operations are working as expected. There
// are more tests for core Kinto.js (and its storage adapter) in the
// xpcshell tests under /services/common
-add_task(function* test_something(){
+add_task(function* test_something() {
const configPath = "/v1/";
const recordsPath = "/v1/buckets/blocklists/collections/certificates/records";
Services.prefs.setCharPref("services.settings.server",
`http://localhost:${server.identity.primaryPort}/v1`);
// register a handler
- function handleResponse (request, response) {
+ function handleResponse(request, response) {
try {
const sample = getSampleResponse(request, server.identity.primaryPort);
if (!sample) {
do_throw(`unexpected ${request.method} request for ${request.path}?${request.queryString}`);
}
response.setStatusLine(null, sample.status.status,
sample.status.statusText);
@@ -174,17 +174,17 @@ function getSampleResponse(req, port) {
"Etag: \"4000\""
],
"status": {status: 200, statusText: "OK"},
"responseBody": JSON.stringify({"data":[{
"issuerName":"MFkxCzAJBgNVBAYTAk5MMR4wHAYDVQQKExVTdGFhdCBkZXIgTmVkZXJsYW5kZW4xKjAoBgNVBAMTIVN0YWF0IGRlciBOZWRlcmxhbmRlbiBPdmVyaGVpZCBDQQ",
"serialNumber":"ATFpsA==",
"id":"dabafde9-df4a-ddba-2548-748da04cc02c",
"last_modified":4000
- },{
+ }, {
"subject":"MCIxIDAeBgNVBAMMF0Fub3RoZXIgVGVzdCBFbmQtZW50aXR5",
"pubKeyHash":"VCIlmPM9NkgFQtrs4Oa5TeFcDu6MWRTKSNdePEhOgD8=",
"id":"dabafde9-df4a-ddba-2548-748da04cc02d",
"last_modified":4000
}]})
},
"GET:/v1/buckets/blocklists/collections/certificates/records?_sort=-last_modified&_since=4000": {
"sampleHeaders": [
@@ -195,22 +195,22 @@ function getSampleResponse(req, port) {
"Etag: \"5000\""
],
"status": {status: 200, statusText: "OK"},
"responseBody": JSON.stringify({"data":[{
"issuerName":"not a base64 encoded issuer",
"serialNumber":"not a base64 encoded serial",
"id":"dabafde9-df4a-ddba-2548-748da04cc02e",
"last_modified":5000
- },{
+ }, {
"subject":"not a base64 encoded subject",
"pubKeyHash":"not a base64 encoded pubKeyHash",
"id":"dabafde9-df4a-ddba-2548-748da04cc02f",
"last_modified":5000
- },{
+ }, {
"subject":"MCIxIDAeBgNVBAMMF0Fub3RoZXIgVGVzdCBFbmQtZW50aXR5",
"pubKeyHash":"VCIlmPM9NkgFQtrs4Oa5TeFcDu6MWRTKSNdePEhOgD8=",
"id":"dabafde9-df4a-ddba-2548-748da04cc02g",
"last_modified":5000
}]})
}
};
return responses[`${req.method}:${req.path}?${req.queryString}`] ||
--- a/services/common/tests/unit/test_blocklist_clients.js
+++ b/services/common/tests/unit/test_blocklist_clients.js
@@ -12,19 +12,19 @@ const { Kinto } = Cu.import("resource://
const { FirefoxAdapter } = Cu.import("resource://services-common/kinto-storage-adapter.js", {});
const BlocklistClients = Cu.import("resource://services-common/blocklist-clients.js", {});
const BinaryInputStream = CC("@mozilla.org/binaryinputstream;1",
"nsIBinaryInputStream", "setInputStream");
const kintoFilename = "kinto.sqlite";
const gBlocklistClients = [
- {client: BlocklistClients.AddonBlocklistClient, filename: BlocklistClients.FILENAME_ADDONS_JSON, testData: ["i808","i720", "i539"]},
- {client: BlocklistClients.PluginBlocklistClient, filename: BlocklistClients.FILENAME_PLUGINS_JSON, testData: ["p1044","p32","p28"]},
- {client: BlocklistClients.GfxBlocklistClient, filename: BlocklistClients.FILENAME_GFX_JSON, testData: ["g204","g200","g36"]},
+ {client: BlocklistClients.AddonBlocklistClient, filename: BlocklistClients.FILENAME_ADDONS_JSON, testData: ["i808", "i720", "i539"]},
+ {client: BlocklistClients.PluginBlocklistClient, filename: BlocklistClients.FILENAME_PLUGINS_JSON, testData: ["p1044", "p32", "p28"]},
+ {client: BlocklistClients.GfxBlocklistClient, filename: BlocklistClients.FILENAME_GFX_JSON, testData: ["g204", "g200", "g36"]},
];
let server;
function kintoCollection(collectionName, sqliteHandle) {
const config = {
// Set the remote to be some server that will cause test failure when
@@ -113,58 +113,58 @@ function run_test() {
run_next_test();
do_register_cleanup(function() {
server.stop(() => { });
});
}
-add_task(function* test_records_obtained_from_server_are_stored_in_db(){
+add_task(function* test_records_obtained_from_server_are_stored_in_db() {
for (let {client} of gBlocklistClients) {
// Test an empty db populates
let result = yield client.maybeSync(2000, Date.now());
// Open the collection, verify it's been populated:
// Our test data has a single record; it should be in the local collection
const sqliteHandle = yield FirefoxAdapter.openConnection({path: kintoFilename});
let collection = kintoCollection(client.collectionName, sqliteHandle);
let list = yield collection.list();
equal(list.data.length, 1);
yield sqliteHandle.close();
}
});
add_task(clear_state);
-add_task(function* test_list_is_written_to_file_in_profile(){
+add_task(function* test_list_is_written_to_file_in_profile() {
for (let {client, filename, testData} of gBlocklistClients) {
const profFile = FileUtils.getFile(KEY_PROFILEDIR, [filename]);
strictEqual(profFile.exists(), false);
let result = yield client.maybeSync(2000, Date.now());
strictEqual(profFile.exists(), true);
const content = yield readJSON(profFile.path);
equal(content.data[0].blockID, testData[testData.length - 1]);
}
});
add_task(clear_state);
-add_task(function* test_current_server_time_is_saved_in_pref(){
+add_task(function* test_current_server_time_is_saved_in_pref() {
for (let {client} of gBlocklistClients) {
const before = Services.prefs.getIntPref(client.lastCheckTimePref);
const serverTime = Date.now();
yield client.maybeSync(2000, serverTime);
const after = Services.prefs.getIntPref(client.lastCheckTimePref);
equal(after, Math.round(serverTime / 1000));
}
});
add_task(clear_state);
-add_task(function* test_update_json_file_when_addons_has_changes(){
+add_task(function* test_update_json_file_when_addons_has_changes() {
for (let {client, filename, testData} of gBlocklistClients) {
yield client.maybeSync(2000, Date.now() - 1000);
const before = Services.prefs.getIntPref(client.lastCheckTimePref);
const profFile = FileUtils.getFile(KEY_PROFILEDIR, [filename]);
const fileLastModified = profFile.lastModifiedTime = profFile.lastModifiedTime - 1000;
const serverTime = Date.now();
yield client.maybeSync(3001, serverTime);
@@ -175,32 +175,32 @@ add_task(function* test_update_json_file
deepEqual(content.data.map((r) => r.blockID), testData);
// Server time was updated.
const after = Services.prefs.getIntPref(client.lastCheckTimePref);
equal(after, Math.round(serverTime / 1000));
}
});
add_task(clear_state);
-add_task(function* test_sends_reload_message_when_blocklist_has_changes(){
+add_task(function* test_sends_reload_message_when_blocklist_has_changes() {
for (let {client, filename} of gBlocklistClients) {
let received = yield new Promise((resolve, reject) => {
Services.ppmm.addMessageListener("Blocklist:reload-from-disk", {
receiveMessage(aMsg) { resolve(aMsg) }
});
client.maybeSync(2000, Date.now() - 1000);
});
equal(received.data.filename, filename);
}
});
add_task(clear_state);
-add_task(function* test_do_nothing_when_blocklist_is_up_to_date(){
+add_task(function* test_do_nothing_when_blocklist_is_up_to_date() {
for (let {client, filename} of gBlocklistClients) {
yield client.maybeSync(2000, Date.now() - 1000);
const before = Services.prefs.getIntPref(client.lastCheckTimePref);
const profFile = FileUtils.getFile(KEY_PROFILEDIR, [filename]);
const fileLastModified = profFile.lastModifiedTime = profFile.lastModifiedTime - 1000;
const serverTime = Date.now();
yield client.maybeSync(3000, serverTime);
--- a/services/common/tests/unit/test_blocklist_pinning.js
+++ b/services/common/tests/unit/test_blocklist_pinning.js
@@ -19,17 +19,17 @@ var id = "xpcshell@tests.mozilla.org";
var appName = "XPCShell";
var version = "1";
var platformVersion = "1.9.2";
Cu.import("resource://testing-common/AppInfo.jsm", this);
updateAppInfo({
name: appName,
ID: id,
- version: version,
+ version,
platformVersion: platformVersion ? platformVersion : "1.0",
crashReporter: true,
});
let server;
function do_get_kinto_collection(connection, collectionName) {
@@ -44,32 +44,32 @@ function do_get_kinto_collection(connect
bucket: "pinning"
};
let kintoClient = new Kinto(config);
return kintoClient.collection(collectionName);
}
// Some simple tests to demonstrate that the core preload sync operations work
// correctly and that simple kinto operations are working as expected.
-add_task(function* test_something(){
+add_task(function* test_something() {
// set the collection name explicitly - since there will be version
// specific collection names in prefs
Services.prefs.setCharPref(PREF_BLOCKLIST_PINNING_COLLECTION,
COLLECTION_NAME);
const { PinningPreloadClient } = Cu.import("resource://services-common/blocklist-clients.js", {});
const configPath = "/v1/";
const recordsPath = "/v1/buckets/pinning/collections/pins/records";
Services.prefs.setCharPref("services.settings.server",
`http://localhost:${server.identity.primaryPort}/v1`);
// register a handler
- function handleResponse (request, response) {
+ function handleResponse(request, response) {
try {
const sample = getSampleResponse(request, server.identity.primaryPort);
if (!sample) {
do_throw(`unexpected ${request.method} request for ${request.path}?${request.queryString}`);
}
response.setStatusLine(null, sample.status.status,
sample.status.statusText);
@@ -240,37 +240,37 @@ function getSampleResponse(req, port) {
"hostName": "two.example.com",
"includeSubdomains": false,
"expires": new Date().getTime() + 1000000,
"pins" : ["cUPcTAZWKaASuYWhhneDttWpY3oBAkE3h2+soZS7sWs=",
"M8HztCzM3elUxkcjR2S5P4hhyBNf6lHkmjAHKhpGPWE="],
"versions" : [appInfo.version],
"id":"dabafde9-df4a-ddba-2548-748da04cc02c",
"last_modified":4000
- },{
+ }, {
"pinType": "KeyPin",
"hostName": "three.example.com",
"includeSubdomains": false,
"expires": new Date().getTime() + 1000000,
"pins" : ["cUPcTAZWKaASuYWhhneDttWpY3oBAkE3h2+soZS7sWs=",
"M8HztCzM3elUxkcjR2S5P4hhyBNf6lHkmjAHKhpGPWE="],
"versions" : [appInfo.version, "some other version that won't match"],
"id":"dabafde9-df4a-ddba-2548-748da04cc02d",
"last_modified":4000
- },{
+ }, {
"pinType": "KeyPin",
"hostName": "four.example.com",
"includeSubdomains": false,
"expires": new Date().getTime() + 1000000,
"pins" : ["cUPcTAZWKaASuYWhhneDttWpY3oBAkE3h2+soZS7sWs=",
"M8HztCzM3elUxkcjR2S5P4hhyBNf6lHkmjAHKhpGPWE="],
"versions" : ["some version that won't match"],
"id":"dabafde9-df4a-ddba-2548-748da04cc02e",
"last_modified":4000
- },{
+ }, {
"pinType": "STSPin",
"hostName": "five.example.com",
"includeSubdomains": false,
"expires": new Date().getTime() + 1000000,
"versions" : [appInfo.version, "some version that won't match"],
"id":"dabafde9-df4a-ddba-2548-748da04cc032",
"last_modified":4000
}]})
@@ -284,35 +284,35 @@ function getSampleResponse(req, port) {
"Etag: \"5000\""
],
"status": {status: 200, statusText: "OK"},
"responseBody": JSON.stringify({"data":[{
"irrelevant":"this entry looks nothing whatsoever like a pin preload",
"pinType": "KeyPin",
"id":"dabafde9-df4a-ddba-2548-748da04cc02f",
"last_modified":5000
- },{
+ }, {
"irrelevant":"this entry has data of the wrong type",
"pinType": "KeyPin",
"hostName": 3,
"includeSubdomains": "nonsense",
"expires": "more nonsense",
- "pins" : [1,2,3,4],
+ "pins" : [1, 2, 3, 4],
"id":"dabafde9-df4a-ddba-2548-748da04cc030",
"last_modified":5000
- },{
+ }, {
"irrelevant":"this entry is missing the actual pins",
"pinType": "KeyPin",
"hostName": "missingpins.example.com",
"includeSubdomains": false,
"expires": new Date().getTime() + 1000000,
"versions" : [appInfo.version],
"id":"dabafde9-df4a-ddba-2548-748da04cc031",
"last_modified":5000
- },{
+ }, {
"pinType": "STSPin",
"hostName": "five.example.com",
"includeSubdomains": true,
"expires": new Date().getTime() + 1000000,
"versions" : [appInfo.version, "some version that won't match"],
"id":"dabafde9-df4a-ddba-2548-748da04cc032",
"last_modified":5000
}]})
--- a/services/common/tests/unit/test_blocklist_signatures.js
+++ b/services/common/tests/unit/test_blocklist_signatures.js
@@ -60,17 +60,17 @@ function* checkRecordCount(count) {
const base = Services.prefs.getCharPref(PREF_SETTINGS_SERVER);
const bucket = Services.prefs.getCharPref(PREF_BLOCKLIST_BUCKET);
const collectionName =
Services.prefs.getCharPref(PREF_BLOCKLIST_ONECRL_COLLECTION);
const sqliteHandle = yield FirefoxAdapter.openConnection({path: kintoFilename});
const config = {
remote: base,
- bucket: bucket,
+ bucket,
adapter: FirefoxAdapter,
adapterOptions: {sqliteHandle},
};
const db = new Kinto(config);
const collection = db.collection(collectionName);
// Check we have the expected number of records
@@ -78,52 +78,52 @@ function* checkRecordCount(count) {
do_check_eq(count, records.data.length);
// Close the collection so the test can exit cleanly
yield sqliteHandle.close();
}
// Check to ensure maybeSync is called with correct values when a changes
// document contains information on when a collection was last modified
-add_task(function* test_check_signatures(){
+add_task(function* test_check_signatures() {
const port = server.identity.primaryPort;
// a response to give the client when the cert chain is expected
function makeMetaResponseBody(lastModified, signature) {
return {
data: {
id: "certificates",
last_modified: lastModified,
signature: {
x5u: `http://localhost:${port}/test_blocklist_signatures/test_cert_chain.pem`,
public_key: "fake",
"content-signature": `x5u=http://localhost:${port}/test_blocklist_signatures/test_cert_chain.pem;p384ecdsa=${signature}`,
signature_encoding: "rs_base64url",
- signature: signature,
+ signature,
hash_algorithm: "sha384",
ref: "1yryrnmzou5rf31ou80znpnq8n"
}
}
};
}
function makeMetaResponse(eTag, body, comment) {
return {
- comment: comment,
+ comment,
sampleHeaders: [
"Content-Type: application/json; charset=UTF-8",
`ETag: \"${eTag}\"`
],
status: {status: 200, statusText: "OK"},
responseBody: JSON.stringify(body)
};
}
- function registerHandlers(responses){
- function handleResponse (serverTimeMillis, request, response) {
+ function registerHandlers(responses) {
+ function handleResponse(serverTimeMillis, request, response) {
const key = `${request.method}:${request.path}?${request.queryString}`;
const available = responses[key];
const sampled = available.length > 1 ? available.shift() : available[0];
if (!sampled) {
do_throw(`unexpected ${request.method} request for ${request.path}?${request.queryString}`);
}
--- a/services/common/tests/unit/test_blocklist_updater.js
+++ b/services/common/tests/unit/test_blocklist_updater.js
@@ -4,21 +4,21 @@ var server;
const PREF_SETTINGS_SERVER = "services.settings.server";
const PREF_LAST_UPDATE = "services.blocklist.last_update_seconds";
const PREF_LAST_ETAG = "services.blocklist.last_etag";
const PREF_CLOCK_SKEW_SECONDS = "services.blocklist.clock_skew_seconds";
// Check to ensure maybeSync is called with correct values when a changes
// document contains information on when a collection was last modified
-add_task(function* test_check_maybeSync(){
+add_task(function* test_check_maybeSync() {
const changesPath = "/v1/buckets/monitor/collections/changes/records";
// register a handler
- function handleResponse (serverTimeMillis, request, response) {
+ function handleResponse(serverTimeMillis, request, response) {
try {
const sampled = getSampleResponse(request, server.identity.primaryPort);
if (!sampled) {
do_throw(`unexpected ${request.method} request for ${request.path}?${request.queryString}`);
}
response.setStatusLine(null, sampled.status.status,
sampled.status.statusText);
@@ -82,25 +82,25 @@ add_task(function* test_check_maybeSync(
// Last timestamp was saved. An ETag header value is a quoted string.
let lastEtag = Services.prefs.getCharPref(PREF_LAST_ETAG);
do_check_eq(lastEtag, "\"1100\"");
// Simulate a poll with up-to-date collection.
Services.prefs.setIntPref(PREF_LAST_UPDATE, 0);
// If server has no change, a 304 is received, maybeSync() is not called.
updater.addTestBlocklistClient("test-collection", {
- maybeSync: () => {throw new Error("Should not be called");}
+ maybeSync: () => { throw new Error("Should not be called"); }
});
yield updater.checkVersions();
// Last update is overwritten
do_check_eq(Services.prefs.getIntPref(PREF_LAST_UPDATE), 2);
// Simulate a server error.
- function simulateErrorResponse (request, response) {
+ function simulateErrorResponse(request, response) {
response.setHeader("Date", (new Date(3000)).toUTCString());
response.setHeader("Content-Type", "application/json; charset=UTF-8");
response.write(JSON.stringify({
code: 503,
errno: 999,
error: "Service Unavailable",
}));
response.setStatusLine(null, 503, "Service Unavailable");
--- a/services/common/tests/unit/test_hawkclient.js
+++ b/services/common/tests/unit/test_hawkclient.js
@@ -151,17 +151,17 @@ add_task(function* test_server_error() {
}
});
let client = new HawkClient(server.baseURI);
try {
yield client.request("/foo", method, TEST_CREDS);
do_throw("Expected an error");
- } catch(err) {
+ } catch (err) {
do_check_eq(418, err.code);
do_check_eq("I am a Teapot", err.message);
}
yield deferredStop(server);
});
add_task(function* test_server_error_json() {
@@ -174,17 +174,17 @@ add_task(function* test_server_error_jso
}
});
let client = new HawkClient(server.baseURI);
try {
yield client.request("/foo", method, TEST_CREDS);
do_throw("Expected an error");
- } catch(err) {
+ } catch (err) {
do_check_eq("Cannot get ye flask.", err.error);
}
yield deferredStop(server);
});
add_task(function* test_offset_after_request() {
let message = "Ohai!";
@@ -307,17 +307,17 @@ add_task(function* test_retry_request_on
return;
}
// Second time through, timestamp should be corrected by client
do_check_true(delta < MINUTE_MS);
let message = "i love you!!!";
response.setStatusLine(request.httpVersion, 200, "OK");
response.bodyOutputStream.write(message, message.length);
- return;
+
}
});
let client = new HawkClient(server.baseURI);
function getOffset() {
return client.localtimeOffsetMsec;
}
@@ -412,17 +412,17 @@ add_task(function* test_500_no_retry() {
client.now = () => {
return Date.now() - 12 * HOUR_MS;
};
// Request will 500; no retries
try {
yield client.request("/no-shutup", method, credentials);
do_throw("Expected an error");
- } catch(err) {
+ } catch (err) {
do_check_eq(err.code, 500);
}
yield deferredStop(server);
});
add_task(function* test_401_then_500() {
// Like test_multiple_401_retry_once, but return a 500 to the
@@ -456,17 +456,17 @@ add_task(function* test_401_then_500() {
}
// Second time through, timestamp should be corrected by client
// And fail on the client
do_check_true(delta < MINUTE_MS);
let message = "Cannot get ye flask.";
response.setStatusLine(request.httpVersion, 500, "Internal server error");
response.bodyOutputStream.write(message, message.length);
- return;
+
}
});
let client = new HawkClient(server.baseURI);
function getOffset() {
return client.localtimeOffsetMsec;
}
@@ -475,38 +475,38 @@ add_task(function* test_401_then_500() {
};
// We begin with no offset
do_check_eq(client.localtimeOffsetMsec, 0);
// Request will have bad timestamp; client will retry once
try {
yield client.request("/maybe", method, credentials);
- } catch(err) {
+ } catch (err) {
do_check_eq(err.code, 500);
}
do_check_eq(attempts, 2);
yield deferredStop(server);
});
add_task(function* throw_if_not_json_body() {
let client = new HawkClient("https://example.com");
try {
yield client.request("/bogus", "GET", {}, "I am not json");
do_throw("Expected an error");
- } catch(err) {
+ } catch (err) {
do_check_true(!!err.message);
}
});
// End of tests.
// Utility functions follow
-function getTimestampDelta(authHeader, now=Date.now()) {
+function getTimestampDelta(authHeader, now = Date.now()) {
let tsMS = new Date(
parseInt(/ts="(\d+)"/.exec(authHeader)[1], 10) * SECOND_MS);
return Math.abs(tsMS - now);
}
function deferredStop(server) {
let deferred = Promise.defer();
server.stop(deferred.resolve);
--- a/services/common/tests/unit/test_hawkrequest.js
+++ b/services/common/tests/unit/test_hawkrequest.js
@@ -4,23 +4,23 @@
"use strict";
Cu.import("resource://gre/modules/Log.jsm");
Cu.import("resource://services-common/utils.js");
Cu.import("resource://services-common/hawkrequest.js");
// https://github.com/mozilla/fxa-auth-server/wiki/onepw-protocol#wiki-use-session-certificatesign-etc
var SESSION_KEYS = {
- sessionToken: h("a0a1a2a3a4a5a6a7 a8a9aaabacadaeaf"+
+ sessionToken: h("a0a1a2a3a4a5a6a7 a8a9aaabacadaeaf" +
"b0b1b2b3b4b5b6b7 b8b9babbbcbdbebf"),
- tokenID: h("c0a29dcf46174973 da1378696e4c82ae"+
+ tokenID: h("c0a29dcf46174973 da1378696e4c82ae" +
"10f723cf4f4d9f75 e39f4ae3851595ab"),
- reqHMACkey: h("9d8f22998ee7f579 8b887042466b72d5"+
+ reqHMACkey: h("9d8f22998ee7f579 8b887042466b72d5" +
"3e56ab0c094388bf 65831f702d2febc0"),
};
function do_register_cleanup() {
Services.prefs.resetUserPrefs();
// remove the pref change listener
let hawk = new HAWKAuthenticatedRESTRequest("https://example.com");
@@ -70,17 +70,17 @@ add_test(function test_intl_accept_langu
setLanguagePref(languages[testCount]);
return;
}
// We've checked all the entries in languages[]. Cleanup and move on.
do_print("Checked " + testCount + " languages. Removing checkLanguagePref as pref observer.");
Services.prefs.removeObserver("intl.accept_languages", checkLanguagePref);
run_next_test();
- return;
+
});
}
});
add_test(function test_hawk_authenticated_request() {
let onProgressCalled = false;
let postData = {your: "data"};
@@ -196,17 +196,17 @@ add_test(function test_hawk_language_pre
// language.
request = new HAWKAuthenticatedRESTRequest(url, credentials);
CommonUtils.nextTick(testFirstLanguage);
function testFirstLanguage() {
do_check_eq(languages[0], request._intl.accept_languages);
// Change the language pref ...
- setLanguage(languages[1]);
+ setLanguage(languages[1]);
CommonUtils.nextTick(testRequest);
}
function testRequest() {
// Change of language pref should be picked up, which we can see on the
// server by inspecting the request headers.
request = new HAWKAuthenticatedRESTRequest(url, credentials);
request.post({}, function(error) {
--- a/services/common/tests/unit/test_kinto.js
+++ b/services/common/tests/unit/test_kinto.js
@@ -12,17 +12,17 @@ var server;
// set up what we need to make storage adapters
const kintoFilename = "kinto.sqlite";
function do_get_kinto_sqliteHandle() {
return FirefoxAdapter.openConnection({path: kintoFilename});
}
-function do_get_kinto_collection(sqliteHandle, collection="test_collection") {
+function do_get_kinto_collection(sqliteHandle, collection = "test_collection") {
let config = {
remote:`http://localhost:${server.identity.primaryPort}/v1/`,
headers: {Authorization: "Basic " + btoa("user:pass")},
adapter: FirefoxAdapter,
adapterOptions: {sqliteHandle},
};
return new Kinto(config).collection(collection);
}
@@ -149,17 +149,17 @@ add_task(function* test_kinto_clear() {
do_check_eq(list.data.length, 0);
} finally {
yield sqliteHandle.close();
}
});
add_task(clear_collection);
-add_task(function* test_kinto_delete(){
+add_task(function* test_kinto_delete() {
let sqliteHandle;
try {
sqliteHandle = yield do_get_kinto_sqliteHandle();
const collection = do_get_kinto_collection(sqliteHandle);
const newRecord = { foo: "bar" };
// check a record is created
let createResult = yield collection.create(newRecord);
do_check_eq(createResult.data.foo, newRecord.foo);
@@ -175,17 +175,17 @@ add_task(function* test_kinto_delete(){
getResult = yield collection.get(createResult.data.id);
do_throw("there should not be a result");
} catch (e) { }
} finally {
yield sqliteHandle.close();
}
});
-add_task(function* test_kinto_list(){
+add_task(function* test_kinto_list() {
let sqliteHandle;
try {
sqliteHandle = yield do_get_kinto_sqliteHandle();
const collection = do_get_kinto_collection(sqliteHandle);
const expected = 10;
const created = [];
for (let i = 0; i < expected; i++) {
let newRecord = { foo: "test " + i };
@@ -209,67 +209,67 @@ add_task(function* test_kinto_list(){
}
} finally {
yield sqliteHandle.close();
}
});
add_task(clear_collection);
-add_task(function* test_loadDump_ignores_already_imported_records(){
+add_task(function* test_loadDump_ignores_already_imported_records() {
let sqliteHandle;
try {
sqliteHandle = yield do_get_kinto_sqliteHandle();
const collection = do_get_kinto_collection(sqliteHandle);
const record = {id: "41b71c13-17e9-4ee3-9268-6a41abf9730f", title: "foo", last_modified: 1457896541};
yield collection.loadDump([record]);
let impactedRecords = yield collection.loadDump([record]);
do_check_eq(impactedRecords.length, 0);
} finally {
yield sqliteHandle.close();
}
});
add_task(clear_collection);
-add_task(function* test_loadDump_should_overwrite_old_records(){
+add_task(function* test_loadDump_should_overwrite_old_records() {
let sqliteHandle;
try {
sqliteHandle = yield do_get_kinto_sqliteHandle();
const collection = do_get_kinto_collection(sqliteHandle);
const record = {id: "41b71c13-17e9-4ee3-9268-6a41abf9730f", title: "foo", last_modified: 1457896541};
yield collection.loadDump([record]);
const updated = Object.assign({}, record, {last_modified: 1457896543});
let impactedRecords = yield collection.loadDump([updated]);
do_check_eq(impactedRecords.length, 1);
} finally {
yield sqliteHandle.close();
}
});
add_task(clear_collection);
-add_task(function* test_loadDump_should_not_overwrite_unsynced_records(){
+add_task(function* test_loadDump_should_not_overwrite_unsynced_records() {
let sqliteHandle;
try {
sqliteHandle = yield do_get_kinto_sqliteHandle();
const collection = do_get_kinto_collection(sqliteHandle);
const recordId = "41b71c13-17e9-4ee3-9268-6a41abf9730f";
yield collection.create({id: recordId, title: "foo"}, {useRecordId: true});
const record = {id: recordId, title: "bar", last_modified: 1457896541};
let impactedRecords = yield collection.loadDump([record]);
do_check_eq(impactedRecords.length, 0);
} finally {
yield sqliteHandle.close();
}
});
add_task(clear_collection);
-add_task(function* test_loadDump_should_not_overwrite_records_without_last_modified(){
+add_task(function* test_loadDump_should_not_overwrite_records_without_last_modified() {
let sqliteHandle;
try {
sqliteHandle = yield do_get_kinto_sqliteHandle();
const collection = do_get_kinto_collection(sqliteHandle);
const recordId = "41b71c13-17e9-4ee3-9268-6a41abf9730f";
yield collection.create({id: recordId, title: "foo"}, {synced: true});
const record = {id: recordId, title: "bar", last_modified: 1457896541};
let impactedRecords = yield collection.loadDump([record]);
@@ -279,21 +279,21 @@ add_task(function* test_loadDump_should_
}
});
add_task(clear_collection);
// Now do some sanity checks against a server - we're not looking to test
// core kinto.js functionality here (there is excellent test coverage in
// kinto.js), more making sure things are basically working as expected.
-add_task(function* test_kinto_sync(){
+add_task(function* test_kinto_sync() {
const configPath = "/v1/";
const recordsPath = "/v1/buckets/default/collections/test_collection/records";
// register a handler
- function handleResponse (request, response) {
+ function handleResponse(request, response) {
try {
const sampled = getSampleResponse(request, server.identity.primaryPort);
if (!sampled) {
do_throw(`unexpected ${request.method} request for ${request.path}?${request.queryString}`);
}
response.setStatusLine(null, sampled.status.status,
sampled.status.statusText);
--- a/services/common/tests/unit/test_load_modules.js
+++ b/services/common/tests/unit/test_load_modules.js
@@ -20,32 +20,32 @@ const TEST_BASE = "resource://testing-co
const shared_test_modules = [
"logging.js",
];
const non_android_test_modules = [
"storageserver.js",
];
-function expectImportsToSucceed(mm, base=MODULE_BASE) {
+function expectImportsToSucceed(mm, base = MODULE_BASE) {
for (let m of mm) {
let resource = base + m;
let succeeded = false;
try {
Components.utils.import(resource, {});
succeeded = true;
} catch (e) {}
if (!succeeded) {
throw "Importing " + resource + " should have succeeded!";
}
}
}
-function expectImportsToFail(mm, base=MODULE_BASE) {
+function expectImportsToFail(mm, base = MODULE_BASE) {
for (let m of mm) {
let resource = base + m;
let succeeded = false;
try {
Components.utils.import(resource, {});
succeeded = true;
} catch (e) {}
--- a/services/common/tests/unit/test_observers.js
+++ b/services/common/tests/unit/test_observers.js
@@ -31,17 +31,17 @@ add_test(function test_function_observer
do_check_true(foo);
run_next_test();
});
add_test(function test_method_observer() {
let obj = {
foo: false,
- onFoo: function(subject, data) {
+ onFoo(subject, data) {
this.foo = !this.foo;
do_check_eq(subject, gSubject);
do_check_eq(data, "some data");
}
};
// The observer is notified after being added.
Observers.add("foo", obj.onFoo, obj);
@@ -54,17 +54,17 @@ add_test(function test_method_observer()
do_check_true(obj.foo);
run_next_test();
});
add_test(function test_object_observer() {
let obj = {
foo: false,
- observe: function(subject, topic, data) {
+ observe(subject, topic, data) {
this.foo = !this.foo;
do_check_eq(subject, gSubject);
do_check_eq(topic, "foo");
do_check_eq(data, "some data");
}
};
--- a/services/common/tests/unit/test_restrequest.js
+++ b/services/common/tests/unit/test_restrequest.js
@@ -71,17 +71,17 @@ add_test(function test_proxy_auth_redire
let server = httpd_setup({
"/original": original,
"/pac3": pacHandler
});
PACSystemSettings.PACURI = server.baseURI + "/pac3";
installFakePAC();
let res = new RESTRequest(server.baseURI + "/original");
- res.get(function (error) {
+ res.get(function(error) {
do_check_true(pacFetched);
do_check_true(fetched);
do_check_true(!error);
do_check_true(this.response.success);
do_check_eq("TADA!", this.response.body);
uninstallFakePAC();
server.stop(run_next_test);
});
@@ -105,17 +105,17 @@ add_test(function test_forbidden_port()
/**
* Demonstrate API short-hand: create a request and dispatch it immediately.
*/
add_test(function test_simple_get() {
let handler = httpd_handler(200, "OK", "Huzzah!");
let server = httpd_setup({"/resource": handler});
- let request = new RESTRequest(server.baseURI + "/resource").get(function (error) {
+ let request = new RESTRequest(server.baseURI + "/resource").get(function(error) {
do_check_eq(error, null);
do_check_eq(this.status, this.COMPLETED);
do_check_true(this.response.success);
do_check_eq(this.response.status, 200);
do_check_eq(this.response.body, "Huzzah!");
server.stop(run_next_test);
@@ -129,51 +129,51 @@ add_test(function test_simple_get() {
*/
add_test(function test_get() {
let handler = httpd_handler(200, "OK", "Huzzah!");
let server = httpd_setup({"/resource": handler});
let request = new RESTRequest(server.baseURI + "/resource");
do_check_eq(request.status, request.NOT_SENT);
- request.onProgress = request.onComplete = function () {
+ request.onProgress = request.onComplete = function() {
do_throw("This function should have been overwritten!");
};
let onProgress_called = false;
function onProgress() {
onProgress_called = true;
do_check_eq(this.status, request.IN_PROGRESS);
do_check_true(this.response.body.length > 0);
do_check_true(!!(this.channel.loadFlags & Ci.nsIRequest.LOAD_BYPASS_CACHE));
do_check_true(!!(this.channel.loadFlags & Ci.nsIRequest.INHIBIT_CACHING));
- };
+ }
function onComplete(error) {
do_check_eq(error, null);
do_check_eq(this.status, this.COMPLETED);
do_check_true(this.response.success);
do_check_eq(this.response.status, 200);
do_check_eq(this.response.body, "Huzzah!");
do_check_eq(handler.request.method, "GET");
do_check_true(onProgress_called);
- CommonUtils.nextTick(function () {
+ CommonUtils.nextTick(function() {
do_check_eq(request.onComplete, null);
do_check_eq(request.onProgress, null);
server.stop(run_next_test);
});
- };
+ }
do_check_eq(request.get(onComplete, onProgress), request);
do_check_eq(request.status, request.SENT);
do_check_eq(request.method, "GET");
- do_check_throws(function () {
+ do_check_throws(function() {
request.get();
});
});
/**
* Test HTTP GET with UTF-8 content, and custom Content-Type.
*/
add_test(function test_get_utf8() {
@@ -310,51 +310,51 @@ add_test(function test_charsets() {
function check_posting_data(method) {
let funcName = method.toLowerCase();
let handler = httpd_handler(200, "OK", "Got it!");
let server = httpd_setup({"/resource": handler});
let request = new RESTRequest(server.baseURI + "/resource");
do_check_eq(request.status, request.NOT_SENT);
- request.onProgress = request.onComplete = function () {
+ request.onProgress = request.onComplete = function() {
do_throw("This function should have been overwritten!");
};
let onProgress_called = false;
function onProgress() {
onProgress_called = true;
do_check_eq(this.status, request.IN_PROGRESS);
do_check_true(this.response.body.length > 0);
- };
+ }
function onComplete(error) {
do_check_eq(error, null);
do_check_eq(this.status, this.COMPLETED);
do_check_true(this.response.success);
do_check_eq(this.response.status, 200);
do_check_eq(this.response.body, "Got it!");
do_check_eq(handler.request.method, method);
do_check_eq(handler.request.body, "Hullo?");
do_check_eq(handler.request.getHeader("Content-Type"), "text/plain");
do_check_true(onProgress_called);
- CommonUtils.nextTick(function () {
+ CommonUtils.nextTick(function() {
do_check_eq(request.onComplete, null);
do_check_eq(request.onProgress, null);
server.stop(run_next_test);
});
- };
+ }
do_check_eq(request[funcName]("Hullo?", onComplete, onProgress), request);
do_check_eq(request.status, request.SENT);
do_check_eq(request.method, method);
- do_check_throws(function () {
+ do_check_throws(function() {
request[funcName]("Hai!");
});
}
/**
* Test HTTP PATCH with a simple string argument and default Content-Type.
*/
add_test(function test_patch() {
@@ -380,61 +380,61 @@ add_test(function test_post() {
*/
add_test(function test_delete() {
let handler = httpd_handler(200, "OK", "Got it!");
let server = httpd_setup({"/resource": handler});
let request = new RESTRequest(server.baseURI + "/resource");
do_check_eq(request.status, request.NOT_SENT);
- request.onProgress = request.onComplete = function () {
+ request.onProgress = request.onComplete = function() {
do_throw("This function should have been overwritten!");
};
let onProgress_called = false;
function onProgress() {
onProgress_called = true;
do_check_eq(this.status, request.IN_PROGRESS);
do_check_true(this.response.body.length > 0);
- };
+ }
function onComplete(error) {
do_check_eq(error, null);
do_check_eq(this.status, this.COMPLETED);
do_check_true(this.response.success);
do_check_eq(this.response.status, 200);
do_check_eq(this.response.body, "Got it!");
do_check_eq(handler.request.method, "DELETE");
do_check_true(onProgress_called);
- CommonUtils.nextTick(function () {
+ CommonUtils.nextTick(function() {
do_check_eq(request.onComplete, null);
do_check_eq(request.onProgress, null);
server.stop(run_next_test);
});
- };
+ }
do_check_eq(request.delete(onComplete, onProgress), request);
do_check_eq(request.status, request.SENT);
do_check_eq(request.method, "DELETE");
- do_check_throws(function () {
+ do_check_throws(function() {
request.delete();
});
});
/**
* Test an HTTP response with a non-200 status code.
*/
add_test(function test_get_404() {
let handler = httpd_handler(404, "Not Found", "Cannae find it!");
let server = httpd_setup({"/resource": handler});
let request = new RESTRequest(server.baseURI + "/resource");
- request.get(function (error) {
+ request.get(function(error) {
do_check_eq(error, null);
do_check_eq(this.status, this.COMPLETED);
do_check_false(this.response.success);
do_check_eq(this.response.status, 404);
do_check_eq(this.response.body, "Cannae find it!");
server.stop(run_next_test);
@@ -450,17 +450,17 @@ add_test(function test_put_json() {
let server = httpd_setup({"/resource": handler});
let sample_data = {
some: "sample_data",
injson: "format",
number: 42
};
let request = new RESTRequest(server.baseURI + "/resource");
- request.put(sample_data, function (error) {
+ request.put(sample_data, function(error) {
do_check_eq(error, null);
do_check_eq(this.status, this.COMPLETED);
do_check_true(this.response.success);
do_check_eq(this.response.status, 200);
do_check_eq(this.response.body, "");
do_check_eq(handler.request.method, "PUT");
@@ -480,17 +480,17 @@ add_test(function test_post_json() {
let server = httpd_setup({"/resource": handler});
let sample_data = {
some: "sample_data",
injson: "format",
number: 42
};
let request = new RESTRequest(server.baseURI + "/resource");
- request.post(sample_data, function (error) {
+ request.post(sample_data, function(error) {
do_check_eq(error, null);
do_check_eq(this.status, this.COMPLETED);
do_check_true(this.response.success);
do_check_eq(this.response.status, 200);
do_check_eq(this.response.body, "");
do_check_eq(handler.request.method, "POST");
@@ -506,17 +506,17 @@ add_test(function test_post_json() {
* to POST is already a string.
*/
add_test(function test_post_json() {
let handler = httpd_handler(200, "OK");
let server = httpd_setup({"/resource": handler});
let sample_data = "hello";
let request = new RESTRequest(server.baseURI + "/resource");
- request.post(sample_data, function (error) {
+ request.post(sample_data, function(error) {
do_check_eq(error, null);
do_check_eq(this.status, this.COMPLETED);
do_check_true(this.response.success);
do_check_eq(this.response.status, 200);
do_check_eq(this.response.body, "");
do_check_eq(handler.request.method, "POST");
@@ -531,17 +531,17 @@ add_test(function test_post_json() {
* HTTP PUT with a custom Content-Type header.
*/
add_test(function test_put_override_content_type() {
let handler = httpd_handler(200, "OK");
let server = httpd_setup({"/resource": handler});
let request = new RESTRequest(server.baseURI + "/resource");
request.setHeader("Content-Type", "application/lolcat");
- request.put("O HAI!!1!", function (error) {
+ request.put("O HAI!!1!", function(error) {
do_check_eq(error, null);
do_check_eq(this.status, this.COMPLETED);
do_check_true(this.response.success);
do_check_eq(this.response.status, 200);
do_check_eq(this.response.body, "");
do_check_eq(handler.request.method, "PUT");
@@ -556,17 +556,17 @@ add_test(function test_put_override_cont
* HTTP POST with a custom Content-Type header.
*/
add_test(function test_post_override_content_type() {
let handler = httpd_handler(200, "OK");
let server = httpd_setup({"/resource": handler});
let request = new RESTRequest(server.baseURI + "/resource");
request.setHeader("Content-Type", "application/lolcat");
- request.post("O HAI!!1!", function (error) {
+ request.post("O HAI!!1!", function(error) {
do_check_eq(error, null);
do_check_eq(this.status, this.COMPLETED);
do_check_true(this.response.success);
do_check_eq(this.response.status, 200);
do_check_eq(this.response.body, "");
do_check_eq(handler.request.method, "POST");
@@ -584,17 +584,17 @@ add_test(function test_get_no_headers()
let handler = httpd_handler(200, "OK");
let server = httpd_setup({"/resource": handler});
let ignore_headers = ["host", "user-agent", "accept", "accept-language",
"accept-encoding", "accept-charset", "keep-alive",
"connection", "pragma", "cache-control",
"content-length"];
- new RESTRequest(server.baseURI + "/resource").get(function (error) {
+ new RESTRequest(server.baseURI + "/resource").get(function(error) {
do_check_eq(error, null);
do_check_eq(this.response.status, 200);
do_check_eq(this.response.body, "");
let server_headers = handler.request.headers;
while (server_headers.hasMoreElements()) {
let header = server_headers.getNext().toString();
@@ -611,17 +611,17 @@ add_test(function test_get_no_headers()
* Test changing the URI after having created the request.
*/
add_test(function test_changing_uri() {
let handler = httpd_handler(200, "OK");
let server = httpd_setup({"/resource": handler});
let request = new RESTRequest("http://localhost:1234/the-wrong-resource");
request.uri = CommonUtils.makeURI(server.baseURI + "/resource");
- request.get(function (error) {
+ request.get(function(error) {
do_check_eq(error, null);
do_check_eq(this.response.status, 200);
server.stop(run_next_test);
});
});
/**
* Test setting HTTP request headers.
@@ -631,17 +631,17 @@ add_test(function test_request_setHeader
let server = httpd_setup({"/resource": handler});
let request = new RESTRequest(server.baseURI + "/resource");
request.setHeader("X-What-Is-Weave", "awesome");
request.setHeader("X-WHAT-is-Weave", "more awesomer");
request.setHeader("Another-Header", "Hello World");
- request.get(function (error) {
+ request.get(function(error) {
do_check_eq(error, null);
do_check_eq(this.response.status, 200);
do_check_eq(this.response.body, "");
do_check_eq(handler.request.getHeader("X-What-Is-Weave"), "more awesomer");
do_check_eq(handler.request.getHeader("another-header"), "Hello World");
@@ -656,17 +656,17 @@ add_test(function test_response_headers(
function handler(request, response) {
response.setHeader("X-What-Is-Weave", "awesome");
response.setHeader("Another-Header", "Hello World");
response.setStatusLine(request.httpVersion, 200, "OK");
}
let server = httpd_setup({"/resource": handler});
let request = new RESTRequest(server.baseURI + "/resource");
- request.get(function (error) {
+ request.get(function(error) {
do_check_eq(error, null);
do_check_eq(this.response.status, 200);
do_check_eq(this.response.body, "");
do_check_eq(this.response.headers["x-what-is-weave"], "awesome");
do_check_eq(this.response.headers["another-header"], "Hello World");
@@ -678,17 +678,17 @@ add_test(function test_response_headers(
* The onComplete() handler gets called in case of any network errors
* (e.g. NS_ERROR_CONNECTION_REFUSED).
*/
add_test(function test_connection_refused() {
let request = new RESTRequest("http://localhost:1234/resource");
request.onProgress = function onProgress() {
do_throw("Shouldn't have called request.onProgress()!");
};
- request.get(function (error) {
+ request.get(function(error) {
do_check_eq(error.result, Cr.NS_ERROR_CONNECTION_REFUSED);
do_check_eq(error.message, "NS_ERROR_CONNECTION_REFUSED");
do_check_eq(this.status, this.COMPLETED);
run_next_test();
});
do_check_eq(request.status, request.SENT);
});
@@ -699,33 +699,33 @@ add_test(function test_abort() {
function handler() {
do_throw("Shouldn't have gotten here!");
}
let server = httpd_setup({"/resource": handler});
let request = new RESTRequest(server.baseURI + "/resource");
// Aborting a request that hasn't been sent yet is pointless and will throw.
- do_check_throws(function () {
+ do_check_throws(function() {
request.abort();
});
- request.onProgress = request.onComplete = function () {
+ request.onProgress = request.onComplete = function() {
do_throw("Shouldn't have gotten here!");
};
request.get();
request.abort();
// Aborting an already aborted request is pointless and will throw.
- do_check_throws(function () {
+ do_check_throws(function() {
request.abort();
});
do_check_eq(request.status, request.ABORTED);
- CommonUtils.nextTick(function () {
+ CommonUtils.nextTick(function() {
server.stop(run_next_test);
});
});
/**
* A non-zero 'timeout' property specifies the amount of seconds to wait after
* channel activity until the request is automatically canceled.
*/
@@ -741,17 +741,17 @@ add_test(function test_timeout() {
};
server.start();
let identity = server.identity;
let uri = identity.primaryScheme + "://" + identity.primaryHost + ":" +
identity.primaryPort;
let request = new RESTRequest(uri + "/resource");
request.timeout = 0.1; // 100 milliseconds
- request.get(function (error) {
+ request.get(function(error) {
do_check_eq(error.result, Cr.NS_ERROR_NET_TIMEOUT);
do_check_eq(this.status, this.ABORTED);
// server_connection is undefined on the Android emulator for reasons
// unknown. Yet, we still get here. If this test is refactored, we should
// investigate the reason why the above callback is behaving differently.
if (server_connection) {
_("Closing connection.");
@@ -813,17 +813,17 @@ add_test(function test_new_channel() {
response.bodyOutputStream.write(body, body.length);
}
let server1 = httpd_setup({"/redirect": redirectHandler});
let server2 = httpd_setup({"/resource": resourceHandler});
redirectURL = server2.baseURI + "/resource";
function advance() {
- server1.stop(function () {
+ server1.stop(function() {
server2.stop(run_next_test);
});
}
let request = new RESTRequest(server1.baseURI + "/redirect");
request.setHeader("User-Agent", "foo bar");
// Swizzle in our own fakery, because this redirect is neither
@@ -858,16 +858,16 @@ add_test(function test_not_sending_cooki
let server = httpd_setup({"/test": handler});
let cookieSer = Cc["@mozilla.org/cookieService;1"]
.getService(Ci.nsICookieService);
let uri = CommonUtils.makeURI(server.baseURI);
cookieSer.setCookieString(uri, null, "test=test; path=/;", null);
let res = new RESTRequest(server.baseURI + "/test");
- res.get(function (error) {
+ res.get(function(error) {
do_check_null(error);
do_check_true(this.response.success);
do_check_eq("COOKIE!", this.response.body);
server.stop(run_next_test);
});
});
--- a/services/common/tests/unit/test_storage_adapter.js
+++ b/services/common/tests/unit/test_storage_adapter.js
@@ -18,17 +18,17 @@ function do_get_kinto_adapter(sqliteHand
function do_get_kinto_db() {
let profile = do_get_profile();
let kintoDB = profile.clone();
kintoDB.append(kintoFilename);
return kintoDB;
}
function cleanup_kinto() {
- add_test(function cleanup_kinto_files(){
+ add_test(function cleanup_kinto_files() {
let kintoDB = do_get_kinto_db();
// clean up the db
kintoDB.remove(false);
run_next_test();
});
}
function test_collection_operations() {
@@ -246,17 +246,17 @@ add_test(function test_db_creation() {
// existing database
add_test(function test_creation_from_empty_db() {
add_test(function test_create_from_empty_db() {
// place an empty kinto db file in the profile
let profile = do_get_profile();
let kintoDB = do_get_kinto_db();
let emptyDB = do_get_file("test_storage_adapter/empty.sqlite");
- emptyDB.copyTo(profile,kintoFilename);
+ emptyDB.copyTo(profile, kintoFilename);
run_next_test();
});
test_collection_operations();
cleanup_kinto();
run_next_test();
--- a/services/common/tests/unit/test_storage_server.js
+++ b/services/common/tests/unit/test_storage_server.js
@@ -7,17 +7,17 @@ Cu.import("resource://services-common/ut
Cu.import("resource://testing-common/services/common/storageserver.js");
const DEFAULT_USER = "123";
const DEFAULT_PASSWORD = "password";
/**
* Helper function to prepare a RESTRequest against the server.
*/
-function localRequest(server, path, user=DEFAULT_USER, password=DEFAULT_PASSWORD) {
+function localRequest(server, path, user = DEFAULT_USER, password = DEFAULT_PASSWORD) {
_("localRequest: " + path);
let identity = server.server.identity;
let url = identity.primaryScheme + "://" + identity.primaryHost + ":" +
identity.primaryPort + path;
_("url: " + url);
let req = new RESTRequest(url);
let header = basic_auth_header(user, password);
@@ -116,17 +116,17 @@ add_test(function test_creation() {
_("Ensure a simple server can be created.");
// Explicit callback for this one.
let server = new StorageServer({
__proto__: StorageServerCallback,
});
do_check_true(!!server);
- server.start(-1, function () {
+ server.start(-1, function() {
_("Started on " + server.port);
server.stop(run_next_test);
});
});
add_test(function test_synchronous_start() {
_("Ensure starting using startSynchronous works.");
@@ -186,17 +186,17 @@ add_test(function test_basic_http() {
server.registerUser("345", "password");
do_check_true(server.userExists("345"));
server.startSynchronous();
_("Started on " + server.port);
do_check_eq(server.requestCount, 0);
let req = localRequest(server, "/2.0/storage/crypto/keys");
_("req is " + req);
- req.get(function (err) {
+ req.get(function(err) {
do_check_eq(null, err);
do_check_eq(server.requestCount, 1);
server.stop(run_next_test);
});
});
add_test(function test_info_collections() {
let server = new StorageServer();
@@ -588,21 +588,21 @@ add_test(function test_x_num_records() {
server.registerUser("123", "password");
server.createContents("123", {
crypto: {foos: {foo: "bar"},
bars: {foo: "baz"}}
});
server.startSynchronous();
let bso = localRequest(server, "/2.0/123/storage/crypto/foos");
- bso.get(function (err) {
+ bso.get(function(err) {
// BSO fetches don't have one.
do_check_false("x-num-records" in this.response.headers);
let col = localRequest(server, "/2.0/123/storage/crypto");
- col.get(function (err) {
+ col.get(function(err) {
// Collection fetches do.
do_check_eq(this.response.headers["x-num-records"], "2");
server.stop(run_next_test);
});
});
});
add_test(function test_put_delete_put() {
--- a/services/common/tests/unit/test_tokenauthenticatedrequest.js
+++ b/services/common/tests/unit/test_tokenauthenticatedrequest.js
@@ -19,33 +19,33 @@ add_test(function test_authenticated_req
// TODO: We use a preset key here, but use getTokenFromBrowserIDAssertion()
// from TokenServerClient to get a real one when possible. (Bug 745800)
let id = "eyJleHBpcmVzIjogMTM2NTAxMDg5OC4x";
let key = "qTZf4ZFpAMpMoeSsX3zVRjiqmNs=";
let method = "GET";
let nonce = btoa(CryptoUtils.generateRandomBytes(16));
let ts = Math.floor(Date.now() / 1000);
- let extra = {ts: ts, nonce: nonce};
+ let extra = {ts, nonce};
let auth;
let server = httpd_setup({"/foo": function(request, response) {
do_check_true(request.hasHeader("Authorization"));
do_check_eq(auth, request.getHeader("Authorization"));
response.setStatusLine(request.httpVersion, 200, "OK");
response.bodyOutputStream.write(message, message.length);
}
});
let uri = CommonUtils.makeURI(server.baseURI + "/foo");
let sig = CryptoUtils.computeHTTPMACSHA1(id, key, method, uri, extra);
auth = sig.getHeader();
- let req = new TokenAuthenticatedRESTRequest(uri, {id: id, key: key}, extra);
+ let req = new TokenAuthenticatedRESTRequest(uri, {id, key}, extra);
let cb = Async.makeSpinningCallback();
req.get(cb);
let result = cb.wait();
do_check_eq(null, result);
do_check_eq(message, req.response.body);
server.stop(run_next_test);
--- a/services/common/tests/unit/test_tokenserverclient.js
+++ b/services/common/tests/unit/test_tokenserverclient.js
@@ -25,17 +25,17 @@ add_test(function test_working_bid_excha
response.setStatusLine(request.httpVersion, 200, "OK");
response.setHeader("Content-Type", "application/json");
let body = JSON.stringify({
id: "id",
key: "key",
api_endpoint: service,
uid: "uid",
- duration: duration,
+ duration,
});
response.bodyOutputStream.write(body, body.length);
}
});
let client = new TokenServerClient();
let cb = Async.makeSpinningCallback();
let url = server.baseURI + "/1.0/foo/1.0";
@@ -82,17 +82,17 @@ add_test(function test_conditions_requir
let server = httpd_setup({
"/1.0/foo/1.0": function(request, response) {
do_check_false(request.hasHeader("x-conditions-accepted"));
response.setStatusLine(request.httpVersion, 403, "Forbidden");
response.setHeader("Content-Type", "application/json");
let body = JSON.stringify({
- errors: [{description: description, location: "body", name: ""}],
+ errors: [{description, location: "body", name: ""}],
urls: {tos: tosURL}
});
response.bodyOutputStream.write(body, body.length);
}
});
let client = new TokenServerClient();
let url = server.baseURI + "/1.0/foo/1.0";
@@ -216,17 +216,17 @@ add_test(function test_send_extra_header
response.setStatusLine(request.httpVersion, 200, "OK");
response.setHeader("Content-Type", "application/json");
let body = JSON.stringify({
id: "id",
key: "key",
api_endpoint: "http://example.com/",
uid: "uid",
- duration: duration,
+ duration,
});
response.bodyOutputStream.write(body, body.length);
}
});
let client = new TokenServerClient();
let url = server.baseURI + "/1.0/foo/1.0";
@@ -403,17 +403,17 @@ add_test(function test_rich_media_types(
response.setStatusLine(request.httpVersion, 200, "OK");
response.setHeader("Content-Type", "application/json; foo=bar; bar=foo");
let body = JSON.stringify({
id: "id",
key: "key",
api_endpoint: "foo",
uid: "uid",
- duration: duration,
+ duration,
});
response.bodyOutputStream.write(body, body.length);
}
});
let url = server.baseURI + "/foo";
let client = new TokenServerClient();
client.getTokenFromBrowserIDAssertion(url, "assertion", function(error, r) {
@@ -432,17 +432,17 @@ add_test(function test_exception_during_
response.setStatusLine(request.httpVersion, 200, "OK");
response.setHeader("Content-Type", "application/json");
let body = JSON.stringify({
id: "id",
key: "key",
api_endpoint: "foo",
uid: "uid",
- duration: duration,
+ duration,
});
response.bodyOutputStream.write(body, body.length);
}
});
let url = server.baseURI + "/foo";
let client = new TokenServerClient();
let cb = Async.makeSpinningCallback();
--- a/services/common/tests/unit/test_utils_convert_string.js
+++ b/services/common/tests/unit/test_utils_convert_string.js
@@ -3,31 +3,31 @@
"use strict";
Cu.import("resource://services-common/utils.js");
// A wise line of Greek verse, and the utf-8 byte encoding.
// N.b., Greek begins at utf-8 ce 91
const TEST_STR = "πόλλ' οἶδ' ἀλώπηξ, ἀλλ' ἐχῖνος ἓν μέγα";
-const TEST_HEX = h("cf 80 cf 8c ce bb ce bb 27 20 ce bf e1 bc b6 ce"+
- "b4 27 20 e1 bc 80 ce bb cf 8e cf 80 ce b7 ce be"+
- "2c 20 e1 bc 80 ce bb ce bb 27 20 e1 bc 90 cf 87"+
- "e1 bf 96 ce bd ce bf cf 82 20 e1 bc 93 ce bd 20"+
+const TEST_HEX = h("cf 80 cf 8c ce bb ce bb 27 20 ce bf e1 bc b6 ce" +
+ "b4 27 20 e1 bc 80 ce bb cf 8e cf 80 ce b7 ce be" +
+ "2c 20 e1 bc 80 ce bb ce bb 27 20 e1 bc 90 cf 87" +
+ "e1 bf 96 ce bd ce bf cf 82 20 e1 bc 93 ce bd 20" +
"ce bc ce ad ce b3 ce b1");
// Integer byte values for the above
-const TEST_BYTES = [207,128,207,140,206,187,206,187,
- 39, 32,206,191,225,188,182,206,
- 180, 39, 32,225,188,128,206,187,
- 207,142,207,128,206,183,206,190,
- 44, 32,225,188,128,206,187,206,
- 187, 39, 32,225,188,144,207,135,
- 225,191,150,206,189,206,191,207,
- 130, 32,225,188,147,206,189, 32,
- 206,188,206,173,206,179,206,177];
+const TEST_BYTES = [207, 128, 207, 140, 206, 187, 206, 187,
+ 39, 32, 206, 191, 225, 188, 182, 206,
+ 180, 39, 32, 225, 188, 128, 206, 187,
+ 207, 142, 207, 128, 206, 183, 206, 190,
+ 44, 32, 225, 188, 128, 206, 187, 206,
+ 187, 39, 32, 225, 188, 144, 207, 135,
+ 225, 191, 150, 206, 189, 206, 191, 207,
+ 130, 32, 225, 188, 147, 206, 189, 32,
+ 206, 188, 206, 173, 206, 179, 206, 177];
function run_test() {
run_next_test();
}
add_test(function test_compress_string() {
const INPUT = "hello";
--- a/services/common/tests/unit/test_utils_encodeBase64URL.js
+++ b/services/common/tests/unit/test_utils_encodeBase64URL.js
@@ -8,17 +8,17 @@ function run_test() {
}
add_test(function test_simple() {
let expected = {
hello: "aGVsbG8=",
"<>?": "PD4_",
};
- for (let [k,v] of Object.entries(expected)) {
+ for (let [k, v] of Object.entries(expected)) {
do_check_eq(CommonUtils.encodeBase64URL(k), v);
}
run_next_test();
});
add_test(function test_no_padding() {
do_check_eq(CommonUtils.encodeBase64URL("hello", false), "aGVsbG8");
--- a/services/common/tests/unit/test_utils_json.js
+++ b/services/common/tests/unit/test_utils_json.js
@@ -22,17 +22,17 @@ add_test(function test_writeJSON_readJSO
};
function checkJSON(json) {
do_check_eq(contents.a, json.a);
do_check_eq(contents.b.c, json.b.c);
do_check_eq(contents.d, json.d);
do_check_eq(contents.e, json.e);
run_next_test();
- };
+ }
function doRead() {
CommonUtils.readJSON(path)
.then(checkJSON, do_throw);
}
let path = OS.Path.join(OS.Constants.Path.profileDir, "bar.json");
CommonUtils.writeJSON(contents, path)
--- a/services/common/tests/unit/test_utils_namedTimer.js
+++ b/services/common/tests/unit/test_utils_namedTimer.js
@@ -8,17 +8,17 @@ function run_test() {
}
add_test(function test_required_args() {
try {
CommonUtils.namedTimer(function callback() {
do_throw("Shouldn't fire.");
}, 0);
do_throw("Should have thrown!");
- } catch(ex) {
+ } catch (ex) {
run_next_test();
}
});
add_test(function test_simple() {
_("Test basic properties of CommonUtils.namedTimer.");
const delay = 200;
--- a/services/common/tokenserverclient.js
+++ b/services/common/tokenserverclient.js
@@ -94,17 +94,17 @@ TokenServerClientNetworkError.prototype.
*
* general -- A general server error has occurred. Clients should
* interpret this as an opaque failure.
*
* @param message
* (string) Error message.
*/
this.TokenServerClientServerError =
- function TokenServerClientServerError(message, cause="general") {
+ function TokenServerClientServerError(message, cause = "general") {
this.now = new Date().toISOString(); // may be useful to diagnose time-skew issues.
this.name = "TokenServerClientServerError";
this.message = message || "Server error.";
this.cause = cause;
this.stack = Error().stack;
}
TokenServerClientServerError.prototype = new TokenServerClientError();
TokenServerClientServerError.prototype.constructor =
@@ -239,17 +239,17 @@ TokenServerClient.prototype = {
* @param assertion
* (string) BrowserID assertion to exchange token for.
* @param cb
* (function) Callback to be invoked with result of operation.
* @param conditionsAccepted
* (bool) Whether to send acceptance to service conditions.
*/
getTokenFromBrowserIDAssertion:
- function getTokenFromBrowserIDAssertion(url, assertion, cb, addHeaders={}) {
+ function getTokenFromBrowserIDAssertion(url, assertion, cb, addHeaders = {}) {
if (!url) {
throw new TokenServerClientError("url argument is not valid.");
}
if (!assertion) {
throw new TokenServerClientError("assertion argument is not valid.");
}
@@ -431,17 +431,17 @@ TokenServerClient.prototype = {
* allows the handler of notifications to be sure they are handling
* notifications for the service they expect.
*
* If not set, no notifications will be sent.
*/
observerPrefix: null,
// Given an optional header value, notify that a backoff has been requested.
- _maybeNotifyBackoff: function (response, headerName) {
+ _maybeNotifyBackoff(response, headerName) {
if (!this.observerPrefix) {
return;
}
let headerVal = response.headers[headerName];
if (!headerVal) {
return;
}
let backoffInterval;
@@ -451,12 +451,12 @@ TokenServerClient.prototype = {
this._log.error("TokenServer response had invalid backoff value in '" +
headerName + "' header: " + headerVal);
return;
}
Observers.notify(this.observerPrefix + ":backoff:interval", backoffInterval);
},
// override points for testing.
- newRESTRequest: function(url) {
+ newRESTRequest(url) {
return new RESTRequest(url);
}
};
--- a/services/common/utils.js
+++ b/services/common/utils.js
@@ -16,53 +16,53 @@ this.CommonUtils = {
/*
* Set manipulation methods. These should be lifted into toolkit, or added to
* `Set` itself.
*/
/**
* Return elements of `a` or `b`.
*/
- union: function (a, b) {
+ union(a, b) {
let out = new Set(a);
for (let x of b) {
out.add(x);
}
return out;
},
/**
* Return elements of `a` that are not present in `b`.
*/
- difference: function (a, b) {
+ difference(a, b) {
let out = new Set(a);
for (let x of b) {
out.delete(x);
}
return out;
},
/**
* Return elements of `a` that are also in `b`.
*/
- intersection: function (a, b) {
+ intersection(a, b) {
let out = new Set();
for (let x of a) {
if (b.has(x)) {
out.add(x);
}
}
return out;
},
/**
* Return true if `a` and `b` are the same size, and
* every element of `a` is in `b`.
*/
- setEqual: function (a, b) {
+ setEqual(a, b) {
if (a.size != b.size) {
return false;
}
for (let x of a) {
if (!b.has(x)) {
return false;
}
}
@@ -73,17 +73,17 @@ this.CommonUtils = {
* Encode byte string as base64URL (RFC 4648).
*
* @param bytes
* (string) Raw byte string to encode.
* @param pad
* (bool) Whether to include padding characters (=). Defaults
* to true for historical reasons.
*/
- encodeBase64URL: function encodeBase64URL(bytes, pad=true) {
+ encodeBase64URL: function encodeBase64URL(bytes, pad = true) {
let s = btoa(bytes).replace(/\+/g, "-").replace(/\//g, "_");
if (!pad) {
return s.replace(/=+$/, "");
}
return s;
},
@@ -120,34 +120,34 @@ this.CommonUtils = {
/**
* Return a promise resolving on some later tick.
*
* This a wrapper around Promise.resolve() that prevents stack
* accumulation and prevents callers from accidentally relying on
* same-tick promise resolution.
*/
- laterTickResolvingPromise: function (value, prototype) {
+ laterTickResolvingPromise(value, prototype) {
let deferred = Promise.defer(prototype);
this.nextTick(deferred.resolve.bind(deferred, value));
return deferred.promise;
},
/**
* Spin the event loop and return once the next tick is executed.
*
* This is an evil function and should not be used in production code. It
* exists in this module for ease-of-use.
*/
waitForNextTick: function waitForNextTick() {
let cb = Async.makeSyncCallback();
this.nextTick(cb);
Async.waitForSyncCallback(cb);
- return;
+
},
/**
* Return a timer that is scheduled to call the callback after waiting the
* provided time or as soon as possible. The timer will be set as a property
* of the provided object with the given timer name.
*/
namedTimer: function namedTimer(callback, wait, thisObj, name) {
@@ -375,30 +375,30 @@ this.CommonUtils = {
},
/**
* Parses a JSON file from disk using OS.File and promises.
*
* @param path the file to read. Will be passed to `OS.File.read()`.
* @return a promise that resolves to the JSON contents of the named file.
*/
- readJSON: function(path) {
+ readJSON(path) {
return OS.File.read(path, { encoding: "utf-8" }).then((data) => {
return JSON.parse(data);
});
},
/**
* Write a JSON object to the named file using OS.File and promises.
*
* @param contents a JS object. Will be serialized.
* @param path the path of the file to write.
* @return a promise, as produced by OS.File.writeAtomic.
*/
- writeJSON: function(contents, path) {
+ writeJSON(contents, path) {
let data = JSON.stringify(contents);
return OS.File.writeAtomic(path, data, {encoding: "utf-8", tmpPath: path + ".tmp"});
},
/**
* Ensure that the specified value is defined in integer milliseconds since
* UNIX epoch.
@@ -487,17 +487,17 @@ this.CommonUtils = {
* (Preferences) Branch from which to retrieve preference.
* @param pref
* (string) The preference to read from.
* @param def
* (Number) The default value to use if the preference is not defined.
* @param log
* (Log.Logger) Logger to write warnings to.
*/
- getEpochPref: function getEpochPref(branch, pref, def=0, log=null) {
+ getEpochPref: function getEpochPref(branch, pref, def = 0, log = null) {
if (!Number.isInteger(def)) {
throw new Error("Default value is not a number: " + def);
}
let valueStr = branch.get(pref, null);
if (valueStr !== null) {
let valueInt = parseInt(valueStr, 10);
@@ -532,18 +532,18 @@ this.CommonUtils = {
* @param def
* (Number) The default value (in milliseconds) if the preference is
* not defined or invalid.
* @param log
* (Log.Logger) Logger to write warnings to.
* @param oldestYear
* (Number) Oldest year to accept in read values.
*/
- getDatePref: function getDatePref(branch, pref, def=0, log=null,
- oldestYear=2010) {
+ getDatePref: function getDatePref(branch, pref, def = 0, log = null,
+ oldestYear = 2010) {
let valueInt = this.getEpochPref(branch, pref, def, log);
let date = new Date(valueInt);
if (valueInt == def || date.getFullYear() >= oldestYear) {
return date;
}
@@ -567,17 +567,17 @@ this.CommonUtils = {
* (Preference) Branch from which to read preference.
* @param pref
* (string) Name of preference to write to.
* @param date
* (Date) The value to save.
* @param oldestYear
* (Number) The oldest year to accept for values.
*/
- setDatePref: function setDatePref(branch, pref, date, oldestYear=2010) {
+ setDatePref: function setDatePref(branch, pref, date, oldestYear = 2010) {
if (date.getFullYear() < oldestYear) {
throw new Error("Trying to set " + pref + " to a very old time: " +
date + ". The current time is " + new Date() +
". Is the system clock wrong?");
}
branch.set(pref, "" + date.getTime());
},
--- a/services/crypto/component/tests/unit/test_jpake.js
+++ b/services/crypto/component/tests/unit/test_jpake.js
@@ -3,17 +3,17 @@ var Ci = Components.interfaces;
// Ensure PSM is initialized.
Cc["@mozilla.org/psm;1"].getService(Ci.nsISupports);
function do_check_throws(func) {
let have_error = false;
try {
func();
- } catch(ex) {
+ } catch (ex) {
dump("Was expecting an exception. Caught: " + ex + "\n");
have_error = true;
}
do_check_true(have_error);
}
function test_success() {
let a = Cc["@mozilla.org/services-crypto/sync-jpake;1"]
@@ -194,17 +194,17 @@ function test_x4_zero() {
let b_gva = {};
let b_ra = {};
do_check_throws(function() {
b.round2("alice", "secret", a_gx1.value, a_gv1.value, a_r1.value,
a_gx2.value, a_gv2.value, a_r2.value, b_A, b_gva, b_ra);
});
};
-
+
// g^x is NIST 3072's p + 1, (p + 1) mod p == 1, x == 0
test("90066455B5CFC38F9CAA4A48B4281F292C260FEEF01FD61037E56258A7795A1C"
+ "7AD46076982CE6BB956936C6AB4DCFE05E6784586940CA544B9B2140E1EB523F"
+ "009D20A7E7880E4E5BFA690F1B9004A27811CD9904AF70420EEFD6EA11EF7DA1"
+ "29F58835FF56B89FAA637BC9AC2EFAAB903402229F491D8D3485261CD068699B"
+ "6BA58A1DDBBEF6DB51E8FE34E8A78E542D7BA351C21EA8D8F1D29F5D5D159394"
+ "87E27F4416B0CA632C59EFD1B1EB66511A5A0FBF615B766C5862D0BD8A3FE7A0"
+ "E0DA0FB2FE1FCB19E8F9996A8EA0FCCDE538175238FC8B0EE6F29AF7F642773E"
@@ -241,17 +241,17 @@ function test_x4_zero() {
+ "99EEF4816375B119824ACC9AA56D1340B6A49D05F855DE699B351012028C"
+ "CA43001F708CC61E71CA3849935BEEBABC0D268CD41B8D2B8DCA705FDFF8"
+ "1DAA772DA96EDEA0B291FD5C0C1B8EFE5318D37EBC1BFF53A9DDEC4171A6"
+ "479E341438970058E25C8F2BCDA6166C8BF1B065C174",
"8B2BACE575179D762F6F2FFDBFF00B497C07766AB3EED9961447CF6F43D06A97");
}
function test_invalid_input_round2() {
- let a = Cc["@mozilla.org/services-crypto/sync-jpake;1"]
+ let a = Cc["@mozilla.org/services-crypto/sync-jpake;1"]
.createInstance(Ci.nsISyncJPAKE);
a.round1("alice", {}, {}, {}, {}, {}, {});
do_check_throws(function() {
a.round2("invalid", "sekrit", "some", "real", "garbage",
"even", "more", "garbage", {}, {}, {});
});
}
--- a/services/crypto/modules/WeaveCrypto.js
+++ b/services/crypto/modules/WeaveCrypto.js
@@ -115,17 +115,17 @@ WeaveCrypto.prototype = {
}
let iv = this.byteCompressInts(ivStr);
let symKey = this.importSymKey(symKeyStr, operation);
let cryptMethod = (operation === OPERATIONS.ENCRYPT
? crypto.subtle.encrypt
: crypto.subtle.decrypt)
.bind(crypto.subtle);
- let algo = { name: CRYPT_ALGO, iv: iv };
+ let algo = { name: CRYPT_ALGO, iv };
return Async.promiseSpinningly(
cryptMethod(algo, symKey, data)
.then(keyBytes => new Uint8Array(keyBytes))
);
},
@@ -240,17 +240,17 @@ WeaveCrypto.prototype = {
*/
deriveKeyFromPassphrase(passphrase, saltStr, keyLength = 32) {
this.log("deriveKeyFromPassphrase() called.");
let keyData = this.makeUint8Array(passphrase, false);
let salt = this.makeUint8Array(saltStr, true);
let importAlgo = { name: KEY_DERIVATION_ALGO };
let deriveAlgo = {
name: KEY_DERIVATION_ALGO,
- salt: salt,
+ salt,
iterations: KEY_DERIVATION_ITERATIONS,
hash: { name: KEY_DERIVATION_HASHING_ALGO },
};
let derivedKeyType = {
name: DERIVED_KEY_ALGO,
length: keyLength * 8,
};
return Async.promiseSpinningly(
--- a/services/crypto/modules/utils.js
+++ b/services/crypto/modules/utils.js
@@ -10,17 +10,17 @@ Cu.import("resource://services-common/ob
Cu.import("resource://services-common/utils.js");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
this.CryptoUtils = {
xor: function xor(a, b) {
let bytes = [];
if (a.length != b.length) {
- throw new Error("can't xor unequal length strings: "+a.length+" vs "+b.length);
+ throw new Error("can't xor unequal length strings: " + a.length + " vs " + b.length);
}
for (let i = 0; i < a.length; i++) {
bytes[i] = a.charCodeAt(i) ^ b.charCodeAt(i);
}
return String.fromCharCode.apply(String, bytes);
},
@@ -66,17 +66,17 @@ this.CryptoUtils = {
},
/**
* Encode the message into UTF-8 and feed the resulting bytes into the
* given hasher. Does not return a hash. This can be called multiple times
* with a single hasher, but eventually you must extract the result
* yourself.
*/
- updateUTF8: function(message, hasher) {
+ updateUTF8(message, hasher) {
let bytes = this._utf8Converter.convertToByteArray(message, {});
hasher.update(bytes, bytes.length);
},
/**
* UTF-8 encode a message and perform a SHA-1 over it.
*
* @param message
@@ -131,36 +131,36 @@ this.CryptoUtils = {
},
/**
* HMAC-based Key Derivation (RFC 5869).
*/
hkdf: function hkdf(ikm, xts, info, len) {
const BLOCKSIZE = 256 / 8;
if (typeof xts === undefined)
- xts = String.fromCharCode(0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0);
+ xts = String.fromCharCode(0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0);
let h = CryptoUtils.makeHMACHasher(Ci.nsICryptoHMAC.SHA256,
CryptoUtils.makeHMACKey(xts));
let prk = CryptoUtils.digestBytes(ikm, h);
return CryptoUtils.hkdfExpand(prk, info, len);
},
/**
* HMAC-based Key Derivation Step 2 according to RFC 5869.
*/
hkdfExpand: function hkdfExpand(prk, info, len) {
const BLOCKSIZE = 256 / 8;
let h = CryptoUtils.makeHMACHasher(Ci.nsICryptoHMAC.SHA256,
CryptoUtils.makeHMACKey(prk));
let T = "";
let Tn = "";
- let iterations = Math.ceil(len/BLOCKSIZE);
+ let iterations = Math.ceil(len / BLOCKSIZE);
for (let i = 0; i < iterations; i++) {
Tn = CryptoUtils.digestBytes(Tn + info + String.fromCharCode(i + 1), h);
T += Tn;
}
return T.slice(0, len);
},
/**
@@ -179,17 +179,17 @@ this.CryptoUtils = {
*
* The default value of 20 for hmacLen is appropriate for SHA1. For SHA256,
* hmacLen should be 32.
*
* The output is an octet string of length dkLen, which you
* can encode as you wish.
*/
pbkdf2Generate : function pbkdf2Generate(P, S, c, dkLen,
- hmacAlg=Ci.nsICryptoHMAC.SHA1, hmacLen=20) {
+ hmacAlg = Ci.nsICryptoHMAC.SHA1, hmacLen = 20) {
// We don't have a default in the algo itself, as NSS does.
// Use the constant.
if (!dkLen) {
dkLen = SYNC_KEY_DECODED_LENGTH;
}
function F(S, c, i, h) {
@@ -242,32 +242,31 @@ this.CryptoUtils = {
CryptoUtils.makeHMACKey(P));
let T = [];
for (let i = 0; i < l;) {
T[i] = F(S, c, ++i, h);
}
let ret = "";
- for (let i = 0; i < l-1;) {
+ for (let i = 0; i < l - 1;) {
ret += T[i++];
}
ret += T[l - 1].substr(0, r);
return ret;
},
deriveKeyFromPassphrase: function deriveKeyFromPassphrase(passphrase,
salt,
keyLength,
forceJS) {
if (Svc.Crypto.deriveKeyFromPassphrase && !forceJS) {
return Svc.Crypto.deriveKeyFromPassphrase(passphrase, salt, keyLength);
- }
- else {
+ } else {
// Fall back to JS implementation.
// 4096 is hardcoded in WeaveCrypto, so do so here.
return CryptoUtils.pbkdf2Generate(passphrase, atob(salt), 4096,
keyLength);
}
},
/**
@@ -329,43 +328,43 @@ this.CryptoUtils = {
port = "443";
} else {
throw new Error("Unsupported URI scheme: " + uri.scheme);
}
let ext = (extra && extra.ext) ? extra.ext : "";
let requestString = ts.toString(10) + "\n" +
- nonce + "\n" +
- usedMethod + "\n" +
- uri.path + "\n" +
- host + "\n" +
- port + "\n" +
- ext + "\n";
+ nonce + "\n" +
+ usedMethod + "\n" +
+ uri.path + "\n" +
+ host + "\n" +
+ port + "\n" +
+ ext + "\n";
let hasher = CryptoUtils.makeHMACHasher(Ci.nsICryptoHMAC.SHA1,
CryptoUtils.makeHMACKey(key));
let mac = CryptoUtils.digestBytes(requestString, hasher);
function getHeader() {
return CryptoUtils.getHTTPMACSHA1Header(this.identifier, this.ts,
this.nonce, this.mac, this.ext);
}
return {
- identifier: identifier,
- key: key,
+ identifier,
+ key,
method: usedMethod,
hostname: host,
- port: port,
- mac: mac,
- nonce: nonce,
- ts: ts,
- ext: ext,
- getHeader: getHeader
+ port,
+ mac,
+ nonce,
+ ts,
+ ext,
+ getHeader
};
},
/**
* Obtain the HTTP MAC Authorization header value from fields.
*
* @param identifier
@@ -378,33 +377,33 @@ this.CryptoUtils = {
* (string) Computed HMAC digest (raw bytes).
* @param ext
* (optional) (string) Extra string content.
* @returns
* (string) Value to put in Authorization header.
*/
getHTTPMACSHA1Header: function getHTTPMACSHA1Header(identifier, ts, nonce,
mac, ext) {
- let header ='MAC id="' + identifier + '", ' +
- 'ts="' + ts + '", ' +
- 'nonce="' + nonce + '", ' +
- 'mac="' + btoa(mac) + '"';
+ let header = 'MAC id="' + identifier + '", ' +
+ 'ts="' + ts + '", ' +
+ 'nonce="' + nonce + '", ' +
+ 'mac="' + btoa(mac) + '"';
if (!ext) {
return header;
}
- return header += ', ext="' + ext +'"';
+ return header += ', ext="' + ext + '"';
},
/**
* Given an HTTP header value, strip out any attributes.
*/
- stripHeaderAttributes: function(value) {
+ stripHeaderAttributes(value) {
value = value || "";
let i = value.indexOf(";");
return value.substring(0, (i >= 0) ? i : undefined).trim().toLowerCase();
},
/**
* Compute the HAWK client values (mostly the header) for an HTTP request.
*
@@ -453,17 +452,17 @@ this.CryptoUtils = {
* method - (string)
* resource - (string) path plus querystring
* host - (string)
* port - (number)
* hash - (string) payload hash (base64)
* ext - (string) app-specific data
* MAC - (string) request MAC (base64)
*/
- computeHAWK: function(uri, method, options) {
+ computeHAWK(uri, method, options) {
let credentials = options.credentials;
let ts = options.ts || Math.floor(((options.now || Date.now()) +
(options.localtimeOffsetMsec || 0))
/ 1000);
let hash_algo, hmac_algo;
if (credentials.algorithm == "sha1") {
hash_algo = Ci.nsICryptoHash.SHA1;
@@ -482,17 +481,17 @@ this.CryptoUtils = {
port = 80;
} else if (uri.scheme == "https") {
port = 443;
} else {
throw new Error("Unsupported URI scheme: " + uri.scheme);
}
let artifacts = {
- ts: ts,
+ ts,
nonce: options.nonce || btoa(CryptoUtils.generateRandomBytes(8)),
method: method.toUpperCase(),
resource: uri.path, // This includes both path and search/queryarg.
host: uri.asciiHost.toLowerCase(), // This includes punycoding.
port: port.toString(10),
hash: options.hash,
ext: options.ext,
};
@@ -500,33 +499,33 @@ this.CryptoUtils = {
let contentType = CryptoUtils.stripHeaderAttributes(options.contentType);
if (!artifacts.hash && options.hasOwnProperty("payload")
&& options.payload) {
let hasher = Cc["@mozilla.org/security/hash;1"]
.createInstance(Ci.nsICryptoHash);
hasher.init(hash_algo);
CryptoUtils.updateUTF8("hawk.1.payload\n", hasher);
- CryptoUtils.updateUTF8(contentType+"\n", hasher);
+ CryptoUtils.updateUTF8(contentType + "\n", hasher);
CryptoUtils.updateUTF8(options.payload, hasher);
CryptoUtils.updateUTF8("\n", hasher);
let hash = hasher.finish(false);
// HAWK specifies this .hash to use +/ (not _-) and include the
// trailing "==" padding.
let hash_b64 = btoa(hash);
artifacts.hash = hash_b64;
}
- let requestString = ("hawk.1.header" + "\n" +
+ let requestString = ("hawk.1.header" + "\n" +
artifacts.ts.toString(10) + "\n" +
- artifacts.nonce + "\n" +
- artifacts.method + "\n" +
- artifacts.resource + "\n" +
- artifacts.host + "\n" +
- artifacts.port + "\n" +
+ artifacts.nonce + "\n" +
+ artifacts.method + "\n" +
+ artifacts.resource + "\n" +
+ artifacts.host + "\n" +
+ artifacts.port + "\n" +
(artifacts.hash || "") + "\n");
if (artifacts.ext) {
requestString += artifacts.ext.replace("\\", "\\\\").replace("\n", "\\n");
}
requestString += "\n";
let hasher = CryptoUtils.makeHMACHasher(hmac_algo,
CryptoUtils.makeHMACKey(credentials.key));
@@ -539,17 +538,17 @@ this.CryptoUtils = {
}
let header = ('Hawk id="' + credentials.id + '", ' +
'ts="' + artifacts.ts + '", ' +
'nonce="' + artifacts.nonce + '", ' +
(artifacts.hash ? ('hash="' + artifacts.hash + '", ') : "") +
(artifacts.ext ? ('ext="' + escape(artifacts.ext) + '", ') : "") +
'mac="' + artifacts.mac + '"');
return {
- artifacts: artifacts,
+ artifacts,
field: header,
};
},
};
XPCOMUtils.defineLazyGetter(CryptoUtils, "_utf8Converter", function() {
let converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"]
--- a/services/crypto/tests/unit/head_helpers.js
+++ b/services/crypto/tests/unit/head_helpers.js
@@ -3,35 +3,34 @@ var Ci = Components.interfaces;
var Cr = Components.results;
var Cu = Components.utils;
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
try {
// In the context of xpcshell tests, there won't be a default AppInfo
Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULAppInfo);
-}
-catch(ex) {
+} catch (ex) {
// Make sure to provide the right OS so crypto loads the right binaries
var OS = "XPCShell";
if (mozinfo.os == "win")
OS = "WINNT";
else if (mozinfo.os == "mac")
OS = "Darwin";
else
OS = "Linux";
Cu.import("resource://testing-common/AppInfo.jsm", this);
updateAppInfo({
name: "XPCShell",
ID: "{3e3ba16c-1675-4e88-b9c8-afef81b3d2ef}",
version: "1",
platformVersion: "",
- OS: OS,
+ OS,
});
}
// Register resource alias. Normally done in SyncComponents.manifest.
function addResourceAlias() {
Cu.import("resource://gre/modules/Services.jsm");
const resProt = Services.io.getProtocolHandler("resource")
.QueryInterface(Ci.nsIResProtocolHandler);
--- a/services/crypto/tests/unit/test_utils_hawk.js
+++ b/services/crypto/tests/unit/test_utils_hawk.js
@@ -24,18 +24,18 @@ add_test(function test_hawk() {
let method = "POST";
let ts = 1353809207;
let nonce = "Ygvqdz";
let result;
let uri_http = CommonUtils.makeURI("http://example.net/somewhere/over/the/rainbow");
let sha1_opts = { credentials: credentials_sha1,
ext: "Bazinga!",
- ts: ts,
- nonce: nonce,
+ ts,
+ nonce,
payload: "something to write about",
};
result = compute(uri_http, method, sha1_opts);
// The HAWK spec uses non-urlsafe base64 (+/) for its output MAC string.
do_check_eq(result.field,
'Hawk id="123456", ts="1353809207", nonce="Ygvqdz", ' +
'hash="bsvY3IfUllw6V5rvk4tStEvpBhE=", ext="Bazinga!", ' +
@@ -55,18 +55,18 @@ add_test(function test_hawk() {
id: "123456",
key: "2983d45yun89q",
algorithm: "sha256",
};
let uri_https = CommonUtils.makeURI("https://example.net/somewhere/over/the/rainbow");
let sha256_opts = { credentials: credentials_sha256,
ext: "Bazinga!",
- ts: ts,
- nonce: nonce,
+ ts,
+ nonce,
payload: "something to write about",
contentType: "text/plain",
};
result = compute(uri_https, method, sha256_opts);
do_check_eq(result.field,
'Hawk id="123456", ts="1353809207", nonce="Ygvqdz", ' +
'hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", ' +
@@ -78,18 +78,18 @@ add_test(function test_hawk() {
do_check_eq(result.artifacts.method, method);
do_check_eq(result.artifacts.resource, "/somewhere/over/the/rainbow");
do_check_eq(result.artifacts.host, "example.net");
do_check_eq(result.artifacts.port, 443);
do_check_eq(result.artifacts.hash, "2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=");
do_check_eq(result.artifacts.ext, "Bazinga!");
let sha256_opts_noext = { credentials: credentials_sha256,
- ts: ts,
- nonce: nonce,
+ ts,
+ nonce,
payload: "something to write about",
contentType: "text/plain",
};
result = compute(uri_https, method, sha256_opts_noext);
do_check_eq(result.field,
'Hawk id="123456", ts="1353809207", nonce="Ygvqdz", ' +
'hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", ' +
'mac="HTgtd0jPI6E4izx8e4OHdO36q00xFCU0FolNq3RiCYs="'
@@ -111,18 +111,18 @@ add_test(function test_hawk() {
result = compute(uri_https, method, { credentials: credentials_sha256 });
let fields = result.field.split(" ");
do_check_eq(fields[0], "Hawk");
do_check_eq(fields[1], 'id="123456",'); // from creds.id
do_check_true(fields[2].startsWith('ts="'));
/* The HAWK spec calls for seconds-since-epoch, not ms-since-epoch.
* Warning: this test will fail in the year 33658, and for time travellers
* who journey earlier than 2001. Please plan accordingly. */
- do_check_true(result.artifacts.ts > 1000*1000*1000);
- do_check_true(result.artifacts.ts < 1000*1000*1000*1000);
+ do_check_true(result.artifacts.ts > 1000 * 1000 * 1000);
+ do_check_true(result.artifacts.ts < 1000 * 1000 * 1000 * 1000);
do_check_true(fields[3].startsWith('nonce="'));
do_check_eq(fields[3].length, ('nonce="12345678901=",').length);
do_check_eq(result.artifacts.nonce.length, ("12345678901=").length);
let result2 = compute(uri_https, method, { credentials: credentials_sha256 });
do_check_neq(result.artifacts.nonce, result2.artifacts.nonce);
/* Using an upper-case URI hostname shouldn't affect the hash. */
@@ -154,17 +154,17 @@ add_test(function test_hawk() {
result = compute(uri_https, method, { credentials: credentials_sha256,
now: 1378848968650,
});
do_check_eq(result.artifacts.ts, 1378848968);
result = compute(uri_https, method, { credentials: credentials_sha256,
now: 1378848968650,
- localtimeOffsetMsec: 1000*1000,
+ localtimeOffsetMsec: 1000 * 1000,
});
do_check_eq(result.artifacts.ts, 1378848968 + 1000);
/* Search/query-args in URIs should be included in the hash. */
let makeURI = CommonUtils.makeURI;
result = compute(makeURI("http://example.net/path"), method, sha256_opts);
do_check_eq(result.artifacts.resource, "/path");
do_check_eq(result.artifacts.mac, "WyKHJjWaeYt8aJD+H9UeCWc0Y9C+07ooTmrcrOW4MPI=");
--- a/services/crypto/tests/unit/test_utils_httpmac.js
+++ b/services/crypto/tests/unit/test_utils_httpmac.js
@@ -17,28 +17,28 @@ add_test(function test_sha1() {
let id = "vmo1txkttblmn51u2p3zk2xiy16hgvm5ok8qiv1yyi86ffjzy9zj0ez9x6wnvbx7";
let key = "b8u1cc5iiio5o319og7hh8faf2gi5ym4aq0zwf112cv1287an65fudu5zj7zo7dz";
let ts = 1329181221;
let method = "GET";
let nonce = "wGX71";
let uri = CommonUtils.makeURI("http://10.250.2.176/alias/");
let result = CryptoUtils.computeHTTPMACSHA1(id, key, method, uri,
- {ts: ts, nonce: nonce});
+ {ts, nonce});
do_check_eq(btoa(result.mac), "jzh5chjQc2zFEvLbyHnPdX11Yck=");
do_check_eq(result.getHeader(),
'MAC id="vmo1txkttblmn51u2p3zk2xiy16hgvm5ok8qiv1yyi86ffjzy9zj0ez9x6wnvbx7", ' +
'ts="1329181221", nonce="wGX71", mac="jzh5chjQc2zFEvLbyHnPdX11Yck="');
let ext = "EXTRA DATA; foo,bar=1";
result = CryptoUtils.computeHTTPMACSHA1(id, key, method, uri,
- {ts: ts, nonce: nonce, ext: ext});
+ {ts, nonce, ext});
do_check_eq(btoa(result.mac), "bNf4Fnt5k6DnhmyipLPkuZroH68=");
do_check_eq(result.getHeader(),
'MAC id="vmo1txkttblmn51u2p3zk2xiy16hgvm5ok8qiv1yyi86ffjzy9zj0ez9x6wnvbx7", ' +
'ts="1329181221", nonce="wGX71", mac="bNf4Fnt5k6DnhmyipLPkuZroH68=", ' +
'ext="EXTRA DATA; foo,bar=1"');
run_next_test();
});
--- a/services/crypto/tests/unit/test_utils_pbkdf2.js
+++ b/services/crypto/tests/unit/test_utils_pbkdf2.js
@@ -25,36 +25,36 @@ add_task(function test_pbkdf2() {
// PBKDF2 HMAC-SHA1 Test Vectors
add_task(function test_pbkdf2_hmac_sha1() {
let pbkdf2 = CryptoUtils.pbkdf2Generate;
let vectors = [
{P: "password", // (8 octets)
S: "salt", // (4 octets)
c: 1,
dkLen: 20,
- DK: h("0c 60 c8 0f 96 1f 0e 71"+
- "f3 a9 b5 24 af 60 12 06"+
+ DK: h("0c 60 c8 0f 96 1f 0e 71" +
+ "f3 a9 b5 24 af 60 12 06" +
"2f e0 37 a6"), // (20 octets)
},
{P: "password", // (8 octets)
S: "salt", // (4 octets)
c: 2,
dkLen: 20,
- DK: h("ea 6c 01 4d c7 2d 6f 8c"+
- "cd 1e d9 2a ce 1d 41 f0"+
+ DK: h("ea 6c 01 4d c7 2d 6f 8c" +
+ "cd 1e d9 2a ce 1d 41 f0" +
"d8 de 89 57"), // (20 octets)
},
{P: "password", // (8 octets)
S: "salt", // (4 octets)
c: 4096,
dkLen: 20,
- DK: h("4b 00 79 01 b7 65 48 9a"+
- "be ad 49 d9 26 f7 21 d0"+
+ DK: h("4b 00 79 01 b7 65 48 9a" +
+ "be ad 49 d9 26 f7 21 d0" +
"65 a4 29 c1"), // (20 octets)
},
// XXX Uncomment the following test after Bug 968567 lands
//
// XXX As it stands, I estimate that the CryptoUtils implementation will
// take approximately 16 hours in my 2.3GHz MacBook to perform this many
// rounds.
@@ -67,28 +67,28 @@ add_task(function test_pbkdf2_hmac_sha1(
// "e9 94 5b 3d 6b a2 15 8c"+
// "26 34 e9 84"), // (20 octets)
// },
{P: "passwordPASSWORDpassword", // (24 octets)
S: "saltSALTsaltSALTsaltSALTsaltSALTsalt", // (36 octets)
c: 4096,
dkLen: 25,
- DK: h("3d 2e ec 4f e4 1c 84 9b"+
- "80 c8 d8 36 62 c0 e4 4a"+
- "8b 29 1a 96 4c f2 f0 70"+
+ DK: h("3d 2e ec 4f e4 1c 84 9b" +
+ "80 c8 d8 36 62 c0 e4 4a" +
+ "8b 29 1a 96 4c f2 f0 70" +
"38"), // (25 octets)
},
{P: "pass\0word", // (9 octets)
S: "sa\0lt", // (5 octets)
c: 4096,
dkLen: 16,
- DK: h("56 fa 6a a7 55 48 09 9d"+
+ DK: h("56 fa 6a a7 55 48 09 9d" +
"cc 37 d7 f0 34 25 e0 c3"), // (16 octets)
},
];
for (let v of vectors) {
do_check_eq(v.DK, b2h(pbkdf2(v.P, v.S, v.c, v.dkLen)));
}
});
@@ -99,58 +99,58 @@ add_task(function test_pbkdf2_hmac_sha1(
// https://stackoverflow.com/questions/5130513/pbkdf2-hmac-sha2-test-vectors
add_task(function test_pbkdf2_hmac_sha256() {
let pbkdf2 = CryptoUtils.pbkdf2Generate;
let vectors = [
{P: "password", // (8 octets)
S: "salt", // (4 octets)
c: 1,
dkLen: 32,
- DK: h("12 0f b6 cf fc f8 b3 2c"+
- "43 e7 22 52 56 c4 f8 37"+
- "a8 65 48 c9 2c cc 35 48"+
+ DK: h("12 0f b6 cf fc f8 b3 2c" +
+ "43 e7 22 52 56 c4 f8 37" +
+ "a8 65 48 c9 2c cc 35 48" +
"08 05 98 7c b7 0b e1 7b"), // (32 octets)
},
{P: "password", // (8 octets)
S: "salt", // (4 octets)
c: 2,
dkLen: 32,
- DK: h("ae 4d 0c 95 af 6b 46 d3"+
- "2d 0a df f9 28 f0 6d d0"+
- "2a 30 3f 8e f3 c2 51 df"+
+ DK: h("ae 4d 0c 95 af 6b 46 d3" +
+ "2d 0a df f9 28 f0 6d d0" +
+ "2a 30 3f 8e f3 c2 51 df" +
"d6 e2 d8 5a 95 47 4c 43"), // (32 octets)
},
{P: "password", // (8 octets)
S: "salt", // (4 octets)
c: 4096,
dkLen: 32,
- DK: h("c5 e4 78 d5 92 88 c8 41"+
- "aa 53 0d b6 84 5c 4c 8d"+
- "96 28 93 a0 01 ce 4e 11"+
+ DK: h("c5 e4 78 d5 92 88 c8 41" +
+ "aa 53 0d b6 84 5c 4c 8d" +
+ "96 28 93 a0 01 ce 4e 11" +
"a4 96 38 73 aa 98 13 4a"), // (32 octets)
},
{P: "passwordPASSWORDpassword", // (24 octets)
S: "saltSALTsaltSALTsaltSALTsaltSALTsalt", // (36 octets)
c: 4096,
dkLen: 40,
- DK: h("34 8c 89 db cb d3 2b 2f"+
- "32 d8 14 b8 11 6e 84 cf"+
- "2b 17 34 7e bc 18 00 18"+
- "1c 4e 2a 1f b8 dd 53 e1"+
+ DK: h("34 8c 89 db cb d3 2b 2f" +
+ "32 d8 14 b8 11 6e 84 cf" +
+ "2b 17 34 7e bc 18 00 18" +
+ "1c 4e 2a 1f b8 dd 53 e1" +
"c6 35 51 8c 7d ac 47 e9"), // (40 octets)
},
{P: "pass\0word", // (9 octets)
S: "sa\0lt", // (5 octets)
c: 4096,
dkLen: 16,
- DK: h("89 b6 9d 05 16 f8 29 89"+
+ DK: h("89 b6 9d 05 16 f8 29 89" +
"3c 69 62 26 65 0a 86 87"), // (16 octets)
},
];
for (let v of vectors) {
do_check_eq(v.DK,
b2h(pbkdf2(v.P, v.S, v.c, v.dkLen, Ci.nsICryptoHMAC.SHA256, 32)));
}
--- a/services/fxaccounts/Credentials.jsm
+++ b/services/fxaccounts/Credentials.jsm
@@ -45,60 +45,60 @@ var log = Log.repository.getLogger("Iden
log.level = LOG_LEVEL;
log.addAppender(new Log.ConsoleAppender(new Log.BasicFormatter()));
this.Credentials = Object.freeze({
/**
* Make constants accessible to tests
*/
constants: {
- PROTOCOL_VERSION: PROTOCOL_VERSION,
- PBKDF2_ROUNDS: PBKDF2_ROUNDS,
- STRETCHED_PW_LENGTH_BYTES: STRETCHED_PW_LENGTH_BYTES,
- HKDF_SALT: HKDF_SALT,
- HKDF_LENGTH: HKDF_LENGTH,
- HMAC_ALGORITHM: HMAC_ALGORITHM,
- HMAC_LENGTH: HMAC_LENGTH,
+ PROTOCOL_VERSION,
+ PBKDF2_ROUNDS,
+ STRETCHED_PW_LENGTH_BYTES,
+ HKDF_SALT,
+ HKDF_LENGTH,
+ HMAC_ALGORITHM,
+ HMAC_LENGTH,
},
/**
* KW function from https://github.com/mozilla/fxa-auth-server/wiki/onepw-protocol
*
* keyWord derivation for use as a salt.
*
*
* @param {String} context String for use in generating salt
*
* @return {bitArray} the salt
*
* Note that PROTOCOL_VERSION does not refer in any way to the version of the
* Firefox Accounts API.
*/
- keyWord: function(context) {
+ keyWord(context) {
return CommonUtils.stringToBytes(PROTOCOL_VERSION + context);
},
/**
* KWE function from https://github.com/mozilla/fxa-auth-server/wiki/onepw-protocol
*
* keyWord extended with a name and an email.
*
* @param {String} name The name of the salt
* @param {String} email The email of the user.
*
* @return {bitArray} the salt combination with the namespace
*
* Note that PROTOCOL_VERSION does not refer in any way to the version of the
* Firefox Accounts API.
*/
- keyWordExtended: function(name, email) {
+ keyWordExtended(name, email) {
return CommonUtils.stringToBytes(PROTOCOL_VERSION + name + ':' + email);
},
- setup: function(emailInput, passwordInput, options={}) {
+ setup(emailInput, passwordInput, options = {}) {
let deferred = Promise.defer();
log.debug("setup credentials for " + emailInput);
let hkdfSalt = options.hkdfSalt || HKDF_SALT;
let hkdfLength = options.hkdfLength || HKDF_LENGTH;
let hmacLength = options.hmacLength || HMAC_LENGTH;
let hmacAlgorithm = options.hmacAlgorithm || HMAC_ALGORITHM;
let stretchedPWLength = options.stretchedPassLength || STRETCHED_PW_LENGTH_BYTES;
--- a/services/fxaccounts/FxAccounts.jsm
+++ b/services/fxaccounts/FxAccounts.jsm
@@ -161,27 +161,27 @@ AccountState.prototype = {
updateUserAccountData(updatedFields) {
if (!this.isCurrent) {
return Promise.reject(new Error("Another user has signed in"));
}
return this.storageManager.updateAccountData(updatedFields);
},
- resolve: function(result) {
+ resolve(result) {
if (!this.isCurrent) {
log.info("An accountState promise was resolved, but was actually rejected" +
" due to a different user being signed in. Originally resolved" +
" with", result);
return Promise.reject(new Error("A different user signed in"));
}
return Promise.resolve(result);
},
- reject: function(error) {
+ reject(error) {
// It could be argued that we should just let it reject with the original
// error - but this runs the risk of the error being (eg) a 401, which
// might cause the consumer to attempt some remediation and cause other
// problems.
if (!this.isCurrent) {
log.info("An accountState promise was rejected, but we are ignoring that" +
"reason and rejecting it due to a different user being signed in." +
"Originally rejected with", error);
@@ -307,17 +307,17 @@ function copyObjectProperties(from, to,
function urlsafeBase64Encode(key) {
return ChromeUtils.base64URLEncode(new Uint8Array(key), { pad: false });
}
/**
* The public API's constructor.
*/
-this.FxAccounts = function (mockInternal) {
+this.FxAccounts = function(mockInternal) {
let internal = new FxAccountsInternal();
let external = {};
// Copy all public properties to the 'external' object.
let prototype = FxAccountsInternal.prototype;
let options = {keys: publicProperties, bind: internal};
copyObjectProperties(prototype, external, options);
@@ -329,17 +329,17 @@ this.FxAccounts = function (mockInternal
if (mockInternal) {
// Exposes the internal object for testing only.
external.internal = internal;
}
if (!internal.fxaPushService) {
// internal.fxaPushService option is used in testing.
// Otherwise we load the service lazily.
- XPCOMUtils.defineLazyGetter(internal, "fxaPushService", function () {
+ XPCOMUtils.defineLazyGetter(internal, "fxaPushService", function() {
return Components.classes["@mozilla.org/fxaccounts/push;1"]
.getService(Components.interfaces.nsISupports)
.wrappedJSObject;
});
}
// wait until after the mocks are setup before initializing.
internal.initialize();
@@ -388,17 +388,17 @@ FxAccountsInternal.prototype = {
// The profile object used to fetch the actual user profile.
_profile: null,
get profile() {
if (!this._profile) {
let profileServerUrl = Services.urlFormatter.formatURLPref("identity.fxaccounts.remote.profile.uri");
this._profile = new FxAccountsProfile({
fxa: this,
- profileServerUrl: profileServerUrl,
+ profileServerUrl,
});
}
return this._profile;
},
// A hook-point for tests who may want a mocked AccountState or mocked storage.
newAccountState(credentials) {
let storage = new FxAccountsStorageManager();
@@ -406,17 +406,17 @@ FxAccountsInternal.prototype = {
return new AccountState(storage);
},
/**
* Send a message to a set of devices in the same account
*
* @return Promise
*/
- notifyDevices: function(deviceIds, payload, TTL) {
+ notifyDevices(deviceIds, payload, TTL) {
if (!Array.isArray(deviceIds)) {
deviceIds = [deviceIds];
}
return this.currentAccountState.getUserAccountData()
.then(data => {
if (!data) {
throw this._error(ERROR_NO_ACCOUNT);
}
@@ -428,21 +428,21 @@ FxAccountsInternal.prototype = {
payload, TTL);
});
},
/**
* Return the current time in milliseconds as an integer. Allows tests to
* manipulate the date to simulate certificate expiration.
*/
- now: function() {
+ now() {
return this.fxAccountsClient.now();
},
- getAccountsClient: function() {
+ getAccountsClient() {
return this.fxAccountsClient;
},
/**
* Return clock offset in milliseconds, as reported by the fxAccountsClient.
* This can be overridden for testing.
*
* The offset is the number of milliseconds that must be added to the client
@@ -709,42 +709,42 @@ FxAccountsInternal.prototype = {
return this.currentAccountState.getUserAccountData().then(data => {
if (!data) {
return false;
}
return this.fxAccountsClient.accountStatus(data.uid);
});
},
- checkVerificationStatus: function() {
+ checkVerificationStatus() {
log.trace('checkVerificationStatus');
let currentState = this.currentAccountState;
return currentState.getUserAccountData().then(data => {
if (!data) {
log.trace("checkVerificationStatus - no user data");
return null;
}
// Always check the verification status, even if the local state indicates
// we're already verified. If the user changed their password, the check
// will fail, and we'll enter the reauth state.
log.trace("checkVerificationStatus - forcing verification status check");
return this.pollEmailStatus(currentState, data.sessionToken, "push");
});
},
- _destroyOAuthToken: function(tokenData) {
+ _destroyOAuthToken(tokenData) {
let client = new FxAccountsOAuthGrantClient({
serverURL: tokenData.server,
client_id: FX_OAUTH_CLIENT_ID
});
return client.destroyToken(tokenData.token)
},
- _destroyAllOAuthTokens: function(tokenInfos) {
+ _destroyAllOAuthTokens(tokenInfos) {
// let's just destroy them all in parallel...
let promises = [];
for (let [key, tokenInfo] of Object.entries(tokenInfos || {})) {
promises.push(this._destroyOAuthToken(tokenInfo));
}
return Promise.all(promises);
},
@@ -859,17 +859,17 @@ FxAccountsInternal.prototype = {
* uid: The user's unique id
* sessionToken: Session for the FxA server
* kA: An encryption key from the FxA server
* kB: An encryption key derived from the user's FxA password
* verified: email verification status
* }
* or null if no user is signed in
*/
- getKeys: function() {
+ getKeys() {
let currentState = this.currentAccountState;
return currentState.getUserAccountData().then((userData) => {
if (!userData) {
throw new Error("Can't get keys; User is not signed in");
}
if (userData.kA && userData.kB) {
return userData;
}
@@ -895,17 +895,17 @@ FxAccountsInternal.prototype = {
}
}
return currentState.whenKeysReadyDeferred.promise;
}).catch(err =>
this._handleTokenError(err)
).then(result => currentState.resolve(result));
},
- fetchAndUnwrapKeys: function(keyFetchToken) {
+ fetchAndUnwrapKeys(keyFetchToken) {
if (logPII) {
log.debug("fetchAndUnwrapKeys: token: " + keyFetchToken);
}
let currentState = this.currentAccountState;
return Task.spawn(function* task() {
// Sign out if we don't have a key fetch token.
if (!keyFetchToken) {
log.warn("improper fetchAndUnwrapKeys() call: token missing");
@@ -946,17 +946,17 @@ FxAccountsInternal.prototype = {
// We are now ready for business. This should only be invoked once
// per setSignedInUser(), regardless of whether we've rebooted since
// setSignedInUser() was called.
this.notifyObservers(ONVERIFIED_NOTIFICATION);
return currentState.getUserAccountData();
}.bind(this)).then(result => currentState.resolve(result));
},
- getAssertionFromCert: function(data, keyPair, cert, audience) {
+ getAssertionFromCert(data, keyPair, cert, audience) {
log.debug("getAssertionFromCert");
let payload = {};
let d = Promise.defer();
let options = {
duration: ASSERTION_LIFETIME,
localtimeOffsetMsec: this.localtimeOffsetMsec,
now: this.now()
};
@@ -973,17 +973,17 @@ FxAccountsInternal.prototype = {
log.debug("getAssertionFromCert returning signed: " + signed);
}
d.resolve(signed);
}
});
return d.promise.then(result => currentState.resolve(result));
},
- getCertificateSigned: function(sessionToken, serializedPublicKey, lifetime) {
+ getCertificateSigned(sessionToken, serializedPublicKey, lifetime) {
log.debug("getCertificateSigned: " + !!sessionToken + " " + !!serializedPublicKey);
if (logPII) {
log.debug("getCertificateSigned: " + sessionToken + " " + serializedPublicKey);
}
return this.fxAccountsClient.signCertificate(
sessionToken,
JSON.parse(serializedPublicKey),
lifetime
@@ -998,17 +998,17 @@ FxAccountsInternal.prototype = {
// then don't use any cached key pair/certificate, i.e., generate a new
// one and get it signed.
// The purpose of this pref is to expedite any auth errors as the result of a
// expired or revoked FxA session token, e.g., from resetting or changing the FxA
// password.
let ignoreCachedAuthCredentials = false;
try {
ignoreCachedAuthCredentials = Services.prefs.getBoolPref("services.sync.debug.ignoreCachedAuthCredentials");
- } catch(e) {
+ } catch (e) {
// Pref doesn't exist
}
let mustBeValidUntil = this.now() + ASSERTION_USE_PERIOD;
let accountData = yield currentState.getUserAccountData(["cert", "keyPair", "sessionToken"]);
let keyPairValid = !ignoreCachedAuthCredentials &&
accountData.keyPair &&
(accountData.keyPair.validUntil > mustBeValidUntil);
@@ -1069,46 +1069,46 @@ FxAccountsInternal.prototype = {
rawCert: certificate,
validUntil: certWillBeValidUntil,
},
};
yield currentState.updateUserAccountData(toUpdate);
}
return {
keyPair: keyPair.rawKeyPair,
- certificate: certificate,
+ certificate,
}
}),
- getUserAccountData: function() {
+ getUserAccountData() {
return this.currentAccountState.getUserAccountData();
},
isUserEmailVerified: function isUserEmailVerified(data) {
return !!(data && data.verified);
},
/**
* Setup for and if necessary do email verification polling.
*/
- loadAndPoll: function() {
+ loadAndPoll() {
let currentState = this.currentAccountState;
return currentState.getUserAccountData()
.then(data => {
if (data) {
Services.telemetry.getHistogramById("FXA_CONFIGURED").add(1);
if (!this.isUserEmailVerified(data)) {
this.pollEmailStatus(currentState, data.sessionToken, "start");
}
}
return data;
});
},
- startVerifiedCheck: function(data) {
+ startVerifiedCheck(data) {
log.debug("startVerifiedCheck", data && data.verified);
if (logPII) {
log.debug("startVerifiedCheck with user data", data);
}
// Get us to the verified state, then get the keys. This returns a promise
// that will fire when we are completely ready.
//
@@ -1120,32 +1120,32 @@ FxAccountsInternal.prototype = {
// this is simply kicking off a background fetch) so we must add a rejection
// handler to avoid runtime warnings about the rejection not being handled.
this.whenVerified(data).then(
() => this.getKeys(),
err => log.info("startVerifiedCheck promise was rejected: " + err)
);
},
- whenVerified: function(data) {
+ whenVerified(data) {
let currentState = this.currentAccountState;
if (data.verified) {
log.debug("already verified");
return currentState.resolve(data);
}
if (!currentState.whenVerifiedDeferred) {
log.debug("whenVerified promise starts polling for verified email");
this.pollEmailStatus(currentState, data.sessionToken, "start");
}
return currentState.whenVerifiedDeferred.promise.then(
result => currentState.resolve(result)
);
},
- notifyObservers: function(topic, data) {
+ notifyObservers(topic, data) {
log.debug("Notifying observers of " + topic);
Services.obs.notifyObservers(null, topic, data);
},
// XXX - pollEmailStatus should maybe be on the AccountState object?
pollEmailStatus: function pollEmailStatus(currentState, sessionToken, why) {
log.debug("entering pollEmailStatus: " + why);
if (why == "start" || why == "push") {
@@ -1212,17 +1212,17 @@ FxAccountsInternal.prototype = {
},
_rejectWhenVerified(currentState, error) {
currentState.whenVerifiedDeferred.reject(error);
delete currentState.whenVerifiedDeferred;
},
// Poll email status using truncated exponential back-off.
- pollEmailStatusAgain: function (currentState, sessionToken, timeoutMs) {
+ pollEmailStatusAgain(currentState, sessionToken, timeoutMs) {
let ageMs = Date.now() - this.pollStartDate;
if (ageMs >= this.POLL_SESSION) {
if (currentState.whenVerifiedDeferred) {
let error = new Error("User email verification timed out.");
this._rejectWhenVerified(currentState, error);
}
log.debug("polling session exceeded, giving up");
return;
@@ -1233,21 +1233,21 @@ FxAccountsInternal.prototype = {
: this.VERIFICATION_POLL_TIMEOUT_SUBSEQUENT;
}
log.debug("polling with timeout = " + timeoutMs);
this.currentTimer = setTimeout(() => {
this.pollEmailStatus(currentState, sessionToken, "timer");
}, timeoutMs);
},
- requiresHttps: function() {
+ requiresHttps() {
let allowHttp = false;
try {
allowHttp = Services.prefs.getBoolPref("identity.fxaccounts.allowHttp");
- } catch(e) {
+ } catch (e) {
// Pref doesn't exist
}
return allowHttp !== true;
},
promiseAccountsSignUpURI() {
return FxAccountsConfig.promiseAccountsSignUpURI();
},
@@ -1275,17 +1275,17 @@ FxAccountsInternal.prototype = {
return url + newQueryPortion;
}).then(result => currentState.resolve(result));
}),
// Returns a promise that resolves with the URL to use to change
// the current account's profile image.
// if settingToEdit is set, the profile page should hightlight that setting
// for the user to edit.
- promiseAccountsChangeProfileURI: function(entrypoint, settingToEdit = null) {
+ promiseAccountsChangeProfileURI(entrypoint, settingToEdit = null) {
let url = Services.urlFormatter.formatURLPref("identity.fxaccounts.settings.uri");
if (settingToEdit) {
url += (url.indexOf("?") == -1 ? "?" : "&") +
"setting=" + encodeURIComponent(settingToEdit);
}
if (this.requiresHttps() && !/^https:/.test(url)) { // Comment to un-break emacs js-mode highlighting
@@ -1304,17 +1304,17 @@ FxAccountsInternal.prototype = {
newQueryPortion += "&entrypoint=" + encodeURIComponent(entrypoint);
}
return url + newQueryPortion;
}).then(result => currentState.resolve(result));
},
// Returns a promise that resolves with the URL to use to manage the current
// user's FxA acct.
- promiseAccountsManageURI: function(entrypoint) {
+ promiseAccountsManageURI(entrypoint) {
let url = Services.urlFormatter.formatURLPref("identity.fxaccounts.settings.uri");
if (this.requiresHttps() && !/^https:/.test(url)) { // Comment to un-break emacs js-mode highlighting
throw new Error("Firefox Accounts server must use HTTPS");
}
let currentState = this.currentAccountState;
// but we need to append the uid and email address onto a query string
// (if the server has no matching uid it will offer to sign in with the
// email address)
@@ -1392,17 +1392,17 @@ FxAccountsInternal.prototype = {
try {
log.debug("getOAuthToken fetching new token from", oAuthURL);
let assertion = yield this.getAssertion(oAuthURL);
let result = yield client.getTokenFromAssertion(assertion, scopeString);
let token = result.access_token;
// If we got one, cache it.
if (token) {
- let entry = {token: token, server: oAuthURL};
+ let entry = {token, server: oAuthURL};
// But before we do, check the cache again - if we find one now, it
// means someone else concurrently requested the same scope and beat
// us to the cache write. To be nice to the server, we revoke the one
// we just got and return the newly cached value.
let cached = currentState.getCachedToken(scope);
if (cached) {
log.debug("Detected a race for this token - revoking the new one.");
this._destroyOAuthToken(entry);
@@ -1460,31 +1460,31 @@ FxAccountsInternal.prototype = {
* AUTH_ERROR
* UNKNOWN_ERROR
*
* These errors will pass through:
* INVALID_PARAMETER
* NO_ACCOUNT
* UNVERIFIED_ACCOUNT
*/
- _errorToErrorClass: function (aError) {
+ _errorToErrorClass(aError) {
if (aError.errno) {
let error = SERVER_ERRNO_TO_ERROR[aError.errno];
return this._error(ERROR_TO_GENERAL_ERROR_CLASS[error] || ERROR_UNKNOWN, aError);
} else if (aError.message &&
(aError.message === "INVALID_PARAMETER" ||
aError.message === "NO_ACCOUNT" ||
aError.message === "UNVERIFIED_ACCOUNT" ||
aError.message === "AUTH_ERROR")) {
return aError;
}
return this._error(ERROR_UNKNOWN, aError);
},
- _error: function(aError, aDetails) {
+ _error(aError, aDetails) {
log.error("FxA rejecting with error ${aError}, details: ${aDetails}", {aError, aDetails});
let reason = new Error(aError);
if (aDetails) {
reason.details = aDetails;
}
return reason;
},
@@ -1505,17 +1505,17 @@ FxAccountsInternal.prototype = {
* an error object ({error: ERROR, details: {}}) of the following:
* INVALID_PARAMETER
* NO_ACCOUNT
* UNVERIFIED_ACCOUNT
* NETWORK_ERROR
* AUTH_ERROR
* UNKNOWN_ERROR
*/
- getSignedInUserProfile: function () {
+ getSignedInUserProfile() {
let currentState = this.currentAccountState;
return this.profile.getProfile().then(
profileData => {
let profile = Cu.cloneInto(profileData, {});
return currentState.resolve(profile);
},
error => {
log.error("Could not retrieve profile data", error);
@@ -1584,17 +1584,17 @@ FxAccountsInternal.prototype = {
try {
// Allow tests to skip device registration because:
// 1. It makes remote requests to the auth server.
// 2. _getDeviceName does not work from xpcshell.
// 3. The B2G tests fail when attempting to import services-sync/util.js.
if (Services.prefs.getBoolPref("identity.fxaccounts.skipDeviceRegistration")) {
return Promise.resolve();
}
- } catch(ignore) {}
+ } catch (ignore) {}
if (!signedInUser.sessionToken) {
return Promise.reject(new Error(
"_registerOrUpdateDevice called without a session token"));
}
return this.fxaPushService.registerPushEndpoint().then(subscription => {
const deviceName = this._getDeviceName();
--- a/services/fxaccounts/FxAccountsClient.jsm
+++ b/services/fxaccounts/FxAccountsClient.jsm
@@ -50,17 +50,17 @@ this.FxAccountsClient.prototype = {
},
/*
* Return current time in milliseconds
*
* Not used by this module, but made available to the FxAccounts.jsm
* that uses this client.
*/
- now: function() {
+ now() {
return this.hawk.now();
},
/**
* Common code from signIn and signUp.
*
* @param path
* Request URL path. Can be /account/create or /account/login
@@ -82,22 +82,22 @@ this.FxAccountsClient.prototype = {
* sessionToken: a session token (hex)
* uid: the user's unique ID (hex)
* unwrapBKey: used to unwrap kB, derived locally from the
* password (not revealed to the FxA server)
* verified (optional): flag indicating verification status of the
* email
* }
*/
- _createSession: function(path, email, password, getKeys=false,
- retryOK=true) {
+ _createSession(path, email, password, getKeys = false,
+ retryOK = true) {
return Credentials.setup(email, password).then((creds) => {
let data = {
authPW: CommonUtils.bytesAsHex(creds.authPW),
- email: email,
+ email,
};
let keys = getKeys ? "?keys=true" : "";
return this._request(path + keys, "POST", null, data).then(
// Include the canonical capitalization of the email in the response so
// the caller can set its signed-in user state accordingly.
result => {
result.email = data.email;
@@ -146,17 +146,17 @@ this.FxAccountsClient.prototype = {
* {
* uid: the user's unique ID (hex)
* sessionToken: a session token (hex)
* keyFetchToken: a key fetch token (hex),
* unwrapBKey: used to unwrap kB, derived locally from the
* password (not revealed to the FxA server)
* }
*/
- signUp: function(email, password, getKeys=false) {
+ signUp(email, password, getKeys = false) {
return this._createSession(SIGNUP, email, password, getKeys,
false /* no retry */);
},
/**
* Authenticate and create a new session with the Firefox Account API server
*
* @param email
@@ -173,30 +173,30 @@ this.FxAccountsClient.prototype = {
* keyFetchToken: a key fetch token (hex)
* sessionToken: a session token (hex)
* uid: the user's unique ID (hex)
* unwrapBKey: used to unwrap kB, derived locally from the
* password (not revealed to the FxA server)
* verified: flag indicating verification status of the email
* }
*/
- signIn: function signIn(email, password, getKeys=false) {
+ signIn: function signIn(email, password, getKeys = false) {
return this._createSession(SIGNIN, email, password, getKeys,
true /* retry */);
},
/**
* Check the status of a session given a session token
*
* @param sessionTokenHex
* The session token encoded in hex
* @return Promise
* Resolves with a boolean indicating if the session is still valid
*/
- sessionStatus: function (sessionTokenHex) {
+ sessionStatus(sessionTokenHex) {
return this._request("/session/status", "GET",
deriveHawkCredentials(sessionTokenHex, "sessionToken")).then(
() => Promise.resolve(true),
error => {
if (isInvalidTokenError(error)) {
return Promise.resolve(false);
}
throw error;
@@ -206,50 +206,50 @@ this.FxAccountsClient.prototype = {
/**
* Destroy the current session with the Firefox Account API server
*
* @param sessionTokenHex
* The session token encoded in hex
* @return Promise
*/
- signOut: function (sessionTokenHex, options = {}) {
+ signOut(sessionTokenHex, options = {}) {
let path = "/session/destroy";
if (options.service) {
path += "?service=" + encodeURIComponent(options.service);
}
return this._request(path, "POST",
deriveHawkCredentials(sessionTokenHex, "sessionToken"));
},
/**
* Check the verification status of the user's FxA email address
*
* @param sessionTokenHex
* The current session token encoded in hex
* @return Promise
*/
- recoveryEmailStatus: function (sessionTokenHex, options = {}) {
+ recoveryEmailStatus(sessionTokenHex, options = {}) {
let path = "/recovery_email/status";
if (options.reason) {
path += "?reason=" + encodeURIComponent(options.reason);
}
return this._request(path, "GET",
deriveHawkCredentials(sessionTokenHex, "sessionToken"));
},
/**
* Resend the verification email for the user
*
* @param sessionTokenHex
* The current token encoded in hex
* @return Promise
*/
- resendVerificationEmail: function(sessionTokenHex) {
+ resendVerificationEmail(sessionTokenHex) {
return this._request("/recovery_email/resend_code", "POST",
deriveHawkCredentials(sessionTokenHex, "sessionToken"));
},
/**
* Retrieve encryption keys
*
* @param keyFetchTokenHex
@@ -257,17 +257,17 @@ this.FxAccountsClient.prototype = {
* @return Promise
* Returns a promise that resolves to an object:
* {
* kA: an encryption key for recevorable data (bytes)
* wrapKB: an encryption key that requires knowledge of the
* user's password (bytes)
* }
*/
- accountKeys: function (keyFetchTokenHex) {
+ accountKeys(keyFetchTokenHex) {
let creds = deriveHawkCredentials(keyFetchTokenHex, "keyFetchToken");
let keyRequestKey = creds.extra.slice(0, 32);
let morecreds = CryptoUtils.hkdf(keyRequestKey, undefined,
Credentials.keyWord("account/keys"), 3 * 32);
let respHMACKey = morecreds.slice(0, 32);
let respXORKey = morecreds.slice(32, 96);
return this._request("/account/keys", "GET", creds).then(resp => {
@@ -306,17 +306,17 @@ this.FxAccountsClient.prototype = {
* The lifetime of the certificate
* @return Promise
* Returns a promise that resolves to the signed certificate.
* The certificate can be used to generate a Persona assertion.
* @throws a new Error
* wrapping any of these HTTP code/errno pairs:
* https://github.com/mozilla/fxa-auth-server/blob/master/docs/api.md#response-12
*/
- signCertificate: function (sessionTokenHex, serializedPublicKey, lifetime) {
+ signCertificate(sessionTokenHex, serializedPublicKey, lifetime) {
let creds = deriveHawkCredentials(sessionTokenHex, "sessionToken");
let body = { publicKey: serializedPublicKey,
duration: lifetime };
return Promise.resolve()
.then(_ => this._request("/certificate/sign", "POST", creds, body))
.then(resp => resp.cert,
err => {
@@ -329,17 +329,17 @@ this.FxAccountsClient.prototype = {
* Determine if an account exists
*
* @param email
* The email address to check
* @return Promise
* The promise resolves to true if the account exists, or false
* if it doesn't. The promise is rejected on other errors.
*/
- accountExists: function (email) {
+ accountExists(email) {
return this.signIn(email, "").then(
(cantHappen) => {
throw new Error("How did I sign in with an empty password?");
},
(expectedError) => {
switch (expectedError.errno) {
case ERRNO_ACCOUNT_DOES_NOT_EXIST:
return false;
@@ -357,18 +357,18 @@ this.FxAccountsClient.prototype = {
},
/**
* Given the uid of an existing account (not an arbitrary email), ask
* the server if it still exists via /account/status.
*
* Used for differentiating between password change and account deletion.
*/
- accountStatus: function(uid) {
- return this._request("/account/status?uid="+uid, "GET").then(
+ accountStatus(uid) {
+ return this._request("/account/status?uid=" + uid, "GET").then(
(result) => {
return result.exists;
},
(error) => {
log.error("accountStatus failed with: " + error);
return Promise.reject(error);
}
);
@@ -535,17 +535,17 @@ this.FxAccountsClient.prototype = {
*/
getDeviceList(sessionTokenHex) {
let path = "/account/devices";
let creds = deriveHawkCredentials(sessionTokenHex, "sessionToken");
return this._request(path, "GET", creds, {});
},
- _clearBackoff: function() {
+ _clearBackoff() {
this.backoffError = null;
},
/**
* A general method for sending raw API calls to the FxA auth server.
* All request bodies and responses are JSON.
*
* @param path
--- a/services/fxaccounts/FxAccountsManager.jsm
+++ b/services/fxaccounts/FxAccountsManager.jsm
@@ -22,22 +22,22 @@ Cu.import("resource://gre/modules/Promis
Cu.import("resource://gre/modules/FxAccountsCommon.js");
XPCOMUtils.defineLazyServiceGetter(this, "permissionManager",
"@mozilla.org/permissionmanager;1",
"nsIPermissionManager");
this.FxAccountsManager = {
- init: function() {
+ init() {
Services.obs.addObserver(this, ONLOGOUT_NOTIFICATION, false);
Services.obs.addObserver(this, ON_FXA_UPDATE_NOTIFICATION, false);
},
- observe: function(aSubject, aTopic, aData) {
+ observe(aSubject, aTopic, aData) {
// Both topics indicate our cache is invalid
this._activeSession = null;
if (aData == ONVERIFIED_NOTIFICATION) {
log.debug("FxAccountsManager: cache cleared, broadcasting: " + aData);
Services.obs.notifyObservers(null, aData, null);
}
},
@@ -62,50 +62,50 @@ this.FxAccountsManager = {
return {
email: this._activeSession.email,
verified: this._activeSession.verified,
profile: this._activeSession.profile,
}
},
- _error: function(aError, aDetails) {
+ _error(aError, aDetails) {
log.error(aError);
let reason = {
error: aError
};
if (aDetails) {
reason.details = aDetails;
}
return Promise.reject(reason);
},
- _getError: function(aServerResponse) {
+ _getError(aServerResponse) {
if (!aServerResponse || !aServerResponse.error || !aServerResponse.error.errno) {
return;
}
let error = SERVER_ERRNO_TO_ERROR[aServerResponse.error.errno];
return error;
},
- _serverError: function(aServerResponse) {
+ _serverError(aServerResponse) {
let error = this._getError({ error: aServerResponse });
return this._error(error ? error : ERROR_SERVER_ERROR, aServerResponse);
},
// As with _fxAccounts, we don't really need this method, but this way we
// allow tests to mock FxAccountsClient. By default, we want to return the
// client used by the fxAccounts object because deep down they should have
// access to the same hawk request object which will enable them to share
// local clock skeq data.
- _getFxAccountsClient: function() {
+ _getFxAccountsClient() {
return this._fxAccounts.getAccountsClient();
},
- _signInSignUp: function(aMethod, aEmail, aPassword, aFetchKeys) {
+ _signInSignUp(aMethod, aEmail, aPassword, aFetchKeys) {
if (Services.io.offline) {
return this._error(ERROR_OFFLINE);
}
if (!aEmail) {
return this._error(ERROR_INVALID_EMAIL);
}
@@ -130,17 +130,17 @@ this.FxAccountsManager = {
}
return client[aMethod](aEmail, aPassword, aFetchKeys);
}
).then(
user => {
let error = this._getError(user);
if (!user || !user.uid || !user.sessionToken || error) {
return this._error(error ? error : ERROR_INTERNAL_INVALID_USER, {
- user: user
+ user
});
}
// If the user object includes an email field, it may differ in
// capitalization from what we sent down. This is the server's
// canonical capitalization and should be used instead.
user.email = user.email || aEmail;
@@ -194,17 +194,17 @@ this.FxAccountsManager = {
*
* As of May 2014, the only HTTP call triggered by this._getAssertion()
* is to /certificate/sign via:
* FxAccounts.getAssertion()
* FxAccountsInternal.getCertificateSigned()
* FxAccountsClient.signCertificate()
* See the latter method for possible (error code, errno) pairs.
*/
- _handleGetAssertionError: function(reason, aAudience, aPrincipal) {
+ _handleGetAssertionError(reason, aAudience, aPrincipal) {
log.debug("FxAccountsManager._handleGetAssertionError()");
let errno = (reason ? reason.errno : NaN) || NaN;
// If the previously valid email/password pair is no longer valid ...
if (errno == ERRNO_INVALID_AUTH_TOKEN) {
return this._fxAccounts.accountStatus().then(
(exists) => {
// ... if the email still maps to an account, the password
// must have changed, so ask the user to enter the new one ...
@@ -231,17 +231,17 @@ this.FxAccountsManager = {
}
);
}
);
}
return Promise.reject(reason.message ? { error: reason.message } : reason);
},
- _getAssertion: function(aAudience, aPrincipal) {
+ _getAssertion(aAudience, aPrincipal) {
return this._fxAccounts.getAssertion(aAudience).then(
(result) => {
if (aPrincipal) {
this._addPermission(aPrincipal);
}
return result;
},
(reason) => {
@@ -255,18 +255,18 @@ this.FxAccountsManager = {
* Interactively demonstrate knowledge of the FxA password
* for the currently logged-in account.
* There are two very different scenarios:
* 1) The password has changed on the server. Failure should log
* the current account OUT.
* 2) The person typing can't prove knowledge of the password used
* to log in. Failure should do nothing.
*/
- _refreshAuthentication: function(aAudience, aEmail, aPrincipal,
- logoutOnFailure=false) {
+ _refreshAuthentication(aAudience, aEmail, aPrincipal,
+ logoutOnFailure = false) {
this._refreshing = true;
return this._uiRequest(UI_REQUEST_REFRESH_AUTH,
aAudience, aPrincipal, aEmail).then(
(assertion) => {
this._refreshing = false;
return assertion;
},
(reason) => {
@@ -278,21 +278,21 @@ this.FxAccountsManager = {
}
);
}
return this._error(reason);
}
);
},
- _localSignOut: function() {
+ _localSignOut() {
return this._fxAccounts.signOut(true);
},
- _signOut: function() {
+ _signOut() {
if (!this._activeSession) {
return Promise.resolve();
}
// We clear the local session cache as soon as we get the onlogout
// notification triggered within FxAccounts.signOut, so we save the
// session token value to be able to remove the remote server session
// in case that we have network connection.
@@ -321,17 +321,17 @@ this.FxAccountsManager = {
reason => {
return this._serverError(reason);
}
);
}
);
},
- _uiRequest: function(aRequest, aAudience, aPrincipal, aParams) {
+ _uiRequest(aRequest, aAudience, aPrincipal, aParams) {
if (Services.io.offline) {
return this._error(ERROR_OFFLINE);
}
let ui = Cc["@mozilla.org/fxaccounts/fxaccounts-ui-glue;1"]
.createInstance(Ci.nsIFxAccountsUIGlue);
if (!ui[aRequest]) {
return this._error(ERROR_UI_REQUEST);
}
@@ -353,65 +353,65 @@ this.FxAccountsManager = {
});
},
error => {
return this._error(ERROR_UI_ERROR, error);
}
);
},
- _addPermission: function(aPrincipal) {
+ _addPermission(aPrincipal) {
// This will fail from tests cause we are running them in the child
// process until we have chrome tests in b2g. Bug 797164.
try {
permissionManager.addFromPrincipal(aPrincipal, FXACCOUNTS_PERMISSION,
Ci.nsIPermissionManager.ALLOW_ACTION);
} catch (e) {
log.warn("Could not add permission " + e);
}
},
// -- API --
- signIn: function(aEmail, aPassword, aFetchKeys) {
+ signIn(aEmail, aPassword, aFetchKeys) {
return this._signInSignUp("signIn", aEmail, aPassword, aFetchKeys);
},
- signUp: function(aEmail, aPassword, aFetchKeys) {
+ signUp(aEmail, aPassword, aFetchKeys) {
return this._signInSignUp("signUp", aEmail, aPassword, aFetchKeys);
},
- signOut: function() {
+ signOut() {
if (!this._activeSession) {
// If there is no cached active session, we try to get it from the
// account storage.
return this.getAccount().then(
result => {
if (!result) {
return Promise.resolve();
}
return this._signOut();
}
);
}
return this._signOut();
},
- resendVerificationEmail: function() {
+ resendVerificationEmail() {
return this._fxAccounts.resendVerificationEmail().then(
(result) => {
return result;
},
(error) => {
return this._error(ERROR_SERVER_ERROR, error);
}
);
},
- getAccount: function() {
+ getAccount() {
// We check first if we have session details cached.
if (this._activeSession) {
// If our cache says that the account is not yet verified,
// we kick off verification before returning what we have.
if (!this._activeSession.verified) {
this.verificationStatus(this._activeSession);
}
log.debug("Account " + JSON.stringify(this._user));
@@ -447,17 +447,17 @@ this.FxAccountsManager = {
// FxAccounts logs already inform about the error.
log.debug("Account ", this._user);
return Promise.resolve(this._user);
});
}
);
},
- queryAccount: function(aEmail) {
+ queryAccount(aEmail) {
log.debug("queryAccount " + aEmail);
if (Services.io.offline) {
return this._error(ERROR_OFFLINE);
}
let deferred = Promise.defer();
if (!aEmail) {
@@ -476,17 +476,17 @@ this.FxAccountsManager = {
return Promise.resolve({
registered: result
});
},
reason => { this._serverError(reason); }
);
},
- verificationStatus: function() {
+ verificationStatus() {
log.debug("verificationStatus");
if (!this._activeSession || !this._activeSession.sessionToken) {
this._error(ERROR_NO_TOKEN_SESSION);
}
// There is no way to unverify an already verified account, so we just
// return the account details of a verified account
if (this._activeSession.verified) {
@@ -540,33 +540,33 @@ this.FxAccountsManager = {
* trigger either the sign in or refresh flows (if our account
* changed on the server).
*
* aOptions can include:
* refreshAuthentication - (bool) Force re-auth.
* silent - (bool) Prevent any UI interaction.
* I.e., try to get an automatic assertion.
*/
- getAssertion: function(aAudience, aPrincipal, aOptions) {
+ getAssertion(aAudience, aPrincipal, aOptions) {
if (!aAudience) {
return this._error(ERROR_INVALID_AUDIENCE);
}
let principal = aPrincipal;
log.debug("FxAccountsManager.getAssertion() aPrincipal: ",
principal.origin, principal.appId,
principal.isInIsolatedMozBrowserElement);
return this.getAccount().then(
user => {
if (user) {
// Three have-user cases to consider. First: are we unverified?
if (!user.verified) {
return this._error(ERROR_UNVERIFIED_ACCOUNT, {
- user: user
+ user
});
}
// Second case: do we need to refresh?
if (aOptions &&
(typeof(aOptions.refreshAuthentication) != "undefined")) {
let gracePeriod = aOptions.refreshAuthentication;
if (typeof(gracePeriod) !== "number" || isNaN(gracePeriod)) {
return this._error(ERROR_INVALID_REFRESH_AUTH_VALUE);
@@ -615,38 +615,38 @@ this.FxAccountsManager = {
if (aOptions && aOptions.silent) {
return Promise.resolve(null);
}
return this._uiRequest(UI_REQUEST_SIGN_IN_FLOW, aAudience, principal);
}
);
},
- getKeys: function() {
+ getKeys() {
let syncEnabled = false;
try {
syncEnabled = Services.prefs.getBoolPref("services.sync.enabled");
- } catch(e) {
+ } catch (e) {
dump("Sync is disabled, so you won't get the keys. " + e + "\n");
}
if (!syncEnabled) {
return Promise.reject(ERROR_SYNC_DISABLED);
}
return this.getAccount().then(
user => {
if (!user) {
log.debug("No signed in user");
return Promise.resolve(null);
}
if (!user.verified) {
return this._error(ERROR_UNVERIFIED_ACCOUNT, {
- user: user
+ user
});
}
return this._fxAccounts.getKeys();
}
);
}
};
--- a/services/fxaccounts/FxAccountsOAuthClient.jsm
+++ b/services/fxaccounts/FxAccountsOAuthClient.jsm
@@ -111,73 +111,73 @@ this.FxAccountsOAuthClient.prototype = {
/**
* WebChannel origin, used to validate origin of messages.
*/
_webChannelOrigin: null,
/**
* Opens a tab at "this._fxaOAuthStartUrl".
* Registers a WebChannel listener and sets up a callback if needed.
*/
- launchWebFlow: function () {
+ launchWebFlow() {
if (!this._channelCallback) {
this._registerChannel();
}
if (this._complete) {
throw new Error("This client already completed the OAuth flow");
} else {
let opener = Services.wm.getMostRecentWindow("navigator:browser").gBrowser;
opener.selectedTab = opener.addTab(this._fxaOAuthStartUrl.href);
}
},
/**
* Release all resources that are in use.
*/
- tearDown: function() {
+ tearDown() {
this.onComplete = null;
this.onError = null;
this._complete = true;
this._channel.stopListening();
this._channel = null;
},
/**
* Configures WebChannel id and origin
*
* @private
*/
- _configureChannel: function() {
+ _configureChannel() {
this._webChannelId = "oauth_" + this.parameters.client_id;
// if this.parameters.content_uri is present but not a valid URI, then this will throw an error.
try {
this._webChannelOrigin = Services.io.newURI(this.parameters.content_uri);
} catch (e) {
throw e;
}
},
/**
* Create a new channel with the WebChannelBroker, setup a callback listener
* @private
*/
- _registerChannel: function() {
+ _registerChannel() {
/**
* Processes messages that are called back from the FxAccountsChannel
*
* @param webChannelId {String}
* Command webChannelId
* @param message {Object}
* Command message
* @param sendingContext {Object}
* Channel message event sendingContext
* @private
*/
- let listener = function (webChannelId, message, sendingContext) {
+ let listener = function(webChannelId, message, sendingContext) {
if (message) {
let command = message.command;
let data = message.data;
let target = sendingContext && sendingContext.browser;
switch (command) {
case "oauth_complete":
// validate the returned state and call onComplete or onError
@@ -246,17 +246,17 @@ this.FxAccountsOAuthClient.prototype = {
/**
* Validates the required FxA OAuth parameters
*
* @param options {Object}
* OAuth client options
* @private
*/
- _validateOptions: function (options) {
+ _validateOptions(options) {
if (!options || !options.parameters) {
throw new Error("Missing 'parameters' configuration option");
}
["oauth_uri", "client_id", "content_uri", "state"].forEach(option => {
if (!options.parameters[option]) {
throw new Error("Missing 'parameters." + option + "' parameter");
}
--- a/services/fxaccounts/FxAccountsOAuthGrantClient.jsm
+++ b/services/fxaccounts/FxAccountsOAuthGrantClient.jsm
@@ -54,60 +54,60 @@ this.FxAccountsOAuthGrantClient.prototyp
/**
* Retrieves an OAuth access token for the signed in user
*
* @param {Object} assertion BrowserID assertion
* @param {String} scope OAuth scope
* @return Promise
* Resolves: {Object} Object with access_token property
*/
- getTokenFromAssertion: function (assertion, scope) {
+ getTokenFromAssertion(assertion, scope) {
if (!assertion) {
throw new Error("Missing 'assertion' parameter");
}
if (!scope) {
throw new Error("Missing 'scope' parameter");
}
let params = {
- scope: scope,
+ scope,
client_id: this.parameters.client_id,
- assertion: assertion,
+ assertion,
response_type: "token"
};
return this._createRequest(AUTH_ENDPOINT, "POST", params);
},
/**
* Destroys a previously fetched OAuth access token.
*
* @param {String} token The previously fetched token
* @return Promise
* Resolves: {Object} with the server response, which is typically
* ignored.
*/
- destroyToken: function (token) {
+ destroyToken(token) {
if (!token) {
throw new Error("Missing 'token' parameter");
}
let params = {
- token: token,
+ token,
};
return this._createRequest(DESTROY_ENDPOINT, "POST", params);
},
/**
* Validates the required FxA OAuth parameters
*
* @param options {Object}
* OAuth client options
* @private
*/
- _validateOptions: function (options) {
+ _validateOptions(options) {
if (!options) {
throw new Error("Missing configuration options");
}
["serverURL", "client_id"].forEach(option => {
if (!options[option]) {
throw new Error("Missing '" + option + "' parameter");
}
@@ -126,26 +126,26 @@ this.FxAccountsOAuthGrantClient.prototyp
* Profile server path, i.e "/profile".
* @param {String} [method]
* Type of request, i.e "GET".
* @return Promise
* Resolves: {Object} Successful response from the Profile server.
* Rejects: {FxAccountsOAuthGrantClientError} Profile client error.
* @private
*/
- _createRequest: function(path, method = "POST", params) {
+ _createRequest(path, method = "POST", params) {
return new Promise((resolve, reject) => {
let profileDataUrl = this.serverURL + path;
let request = new this._Request(profileDataUrl);
method = method.toUpperCase();
request.setHeader("Accept", "application/json");
request.setHeader("Content-Type", "application/json");
- request.onComplete = function (error) {
+ request.onComplete = function(error) {
if (error) {
return reject(new FxAccountsOAuthGrantClientError({
error: ERROR_NETWORK,
errno: ERRNO_NETWORK,
message: error.toString(),
}));
}
--- a/services/fxaccounts/FxAccountsProfile.jsm
+++ b/services/fxaccounts/FxAccountsProfile.jsm
@@ -66,17 +66,17 @@ function objEquiv(a, b) {
}
return true;
}
function hasChanged(oldData, newData) {
return !deepEqual(oldData, newData);
}
-this.FxAccountsProfile = function (options = {}) {
+this.FxAccountsProfile = function(options = {}) {
this._cachedProfile = null;
this._cachedAt = 0; // when we saved the cached version.
this._currentFetchPromise = null;
this._isNotifying = false; // are we sending a notification?
this.fxa = options.fxa || fxAccounts;
this.client = options.profileClient || new FxAccountsProfileClient({
fxa: this.fxa,
serverURL: options.profileServerUrl,
@@ -101,53 +101,53 @@ this.FxAccountsProfile.prototype = {
// the user has just changed their profile via the web, so we want to
// ignore our "freshness threshold"
if (topic == ON_PROFILE_CHANGE_NOTIFICATION && !this._isNotifying) {
log.debug("FxAccountsProfile observed profile change");
this._cachedAt = 0;
}
},
- tearDown: function () {
+ tearDown() {
this.fxa = null;
this.client = null;
this._cachedProfile = null;
Services.obs.removeObserver(this, ON_PROFILE_CHANGE_NOTIFICATION);
},
- _getCachedProfile: function () {
+ _getCachedProfile() {
// The cached profile will end up back in the generic accountData
// once bug 1157529 is fixed.
return Promise.resolve(this._cachedProfile);
},
- _notifyProfileChange: function (uid) {
+ _notifyProfileChange(uid) {
this._isNotifying = true;
Services.obs.notifyObservers(null, ON_PROFILE_CHANGE_NOTIFICATION, uid);
this._isNotifying = false;
},
// Cache fetched data if it is different from what's in the cache.
// Send out a notification if it has changed so that UI can update.
- _cacheProfile: function (profileData) {
+ _cacheProfile(profileData) {
if (!hasChanged(this._cachedProfile, profileData)) {
log.debug("fetched profile matches cached copy");
return Promise.resolve(null); // indicates no change (but only tests care)
}
this._cachedProfile = profileData;
this._cachedAt = Date.now();
return this.fxa.getSignedInUser()
.then(userData => {
log.debug("notifying profile changed for user ${uid}", userData);
this._notifyProfileChange(userData.uid);
return profileData;
});
},
- _fetchAndCacheProfile: function () {
+ _fetchAndCacheProfile() {
if (!this._currentFetchPromise) {
this._currentFetchPromise = this.client.fetchProfile().then(profile => {
return this._cacheProfile(profile).then(() => {
return profile;
});
}).then(profile => {
this._currentFetchPromise = null;
return profile;
@@ -157,17 +157,17 @@ this.FxAccountsProfile.prototype = {
});
}
return this._currentFetchPromise
},
// Returns cached data right away if available, then fetches the latest profile
// data in the background. After data is fetched a notification will be sent
// out if the profile has changed.
- getProfile: function () {
+ getProfile() {
return this._getCachedProfile()
.then(cachedProfile => {
if (cachedProfile) {
if (Date.now() > this._cachedAt + this.PROFILE_FRESHNESS_THRESHOLD) {
// Note that _fetchAndCacheProfile isn't returned, so continues
// in the background.
this._fetchAndCacheProfile().catch(err => {
log.error("Background refresh of profile failed", err);
--- a/services/fxaccounts/FxAccountsProfileClient.jsm
+++ b/services/fxaccounts/FxAccountsProfileClient.jsm
@@ -123,26 +123,26 @@ this.FxAccountsProfileClient.prototype =
* @param {String} method
* Type of request, i.e "GET".
* @param {String} token
* @return Promise
* Resolves: {Object} Successful response from the Profile server.
* Rejects: {FxAccountsProfileClientError} Profile client error.
* @private
*/
- _rawRequest: function(path, method, token) {
+ _rawRequest(path, method, token) {
return new Promise((resolve, reject) => {
let profileDataUrl = this.serverURL + path;
let request = new this._Request(profileDataUrl);
method = method.toUpperCase();
request.setHeader("Authorization", "Bearer " + token);
request.setHeader("Accept", "application/json");
- request.onComplete = function (error) {
+ request.onComplete = function(error) {
if (error) {
return reject(new FxAccountsProfileClientError({
error: ERROR_NETWORK,
errno: ERRNO_NETWORK,
message: error.toString(),
}));
}
@@ -187,29 +187,29 @@ this.FxAccountsProfileClient.prototype =
/**
* Retrieve user's profile from the server
*
* @return Promise
* Resolves: {Object} Successful response from the '/profile' endpoint.
* Rejects: {FxAccountsProfileClientError} profile client error.
*/
- fetchProfile: function () {
+ fetchProfile() {
log.debug("FxAccountsProfileClient: Requested profile");
return this._createRequest("/profile", "GET");
},
/**
* Retrieve user's profile from the server
*
* @return Promise
* Resolves: {Object} Successful response from the '/avatar' endpoint.
* Rejects: {FxAccountsProfileClientError} profile client error.
*/
- fetchProfileImage: function () {
+ fetchProfileImage() {
log.debug("FxAccountsProfileClient: Requested avatar");
return this._createRequest("/avatar", "GET");
}
};
/**
* Normalized profile client errors
* @param {Object} [details]
--- a/services/fxaccounts/FxAccountsPush.js
+++ b/services/fxaccounts/FxAccountsPush.js
@@ -235,9 +235,9 @@ FxAccountsPushService.prototype = {
},
};
// Service registration below registers with FxAccountsComponents.manifest
const components = [FxAccountsPushService];
this.NSGetFactory = XPCOMUtils.generateNSGetFactory(components);
// The following registration below helps with testing this service.
-this.EXPORTED_SYMBOLS=["FxAccountsPushService"];
+this.EXPORTED_SYMBOLS = ["FxAccountsPushService"];
--- a/services/fxaccounts/FxAccountsStorage.jsm
+++ b/services/fxaccounts/FxAccountsStorage.jsm
@@ -269,17 +269,17 @@ this.FxAccountsStorageManager.prototype
Note: _readPlainStorage is only called during initialize, so isn't
protected via _queueStorageOperation() nor _promiseInitialized.
*/
_readPlainStorage: Task.async(function* () {
let got;
try {
got = yield this.plainStorage.get();
- } catch(err) {
+ } catch (err) {
// File hasn't been created yet. That will be done
// when write is called.
if (!(err instanceof OS.File.Error) || !err.becauseNoSuchFile) {
log.error("Failed to read plain storage", err);
}
// either way, we return null.
got = null;
}
@@ -439,35 +439,35 @@ this.FxAccountsStorageManager.prototype
* filename: of the file to write to
* baseDir: directory where the file resides
* }
* @return instance
*/
function JSONStorage(options) {
this.baseDir = options.baseDir;
this.path = OS.Path.join(options.baseDir, options.filename);
-};
+}
JSONStorage.prototype = {
- set: function(contents) {
+ set(contents) {
log.trace("starting write of json user data", contents ? Object.keys(contents.accountData) : "null");
let start = Date.now();
return OS.File.makeDir(this.baseDir, {ignoreExisting: true})
.then(CommonUtils.writeJSON.bind(null, contents, this.path))
.then(result => {
- log.trace("finished write of json user data - took", Date.now()-start);
+ log.trace("finished write of json user data - took", Date.now() - start);
return result;
});
},
- get: function() {
+ get() {
log.trace("starting fetch of json user data");
let start = Date.now();
return CommonUtils.readJSON(this.path).then(result => {
- log.trace("finished fetch of json user data - took", Date.now()-start);
+ log.trace("finished fetch of json user data - took", Date.now() - start);
return result;
});
},
};
function StorageLockedError() {
}
/**
--- a/services/fxaccounts/FxAccountsWebChannel.jsm
+++ b/services/fxaccounts/FxAccountsWebChannel.jsm
@@ -152,17 +152,17 @@ this.FxAccountsWebChannel.prototype = {
case COMMAND_DELETE:
this._helpers.logout(data.uid).catch(error =>
this._sendError(error, message, sendingContext));
break;
case COMMAND_CAN_LINK_ACCOUNT:
let canLinkAccount = this._helpers.shouldAllowRelink(data.email);
let response = {
- command: command,
+ command,
messageId: message.messageId,
data: { ok: canLinkAccount }
};
log.debug("FxAccountsWebChannel response", response);
this._channel.send(response, sendingContext);
break;
case COMMAND_SYNC_PREFERENCES:
--- a/services/fxaccounts/tests/xpcshell/test_accounts.js
+++ b/services/fxaccounts/tests/xpcshell/test_accounts.js
@@ -88,31 +88,31 @@ MockStorageManager.prototype = {
function MockFxAccountsClient() {
this._email = "nobody@example.com";
this._verified = false;
this._deletedOnServer = false; // for testing accountStatus
// mock calls up to the auth server to determine whether the
// user account has been verified
- this.recoveryEmailStatus = function (sessionToken) {
+ this.recoveryEmailStatus = function(sessionToken) {
// simulate a call to /recovery_email/status
return Promise.resolve({
email: this._email,
verified: this._verified
});
};
this.accountStatus = function(uid) {
let deferred = Promise.defer();
deferred.resolve(!!uid && (!this._deletedOnServer));
return deferred.promise;
};
- this.accountKeys = function (keyFetchToken) {
+ this.accountKeys = function(keyFetchToken) {
let deferred = Promise.defer();
do_timeout(50, () => {
let response = {
kA: expandBytes("11"),
wrapKB: expandBytes("22")
};
deferred.resolve(response);
@@ -144,26 +144,26 @@ MockFxAccountsClient.prototype = {
*/
function MockFxAccounts() {
return new FxAccounts({
VERIFICATION_POLL_TIMEOUT_INITIAL: 100, // 100ms
_getCertificateSigned_calls: [],
_d_signCertificate: Promise.defer(),
_now_is: new Date(),
- now: function () {
+ now() {
return this._now_is;
},
newAccountState(credentials) {
// we use a real accountState but mocked storage.
let storage = new MockStorageManager();
storage.initialize(credentials);
return new AccountState(storage);
},
- getCertificateSigned: function (sessionToken, serializedPublicKey) {
+ getCertificateSigned(sessionToken, serializedPublicKey) {
_("mock getCertificateSigned\n");
this._getCertificateSigned_calls.push([sessionToken, serializedPublicKey]);
return this._d_signCertificate.promise;
},
_registerOrUpdateDevice() {
return Promise.resolve();
},
fxAccountsClient: new MockFxAccountsClient()
@@ -329,17 +329,17 @@ add_task(function* test_getCertificateOf
do_throw("Unexpected success");
},
err => {
Services.io.offline = offline;
// ... so we have to check the error string.
do_check_eq(err, "Error: OFFLINE");
}
);
- yield fxa.signOut(/*localOnly = */true);
+ yield fxa.signOut(/* localOnly = */true);
});
add_task(function* test_getCertificateCached() {
_("getCertificateCached()");
let fxa = MakeFxAccounts();
let credentials = {
email: "foo@example.com",
uid: "1234@lcip.org",
@@ -356,17 +356,17 @@ add_task(function* test_getCertificateCa
},
};
yield fxa.setSignedInUser(credentials);
let {keyPair, certificate} = yield fxa.internal.getKeypairAndCertificate(fxa.internal.currentAccountState);
// should have the same keypair and cert.
do_check_eq(keyPair, credentials.keyPair.rawKeyPair);
do_check_eq(certificate, credentials.cert.rawCert);
- yield fxa.signOut(/*localOnly = */true);
+ yield fxa.signOut(/* localOnly = */true);
});
add_task(function* test_getCertificateExpiredCert() {
_("getCertificateExpiredCert()");
let fxa = MakeFxAccounts({
getCertificateSigned() {
return "new cert";
}
@@ -387,17 +387,17 @@ add_task(function* test_getCertificateEx
rawCert: "expired-cert",
},
};
yield fxa.setSignedInUser(credentials);
let {keyPair, certificate} = yield fxa.internal.getKeypairAndCertificate(fxa.internal.currentAccountState);
// should have the same keypair but a new cert.
do_check_eq(keyPair, credentials.keyPair.rawKeyPair);
do_check_neq(certificate, credentials.cert.rawCert);
- yield fxa.signOut(/*localOnly = */true);
+ yield fxa.signOut(/* localOnly = */true);
});
add_task(function* test_getCertificateExpiredKeypair() {
_("getCertificateExpiredKeypair()");
let fxa = MakeFxAccounts({
getCertificateSigned() {
return "new cert";
},
@@ -420,17 +420,17 @@ add_task(function* test_getCertificateEx
};
yield fxa.setSignedInUser(credentials);
let {keyPair, certificate} = yield fxa.internal.getKeypairAndCertificate(fxa.internal.currentAccountState);
// even though the cert was valid, the fact the keypair was not means we
// should have fetched both.
do_check_neq(keyPair, credentials.keyPair.rawKeyPair);
do_check_neq(certificate, credentials.cert.rawCert);
- yield fxa.signOut(/*localOnly = */true);
+ yield fxa.signOut(/* localOnly = */true);
});
// Sanity-check that our mocked client is working correctly
add_test(function test_client_mock() {
let fxa = new MockFxAccounts();
let client = fxa.internal.fxAccountsClient;
do_check_eq(client._verified, false);
do_check_eq(typeof client.signIn, "function");
@@ -829,17 +829,17 @@ add_task(function* test_getAssertion() {
_("----- DONE ----\n");
});
add_task(function* test_resend_email_not_signed_in() {
let fxa = new MockFxAccounts();
try {
yield fxa.resendVerificationEmail();
- } catch(err) {
+ } catch (err) {
do_check_eq(err.message,
"Cannot resend verification email; no signed-in user");
return;
}
do_throw("Should not be able to resend email when nobody is signed in");
});
add_test(function test_accountStatus() {
@@ -959,21 +959,21 @@ add_task(function* test_sign_out_with_de
do_check_true(user);
Object.keys(credentials).forEach(key => do_check_eq(credentials[key], user[key]));
const spy = {
signOut: { count: 0 },
signOutAndDeviceDestroy: { count: 0, args: [] }
};
const client = fxa.internal.fxAccountsClient;
- client.signOut = function () {
+ client.signOut = function() {
spy.signOut.count += 1;
return Promise.resolve();
};
- client.signOutAndDestroyDevice = function () {
+ client.signOutAndDestroyDevice = function() {
spy.signOutAndDeviceDestroy.count += 1;
spy.signOutAndDeviceDestroy.args.push(arguments);
return Promise.resolve();
};
const promise = new Promise(resolve => {
makeObserver(ONLOGOUT_NOTIFICATION, () => {
log.debug("test_sign_out_with_device observed onlogout");
@@ -1006,22 +1006,22 @@ add_task(function* test_sign_out_without
const user = yield fxa.internal.getUserAccountData();
const spy = {
signOut: { count: 0, args: [] },
signOutAndDeviceDestroy: { count: 0 }
};
const client = fxa.internal.fxAccountsClient;
- client.signOut = function () {
+ client.signOut = function() {
spy.signOut.count += 1;
spy.signOut.args.push(arguments);
return Promise.resolve();
};
- client.signOutAndDestroyDevice = function () {
+ client.signOutAndDestroyDevice = function() {
spy.signOutAndDeviceDestroy.count += 1;
return Promise.resolve();
};
const promise = new Promise(resolve => {
makeObserver(ONLOGOUT_NOTIFICATION, () => {
log.debug("test_sign_out_without_device observed onlogout");
// user should be undefined after sign out
@@ -1074,24 +1074,24 @@ add_test(function test_getOAuthToken() {
fxa.internal._d_signCertificate.resolve("cert1");
// create a mock oauth client
let client = new FxAccountsOAuthGrantClient({
serverURL: "http://example.com/v1",
client_id: "abc123"
});
- client.getTokenFromAssertion = function () {
+ client.getTokenFromAssertion = function() {
getTokenFromAssertionCalled = true;
return Promise.resolve({ access_token: "token" });
};
fxa.setSignedInUser(alice).then(
() => {
- fxa.getOAuthToken({ scope: "profile", client: client }).then(
+ fxa.getOAuthToken({ scope: "profile", client }).then(
(result) => {
do_check_true(getTokenFromAssertionCalled);
do_check_eq(result, "token");
run_next_test();
}
)
}
);
@@ -1106,25 +1106,25 @@ add_test(function test_getOAuthTokenScop
fxa.internal._d_signCertificate.resolve("cert1");
// create a mock oauth client
let client = new FxAccountsOAuthGrantClient({
serverURL: "http://example.com/v1",
client_id: "abc123"
});
- client.getTokenFromAssertion = function (assertion, scopeString) {
+ client.getTokenFromAssertion = function(assertion, scopeString) {
equal(scopeString, "foo bar");
getTokenFromAssertionCalled = true;
return Promise.resolve({ access_token: "token" });
};
fxa.setSignedInUser(alice).then(
() => {
- fxa.getOAuthToken({ scope: ["foo", "bar"], client: client }).then(
+ fxa.getOAuthToken({ scope: ["foo", "bar"], client }).then(
(result) => {
do_check_true(getTokenFromAssertionCalled);
do_check_eq(result, "token");
run_next_test();
}
)
}
);
@@ -1139,32 +1139,32 @@ add_task(function* test_getOAuthTokenCac
fxa.internal._d_signCertificate.resolve("cert1");
// create a mock oauth client
let client = new FxAccountsOAuthGrantClient({
serverURL: "http://example.com/v1",
client_id: "abc123"
});
- client.getTokenFromAssertion = function () {
+ client.getTokenFromAssertion = function() {
numTokenFromAssertionCalls += 1;
return Promise.resolve({ access_token: "token" });
};
yield fxa.setSignedInUser(alice);
- let result = yield fxa.getOAuthToken({ scope: "profile", client: client, service: "test-service" });
+ let result = yield fxa.getOAuthToken({ scope: "profile", client, service: "test-service" });
do_check_eq(numTokenFromAssertionCalls, 1);
do_check_eq(result, "token");
// requesting it again should not re-fetch the token.
- result = yield fxa.getOAuthToken({ scope: "profile", client: client, service: "test-service" });
+ result = yield fxa.getOAuthToken({ scope: "profile", client, service: "test-service" });
do_check_eq(numTokenFromAssertionCalls, 1);
do_check_eq(result, "token");
// But requesting the same service and a different scope *will* get a new one.
- result = yield fxa.getOAuthToken({ scope: "something-else", client: client, service: "test-service" });
+ result = yield fxa.getOAuthToken({ scope: "something-else", client, service: "test-service" });
do_check_eq(numTokenFromAssertionCalls, 2);
do_check_eq(result, "token");
});
add_task(function* test_getOAuthTokenCachedScopeNormalization() {
let fxa = new MockFxAccounts();
let alice = getTestUser("alice");
alice.verified = true;
@@ -1172,36 +1172,36 @@ add_task(function* test_getOAuthTokenCac
fxa.internal._d_signCertificate.resolve("cert1");
// create a mock oauth client
let client = new FxAccountsOAuthGrantClient({
serverURL: "http://example.com/v1",
client_id: "abc123"
});
- client.getTokenFromAssertion = function () {
+ client.getTokenFromAssertion = function() {
numTokenFromAssertionCalls += 1;
return Promise.resolve({ access_token: "token" });
};
yield fxa.setSignedInUser(alice);
- let result = yield fxa.getOAuthToken({ scope: ["foo", "bar"], client: client, service: "test-service" });
+ let result = yield fxa.getOAuthToken({ scope: ["foo", "bar"], client, service: "test-service" });
do_check_eq(numTokenFromAssertionCalls, 1);
do_check_eq(result, "token");
// requesting it again with the scope array in a different order not re-fetch the token.
- result = yield fxa.getOAuthToken({ scope: ["bar", "foo"], client: client, service: "test-service" });
+ result = yield fxa.getOAuthToken({ scope: ["bar", "foo"], client, service: "test-service" });
do_check_eq(numTokenFromAssertionCalls, 1);
do_check_eq(result, "token");
// requesting it again with the scope array in different case not re-fetch the token.
- result = yield fxa.getOAuthToken({ scope: ["Bar", "Foo"], client: client, service: "test-service" });
+ result = yield fxa.getOAuthToken({ scope: ["Bar", "Foo"], client, service: "test-service" });
do_check_eq(numTokenFromAssertionCalls, 1);
do_check_eq(result, "token");
// But requesting with a new entry in the array does fetch one.
- result = yield fxa.getOAuthToken({ scope: ["foo", "bar", "etc"], client: client, service: "test-service" });
+ result = yield fxa.getOAuthToken({ scope: ["foo", "bar", "etc"], client, service: "test-service" });
do_check_eq(numTokenFromAssertionCalls, 2);
do_check_eq(result, "token");
});
Services.prefs.setCharPref("identity.fxaccounts.remote.oauth.uri", "https://example.com/v1");
add_test(function test_getOAuthToken_invalid_param() {
let fxa = new MockFxAccounts();
@@ -1234,17 +1234,17 @@ add_test(function test_getOAuthToken_mis
Services.prefs.setCharPref("identity.fxaccounts.remote.oauth.uri", "https://example.com/v1");
fxa.signOut().then(run_next_test);
});
});
add_test(function test_getOAuthToken_no_account() {
let fxa = new MockFxAccounts();
- fxa.internal.currentAccountState.getUserAccountData = function () {
+ fxa.internal.currentAccountState.getUserAccountData = function() {
return Promise.resolve(null);
};
fxa.getOAuthToken({ scope: "profile" })
.then(null, err => {
do_check_eq(err.message, "NO_ACCOUNT");
fxa.signOut().then(run_next_test);
});
@@ -1270,25 +1270,25 @@ add_test(function test_getOAuthToken_net
fxa.internal._d_signCertificate.resolve("cert1");
// create a mock oauth client
let client = new FxAccountsOAuthGrantClient({
serverURL: "http://example.com/v1",
client_id: "abc123"
});
- client.getTokenFromAssertion = function () {
+ client.getTokenFromAssertion = function() {
return Promise.reject(new FxAccountsOAuthGrantClientError({
error: ERROR_NETWORK,
errno: ERRNO_NETWORK
}));
};
fxa.setSignedInUser(alice).then(() => {
- fxa.getOAuthToken({ scope: "profile", client: client })
+ fxa.getOAuthToken({ scope: "profile", client })
.then(null, err => {
do_check_eq(err.message, "NETWORK_ERROR");
do_check_eq(err.details.errno, ERRNO_NETWORK);
run_next_test();
});
});
});
@@ -1299,25 +1299,25 @@ add_test(function test_getOAuthToken_aut
fxa.internal._d_signCertificate.resolve("cert1");
// create a mock oauth client
let client = new FxAccountsOAuthGrantClient({
serverURL: "http://example.com/v1",
client_id: "abc123"
});
- client.getTokenFromAssertion = function () {
+ client.getTokenFromAssertion = function() {
return Promise.reject(new FxAccountsOAuthGrantClientError({
error: ERROR_INVALID_FXA_ASSERTION,
errno: ERRNO_INVALID_FXA_ASSERTION
}));
};
fxa.setSignedInUser(alice).then(() => {
- fxa.getOAuthToken({ scope: "profile", client: client })
+ fxa.getOAuthToken({ scope: "profile", client })
.then(null, err => {
do_check_eq(err.message, "AUTH_ERROR");
do_check_eq(err.details.errno, ERRNO_INVALID_FXA_ASSERTION);
run_next_test();
});
});
});
@@ -1328,38 +1328,38 @@ add_test(function test_getOAuthToken_unk
fxa.internal._d_signCertificate.resolve("cert1");
// create a mock oauth client
let client = new FxAccountsOAuthGrantClient({
serverURL: "http://example.com/v1",
client_id: "abc123"
});
- client.getTokenFromAssertion = function () {
+ client.getTokenFromAssertion = function() {
return Promise.reject("boom");
};
fxa.setSignedInUser(alice).then(() => {
- fxa.getOAuthToken({ scope: "profile", client: client })
+ fxa.getOAuthToken({ scope: "profile", client })
.then(null, err => {
do_check_eq(err.message, "UNKNOWN_ERROR");
run_next_test();
});
});
});
add_test(function test_getSignedInUserProfile() {
let alice = getTestUser("alice");
alice.verified = true;
let mockProfile = {
- getProfile: function () {
+ getProfile() {
return Promise.resolve({ avatar: "image" });
},
- tearDown: function() {},
+ tearDown() {},
};
let fxa = new FxAccounts({
_signOutServer() { return Promise.resolve(); },
_registerOrUpdateDevice() { return Promise.resolve(); }
});
fxa.setSignedInUser(alice).then(() => {
fxa.internal._profile = mockProfile;
@@ -1372,27 +1372,27 @@ add_test(function test_getSignedInUserPr
});
});
add_test(function test_getSignedInUserProfile_error_uses_account_data() {
let fxa = new MockFxAccounts();
let alice = getTestUser("alice");
alice.verified = true;
- fxa.internal.getSignedInUser = function () {
+ fxa.internal.getSignedInUser = function() {
return Promise.resolve({ email: "foo@bar.com" });
};
let teardownCalled = false;
fxa.setSignedInUser(alice).then(() => {
fxa.internal._profile = {
- getProfile: function () {
+ getProfile() {
return Promise.reject("boom");
},
- tearDown: function() {
+ tearDown() {
teardownCalled = true;
}
};
fxa.getSignedInUserProfile()
.catch(error => {
do_check_eq(error.message, "UNKNOWN_ERROR");
fxa.signOut().then(() => {
@@ -1415,17 +1415,17 @@ add_test(function test_getSignedInUserPr
});
});
});
add_test(function test_getSignedInUserProfile_no_account_data() {
let fxa = new MockFxAccounts();
- fxa.internal.getSignedInUser = function () {
+ fxa.internal.getSignedInUser = function() {
return Promise.resolve(null);
};
fxa.getSignedInUserProfile()
.catch(error => {
do_check_eq(error.message, "NO_ACCOUNT");
fxa.signOut().then(run_next_test);
});
@@ -1464,21 +1464,21 @@ add_task(function* test_checkVerificatio
* Utility functions follow.
*/
function expandHex(two_hex) {
// Return a 64-character hex string, encoding 32 identical bytes.
let eight_hex = two_hex + two_hex + two_hex + two_hex;
let thirtytwo_hex = eight_hex + eight_hex + eight_hex + eight_hex;
return thirtytwo_hex + thirtytwo_hex;
-};
+}
function expandBytes(two_hex) {
return CommonUtils.hexToBytes(expandHex(two_hex));
-};
+}
function getTestUser(name) {
return {
email: name + "@example.com",
uid: "1ad7f502-4cc7-4ec1-a209-071fd2fae348",
deviceId: name + "'s device id",
sessionToken: name + "'s session token",
keyFetchToken: name + "'s keyfetch token",
@@ -1488,17 +1488,17 @@ function getTestUser(name) {
}
function makeObserver(aObserveTopic, aObserveFunc) {
let observer = {
// nsISupports provides type management in C++
// nsIObserver is to be an observer
QueryInterface: XPCOMUtils.generateQI([Ci.nsISupports, Ci.nsIObserver]),
- observe: function (aSubject, aTopic, aData) {
+ observe(aSubject, aTopic, aData) {
log.debug("observed " + aTopic + " " + aData);
if (aTopic == aObserveTopic) {
removeMe();
aObserveFunc(aSubject, aTopic, aData);
}
}
};
@@ -1506,18 +1506,17 @@ function makeObserver(aObserveTopic, aOb
log.debug("removing observer for " + aObserveTopic);
Services.obs.removeObserver(observer, aObserveTopic);
}
Services.obs.addObserver(observer, aObserveTopic, false);
return removeMe;
}
-function do_check_throws(func, result, stack)
-{
+function do_check_throws(func, result, stack) {
if (!stack)
stack = Components.stack.caller;
try {
func();
} catch (ex) {
if (ex.name == result) {
return;
--- a/services/fxaccounts/tests/xpcshell/test_accounts_device_registration.js
+++ b/services/fxaccounts/tests/xpcshell/test_accounts_device_registration.js
@@ -64,17 +64,17 @@ MockStorageManager.prototype = {
function MockFxAccountsClient(device) {
this._email = "nobody@example.com";
this._verified = false;
this._deletedOnServer = false; // for testing accountStatus
// mock calls up to the auth server to determine whether the
// user account has been verified
- this.recoveryEmailStatus = function (sessionToken) {
+ this.recoveryEmailStatus = function(sessionToken) {
// simulate a call to /recovery_email/status
return Promise.resolve({
email: this._email,
verified: this._verified
});
};
this.accountStatus = function(uid) {
@@ -105,17 +105,17 @@ function MockFxAccounts(device = {}) {
return device.name || "mock device name";
},
fxAccountsClient: new MockFxAccountsClient(device),
fxaPushService: {
registerPushEndpoint() {
return new Promise((resolve) => {
resolve({
endpoint: "http://mochi.test:8888",
- getKey: function(type) {
+ getKey(type) {
return ChromeUtils.base64URLDecode(
type === "auth" ? BOGUS_AUTHKEY : BOGUS_PUBLICKEY,
{ padding: "ignore" });
}
});
});
},
},
@@ -133,32 +133,32 @@ add_task(function* test_updateDeviceRegi
yield fxa.internal.setSignedInUser(credentials);
const spy = {
registerDevice: { count: 0, args: [] },
updateDevice: { count: 0, args: [] },
getDeviceList: { count: 0, args: [] }
};
const client = fxa.internal.fxAccountsClient;
- client.registerDevice = function () {
+ client.registerDevice = function() {
spy.registerDevice.count += 1;
spy.registerDevice.args.push(arguments);
return Promise.resolve({
id: "newly-generated device id",
createdAt: Date.now(),
name: deviceName,
type: deviceType
});
};
- client.updateDevice = function () {
+ client.updateDevice = function() {
spy.updateDevice.count += 1;
spy.updateDevice.args.push(arguments);
return Promise.resolve({});
};
- client.getDeviceList = function () {
+ client.getDeviceList = function() {
spy.getDeviceList.count += 1;
spy.getDeviceList.args.push(arguments);
return Promise.resolve([]);
};
const result = yield fxa.updateDeviceRegistration();
do_check_eq(result, "newly-generated device id");
@@ -189,30 +189,30 @@ add_task(function* test_updateDeviceRegi
yield fxa.internal.setSignedInUser(credentials);
const spy = {
registerDevice: { count: 0, args: [] },
updateDevice: { count: 0, args: [] },
getDeviceList: { count: 0, args: [] }
};
const client = fxa.internal.fxAccountsClient;
- client.registerDevice = function () {
+ client.registerDevice = function() {
spy.registerDevice.count += 1;
spy.registerDevice.args.push(arguments);
return Promise.resolve({});
};
- client.updateDevice = function () {
+ client.updateDevice = function() {
spy.updateDevice.count += 1;
spy.updateDevice.args.push(arguments);
return Promise.resolve({
id: credentials.deviceId,
name: deviceName
});
};
- client.getDeviceList = function () {
+ client.getDeviceList = function() {
spy.getDeviceList.count += 1;
spy.getDeviceList.args.push(arguments);
return Promise.resolve([]);
};
const result = yield fxa.updateDeviceRegistration();
do_check_eq(result, credentials.deviceId);
do_check_eq(spy.registerDevice.count, 0);
@@ -242,35 +242,35 @@ add_task(function* test_updateDeviceRegi
yield fxa.internal.setSignedInUser(credentials);
const spy = {
registerDevice: { count: 0, args: [] },
updateDevice: { count: 0, args: [] },
getDeviceList: { count: 0, args: [] }
};
const client = fxa.internal.fxAccountsClient;
- client.registerDevice = function () {
+ client.registerDevice = function() {
spy.registerDevice.count += 1;
spy.registerDevice.args.push(arguments);
return Promise.resolve({
id: "a different newly-generated device id",
createdAt: Date.now(),
name: deviceName,
type: deviceType
});
};
- client.updateDevice = function () {
+ client.updateDevice = function() {
spy.updateDevice.count += 1;
spy.updateDevice.args.push(arguments);
return Promise.reject({
code: 400,
errno: ERRNO_UNKNOWN_DEVICE
});
};
- client.getDeviceList = function () {
+ client.getDeviceList = function() {
spy.getDeviceList.count += 1;
spy.getDeviceList.args.push(arguments);
return Promise.resolve([]);
};
const result = yield fxa.updateDeviceRegistration();
do_check_null(result);
@@ -302,37 +302,37 @@ add_task(function* test_updateDeviceRegi
yield fxa.internal.setSignedInUser(credentials);
const spy = {
registerDevice: { count: 0, args: [] },
updateDevice: { count: 0, args: [], times: [] },
getDeviceList: { count: 0, args: [] }
};
const client = fxa.internal.fxAccountsClient;
- client.registerDevice = function () {
+ client.registerDevice = function() {
spy.registerDevice.count += 1;
spy.registerDevice.args.push(arguments);
return Promise.resolve({});
};
- client.updateDevice = function () {
+ client.updateDevice = function() {
spy.updateDevice.count += 1;
spy.updateDevice.args.push(arguments);
spy.updateDevice.time = Date.now();
if (spy.updateDevice.count === 1) {
return Promise.reject({
code: 400,
errno: ERRNO_DEVICE_SESSION_CONFLICT
});
}
return Promise.resolve({
id: credentials.deviceId,
name: deviceName
});
};
- client.getDeviceList = function () {
+ client.getDeviceList = function() {
spy.getDeviceList.count += 1;
spy.getDeviceList.args.push(arguments);
spy.getDeviceList.time = Date.now();
return Promise.resolve([
{ id: "ignore", name: "ignore", type: "ignore", isCurrentDevice: false },
{ id: credentials.deviceId, name: deviceName, type: deviceType, isCurrentDevice: true }
]);
};
@@ -371,30 +371,30 @@ add_task(function* test_updateDeviceRegi
yield fxa.internal.setSignedInUser(credentials);
const spy = {
registerDevice: { count: 0, args: [] },
updateDevice: { count: 0, args: [] },
getDeviceList: { count: 0, args: [] }
};
const client = fxa.internal.fxAccountsClient;
- client.registerDevice = function () {
+ client.registerDevice = function() {
spy.registerDevice.count += 1;
spy.registerDevice.args.push(arguments);
return Promise.reject({
code: 400,
errno: ERRNO_TOO_MANY_CLIENT_REQUESTS
});
};
- client.updateDevice = function () {
+ client.updateDevice = function() {
spy.updateDevice.count += 1;
spy.updateDevice.args.push(arguments);
return Promise.resolve({});
};
- client.getDeviceList = function () {
+ client.getDeviceList = function() {
spy.getDeviceList.count += 1;
spy.getDeviceList.args.push(arguments);
return Promise.resolve([]);
};
const result = yield fxa.updateDeviceRegistration();
do_check_null(result);
@@ -415,17 +415,17 @@ add_task(function* test_getDeviceId_with
delete credentials.deviceId;
const fxa = new MockFxAccounts();
yield fxa.internal.setSignedInUser(credentials);
const spy = { count: 0, args: [] };
fxa.internal.currentAccountState.getUserAccountData =
() => Promise.resolve({ email: credentials.email,
deviceRegistrationVersion: DEVICE_REGISTRATION_VERSION });
- fxa.internal._registerOrUpdateDevice = function () {
+ fxa.internal._registerOrUpdateDevice = function() {
spy.count += 1;
spy.args.push(arguments);
return Promise.resolve("bar");
};
const result = yield fxa.internal.getDeviceId();
do_check_eq(spy.count, 1);
@@ -439,17 +439,17 @@ add_task(function* test_getDeviceId_with
const credentials = getTestUser("foo");
credentials.verified = true;
const fxa = new MockFxAccounts();
yield fxa.internal.setSignedInUser(credentials);
const spy = { count: 0, args: [] };
fxa.internal.currentAccountState.getUserAccountData =
() => Promise.resolve({ deviceId: credentials.deviceId, deviceRegistrationVersion: 0 });
- fxa.internal._registerOrUpdateDevice = function () {
+ fxa.internal._registerOrUpdateDevice = function() {
spy.count += 1;
spy.args.push(arguments);
return Promise.resolve("wibble");
};
const result = yield fxa.internal.getDeviceId();
do_check_eq(spy.count, 1);
@@ -462,17 +462,17 @@ add_task(function* test_getDeviceId_with
const credentials = getTestUser("foo");
credentials.verified = true;
const fxa = new MockFxAccounts();
yield fxa.internal.setSignedInUser(credentials);
const spy = { count: 0 };
fxa.internal.currentAccountState.getUserAccountData =
() => Promise.resolve({ deviceId: credentials.deviceId, deviceRegistrationVersion: DEVICE_REGISTRATION_VERSION });
- fxa.internal._registerOrUpdateDevice = function () {
+ fxa.internal._registerOrUpdateDevice = function() {
spy.count += 1;
return Promise.resolve("bar");
};
const result = yield fxa.internal.getDeviceId();
do_check_eq(spy.count, 0);
do_check_eq(result, "foo's device id");
@@ -482,17 +482,17 @@ add_task(function* test_getDeviceId_with
const credentials = getTestUser("foo");
credentials.verified = true;
const fxa = new MockFxAccounts();
yield fxa.internal.setSignedInUser(credentials);
const spy = { count: 0, args: [] };
fxa.internal.currentAccountState.getUserAccountData =
() => Promise.resolve({ deviceId: credentials.deviceId });
- fxa.internal._registerOrUpdateDevice = function () {
+ fxa.internal._registerOrUpdateDevice = function() {
spy.count += 1;
spy.args.push(arguments);
return Promise.resolve("wibble");
};
const result = yield fxa.internal.getDeviceId();
do_check_eq(spy.count, 1);
@@ -501,21 +501,21 @@ add_task(function* test_getDeviceId_with
do_check_eq(result, "wibble");
});
function expandHex(two_hex) {
// Return a 64-character hex string, encoding 32 identical bytes.
let eight_hex = two_hex + two_hex + two_hex + two_hex;
let thirtytwo_hex = eight_hex + eight_hex + eight_hex + eight_hex;
return thirtytwo_hex + thirtytwo_hex;
-};
+}
function expandBytes(two_hex) {
return CommonUtils.hexToBytes(expandHex(two_hex));
-};
+}
function getTestUser(name) {
return {
email: name + "@example.com",
uid: "1ad7f502-4cc7-4ec1-a209-071fd2fae348",
deviceId: name + "'s device id",
sessionToken: name + "'s session token",
keyFetchToken: name + "'s keyfetch token",
--- a/services/fxaccounts/tests/xpcshell/test_client.js
+++ b/services/fxaccounts/tests/xpcshell/test_client.js
@@ -12,30 +12,30 @@ Cu.import("resource://services-crypto/ut
const FAKE_SESSION_TOKEN = "a0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebf";
function run_test() {
run_next_test();
}
// https://wiki.mozilla.org/Identity/AttachedServices/KeyServerProtocol#.2Faccount.2Fkeys
var ACCOUNT_KEYS = {
- keyFetch: h("8081828384858687 88898a8b8c8d8e8f"+
+ keyFetch: h("8081828384858687 88898a8b8c8d8e8f" +
"9091929394959697 98999a9b9c9d9e9f"),
- response: h("ee5c58845c7c9412 b11bbd20920c2fdd"+
- "d83c33c9cd2c2de2 d66b222613364636"+
- "c2c0f8cfbb7c6304 72c0bd88451342c6"+
- "c05b14ce342c5ad4 6ad89e84464c993c"+
- "3927d30230157d08 17a077eef4b20d97"+
+ response: h("ee5c58845c7c9412 b11bbd20920c2fdd" +
+ "d83c33c9cd2c2de2 d66b222613364636" +
+ "c2c0f8cfbb7c6304 72c0bd88451342c6" +
+ "c05b14ce342c5ad4 6ad89e84464c993c" +
+ "3927d30230157d08 17a077eef4b20d97" +
"6f7a97363faf3f06 4c003ada7d01aa70"),
- kA: h("2021222324252627 28292a2b2c2d2e2f"+
+ kA: h("2021222324252627 28292a2b2c2d2e2f" +
"3031323334353637 38393a3b3c3d3e3f"),
- wrapKB: h("4041424344454647 48494a4b4c4d4e4f"+
+ wrapKB: h("4041424344454647 48494a4b4c4d4e4f" +
"5051525354555657 58595a5b5c5d5e5f"),
};
function deferredStop(server) {
let deferred = Promise.defer();
server.stop(deferred.resolve);
return deferred.promise;
}
@@ -233,17 +233,17 @@ add_task(function* test_signUp() {
do_check_eq("keyFetchToken", result.keyFetchToken);
do_check_eq(result.unwrapBKey,
"f589225b609e56075d76eb74f771ff9ab18a4dc0e901e131ba8f984c7fb0ca8c");
// Try to create an existing account. Triggers error path.
try {
result = yield client.signUp(unicodeUsername, unicodePassword);
do_throw("Expected to catch an exception");
- } catch(expectedError) {
+ } catch (expectedError) {
do_check_eq(101, expectedError.errno);
}
yield deferredStop(server);
});
add_task(function* test_signIn() {
let sessionMessage_noKey = JSON.stringify({
@@ -274,39 +274,36 @@ add_task(function* test_signIn() {
let jsonBody = JSON.parse(body);
if (jsonBody.email == unicodeUsername) {
do_check_eq("", request._queryString);
do_check_eq(jsonBody.authPW, "08b9d111196b8408e8ed92439da49206c8ecfbf343df0ae1ecefcd1e0174a8b6");
response.setStatusLine(request.httpVersion, 200, "OK");
response.bodyOutputStream.write(sessionMessage_noKey,
sessionMessage_noKey.length);
- return;
- }
- else if (jsonBody.email == "you@example.com") {
+
+ } else if (jsonBody.email == "you@example.com") {
do_check_eq("keys=true", request._queryString);
do_check_eq(jsonBody.authPW, "93d20ec50304d496d0707ec20d7e8c89459b6396ec5dd5b9e92809c5e42856c7");
response.setStatusLine(request.httpVersion, 200, "OK");
response.bodyOutputStream.write(sessionMessage_withKey,
sessionMessage_withKey.length);
- return;
- }
- else if (jsonBody.email == "You@example.com") {
+
+ } else if (jsonBody.email == "You@example.com") {
// Error trying to sign in with a wrong capitalization
response.setStatusLine(request.httpVersion, 400, "Bad request");
response.bodyOutputStream.write(errorMessage_wrongCap,
errorMessage_wrongCap.length);
- return;
- }
- else {
+
+ } else {
// Error trying to sign in to nonexistent account
response.setStatusLine(request.httpVersion, 400, "Bad request");
response.bodyOutputStream.write(errorMessage_notExistent,
errorMessage_notExistent.length);
- return;
+
}
},
});
// Login without retrieving optional keys
let client = new FxAccountsClient(server.baseURI);
let result = yield client.signIn(unicodeUsername, 'bigsecret');
do_check_eq(FAKE_SESSION_TOKEN, result.sessionToken);
@@ -352,29 +349,29 @@ add_task(function* test_signOut() {
response.setStatusLine(request.httpVersion, 200, "OK");
response.bodyOutputStream.write(signoutMessage, signoutMessage.length);
return;
}
// Error trying to sign out of nonexistent account
response.setStatusLine(request.httpVersion, 400, "Bad request");
response.bodyOutputStream.write(errorMessage, errorMessage.length);
- return;
+
},
});
let client = new FxAccountsClient(server.baseURI);
let result = yield client.signOut("FakeSession");
do_check_eq(typeof result, "object");
// Trigger error path
try {
result = yield client.signOut("FakeSession");
do_throw("Expected to catch an exception");
- } catch(expectedError) {
+ } catch (expectedError) {
do_check_eq(102, expectedError.errno);
}
yield deferredStop(server);
});
add_task(function* test_recoveryEmailStatus() {
let emailStatus = JSON.stringify({verified: true});
@@ -391,46 +388,46 @@ add_task(function* test_recoveryEmailSta
response.setStatusLine(request.httpVersion, 200, "OK");
response.bodyOutputStream.write(emailStatus, emailStatus.length);
return;
}
// Second call gets an error trying to query a nonexistent account
response.setStatusLine(request.httpVersion, 400, "Bad request");
response.bodyOutputStream.write(errorMessage, errorMessage.length);
- return;
+
},
});
let client = new FxAccountsClient(server.baseURI);
let result = yield client.recoveryEmailStatus(FAKE_SESSION_TOKEN);
do_check_eq(result.verified, true);
// Trigger error path
try {
result = yield client.recoveryEmailStatus("some bogus session");
do_throw("Expected to catch an exception");
- } catch(expectedError) {
+ } catch (expectedError) {
do_check_eq(102, expectedError.errno);
}
yield deferredStop(server);
});
add_task(function* test_recoveryEmailStatusWithReason() {
let emailStatus = JSON.stringify({verified: true});
let server = httpd_setup({
"/recovery_email/status": function(request, response) {
do_check_true(request.hasHeader("Authorization"));
// if there is a query string then it will have a reason
do_check_eq("reason=push", request._queryString);
response.setStatusLine(request.httpVersion, 200, "OK");
response.bodyOutputStream.write(emailStatus, emailStatus.length);
- return;
+
},
});
let client = new FxAccountsClient(server.baseURI);
let result = yield client.recoveryEmailStatus(FAKE_SESSION_TOKEN, {
reason: "push",
});
do_check_eq(result.verified, true);
@@ -450,29 +447,29 @@ add_task(function* test_resendVerificati
response.setStatusLine(request.httpVersion, 200, "OK");
response.bodyOutputStream.write(emptyMessage, emptyMessage.length);
return;
}
// Second call gets an error trying to query a nonexistent account
response.setStatusLine(request.httpVersion, 400, "Bad request");
response.bodyOutputStream.write(errorMessage, errorMessage.length);
- return;
+
},
});
let client = new FxAccountsClient(server.baseURI);
let result = yield client.resendVerificationEmail(FAKE_SESSION_TOKEN);
do_check_eq(JSON.stringify(result), emptyMessage);
// Trigger error path
try {
result = yield client.resendVerificationEmail("some bogus session");
do_throw("Expected to catch an exception");
- } catch(expectedError) {
+ } catch (expectedError) {
do_check_eq(102, expectedError.errno);
}
yield deferredStop(server);
});
add_task(function* test_accountKeys() {
// Four calls to accountKeys(). The first one should work correctly, and we
@@ -484,17 +481,17 @@ add_task(function* test_accountKeys() {
let emptyMessage = "{}";
let attempt = 0;
let server = httpd_setup({
"/account/keys": function(request, response) {
do_check_true(request.hasHeader("Authorization"));
attempt += 1;
- switch(attempt) {
+ switch (attempt) {
case 1:
// First time succeeds
response.setStatusLine(request.httpVersion, 200, "OK");
response.bodyOutputStream.write(responseMessage, responseMessage.length);
break;
case 2:
// Second time, return no bundle to trigger client error
@@ -527,33 +524,33 @@ add_task(function* test_accountKeys() {
let result = yield client.accountKeys(ACCOUNT_KEYS.keyFetch);
do_check_eq(CommonUtils.hexToBytes(ACCOUNT_KEYS.kA), result.kA);
do_check_eq(CommonUtils.hexToBytes(ACCOUNT_KEYS.wrapKB), result.wrapKB);
// Second try, empty bundle should trigger error
try {
result = yield client.accountKeys(ACCOUNT_KEYS.keyFetch);
do_throw("Expected to catch an exception");
- } catch(expectedError) {
+ } catch (expectedError) {
do_check_eq(expectedError.message, "failed to retrieve keys");
}
// Third try, bad bundle results in MAC error
try {
result = yield client.accountKeys(ACCOUNT_KEYS.keyFetch);
do_throw("Expected to catch an exception");
- } catch(expectedError) {
+ } catch (expectedError) {
do_check_eq(expectedError.message, "error unbundling encryption keys");
}
// Fourth try, pretend account doesn't exist
try {
result = yield client.accountKeys(ACCOUNT_KEYS.keyFetch);
do_throw("Expected to catch an exception");
- } catch(expectedError) {
+ } catch (expectedError) {
do_check_eq(102, expectedError.errno);
}
yield deferredStop(server);
});
add_task(function* test_signCertificate() {
let certSignMessage = JSON.stringify({cert: {bar: "baz"}});
@@ -573,29 +570,29 @@ add_task(function* test_signCertificate(
response.setStatusLine(request.httpVersion, 200, "OK");
response.bodyOutputStream.write(certSignMessage, certSignMessage.length);
return;
}
// Second attempt, trigger error
response.setStatusLine(request.httpVersion, 400, "Bad request");
response.bodyOutputStream.write(errorMessage, errorMessage.length);
- return;
+
},
});
let client = new FxAccountsClient(server.baseURI);
let result = yield client.signCertificate(FAKE_SESSION_TOKEN, JSON.stringify({foo: "bar"}), 600);
do_check_eq("baz", result.bar);
// Account doesn't exist
try {
result = yield client.signCertificate("bogus", JSON.stringify({foo: "bar"}), 600);
do_throw("Expected to catch an exception");
- } catch(expectedError) {
+ } catch (expectedError) {
do_check_eq(102, expectedError.errno);
}
yield deferredStop(server);
});
add_task(function* test_accountExists() {
let sessionMessage = JSON.stringify({sessionToken: FAKE_SESSION_TOKEN});
@@ -646,17 +643,17 @@ add_task(function* test_accountExists()
do_check_true(result);
result = yield client.accountExists("i.dont.exist@example.com");
do_check_false(result);
try {
result = yield client.accountExists("i.break.things@example.com");
do_throw("Expected to catch an exception");
- } catch(unexpectedError) {
+ } catch (unexpectedError) {
do_check_eq(unexpectedError.code, 500);
}
yield deferredStop(server);
});
add_task(function* test_registerDevice() {
const DEVICE_ID = "device id";
@@ -697,17 +694,17 @@ add_task(function* test_registerDevice()
do_check_eq(typeof result.createdAt, 'number');
do_check_true(result.createdAt > 0);
do_check_eq(result.name, DEVICE_NAME);
do_check_eq(result.type, DEVICE_TYPE);
try {
yield client.registerDevice(FAKE_SESSION_TOKEN, ERROR_NAME, DEVICE_TYPE);
do_throw("Expected to catch an exception");
- } catch(unexpectedError) {
+ } catch (unexpectedError) {
do_check_eq(unexpectedError.code, 500);
}
yield deferredStop(server);
});
add_task(function* test_updateDevice() {
const DEVICE_ID = "some other id";
@@ -741,17 +738,17 @@ add_task(function* test_updateDevice() {
do_check_true(result);
do_check_eq(Object.keys(result).length, 2);
do_check_eq(result.id, DEVICE_ID);
do_check_eq(result.name, DEVICE_NAME);
try {
yield client.updateDevice(FAKE_SESSION_TOKEN, ERROR_ID, DEVICE_NAME);
do_throw("Expected to catch an exception");
- } catch(unexpectedError) {
+ } catch (unexpectedError) {
do_check_eq(unexpectedError.code, 500);
}
yield deferredStop(server);
});
add_task(function* test_signOutAndDestroyDevice() {
const DEVICE_ID = "device id";
@@ -780,17 +777,17 @@ add_task(function* test_signOutAndDestro
const result = yield client.signOutAndDestroyDevice(FAKE_SESSION_TOKEN, DEVICE_ID);
do_check_true(result);
do_check_eq(Object.keys(result).length, 0);
try {
yield client.signOutAndDestroyDevice(FAKE_SESSION_TOKEN, ERROR_ID);
do_throw("Expected to catch an exception");
- } catch(unexpectedError) {
+ } catch (unexpectedError) {
do_check_eq(unexpectedError.code, 500);
}
yield deferredStop(server);
});
add_task(function* test_getDeviceList() {
let canReturnDevices;
@@ -813,17 +810,17 @@ add_task(function* test_getDeviceList()
const result = yield client.getDeviceList(FAKE_SESSION_TOKEN);
do_check_true(Array.isArray(result));
do_check_eq(result.length, 0);
try {
canReturnDevices = false;
yield client.getDeviceList(FAKE_SESSION_TOKEN);
do_throw("Expected to catch an exception");
- } catch(unexpectedError) {
+ } catch (unexpectedError) {
do_check_eq(unexpectedError.code, 500);
}
yield deferredStop(server);
});
add_task(function* test_client_metrics() {
function writeResp(response, msg) {
--- a/services/fxaccounts/tests/xpcshell/test_oauth_grant_client.js
+++ b/services/fxaccounts/tests/xpcshell/test_oauth_grant_client.js
@@ -15,181 +15,181 @@ const CLIENT_OPTIONS = {
const STATUS_SUCCESS = 200;
/**
* Mock request responder
* @param {String} response
* Mocked raw response from the server
* @returns {Function}
*/
-var mockResponse = function (response) {
- return function () {
+var mockResponse = function(response) {
+ return function() {
return {
- setHeader: function () {},
- post: function () {
+ setHeader() {},
+ post() {
this.response = response;
this.onComplete();
}
};
};
};
/**
* Mock request error responder
* @param {Error} error
* Error object
* @returns {Function}
*/
-var mockResponseError = function (error) {
- return function () {
+var mockResponseError = function(error) {
+ return function() {
return {
- setHeader: function () {},
- post: function () {
+ setHeader() {},
+ post() {
this.onComplete(error);
}
};
};
};
-add_test(function missingParams () {
+add_test(function missingParams() {
let client = new FxAccountsOAuthGrantClient(CLIENT_OPTIONS);
try {
client.getTokenFromAssertion()
} catch (e) {
do_check_eq(e.message, "Missing 'assertion' parameter");
}
try {
client.getTokenFromAssertion("assertion")
} catch (e) {
do_check_eq(e.message, "Missing 'scope' parameter");
}
run_next_test();
});
-add_test(function successfulResponse () {
+add_test(function successfulResponse() {
let client = new FxAccountsOAuthGrantClient(CLIENT_OPTIONS);
let response = {
success: true,
status: STATUS_SUCCESS,
body: "{\"access_token\":\"http://example.com/image.jpeg\",\"id\":\"0d5c1a89b8c54580b8e3e8adadae864a\"}",
};
client._Request = new mockResponse(response);
client.getTokenFromAssertion("assertion", "scope")
.then(
- function (result) {
+ function(result) {
do_check_eq(result.access_token, "http://example.com/image.jpeg");
run_next_test();
}
);
});
-add_test(function successfulDestroy () {
+add_test(function successfulDestroy() {
let client = new FxAccountsOAuthGrantClient(CLIENT_OPTIONS);
let response = {
success: true,
status: STATUS_SUCCESS,
body: "{}",
};
client._Request = new mockResponse(response);
client.destroyToken("deadbeef").then(run_next_test);
});
-add_test(function parseErrorResponse () {
+add_test(function parseErrorResponse() {
let client = new FxAccountsOAuthGrantClient(CLIENT_OPTIONS);
let response = {
success: true,
status: STATUS_SUCCESS,
body: "unexpected",
};
client._Request = new mockResponse(response);
client.getTokenFromAssertion("assertion", "scope")
.then(
null,
- function (e) {
+ function(e) {
do_check_eq(e.name, "FxAccountsOAuthGrantClientError");
do_check_eq(e.code, STATUS_SUCCESS);
do_check_eq(e.errno, ERRNO_PARSE);
do_check_eq(e.error, ERROR_PARSE);
do_check_eq(e.message, "unexpected");
run_next_test();
}
);
});
-add_test(function serverErrorResponse () {
+add_test(function serverErrorResponse() {
let client = new FxAccountsOAuthGrantClient(CLIENT_OPTIONS);
let response = {
status: 400,
body: "{ \"code\": 400, \"errno\": 104, \"error\": \"Bad Request\", \"message\": \"Unauthorized\", \"reason\": \"Invalid fxa assertion\" }",
};
client._Request = new mockResponse(response);
client.getTokenFromAssertion("blah", "scope")
.then(
null,
- function (e) {
+ function(e) {
do_check_eq(e.name, "FxAccountsOAuthGrantClientError");
do_check_eq(e.code, 400);
do_check_eq(e.errno, ERRNO_INVALID_FXA_ASSERTION);
do_check_eq(e.error, "Bad Request");
do_check_eq(e.message, "Unauthorized");
run_next_test();
}
);
});
-add_test(function networkErrorResponse () {
+add_test(function networkErrorResponse() {
let client = new FxAccountsOAuthGrantClient({
serverURL: "http://",
client_id: "abc123"
});
Services.prefs.setBoolPref("identity.fxaccounts.skipDeviceRegistration", true);
client.getTokenFromAssertion("assertion", "scope")
.then(
null,
- function (e) {
+ function(e) {
do_check_eq(e.name, "FxAccountsOAuthGrantClientError");
do_check_eq(e.code, null);
do_check_eq(e.errno, ERRNO_NETWORK);
do_check_eq(e.error, ERROR_NETWORK);
run_next_test();
}
).catch(() => {}).then(() =>
Services.prefs.clearUserPref("identity.fxaccounts.skipDeviceRegistration"));
});
-add_test(function unsupportedMethod () {
+add_test(function unsupportedMethod() {
let client = new FxAccountsOAuthGrantClient(CLIENT_OPTIONS);
return client._createRequest("/", "PUT")
.then(
null,
- function (e) {
+ function(e) {
do_check_eq(e.name, "FxAccountsOAuthGrantClientError");
do_check_eq(e.code, ERROR_CODE_METHOD_NOT_ALLOWED);
do_check_eq(e.errno, ERRNO_NETWORK);
do_check_eq(e.error, ERROR_NETWORK);
do_check_eq(e.message, ERROR_MSG_METHOD_NOT_ALLOWED);
run_next_test();
}
);
});
-add_test(function onCompleteRequestError () {
+add_test(function onCompleteRequestError() {
let client = new FxAccountsOAuthGrantClient(CLIENT_OPTIONS);
client._Request = new mockResponseError(new Error("onComplete error"));
client.getTokenFromAssertion("assertion", "scope")
.then(
null,
- function (e) {
+ function(e) {
do_check_eq(e.name, "FxAccountsOAuthGrantClientError");
do_check_eq(e.code, null);
do_check_eq(e.errno, ERRNO_NETWORK);
do_check_eq(e.error, ERROR_NETWORK);
do_check_eq(e.message, "Error: onComplete error");
run_next_test();
}
);
@@ -201,17 +201,17 @@ add_test(function incorrectErrno() {
status: 400,
body: "{ \"code\": 400, \"errno\": \"bad errno\", \"error\": \"Bad Request\", \"message\": \"Unauthorized\", \"reason\": \"Invalid fxa assertion\" }",
};
client._Request = new mockResponse(response);
client.getTokenFromAssertion("blah", "scope")
.then(
null,
- function (e) {
+ function(e) {
do_check_eq(e.name, "FxAccountsOAuthGrantClientError");
do_check_eq(e.code, 400);
do_check_eq(e.errno, ERRNO_UNKNOWN_ERROR);
do_check_eq(e.error, "Bad Request");
do_check_eq(e.message, "Unauthorized");
run_next_test();
}
);
--- a/services/fxaccounts/tests/xpcshell/test_oauth_grant_client_server.js
+++ b/services/fxaccounts/tests/xpcshell/test_oauth_grant_client_server.js
@@ -45,17 +45,17 @@ function startServer() {
}
function promiseStopServer(server) {
return new Promise(resolve => {
server.stop(resolve);
});
}
-add_task(function* getAndRevokeToken () {
+add_task(function* getAndRevokeToken() {
let server = startServer();
let clientOptions = {
serverURL: "http://localhost:" + server.identity.primaryPort + "/v1",
client_id: 'abc123',
}
let client = new FxAccountsOAuthGrantClient(clientOptions);
let result = yield client.getTokenFromAssertion("assertion", "scope");
--- a/services/fxaccounts/tests/xpcshell/test_oauth_token_storage.js
+++ b/services/fxaccounts/tests/xpcshell/test_oauth_token_storage.js
@@ -77,17 +77,17 @@ function MockFxAccountsClient() {
FxAccountsClient.apply(this);
}
MockFxAccountsClient.prototype = {
__proto__: FxAccountsClient.prototype
}
-function MockFxAccounts(device={}) {
+function MockFxAccounts(device = {}) {
return new FxAccounts({
fxAccountsClient: new MockFxAccountsClient(),
newAccountState(credentials) {
// we use a real accountState but mocked storage.
let storage = new MockStorageManager();
storage.initialize(credentials);
return new AccountState(storage);
},
--- a/services/fxaccounts/tests/xpcshell/test_oauth_tokens.js
+++ b/services/fxaccounts/tests/xpcshell/test_oauth_tokens.js
@@ -84,17 +84,17 @@ function MockFxAccounts(mockGrantClient)
fxAccountsClient: new MockFxAccountsClient(),
getAssertion: () => Promise.resolve("assertion"),
newAccountState(credentials) {
// we use a real accountState but mocked storage.
let storage = new MockStorageManager();
storage.initialize(credentials);
return new AccountState(storage);
},
- _destroyOAuthToken: function(tokenData) {
+ _destroyOAuthToken(tokenData) {
// somewhat sad duplication of _destroyOAuthToken, but hard to avoid.
return mockGrantClient.destroyToken(tokenData.token).then( () => {
Services.obs.notifyObservers(null, "testhelper-fxa-revoke-complete", null);
});
},
_getDeviceName() {
return "mock device name";
},
@@ -151,17 +151,17 @@ MockFxAccountsOAuthGrantClient.prototype
},
// and some stuff used only for tests.
numTokenFetches: 0,
activeTokens: null,
}
add_task(function* testRevoke() {
let client = new MockFxAccountsOAuthGrantClient();
- let tokenOptions = { scope: "test-scope", client: client };
+ let tokenOptions = { scope: "test-scope", client };
let fxa = yield createMockFxA(client);
// get our first token and check we hit the mock.
let token1 = yield fxa.getOAuthToken(tokenOptions);
equal(client.numTokenFetches, 1);
equal(client.activeTokens.size, 1);
ok(token1, "got a token");
equal(token1, "token0");
@@ -181,23 +181,23 @@ add_task(function* testRevoke() {
notEqual(token1, token2, "got a different token");
});
add_task(function* testSignOutDestroysTokens() {
let client = new MockFxAccountsOAuthGrantClient();
let fxa = yield createMockFxA(client);
// get our first token and check we hit the mock.
- let token1 = yield fxa.getOAuthToken({ scope: "test-scope", client: client });
+ let token1 = yield fxa.getOAuthToken({ scope: "test-scope", client });
equal(client.numTokenFetches, 1);
equal(client.activeTokens.size, 1);
ok(token1, "got a token");
// get another
- let token2 = yield fxa.getOAuthToken({ scope: "test-scope-2", client: client });
+ let token2 = yield fxa.getOAuthToken({ scope: "test-scope-2", client });
equal(client.numTokenFetches, 2);
equal(client.activeTokens.size, 2);
ok(token2, "got a token");
notEqual(token1, token2, "got a different token");
// now sign out - they should be removed.
yield fxa.signOut();
// FxA fires an observer when the "background" signout is complete.
@@ -217,20 +217,20 @@ add_task(function* testTokenRaces() {
// We should see 2 notifications as part of this - set up the listeners
// now (and wait on them later)
let notifications = Promise.all([
promiseNotification("testhelper-fxa-revoke-complete"),
promiseNotification("testhelper-fxa-revoke-complete"),
]);
let results = yield Promise.all([
- fxa.getOAuthToken({scope: "test-scope", client: client}),
- fxa.getOAuthToken({scope: "test-scope", client: client}),
- fxa.getOAuthToken({scope: "test-scope-2", client: client}),
- fxa.getOAuthToken({scope: "test-scope-2", client: client}),
+ fxa.getOAuthToken({scope: "test-scope", client}),
+ fxa.getOAuthToken({scope: "test-scope", client}),
+ fxa.getOAuthToken({scope: "test-scope-2", client}),
+ fxa.getOAuthToken({scope: "test-scope-2", client}),
]);
equal(client.numTokenFetches, 4, "should have fetched 4 tokens.");
// We should see 2 of the 4 revoked due to the race.
yield notifications;
// Should have 2 unique tokens
results.sort();
--- a/services/fxaccounts/tests/xpcshell/test_profile.js
+++ b/services/fxaccounts/tests/xpcshell/test_profile.js
@@ -14,53 +14,53 @@ Services.prefs.setCharPref("identity.fxa
const STATUS_SUCCESS = 200;
/**
* Mock request responder
* @param {String} response
* Mocked raw response from the server
* @returns {Function}
*/
-var mockResponse = function (response) {
- let Request = function (requestUri) {
+var mockResponse = function(response) {
+ let Request = function(requestUri) {
// Store the request uri so tests can inspect it
Request._requestUri = requestUri;
return {
- setHeader: function () {},
- head: function () {
+ setHeader() {},
+ head() {
this.response = response;
this.onComplete();
}
};
};
return Request;
};
/**
* Mock request error responder
* @param {Error} error
* Error object
* @returns {Function}
*/
-var mockResponseError = function (error) {
- return function () {
+var mockResponseError = function(error) {
+ return function() {
return {
- setHeader: function () {},
- head: function () {
+ setHeader() {},
+ head() {
this.onComplete(error);
}
};
};
};
-var mockClient = function (fxa) {
+var mockClient = function(fxa) {
let options = {
serverURL: "http://127.0.0.1:1111/v1",
- fxa: fxa,
+ fxa,
}
return new FxAccountsProfileClient(options);
};
const ACCOUNT_DATA = {
uid: "abc123"
};
@@ -69,46 +69,46 @@ function FxaMock() {
FxaMock.prototype = {
currentAccountState: {
profile: null,
get isCurrent() {
return true;
}
},
- getSignedInUser: function () {
+ getSignedInUser() {
return Promise.resolve(ACCOUNT_DATA);
}
};
var mockFxa = function() {
return new FxaMock();
};
function CreateFxAccountsProfile(fxa = null, client = null) {
if (!fxa) {
fxa = mockFxa();
}
let options = {
- fxa: fxa,
+ fxa,
profileServerUrl: "http://127.0.0.1:1111/v1"
}
if (client) {
options.profileClient = client;
}
return new FxAccountsProfile(options);
}
add_test(function getCachedProfile() {
let profile = CreateFxAccountsProfile();
// a little pointless until bug 1157529 is fixed...
profile._cachedProfile = { avatar: "myurl" };
return profile._getCachedProfile()
- .then(function (cached) {
+ .then(function(cached) {
do_check_eq(cached.avatar, "myurl");
run_next_test();
});
});
add_test(function cacheProfile_change() {
let fxa = mockFxa();
/* Saving profile data disabled - bug 1157529
@@ -116,50 +116,50 @@ add_test(function cacheProfile_change()
fxa.setUserAccountData = function (data) {
setUserAccountDataCalled = true;
do_check_eq(data.profile.avatar, "myurl");
return Promise.resolve();
};
*/
let profile = CreateFxAccountsProfile(fxa);
- makeObserver(ON_PROFILE_CHANGE_NOTIFICATION, function (subject, topic, data) {
+ makeObserver(ON_PROFILE_CHANGE_NOTIFICATION, function(subject, topic, data) {
do_check_eq(data, ACCOUNT_DATA.uid);
// do_check_true(setUserAccountDataCalled); - bug 1157529
run_next_test();
});
return profile._cacheProfile({ avatar: "myurl" });
});
add_test(function cacheProfile_no_change() {
let fxa = mockFxa();
let profile = CreateFxAccountsProfile(fxa)
profile._cachedProfile = { avatar: "myurl" };
// XXX - saving is disabled (but we can leave that in for now as we are
// just checking it is *not* called)
- fxa.setSignedInUser = function (data) {
+ fxa.setSignedInUser = function(data) {
throw new Error("should not update account data");
};
return profile._cacheProfile({ avatar: "myurl" })
.then((result) => {
do_check_false(!!result);
run_next_test();
});
});
add_test(function fetchAndCacheProfile_ok() {
let client = mockClient(mockFxa());
- client.fetchProfile = function () {
+ client.fetchProfile = function() {
return Promise.resolve({ avatar: "myimg"});
};
let profile = CreateFxAccountsProfile(null, client);
- profile._cacheProfile = function (toCache) {
+ profile._cacheProfile = function(toCache) {
do_check_eq(toCache.avatar, "myimg");
return Promise.resolve();
};
return profile._fetchAndCacheProfile()
.then(result => {
do_check_eq(result.avatar, "myimg");
run_next_test();
@@ -172,17 +172,17 @@ add_task(function* fetchAndCacheProfileO
// A promise that remains unresolved while we fire off 2 requests for
// a profile.
let resolveProfile;
let promiseProfile = new Promise(resolve => {
resolveProfile = resolve;
});
let numFetches = 0;
let client = mockClient(mockFxa());
- client.fetchProfile = function () {
+ client.fetchProfile = function() {
numFetches += 1;
return promiseProfile;
};
let profile = CreateFxAccountsProfile(null, client);
let request1 = profile._fetchAndCacheProfile();
let request2 = profile._fetchAndCacheProfile();
@@ -204,22 +204,22 @@ add_task(function* fetchAndCacheProfileO
});
// Check that sharing a single fetch promise works correctly when the promise
// is rejected.
add_task(function* fetchAndCacheProfileOnce() {
// A promise that remains unresolved while we fire off 2 requests for
// a profile.
let rejectProfile;
- let promiseProfile = new Promise((resolve,reject) => {
+ let promiseProfile = new Promise((resolve, reject) => {
rejectProfile = reject;
});
let numFetches = 0;
let client = mockClient(mockFxa());
- client.fetchProfile = function () {
+ client.fetchProfile = function() {
numFetches += 1;
return promiseProfile;
};
let profile = CreateFxAccountsProfile(null, client);
let request1 = profile._fetchAndCacheProfile();
let request2 = profile._fetchAndCacheProfile();
@@ -244,30 +244,30 @@ add_task(function* fetchAndCacheProfileO
throw new Error("should have rejected");
} catch (ex) {
if (ex != "oh noes") {
throw ex;
}
}
// but a new request should work.
- client.fetchProfile = function () {
+ client.fetchProfile = function() {
return Promise.resolve({ avatar: "myimg"});
};
let got = yield profile._fetchAndCacheProfile();
do_check_eq(got.avatar, "myimg");
});
// Check that a new profile request within PROFILE_FRESHNESS_THRESHOLD of the
// last one doesn't kick off a new request to check the cached copy is fresh.
add_task(function* fetchAndCacheProfileAfterThreshold() {
let numFetches = 0;
let client = mockClient(mockFxa());
- client.fetchProfile = function () {
+ client.fetchProfile = function() {
numFetches += 1;
return Promise.resolve({ avatar: "myimg"});
};
let profile = CreateFxAccountsProfile(null, client);
profile.PROFILE_FRESHNESS_THRESHOLD = 1000;
yield profile.getProfile();
do_check_eq(numFetches, 1);
@@ -284,17 +284,17 @@ add_task(function* fetchAndCacheProfileA
});
// Check that a new profile request within PROFILE_FRESHNESS_THRESHOLD of the
// last one *does* kick off a new request if ON_PROFILE_CHANGE_NOTIFICATION
// is sent.
add_task(function* fetchAndCacheProfileBeforeThresholdOnNotification() {
let numFetches = 0;
let client = mockClient(mockFxa());
- client.fetchProfile = function () {
+ client.fetchProfile = function() {
numFetches += 1;
return Promise.resolve({ avatar: "myimg"});
};
let profile = CreateFxAccountsProfile(null, client);
profile.PROFILE_FRESHNESS_THRESHOLD = 1000;
yield profile.getProfile();
do_check_eq(numFetches, 1);
@@ -318,66 +318,66 @@ add_test(function tearDown_ok() {
run_next_test();
});
add_test(function getProfile_ok() {
let cachedUrl = "myurl";
let didFetch = false;
let profile = CreateFxAccountsProfile();
- profile._getCachedProfile = function () {
+ profile._getCachedProfile = function() {
return Promise.resolve({ avatar: cachedUrl });
};
- profile._fetchAndCacheProfile = function () {
+ profile._fetchAndCacheProfile = function() {
didFetch = true;
return Promise.resolve();
};
return profile.getProfile()
.then(result => {
do_check_eq(result.avatar, cachedUrl);
do_check_true(didFetch);
run_next_test();
});
});
add_test(function getProfile_no_cache() {
let fetchedUrl = "newUrl";
let profile = CreateFxAccountsProfile();
- profile._getCachedProfile = function () {
+ profile._getCachedProfile = function() {
return Promise.resolve();
};
- profile._fetchAndCacheProfile = function () {
+ profile._fetchAndCacheProfile = function() {
return Promise.resolve({ avatar: fetchedUrl });
};
return profile.getProfile()
.then(result => {
do_check_eq(result.avatar, fetchedUrl);
run_next_test();
});
});
add_test(function getProfile_has_cached_fetch_deleted() {
let cachedUrl = "myurl";
let fxa = mockFxa();
let client = mockClient(fxa);
- client.fetchProfile = function () {
+ client.fetchProfile = function() {
return Promise.resolve({ avatar: null });
};
let profile = CreateFxAccountsProfile(fxa, client);
profile._cachedProfile = { avatar: cachedUrl };
// instead of checking this in a mocked "save" function, just check after the
// observer
- makeObserver(ON_PROFILE_CHANGE_NOTIFICATION, function (subject, topic, data) {
+ makeObserver(ON_PROFILE_CHANGE_NOTIFICATION, function(subject, topic, data) {
profile.getProfile()
.then(profileData => {
do_check_null(profileData.avatar);
run_next_test();
});
});
return profile.getProfile()
@@ -386,17 +386,17 @@ add_test(function getProfile_has_cached_
});
});
function run_test() {
run_next_test();
}
function makeObserver(aObserveTopic, aObserveFunc) {
- let callback = function (aSubject, aTopic, aData) {
+ let callback = function(aSubject, aTopic, aData) {
log.debug("observed " + aTopic + " " + aData);
if (aTopic == aObserveTopic) {
removeMe();
aObserveFunc(aSubject, aTopic, aData);
}
};
function removeMe() {
--- a/services/fxaccounts/tests/xpcshell/test_profile_client.js
+++ b/services/fxaccounts/tests/xpcshell/test_profile_client.js
@@ -9,23 +9,23 @@ Cu.import("resource://gre/modules/FxAcco
const STATUS_SUCCESS = 200;
/**
* Mock request responder
* @param {String} response
* Mocked raw response from the server
* @returns {Function}
*/
-var mockResponse = function (response) {
- let Request = function (requestUri) {
+var mockResponse = function(response) {
+ let Request = function(requestUri) {
// Store the request uri so tests can inspect it
Request._requestUri = requestUri;
return {
- setHeader: function () {},
- get: function () {
+ setHeader() {},
+ get() {
this.response = response;
this.onComplete();
}
};
};
return Request;
};
@@ -46,95 +46,95 @@ const PROFILE_OPTIONS = {
};
/**
* Mock request error responder
* @param {Error} error
* Error object
* @returns {Function}
*/
-var mockResponseError = function (error) {
- return function () {
+var mockResponseError = function(error) {
+ return function() {
return {
- setHeader: function () {},
- get: function () {
+ setHeader() {},
+ get() {
this.onComplete(error);
}
};
};
};
-add_test(function successfulResponse () {
+add_test(function successfulResponse() {
let client = new FxAccountsProfileClient(PROFILE_OPTIONS);
let response = {
success: true,
status: STATUS_SUCCESS,
body: "{\"email\":\"someone@restmail.net\",\"uid\":\"0d5c1a89b8c54580b8e3e8adadae864a\"}",
};
client._Request = new mockResponse(response);
client.fetchProfile()
.then(
- function (result) {
+ function(result) {
do_check_eq(client._Request._requestUri, "http://127.0.0.1:1111/v1/profile");
do_check_eq(result.email, "someone@restmail.net");
do_check_eq(result.uid, "0d5c1a89b8c54580b8e3e8adadae864a");
run_next_test();
}
);
});
-add_test(function parseErrorResponse () {
+add_test(function parseErrorResponse() {
let client = new FxAccountsProfileClient(PROFILE_OPTIONS);
let response = {
success: true,
status: STATUS_SUCCESS,
body: "unexpected",
};
client._Request = new mockResponse(response);
client.fetchProfile()
.then(
null,
- function (e) {
+ function(e) {
do_check_eq(e.name, "FxAccountsProfileClientError");
do_check_eq(e.code, STATUS_SUCCESS);
do_check_eq(e.errno, ERRNO_PARSE);
do_check_eq(e.error, ERROR_PARSE);
do_check_eq(e.message, "unexpected");
run_next_test();
}
);
});
-add_test(function serverErrorResponse () {
+add_test(function serverErrorResponse() {
let client = new FxAccountsProfileClient(PROFILE_OPTIONS);
let response = {
status: 500,
body: "{ \"code\": 500, \"errno\": 100, \"error\": \"Bad Request\", \"message\": \"Something went wrong\", \"reason\": \"Because the internet\" }",
};
client._Request = new mockResponse(response);
client.fetchProfile()
.then(
null,
- function (e) {
+ function(e) {
do_check_eq(e.name, "FxAccountsProfileClientError");
do_check_eq(e.code, 500);
do_check_eq(e.errno, 100);
do_check_eq(e.error, "Bad Request");
do_check_eq(e.message, "Something went wrong");
run_next_test();
}
);
});
// Test that we get a token, then if we get a 401 we revoke it, get a new one
// and retry.
-add_test(function server401ResponseThenSuccess () {
+add_test(function server401ResponseThenSuccess() {
// The last token we handed out.
let lastToken = -1;
// The number of times our removeCachedOAuthToken function was called.
let numTokensRemoved = 0;
let mockFxa = {
getOAuthToken(options) {
do_check_eq(options.scope, "profile");
@@ -166,23 +166,23 @@ add_test(function server401ResponseThenS
},
];
let numRequests = 0;
let numAuthHeaders = 0;
// Like mockResponse but we want access to headers etc.
client._Request = function(requestUri) {
return {
- setHeader: function (name, value) {
+ setHeader(name, value) {
if (name == "Authorization") {
numAuthHeaders++;
do_check_eq(value, "Bearer " + lastToken);
}
},
- get: function () {
+ get() {
this.response = responses[numRequests];
++numRequests;
this.onComplete();
}
};
}
client.fetchProfile()
@@ -197,17 +197,17 @@ add_test(function server401ResponseThenS
run_next_test();
}
);
});
// Test that we get a token, then if we get a 401 we revoke it, get a new one
// and retry - but we *still* get a 401 on the retry, so the caller sees that.
-add_test(function server401ResponsePersists () {
+add_test(function server401ResponsePersists() {
// The last token we handed out.
let lastToken = -1;
// The number of times our removeCachedOAuthToken function was called.
let numTokensRemoved = 0;
let mockFxa = {
getOAuthToken(options) {
do_check_eq(options.scope, "profile");
@@ -230,111 +230,111 @@ add_test(function server401ResponsePersi
status: 401,
body: "{ \"code\": 401, \"errno\": 100, \"error\": \"It's not your token, it's you!\", \"message\": \"I don't like you\", \"reason\": \"Because security\" }",
};
let numRequests = 0;
let numAuthHeaders = 0;
client._Request = function(requestUri) {
return {
- setHeader: function (name, value) {
+ setHeader(name, value) {
if (name == "Authorization") {
numAuthHeaders++;
do_check_eq(value, "Bearer " + lastToken);
}
},
- get: function () {
+ get() {
this.response = response;
++numRequests;
this.onComplete();
}
};
}
client.fetchProfile().then(
null,
- function (e) {
+ function(e) {
do_check_eq(e.name, "FxAccountsProfileClientError");
do_check_eq(e.code, 401);
do_check_eq(e.errno, 100);
do_check_eq(e.error, "It's not your token, it's you!");
// should have been exactly 2 requests and exactly 2 auth headers.
do_check_eq(numRequests, 2);
do_check_eq(numAuthHeaders, 2);
// and we should have seen both tokens revoked.
do_check_eq(numTokensRemoved, 2);
run_next_test();
}
);
});
-add_test(function networkErrorResponse () {
+add_test(function networkErrorResponse() {
let client = new FxAccountsProfileClient({
serverURL: "http://",
fxa: mockFxa,
});
client.fetchProfile()
.then(
null,
- function (e) {
+ function(e) {
do_check_eq(e.name, "FxAccountsProfileClientError");
do_check_eq(e.code, null);
do_check_eq(e.errno, ERRNO_NETWORK);
do_check_eq(e.error, ERROR_NETWORK);
run_next_test();
}
);
});
-add_test(function unsupportedMethod () {
+add_test(function unsupportedMethod() {
let client = new FxAccountsProfileClient(PROFILE_OPTIONS);
return client._createRequest("/profile", "PUT")
.then(
null,
- function (e) {
+ function(e) {
do_check_eq(e.name, "FxAccountsProfileClientError");
do_check_eq(e.code, ERROR_CODE_METHOD_NOT_ALLOWED);
do_check_eq(e.errno, ERRNO_NETWORK);
do_check_eq(e.error, ERROR_NETWORK);
do_check_eq(e.message, ERROR_MSG_METHOD_NOT_ALLOWED);
run_next_test();
}
);
});
-add_test(function onCompleteRequestError () {
+add_test(function onCompleteRequestError() {
let client = new FxAccountsProfileClient(PROFILE_OPTIONS);
client._Request = new mockResponseError(new Error("onComplete error"));
client.fetchProfile()
.then(
null,
- function (e) {
+ function(e) {
do_check_eq(e.name, "FxAccountsProfileClientError");
do_check_eq(e.code, null);
do_check_eq(e.errno, ERRNO_NETWORK);
do_check_eq(e.error, ERROR_NETWORK);
do_check_eq(e.message, "Error: onComplete error");
run_next_test();
}
);
});
-add_test(function fetchProfileImage_successfulResponse () {
+add_test(function fetchProfileImage_successfulResponse() {
let client = new FxAccountsProfileClient(PROFILE_OPTIONS);
let response = {
success: true,
status: STATUS_SUCCESS,
body: "{\"avatar\":\"http://example.com/image.jpg\",\"id\":\"0d5c1a89b8c54580b8e3e8adadae864a\"}",
};
client._Request = new mockResponse(response);
client.fetchProfileImage()
.then(
- function (result) {
+ function(result) {
do_check_eq(client._Request._requestUri, "http://127.0.0.1:1111/v1/avatar");
do_check_eq(result.avatar, "http://example.com/image.jpg");
do_check_eq(result.id, "0d5c1a89b8c54580b8e3e8adadae864a");
run_next_test();
}
);
});
--- a/services/fxaccounts/tests/xpcshell/test_push_service.js
+++ b/services/fxaccounts/tests/xpcshell/test_push_service.js
@@ -101,17 +101,17 @@ add_task(function* unsubscribeFailure()
});
let result = yield pushService.unsubscribe();
equal(result, null);
});
add_test(function observeLogout() {
let customLog = Object.assign(mockLog, {
- trace: function (msg) {
+ trace(msg) {
if (msg === "FxAccountsPushService unsubscribe") {
// logout means we unsubscribe
run_next_test();
}
}
});
let pushService = new FxAccountsPushService({
@@ -119,22 +119,22 @@ add_test(function observeLogout() {
log: customLog
});
pushService.observe(null, ONLOGOUT_NOTIFICATION);
});
add_test(function observePushTopicVerify() {
let emptyMsg = {
- QueryInterface: function() {
+ QueryInterface() {
return this;
}
};
let customAccounts = Object.assign(mockFxAccounts, {
- checkVerificationStatus: function () {
+ checkVerificationStatus() {
// checking verification status on push messages without data
run_next_test();
}
});
let pushService = new FxAccountsPushService({
pushService: mockPushService,
fxAccounts: customAccounts,
@@ -148,17 +148,17 @@ add_test(function observePushTopicDevice
data: {
json: () => ({
command: ON_DEVICE_CONNECTED_NOTIFICATION,
data: {
deviceName: "My phone"
}
})
},
- QueryInterface: function() {
+ QueryInterface() {
return this;
}
};
let obs = (subject, topic, data) => {
Services.obs.removeObserver(obs, topic);
run_next_test();
};
Services.obs.addObserver(obs, ON_DEVICE_CONNECTED_NOTIFICATION, false);
@@ -177,22 +177,22 @@ add_test(function observePushTopicDevice
data: {
json: () => ({
command: ON_DEVICE_DISCONNECTED_NOTIFICATION,
data: {
id: deviceId
}
})
},
- QueryInterface: function() {
+ QueryInterface() {
return this;
}
};
let customAccounts = Object.assign(mockFxAccounts, {
- handleDeviceDisconnection: function () {
+ handleDeviceDisconnection() {
// checking verification status on push messages without data
run_next_test();
}
});
let pushService = new FxAccountsPushService({
pushService: mockPushService,
fxAccounts: customAccounts,
@@ -203,58 +203,58 @@ add_test(function observePushTopicDevice
add_test(function observePushTopicPasswordChanged() {
let msg = {
data: {
json: () => ({
command: ON_PASSWORD_CHANGED_NOTIFICATION
})
},
- QueryInterface: function() {
+ QueryInterface() {
return this;
}
};
let pushService = new FxAccountsPushService({
pushService: mockPushService,
});
- pushService._onPasswordChanged = function () {
+ pushService._onPasswordChanged = function() {
run_next_test();
}
pushService.observe(msg, mockPushService.pushTopic, FXA_PUSH_SCOPE_ACCOUNT_UPDATE);
});
add_test(function observePushTopicPasswordReset() {
let msg = {
data: {
json: () => ({
command: ON_PASSWORD_RESET_NOTIFICATION
})
},
- QueryInterface: function() {
+ QueryInterface() {
return this;
}
};
let pushService = new FxAccountsPushService({
pushService: mockPushService
});
- pushService._onPasswordChanged = function () {
+ pushService._onPasswordChanged = function() {
run_next_test();
}
pushService.observe(msg, mockPushService.pushTopic, FXA_PUSH_SCOPE_ACCOUNT_UPDATE);
});
add_test(function observeSubscriptionChangeTopic() {
let customAccounts = Object.assign(mockFxAccounts, {
- updateDeviceRegistration: function () {
+ updateDeviceRegistration() {
// subscription change means updating the device registration
run_next_test();
}
});
let pushService = new FxAccountsPushService({
pushService: mockPushService,
fxAccounts: customAccounts,
--- a/services/fxaccounts/tests/xpcshell/test_storage_manager.js
+++ b/services/fxaccounts/tests/xpcshell/test_storage_manager.js
@@ -17,17 +17,17 @@ log.level = Log.Level.Trace;
const DEVICE_REGISTRATION_VERSION = 42;
// A couple of mocks we can use.
function MockedPlainStorage(accountData) {
let data = null;
if (accountData) {
data = {
version: DATA_FORMAT_VERSION,
- accountData: accountData,
+ accountData,
}
}
this.data = data;
this.numReads = 0;
}
MockedPlainStorage.prototype = {
get: Task.async(function* () {
this.numReads++;
@@ -40,27 +40,32 @@ MockedPlainStorage.prototype = {
}),
};
function MockedSecureStorage(accountData) {
let data = null;
if (accountData) {
data = {
version: DATA_FORMAT_VERSION,
- accountData: accountData,
+ accountData,
}
}
this.data = data;
this.numReads = 0;
}
MockedSecureStorage.prototype = {
fetchCount: 0,
locked: false,
+ /* eslint-disable object-shorthand */
+ // This constructor must be declared without
+ // object shorthand or we get an exception of
+ // "TypeError: this.STORAGE_LOCKED is not a constructor"
STORAGE_LOCKED: function() {},
+ /* eslint-enable object-shorthand */
get: Task.async(function* (uid, email) {
this.fetchCount++;
if (this.locked) {
throw new this.STORAGE_LOCKED();
}
this.numReads++;
Assert.equal(this.numReads, 1, "should only ever be 1 read of unlocked data");
return this.data;
--- a/services/fxaccounts/tests/xpcshell/test_web_channel.js
+++ b/services/fxaccounts/tests/xpcshell/test_web_channel.js
@@ -10,17 +10,17 @@ const { FxAccountsWebChannel, FxAccounts
const URL_STRING = "https://example.com";
const mockSendingContext = {
browser: {},
principal: {},
eventTarget: {}
};
-add_test(function () {
+add_test(function() {
validationHelper(undefined,
"Error: Missing configuration options");
validationHelper({
channel_id: WEBCHANNEL_ID
},
"Error: Missing 'content_uri' option");
@@ -113,17 +113,17 @@ add_test(function test_exception_reporti
});
add_test(function test_profile_image_change_message() {
var mockMessage = {
command: "profile:change",
data: { uid: "foo" }
};
- makeObserver(ON_PROFILE_CHANGE_NOTIFICATION, function (subject, topic, data) {
+ makeObserver(ON_PROFILE_CHANGE_NOTIFICATION, function(subject, topic, data) {
do_check_eq(data, "foo");
run_next_test();
});
var channel = new FxAccountsWebChannel({
channel_id: WEBCHANNEL_ID,
content_uri: URL_STRING
});
@@ -136,17 +136,17 @@ add_test(function test_login_message() {
command: 'fxaccounts:login',
data: { email: 'testuser@testuser.com' }
};
let channel = new FxAccountsWebChannel({
channel_id: WEBCHANNEL_ID,
content_uri: URL_STRING,
helpers: {
- login: function (accountData) {
+ login(accountData) {
do_check_eq(accountData.email, 'testuser@testuser.com');
run_next_test();
return Promise.resolve();
}
}
});
channel._channelCallback(WEBCHANNEL_ID, mockMessage, mockSendingContext);
@@ -157,17 +157,17 @@ add_test(function test_logout_message()
command: 'fxaccounts:logout',
data: { uid: "foo" }
};
let channel = new FxAccountsWebChannel({
channel_id: WEBCHANNEL_ID,
content_uri: URL_STRING,
helpers: {
- logout: function (uid) {
+ logout(uid) {
do_check_eq(uid, 'foo');
run_next_test();
return Promise.resolve();
}
}
});
channel._channelCallback(WEBCHANNEL_ID, mockMessage, mockSendingContext);
@@ -178,17 +178,17 @@ add_test(function test_delete_message()
command: 'fxaccounts:delete',
data: { uid: "foo" }
};
let channel = new FxAccountsWebChannel({
channel_id: WEBCHANNEL_ID,
content_uri: URL_STRING,
helpers: {
- logout: function (uid) {
+ logout(uid) {
do_check_eq(uid, 'foo');
run_next_test();
return Promise.resolve();
}
}
});
channel._channelCallback(WEBCHANNEL_ID, mockMessage, mockSendingContext);
@@ -199,17 +199,17 @@ add_test(function test_can_link_account_
command: 'fxaccounts:can_link_account',
data: { email: 'testuser@testuser.com' }
};
let channel = new FxAccountsWebChannel({
channel_id: WEBCHANNEL_ID,
content_uri: URL_STRING,
helpers: {
- shouldAllowRelink: function (email) {
+ shouldAllowRelink(email) {
do_check_eq(email, 'testuser@testuser.com');
run_next_test();
}
}
});
channel._channelCallback(WEBCHANNEL_ID, mockMessage, mockSendingContext);
});
@@ -219,17 +219,17 @@ add_test(function test_sync_preferences_
command: 'fxaccounts:sync_preferences',
data: { entryPoint: 'fxa:verification_complete' }
};
let channel = new FxAccountsWebChannel({
channel_id: WEBCHANNEL_ID,
content_uri: URL_STRING,
helpers: {
- openSyncPreferences: function (browser, entryPoint) {
+ openSyncPreferences(browser, entryPoint) {
do_check_eq(entryPoint, 'fxa:verification_complete');
do_check_eq(browser, mockSendingContext.browser);
run_next_test();
}
}
});
channel._channelCallback(WEBCHANNEL_ID, mockMessage, mockSendingContext);
@@ -274,17 +274,17 @@ add_test(function test_helpers_should_al
do_check_false(helpers.shouldAllowRelink('not_allowed_to_relink@testuser.com'));
run_next_test();
});
add_task(function* test_helpers_login_without_customize_sync() {
let helpers = new FxAccountsWebChannelHelpers({
fxAccounts: {
- setSignedInUser: function(accountData) {
+ setSignedInUser(accountData) {
return new Promise(resolve => {
// ensure fxAccounts is informed of the new user being signed in.
do_check_eq(accountData.email, 'testuser@testuser.com');
// verifiedCanLinkAccount should be stripped in the data.
do_check_false('verifiedCanLinkAccount' in accountData);
// the customizeSync pref should not update
@@ -310,17 +310,17 @@ add_task(function* test_helpers_login_wi
verifiedCanLinkAccount: true,
customizeSync: false
});
});
add_task(function* test_helpers_login_with_customize_sync() {
let helpers = new FxAccountsWebChannelHelpers({
fxAccounts: {
- setSignedInUser: function(accountData) {
+ setSignedInUser(accountData) {
return new Promise(resolve => {
// ensure fxAccounts is informed of the new user being signed in.
do_check_eq(accountData.email, 'testuser@testuser.com');
// customizeSync should be stripped in the data.
do_check_false('customizeSync' in accountData);
// the customizeSync pref should not update
@@ -340,17 +340,17 @@ add_task(function* test_helpers_login_wi
verifiedCanLinkAccount: true,
customizeSync: true
});
});
add_task(function* test_helpers_login_with_customize_sync_and_declined_engines() {
let helpers = new FxAccountsWebChannelHelpers({
fxAccounts: {
- setSignedInUser: function(accountData) {
+ setSignedInUser(accountData) {
return new Promise(resolve => {
// ensure fxAccounts is informed of the new user being signed in.
do_check_eq(accountData.email, 'testuser@testuser.com');
// customizeSync should be stripped in the data.
do_check_false('customizeSync' in accountData);
do_check_false('declinedSyncEngines' in accountData);
do_check_eq(Services.prefs.getBoolPref("services.sync.engine.addons"), false);
@@ -463,17 +463,17 @@ add_task(function* test_helpers_change_p
}
});
function run_test() {
run_next_test();
}
function makeObserver(aObserveTopic, aObserveFunc) {
- let callback = function (aSubject, aTopic, aData) {
+ let callback = function(aSubject, aTopic, aData) {
log.debug("observed " + aTopic + " " + aData);
if (aTopic == aObserveTopic) {
removeMe();
aObserveFunc(aSubject, aTopic, aData);
}
};
function removeMe() {
--- a/services/sync/Weave.js
+++ b/services/sync/Weave.js
@@ -66,29 +66,29 @@ function WeaveService() {
this.ready = false;
}
WeaveService.prototype = {
classID: Components.ID("{74b89fb0-f200-4ae8-a3ec-dd164117f6de}"),
QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver,
Ci.nsISupportsWeakReference]),
- ensureLoaded: function () {
+ ensureLoaded() {
// If we are loaded and not using FxA, load the migration module.
if (!this.fxAccountsEnabled) {
Cu.import("resource://services-sync/FxaMigrator.jsm");
}
Components.utils.import("resource://services-sync/main.js");
// Side-effect of accessing the service is that it is instantiated.
Weave.Service;
},
- whenLoaded: function() {
+ whenLoaded() {
if (this.ready) {
return Promise.resolve();
}
let deferred = Promise.defer();
Services.obs.addObserver(function onReady() {
Services.obs.removeObserver(onReady, "weave:service:ready");
deferred.resolve();
@@ -122,17 +122,17 @@ WeaveService.prototype = {
* It does *not* perform a robust check to see if the client is working.
* For that, you'll want to check Weave.Status.checkSetup().
*/
get enabled() {
let prefs = Services.prefs.getBranch(SYNC_PREFS_BRANCH);
return prefs.prefHasUserValue("username");
},
- observe: function (subject, topic, data) {
+ observe(subject, topic, data) {
switch (topic) {
case "app-startup":
let os = Cc["@mozilla.org/observer-service;1"].
getService(Ci.nsIObserverService);
os.addObserver(this, "final-ui-startup", true);
break;
case "final-ui-startup":
@@ -167,21 +167,21 @@ WeaveService.prototype = {
function AboutWeaveLog() {}
AboutWeaveLog.prototype = {
classID: Components.ID("{d28f8a0b-95da-48f4-b712-caf37097be41}"),
QueryInterface: XPCOMUtils.generateQI([Ci.nsIAboutModule,
Ci.nsISupportsWeakReference]),
- getURIFlags: function(aURI) {
+ getURIFlags(aURI) {
return 0;
},
- newChannel: function(aURI, aLoadInfo) {
+ newChannel(aURI, aLoadInfo) {
let dir = FileUtils.getDir("ProfD", ["weave", "logs"], true);
let uri = Services.io.newFileURI(dir);
let channel = Services.io.newChannelFromURIWithLoadInfo(uri, aLoadInfo);
channel.originalURI = aURI;
// Ensure that the about page has the same privileges as a regular directory
// view. That way links to files can be opened. make sure we use the correct
--- a/services/sync/modules-testing/fakeservices.js
+++ b/services/sync/modules-testing/fakeservices.js
@@ -79,17 +79,17 @@ this.fakeSHA256HMAC = function fakeSHA25
}
this.FakeGUIDService = function FakeGUIDService() {
let latestGUID = 0;
Utils.makeGUID = function makeGUID() {
// ensure that this always returns a unique 12 character string
let nextGUID = "fake-guid-" + String(latestGUID++).padStart(2, "0");
- return nextGUID.slice(nextGUID.length-12, nextGUID.length);
+ return nextGUID.slice(nextGUID.length - 12, nextGUID.length);
};
}
/*
* Mock implementation of WeaveCrypto. It does not encrypt or
* decrypt, merely returning the input verbatim.
*/
this.FakeCryptoService = function FakeCryptoService() {
--- a/services/sync/modules-testing/fxa_utils.js
+++ b/services/sync/modules-testing/fxa_utils.js
@@ -1,58 +1,58 @@
-"use strict";
-
-this.EXPORTED_SYMBOLS = [
- "initializeIdentityWithTokenServerResponse",
-];
-
-var {utils: Cu} = Components;
-
-Cu.import("resource://gre/modules/Log.jsm");
-Cu.import("resource://services-sync/main.js");
-Cu.import("resource://services-sync/browserid_identity.js");
-Cu.import("resource://services-common/tokenserverclient.js");
-Cu.import("resource://testing-common/services/common/logging.js");
-Cu.import("resource://testing-common/services/sync/utils.js");
-
-// Create a new browserid_identity object and initialize it with a
-// mocked TokenServerClient which always receives the specified response.
-this.initializeIdentityWithTokenServerResponse = function(response) {
- // First create a mock "request" object that well' hack into the token server.
- // A log for it
- let requestLog = Log.repository.getLogger("testing.mock-rest");
- if (!requestLog.appenders.length) { // might as well see what it says :)
- requestLog.addAppender(new Log.DumpAppender());
- requestLog.level = Log.Level.Trace;
- }
-
- // A mock request object.
- function MockRESTRequest(url) {};
- MockRESTRequest.prototype = {
- _log: requestLog,
- setHeader: function() {},
- get: function(callback) {
- this.response = response;
- callback.call(this);
- }
- }
- // The mocked TokenServer client which will get the response.
- function MockTSC() { }
- MockTSC.prototype = new TokenServerClient();
- MockTSC.prototype.constructor = MockTSC;
- MockTSC.prototype.newRESTRequest = function(url) {
- return new MockRESTRequest(url);
- }
- // Arrange for the same observerPrefix as browserid_identity uses.
- MockTSC.prototype.observerPrefix = "weave:service";
-
- // tie it all together.
- Weave.Status.__authManager = Weave.Service.identity = new BrowserIDManager();
- Weave.Service._clusterManager = Weave.Service.identity.createClusterManager(Weave.Service);
- let browseridManager = Weave.Service.identity;
- // a sanity check
- if (!(browseridManager instanceof BrowserIDManager)) {
- throw new Error("sync isn't configured for browserid_identity");
- }
- let mockTSC = new MockTSC()
- configureFxAccountIdentity(browseridManager);
- browseridManager._tokenServerClient = mockTSC;
-}
+"use strict";
+
+this.EXPORTED_SYMBOLS = [
+ "initializeIdentityWithTokenServerResponse",
+];
+
+var {utils: Cu} = Components;
+
+Cu.import("resource://gre/modules/Log.jsm");
+Cu.import("resource://services-sync/main.js");
+Cu.import("resource://services-sync/browserid_identity.js");
+Cu.import("resource://services-common/tokenserverclient.js");
+Cu.import("resource://testing-common/services/common/logging.js");
+Cu.import("resource://testing-common/services/sync/utils.js");
+
+// Create a new browserid_identity object and initialize it with a
+// mocked TokenServerClient which always receives the specified response.
+this.initializeIdentityWithTokenServerResponse = function(response) {
+ // First create a mock "request" object that well' hack into the token server.
+ // A log for it
+ let requestLog = Log.repository.getLogger("testing.mock-rest");
+ if (!requestLog.appenders.length) { // might as well see what it says :)
+ requestLog.addAppender(new Log.DumpAppender());
+ requestLog.level = Log.Level.Trace;
+ }
+
+ // A mock request object.
+ function MockRESTRequest(url) {}
+ MockRESTRequest.prototype = {
+ _log: requestLog,
+ setHeader() {},
+ get(callback) {
+ this.response = response;
+ callback.call(this);
+ }
+ }
+ // The mocked TokenServer client which will get the response.
+ function MockTSC() { }
+ MockTSC.prototype = new TokenServerClient();
+ MockTSC.prototype.constructor = MockTSC;
+ MockTSC.prototype.newRESTRequest = function(url) {
+ return new MockRESTRequest(url);
+ }
+ // Arrange for the same observerPrefix as browserid_identity uses.
+ MockTSC.prototype.observerPrefix = "weave:service";
+
+ // tie it all together.
+ Weave.Status.__authManager = Weave.Service.identity = new BrowserIDManager();
+ Weave.Service._clusterManager = Weave.Service.identity.createClusterManager(Weave.Service);
+ let browseridManager = Weave.Service.identity;
+ // a sanity check
+ if (!(browseridManager instanceof BrowserIDManager)) {
+ throw new Error("sync isn't configured for browserid_identity");
+ }
+ let mockTSC = new MockTSC()
+ configureFxAccountIdentity(browseridManager);
+ browseridManager._tokenServerClient = mockTSC;
+}
--- a/services/sync/modules-testing/utils.js
+++ b/services/sync/modules-testing/utils.js
@@ -233,17 +233,17 @@ this.configureFxAccountIdentity = functi
accountStatus() {
return Promise.resolve(true);
}
};
let mockFxAClient = new MockFxAccountsClient();
fxa.internal._fxAccountsClient = mockFxAClient;
let mockTSC = { // TokenServerClient
- getTokenFromBrowserIDAssertion: function(uri, assertion, cb) {
+ getTokenFromBrowserIDAssertion(uri, assertion, cb) {
config.fxaccount.token.uid = config.username;
cb(null, config.fxaccount.token);
},
};
authService._fxaService = fxa;
authService._tokenServerClient = mockTSC;
// Set the "account" of the browserId manager to be the "email" of the
// logged in user of the mockFXA service.
@@ -288,17 +288,17 @@ this.configureIdentity = async function(
if (server) {
ns.Service.clusterURL = server.baseURI + "/";
}
ns.Service.identity.username = config.username;
ns.Service._updateCachedURLs();
setBasicCredentials(config.username, config.sync.password, config.sync.syncKey);
}
-this.SyncTestingInfrastructure = async function (server, username, password) {
+this.SyncTestingInfrastructure = async function(server, username, password) {
let ns = {};
Cu.import("resource://services-sync/service.js", ns);
let config = makeIdentityConfig({ username, password });
await configureIdentity(config, server);
return {
logStats: initTestLogging(),
fakeFilesystem: new FakeFilesystemService({}),
--- a/services/sync/modules/SyncedTabs.jsm
+++ b/services/sync/modules/SyncedTabs.jsm
@@ -176,17 +176,17 @@ let SyncedTabsInternal = {
Services.tm.currentThread.dispatch(() => {
try {
log.info("Doing a tab sync.");
Weave.Service.sync(["tabs"]);
resolve(true);
} catch (ex) {
log.error("Sync failed", ex);
reject(ex);
- };
+ }
}, Ci.nsIThread.DISPATCH_NORMAL);
});
},
observe(subject, topic, data) {
log.trace(`observed topic=${topic}, data=${data}, subject=${subject}`);
switch (topic) {
case "weave:engine:sync:finish":
--- a/services/sync/modules/addonsreconciler.js
+++ b/services/sync/modules/addonsreconciler.js
@@ -247,18 +247,17 @@ AddonsReconciler.prototype = {
let file = path || DEFAULT_STATE_FILE;
let state = {version: 1, addons: {}, changes: []};
for (let [id, record] of Object.entries(this._addons)) {
state.addons[id] = {};
for (let [k, v] of Object.entries(record)) {
if (k == "modified") {
state.addons[id][k] = v.getTime();
- }
- else {
+ } else {
state.addons[id][k] = v;
}
}
}
for (let [time, change, id] of this._changes) {
state.changes.push([time.getTime(), change, id]);
}
@@ -343,17 +342,17 @@ AddonsReconciler.prototype = {
* Refreshes the global state of add-ons by querying the AddonManager.
*/
refreshGlobalState: function refreshGlobalState(callback) {
this._log.info("Refreshing global state from AddonManager.");
this._ensureStateLoaded();
let installs;
- AddonManager.getAllAddons(function (addons) {
+ AddonManager.getAllAddons(function(addons) {
let ids = {};
for (let addon of addons) {
ids[addon.id] = true;
this.rectifyStateFromAddon(addon);
}
// Look for locally-defined add-ons that no longer exist and update their
@@ -422,19 +421,19 @@ AddonsReconciler.prototype = {
let id = addon.id;
let enabled = !addon.userDisabled;
let guid = addon.syncGUID;
let now = new Date();
if (!(id in this._addons)) {
let record = {
- id: id,
- guid: guid,
- enabled: enabled,
+ id,
+ guid,
+ enabled,
installed: true,
modified: now,
type: addon.type,
scope: addon.scope,
foreignInstall: addon.foreignInstall,
isSyncable: addon.isSyncable,
};
this._addons[id] = record;
@@ -629,18 +628,17 @@ AddonsReconciler.prototype = {
}
// See note for _shouldPersist.
if (this._shouldPersist) {
let cb = Async.makeSpinningCallback();
this.saveState(null, cb);
cb.wait();
}
- }
- catch (ex) {
+ } catch (ex) {
this._log.warn("Exception", ex);
}
},
// AddonListeners
onEnabling: function onEnabling(addon, requiresRestart) {
this._handleListener("onEnabling", addon, requiresRestart);
},
--- a/services/sync/modules/addonutils.js
+++ b/services/sync/modules/addonutils.js
@@ -109,49 +109,48 @@ AddonUtilsInternal.prototype = {
let listener = {
onInstallStarted: function onInstallStarted(install) {
if (!options) {
return;
}
if (options.syncGUID) {
- log.info("Setting syncGUID of " + install.name +": " +
+ log.info("Setting syncGUID of " + install.name + ": " +
options.syncGUID);
install.addon.syncGUID = options.syncGUID;
}
// We only need to change userDisabled if it is disabled because
// enabled is the default.
if ("enabled" in options && !options.enabled) {
log.info("Marking add-on as disabled for install: " +
install.name);
install.addon.userDisabled = true;
}
},
- onInstallEnded: function(install, addon) {
+ onInstallEnded(install, addon) {
install.removeListener(listener);
- cb(null, {id: addon.id, install: install, addon: addon});
+ cb(null, {id: addon.id, install, addon});
},
- onInstallFailed: function(install) {
+ onInstallFailed(install) {
install.removeListener(listener);
cb(new Error("Install failed: " + install.error), null);
},
- onDownloadFailed: function(install) {
+ onDownloadFailed(install) {
install.removeListener(listener);
cb(new Error("Download failed: " + install.error), null);
}
};
install.addListener(listener);
install.install();
- }
- catch (ex) {
+ } catch (ex) {
this._log.error("Error installing add-on", ex);
cb(ex, null);
}
}.bind(this));
},
/**
* Uninstalls the Addon instance and invoke a callback when it is done.
@@ -159,33 +158,33 @@ AddonUtilsInternal.prototype = {
* @param addon
* Addon instance to uninstall.
* @param cb
* Function to be invoked when uninstall has finished. It receives a
* truthy value signifying error and the add-on which was uninstalled.
*/
uninstallAddon: function uninstallAddon(addon, cb) {
let listener = {
- onUninstalling: function(uninstalling, needsRestart) {
+ onUninstalling(uninstalling, needsRestart) {
if (addon.id != uninstalling.id) {
return;
}
// We assume restartless add-ons will send the onUninstalled event
// soon.
if (!needsRestart) {
return;
}
// For non-restartless add-ons, we issue the callback on uninstalling
// because we will likely never see the uninstalled event.
AddonManager.removeAddonListener(listener);
cb(null, addon);
},
- onUninstalled: function(uninstalled) {
+ onUninstalled(uninstalled) {
if (addon.id != uninstalled.id) {
return;
}
AddonManager.removeAddonListener(listener);
cb(null, addon);
}
};
@@ -268,17 +267,17 @@ AddonUtilsInternal.prototype = {
if (finishedCount >= expectedInstallCount) {
if (ourResult.errors.length > 0) {
cb(new Error("1 or more add-ons failed to install"), ourResult);
} else {
cb(null, ourResult);
}
}
- }.bind(this);
+ };
let toInstall = [];
// Rewrite the "src" query string parameter of the source URI to note
// that the add-on was installed by Sync and not something else so
// server-side metrics aren't skewed (bug 708134). The server should
// ideally send proper URLs, but this solution was deemed too
// complicated at the time the functionality was implemented.
@@ -489,17 +488,17 @@ AddonUtilsInternal.prototype = {
AddonManager.addAddonListener(listener);
}
this._log.info("Updating userDisabled flag: " + addon.id + " -> " + value);
addon.userDisabled = !!value;
if (!addon.appDisabled) {
cb(null, addon);
- return;
+
}
// Else the listener will handle invoking the callback.
},
};
XPCOMUtils.defineLazyGetter(this, "AddonUtils", function() {
return new AddonUtilsInternal();
--- a/services/sync/modules/bookmark_validator.js
+++ b/services/sync/modules/bookmark_validator.js
@@ -332,22 +332,20 @@ class BookmarkValidator {
for (let record of serverRecords) {
if (!record.id) {
++problemData.missingIDs;
continue;
}
if (record.deleted) {
deletedItemIds.add(record.id);
- } else {
- if (idToRecord.has(record.id)) {
+ } else if (idToRecord.has(record.id)) {
problemData.duplicates.push(record.id);
continue;
}
- }
idToRecord.set(record.id, record);
if (record.children) {
if (record.type !== "folder") {
// Due to implementation details in engines/bookmarks.js, (Livemark
// subclassing BookmarkFolder) Livemarks will have a children array,
// but it should still be empty.
if (!record.children.length) {
@@ -763,22 +761,22 @@ class BookmarkValidator {
let start = Date.now();
let clientTree = yield PlacesUtils.promiseBookmarksTree("", {
includeItemIds: true
});
let serverState = self._getServerState(engine);
let serverRecordCount = serverState.length;
let result = self.compareServerWithClient(serverState, clientTree);
let end = Date.now();
- let duration = end-start;
+ let duration = end - start;
return {
duration,
version: self.version,
problems: result.problemData,
recordCount: serverRecordCount
};
});
}
-};
+}
BookmarkValidator.prototype.version = BOOKMARK_VALIDATOR_VERSION;
--- a/services/sync/modules/browserid_identity.js
+++ b/services/sync/modules/browserid_identity.js
@@ -47,17 +47,17 @@ const OBSERVER_TOPICS = [
fxAccountsCommon.ONLOGOUT_NOTIFICATION,
fxAccountsCommon.ON_ACCOUNT_STATE_CHANGE_NOTIFICATION,
];
const PREF_SYNC_SHOW_CUSTOMIZATION = "services.sync-setup.ui.showCustomizationDialog";
function deriveKeyBundle(kB) {
let out = CryptoUtils.hkdf(kB, undefined,
- "identity.mozilla.com/picl/v1/oldsync", 2*32);
+ "identity.mozilla.com/picl/v1/oldsync", 2 * 32);
let bundle = new BulkKeyBundle();
// [encryptionKey, hmacKey]
bundle.keyPair = [out.slice(0, 32), out.slice(32, 64)];
return bundle;
}
/*
General authentication error for abstracting authentication
@@ -67,17 +67,17 @@ function deriveKeyBundle(kB) {
called on it)
*/
function AuthenticationError(details, source) {
this.details = details;
this.source = source;
}
AuthenticationError.prototype = {
- toString: function() {
+ toString() {
return "AuthenticationError(" + this.details + ")";
}
}
this.BrowserIDManager = function BrowserIDManager() {
// NOTE: _fxaService and _tokenServerClient are replaced with mocks by
// the test suite.
this._fxaService = fxAccounts;
@@ -129,17 +129,17 @@ this.BrowserIDManager.prototype = {
// identity without knowing the metrics HMAC key.
return Utils.sha256(deviceID + uid);
},
deviceID() {
return this._signedInUser && this._signedInUser.deviceId;
},
- initialize: function() {
+ initialize() {
for (let topic of OBSERVER_TOPICS) {
Services.obs.addObserver(this, topic, false);
}
// and a background fetch of account data just so we can set this.account,
// so we have a username available before we've actually done a login.
// XXX - this is actually a hack just for tests and really shouldn't be
// necessary. Also, you'd think it would be safe to allow this.account to
// be set to null when there's no user logged in, but argue with the test
@@ -152,17 +152,17 @@ this.BrowserIDManager.prototype = {
// As above, this is only for tests so it is safe to ignore.
});
},
/**
* Ensure the user is logged in. Returns a promise that resolves when
* the user is logged in, or is rejected if the login attempt has failed.
*/
- ensureLoggedIn: function() {
+ ensureLoggedIn() {
if (!this._shouldHaveSyncKeyBundle && this.whenReadyToAuthenticate) {
// We are already in the process of logging in.
return this.whenReadyToAuthenticate.promise;
}
// If we are already happy then there is nothing more to do.
if (this._syncKeyBundle) {
return Promise.resolve();
@@ -176,39 +176,39 @@ this.BrowserIDManager.prototype = {
}
// So - we've a previous auth problem and aren't currently attempting to
// log in - so fire that off.
this.initializeWithCurrentIdentity();
return this.whenReadyToAuthenticate.promise;
},
- finalize: function() {
+ finalize() {
// After this is called, we can expect Service.identity != this.
for (let topic of OBSERVER_TOPICS) {
Services.obs.removeObserver(this, topic);
}
this.resetCredentials();
this._signedInUser = null;
},
- offerSyncOptions: function () {
+ offerSyncOptions() {
// If the user chose to "Customize sync options" when signing
// up with Firefox Accounts, ask them to choose what to sync.
const url = "chrome://browser/content/sync/customize.xul";
const features = "centerscreen,chrome,modal,dialog,resizable=no";
let win = Services.wm.getMostRecentWindow("navigator:browser");
let data = {accepted: false};
win.openDialog(url, "_blank", features, data);
return data;
},
- initializeWithCurrentIdentity: function(isInitialSync=false) {
+ initializeWithCurrentIdentity(isInitialSync = false) {
// While this function returns a promise that resolves once we've started
// the auth process, that process is complete when
// this.whenReadyToAuthenticate.promise resolves.
this._log.trace("initializeWithCurrentIdentity");
// Reset the world before we do anything async.
this.whenReadyToAuthenticate = Promise.defer();
this.whenReadyToAuthenticate.promise.catch(err => {
@@ -279,37 +279,37 @@ this.BrowserIDManager.prototype = {
this.whenReadyToAuthenticate.reject(authErr);
});
// and we are done - the fetch continues on in the background...
}).catch(err => {
this._log.error("Processing logged in account", err);
});
},
- _updateSignedInUser: function(userData) {
+ _updateSignedInUser(userData) {
// This object should only ever be used for a single user. It is an
// error to update the data if the user changes (but updates are still
// necessary, as each call may add more attributes to the user).
// We start with no user, so an initial update is always ok.
if (this._signedInUser && this._signedInUser.email != userData.email) {
throw new Error("Attempting to update to a different user.")
}
this._signedInUser = userData;
},
- logout: function() {
+ logout() {
// This will be called when sync fails (or when the account is being
// unlinked etc). It may have failed because we got a 401 from a sync
// server, so we nuke the token. Next time sync runs and wants an
// authentication header, we will notice the lack of the token and fetch a
// new one.
this._token = null;
},
- observe: function (subject, topic, data) {
+ observe(subject, topic, data) {
this._log.debug("observed " + topic);
switch (topic) {
case fxAccountsCommon.ONLOGIN_NOTIFICATION:
// This should only happen if we've been initialized without a current
// user - otherwise we'd have seen the LOGOUT notification and been
// thrown away.
// The exception is when we've initialized with a user that needs to
// reauth with the server - in that case we will also get here, but
@@ -333,44 +333,44 @@ this.BrowserIDManager.prototype = {
this._log.error("Error while fetching a new token", err));
break;
}
},
/**
* Compute the sha256 of the message bytes. Return bytes.
*/
- _sha256: function(message) {
+ _sha256(message) {
let hasher = Cc["@mozilla.org/security/hash;1"]
.createInstance(Ci.nsICryptoHash);
hasher.init(hasher.SHA256);
return CryptoUtils.digestBytes(message, hasher);
},
/**
* Compute the X-Client-State header given the byte string kB.
*
* Return string: hex(first16Bytes(sha256(kBbytes)))
*/
- _computeXClientState: function(kBbytes) {
+ _computeXClientState(kBbytes) {
return CommonUtils.bytesAsHex(this._sha256(kBbytes).slice(0, 16), false);
},
/**
* Provide override point for testing token expiration.
*/
- _now: function() {
+ _now() {
return this._fxaService.now()
},
get _localtimeOffsetMsec() {
return this._fxaService.localtimeOffsetMsec;
},
- usernameFromAccount: function(val) {
+ usernameFromAccount(val) {
// we don't differentiate between "username" and "account"
return val;
},
/**
* Obtains the HTTP Basic auth password.
*
* Returns a string if set or null if it is not set.
@@ -402,66 +402,65 @@ this.BrowserIDManager.prototype = {
if (this.syncKeyBundle) {
// TODO: This is probably fine because the code shouldn't be
// using the sync key directly (it should use the sync key
// bundle), but I don't like it. We should probably refactor
// code that is inspecting this to not do validation on this
// field directly and instead call a isSyncKeyValid() function
// that we can override.
return "99999999999999999999999999";
- }
- else {
+ } else {
return null;
}
},
set syncKey(value) {
throw "syncKey setter should be not used in BrowserIDManager";
},
get syncKeyBundle() {
return this._syncKeyBundle;
},
/**
* Resets/Drops all credentials we hold for the current user.
*/
- resetCredentials: function() {
+ resetCredentials() {
this.resetSyncKey();
this._token = null;
this._hashedUID = null;
// The cluster URL comes from the token, so resetting it to empty will
// force Sync to not accidentally use a value from an earlier token.
Weave.Service.clusterURL = null;
},
/**
* Resets/Drops the sync key we hold for the current user.
*/
- resetSyncKey: function() {
+ resetSyncKey() {
this._syncKey = null;
this._syncKeyBundle = null;
this._syncKeyUpdated = true;
this._shouldHaveSyncKeyBundle = false;
},
/**
* Pre-fetches any information that might help with migration away from this
* identity. Called after every sync and is really just an optimization that
* allows us to avoid a network request for when we actually need the
* migration info.
*/
- prefetchMigrationSentinel: function(service) {
+ prefetchMigrationSentinel(service) {
// nothing to do here until we decide to migrate away from FxA.
},
/**
* Return credentials hosts for this identity only.
*/
- _getSyncCredentialsHosts: function() {
+ _getSyncCredentialsHosts() {
return Utils.getSyncCredentialsHostsFxA();
},
/**
* The current state of the auth credentials.
*
* This essentially validates that enough credentials are available to use
* Sync. It doesn't check we have all the keys we need as the master-password
@@ -481,30 +480,30 @@ this.BrowserIDManager.prototype = {
return LOGIN_FAILED_NO_USERNAME;
}
return STATUS_OK;
},
// Do we currently have keys, or do we have enough that we should be able
// to successfully fetch them?
- _canFetchKeys: function() {
+ _canFetchKeys() {
let userData = this._signedInUser;
// a keyFetchToken means we can almost certainly grab them.
// kA and kB means we already have them.
return userData && (userData.keyFetchToken || (userData.kA && userData.kB));
},
/**
* Verify the current auth state, unlocking the master-password if necessary.
*
* Returns a promise that resolves with the current auth state after
* attempting to unlock.
*/
- unlockAndVerifyAuthState: function() {
+ unlockAndVerifyAuthState() {
if (this._canFetchKeys()) {
log.debug("unlockAndVerifyAuthState already has (or can fetch) sync keys");
return Promise.resolve(STATUS_OK);
}
// so no keys - ensure MP unlocked.
if (!Utils.ensureMPUnlocked()) {
// user declined to unlock, so we don't know if they are stored there.
log.debug("unlockAndVerifyAuthState: user declined to unlock master-password");
@@ -529,23 +528,23 @@ this.BrowserIDManager.prototype = {
}
);
},
/**
* Do we have a non-null, not yet expired token for the user currently
* signed in?
*/
- hasValidToken: function() {
+ hasValidToken() {
// If pref is set to ignore cached authentication credentials for debugging,
// then return false to force the fetching of a new token.
let ignoreCachedAuthCredentials = false;
try {
ignoreCachedAuthCredentials = Svc.Prefs.get("debug.ignoreCachedAuthCredentials");
- } catch(e) {
+ } catch (e) {
// Pref doesn't exist
}
if (ignoreCachedAuthCredentials) {
return false;
}
if (!this._token) {
return false;
}
@@ -568,17 +567,17 @@ this.BrowserIDManager.prototype = {
url = url.slice(0, -1);
}
return url;
},
// Refresh the sync token for our user. Returns a promise that resolves
// with a token (which may be null in one sad edge-case), or rejects with an
// error.
- _fetchTokenForUser: function() {
+ _fetchTokenForUser() {
// tokenServerURI is mis-named - convention is uri means nsISomething...
let tokenServerURI = this._tokenServerUrl;
let log = this._log;
let client = this._tokenServerClient;
let fxa = this._fxaService;
let userData = this._signedInUser;
// We need kA and kB for things to work. If we don't have them, just
@@ -602,17 +601,17 @@ this.BrowserIDManager.prototype = {
this._updateSignedInUser(userData); // throws if the user changed.
}
);
}
let getToken = assertion => {
log.debug("Getting a token");
let deferred = Promise.defer();
- let cb = function (err, token) {
+ let cb = function(err, token) {
if (err) {
return deferred.reject(err);
}
log.debug("Successfully got a sync token");
return deferred.resolve(token);
};
let kBbytes = CommonUtils.hexToBytes(userData.kB);
@@ -689,17 +688,17 @@ this.BrowserIDManager.prototype = {
this._shouldHaveSyncKeyBundle = true;
Weave.Status.login = this._authFailureReason;
throw err;
});
},
// Returns a promise that is resolved when we have a valid token for the
// current user stored in this._token. When resolved, this._token is valid.
- _ensureValidToken: function() {
+ _ensureValidToken() {
if (this.hasValidToken()) {
this._log.debug("_ensureValidToken already has one");
return Promise.resolve();
}
const notifyStateChanged =
() => Services.obs.notifyObservers(null, "weave:service:login:change", null);
// reset this._token as a safety net to reduce the possibility of us
// repeatedly attempting to use an invalid token if _fetchTokenForUser throws.
@@ -718,32 +717,32 @@ this.BrowserIDManager.prototype = {
},
error => {
notifyStateChanged();
throw error
}
);
},
- getResourceAuthenticator: function () {
+ getResourceAuthenticator() {
return this._getAuthenticationHeader.bind(this);
},
/**
* Obtain a function to be used for adding auth to RESTRequest instances.
*/
- getRESTRequestAuthenticator: function() {
+ getRESTRequestAuthenticator() {
return this._addAuthenticationHeader.bind(this);
},
/**
* @return a Hawk HTTP Authorization Header, lightly wrapped, for the .uri
* of a RESTRequest or AsyncResponse object.
*/
- _getAuthenticationHeader: function(httpObject, method) {
+ _getAuthenticationHeader(httpObject, method) {
let cb = Async.makeSpinningCallback();
this._ensureValidToken().then(cb, cb);
// Note that in failure states we return null, causing the request to be
// made without authorization headers, thereby presumably causing a 401,
// which causes Sync to log out. If we throw, this may not happen as
// expected.
try {
cb.wait();
@@ -763,33 +762,33 @@ this.BrowserIDManager.prototype = {
};
method = method || httpObject.method;
// Get the local clock offset from the Firefox Accounts server. This should
// be close to the offset from the storage server.
let options = {
now: this._now(),
localtimeOffsetMsec: this._localtimeOffsetMsec,
- credentials: credentials,
+ credentials,
};
let headerValue = CryptoUtils.computeHAWK(httpObject.uri, method, options);
return {headers: {authorization: headerValue.field}};
},
- _addAuthenticationHeader: function(request, method) {
+ _addAuthenticationHeader(request, method) {
let header = this._getAuthenticationHeader(request, method);
if (!header) {
return null;
}
request.setHeader("authorization", header.headers.authorization);
return request;
},
- createClusterManager: function(service) {
+ createClusterManager(service) {
return new BrowserIDClusterManager(service);
},
// Tell Sync what the login status should be if it saw a 401 fetching
// info/collections as part of login verification (typically immediately
// after login.)
// In our case, it almost certainly means a transient error fetching a token
// (and hitting this will cause us to logout, which will correctly handle an
@@ -804,17 +803,17 @@ this.BrowserIDManager.prototype = {
function BrowserIDClusterManager(service) {
ClusterManager.call(this, service);
}
BrowserIDClusterManager.prototype = {
__proto__: ClusterManager.prototype,
- _findCluster: function() {
+ _findCluster() {
let endPointFromIdentityToken = function() {
// The only reason (in theory ;) that we can end up with a null token
// is when this.identity._canFetchKeys() returned false. In turn, this
// should only happen if the master-password is locked or the credentials
// storage is screwed, and in those cases we shouldn't have started
// syncing so shouldn't get here anyway.
// But better safe than sorry! To keep things clearer, throw an explicit
// exception - the message will appear in the logs and the error will be
@@ -847,17 +846,17 @@ BrowserIDClusterManager.prototype = {
}
return this.identity._ensureValidToken();
}
).then(endPointFromIdentityToken
);
}.bind(this);
let cb = Async.makeSpinningCallback();
- promiseClusterURL().then(function (clusterURL) {
+ promiseClusterURL().then(function(clusterURL) {
cb(null, clusterURL);
}).then(
null, err => {
log.info("Failed to fetch the cluster URL", err);
// service.js's verifyLogin() method will attempt to fetch a cluster
// URL when it sees a 401. If it gets null, it treats it as a "real"
// auth error and sets Status.login to LOGIN_FAILED_LOGIN_REJECTED, which
// in turn causes a notification bar to appear informing the user they
@@ -875,17 +874,17 @@ BrowserIDClusterManager.prototype = {
} else {
// callback with an error - cb.wait() completes by raising an exception.
cb(err);
}
});
return cb.wait();
},
- getUserBaseURL: function() {
+ getUserBaseURL() {
// Legacy Sync and FxA Sync construct the userBaseURL differently. Legacy
// Sync appends path components onto an empty path, and in FxA Sync the
// token server constructs this for us in an opaque manner. Since the
// cluster manager already sets the clusterURL on Service and also has
// access to the current identity, we added this functionality here.
return this.service.clusterURL;
}
}
--- a/services/sync/modules/collection_validator.js
+++ b/services/sync/modules/collection_validator.js
@@ -158,17 +158,17 @@ class CollectionValidator {
for (let record of clientItems) {
let id = record[this.idProp];
record.shouldSync = this.syncedByClient(record);
seenClient.set(id, record);
let combined = allRecords.get(id);
if (combined) {
combined.client = record;
} else {
- allRecords.set(id, { client: record, server: null });
+ allRecords.set(id, { client: record, server: null });
}
}
for (let [id, { server, client }] of allRecords) {
if (!client && !server) {
throw new Error("Impossible: no client or server record for " + id);
} else if (server && !client) {
if (server.understood) {
--- a/services/sync/modules/engines.js
+++ b/services/sync/modules/engines.js
@@ -100,17 +100,17 @@ Tracker.prototype = {
},
set score(value) {
this._score = value;
Observers.notify("weave:engine:score:updated", this.name);
},
// Should be called by service everytime a sync has been done for an engine
- resetScore: function () {
+ resetScore() {
this._score = 0;
},
persistChangedIDs: true,
_saveChangedIDs() {
if (!this.persistChangedIDs) {
this._log.debug("Not saving changedIDs.");
@@ -118,34 +118,34 @@ Tracker.prototype = {
}
this._storage.saveSoon();
},
// ignore/unignore specific IDs. Useful for ignoring items that are
// being processed, or that shouldn't be synced.
// But note: not persisted to disk
- ignoreID: function (id) {
+ ignoreID(id) {
this.unignoreID(id);
this._ignored.push(id);
},
- unignoreID: function (id) {
+ unignoreID(id) {
let index = this._ignored.indexOf(id);
if (index != -1)
this._ignored.splice(index, 1);
},
_saveChangedID(id, when) {
this._log.trace(`Adding changed ID: ${id}, ${JSON.stringify(when)}`);
this.changedIDs[id] = when;
this._saveChangedIDs();
},
- addChangedID: function (id, when) {
+ addChangedID(id, when) {
if (!id) {
this._log.warn("Attempted to add undefined ID to tracker");
return false;
}
if (this.ignoreAll || this._ignored.includes(id)) {
return false;
}
@@ -158,17 +158,17 @@ Tracker.prototype = {
// Add/update the entry if we have a newer time.
if ((this.changedIDs[id] || -Infinity) < when) {
this._saveChangedID(id, when);
}
return true;
},
- removeChangedID: function (...ids) {
+ removeChangedID(...ids) {
if (!ids.length || this.ignoreAll) {
return false;
}
for (let id of ids) {
if (!id) {
this._log.warn("Attempted to remove undefined ID from tracker");
continue;
}
@@ -180,59 +180,59 @@ Tracker.prototype = {
this._log.trace("Removing changed ID " + id);
delete this.changedIDs[id];
}
}
this._saveChangedIDs();
return true;
},
- clearChangedIDs: function () {
+ clearChangedIDs() {
this._log.trace("Clearing changed ID list");
this._storage.data = {};
this._saveChangedIDs();
},
_now() {
return Date.now() / 1000;
},
_isTracking: false,
// Override these in your subclasses.
- startTracking: function () {
+ startTracking() {
},
- stopTracking: function () {
+ stopTracking() {
},
- engineIsEnabled: function () {
+ engineIsEnabled() {
if (!this.engine) {
// Can't tell -- we must be running in a test!
return true;
}
return this.engine.enabled;
},
- onEngineEnabledChanged: function (engineEnabled) {
+ onEngineEnabledChanged(engineEnabled) {
if (engineEnabled == this._isTracking) {
return;
}
if (engineEnabled) {
this.startTracking();
this._isTracking = true;
} else {
this.stopTracking();
this._isTracking = false;
this.clearChangedIDs();
}
},
- observe: function (subject, topic, data) {
+ observe(subject, topic, data) {
switch (topic) {
case "weave:engine:start-tracking":
if (!this.engineIsEnabled()) {
return;
}
this._log.trace("Got start-tracking.");
if (!this._isTracking) {
this.startTracking();
@@ -245,17 +245,17 @@ Tracker.prototype = {
this.stopTracking();
this._isTracking = false;
}
return;
case "nsPref:changed":
if (data == PREFS_BRANCH + "engine." + this.engine.prefName) {
this.onEngineEnabledChanged(this.engine.enabled);
}
- return;
+
}
}
};
/**
* The Store serves as the interface between Sync and stored data.
@@ -312,17 +312,17 @@ Store.prototype = {
*
* The default implementation simply iterates over all records and calls
* applyIncoming(). Store implementations may overwrite this function
* if desired.
*
* @param records Array of records to apply
* @return Array of record IDs which did not apply cleanly
*/
- applyIncomingBatch: function (records) {
+ applyIncomingBatch(records) {
let failed = [];
for (let record of records) {
try {
this.applyIncoming(record);
} catch (ex) {
if (ex.code == Engine.prototype.eEngineAbortApplyIncoming) {
// This kind of exception should have a 'cause' attribute, which is an
// originating exception.
@@ -331,34 +331,34 @@ Store.prototype = {
}
if (Async.isShutdownException(ex)) {
throw ex;
}
this._log.warn("Failed to apply incoming record " + record.id, ex);
this.engine._noteApplyFailure();
failed.push(record.id);
}
- };
+ }
return failed;
},
/**
* Apply a single record against the store.
*
* This takes a single record and makes the local changes required so the
* local state matches what's in the record.
*
* The default implementation calls one of remove(), create(), or update()
* depending on the state obtained from the store itself. Store
* implementations may overwrite this function if desired.
*
* @param record
* Record to apply
*/
- applyIncoming: function (record) {
+ applyIncoming(record) {
if (record.deleted)
this.remove(record);
else if (!this.itemExists(record.id))
this.create(record);
else
this.update(record);
},
@@ -368,57 +368,57 @@ Store.prototype = {
* Create an item in the store from a record.
*
* This is called by the default implementation of applyIncoming(). If using
* applyIncomingBatch(), this won't be called unless your store calls it.
*
* @param record
* The store record to create an item from
*/
- create: function (record) {
+ create(record) {
throw "override create in a subclass";
},
/**
* Remove an item in the store from a record.
*
* This is called by the default implementation of applyIncoming(). If using
* applyIncomingBatch(), this won't be called unless your store calls it.
*
* @param record
* The store record to delete an item from
*/
- remove: function (record) {
+ remove(record) {
throw "override remove in a subclass";
},
/**
* Update an item from a record.
*
* This is called by the default implementation of applyIncoming(). If using
* applyIncomingBatch(), this won't be called unless your store calls it.
*
* @param record
* The record to use to update an item from
*/
- update: function (record) {
+ update(record) {
throw "override update in a subclass";
},
/**
* Determine whether a record with the specified ID exists.
*
* Takes a string record ID and returns a booleans saying whether the record
* exists.
*
* @param id
* string record ID
* @return boolean indicating whether record exists locally
*/
- itemExists: function (id) {
+ itemExists(id) {
throw "override itemExists in a subclass";
},
/**
* Create a record from the specified ID.
*
* If the ID is known, the record should be populated with metadata from
* the store. If the ID is not known, the record should be created with the
@@ -426,69 +426,69 @@ Store.prototype = {
*
* @param id
* string record ID
* @param collection
* Collection to add record to. This is typically passed into the
* constructor for the newly-created record.
* @return record type for this engine
*/
- createRecord: function (id, collection) {
+ createRecord(id, collection) {
throw "override createRecord in a subclass";
},
/**
* Change the ID of a record.
*
* @param oldID
* string old/current record ID
* @param newID
* string new record ID
*/
- changeItemID: function (oldID, newID) {
+ changeItemID(oldID, newID) {
throw "override changeItemID in a subclass";
},
/**
* Obtain the set of all known record IDs.
*
* @return Object with ID strings as keys and values of true. The values
* are ignored.
*/
- getAllIDs: function () {
+ getAllIDs() {
throw "override getAllIDs in a subclass";
},
/**
* Wipe all data in the store.
*
* This function is called during remote wipes or when replacing local data
* with remote data.
*
* This function should delete all local data that the store is managing. It
* can be thought of as clearing out all state and restoring the "new
* browser" state.
*/
- wipe: function () {
+ wipe() {
throw "override wipe in a subclass";
}
};
this.EngineManager = function EngineManager(service) {
this.service = service;
this._engines = {};
// This will be populated by Service on startup.
this._declined = new Set();
this._log = Log.repository.getLogger("Sync.EngineManager");
this._log.level = Log.Level[Svc.Prefs.get("log.logger.service.engines", "Debug")];
}
EngineManager.prototype = {
- get: function (name) {
+ get(name) {
// Return an array of engines if we have an array of names
if (Array.isArray(name)) {
let engines = [];
name.forEach(function(name) {
let engine = this.get(name);
if (engine) {
engines.push(engine);
}
@@ -501,80 +501,80 @@ EngineManager.prototype = {
this._log.debug("Could not get engine: " + name);
if (Object.keys) {
this._log.debug("Engines are: " + JSON.stringify(Object.keys(this._engines)));
}
}
return engine;
},
- getAll: function () {
+ getAll() {
let engines = [];
for (let [, engine] of Object.entries(this._engines)) {
engines.push(engine);
}
return engines;
},
/**
* N.B., does not pay attention to the declined list.
*/
- getEnabled: function () {
+ getEnabled() {
return this.getAll()
.filter((engine) => engine.enabled)
.sort((a, b) => a.syncPriority - b.syncPriority);
},
get enabledEngineNames() {
return this.getEnabled().map(e => e.name);
},
- persistDeclined: function () {
+ persistDeclined() {
Svc.Prefs.set("declinedEngines", [...this._declined].join(","));
},
/**
* Returns an array.
*/
- getDeclined: function () {
+ getDeclined() {
return [...this._declined];
},
- setDeclined: function (engines) {
+ setDeclined(engines) {
this._declined = new Set(engines);
this.persistDeclined();
},
- isDeclined: function (engineName) {
+ isDeclined(engineName) {
return this._declined.has(engineName);
},
/**
* Accepts a Set or an array.
*/
- decline: function (engines) {
+ decline(engines) {
for (let e of engines) {
this._declined.add(e);
}
this.persistDeclined();
},
- undecline: function (engines) {
+ undecline(engines) {
for (let e of engines) {
this._declined.delete(e);
}
this.persistDeclined();
},
/**
* Mark any non-enabled engines as declined.
*
* This is useful after initial customization during setup.
*/
- declineDisabled: function () {
+ declineDisabled() {
for (let e of this.getAll()) {
if (!e.enabled) {
this._log.debug("Declining disabled engine " + e.name);
this._declined.add(e.name);
}
}
this.persistDeclined();
},
@@ -582,17 +582,17 @@ EngineManager.prototype = {
/**
* Register an Engine to the service. Alternatively, give an array of engine
* objects to register.
*
* @param engineObject
* Engine object used to get an instance of the engine
* @return The engine object if anything failed
*/
- register: function (engineObject) {
+ register(engineObject) {
if (Array.isArray(engineObject)) {
return engineObject.map(this.register, this);
}
try {
let engine = new engineObject(this.service);
let name = engine.name;
if (name in this._engines) {
@@ -605,25 +605,25 @@ EngineManager.prototype = {
name = name.prototype || "";
name = name.name || "";
this._log.error(`Could not initialize engine ${name}`, ex);
return engineObject;
}
},
- unregister: function (val) {
+ unregister(val) {
let name = val;
if (val instanceof Engine) {
name = val.name;
}
delete this._engines[name];
},
- clear: function () {
+ clear() {
for (let name in this._engines) {
delete this._engines[name];
}
},
};
this.Engine = function Engine(name, service) {
if (!service) {
@@ -680,58 +680,58 @@ Engine.prototype = {
},
get _tracker() {
let tracker = new this._trackerObj(this.Name, this);
this.__defineGetter__("_tracker", () => tracker);
return tracker;
},
- sync: function () {
+ sync() {
if (!this.enabled) {
return;
}
if (!this._sync) {
throw "engine does not implement _sync method";
}
this._notify("sync", this.name, this._sync)();
},
/**
* Get rid of any local meta-data.
*/
- resetClient: function () {
+ resetClient() {
if (!this._resetClient) {
throw "engine does not implement _resetClient method";
}
this._notify("reset-client", this.name, this._resetClient)();
},
- _wipeClient: function () {
+ _wipeClient() {
this.resetClient();
this._log.debug("Deleting all local data");
this._tracker.ignoreAll = true;
this._store.wipe();
this._tracker.ignoreAll = false;
this._tracker.clearChangedIDs();
},
- wipeClient: function () {
+ wipeClient() {
this._notify("wipe-client", this.name, this._wipeClient)();
},
/**
* If one exists, initialize and return a validator for this engine (which
* must have a `validate(engine)` method that returns a promise to an object
* with a getSummary method). Otherwise return null.
*/
- getValidator: function () {
+ getValidator() {
return null;
}
};
this.SyncEngine = function SyncEngine(name, service) {
Engine.call(this, name || "SyncEngine", service);
this.loadToFetch();
@@ -805,17 +805,17 @@ SyncEngine.prototype = {
return parseFloat(Svc.Prefs.get(this.name + ".lastSync", "0"));
},
set lastSync(value) {
// Reset the pref in-case it's a number instead of a string
Svc.Prefs.reset(this.name + ".lastSync");
// Store the value as a string to keep floating point precision
Svc.Prefs.set(this.name + ".lastSync", value.toString());
},
- resetLastSync: function () {
+ resetLastSync() {
this._log.debug("Resetting " + this.name + " last sync time");
Svc.Prefs.reset(this.name + ".lastSync");
Svc.Prefs.set(this.name + ".lastSync", "0");
this.lastSyncLocal = 0;
},
get toFetch() {
return this._toFetch;
@@ -826,22 +826,22 @@ SyncEngine.prototype = {
this._log.error("Failed to read JSON records to fetch", error);
}
}
// Coerce the array to a string for more efficient comparison.
if (val + "" == this._toFetch) {
return;
}
this._toFetch = val;
- Utils.namedTimer(function () {
+ Utils.namedTimer(function() {
Utils.jsonSave("toFetch/" + this.name, this, val, cb);
}, 0, this, "_toFetchDelay");
},
- loadToFetch: function () {
+ loadToFetch() {
// Initialize to empty if there's no file.
this._toFetch = [];
Utils.jsonLoad("toFetch/" + this.name, this, function(toFetch) {
if (toFetch) {
this._toFetch = toFetch;
}
});
},
@@ -857,22 +857,22 @@ SyncEngine.prototype = {
this._log.debug("Successfully wrote previousFailed.");
}
}
// Coerce the array to a string for more efficient comparison.
if (val + "" == this._previousFailed) {
return;
}
this._previousFailed = val;
- Utils.namedTimer(function () {
+ Utils.namedTimer(function() {
Utils.jsonSave("failed/" + this.name, this, val, cb);
}, 0, this, "_previousFailedDelay");
},
- loadPreviousFailed: function () {
+ loadPreviousFailed() {
// Initialize to empty if there's no file
this._previousFailed = [];
Utils.jsonLoad("failed/" + this.name, this, function(previousFailed) {
if (previousFailed) {
this._previousFailed = previousFailed;
}
});
},
@@ -887,30 +887,30 @@ SyncEngine.prototype = {
// Store as a string because pref can only store C longs as numbers.
Svc.Prefs.set(this.name + ".lastSyncLocal", value.toString());
},
/*
* Returns a changeset for this sync. Engine implementations can override this
* method to bypass the tracker for certain or all changed items.
*/
- getChangedIDs: function () {
+ getChangedIDs() {
return this._tracker.changedIDs;
},
// Create a new record using the store and add in crypto fields.
- _createRecord: function (id) {
+ _createRecord(id) {
let record = this._store.createRecord(id, this.name);
record.id = id;
record.collection = this.name;
return record;
},
// Any setup that needs to happen at the beginning of each sync.
- _syncStartup: function () {
+ _syncStartup() {
// Determine if we need to wipe on outdated versions
let metaGlobal = this.service.recordManager.get(this.metaURL);
let engines = metaGlobal.payload.engines || {};
let engineData = engines[this.name] || {};
let needsWipe = false;
@@ -937,17 +937,17 @@ SyncEngine.prototype = {
error.failureCode = VERSION_OUT_OF_DATE;
throw error;
}
// Changes to syncID mean we'll need to upload everything
else if (engineData.syncID != this.syncID) {
this._log.debug("Engine syncIDs: " + [engineData.syncID, this.syncID]);
this.syncID = engineData.syncID;
this._resetClient();
- };
+ }
// Delete any existing data and reupload on bad version or missing meta.
// No crypto component here...? We could regenerate per-collection keys...
if (needsWipe) {
this.wipeServer();
}
// Save objects that need to be uploaded in this._modified. We also save
@@ -973,26 +973,26 @@ SyncEngine.prototype = {
// Keep track of what to delete at the end of sync
this._delete = {};
},
/**
* A tiny abstraction to make it easier to test incoming record
* application.
*/
- itemSource: function () {
+ itemSource() {
return new Collection(this.engineURL, this._recordObj, this.service);
},
/**
* Process incoming records.
* In the most awful and untestable way possible.
* This now accepts something that makes testing vaguely less impossible.
*/
- _processIncoming: function (newitems) {
+ _processIncoming(newitems) {
this._log.trace("Downloading & applying server changes");
// Figure out how many total items to fetch this sync; do less on mobile.
let batchSize = this.downloadLimit || Infinity;
let isMobile = (Svc.Prefs.get("client.type") == "mobile");
if (!newitems) {
newitems = this.itemSource();
@@ -1276,45 +1276,45 @@ SyncEngine.prototype = {
// Indicates whether an incoming item should be deleted from the server at
// the end of the sync. Engines can override this method to clean up records
// that shouldn't be on the server.
_shouldDeleteRemotely(remoteItem) {
return false;
},
- _noteApplyFailure: function () {
+ _noteApplyFailure() {
// here would be a good place to record telemetry...
},
- _noteApplyNewFailure: function () {
+ _noteApplyNewFailure() {
// here would be a good place to record telemetry...
},
/**
* Find a GUID of an item that is a duplicate of the incoming item but happens
* to have a different GUID
*
* @return GUID of the similar item; falsy otherwise
*/
- _findDupe: function (item) {
+ _findDupe(item) {
// By default, assume there's no dupe items for the engine
},
// Called when the server has a record marked as deleted, but locally we've
// changed it more recently than the deletion. If we return false, the
// record will be deleted locally. If we return true, we'll reupload the
// record to the server -- any extra work that's needed as part of this
// process should be done at this point (such as mark the record's parent
// for reuploading in the case of bookmarks).
_shouldReviveRemotelyDeletedRecord(remoteItem) {
return true;
},
- _deleteId: function (id) {
+ _deleteId(id) {
this._tracker.removeChangedID(id);
this._noteDeletedId(id);
},
// Marks an ID for deletion at the end of the sync.
_noteDeletedId(id) {
if (this._delete.ids == null)
this._delete.ids = [id];
@@ -1339,17 +1339,17 @@ SyncEngine.prototype = {
*
* This function essentially determines whether to apply an incoming record.
*
* @param item
* Record from server to be tested for application.
* @return boolean
* Truthy if incoming record should be applied. False if not.
*/
- _reconcile: function (item) {
+ _reconcile(item) {
if (this._log.level <= Log.Level.Trace) {
this._log.trace("Incoming: " + item);
}
// We start reconciling by collecting a bunch of state. We do this here
// because some state may change during the course of this function and we
// need to operate on the original values.
let existsLocally = this._store.itemExists(item.id);
@@ -1507,17 +1507,17 @@ SyncEngine.prototype = {
// result in data loss and should be handled by giving the engine an
// opportunity to merge the records. Bug 720592 tracks this feature.
this._log.warn("DATA LOSS: Both local and remote changes to record: " +
item.id);
return remoteIsNewer;
},
// Upload outgoing records.
- _uploadOutgoing: function () {
+ _uploadOutgoing() {
this._log.trace("Uploading local changes to server.");
let modifiedIDs = this._modified.ids();
if (modifiedIDs.length) {
this._log.trace("Preparing " + modifiedIDs.length +
" outgoing records");
let counts = { sent: modifiedIDs.length, failed: 0 };
@@ -1607,17 +1607,17 @@ SyncEngine.prototype = {
_onRecordsWritten(succeeded, failed) {
// Implement this method to take specific actions against successfully
// uploaded records and failed records.
},
// Any cleanup necessary.
// Save the current snapshot so as to calculate changes at next sync
- _syncFinish: function () {
+ _syncFinish() {
this._log.trace("Finishing up sync");
this._tracker.resetScore();
let doDelete = Utils.bind2(this, function(key, val) {
let coll = new Collection(this.engineURL, this._recordObj, this.service);
coll[key] = val;
coll.delete();
});
@@ -1634,87 +1634,87 @@ SyncEngine.prototype = {
while (val.length > 0) {
doDelete(key, val.slice(0, 100));
val = val.slice(100);
}
}
}
},
- _syncCleanup: function () {
+ _syncCleanup() {
if (!this._modified) {
return;
}
try {
// Mark failed WBOs as changed again so they are reuploaded next time.
this.trackRemainingChanges();
} finally {
this._modified.clear();
}
},
- _sync: function () {
+ _sync() {
try {
this._syncStartup();
Observers.notify("weave:engine:sync:status", "process-incoming");
this._processIncoming();
Observers.notify("weave:engine:sync:status", "upload-outgoing");
this._uploadOutgoing();
this._syncFinish();
} finally {
this._syncCleanup();
}
},
- canDecrypt: function () {
+ canDecrypt() {
// Report failure even if there's nothing to decrypt
let canDecrypt = false;
// Fetch the most recently uploaded record and try to decrypt it
let test = new Collection(this.engineURL, this._recordObj, this.service);
test.limit = 1;
test.sort = "newest";
test.full = true;
let key = this.service.collectionKeys.keyForCollection(this.name);
test.recordHandler = function recordHandler(record) {
record.decrypt(key);
canDecrypt = true;
- }.bind(this);
+ };
// Any failure fetching/decrypting will just result in false
try {
this._log.trace("Trying to decrypt a record from the server..");
test.get();
} catch (ex) {
if (Async.isShutdownException(ex)) {
throw ex;
}
this._log.debug("Failed test decrypt", ex);
}
return canDecrypt;
},
- _resetClient: function () {
+ _resetClient() {
this.resetLastSync();
this.previousFailed = [];
this.toFetch = [];
},
- wipeServer: function () {
+ wipeServer() {
let response = this.service.resource(this.engineURL).delete();
if (response.status != 200 && response.status != 404) {
throw response;
}
this._resetClient();
},
- removeClientData: function () {
+ removeClientData() {
// Implement this method in engines that store client specific data
// on the server.
},
/*
* Decide on (and partially effect) an error-handling strategy.
*
* Asks the Service to respond to an HMAC error, which might result in keys
@@ -1725,17 +1725,17 @@ SyncEngine.prototype = {
* handleHMACMismatch returns kRecoveryStrategy.retry. Otherwise, it returns
* kRecoveryStrategy.error.
*
* Subclasses of SyncEngine can override this method to allow for different
* behavior -- e.g., to delete and ignore erroneous entries.
*
* All return values will be part of the kRecoveryStrategy enumeration.
*/
- handleHMACMismatch: function (item, mayRetry) {
+ handleHMACMismatch(item, mayRetry) {
// By default we either try again, or bail out noisily.
return (this.service.handleHMACEvent() && mayRetry) ?
SyncEngine.kRecoveryStrategy.retry :
SyncEngine.kRecoveryStrategy.error;
},
/**
* Returns a changeset containing all items in the store. The default
--- a/services/sync/modules/engines/addons.js
+++ b/services/sync/modules/engines/addons.js
@@ -498,17 +498,17 @@ AddonsStore.prototype = {
continue;
}
this._log.info("Uninstalling add-on as part of wipe: " + addon.id);
Utils.catch.call(this, () => addon.uninstall())();
}
},
- /***************************************************************************
+ /** *************************************************************************
* Functions below are unique to this store and not part of the Store API *
***************************************************************************/
/**
* Synchronously obtain an add-on from its public ID.
*
* @param id
* Add-on ID
@@ -727,25 +727,25 @@ AddonsTracker.prototype = {
addon.id);
return;
}
this.addChangedID(addon.guid, date.getTime() / 1000);
this.score += SCORE_INCREMENT_XLARGE;
},
- startTracking: function() {
+ startTracking() {
if (this.engine.enabled) {
this.reconciler.startListening();
}
this.reconciler.addChangeListener(this);
},
- stopTracking: function() {
+ stopTracking() {
this.reconciler.removeChangeListener(this);
this.reconciler.stopListening();
},
};
class AddonValidator extends CollectionValidator {
constructor(engine = null) {
super("addons", "id", [
--- a/services/sync/modules/engines/bookmarks.js
+++ b/services/sync/modules/engines/bookmarks.js
@@ -307,17 +307,17 @@ BookmarksEngine.prototype = {
},
_guidMapFailed: false,
_buildGUIDMap: function _buildGUIDMap() {
let store = this._store;
let guidMap = {};
let tree = Async.promiseSpinningly(PlacesUtils.promiseBookmarksTree(""));
- function* walkBookmarksTree(tree, parent=null) {
+ function* walkBookmarksTree(tree, parent = null) {
if (tree) {
// Skip root node
if (parent) {
yield [tree, parent];
}
if (tree.children) {
for (let child of tree.children) {
store._sleep(0); // avoid jank while looping.
@@ -357,17 +357,17 @@ BookmarksEngine.prototype = {
// Folder
key = "f" + (node.title || "");
break;
case PlacesUtils.TYPE_X_MOZ_PLACE_SEPARATOR:
// Separator
key = "s" + node.index;
break;
default:
- this._log.error("Unknown place type: '"+placeType+"'");
+ this._log.error("Unknown place type: '" + placeType + "'");
continue;
}
let parentName = parent.title || "";
if (guidMap[parentName] == null)
guidMap[parentName] = {};
// If the entry already exists, remember that there are explicit dupes.
@@ -517,17 +517,17 @@ BookmarksEngine.prototype = {
let newChanges = Async.promiseSpinningly(PlacesSyncUtils.bookmarks.touch(item.id));
if (newChanges) {
this._modified.insert(newChanges);
return true;
}
return false;
},
- _processIncoming: function (newitems) {
+ _processIncoming(newitems) {
try {
SyncEngine.prototype._processIncoming.call(this, newitems);
} finally {
try {
this._deletePending();
} finally {
// Reorder children.
this._store._orderChildren();
@@ -780,17 +780,17 @@ BookmarksStore.prototype = {
record.fromSyncBookmark(item);
record.sortindex = this._calculateIndex(record);
return record;
},
_stmts: {},
- _getStmt: function(query) {
+ _getStmt(query) {
if (query in this._stmts) {
return this._stmts[query];
}
this._log.trace("Creating SQL statement: " + query);
let db = PlacesUtils.history.QueryInterface(Ci.nsPIPlacesDatabase)
.DBConnection;
return this._stmts[query] = db.createAsyncStatement(query);
@@ -861,38 +861,38 @@ function BookmarksTracker(name, engine)
this._migratedOldEntries = false;
Tracker.call(this, name, engine);
Svc.Obs.add("places-shutdown", this);
}
BookmarksTracker.prototype = {
__proto__: Tracker.prototype,
- //`_ignore` checks the change source for each observer notification, so we
+ // `_ignore` checks the change source for each observer notification, so we
// don't want to let the engine ignore all changes during a sync.
get ignoreAll() {
return false;
},
// Define an empty setter so that the engine doesn't throw a `TypeError`
// setting a read-only property.
set ignoreAll(value) {},
// We never want to persist changed IDs, as the changes are already stored
// in Places.
persistChangedIDs: false,
- startTracking: function() {
+ startTracking() {
PlacesUtils.bookmarks.addObserver(this, true);
Svc.Obs.add("bookmarks-restore-begin", this);
Svc.Obs.add("bookmarks-restore-success", this);
Svc.Obs.add("bookmarks-restore-failed", this);
},
- stopTracking: function() {
+ stopTracking() {
PlacesUtils.bookmarks.removeObserver(this);
Svc.Obs.remove("bookmarks-restore-begin", this);
Svc.Obs.remove("bookmarks-restore-success", this);
Svc.Obs.remove("bookmarks-restore-failed", this);
},
// Ensure we aren't accidentally using the base persistence.
addChangedID(id, when) {
@@ -1013,17 +1013,17 @@ BookmarksTracker.prototype = {
if (IGNORED_SOURCES.includes(source)) {
return;
}
this._log.trace("onItemAdded: " + itemId);
this._upScore();
},
- onItemRemoved: function (itemId, parentId, index, type, uri,
+ onItemRemoved(itemId, parentId, index, type, uri,
guid, parentGuid, source) {
if (IGNORED_SOURCES.includes(source)) {
return;
}
this._log.trace("onItemRemoved: " + itemId);
this._upScore();
},
@@ -1090,43 +1090,43 @@ BookmarksTracker.prototype = {
// Ignore annotations except for the ones that we sync.
return;
// Ignore favicon changes to avoid unnecessary churn.
if (property == "favicon")
return;
this._log.trace("onItemChanged: " + itemId +
- (", " + property + (isAnno? " (anno)" : "")) +
+ (", " + property + (isAnno ? " (anno)" : "")) +
(value ? (" = \"" + value + "\"") : ""));
this._upScore();
},
onItemMoved: function BMT_onItemMoved(itemId, oldParent, oldIndex,
newParent, newIndex, itemType,
guid, oldParentGuid, newParentGuid,
source) {
if (IGNORED_SOURCES.includes(source)) {
return;
}
this._log.trace("onItemMoved: " + itemId);
this._upScore();
},
- onBeginUpdateBatch: function () {
+ onBeginUpdateBatch() {
++this._batchDepth;
},
- onEndUpdateBatch: function () {
+ onEndUpdateBatch() {
if (--this._batchDepth === 0 && this._batchSawScoreIncrement) {
this.score += SCORE_INCREMENT_XLARGE;
this._batchSawScoreIncrement = false;
}
},
- onItemVisited: function () {}
+ onItemVisited() {}
};
class BookmarksChangeset extends Changeset {
getModifiedTimestamp(id) {
let change = this.changes[id];
if (!change || change.synced) {
// Pretend the change doesn't exist if we've already synced or
// reconciled it.
--- a/services/sync/modules/engines/clients.js
+++ b/services/sync/modules/engines/clients.js
@@ -485,18 +485,18 @@ ClientEngine.prototype = {
if (!client) {
throw new Error("Unknown remote client ID: '" + clientId + "'.");
}
if (client.stale) {
throw new Error("Stale remote client ID: '" + clientId + "'.");
}
let action = {
- command: command,
- args: args,
+ command,
+ args,
flowID: flowID || Utils.makeGUID(), // used for telemetry.
};
if (this._addClientCommand(clientId, action)) {
this._log.trace(`Client ${clientId} got a new action`, [command, args]);
this._tracker.addChangedID(clientId);
let deviceID;
try {
@@ -700,17 +700,17 @@ ClientStore.prototype = {
[];
// Package the individual components into a record for the local client
if (id == this.engine.localID) {
let cb = Async.makeSpinningCallback();
fxAccounts.getDeviceId().then(id => cb(null, id), cb);
try {
record.fxaDeviceId = cb.wait();
- } catch(error) {
+ } catch (error) {
this._log.warn("failed to get fxa device id", error);
}
record.name = this.engine.localName;
record.type = this.engine.localType;
record.version = Services.appinfo.version;
record.protocols = SUPPORTED_PROTOCOL_VERSIONS;
// Substract the commands we recorded that we've already executed
--- a/services/sync/modules/engines/extension-storage.js
+++ b/services/sync/modules/engines/extension-storage.js
@@ -38,17 +38,17 @@ ExtensionStorageEngine.prototype = {
_trackerObj: ExtensionStorageTracker,
// we don't need these since we implement our own sync logic
_storeObj: undefined,
_recordObj: undefined,
syncPriority: 10,
allowSkippedRecord: false,
- _sync: function () {
+ _sync() {
return Async.promiseSpinningly(ExtensionStorageSync.syncAll());
},
get enabled() {
// By default, we sync extension storage if we sync addons. This
// lets us simplify the UX since users probably don't consider
// "extension preferences" a separate category of syncing.
// However, we also respect engine.extension-storage.force, which
@@ -63,25 +63,25 @@ ExtensionStorageEngine.prototype = {
};
function ExtensionStorageTracker(name, engine) {
Tracker.call(this, name, engine);
}
ExtensionStorageTracker.prototype = {
__proto__: Tracker.prototype,
- startTracking: function () {
+ startTracking() {
Svc.Obs.add("ext.storage.sync-changed", this);
},
- stopTracking: function () {
+ stopTracking() {
Svc.Obs.remove("ext.storage.sync-changed", this);
},
- observe: function (subject, topic, data) {
+ observe(subject, topic, data) {
Tracker.prototype.observe.call(this, subject, topic, data);
if (this.ignoreAll) {
return;
}
if (topic !== "ext.storage.sync-changed") {
return;
@@ -89,25 +89,25 @@ ExtensionStorageTracker.prototype = {
// Single adds, removes and changes are not so important on their
// own, so let's just increment score a bit.
this.score += SCORE_INCREMENT_MEDIUM;
},
// Override a bunch of methods which don't do anything for us.
// This is a performance hack.
- ignoreID: function() {
+ ignoreID() {
},
- unignoreID: function() {
+ unignoreID() {
},
- addChangedID: function() {
+ addChangedID() {
},
- removeChangedID: function() {
+ removeChangedID() {
},
- clearChangedIDs: function() {
+ clearChangedIDs() {
},
};
/**
* Utility function to enforce an order of fields when computing an HMAC.
*/
function ciphertextHMAC(keyBundle, id, IV, ciphertext) {
const hasher = keyBundle.sha256HMACHasher;
@@ -212,17 +212,17 @@ class KeyRingEncryptionRemoteTransformer
if (!user.kB) {
throw new Error("user doesn't have kB");
}
let kB = Utils.hexToBytes(user.kB);
let keyMaterial = CryptoUtils.hkdf(kB, undefined,
- "identity.mozilla.com/picl/v1/chrome.storage.sync", 2*32);
+ "identity.mozilla.com/picl/v1/chrome.storage.sync", 2 * 32);
let bundle = new BulkKeyBundle();
// [encryptionKey, hmacKey]
bundle.keyPair = [keyMaterial.slice(0, 32), keyMaterial.slice(32, 64)];
return bundle;
});
}
// Pass through the kbHash field from the unencrypted record. If
// encryption fails, we can use this to try to detect whether we are
--- a/services/sync/modules/engines/forms.js
+++ b/services/sync/modules/engines/forms.js
@@ -32,71 +32,71 @@ Utils.deferGetSet(FormRec, "cleartext",
var FormWrapper = {
_log: Log.repository.getLogger("Sync.Engine.Forms"),
_getEntryCols: ["fieldname", "value"],
_guidCols: ["guid"],
- _promiseSearch: function(terms, searchData) {
+ _promiseSearch(terms, searchData) {
return new Promise(resolve => {
let results = [];
let callbacks = {
handleResult(result) {
results.push(result);
},
handleCompletion(reason) {
resolve(results);
}
};
Svc.FormHistory.search(terms, searchData, callbacks);
})
},
// Do a "sync" search by spinning the event loop until it completes.
- _searchSpinningly: function(terms, searchData) {
+ _searchSpinningly(terms, searchData) {
return Async.promiseSpinningly(this._promiseSearch(terms, searchData));
},
- _updateSpinningly: function(changes) {
+ _updateSpinningly(changes) {
if (!Svc.FormHistory.enabled) {
return; // update isn't going to do anything.
}
let cb = Async.makeSpinningCallback();
let callbacks = {
- handleCompletion: function(reason) {
+ handleCompletion(reason) {
cb();
}
};
Svc.FormHistory.update(changes, callbacks);
return cb.wait();
},
- getEntry: function (guid) {
- let results = this._searchSpinningly(this._getEntryCols, {guid: guid});
+ getEntry(guid) {
+ let results = this._searchSpinningly(this._getEntryCols, {guid});
if (!results.length) {
return null;
}
return {name: results[0].fieldname, value: results[0].value};
},
- getGUID: function (name, value) {
+ getGUID(name, value) {
// Query for the provided entry.
- let query = { fieldname: name, value: value };
+ let query = { fieldname: name, value };
let results = this._searchSpinningly(this._guidCols, query);
return results.length ? results[0].guid : null;
},
- hasGUID: function (guid) {
+ hasGUID(guid) {
// We could probably use a count function here, but searchSpinningly exists...
- return this._searchSpinningly(this._guidCols, {guid: guid}).length != 0;
+ return this._searchSpinningly(this._guidCols, {guid}).length != 0;
},
- replaceGUID: function (oldGUID, newGUID) {
+ replaceGUID(oldGUID, newGUID) {
let changes = {
op: "update",
guid: oldGUID,
newGuid: newGUID,
}
this._updateSpinningly(changes);
}
@@ -124,92 +124,92 @@ FormEngine.prototype = {
};
function FormStore(name, engine) {
Store.call(this, name, engine);
}
FormStore.prototype = {
__proto__: Store.prototype,
- _processChange: function (change) {
+ _processChange(change) {
// If this._changes is defined, then we are applying a batch, so we
// can defer it.
if (this._changes) {
this._changes.push(change);
return;
}
// Otherwise we must handle the change synchronously, right now.
FormWrapper._updateSpinningly(change);
},
- applyIncomingBatch: function (records) {
+ applyIncomingBatch(records) {
// We collect all the changes to be made then apply them all at once.
this._changes = [];
let failures = Store.prototype.applyIncomingBatch.call(this, records);
if (this._changes.length) {
FormWrapper._updateSpinningly(this._changes);
}
delete this._changes;
return failures;
},
- getAllIDs: function () {
+ getAllIDs() {
let results = FormWrapper._searchSpinningly(["guid"], [])
let guids = {};
for (let result of results) {
guids[result.guid] = true;
}
return guids;
},
- changeItemID: function (oldID, newID) {
+ changeItemID(oldID, newID) {
FormWrapper.replaceGUID(oldID, newID);
},
- itemExists: function (id) {
+ itemExists(id) {
return FormWrapper.hasGUID(id);
},
- createRecord: function (id, collection) {
+ createRecord(id, collection) {
let record = new FormRec(collection, id);
let entry = FormWrapper.getEntry(id);
if (entry != null) {
record.name = entry.name;
record.value = entry.value;
} else {
record.deleted = true;
}
return record;
},
- create: function (record) {
+ create(record) {
this._log.trace("Adding form record for " + record.name);
let change = {
op: "add",
fieldname: record.name,
value: record.value
};
this._processChange(change);
},
- remove: function (record) {
+ remove(record) {
this._log.trace("Removing form record: " + record.id);
let change = {
op: "remove",
guid: record.id
};
this._processChange(change);
},
- update: function (record) {
+ update(record) {
this._log.trace("Ignoring form record update request!");
},
- wipe: function () {
+ wipe() {
let change = {
op: "remove"
};
FormWrapper._updateSpinningly(change);
}
};
function FormTracker(name, engine) {
@@ -217,40 +217,40 @@ function FormTracker(name, engine) {
}
FormTracker.prototype = {
__proto__: Tracker.prototype,
QueryInterface: XPCOMUtils.generateQI([
Ci.nsIObserver,
Ci.nsISupportsWeakReference]),
- startTracking: function() {
+ startTracking() {
Svc.Obs.add("satchel-storage-changed", this);
},
- stopTracking: function() {
+ stopTracking() {
Svc.Obs.remove("satchel-storage-changed", this);
},
- observe: function (subject, topic, data) {
+ observe(subject, topic, data) {
Tracker.prototype.observe.call(this, subject, topic, data);
if (this.ignoreAll) {
return;
}
switch (topic) {
case "satchel-storage-changed":
if (data == "formhistory-add" || data == "formhistory-remove") {
let guid = subject.QueryInterface(Ci.nsISupportsString).toString();
this.trackEntry(guid);
}
break;
}
},
- trackEntry: function (guid) {
+ trackEntry(guid) {
this.addChangedID(guid);
this.score += SCORE_INCREMENT_MEDIUM;
},
};
class FormsProblemData extends CollectionProblemData {
getSummary() {
@@ -297,9 +297,9 @@ class FormValidator extends CollectionVa
res.guid = guid;
res.id = guid;
res.duped = true;
}
}
return res;
}
-}
\ No newline at end of file
+}
--- a/services/sync/modules/engines/history.js
+++ b/services/sync/modules/engines/history.js
@@ -40,17 +40,17 @@ HistoryEngine.prototype = {
_recordObj: HistoryRec,
_storeObj: HistoryStore,
_trackerObj: HistoryTracker,
downloadLimit: MAX_HISTORY_DOWNLOAD,
applyIncomingBatchSize: HISTORY_STORE_BATCH_SIZE,
syncPriority: 7,
- _processIncoming: function (newitems) {
+ _processIncoming(newitems) {
// We want to notify history observers that a batch operation is underway
// so they don't do lots of work for each incoming record.
let observers = PlacesUtils.history.getObservers();
function notifyHistoryObservers(notification) {
for (let observer of observers) {
try {
observer[notification]();
} catch (ex) { }
@@ -129,17 +129,17 @@ HistoryStore.prototype = {
if (!this.__asyncHistory) {
this.__asyncHistory = Cc["@mozilla.org/browser/history;1"]
.getService(Ci.mozIAsyncHistory);
}
return this.__asyncHistory;
},
_stmts: {},
- _getStmt: function(query) {
+ _getStmt(query) {
if (query in this._stmts) {
return this._stmts[query];
}
this._log.trace("Creating SQL statement: " + query);
let db = PlacesUtils.history.QueryInterface(Ci.nsPIPlacesDatabase)
.DBConnection;
return this._stmts[query] = db.createAsyncStatement(query);
@@ -287,31 +287,31 @@ HistoryStore.prototype = {
}
records.length = k; // truncate array
// Nothing to do.
if (!records.length) {
return failed;
}
- let updatePlacesCallback = {
+ let updatePlacesCallback = {
handleResult: function handleResult() {},
handleError: function handleError(resultCode, placeInfo) {
failed.push(placeInfo.guid);
},
handleCompletion: Async.makeSyncCallback()
};
this._asyncHistory.updatePlaces(records, updatePlacesCallback);
Async.waitForSyncCallback(updatePlacesCallback.handleCompletion);
return failed;
},
/**
* Converts a Sync history record to a mozIPlaceInfo.
- *
+ *
* Throws if an invalid record is encountered (invalid URI, etc.),
* returns true if the record is to be applied, false otherwise
* (no visits to add, etc.),
*/
_recordToPlaceInfo: function _recordToPlaceInfo(record) {
// Sort out invalid URIs and ones Places just simply doesn't want.
record.uri = Utils.makeURI(record.histUri);
if (!record.uri) {
@@ -415,78 +415,78 @@ HistoryStore.prototype = {
record.deleted = true;
}
return record;
},
wipe: function HistStore_wipe() {
let cb = Async.makeSyncCallback();
- PlacesUtils.history.clear().then(result => {cb(null, result)}, err => {cb(err)});
+ PlacesUtils.history.clear().then(result => { cb(null, result) }, err => { cb(err) });
return Async.waitForSyncCallback(cb);
}
};
function HistoryTracker(name, engine) {
Tracker.call(this, name, engine);
}
HistoryTracker.prototype = {
__proto__: Tracker.prototype,
- startTracking: function() {
+ startTracking() {
this._log.info("Adding Places observer.");
PlacesUtils.history.addObserver(this, true);
},
- stopTracking: function() {
+ stopTracking() {
this._log.info("Removing Places observer.");
PlacesUtils.history.removeObserver(this);
},
QueryInterface: XPCOMUtils.generateQI([
Ci.nsINavHistoryObserver,
Ci.nsISupportsWeakReference
]),
- onDeleteAffectsGUID: function (uri, guid, reason, source, increment) {
+ onDeleteAffectsGUID(uri, guid, reason, source, increment) {
if (this.ignoreAll || reason == Ci.nsINavHistoryObserver.REASON_EXPIRED) {
return;
}
this._log.trace(source + ": " + uri.spec + ", reason " + reason);
if (this.addChangedID(guid)) {
this.score += increment;
}
},
- onDeleteVisits: function (uri, visitTime, guid, reason) {
+ onDeleteVisits(uri, visitTime, guid, reason) {
this.onDeleteAffectsGUID(uri, guid, reason, "onDeleteVisits", SCORE_INCREMENT_SMALL);
},
- onDeleteURI: function (uri, guid, reason) {
+ onDeleteURI(uri, guid, reason) {
this.onDeleteAffectsGUID(uri, guid, reason, "onDeleteURI", SCORE_INCREMENT_XLARGE);
},
- onVisit: function (uri, vid, time, session, referrer, trans, guid) {
+ onVisit(uri, vid, time, session, referrer, trans, guid) {
if (this.ignoreAll) {
this._log.trace("ignoreAll: ignoring visit for " + guid);
return;
}
this._log.trace("onVisit: " + uri.spec);
if (this.addChangedID(guid)) {
this.score += SCORE_INCREMENT_SMALL;
}
},
- onClearHistory: function () {
+ onClearHistory() {
this._log.trace("onClearHistory");
// Note that we're going to trigger a sync, but none of the cleared
// pages are tracked, so the deletions will not be propagated.
// See Bug 578694.
this.score += SCORE_INCREMENT_XLARGE;
},
- onBeginUpdateBatch: function () {},
- onEndUpdateBatch: function () {},
- onPageChanged: function () {},
- onTitleChanged: function () {},
- onBeforeDeleteURI: function () {},
+ onBeginUpdateBatch() {},
+ onEndUpdateBatch() {},
+ onPageChanged() {},
+ onTitleChanged() {},
+ onBeforeDeleteURI() {},
};
--- a/services/sync/modules/engines/passwords.js
+++ b/services/sync/modules/engines/passwords.js
@@ -36,17 +36,17 @@ PasswordEngine.prototype = {
_storeObj: PasswordStore,
_trackerObj: PasswordTracker,
_recordObj: LoginRec,
applyIncomingBatchSize: PASSWORDS_STORE_BATCH_SIZE,
syncPriority: 2,
- _syncFinish: function () {
+ _syncFinish() {
SyncEngine.prototype._syncFinish.call(this);
// Delete the Weave credentials from the server once.
if (!Svc.Prefs.get("deletePwdFxA", false)) {
try {
let ids = [];
for (let host of Utils.getSyncCredentialsHosts()) {
for (let info of Services.logins.findLogins({}, host, "", "")) {
@@ -73,17 +73,17 @@ PasswordEngine.prototype = {
if (Async.isShutdownException(ex)) {
throw ex;
}
this._log.debug("Password deletes failed", ex);
}
}
},
- _findDupe: function (item) {
+ _findDupe(item) {
let login = this._store._nsLoginInfoFromRecord(item);
if (!login) {
return;
}
let logins = Services.logins.findLogins({}, login.hostname, login.formSubmitURL, login.httpRealm);
this._store._sleep(0); // Yield back to main thread after synchronous operation.
@@ -99,24 +99,24 @@ PasswordEngine.prototype = {
function PasswordStore(name, engine) {
Store.call(this, name, engine);
this._nsLoginInfo = new Components.Constructor("@mozilla.org/login-manager/loginInfo;1", Ci.nsILoginInfo, "init");
}
PasswordStore.prototype = {
__proto__: Store.prototype,
- _newPropertyBag: function () {
+ _newPropertyBag() {
return Cc["@mozilla.org/hash-property-bag;1"].createInstance(Ci.nsIWritablePropertyBag2);
},
/**
* Return an instance of nsILoginInfo (and, implicitly, nsILoginMetaInfo).
*/
- _nsLoginInfoFromRecord: function (record) {
+ _nsLoginInfoFromRecord(record) {
function nullUndefined(x) {
return (x == undefined) ? null : x;
}
if (record.formSubmitURL && record.httpRealm) {
this._log.warn("Record " + record.id + " has both formSubmitURL and httpRealm. Skipping.");
return null;
}
@@ -139,50 +139,50 @@ PasswordStore.prototype = {
}
if (record.timePasswordChanged) {
info.timePasswordChanged = record.timePasswordChanged;
}
return info;
},
- _getLoginFromGUID: function (id) {
+ _getLoginFromGUID(id) {
let prop = this._newPropertyBag();
prop.setPropertyAsAUTF8String("guid", id);
let logins = Services.logins.searchLogins({}, prop);
this._sleep(0); // Yield back to main thread after synchronous operation.
if (logins.length > 0) {
this._log.trace(logins.length + " items matching " + id + " found.");
return logins[0];
}
this._log.trace("No items matching " + id + " found. Ignoring");
return null;
},
- getAllIDs: function () {
+ getAllIDs() {
let items = {};
let logins = Services.logins.getAllLogins({});
for (let i = 0; i < logins.length; i++) {
// Skip over Weave password/passphrase entries.
let metaInfo = logins[i].QueryInterface(Ci.nsILoginMetaInfo);
if (Utils.getSyncCredentialsHosts().has(metaInfo.hostname)) {
continue;
}
items[metaInfo.guid] = metaInfo;
}
return items;
},
- changeItemID: function (oldID, newID) {
+ changeItemID(oldID, newID) {
this._log.trace("Changing item ID: " + oldID + " to " + newID);
let oldLogin = this._getLoginFromGUID(oldID);
if (!oldLogin) {
this._log.trace("Can't change item ID: item doesn't exist");
return;
}
if (this._getLoginFromGUID(newID)) {
@@ -191,21 +191,21 @@ PasswordStore.prototype = {
}
let prop = this._newPropertyBag();
prop.setPropertyAsAUTF8String("guid", newID);
Services.logins.modifyLogin(oldLogin, prop);
},
- itemExists: function (id) {
+ itemExists(id) {
return !!this._getLoginFromGUID(id);
},
- createRecord: function (id, collection) {
+ createRecord(id, collection) {
let record = new LoginRec(collection, id);
let login = this._getLoginFromGUID(id);
if (!login) {
record.deleted = true;
return record;
}
@@ -220,86 +220,86 @@ PasswordStore.prototype = {
// Optional fields.
login.QueryInterface(Ci.nsILoginMetaInfo);
record.timeCreated = login.timeCreated;
record.timePasswordChanged = login.timePasswordChanged;
return record;
},
- create: function (record) {
+ create(record) {
let login = this._nsLoginInfoFromRecord(record);
if (!login) {
return;
}
this._log.debug("Adding login for " + record.hostname);
this._log.trace("httpRealm: " + JSON.stringify(login.httpRealm) + "; " +
"formSubmitURL: " + JSON.stringify(login.formSubmitURL));
try {
Services.logins.addLogin(login);
- } catch(ex) {
+ } catch (ex) {
this._log.debug(`Adding record ${record.id} resulted in exception`, ex);
}
},
- remove: function (record) {
+ remove(record) {
this._log.trace("Removing login " + record.id);
let loginItem = this._getLoginFromGUID(record.id);
if (!loginItem) {
this._log.trace("Asked to remove record that doesn't exist, ignoring");
return;
}
Services.logins.removeLogin(loginItem);
},
- update: function (record) {
+ update(record) {
let loginItem = this._getLoginFromGUID(record.id);
if (!loginItem) {
this._log.debug("Skipping update for unknown item: " + record.hostname);
return;
}
this._log.debug("Updating " + record.hostname);
let newinfo = this._nsLoginInfoFromRecord(record);
if (!newinfo) {
return;
}
try {
Services.logins.modifyLogin(loginItem, newinfo);
- } catch(ex) {
+ } catch (ex) {
this._log.debug(`Modifying record ${record.id} resulted in exception; not modifying`, ex);
}
},
- wipe: function () {
+ wipe() {
Services.logins.removeAllLogins();
},
};
function PasswordTracker(name, engine) {
Tracker.call(this, name, engine);
Svc.Obs.add("weave:engine:start-tracking", this);
Svc.Obs.add("weave:engine:stop-tracking", this);
}
PasswordTracker.prototype = {
__proto__: Tracker.prototype,
- startTracking: function () {
+ startTracking() {
Svc.Obs.add("passwordmgr-storage-changed", this);
},
- stopTracking: function () {
+ stopTracking() {
Svc.Obs.remove("passwordmgr-storage-changed", this);
},
- observe: function (subject, topic, data) {
+ observe(subject, topic, data) {
Tracker.prototype.observe.call(this, subject, topic, data);
if (this.ignoreAll) {
return;
}
// A single add, remove or change or removing all items
// will trigger a sync for MULTI_DEVICE.
--- a/services/sync/modules/engines/prefs.js
+++ b/services/sync/modules/engines/prefs.js
@@ -39,92 +39,92 @@ PrefsEngine.prototype = {
_storeObj: PrefStore,
_trackerObj: PrefTracker,
_recordObj: PrefRec,
version: 2,
syncPriority: 1,
allowSkippedRecord: false,
- getChangedIDs: function () {
+ getChangedIDs() {
// No need for a proper timestamp (no conflict resolution needed).
let changedIDs = {};
if (this._tracker.modified)
changedIDs[PREFS_GUID] = 0;
return changedIDs;
},
- _wipeClient: function () {
+ _wipeClient() {
SyncEngine.prototype._wipeClient.call(this);
this.justWiped = true;
},
- _reconcile: function (item) {
+ _reconcile(item) {
// Apply the incoming item if we don't care about the local data
if (this.justWiped) {
this.justWiped = false;
return true;
}
return SyncEngine.prototype._reconcile.call(this, item);
}
};
function PrefStore(name, engine) {
Store.call(this, name, engine);
- Svc.Obs.add("profile-before-change", function () {
+ Svc.Obs.add("profile-before-change", function() {
this.__prefs = null;
}, this);
}
PrefStore.prototype = {
__proto__: Store.prototype,
__prefs: null,
get _prefs() {
if (!this.__prefs) {
this.__prefs = new Preferences();
}
return this.__prefs;
},
- _getSyncPrefs: function () {
+ _getSyncPrefs() {
let syncPrefs = Cc["@mozilla.org/preferences-service;1"]
.getService(Ci.nsIPrefService)
.getBranch(PREF_SYNC_PREFS_PREFIX)
.getChildList("", {});
// Also sync preferences that determine which prefs get synced.
let controlPrefs = syncPrefs.map(pref => PREF_SYNC_PREFS_PREFIX + pref);
return controlPrefs.concat(syncPrefs);
},
- _isSynced: function (pref) {
+ _isSynced(pref) {
return pref.startsWith(PREF_SYNC_PREFS_PREFIX) ||
this._prefs.get(PREF_SYNC_PREFS_PREFIX + pref, false);
},
- _getAllPrefs: function () {
+ _getAllPrefs() {
let values = {};
for (let pref of this._getSyncPrefs()) {
if (this._isSynced(pref)) {
// Missing and default prefs get the null value.
values[pref] = this._prefs.isSet(pref) ? this._prefs.get(pref, null) : null;
}
}
return values;
},
- _updateLightWeightTheme (themeID) {
+ _updateLightWeightTheme(themeID) {
let themeObject = null;
if (themeID) {
themeObject = LightweightThemeManager.getUsedTheme(themeID);
}
LightweightThemeManager.currentTheme = themeObject;
},
- _setAllPrefs: function (values) {
+ _setAllPrefs(values) {
let selectedThemeIDPref = "lightweightThemes.selectedThemeID";
let selectedThemeIDBefore = this._prefs.get(selectedThemeIDPref, null);
let selectedThemeIDAfter = selectedThemeIDBefore;
// Update 'services.sync.prefs.sync.foo.pref' before 'foo.pref', otherwise
// _isSynced returns false when 'foo.pref' doesn't exist (e.g., on a new device).
let prefs = Object.keys(values).sort(a => -a.indexOf(PREF_SYNC_PREFS_PREFIX));
for (let pref of prefs) {
@@ -143,74 +143,74 @@ PrefStore.prototype = {
// default is to just set the pref
default:
if (value == null) {
// Pref has gone missing. The best we can do is reset it.
this._prefs.reset(pref);
} else {
try {
this._prefs.set(pref, value);
- } catch(ex) {
+ } catch (ex) {
this._log.trace("Failed to set pref: " + pref + ": " + ex);
}
}
}
}
// Notify the lightweight theme manager if the selected theme has changed.
if (selectedThemeIDBefore != selectedThemeIDAfter) {
this._updateLightWeightTheme(selectedThemeIDAfter);
}
},
- getAllIDs: function () {
+ getAllIDs() {
/* We store all prefs in just one WBO, with just one GUID */
let allprefs = {};
allprefs[PREFS_GUID] = true;
return allprefs;
},
- changeItemID: function (oldID, newID) {
+ changeItemID(oldID, newID) {
this._log.trace("PrefStore GUID is constant!");
},
- itemExists: function (id) {
+ itemExists(id) {
return (id === PREFS_GUID);
},
- createRecord: function (id, collection) {
+ createRecord(id, collection) {
let record = new PrefRec(collection, id);
if (id == PREFS_GUID) {
record.value = this._getAllPrefs();
} else {
record.deleted = true;
}
return record;
},
- create: function (record) {
+ create(record) {
this._log.trace("Ignoring create request");
},
- remove: function (record) {
+ remove(record) {
this._log.trace("Ignoring remove request");
},
- update: function (record) {
+ update(record) {
// Silently ignore pref updates that are for other apps.
if (record.id != PREFS_GUID)
return;
this._log.trace("Received pref updates, applying...");
this._setAllPrefs(record.value);
},
- wipe: function () {
+ wipe() {
this._log.trace("Ignoring wipe request");
}
};
function PrefTracker(name, engine) {
Tracker.call(this, name, engine);
Svc.Obs.add("profile-before-change", this);
Svc.Obs.add("weave:engine:start-tracking", this);
@@ -233,26 +233,26 @@ PrefTracker.prototype = {
__prefs: null,
get _prefs() {
if (!this.__prefs) {
this.__prefs = new Preferences();
}
return this.__prefs;
},
- startTracking: function () {
+ startTracking() {
Services.prefs.addObserver("", this, false);
},
- stopTracking: function () {
+ stopTracking() {
this.__prefs = null;
Services.prefs.removeObserver("", this);
},
- observe: function (subject, topic, data) {
+ observe(subject, topic, data) {
Tracker.prototype.observe.call(this, subject, topic, data);
switch (topic) {
case "profile-before-change":
this.stopTracking();
break;
case "nsPref:changed":
// Trigger a sync for MULTI-DEVICE for a change that determines
--- a/services/sync/modules/engines/tabs.js
+++ b/services/sync/modules/engines/tabs.js
@@ -46,57 +46,57 @@ TabEngine.prototype = {
// A flag to indicate if we have synced in this session. This is to help
// consumers of remote tabs that may want to differentiate between "I've an
// empty tab list as I haven't yet synced" vs "I've an empty tab list
// as there really are no tabs"
hasSyncedThisSession: false,
syncPriority: 3,
- getChangedIDs: function () {
+ getChangedIDs() {
// No need for a proper timestamp (no conflict resolution needed).
let changedIDs = {};
if (this._tracker.modified)
changedIDs[this.service.clientsEngine.localID] = 0;
return changedIDs;
},
// API for use by Sync UI code to give user choices of tabs to open.
- getAllClients: function () {
+ getAllClients() {
return this._store._remoteClients;
},
- getClientById: function (id) {
+ getClientById(id) {
return this._store._remoteClients[id];
},
- _resetClient: function () {
+ _resetClient() {
SyncEngine.prototype._resetClient.call(this);
this._store.wipe();
this._tracker.modified = true;
this.hasSyncedThisSession = false;
},
- removeClientData: function () {
+ removeClientData() {
let url = this.engineURL + "/" + this.service.clientsEngine.localID;
this.service.resource(url).delete();
},
/**
* Return a Set of open URLs.
*/
- getOpenURLs: function () {
+ getOpenURLs() {
let urls = new Set();
for (let entry of this._store.getAllTabs()) {
urls.add(entry.urlHistory[0]);
}
return urls;
},
- _reconcile: function (item) {
+ _reconcile(item) {
// Skip our own record.
// TabStore.itemExists tests only against our local client ID.
if (this._store.itemExists(item.id)) {
this._log.trace("Ignoring incoming tab item because of its id: " + item.id);
return false;
}
return SyncEngine.prototype._reconcile.call(this, item);
@@ -110,34 +110,34 @@ TabEngine.prototype = {
function TabStore(name, engine) {
Store.call(this, name, engine);
}
TabStore.prototype = {
__proto__: Store.prototype,
- itemExists: function (id) {
+ itemExists(id) {
return id == this.engine.service.clientsEngine.localID;
},
- getWindowEnumerator: function () {
+ getWindowEnumerator() {
return Services.wm.getEnumerator("navigator:browser");
},
- shouldSkipWindow: function (win) {
+ shouldSkipWindow(win) {
return win.closed ||
PrivateBrowsingUtils.isWindowPrivate(win);
},
- getTabState: function (tab) {
+ getTabState(tab) {
return JSON.parse(Svc.Session.getTabState(tab));
},
- getAllTabs: function (filter) {
+ getAllTabs(filter) {
let filteredUrls = new RegExp(Svc.Prefs.get("engine.tabs.filteredUrls"), "i");
let allTabs = [];
let winEnum = this.getWindowEnumerator();
while (winEnum.hasMoreElements()) {
let win = winEnum.getNext();
if (this.shouldSkipWindow(win)) {
@@ -195,22 +195,22 @@ TabStore.prototype = {
lastUsed: Math.floor((tabState.lastAccessed || 0) / 1000),
});
}
}
return allTabs;
},
- createRecord: function (id, collection) {
+ createRecord(id, collection) {
let record = new TabSetRecord(collection, id);
record.clientName = this.engine.service.clientsEngine.localName;
// Sort tabs in descending-used order to grab the most recently used
- let tabs = this.getAllTabs(true).sort(function (a, b) {
+ let tabs = this.getAllTabs(true).sort(function(a, b) {
return b.lastUsed - a.lastUsed;
});
// Figure out how many tabs we can pack into a payload. Starting with a 28KB
// payload, we can estimate various overheads from encryption/JSON/WBO.
let size = JSON.stringify(tabs).length;
let origLength = tabs.length;
const MAX_TAB_SIZE = 20000;
@@ -220,25 +220,25 @@ TabStore.prototype = {
tabs = tabs.slice(0, cutoff + 1);
// Keep dropping off the last entry until the data fits
while (JSON.stringify(tabs).length > MAX_TAB_SIZE)
tabs.pop();
}
this._log.trace("Created tabs " + tabs.length + " of " + origLength);
- tabs.forEach(function (tab) {
+ tabs.forEach(function(tab) {
this._log.trace("Wrapping tab: " + JSON.stringify(tab));
}, this);
record.tabs = tabs;
return record;
},
- getAllIDs: function () {
+ getAllIDs() {
// Don't report any tabs if all windows are in private browsing for
// first syncs.
let ids = {};
let allWindowsArePrivate = false;
let wins = Services.wm.getEnumerator("navigator:browser");
while (wins.hasMoreElements()) {
if (PrivateBrowsingUtils.isWindowPrivate(wins.getNext())) {
// Ensure that at least there is a private window.
@@ -254,28 +254,28 @@ TabStore.prototype = {
!PrivateBrowsingUtils.permanentPrivateBrowsing) {
return ids;
}
ids[this.engine.service.clientsEngine.localID] = true;
return ids;
},
- wipe: function () {
+ wipe() {
this._remoteClients = {};
},
- create: function (record) {
+ create(record) {
this._log.debug("Adding remote tabs from " + record.clientName);
this._remoteClients[record.id] = Object.assign({}, record.cleartext, {
lastModified: record.modified
});
},
- update: function (record) {
+ update(record) {
this._log.trace("Ignoring tab updates as local ones win");
},
};
function TabTracker(name, engine) {
Tracker.call(this, name, engine);
Svc.Obs.add("weave:engine:start-tracking", this);
@@ -285,83 +285,83 @@ function TabTracker(name, engine) {
this.onTab = Utils.bind2(this, this.onTab);
this._unregisterListeners = Utils.bind2(this, this._unregisterListeners);
}
TabTracker.prototype = {
__proto__: Tracker.prototype,
QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver]),
- clearChangedIDs: function () {
+ clearChangedIDs() {
this.modified = false;
},
_topics: ["pageshow", "TabOpen", "TabClose", "TabSelect"],
- _registerListenersForWindow: function (window) {
+ _registerListenersForWindow(window) {
this._log.trace("Registering tab listeners in window");
for (let topic of this._topics) {
window.addEventListener(topic, this.onTab, false);
}
window.addEventListener("unload", this._unregisterListeners, false);
// If it's got a tab browser we can listen for things like navigation.
if (window.gBrowser) {
window.gBrowser.addProgressListener(this);
}
},
- _unregisterListeners: function (event) {
+ _unregisterListeners(event) {
this._unregisterListenersForWindow(event.target);
},
- _unregisterListenersForWindow: function (window) {
+ _unregisterListenersForWindow(window) {
this._log.trace("Removing tab listeners in window");
window.removeEventListener("unload", this._unregisterListeners, false);
for (let topic of this._topics) {
window.removeEventListener(topic, this.onTab, false);
}
if (window.gBrowser) {
window.gBrowser.removeProgressListener(this);
}
},
- startTracking: function () {
+ startTracking() {
Svc.Obs.add("domwindowopened", this);
let wins = Services.wm.getEnumerator("navigator:browser");
while (wins.hasMoreElements()) {
this._registerListenersForWindow(wins.getNext());
}
},
- stopTracking: function () {
+ stopTracking() {
Svc.Obs.remove("domwindowopened", this);
let wins = Services.wm.getEnumerator("navigator:browser");
while (wins.hasMoreElements()) {
this._unregisterListenersForWindow(wins.getNext());
}
},
- observe: function (subject, topic, data) {
+ observe(subject, topic, data) {
Tracker.prototype.observe.call(this, 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.
this._registerListenersForWindow(subject);
};
// Add tab listeners now that a window has opened.
subject.addEventListener("load", onLoad, false);
break;
}
},
- onTab: function (event) {
+ onTab(event) {
if (event.originalTarget.linkedBrowser) {
let browser = event.originalTarget.linkedBrowser;
if (PrivateBrowsingUtils.isBrowserPrivate(browser) &&
!PrivateBrowsingUtils.permanentPrivateBrowsing) {
this._log.trace("Ignoring tab event from private browsing.");
return;
}
}
@@ -373,17 +373,17 @@ TabTracker.prototype = {
// score. We don't want to sync too frequently. For all other page
// events, always bump the score.
if (event.type != "pageshow" || Math.random() < .1) {
this.score += SCORE_INCREMENT_SMALL;
}
},
// web progress listeners.
- onLocationChange: function (webProgress, request, location, flags) {
+ onLocationChange(webProgress, request, location, flags) {
// We only care about top-level location changes which are not in the same
// document.
if (webProgress.isTopLevel &&
((flags & Ci.nsIWebProgressListener.LOCATION_CHANGE_SAME_DOCUMENT) == 0)) {
this.modified = true;
}
},
};
--- a/services/sync/modules/identity.js
+++ b/services/sync/modules/identity.js
@@ -82,36 +82,36 @@ IdentityManager.prototype = {
_syncKeyAllowLookup: true,
_syncKeySet: false,
_syncKeyBundle: null,
/**
* Initialize the identity provider.
*/
- initialize: function() {
+ initialize() {
// Nothing to do for this identity provider.
},
- finalize: function() {
+ finalize() {
// Nothing to do for this identity provider.
},
/**
* Called whenever Service.logout() is called.
*/
- logout: function() {
+ logout() {
// nothing to do for this identity provider.
},
/**
* Ensure the user is logged in. Returns a promise that resolves when
* the user is logged in, or is rejected if the login attempt has failed.
*/
- ensureLoggedIn: function() {
+ ensureLoggedIn() {
// nothing to do for this identity provider
return Promise.resolve();
},
get account() {
return Svc.Prefs.get("account", this.username);
},
@@ -164,25 +164,25 @@ IdentityManager.prototype = {
// and wipe out the credentials.
this._log.info("Username changed. Removing stored credentials.");
this.resetCredentials();
},
/**
* Resets/Drops all credentials we hold for the current user.
*/
- resetCredentials: function() {
+ resetCredentials() {
this.basicPassword = null;
this.resetSyncKey();
},
/**
* Resets/Drops the sync key we hold for the current user.
*/
- resetSyncKey: function() {
+ resetSyncKey() {
this.syncKey = null;
// syncKeyBundle cleared as a result of setting syncKey.
},
/**
* Obtains the HTTP Basic auth password.
*
* Returns a string if set or null if it is not set.
@@ -367,17 +367,17 @@ IdentityManager.prototype = {
},
/**
* Verify the current auth state, unlocking the master-password if necessary.
*
* Returns a promise that resolves with the current auth state after
* attempting to unlock.
*/
- unlockAndVerifyAuthState: function() {
+ unlockAndVerifyAuthState() {
// Try to fetch the passphrase - this will prompt for MP unlock as a
// side-effect...
try {
this.syncKey;
} catch (ex) {
this._log.debug("Fetching passphrase threw " + ex +
"; assuming master password locked.");
return Promise.resolve(MASTER_PASSWORD_LOCKED);
@@ -436,17 +436,17 @@ IdentityManager.prototype = {
},
/**
* Pre-fetches any information that might help with migration away from this
* identity. Called after every sync and is really just an optimization that
* allows us to avoid a network request for when we actually need the
* migration info.
*/
- prefetchMigrationSentinel: function(service) {
+ prefetchMigrationSentinel(service) {
// Try and fetch the migration sentinel - it will end up in the recordManager
// cache.
try {
service.recordManager.get(service.storageURL + "meta/fxa_credentials");
} catch (ex) {
if (Async.isShutdownException(ex)) {
throw ex;
}
@@ -490,17 +490,17 @@ IdentityManager.prototype = {
let login = new loginInfo(PWDMGR_HOST, null, realm, username,
password, "", "");
Services.logins.addLogin(login);
},
/**
* Return credentials hosts for this identity only.
*/
- _getSyncCredentialsHosts: function() {
+ _getSyncCredentialsHosts() {
return Utils.getSyncCredentialsHostsLegacy();
},
/**
* Deletes Sync credentials from the password manager.
*/
deleteSyncCredentials: function deleteSyncCredentials() {
for (let host of this._getSyncCredentialsHosts()) {
@@ -579,22 +579,22 @@ IdentityManager.prototype = {
return null;
},
onRESTRequestBasic: function onRESTRequestBasic(request) {
let up = this.username + ":" + this.basicPassword;
request.setHeader("authorization", "Basic " + btoa(up));
},
- createClusterManager: function(service) {
+ createClusterManager(service) {
Cu.import("resource://services-sync/stages/cluster.js");
return new ClusterManager(service);
},
- offerSyncOptions: function () {
+ offerSyncOptions() {
// Do nothing for Sync 1.1.
return {accepted: true};
},
// Tell Sync what the login status should be if it saw a 401 fetching
// info/collections as part of login verification (typically immediately
// after login.)
// In our case it means an authoritative "password is incorrect".
--- a/services/sync/modules/jpakeclient.js
+++ b/services/sync/modules/jpakeclient.js
@@ -19,18 +19,18 @@ const JPAKE_SIGNERID_RECEIVER = "receive
const JPAKE_LENGTH_SECRET = 8;
const JPAKE_LENGTH_CLIENTID = 256;
const JPAKE_VERIFY_VALUE = "0123456789ABCDEF";
/**
* Client to exchange encrypted data using the J-PAKE algorithm.
* The exchange between two clients of this type looks like this:
- *
- *
+ *
+ *
* Mobile Server Desktop
* ===================================================================
* |
* retrieve channel <---------------|
* generate random secret |
* show PIN = secret + channel | ask user for PIN
* upload Mobile's message 1 ------>|
* |----> retrieve Mobile's message 1
@@ -54,65 +54,65 @@ const JPAKE_VERIFY_VALUE = "0123456
*
* | encrypt credentials
* |<------------- upload credentials
* retrieve credentials <-----------|
* verify HMAC |
* decrypt credentials |
* delete session ----------------->|
* start syncing |
- *
- *
+ *
+ *
* Create a client object like so:
- *
+ *
* let client = new JPAKEClient(controller);
- *
+ *
* The 'controller' object must implement the following methods:
- *
+ *
* displayPIN(pin) -- Called when a PIN has been generated and is ready to
* be displayed to the user. Only called on the client where the pairing
* was initiated with 'receiveNoPIN()'.
- *
+ *
* onPairingStart() -- Called when the pairing has started and messages are
* being sent back and forth over the channel. Only called on the client
* where the pairing was initiated with 'receiveNoPIN()'.
- *
+ *
* onPaired() -- Called when the device pairing has been established and
* we're ready to send the credentials over. To do that, the controller
* must call 'sendAndComplete()' while the channel is active.
- *
+ *
* onComplete(data) -- Called after transfer has been completed. On
* the sending side this is called with no parameter and as soon as the
* data has been uploaded. This does not mean the receiving side has
* actually retrieved them yet.
*
* onAbort(error) -- Called whenever an error is encountered. All errors lead
* to an abort and the process has to be started again on both sides.
- *
+ *
* To start the data transfer on the receiving side, call
- *
+ *
* client.receiveNoPIN();
- *
+ *
* This will allocate a new channel on the server, generate a PIN, have it
* displayed and then do the transfer once the protocol has been completed
* with the sending side.
- *
+ *
* To initiate the transfer from the sending side, call
- *
+ *
* client.pairWithPIN(pin, true);
- *
+ *
* Once the pairing has been established, the controller's 'onPaired()' method
* will be called. To then transmit the data, call
- *
+ *
* client.sendAndComplete(data);
- *
+ *
* To abort the process, call
- *
+ *
* client.abort();
- *
+ *
* Note that after completion or abort, the 'client' instance may not be reused.
* You will have to create a new one in case you'd like to restart the process.
*/
this.JPAKEClient = function JPAKEClient(controller) {
this.controller = controller;
this._log = Log.repository.getLogger("Sync.JPAKEClient");
this._log.level = Log.Level[Svc.Prefs.get(
@@ -136,17 +136,17 @@ JPAKEClient.prototype = {
/*
* Public API
*/
/**
* Initiate pairing and receive data without providing a PIN. The PIN will
* be generated and passed on to the controller to be displayed to the user.
- *
+ *
* This is typically called on mobile devices where typing is tedious.
*/
receiveNoPIN: function receiveNoPIN() {
this._my_signerid = JPAKE_SIGNERID_RECEIVER;
this._their_signerid = JPAKE_SIGNERID_SENDER;
this._secret = this._createSecret();
@@ -180,20 +180,20 @@ JPAKEClient.prototype = {
},
this._getStep,
this._decryptData,
this._complete)();
},
/**
* Initiate pairing based on the PIN entered by the user.
- *
+ *
* This is typically called on desktop devices where typing is easier than
* on mobile.
- *
+ *
* @param pin
* 12 character string (in human-friendly base32) containing the PIN
* entered by the user.
* @param expectDelay
* Flag that indicates that a significant delay between the pairing
* and the sending should be expected. v2 and earlier of the protocol
* did not allow for this and the pairing to a v2 or earlier client
* will be aborted if this flag is 'true'.
@@ -203,17 +203,17 @@ JPAKEClient.prototype = {
this._their_signerid = JPAKE_SIGNERID_RECEIVER;
this._channel = pin.slice(JPAKE_LENGTH_SECRET);
this._channelURL = this._serverURL + this._channel;
this._secret = pin.slice(0, JPAKE_LENGTH_SECRET);
this._chain(this._computeStepOne,
this._getStep,
- function (callback) {
+ function(callback) {
// Ensure that the other client can deal with a delay for
// the last message if that's requested by the caller.
if (!expectDelay) {
return callback();
}
if (!this._incoming.version || this._incoming.version < 3) {
return this.abort(JPAKE_ERROR_DELAYUNSUPPORTED);
}
@@ -225,17 +225,17 @@ JPAKEClient.prototype = {
this._putStep,
this._computeFinal,
this._getStep,
this._verifyPairing)();
},
/**
* Send data after a successful pairing.
- *
+ *
* @param obj
* Object containing the data to send. It will be serialized as JSON.
*/
sendAndComplete: function sendAndComplete(obj) {
if (!this._paired || this._finished) {
this._log.error("Can't send data, no active pairing!");
throw "No active pairing!";
}
@@ -244,17 +244,17 @@ JPAKEClient.prototype = {
this._putStep,
this._complete)();
},
/**
* Abort the current pairing. The channel on the server will be deleted
* if the abort wasn't due to a network or server error. The controller's
* 'onAbort()' method is notified in all cases.
- *
+ *
* @param error [optional]
* Error constant indicating the reason for the abort. Defaults to
* user abort.
*/
abort: function abort(error) {
this._log.debug("Aborting...");
this._finished = true;
let self = this;
@@ -345,17 +345,17 @@ JPAKEClient.prototype = {
_putStep: function _putStep(callback) {
this._log.trace("Uploading message " + this._outgoing.type);
let request = this._newRequest(this._channelURL);
if (this._their_etag) {
request.setHeader("If-Match", this._their_etag);
} else {
request.setHeader("If-None-Match", "*");
}
- request.put(this._outgoing, Utils.bind2(this, function (error) {
+ request.put(this._outgoing, Utils.bind2(this, function(error) {
if (this._finished) {
return;
}
if (error) {
this._log.error("Error uploading data. " + error);
this.abort(JPAKE_ERROR_NETWORK);
return;
@@ -364,31 +364,31 @@ JPAKEClient.prototype = {
this._log.error("Could not upload data. Server responded with HTTP "
+ request.response.status);
this.abort(JPAKE_ERROR_SERVER);
return;
}
// There's no point in returning early here since the next step will
// always be a GET so let's pause for twice the poll interval.
this._my_etag = request.response.headers["etag"];
- Utils.namedTimer(function () { callback(); }, this._pollInterval * 2,
+ Utils.namedTimer(function() { callback(); }, this._pollInterval * 2,
this, "_pollTimer");
}));
},
// Generic handler for polling for and retrieving data.
_pollTries: 0,
_getStep: function _getStep(callback) {
this._log.trace("Retrieving next message.");
let request = this._newRequest(this._channelURL);
if (this._my_etag) {
request.setHeader("If-None-Match", this._my_etag);
}
- request.get(Utils.bind2(this, function (error) {
+ request.get(Utils.bind2(this, function(error) {
if (this._finished) {
return;
}
if (error) {
this._log.error("Error fetching data. " + error);
this.abort(JPAKE_ERROR_NETWORK);
return;
@@ -440,17 +440,17 @@ JPAKEClient.prototype = {
}));
},
_reportFailure: function _reportFailure(reason, callback) {
this._log.debug("Reporting failure to server.");
let request = this._newRequest(this._serverURL + "report");
request.setHeader("X-KeyExchange-Cid", this._channel);
request.setHeader("X-KeyExchange-Log", reason);
- request.post("", Utils.bind2(this, function (error) {
+ request.post("", Utils.bind2(this, function(error) {
if (error) {
this._log.warn("Report failed: " + error);
} else if (request.response.status != 200) {
this._log.warn("Report failed. Server responded with HTTP "
+ request.response.status);
}
// Do not block on errors, we're done or aborted by now anyway.
@@ -567,17 +567,17 @@ JPAKEClient.prototype = {
this._crypto_key, iv);
} catch (ex) {
this._log.error("Failed to encrypt key verification value.");
this.abort(JPAKE_ERROR_INTERNAL);
return;
}
this._outgoing = {type: this._my_signerid + "3",
version: KEYEXCHANGE_VERSION,
- payload: {ciphertext: ciphertext, IV: iv}};
+ payload: {ciphertext, IV: iv}};
this._log.trace("Generated message " + this._outgoing.type);
callback();
},
_verifyPairing: function _verifyPairing(callback) {
this._log.trace("Verifying their key.");
if (this._incoming.type != this._their_signerid + "3") {
this._log.error("Invalid round 3 data: " +
@@ -596,17 +596,17 @@ JPAKEClient.prototype = {
} catch (ex) {
this._log.error("Keys don't match!");
this.abort(JPAKE_ERROR_KEYMISMATCH);
return;
}
this._log.debug("Verified pairing!");
this._paired = true;
- Utils.nextTick(function () { this.controller.onPaired(); }, this);
+ Utils.nextTick(function() { this.controller.onPaired(); }, this);
callback();
},
_encryptData: function _encryptData(callback) {
this._log.trace("Encrypting data.");
let iv, ciphertext, hmac;
try {
iv = Svc.Crypto.generateRandomIV();
@@ -614,17 +614,17 @@ JPAKEClient.prototype = {
hmac = Utils.bytesAsHex(Utils.digestUTF8(ciphertext, this._hmac_hasher));
} catch (ex) {
this._log.error("Failed to encrypt data.");
this.abort(JPAKE_ERROR_INTERNAL);
return;
}
this._outgoing = {type: this._my_signerid + "3",
version: KEYEXCHANGE_VERSION,
- payload: {ciphertext: ciphertext, IV: iv, hmac: hmac}};
+ payload: {ciphertext, IV: iv, hmac}};
this._log.trace("Generated message " + this._outgoing.type);
callback();
},
_decryptData: function _decryptData(callback) {
this._log.trace("Verifying their key.");
if (this._incoming.type != this._their_signerid + "3") {
this._log.error("Invalid round 3 data: "
@@ -642,17 +642,17 @@ JPAKEClient.prototype = {
} catch (ex) {
this._log.error("HMAC validation failed.");
this.abort(JPAKE_ERROR_KEYMISMATCH);
return;
}
this._log.trace("Decrypting data.");
let cleartext;
- try {
+ try {
cleartext = Svc.Crypto.decrypt(step3.ciphertext, this._crypto_key,
step3.IV);
} catch (ex) {
this._log.error("Failed to decrypt data.");
this.abort(JPAKE_ERROR_INTERNAL);
return;
}
@@ -666,17 +666,17 @@ JPAKEClient.prototype = {
this._log.trace("Decrypted data.");
callback();
},
_complete: function _complete() {
this._log.debug("Exchange completed.");
this._finished = true;
- Utils.nextTick(function () { this.controller.onComplete(this._newData); },
+ Utils.nextTick(function() { this.controller.onComplete(this._newData); },
this);
}
};
/**
* Send credentials over an active J-PAKE channel.
@@ -705,18 +705,18 @@ this.SendCredentialsController =
this.jpakeclient = jpakeclient;
this.service = service;
// Register ourselves as observers the first Sync finishing (either
// successfully or unsuccessfully, we don't care) or for removing
// this device's sync configuration, in case that happens while we
// haven't finished the first sync yet.
Services.obs.addObserver(this, "weave:service:sync:finish", false);
- Services.obs.addObserver(this, "weave:service:sync:error", false);
- Services.obs.addObserver(this, "weave:service:start-over", false);
+ Services.obs.addObserver(this, "weave:service:sync:error", false);
+ Services.obs.addObserver(this, "weave:service:start-over", false);
}
SendCredentialsController.prototype = {
unload: function unload() {
this._log.trace("Unloading.");
try {
Services.obs.removeObserver(this, "weave:service:sync:finish");
Services.obs.removeObserver(this, "weave:service:sync:error");
--- a/services/sync/modules/main.js
+++ b/services/sync/modules/main.js
@@ -17,14 +17,14 @@ function lazyImport(module, dest, props)
function getter(prop) {
return function() {
let ns = {};
Components.utils.import(module, ns);
delete dest[prop];
return dest[prop] = ns[prop];
};
}
- props.forEach(function (prop) { dest.__defineGetter__(prop, getter(prop)); });
+ props.forEach(function(prop) { dest.__defineGetter__(prop, getter(prop)); });
}
for (let mod in lazies) {
lazyImport("resource://services-sync/" + mod, Weave, lazies[mod]);
}
--- a/services/sync/modules/policies.js
+++ b/services/sync/modules/policies.js
@@ -128,17 +128,17 @@ SyncScheduler.prototype = {
if (Status.checkSetup() == STATUS_OK) {
Svc.Obs.add("wake_notification", this);
Svc.Idle.addIdleObserver(this, Svc.Prefs.get("scheduler.idleTime"));
}
},
observe: function observe(subject, topic, data) {
this._log.trace("Handling " + topic);
- switch(topic) {
+ switch (topic) {
case "weave:engine:score:updated":
if (Status.login == LOGIN_SUCCEEDED) {
Utils.namedTimer(this.calculateScore, SCORE_UPDATE_DELAY, this,
"_scoreTimer");
}
break;
case "network:offline-status-changed":
// Whether online or offline, we'll reschedule syncs
@@ -579,17 +579,17 @@ ErrorHandler.prototype = {
"BookmarkSyncUtils"
];
this._logManager = new LogManager(Svc.Prefs, logs, "sync");
},
observe: function observe(subject, topic, data) {
this._log.trace("Handling " + topic);
- switch(topic) {
+ switch (topic) {
case "weave:engine:sync:applied":
if (subject.newFailed) {
// An engine isn't able to apply one or more incoming records.
// We don't fail hard on this, but it usually indicates a bug,
// so for now treat it as sync error (c.f. Service._syncEngine())
Status.engines = [data, ENGINE_APPLY_FAIL];
this._log.debug(data + " failed to apply some records.");
}
@@ -651,17 +651,17 @@ ErrorHandler.prototype = {
}
case "weave:service:sync:finish":
this._log.trace("Status.service is " + Status.service);
// Check both of these status codes: in the event of a failure in one
// engine, Status.service will be SYNC_FAILED_PARTIAL despite
// Status.sync being SYNC_SUCCEEDED.
// *facepalm*
- if (Status.sync == SYNC_SUCCEEDED &&
+ if (Status.sync == SYNC_SUCCEEDED &&
Status.service == STATUS_OK) {
// Great. Let's clear our mid-sync 401 note.
this._log.trace("Clearing lastSyncReassigned.");
Svc.Prefs.reset("lastSyncReassigned");
}
if (Status.service == SYNC_FAILED_PARTIAL) {
this._log.error("Some engines did not sync correctly.");
@@ -838,31 +838,31 @@ ErrorHandler.prototype = {
get earliestNextAlert() {
return Svc.Prefs.get("errorhandler.alert.earliestNext", 0) * 1000;
},
set earliestNextAlert(msec) {
return Svc.Prefs.set("errorhandler.alert.earliestNext", msec / 1000);
},
- clearServerAlerts: function () {
+ clearServerAlerts() {
// If we have any outstanding alerts, apparently they're no longer relevant.
Svc.Prefs.resetBranch("errorhandler.alert");
},
/**
* X-Weave-Alert headers can include a JSON object:
*
* {
* "code": // One of "hard-eol", "soft-eol".
* "url": // For "Learn more" link.
* "message": // Logged in Sync logs.
* }
*/
- handleServerAlert: function (xwa) {
+ handleServerAlert(xwa) {
if (!xwa.code) {
this._log.warn("Got structured X-Weave-Alert, but no alert code.");
return;
}
switch (xwa.code) {
// Gently and occasionally notify the user that this service will be
// shutting down.
@@ -890,17 +890,17 @@ ErrorHandler.prototype = {
},
/**
* Handle HTTP response results or exceptions and set the appropriate
* Status.* bits.
*
* This method also looks for "side-channel" warnings.
*/
- checkServerError: function (resp) {
+ checkServerError(resp) {
switch (resp.status) {
case 200:
case 404:
case 513:
let xwa = resp.headers['x-weave-alert'];
// Only process machine-readable alerts.
if (!xwa || !xwa.startsWith("{")) {
--- a/services/sync/modules/record.js
+++ b/services/sync/modules/record.js
@@ -60,51 +60,51 @@ WBORecord.prototype = {
throw new Error("First argument must be a Resource instance.");
}
return resource.put(this);
},
// Take a base URI string, with trailing slash, and return the URI of this
// WBO based on collection and ID.
- uri: function(base) {
+ uri(base) {
if (this.collection && this.id) {
let url = Utils.makeURI(base + this.collection + "/" + this.id);
url.QueryInterface(Ci.nsIURL);
return url;
}
return null;
},
deserialize: function deserialize(json) {
this.data = json.constructor.toString() == String ? JSON.parse(json) : json;
try {
// The payload is likely to be JSON, but if not, keep it as a string
this.payload = JSON.parse(this.payload);
- } catch(ex) {}
+ } catch (ex) {}
},
toJSON: function toJSON() {
// Copy fields from data to be stringified, making sure payload is a string
let obj = {};
for (let [key, val] of Object.entries(this.data))
obj[key] = key == "payload" ? JSON.stringify(val) : val;
if (this.ttl)
obj.ttl = this.ttl;
return obj;
},
toString: function toString() {
return "{ " +
- "id: " + this.id + " " +
- "index: " + this.sortindex + " " +
- "modified: " + this.modified + " " +
- "ttl: " + this.ttl + " " +
- "payload: " + JSON.stringify(this.payload) +
+ "id: " + this.id + " " +
+ "index: " + this.sortindex + " " +
+ "modified: " + this.modified + " " +
+ "ttl: " + this.ttl + " " +
+ "payload: " + JSON.stringify(this.payload) +
" }";
}
};
Utils.deferGetSet(WBORecord, "data", ["id", "modified", "sortindex", "payload"]);
this.CryptoWrapper = function CryptoWrapper(collection, id) {
this.cleartext = {};
@@ -181,21 +181,21 @@ CryptoWrapper.prototype = {
return this.cleartext;
},
toString: function toString() {
let payload = this.deleted ? "DELETED" : JSON.stringify(this.cleartext);
return "{ " +
- "id: " + this.id + " " +
- "index: " + this.sortindex + " " +
- "modified: " + this.modified + " " +
- "ttl: " + this.ttl + " " +
- "payload: " + payload + " " +
+ "id: " + this.id + " " +
+ "index: " + this.sortindex + " " +
+ "modified: " + this.modified + " " +
+ "ttl: " + this.ttl + " " +
+ "payload: " + payload + " " +
"collection: " + (this.collection || "undefined") +
" }";
},
// The custom setter below masks the parent's getter, so explicitly call it :(
get id() {
return WBORecord.prototype.__lookupGetter__("id").call(this);
},
@@ -325,43 +325,43 @@ CollectionKeyManager.prototype = {
process(m1, m2);
process(m2, m1);
// Return a sorted, unique array.
changed.sort();
let last;
changed = changed.filter(x => (x != last) && (last = x));
return {same: changed.length == 0,
- changed: changed};
+ changed};
},
get isClear() {
return !this._default;
},
clear: function clear() {
this._log.info("Clearing collection keys...");
this.lastModified = 0;
this._collections = {};
this._default = null;
},
- keyForCollection: function(collection) {
+ keyForCollection(collection) {
if (collection && this._collections[collection])
return this._collections[collection];
return this._default;
},
/**
* If `collections` (an array of strings) is provided, iterate
* over it and generate random keys for each collection.
* Create a WBO for the given data.
*/
- _makeWBO: function(collections, defaultBundle) {
+ _makeWBO(collections, defaultBundle) {
let wbo = new CryptoWrapper(CRYPTO_COLLECTION, KEYS_WBO);
let c = {};
for (let k in collections) {
c[k] = collections[k].keyPairB64;
}
wbo.cleartext = {
"default": defaultBundle ? defaultBundle.keyPairB64 : null,
"collections": c,
@@ -369,42 +369,42 @@ CollectionKeyManager.prototype = {
"id": KEYS_WBO
};
return wbo;
},
/**
* Create a WBO for the current keys.
*/
- asWBO: function(collection, id) {
+ asWBO(collection, id) {
return this._makeWBO(this._collections, this._default);
},
/**
* Compute a new default key, and new keys for any specified collections.
*/
- newKeys: function(collections) {
+ newKeys(collections) {
let newDefaultKeyBundle = this.newDefaultKeyBundle();
let newColls = {};
if (collections) {
- collections.forEach(function (c) {
+ collections.forEach(function(c) {
let b = new BulkKeyBundle(c);
b.generateRandom();
newColls[c] = b;
});
}
return [newDefaultKeyBundle, newColls];
},
/**
* Generates new keys, but does not replace our local copy. Use this to
* verify an upload before storing.
*/
- generateNewKeysWBO: function(collections) {
+ generateNewKeysWBO(collections) {
let newDefaultKey, newColls;
[newDefaultKey, newColls] = this.newKeys(collections);
return this._makeWBO(newColls, newDefaultKey);
},
/**
* Create a new default key.
@@ -454,17 +454,17 @@ CollectionKeyManager.prototype = {
b.generateRandom();
newKeys[c] = b;
}
return new CollectionKeyManager(this.lastModified, this._default, newKeys);
},
// Take the fetched info/collections WBO, checking the change
// time of the crypto collection.
- updateNeeded: function(info_collections) {
+ updateNeeded(info_collections) {
this._log.info("Testing for updateNeeded. Last modified: " + this.lastModified);
// No local record of modification time? Need an update.
if (!this.lastModified)
return true;
// No keys on the server? We need an update, though our
@@ -625,17 +625,17 @@ Collection.prototype = {
args.push("limit=" + this.limit);
if (this._batch)
args.push("batch=" + encodeURIComponent(this._batch));
if (this._commit)
args.push("commit=true");
if (this._offset)
args.push("offset=" + encodeURIComponent(this._offset));
- this.uri.query = (args.length > 0)? '?' + args.join('&') : '';
+ this.uri.query = (args.length > 0) ? '?' + args.join('&') : '';
},
// get full items
get full() { return this._full; },
set full(value) {
this._full = value;
this._rebuildURL();
},
@@ -970,17 +970,17 @@ PostQueue.prototype = {
batch = this.batchID;
} else {
// Not the first post and we know we have no batch semantics.
batch = null;
}
headers.push(["x-if-unmodified-since", this.lastModified]);
- this.log.info(`Posting ${this.numQueued} records of ${this.queued.length+1} bytes with batch=${batch}`);
+ this.log.info(`Posting ${this.numQueued} records of ${this.queued.length + 1} bytes with batch=${batch}`);
let queued = this.queued + "]";
if (finalBatchPost) {
this.bytesAlreadyBatched = 0;
this.numAlreadyBatched = 0;
} else {
this.bytesAlreadyBatched += queued.length;
this.numAlreadyBatched += this.numQueued;
}
--- a/services/sync/modules/resource.js
+++ b/services/sync/modules/resource.js
@@ -224,17 +224,17 @@ AsyncResource.prototype = {
this._callback(error);
return;
}
this._data = data;
let action = channel.requestMethod;
this._log.trace("Channel: " + channel);
- this._log.trace("Action: " + action);
+ this._log.trace("Action: " + action);
// Process status and success first. This way a problem with headers
// doesn't fail to include accurate status information.
let status = 0;
let success = false;
try {
status = channel.responseStatus;
@@ -251,17 +251,17 @@ AsyncResource.prototype = {
if (mesg.length > 200)
mesg = mesg.substr(0, 200) + "…";
this._log.debug(mesg);
// Additionally give the full response body when Trace logging.
if (this._log.level <= Log.Level.Trace)
this._log.trace(action + " body: " + data);
- } catch(ex) {
+ } catch (ex) {
// Got a response, but an exception occurred during processing.
// This shouldn't occur.
this._log.warn("Caught unexpected exception in _oncomplete", ex);
}
// Process headers. They can be empty, or the call can otherwise fail, so
// put this in its own try block.
let headers = {};
@@ -459,18 +459,17 @@ ChannelListener.prototype = {
this._log.error("Unexpected error: channel is not a nsIHttpChannel!");
channel.cancel(Cr.NS_BINDING_ABORTED);
return;
}
// Save the latest server timestamp when possible.
try {
AsyncResource.serverTime = channel.getResponseHeader("X-Weave-Timestamp") - 0;
- }
- catch(ex) {}
+ } catch (ex) {}
this._log.trace("onStartRequest: " + channel.requestMethod + " " +
channel.URI.spec);
this._data = '';
this.delayAbort();
},
onStopRequest: function Channel_onStopRequest(channel, context, status) {
@@ -593,21 +592,21 @@ function ChannelNotificationListener(hea
this._headersToCopy = headersToCopy;
this._log = Log.repository.getLogger(this._logName);
this._log.level = Log.Level[Svc.Prefs.get("log.logger.network.resources")];
}
ChannelNotificationListener.prototype = {
_logName: "Sync.Resource",
- getInterface: function(aIID) {
+ getInterface(aIID) {
return this.QueryInterface(aIID);
},
- QueryInterface: function(aIID) {
+ QueryInterface(aIID) {
if (aIID.equals(Ci.nsIBadCertListener2) ||
aIID.equals(Ci.nsIInterfaceRequestor) ||
aIID.equals(Ci.nsISupports) ||
aIID.equals(Ci.nsIChannelEventSink))
return this;
throw Cr.NS_ERROR_NO_INTERFACE;
},
--- a/services/sync/modules/service.js
+++ b/services/sync/modules/service.js
@@ -298,18 +298,17 @@ Sync11Service.prototype = {
this._log.debug("Keys changed: " + JSON.stringify(keysChanged));
if (!skipReset) {
this._log.info("Resetting client to reflect key change.");
if (keysChanged.length) {
// Collection keys only. Reset individual engines.
this.resetClient(keysChanged);
- }
- else {
+ } else {
// Default key changed: wipe it all.
this.resetClient();
}
this._log.info("Downloaded new keys, client reset. Proceeding.");
}
return true;
}
@@ -538,17 +537,17 @@ Sync11Service.prototype = {
return request;
},
/**
* Perform the info fetch as part of a login or key fetch, or
* inside engine sync.
*/
- _fetchInfo: function (url) {
+ _fetchInfo(url) {
let infoURL = url || this.infoURL;
this._log.trace("In _fetchInfo: " + infoURL);
let info;
try {
info = this.resource(infoURL).get();
} catch (ex) {
this.errorHandler.checkServerError(ex);
@@ -614,67 +613,61 @@ Sync11Service.prototype = {
if (infoCollections && (CRYPTO_COLLECTION in infoCollections)) {
try {
cryptoKeys = new CryptoWrapper(CRYPTO_COLLECTION, KEYS_WBO);
let cryptoResp = cryptoKeys.fetch(this.resource(this.cryptoKeysURL)).response;
if (cryptoResp.success) {
let keysChanged = this.handleFetchedKeys(syncKeyBundle, cryptoKeys);
return true;
- }
- else if (cryptoResp.status == 404) {
+ } else if (cryptoResp.status == 404) {
// On failure, ask to generate new keys and upload them.
// Fall through to the behavior below.
this._log.warn("Got 404 for crypto/keys, but 'crypto' in info/collections. Regenerating.");
cryptoKeys = null;
- }
- else {
+ } else {
// Some other problem.
this.status.login = LOGIN_FAILED_SERVER_ERROR;
this.errorHandler.checkServerError(cryptoResp);
this._log.warn("Got status " + cryptoResp.status + " fetching crypto keys.");
return false;
}
- }
- catch (ex) {
+ } catch (ex) {
this._log.warn("Got exception \"" + ex + "\" fetching cryptoKeys.");
// TODO: Um, what exceptions might we get here? Should we re-throw any?
// One kind of exception: HMAC failure.
if (Utils.isHMACMismatch(ex)) {
this.status.login = LOGIN_FAILED_INVALID_PASSPHRASE;
this.status.sync = CREDENTIALS_CHANGED;
- }
- else {
+ } else {
// In the absence of further disambiguation or more precise
// failure constants, just report failure.
this.status.login = LOGIN_FAILED;
}
return false;
}
- }
- else {
+ } else {
this._log.info("... 'crypto' is not a reported collection. Generating new keys.");
}
if (!cryptoKeys) {
this._log.info("No keys! Generating new ones.");
// Better make some and upload them, and wipe the server to ensure
// consistency. This is all achieved via _freshStart.
// If _freshStart fails to clear the server or upload keys, it will
// throw.
this._freshStart();
return true;
}
// Last-ditch case.
return false;
- }
- else {
+ } else {
// No update needed: we're good!
return true;
}
} catch (ex) {
// This means no keys are present, or there's a network error.
this._log.debug("Failed to fetch and verify keys", ex);
this.errorHandler.checkServerError(ex);
@@ -883,17 +876,17 @@ Sync11Service.prototype = {
this.status.resetSync();
// Deletion doesn't make sense if we aren't set up yet!
if (this.clusterURL != "") {
// Clear client-specific data from the server, including disabled engines.
for (let engine of [this.clientsEngine].concat(this.engineManager.getAll())) {
try {
engine.removeClientData();
- } catch(ex) {
+ } catch (ex) {
this._log.warn(`Deleting client data for ${engine.name} failed`, ex);
}
}
this._log.debug("Finished deleting client data.");
} else {
this._log.debug("Skipping client data removal: no cluster URL.");
}
@@ -1157,17 +1150,17 @@ Sync11Service.prototype = {
newMeta.changed = meta.changed;
}
// Switch in the new meta object and record the new time.
meta = newMeta;
this.metaModified = infoResponse.obj.meta;
}
- let remoteVersion = (meta && meta.payload.storageVersion)?
+ let remoteVersion = (meta && meta.payload.storageVersion) ?
meta.payload.storageVersion : "";
this._log.debug(["Weave Version:", WEAVE_VERSION, "Local Storage:",
STORAGE_VERSION, "Remote Storage:", remoteVersion].join(" "));
// Check for cases that require a fresh start. When comparing remoteVersion,
// we need to convert it to a number as older clients used it as a string.
if (!meta || !meta.payload.storageVersion || !meta.payload.syncID ||
@@ -1197,23 +1190,21 @@ Sync11Service.prototype = {
if (status == 404)
this._log.info("Metadata record not found, server was wiped to ensure " +
"consistency.");
else // 200
this._log.info("Wiped server; incompatible metadata: " + remoteVersion);
return true;
- }
- else if (remoteVersion > STORAGE_VERSION) {
+ } else if (remoteVersion > STORAGE_VERSION) {
this.status.sync = VERSION_OUT_OF_DATE;
this._log.warn("Upgrade required to access newer storage version.");
return false;
- }
- else if (meta.payload.syncID != this.syncID) {
+ } else if (meta.payload.syncID != this.syncID) {
this._log.info("Sync IDs differ. Local is " + this.syncID + ", remote is " + meta.payload.syncID);
this.resetClient();
this.collectionKeys.clear();
this.syncID = meta.payload.syncID;
this._log.debug("Clear cached values and take syncId: " + this.syncID);
if (!this.upgradeSyncKey(meta.payload.syncID)) {
@@ -1229,18 +1220,17 @@ Sync11Service.prototype = {
// bug 545725 - re-verify creds and fail sanely
if (!this.verifyLogin()) {
this.status.sync = CREDENTIALS_CHANGED;
this._log.info("Credentials have changed, aborting sync and forcing re-login.");
return false;
}
return true;
- }
- else {
+ } else {
if (!this.upgradeSyncKey(meta.payload.syncID)) {
this._log.warn("Failed to upgrade sync key. Failing remote setup.");
return false;
}
if (!this.verifyAndFetchSymmetricKeys(infoResponse)) {
this._log.warn("Failed to fetch symmetric keys. Failing remote setup.");
return false;
@@ -1290,26 +1280,25 @@ Sync11Service.prototype = {
return reason;
},
sync: function sync(engineNamesToSync) {
let dateStr = Utils.formatTimestamp(new Date());
this._log.debug("User-Agent: " + Utils.userAgent);
this._log.info("Starting sync at " + dateStr);
- this._catch(function () {
+ this._catch(function() {
// Make sure we're logged in.
if (this._shouldLogin()) {
this._log.debug("In sync: should login.");
if (!this.login()) {
this._log.debug("Not syncing: login returned false.");
return;
}
- }
- else {
+ } else {
this._log.trace("In sync: no need to login.");
}
return this._lockedSync(engineNamesToSync);
})();
},
/**
* Sync up engines with the server.
@@ -1361,17 +1350,17 @@ Sync11Service.prototype = {
this.uploadMetaGlobal(meta);
}
}))();
},
/**
* Upload meta/global, throwing the response on failure.
*/
- uploadMetaGlobal: function (meta) {
+ uploadMetaGlobal(meta) {
this._log.debug("Uploading meta/global: " + JSON.stringify(meta));
// It would be good to set the X-If-Unmodified-Since header to `timestamp`
// for this PUT to ensure at least some level of transactionality.
// Unfortunately, the servers don't support it after a wipe right now
// (bug 693893), so we're going to defer this until bug 692700.
let res = this.resource(this.metaURL);
let response = res.put(meta);
@@ -1383,17 +1372,17 @@ Sync11Service.prototype = {
/**
* Get a migration sentinel for the Firefox Accounts migration.
* Returns a JSON blob - it is up to callers of this to make sense of the
* data.
*
* Returns a promise that resolves with the sentinel, or null.
*/
- getFxAMigrationSentinel: function() {
+ getFxAMigrationSentinel() {
if (this._shouldLogin()) {
this._log.debug("In getFxAMigrationSentinel: should login.");
if (!this.login()) {
this._log.debug("Can't get migration sentinel: login returned false.");
return Promise.resolve(null);
}
}
if (!this.identity.syncKeyBundle) {
@@ -1429,17 +1418,17 @@ Sync11Service.prototype = {
/**
* Set a migration sentinel for the Firefox Accounts migration.
* Accepts a JSON blob - it is up to callers of this to make sense of the
* data.
*
* Returns a promise that resolves with a boolean which indicates if the
* sentinel was successfully written.
*/
- setFxAMigrationSentinel: function(sentinel) {
+ setFxAMigrationSentinel(sentinel) {
if (this._shouldLogin()) {
this._log.debug("In setFxAMigrationSentinel: should login.");
if (!this.login()) {
this._log.debug("Can't set migration sentinel: login returned false.");
return Promise.resolve(false);
}
}
if (!this.identity.syncKeyBundle) {
--- a/services/sync/modules/stages/declined.js
+++ b/services/sync/modules/stages/declined.js
@@ -16,24 +16,24 @@ var {utils: Cu} = Components;
Cu.import("resource://services-sync/constants.js");
Cu.import("resource://gre/modules/Log.jsm");
Cu.import("resource://services-common/utils.js");
Cu.import("resource://services-common/observers.js");
Cu.import("resource://gre/modules/Preferences.jsm");
-this.DeclinedEngines = function (service) {
+this.DeclinedEngines = function(service) {
this._log = Log.repository.getLogger("Sync.Declined");
this._log.level = Log.Level[new Preferences(PREFS_BRANCH).get("log.logger.declined")];
this.service = service;
}
this.DeclinedEngines.prototype = {
- updateDeclined: function (meta, engineManager=this.service.engineManager) {
+ updateDeclined(meta, engineManager = this.service.engineManager) {
let enabled = new Set(engineManager.getEnabled().map(e => e.name));
let known = new Set(engineManager.getAll().map(e => e.name));
let remoteDeclined = new Set(meta.payload.declined || []);
let localDeclined = new Set(engineManager.getDeclined());
this._log.debug("Handling remote declined: " + JSON.stringify([...remoteDeclined]));
this._log.debug("Handling local declined: " + JSON.stringify([...localDeclined]));
@@ -57,19 +57,19 @@ this.DeclinedEngines.prototype = {
engineManager.setDeclined(newDeclined);
// Any engines that are locally known, locally disabled, and not remotely
// or locally declined, are candidates for enablement.
let undecided = CommonUtils.difference(CommonUtils.difference(known, enabled), newDeclined);
if (undecided.size) {
let subject = {
declined: newDeclined,
- enabled: enabled,
- known: known,
- undecided: undecided,
+ enabled,
+ known,
+ undecided,
};
CommonUtils.nextTick(() => {
Observers.notify("weave:engines:notdeclined", subject);
});
}
return declinedChanged;
},
--- a/services/sync/modules/stages/enginesync.js
+++ b/services/sync/modules/stages/enginesync.js
@@ -126,18 +126,17 @@ EngineSynchronizer.prototype = {
return;
}
// Repeat remoteSetup in-case the commands forced us to reset
if (!(this.service._remoteSetup(info))) {
this.onComplete(new Error("Remote setup failed after processing commands."));
return;
}
- }
- finally {
+ } finally {
// Always immediately attempt to push back the local client (now
// without commands).
// Note that we don't abort here; if there's a 401 because we've
// been reassigned, we'll handle it around another engine.
this._syncEngine(this.service.clientsEngine);
}
}
@@ -314,18 +313,17 @@ EngineSynchronizer.prototype = {
}
}),
// Returns true if sync should proceed.
// false / no return value means sync should be aborted.
_syncEngine: function _syncEngine(engine) {
try {
engine.sync();
- }
- catch(e) {
+ } catch (e) {
if (e.status == 401) {
// Maybe a 401, cluster update perhaps needed?
// We rely on ErrorHandler observing the sync failure notification to
// schedule another sync and clear node assignment values.
// Here we simply want to muffle the exception and return an
// appropriate value.
return false;
}
@@ -336,17 +334,17 @@ EngineSynchronizer.prototype = {
this._log.info(`${engine.name} was interrupted by shutdown; no other engines will sync`);
return false;
}
}
return true;
},
- _updateEnabledFromMeta: function (meta, numClients, engineManager=this.service.engineManager) {
+ _updateEnabledFromMeta(meta, numClients, engineManager = this.service.engineManager) {
this._log.info("Updating enabled engines: " +
numClients + " clients.");
if (meta.isNew || !meta.payload.engines) {
this._log.debug("meta/global isn't new, or is missing engines. Not updating enabled state.");
return;
}
@@ -440,17 +438,17 @@ EngineSynchronizer.prototype = {
engineManager.decline(toDecline);
engineManager.undecline(toUndecline);
Svc.Prefs.resetBranch("engineStatusChanged.");
this.service._ignorePrefObserver = false;
},
- _updateEnabledEngines: function () {
+ _updateEnabledEngines() {
let meta = this.service.recordManager.get(this.service.metaURL);
let numClients = this.service.scheduler.numClients;
let engineManager = this.service.engineManager;
this._updateEnabledFromMeta(meta, numClients, engineManager);
},
};
Object.freeze(EngineSynchronizer.prototype);
--- a/services/sync/modules/status.js
+++ b/services/sync/modules/status.js
@@ -93,19 +93,19 @@ this.Status = {
this.service = SYNC_FAILED_PARTIAL;
}
},
// Implement toString because adding a logger introduces a cyclic object
// value, so we can't trivially debug-print Status as JSON.
toString: function toString() {
return "<Status" +
- ": login: " + Status.login +
+ ": login: " + Status.login +
", service: " + Status.service +
- ", sync: " + Status.sync + ">";
+ ", sync: " + Status.sync + ">";
},
checkSetup: function checkSetup() {
let result = this._authManager.currentAuthState;
if (result == STATUS_OK) {
Status.service = result;
return result;
}
--- a/services/sync/modules/telemetry.js
+++ b/services/sync/modules/telemetry.js
@@ -593,22 +593,20 @@ class SyncTelemetryImpl {
// An event record is a simple array with at least 4 items.
let event = [ts, category, method, object];
// It may have up to 6 elements if |extra| is defined
if (value) {
event.push(value);
if (extra) {
event.push(extra);
}
- } else {
- if (extra) {
+ } else if (extra) {
event.push(null); // a null for the empty value.
event.push(extra);
}
- }
this.events.push(event);
}
observe(subject, topic, data) {
log.trace(`observed ${topic} ${data}`);
switch (topic) {
case "profile-before-change":
--- a/services/sync/modules/userapi.js
+++ b/services/sync/modules/userapi.js
@@ -109,17 +109,17 @@ UserAPI10Client.prototype = {
if (this.adminSecret) {
request.setHeader("X-Weave-Secret", this.adminSecret);
}
request.onComplete = this._onCreateAccount.bind(this, cb, request);
request.put(body);
},
- _getRequest: function _getRequest(username, path, password=null) {
+ _getRequest: function _getRequest(username, path, password = null) {
let url = this.baseURI + username + path;
let request = new RESTRequest(url);
if (password) {
let up = username + ":" + password;
request.setHeader("authorization", "Basic " + btoa(up));
}
@@ -130,23 +130,23 @@ UserAPI10Client.prototype = {
if (error) {
cb(error, null);
return;
}
let body = request.response.body;
if (body == "0") {
cb(null, false);
- return;
+
} else if (body == "1") {
cb(null, true);
- return;
+
} else {
cb(new Error("Unknown response from server: " + body), null);
- return;
+
}
},
_onWeaveNode: function _onWeaveNode(cb, request, error) {
if (error) {
cb.network = true;
cb(error, null);
return;
@@ -173,17 +173,17 @@ UserAPI10Client.prototype = {
case 404:
error.notFound = true;
break;
default:
error.message = "Unexpected response code: " + response.status;
}
cb(error, null);
- return;
+
},
_onChangePassword: function _onChangePassword(cb, request, error) {
this._log.info("Password change response received: " +
request.response.status);
if (error) {
cb(error);
return;
@@ -213,12 +213,12 @@ UserAPI10Client.prototype = {
cb(null, response.body);
return;
}
error = new Error("Could not create user.");
error.body = response.body;
cb(error, null);
- return;
+
},
};
Object.freeze(UserAPI10Client.prototype);
--- a/services/sync/modules/util.js
+++ b/services/sync/modules/util.js
@@ -88,18 +88,17 @@ this.Utils = {
* Optionally pass a function which will be called if an
* exception occurs.
*/
catch: function Utils_catch(func, exceptionCallback) {
let thisArg = this;
return function WrappedCatch() {
try {
return func.call(thisArg);
- }
- catch(ex) {
+ } catch (ex) {
thisArg._log.debug("Exception calling " + (func.name || "anonymous function"), ex);
if (exceptionCallback) {
return exceptionCallback.call(thisArg, ex);
}
return null;
}
};
},
@@ -114,18 +113,17 @@ this.Utils = {
let thisArg = this;
return function WrappedLock() {
if (!thisArg.lock()) {
throw "Could not acquire lock. Label: \"" + label + "\".";
}
try {
return func.call(thisArg);
- }
- finally {
+ } finally {
thisArg.unlock();
}
};
},
isLockException: function isLockException(ex) {
return ex && ex.indexOf && ex.indexOf("Could not acquire lock.") == 0;
},
@@ -161,18 +159,17 @@ this.Utils = {
};
return function WrappedNotify() {
try {
notify("start", null);
let ret = func.call(thisArg);
notify("finish", ret);
return ret;
- }
- catch(ex) {
+ } catch (ex) {
notify("error", ex);
throw ex;
}
};
};
},
/**
@@ -202,24 +199,24 @@ this.Utils = {
deferGetSet: function Utils_deferGetSet(obj, defer, prop) {
if (Array.isArray(prop))
return prop.map(prop => Utils.deferGetSet(obj, defer, prop));
let prot = obj.prototype;
// Create a getter if it doesn't exist yet
if (!prot.__lookupGetter__(prop)) {
- prot.__defineGetter__(prop, function () {
+ prot.__defineGetter__(prop, function() {
return this[defer][prop];
});
}
// Create a setter if it doesn't exist yet
if (!prot.__lookupSetter__(prop)) {
- prot.__defineSetter__(prop, function (val) {
+ prot.__defineSetter__(prop, function(val) {
this[defer][prop] = val;
});
}
},
lazyStrings: function Weave_lazyStrings(name) {
let bundle = "chrome://weave/locale/services/" + name + ".properties";
return () => new StringBundle(bundle);
@@ -359,21 +356,19 @@ this.Utils = {
let json;
try {
json = yield CommonUtils.readJSON(path);
} catch (e) {
if (e instanceof OS.File.Error && e.becauseNoSuchFile) {
// Ignore non-existent files, but explicitly return null.
json = null;
- } else {
- if (that._log) {
+ } else if (that._log) {
that._log.debug("Failed to load json", e);
}
- }
}
if (callback) {
callback.call(that, json);
}
return json;
}),
@@ -497,17 +492,17 @@ this.Utils = {
* * normalizePassphrase:
* take a presentable passphrase and reduce it to a normalized
* representation for storage. normalizePassphrase can safely be called
* on normalized input.
* * normalizeAccount:
* take user input for account/username, cleaning up appropriately.
*/
- isPassphrase: function(s) {
+ isPassphrase(s) {
if (s) {
return /^[abcdefghijkmnpqrstuvwxyz23456789]{26}$/.test(Utils.normalizePassphrase(s));
}
return false;
},
/**
* Hyphenate a passphrase (26 characters) into groups.
@@ -527,17 +522,17 @@ this.Utils = {
// Get the raw data input. Just base32.
let data = passphrase.toLowerCase().replace(/[^abcdefghijkmnpqrstuvwxyz23456789]/g, "");
// This is the neatest way to do this.
if ((data.length == 1) && !omitTrailingDash)
return data + "-";
// Hyphenate it.
- let y = data.substr(0,1);
+ let y = data.substr(0, 1);
let z = data.substr(1).replace(/(.{1,5})/g, "-$1");
// Correct length? We're done.
if ((z.length == 30) || omitTrailingDash)
return y + z;
// Add a trailing dash if appropriate.
return (y + z.replace(/([^-]{5})$/, "$1-")).substr(0, SYNC_KEY_HYPHENATED_LENGTH);
@@ -624,17 +619,17 @@ this.Utils = {
if (!Utils.mpLocked()) {
return true;
}
let sdr = Cc["@mozilla.org/security/sdr;1"]
.getService(Ci.nsISecretDecoderRing);
try {
sdr.encryptString("bacon");
return true;
- } catch(e) {}
+ } catch (e) {}
return false;
},
/**
* Return a value for a backoff interval. Maximum is eight hours, unless
* Status.backoffInterval is higher.
*
*/
@@ -649,36 +644,36 @@ this.Utils = {
/**
* Return a set of hostnames (including the protocol) which may have
* credentials for sync itself stored in the login manager.
*
* In general, these hosts will not have their passwords synced, will be
* reset when we drop sync credentials, etc.
*/
- getSyncCredentialsHosts: function() {
+ getSyncCredentialsHosts() {
let result = new Set(this.getSyncCredentialsHostsLegacy());
for (let host of this.getSyncCredentialsHostsFxA()) {
result.add(host);
}
return result;
},
/*
* Get the "legacy" identity hosts.
*/
- getSyncCredentialsHostsLegacy: function() {
+ getSyncCredentialsHostsLegacy() {
// the legacy sync host
return new Set([PWDMGR_HOST]);
},
/*
* Get the FxA identity hosts.
*/
- getSyncCredentialsHostsFxA: function() {
+ getSyncCredentialsHostsFxA() {
let result = new Set();
// the FxA host
result.add(FxAccountsCommon.FXA_PWDMGR_HOST);
// We used to include the FxA hosts (hence the Set() result) but we now
// don't give them special treatment (hence the Set() with exactly 1 item)
return result;
},
@@ -779,12 +774,12 @@ Svc.__defineGetter__("Crypto", function(
return Svc.Crypto = cryptoSvc;
});
this.Str = {};
["errors", "sync"].forEach(function(lazy) {
XPCOMUtils.defineLazyGetter(Str, lazy, Utils.lazyStrings(lazy));
});
-Svc.Obs.add("xpcom-shutdown", function () {
+Svc.Obs.add("xpcom-shutdown", function() {
for (let name in Svc)
delete Svc[name];
});
--- a/services/sync/services-sync.js
+++ b/services/sync/services-sync.js
@@ -8,23 +8,23 @@ pref("services.sync.miscURL", "misc/");
pref("services.sync.termsURL", "https://services.mozilla.com/tos/");
pref("services.sync.privacyURL", "https://services.mozilla.com/privacy-policy/");
pref("services.sync.statusURL", "https://services.mozilla.com/status/");
pref("services.sync.syncKeyHelpURL", "https://services.mozilla.com/help/synckey");
pref("services.sync.lastversion", "firstrun");
pref("services.sync.sendVersionInfo", true);
-pref("services.sync.scheduler.eolInterval", 604800); // 1 week
-pref("services.sync.scheduler.idleInterval", 3600); // 1 hour
-pref("services.sync.scheduler.activeInterval", 600); // 10 minutes
-pref("services.sync.scheduler.immediateInterval", 90); // 1.5 minutes
-pref("services.sync.scheduler.idleTime", 300); // 5 minutes
+pref("services.sync.scheduler.eolInterval", 604800); // 1 week
+pref("services.sync.scheduler.idleInterval", 3600); // 1 hour
+pref("services.sync.scheduler.activeInterval", 600); // 10 minutes
+pref("services.sync.scheduler.immediateInterval", 90); // 1.5 minutes
+pref("services.sync.scheduler.idleTime", 300); // 5 minutes
-pref("services.sync.scheduler.fxa.singleDeviceInterval", 3600); // 1 hour
+pref("services.sync.scheduler.fxa.singleDeviceInterval", 3600); // 1 hour
pref("services.sync.scheduler.sync11.singleDeviceInterval", 86400); // 1 day
pref("services.sync.errorhandler.networkFailureReportTimeout", 1209600); // 2 weeks
pref("services.sync.engine.addons", true);
pref("services.sync.engine.bookmarks", true);
pref("services.sync.engine.history", true);
pref("services.sync.engine.passwords", true);
--- a/services/sync/tests/tps/mozmill_sanity.js
+++ b/services/sync/tests/tps/mozmill_sanity.js
@@ -16,15 +16,15 @@ var setupTest = function(module) {
var testTestStep = function() {
assert.ok(true, "test Passes");
controller.open("http://www.mozilla.org");
TPS.Login();
TPS.Sync(ACTIONS.ACTION_SYNC_WIPE_CLIENT);
}
-var teardownTest = function () {
+var teardownTest = function() {
assert.ok(true, "teardownTest passes");
}
var teardownModule = function() {
assert.ok(true, "teardownModule passes");
}
--- a/services/sync/tests/tps/test_bug563989.js
+++ b/services/sync/tests/tps/test_bug563989.js
@@ -77,17 +77,17 @@ var bookmarks_to_delete = {
// Add bookmarks to profile1 and sync.
Phase('phase1', [
[Bookmarks.add, bookmarks_initial],
[Bookmarks.verify, bookmarks_initial],
[Sync],
]);
-// Sync to profile2 and verify that the bookmarks are present. Delete
+// Sync to profile2 and verify that the bookmarks are present. Delete
// some bookmarks, and verify that they're not present, but don't sync again.
Phase('phase2', [
[Sync],
[Bookmarks.verify, bookmarks_initial],
[Bookmarks.delete, bookmarks_to_delete],
[Bookmarks.verifyNot, bookmarks_to_delete],
[Bookmarks.skipValidation]
]);
--- a/services/sync/tests/tps/test_bug575423.js
+++ b/services/sync/tests/tps/test_bug575423.js
@@ -53,20 +53,20 @@ var history2 = [
{ type: 2,
date: -36
}
]
},
{ uri: "http://www.google.com/language_tools?hl=en",
title: "Language Tools",
visits: [
- { type: 1,
+ { type: 1,
date: 0
},
- { type: 2,
+ { type: 2,
date: -40
}
]
}
];
/*
* Test phases
--- a/services/sync/tests/tps/test_formdata.js
+++ b/services/sync/tests/tps/test_formdata.js
@@ -75,17 +75,17 @@ Phase('phase2', [
/*
* Note: Weave does not support syncing deleted form data, so those
* tests are disabled below. See bug 568363.
*/
Phase('phase3', [
[Sync],
[Formdata.delete, formdata_delete],
-//[Formdata.verifyNot, formdata_delete],
+// [Formdata.verifyNot, formdata_delete],
[Formdata.verify, formdata2],
// add new data after the first Sync, ensuring the tracker works.
[Formdata.add, formdata_new],
[Sync],
]);
Phase('phase4', [
[Sync],
--- a/services/sync/tests/tps/test_sync.js
+++ b/services/sync/tests/tps/test_sync.js
@@ -27,17 +27,17 @@ var bookmarks_initial = {
loadInSidebar: false,
tags: ["google", "computers", "misc"],
}
},
{ uri: "http://bugzilla.mozilla.org/show_bug.cgi?id=%s",
title: "Bugzilla",
keyword: "bz",
changes: {
- keyword: "bugzilla"
+ keyword: "bugzilla"
}
},
{ folder: "foldera" },
{ uri: "http://www.mozilla.com" },
{ separator: true },
{ folder: "folderb" },
],
"menu/foldera": [
--- a/services/sync/tests/unit/fake_login_manager.js
+++ b/services/sync/tests/unit/fake_login_manager.js
@@ -22,17 +22,17 @@ var fakeSampleLogins = [
function FakeLoginManager(fakeLogins) {
this.fakeLogins = fakeLogins;
let self = this;
// Use a fake nsILoginManager object.
delete Services.logins;
Services.logins = {
- removeAllLogins: function() { self.fakeLogins = []; },
- getAllLogins: function() { return self.fakeLogins; },
- addLogin: function(login) {
+ removeAllLogins() { self.fakeLogins = []; },
+ getAllLogins() { return self.fakeLogins; },
+ addLogin(login) {
getTestLogger().info("nsILoginManager.addLogin() called " +
"with hostname '" + login.hostname + "'.");
self.fakeLogins.push(login);
}
};
}
--- a/services/sync/tests/unit/head_helpers.js
+++ b/services/sync/tests/unit/head_helpers.js
@@ -32,17 +32,17 @@ XPCOMUtils.defineLazyGetter(this, 'SyncP
XPCOMUtils.defineLazyGetter(this, 'SyncPingValidator', function() {
let ns = {};
Cu.import("resource://testing-common/ajv-4.1.1.js", ns);
let ajv = new ns.Ajv({ async: "co*" });
return ajv.compile(SyncPingSchema);
});
var provider = {
- getFile: function(prop, persistent) {
+ getFile(prop, persistent) {
persistent.value = true;
switch (prop) {
case "ExtPrefDL":
return [Services.dirsvc.get("CurProcD", Ci.nsIFile)];
default:
throw Cr.NS_ERROR_FAILURE;
}
},
@@ -152,44 +152,44 @@ function installAddon(name) {
/**
* Convenience function to uninstall an add-on synchronously.
*
* @param addon
* Addon instance to uninstall
*/
function uninstallAddon(addon) {
let cb = Async.makeSyncCallback();
- let listener = {onUninstalled: function(uninstalled) {
+ let listener = {onUninstalled(uninstalled) {
if (uninstalled.id == addon.id) {
AddonManager.removeAddonListener(listener);
cb(uninstalled);
}
}};
AddonManager.addAddonListener(listener);
addon.uninstall();
Async.waitForSyncCallback(cb);
}
-function generateNewKeys(collectionKeys, collections=null) {
+function generateNewKeys(collectionKeys, collections = null) {
let wbo = collectionKeys.generateNewKeysWBO(collections);
let modified = new_timestamp();
collectionKeys.setContents(wbo.cleartext, modified);
}
// Helpers for testing open tabs.
// These reflect part of the internal structure of TabEngine,
// and stub part of Service.wm.
-function mockShouldSkipWindow (win) {
+function mockShouldSkipWindow(win) {
return win.closed ||
win.mockIsPrivate;
}
-function mockGetTabState (tab) {
+function mockGetTabState(tab) {
return tab;
}
function mockGetWindowEnumerator(url, numWindows, numTabs, indexes, moreURLs) {
let elements = [];
function url2entry(url) {
return {
@@ -199,17 +199,17 @@ function mockGetWindowEnumerator(url, nu
}
for (let w = 0; w < numWindows; ++w) {
let tabs = [];
let win = {
closed: false,
mockIsPrivate: false,
gBrowser: {
- tabs: tabs,
+ tabs,
},
};
elements.push(win);
for (let t = 0; t < numTabs; ++t) {
tabs.push(TestingUtils.deepCopy({
index: indexes ? indexes() : 1,
entries: (moreURLs ? [url].concat(moreURLs()) : [url]).map(url2entry),
@@ -224,30 +224,30 @@ function mockGetWindowEnumerator(url, nu
// Always include a closed window and a private window.
elements.push({
closed: true,
mockIsPrivate: false,
gBrowser: {
tabs: [],
},
});
-
+
elements.push({
closed: false,
mockIsPrivate: true,
gBrowser: {
tabs: [],
},
});
return {
- hasMoreElements: function () {
+ hasMoreElements() {
return elements.length;
},
- getNext: function () {
+ getNext() {
return elements.shift();
},
};
}
// Helper that allows checking array equality.
function do_check_array_eq(a1, a2) {
do_check_eq(a1.length, a2.length);
@@ -445,17 +445,17 @@ function sync_engine_and_validate_telem(
}
// Returns a promise that resolves once the specified observer notification
// has fired.
function promiseOneObserver(topic, callback) {
return new Promise((resolve, reject) => {
let observer = function(subject, data) {
Svc.Obs.remove(topic, observer);
- resolve({ subject: subject, data: data });
+ resolve({ subject, data });
}
Svc.Obs.add(topic, observer)
});
}
function promiseStopServer(server) {
return new Promise(resolve => server.stop(resolve));
}
--- a/services/sync/tests/unit/head_http_server.js
+++ b/services/sync/tests/unit/head_http_server.js
@@ -67,43 +67,43 @@ function ServerWBO(id, initialPayload, m
this.modified = modified || new_timestamp();
}
ServerWBO.prototype = {
get data() {
return JSON.parse(this.payload);
},
- get: function() {
+ get() {
return JSON.stringify(this, ["id", "modified", "payload"]);
},
- put: function(input) {
+ put(input) {
input = JSON.parse(input);
this.payload = input.payload;
this.modified = new_timestamp();
},
- delete: function() {
+ delete() {
delete this.payload;
delete this.modified;
},
// This handler sets `newModified` on the response body if the collection
// timestamp has changed. This allows wrapper handlers to extract information
// that otherwise would exist only in the body stream.
- handler: function() {
+ handler() {
let self = this;
return function(request, response) {
var statusCode = 200;
var status = "OK";
var body;
- switch(request.method) {
+ switch (request.method) {
case "GET":
if (self.payload) {
body = self.get();
} else {
statusCode = 404;
status = "Not Found";
body = "Not Found";
}
@@ -211,18 +211,18 @@ ServerCollection.prototype = {
return os;
},
/**
* Convenience method to get an array of parsed ciphertexts.
*
* @return an array of the payloads of each stored WBO.
*/
- payloads: function () {
- return this.wbos().map(function (wbo) {
+ payloads() {
+ return this.wbos().map(function(wbo) {
return JSON.parse(JSON.parse(wbo.payload).ciphertext);
});
},
// Just for syntactic elegance.
wbo: function wbo(id) {
return this._wbos[id];
},
@@ -262,34 +262,34 @@ ServerCollection.prototype = {
*
* @param id
* (string) ID to remove.
*/
remove: function remove(id) {
delete this._wbos[id];
},
- _inResultSet: function(wbo, options) {
+ _inResultSet(wbo, options) {
return wbo.payload
&& (!options.ids || (options.ids.indexOf(wbo.id) != -1))
&& (!options.newer || (wbo.modified > options.newer));
},
- count: function(options) {
+ count(options) {
options = options || {};
let c = 0;
for (let [id, wbo] of Object.entries(this._wbos)) {
if (wbo.modified && this._inResultSet(wbo, options)) {
c++;
}
}
return c;
},
- get: function(options) {
+ get(options) {
let result;
if (options.full) {
let data = [];
for (let [id, wbo] of Object.entries(this._wbos)) {
// Drop deleted.
if (wbo.modified && this._inResultSet(wbo, options)) {
data.push(wbo.get());
}
@@ -325,17 +325,17 @@ ServerCollection.prototype = {
data = data.slice(start);
}
result = JSON.stringify(data);
options.recordCount = data.length;
}
return result;
},
- post: function(input) {
+ post(input) {
input = JSON.parse(input);
let success = [];
let failed = {};
// This will count records where we have an existing ServerWBO
// registered with us as successful and all other records as failed.
for (let key in input) {
let record = input[key];
@@ -350,35 +350,35 @@ ServerCollection.prototype = {
wbo.payload = record.payload;
wbo.modified = new_timestamp();
success.push(record.id);
} else {
failed[record.id] = "no wbo configured";
}
}
return {modified: new_timestamp(),
- success: success,
- failed: failed};
+ success,
+ failed};
},
- delete: function(options) {
+ delete(options) {
let deleted = [];
for (let [id, wbo] of Object.entries(this._wbos)) {
if (this._inResultSet(wbo, options)) {
this._log.debug("Deleting " + JSON.stringify(wbo));
deleted.push(wbo.id);
wbo.delete();
}
}
return deleted;
},
// This handler sets `newModified` on the response body if the collection
// timestamp has changed.
- handler: function() {
+ handler() {
let self = this;
return function(request, response) {
var statusCode = 200;
var status = "OK";
var body;
// Parse queryString
@@ -402,17 +402,17 @@ ServerCollection.prototype = {
}
if (options.limit) {
options.limit = parseInt(options.limit, 10);
}
if (options.offset) {
options.offset = parseInt(options.offset, 10);
}
- switch(request.method) {
+ switch (request.method) {
case "GET":
body = self.get(options, request);
// see http://moz-services-docs.readthedocs.io/en/latest/storage/apis-1.5.html
// for description of these headers.
let { recordCount: records, nextOffset } = options;
self._log.info("Records: " + records + ", nextOffset: " + nextOffset);
if (records != null) {
@@ -501,17 +501,17 @@ function track_collections_helper() {
};
}
/*
* Return the info/collections object.
*/
function info_collections(request, response) {
let body = "Error.";
- switch(request.method) {
+ switch (request.method) {
case "GET":
body = JSON.stringify(collections);
break;
default:
throw "Non-GET on info_collections.";
}
response.setHeader("Content-Type", "application/json");
@@ -523,19 +523,19 @@ function track_collections_helper() {
}
return {"collections": collections,
"handler": info_collections,
"with_updated_collection": with_updated_collection,
"update_collection": update_collection};
}
-//===========================================================================//
+// ===========================================================================//
// httpd.js-based Sync server. //
-//===========================================================================//
+// ===========================================================================//
/**
* In general, the preferred way of using SyncServer is to directly introspect
* it. Callbacks are available for operations which are hard to verify through
* introspection, such as deletions.
*
* One of the goals of this server is to provide enough hooks for test code to
* find out what it needs without monkeypatching. Use this object as your
@@ -650,17 +650,17 @@ SyncServer.prototype = {
*
* @return a user object, as would be returned by server.user(username).
*/
registerUser: function registerUser(username, password) {
if (username in this.users) {
throw new Error("User already exists.");
}
this.users[username] = {
- password: password,
+ password,
collections: {}
};
return this.user(username);
},
userExists: function userExists(username) {
return username in this.users;
},
@@ -758,26 +758,26 @@ SyncServer.prototype = {
* u.collection("bookmarks").wbo("abcdefg").payload; // Etc.
*
* @return a proxy for the user data stored in this server.
*/
user: function user(username) {
let collection = this.getCollection.bind(this, username);
let createCollection = this.createCollection.bind(this, username);
let createContents = this.createContents.bind(this, username);
- let modified = function (collectionName) {
+ let modified = function(collectionName) {
return collection(collectionName).timestamp;
}
let deleteCollections = this.deleteCollections.bind(this, username);
return {
- collection: collection,
- createCollection: createCollection,
- createContents: createContents,
- deleteCollections: deleteCollections,
- modified: modified
+ collection,
+ createCollection,
+ createContents,
+ deleteCollections,
+ modified
};
},
/*
* Regular expressions for splitting up Sync request paths.
* Sync URLs are of the form:
* /$apipath/$version/$user/$further
* where $further is usually:
--- a/services/sync/tests/unit/test_addon_utils.js
+++ b/services/sync/tests/unit/test_addon_utils.js
@@ -14,17 +14,17 @@ const SERVER_ADDRESS = "http://127.0.0.1
var prefs = new Preferences();
prefs.set("extensions.getAddons.get.url",
SERVER_ADDRESS + "/search/guid:%IDS%");
loadAddonTestFunctions();
startupManager();
-function createAndStartHTTPServer(port=HTTP_PORT) {
+function createAndStartHTTPServer(port = HTTP_PORT) {
try {
let server = new HttpServer();
let bootstrap1XPI = ExtensionsTestPath("/addons/test_bootstrap1_1.xpi");
server.registerFile("/search/guid:missing-sourceuri%40tests.mozilla.org",
do_get_file("missing-sourceuri.xml"));
@@ -76,25 +76,25 @@ add_test(function test_ignore_untrusted_
const bad = ["http://example.com/foo.xpi",
"ftp://example.com/foo.xpi",
"silly://example.com/foo.xpi"];
const good = ["https://example.com/foo.xpi"];
for (let s of bad) {
let sourceURI = ioService.newURI(s);
- let addon = {sourceURI: sourceURI, name: "bad", id: "bad"};
+ let addon = {sourceURI, name: "bad", id: "bad"};
let canInstall = AddonUtils.canInstallAddon(addon);
do_check_false(canInstall, "Correctly rejected a bad URL");
}
for (let s of good) {
let sourceURI = ioService.newURI(s);
- let addon = {sourceURI: sourceURI, name: "good", id: "good"};
+ let addon = {sourceURI, name: "good", id: "good"};
let canInstall = AddonUtils.canInstallAddon(addon);
do_check_true(canInstall, "Correctly accepted a good URL");
}
run_next_test();
});
add_test(function test_source_uri_rewrite() {
@@ -110,22 +110,22 @@ add_test(function test_source_uri_rewrit
AddonUtils.__proto__.installAddonFromSearchResult =
function testInstallAddon(addon, metadata, cb) {
do_check_eq(SERVER_ADDRESS + "/require.xpi?src=sync",
addon.sourceURI.spec);
installCalled = true;
- AddonUtils.getInstallFromSearchResult(addon, function (error, install) {
+ AddonUtils.getInstallFromSearchResult(addon, function(error, install) {
do_check_null(error);
do_check_eq(SERVER_ADDRESS + "/require.xpi?src=sync",
install.sourceURI.spec);
- cb(null, {id: addon.id, addon: addon, install: install});
+ cb(null, {id: addon.id, addon, install});
}, false);
};
let server = createAndStartHTTPServer();
let installCallback = Async.makeSpinningCallback();
let installOptions = {
id: "rewrite@tests.mozilla.org",
--- a/services/sync/tests/unit/test_addons_engine.js
+++ b/services/sync/tests/unit/test_addons_engine.js
@@ -178,17 +178,17 @@ add_task(async function test_disabled_in
amoServer.registerFile("/addon1.xpi", do_get_file(installXPI));
amoServer.start(8888);
// Insert an existing record into the server.
let id = Utils.makeGUID();
let now = Date.now() / 1000;
let record = encryptPayload({
- id: id,
+ id,
applicationID: Services.appinfo.ID,
addonID: ADDON_ID,
enabled: false,
deleted: false,
source: "amo",
});
let wbo = new ServerWBO(id, record, now - 2);
server.insertWBO(USER, "addons", wbo);
--- a/services/sync/tests/unit/test_addons_store.js
+++ b/services/sync/tests/unit/test_addons_store.js
@@ -50,19 +50,19 @@ var reconciler = engine._reconciler;
*
* @param id Sync GUID of record
* @param addonId ID of add-on
* @param enabled Boolean whether record is enabled
* @param deleted Boolean whether record was deleted
*/
function createRecordForThisApp(id, addonId, enabled, deleted) {
return {
- id: id,
+ id,
addonID: addonId,
- enabled: enabled,
+ enabled,
deleted: !!deleted,
applicationID: Services.appinfo.ID,
source: "amo"
};
}
function createAndStartHTTPServer(port) {
try {
@@ -438,17 +438,17 @@ add_test(function test_create_bad_instal
// was not being installed due to requireSecureURL checking *before* we'd
// attempted to get the XPI.
// With requireSecureURL disabled we do see a download failure, but the addon
// *does* get added to |failed|.
// FTR: onDownloadFailed() is called with ERROR_NETWORK_FAILURE, so it's going
// to be tricky to distinguish a 404 from other transient network errors
// where we do want the addon to end up in |failed|.
// This is being tracked in bug 1284778.
- //do_check_eq(0, failed.length);
+ // do_check_eq(0, failed.length);
let addon = getAddonFromAddonManagerByID(id);
do_check_eq(null, addon);
server.stop(run_next_test);
});
add_test(function test_ignore_system() {
--- a/services/sync/tests/unit/test_addons_tracker.js
+++ b/services/sync/tests/unit/test_addons_tracker.js
@@ -120,24 +120,24 @@ add_test(function test_track_user_disabl
do_check_true(addon.isActive);
Svc.Obs.notify("weave:engine:start-tracking");
do_check_eq(0, tracker.score);
let cb = Async.makeSyncCallback();
let listener = {
- onDisabled: function(disabled) {
+ onDisabled(disabled) {
_("onDisabled");
if (disabled.id == addon.id) {
AddonManager.removeAddonListener(listener);
cb();
}
},
- onDisabling: function(disabling) {
+ onDisabling(disabling) {
_("onDisabling add-on");
}
};
AddonManager.addAddonListener(listener);
_("Disabling add-on");
addon.userDisabled = true;
_("Disabling started...");
--- a/services/sync/tests/unit/test_bookmark_batch_fail.js
+++ b/services/sync/tests/unit/test_bookmark_batch_fail.js
@@ -10,14 +10,13 @@ function run_test() {
engine._syncStartup = function() {
throw "FAIL!";
};
try {
_("Try calling the sync that should throw right away");
engine._sync();
do_throw("Should have failed sync!");
- }
- catch(ex) {
+ } catch (ex) {
_("Making sure what we threw ended up as the exception:", ex);
do_check_eq(ex, "FAIL!");
}
}
--- a/services/sync/tests/unit/test_bookmark_duping.js
+++ b/services/sync/tests/unit/test_bookmark_duping.js
@@ -102,17 +102,17 @@ async function validate(collection, expe
let validator = new BookmarkValidator();
let records = collection.payloads();
let problems = validator.inspectServerRecords(records).problemData;
// all non-zero problems.
let summary = problems.getSummary().filter(prob => prob.count != 0);
// split into 2 arrays - expected and unexpected.
- let isInExpectedFailures = elt => {
+ let isInExpectedFailures = elt => {
for (let i = 0; i < expectedFailures.length; i++) {
if (elt.name == expectedFailures[i].name && elt.count == expectedFailures[i].count) {
return true;
}
}
return false;
}
let expected = [];
--- a/services/sync/tests/unit/test_bookmark_engine.js
+++ b/services/sync/tests/unit/test_bookmark_engine.js
@@ -341,17 +341,17 @@ add_task(async function test_processInco
// Make the 10 minutes old so it will only be synced in the toFetch phase.
bogus_record.modified = Date.now() / 1000 - 60 * 10;
engine.lastSync = Date.now() / 1000 - 60;
engine.toFetch = [BOGUS_GUID];
let error;
try {
await sync_engine_and_validate_telem(engine, true)
- } catch(ex) {
+ } catch (ex) {
error = ex;
}
ok(!!error);
// Verify that the bookmark order has been applied.
let new_children = store.createRecord(folder1_guid).children;
do_check_eq(new_children.length, 2);
do_check_eq(new_children[0], folder1_payload.children[0]);
@@ -414,25 +414,25 @@ add_task(async function test_restoreProm
let bmk2_guid = store.GUIDForId(bmk2_id);
_("Get Thunderbird!: " + bmk2_id + ", " + bmk2_guid);
PlacesUtils.bookmarks.removeItem(bmk1_id);
let error;
try {
await sync_engine_and_validate_telem(engine, false);
- } catch(ex) {
+ } catch (ex) {
error = ex;
_("Got error: " + Log.exceptionStr(ex));
}
do_check_true(!error);
_("Verify that there's only one bookmark on the server, and it's Thunderbird.");
// Of course, there's also the Bookmarks Toolbar and Bookmarks Menu...
- let wbos = collection.keys(function (id) {
+ let wbos = collection.keys(function(id) {
return ["menu", "toolbar", "mobile", "unfiled", folder1_guid].indexOf(id) == -1;
});
do_check_eq(wbos.length, 1);
do_check_eq(wbos[0], bmk2_guid);
_("Now restore from a backup.");
await BookmarkJSONUtils.importFromFile(backupFile, true);
@@ -458,34 +458,34 @@ add_task(async function test_restoreProm
do_check_true(found);
_("Have the correct number of IDs locally, too.");
do_check_eq(count, ["menu", "toolbar", "mobile", "unfiled", folder1_id, bmk1_id].length);
_("Sync again. This'll wipe bookmarks from the server.");
try {
await sync_engine_and_validate_telem(engine, false);
- } catch(ex) {
+ } catch (ex) {
error = ex;
_("Got error: " + Log.exceptionStr(ex));
}
do_check_true(!error);
_("Verify that there's only one bookmark on the server, and it's Firefox.");
// Of course, there's also the Bookmarks Toolbar and Bookmarks Menu...
let payloads = server.user("foo").collection("bookmarks").payloads();
- let bookmarkWBOs = payloads.filter(function (wbo) {
+ let bookmarkWBOs = payloads.filter(function(wbo) {
return wbo.type == "bookmark";
});
- let folderWBOs = payloads.filter(function (wbo) {
+ let folderWBOs = payloads.filter(function(wbo) {
return ((wbo.type == "folder") &&
- (wbo.id != "menu") &&
- (wbo.id != "toolbar") &&
- (wbo.id != "unfiled") &&
- (wbo.id != "mobile"));
+ (wbo.id != "menu") &&
+ (wbo.id != "toolbar") &&
+ (wbo.id != "unfiled") &&
+ (wbo.id != "mobile"));
});
do_check_eq(bookmarkWBOs.length, 1);
do_check_eq(bookmarkWBOs[0].id, newFX);
do_check_eq(bookmarkWBOs[0].bmkUri, fxuri.spec);
do_check_eq(bookmarkWBOs[0].title, "Get Firefox!");
_("Our old friend Folder 1 is still in play.");
@@ -711,28 +711,28 @@ add_task(async function test_misreconcil
description: "Now you're for it.",
parentName: "",
parentid: "mobile", // Why not?
children: [],
};
let rec = new FakeRecord(BookmarkFolder, to_apply);
let encrypted = encryptPayload(rec.cleartext);
- encrypted.decrypt = function () {
+ encrypted.decrypt = function() {
for (let x in rec) {
encrypted[x] = rec[x];
}
};
_("Applying record.");
engine._processIncoming({
getBatched() {
return this.get();
},
- get: function () {
+ get() {
this.recordHandler(encrypted);
return {success: true}
},
});
// Ensure that afterwards, toolbar is still there.
// As of 2012-12-05, this only passes because Places doesn't use "toolbar" as
// the real GUID, instead using a generated one. Sync does the translation.
--- a/services/sync/tests/unit/test_bookmark_smart_bookmarks.js
+++ b/services/sync/tests/unit/test_bookmark_smart_bookmarks.js
@@ -106,17 +106,17 @@ add_task(async function test_annotation_
_("Our count has increased since we started.");
do_check_eq(smartBookmarkCount(), startCount + 1);
_("Sync record to the server.");
let collection = server.user("foo").collection("bookmarks");
try {
await sync_engine_and_validate_telem(engine, false);
- let wbos = collection.keys(function (id) {
+ let wbos = collection.keys(function(id) {
return ["menu", "toolbar", "mobile", "unfiled"].indexOf(id) == -1;
});
do_check_eq(wbos.length, 1);
_("Verify that the server WBO has the annotation.");
let serverGUID = wbos[0];
do_check_eq(serverGUID, guid);
let serverWBO = collection.wbo(serverGUID);
--- a/services/sync/tests/unit/test_bookmark_store.js
+++ b/services/sync/tests/unit/test_bookmark_store.js
@@ -103,17 +103,17 @@ add_test(function test_bookmark_create()
do_check_eq(store.GUIDForId(id), tbrecord.id);
do_check_eq(PlacesUtils.bookmarks.getItemType(id),
PlacesUtils.bookmarks.TYPE_BOOKMARK);
do_check_true(PlacesUtils.bookmarks.getBookmarkURI(id).equals(tburi));
do_check_eq(PlacesUtils.bookmarks.getItemTitle(id), null);
let error;
try {
PlacesUtils.annotations.getItemAnnotation(id, "bookmarkProperties/description");
- } catch(ex) {
+ } catch (ex) {
error = ex;
}
do_check_eq(error.result, Cr.NS_ERROR_NOT_AVAILABLE);
do_check_eq(PlacesUtils.bookmarks.getFolderIdForItem(id),
PlacesUtils.bookmarks.toolbarFolder);
do_check_eq(PlacesUtils.bookmarks.getKeywordForBookmark(id), null);
} finally {
_("Clean up.");
@@ -139,17 +139,17 @@ add_test(function test_bookmark_update()
let record = store.createRecord(bmk1_guid);
record.title = null;
record.description = null;
record.keyword = null;
record.tags = null;
store.applyIncoming(record);
_("Verify that the values have been cleared.");
- do_check_throws(function () {
+ do_check_throws(function() {
PlacesUtils.annotations.getItemAnnotation(
bmk1_id, "bookmarkProperties/description");
}, Cr.NS_ERROR_NOT_AVAILABLE);
do_check_eq(PlacesUtils.bookmarks.getItemTitle(bmk1_id), null);
do_check_eq(PlacesUtils.bookmarks.getKeywordForBookmark(bmk1_id), null);
} finally {
_("Clean up.");
store.wipe();
@@ -256,17 +256,17 @@ add_task(async function test_deleted() {
let record = new PlacesItem("bookmarks", bmk1_guid);
record.deleted = true;
store.applyIncoming(record);
await store.deletePending();
_("Ensure it has been deleted.");
let error;
try {
PlacesUtils.bookmarks.getBookmarkURI(bmk1_id);
- } catch(ex) {
+ } catch (ex) {
error = ex;
}
do_check_eq(error.result, Cr.NS_ERROR_ILLEGAL_VALUE);
let newrec = store.createRecord(bmk1_guid);
do_check_eq(newrec.deleted, true);
} finally {
@@ -356,17 +356,17 @@ add_test(function test_orphan() {
PlacesUtils.bookmarks.toolbarFolder, fxuri,
PlacesUtils.bookmarks.DEFAULT_INDEX, "Get Firefox!");
let bmk1_guid = store.GUIDForId(bmk1_id);
do_check_eq(PlacesUtils.bookmarks.getFolderIdForItem(bmk1_id),
PlacesUtils.bookmarks.toolbarFolder);
let error;
try {
PlacesUtils.annotations.getItemAnnotation(bmk1_id, PARENT_ANNO);
- } catch(ex) {
+ } catch (ex) {
error = ex;
}
do_check_eq(error.result, Cr.NS_ERROR_NOT_AVAILABLE);
_("Apply a server record that is the same but refers to non-existent folder.");
let record = store.createRecord(bmk1_guid);
record.parentid = "non-existent";
store.applyIncoming(record);
@@ -419,17 +419,17 @@ add_test(function test_empty_query_doesn
record.parentName = "Toolbar";
record.parentid = "toolbar";
// These should not throw.
store.applyIncoming(record);
delete record.folderName;
store.applyIncoming(record);
-
+
run_next_test();
});
function assertDeleted(id) {
let error;
try {
PlacesUtils.bookmarks.getItemType(id);
} catch (e) {
--- a/services/sync/tests/unit/test_bookmark_tracker.js
+++ b/services/sync/tests/unit/test_bookmark_tracker.js
@@ -211,17 +211,17 @@ add_task(async function test_tracking()
});
add_task(async function test_batch_tracking() {
_("Test tracker does the correct thing during and after a places 'batch'");
await startTracking();
PlacesUtils.bookmarks.runInBatchMode({
- runBatched: function() {
+ runBatched() {
let folder = PlacesUtils.bookmarks.createFolder(
PlacesUtils.bookmarks.bookmarksMenuFolder,
"Test Folder", PlacesUtils.bookmarks.DEFAULT_INDEX);
// We should be tracking the new folder and its parent (and need to jump
// through blocking hoops...)
Async.promiseSpinningly(verifyTrackedCount(2));
// But not have bumped the score.
do_check_eq(tracker.score, 0);
@@ -235,20 +235,20 @@ add_task(async function test_batch_track
});
add_task(async function test_nested_batch_tracking() {
_("Test tracker does the correct thing if a places 'batch' is nested");
await startTracking();
PlacesUtils.bookmarks.runInBatchMode({
- runBatched: function() {
+ runBatched() {
PlacesUtils.bookmarks.runInBatchMode({
- runBatched: function() {
+ runBatched() {
let folder = PlacesUtils.bookmarks.createFolder(
PlacesUtils.bookmarks.bookmarksMenuFolder,
"Test Folder", PlacesUtils.bookmarks.DEFAULT_INDEX);
// We should be tracking the new folder and its parent (and need to jump
// through blocking hoops...)
Async.promiseSpinningly(verifyTrackedCount(2));
// But not have bumped the score.
do_check_eq(tracker.score, 0);
@@ -271,17 +271,17 @@ add_task(async function test_tracker_sql
const SQLITE_MAX_VARIABLE_NUMBER = 999;
let numItems = SQLITE_MAX_VARIABLE_NUMBER * 2 + 10;
let createdIDs = [];
await startTracking();
PlacesUtils.bookmarks.runInBatchMode({
- runBatched: function() {
+ runBatched() {
for (let i = 0; i < numItems; i++) {
let syncBmkID = PlacesUtils.bookmarks.insertBookmark(
PlacesUtils.bookmarks.unfiledBookmarksFolder,
Utils.makeURI("https://example.org/" + i),
PlacesUtils.bookmarks.DEFAULT_INDEX,
"Sync Bookmark " + i);
createdIDs.push(syncBmkID);
}
--- a/services/sync/tests/unit/test_bookmark_validator.js
+++ b/services/sync/tests/unit/test_bookmark_validator.js
@@ -100,17 +100,17 @@ add_test(function test_isr_duplicatesAnd
{id: 'A', type: 'folder', parentid: 'places', children: []},
{type: 'folder', parentid: 'places', children: []}
]).problemData;
equal(c.missingIDs, 1);
deepEqual(c.duplicates, ['A']);
run_next_test();
});
-add_test(function test_isr_duplicateChildren() {
+add_test(function test_isr_duplicateChildren() {
let c = inspectServerRecords([
{id: 'A', type: 'folder', parentid: 'places', children: ['B', 'B']},
{id: 'B', type: 'bookmark', parentid: 'A'},
]).problemData;
deepEqual(c.duplicateChildren, ['A']);
run_next_test();
});
--- a/services/sync/tests/unit/test_browserid_identity.js
+++ b/services/sync/tests/unit/test_browserid_identity.js
@@ -41,17 +41,17 @@ MockFxAccountsClient.prototype = {
return Promise.resolve(true);
}
};
function MockFxAccounts() {
let fxa = new FxAccounts({
_now_is: Date.now(),
- now: function () {
+ now() {
return this._now_is;
},
fxAccountsClient: new MockFxAccountsClient()
});
fxa.internal.currentAccountState.getCertificate = function(data, keyPair, mustBeValidUntil) {
this.cert = {
validUntil: fxa.internal.now() + CERT_LIFETIME,
@@ -62,17 +62,17 @@ function MockFxAccounts() {
return fxa;
}
function run_test() {
initTestLogging("Trace");
Log.repository.getLogger("Sync.Identity").level = Log.Level.Trace;
Log.repository.getLogger("Sync.BrowserIDManager").level = Log.Level.Trace;
run_next_test();
-};
+}
add_test(function test_initial_state() {
_("Verify initial state");
do_check_false(!!browseridManager._token);
do_check_false(browseridManager.hasValidToken());
run_next_test();
}
);
@@ -382,17 +382,17 @@ add_test(function test_sha256() {
["abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
"248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"],
["For this sample, this 63-byte string will be used as input data",
"f08a78cbbaee082b052ae0708f32fa1e50c5c421aa772ba5dbb406a2ea6be342"],
["This is exactly 64 bytes long, not counting the terminating byte",
"ab64eff7e88e2e46165e29f2bce41826bd4c7b3552f6b382a9e7d3af47c245f8"]
];
let bidUser = new BrowserIDManager();
- for (let [input,output] of vectors) {
+ for (let [input, output] of vectors) {
do_check_eq(CommonUtils.bytesAsHex(bidUser._sha256(input)), output);
}
run_next_test();
});
add_test(function test_computeXClientStateHeader() {
let kBhex = "fd5c747806c07ce0b9d69dcfea144663e630b65ec4963596a22f24910d7dd15d";
let kB = CommonUtils.hexToBytes(kBhex);
@@ -700,17 +700,17 @@ add_task(async function test_getKeysMiss
delete identityConfig.fxaccount.user.kA;
delete identityConfig.fxaccount.user.kB;
identityConfig.fxaccount.user.keyFetchToken = 'keyFetchToken';
configureFxAccountIdentity(browseridManager, identityConfig);
// Mock a fxAccounts object that returns no keys
let fxa = new FxAccounts({
- fetchAndUnwrapKeys: function () {
+ fetchAndUnwrapKeys() {
return Promise.resolve({});
},
fxAccountsClient: new MockFxAccountsClient(),
newAccountState(credentials) {
// We only expect this to be called with null indicating the (mock)
// storage should be read.
if (credentials) {
throw new Error("Not expecting to have credentials passed");
@@ -752,17 +752,17 @@ add_task(async function test_signedInUse
// Delete stored keys and the key fetch token.
delete identityConfig.fxaccount.user.kA;
delete identityConfig.fxaccount.user.kB;
delete identityConfig.fxaccount.user.keyFetchToken;
configureFxAccountIdentity(browseridManager, identityConfig);
let fxa = new FxAccounts({
- fetchAndUnwrapKeys: function () {
+ fetchAndUnwrapKeys() {
return Promise.resolve({});
},
fxAccountsClient: new MockFxAccountsClient(),
newAccountState(credentials) {
// We only expect this to be called with null indicating the (mock)
// storage should be read.
if (credentials) {
throw new Error("Not expecting to have credentials passed");
@@ -790,24 +790,24 @@ add_task(async function test_signedInUse
// A token server mock will be used that doesn't hit a server, so we move
// directly to a hawk request.
async function initializeIdentityWithHAWKResponseFactory(config, cbGetResponse) {
// A mock request object.
function MockRESTRequest(uri, credentials, extra) {
this._uri = uri;
this._credentials = credentials;
this._extra = extra;
- };
+ }
MockRESTRequest.prototype = {
- setHeader: function() {},
- post: function(data, callback) {
+ setHeader() {},
+ post(data, callback) {
this.response = cbGetResponse("post", data, this._uri, this._credentials, this._extra);
callback.call(this);
},
- get: function(callback) {
+ get(callback) {
// Skip /status requests (browserid_identity checks if the account still
// exists after an auth error)
if (this._uri.startsWith("http://mockedserver:9999/account/status")) {
this.response = {
status: 200,
headers: {"content-type": "application/json"},
body: JSON.stringify({exists: true}),
};
@@ -853,31 +853,31 @@ async function initializeIdentityWithHAW
"expecting rejection due to hawk error");
}
function getTimestamp(hawkAuthHeader) {
return parseInt(/ts="(\d+)"/.exec(hawkAuthHeader)[1], 10) * SECOND_MS;
}
-function getTimestampDelta(hawkAuthHeader, now=Date.now()) {
+function getTimestampDelta(hawkAuthHeader, now = Date.now()) {
return Math.abs(getTimestamp(hawkAuthHeader) - now);
}
function mockTokenServer(func) {
let requestLog = Log.repository.getLogger("testing.mock-rest");
if (!requestLog.appenders.length) { // might as well see what it says :)
requestLog.addAppender(new Log.DumpAppender());
requestLog.level = Log.Level.Trace;
}
- function MockRESTRequest(url) {};
+ function MockRESTRequest(url) {}
MockRESTRequest.prototype = {
_log: requestLog,
- setHeader: function() {},
- get: function(callback) {
+ setHeader() {},
+ get(callback) {
this.response = func();
callback.call(this);
}
}
// The mocked TokenServer client which will get the response.
function MockTSC() { }
MockTSC.prototype = new TokenServerClient();
MockTSC.prototype.constructor = MockTSC;
--- a/services/sync/tests/unit/test_clients_engine.js
+++ b/services/sync/tests/unit/test_clients_engine.js
@@ -56,20 +56,20 @@ add_task(async function test_bad_hmac()
syncID: engine.syncID}}}},
clients: {},
crypto: {}
};
let deletedCollections = [];
let deletedItems = [];
let callback = {
__proto__: SyncServerCallback,
- onItemDeleted: function (username, coll, wboID) {
+ onItemDeleted(username, coll, wboID) {
deletedItems.push(coll + "/" + wboID);
},
- onCollectionDeleted: function (username, coll) {
+ onCollectionDeleted(username, coll) {
deletedCollections.push(coll);
}
}
let server = serverForUsers({"foo": "password"}, contents, callback);
let user = server.user("foo");
function check_clients_count(expectedCount) {
let stack = Components.stack.caller;
@@ -1447,17 +1447,17 @@ add_task(async function test_command_syn
let notifiedIds;
engine.sendCommand("wipeAll", []);
engine._tracker.addChangedID(engine.localID);
engine.getClientFxaDeviceId = (id) => "fxa-" + id;
engine._notifyCollectionChanged = (ids) => (notifiedIds = ids);
_("Syncing.");
engine._sync();
- deepEqual(notifiedIds, ["fxa-fake-guid-00","fxa-fake-guid-01"]);
+ deepEqual(notifiedIds, ["fxa-fake-guid-00", "fxa-fake-guid-01"]);
ok(!notifiedIds.includes(engine.getClientFxaDeviceId(engine.localID)),
"We never notify the local device");
} finally {
Svc.Prefs.resetBranch("");
Service.recordManager.clearCache();
engine._tracker.clearChangedIDs();
--- a/services/sync/tests/unit/test_collections_recovery.js
+++ b/services/sync/tests/unit/test_collections_recovery.js
@@ -8,31 +8,31 @@ Cu.import("resource://testing-common/ser
add_identity_test(this, async function test_missing_crypto_collection() {
let johnHelper = track_collections_helper();
let johnU = johnHelper.with_updated_collection;
let johnColls = johnHelper.collections;
let empty = false;
function maybe_empty(handler) {
- return function (request, response) {
+ return function(request, response) {
if (empty) {
let body = "{}";
response.setStatusLine(request.httpVersion, 200, "OK");
response.bodyOutputStream.write(body, body.length);
} else {
handler(request, response);
}
};
}
let handlers = {
"/1.1/johndoe/info/collections": maybe_empty(johnHelper.handler),
"/1.1/johndoe/storage/crypto/keys": johnU("crypto", new ServerWBO("keys").handler()),
- "/1.1/johndoe/storage/meta/global": johnU("meta", new ServerWBO("global").handler())
+ "/1.1/johndoe/storage/meta/global": johnU("meta", new ServerWBO("global").handler())
};
let collections = ["clients", "bookmarks", "forms", "history",
"passwords", "prefs", "tabs"];
// Disable addon sync because AddonManager won't be initialized here.
Service.engineManager.unregister("addons");
for (let coll of collections) {
handlers["/1.1/johndoe/storage/" + coll] =
--- a/services/sync/tests/unit/test_corrupt_keys.js
+++ b/services/sync/tests/unit/test_corrupt_keys.js
@@ -94,21 +94,21 @@ add_task(async function test_locally_cha
// Let's create some server side history records.
let liveKeys = Service.collectionKeys.keyForCollection("history");
_("Keys now: " + liveKeys.keyPair);
let visitType = Ci.nsINavHistoryService.TRANSITION_LINK;
let history = johndoe.createCollection("history");
for (let i = 0; i < 5; i++) {
let id = 'record-no--' + i;
- let modified = Date.now()/1000 - 60*(i+10);
+ let modified = Date.now() / 1000 - 60 * (i + 10);
let w = new CryptoWrapper("history", "id");
w.cleartext = {
- id: id,
+ id,
histUri: "http://foo/bar?" + id,
title: id,
sortindex: i,
visits: [{date: (modified - 5) * 1000000, type: visitType}],
deleted: false};
w.encrypt(liveKeys);
let payload = {ciphertext: w.ciphertext,
@@ -155,17 +155,17 @@ add_task(async function test_locally_cha
_("Busting some new server values.");
// Now what happens if we corrupt the HMAC on the server?
for (let i = 5; i < 10; i++) {
let id = 'record-no--' + i;
let modified = 1 + (Date.now() / 1000);
let w = new CryptoWrapper("history", "id");
w.cleartext = {
- id: id,
+ id,
histUri: "http://foo/bar?" + id,
title: id,
sortindex: i,
visits: [{date: (modified - 5 ) * 1000000, type: visitType}],
deleted: false};
w.encrypt(Service.collectionKeys.keyForCollection("history"));
w.hmac = w.hmac.toUpperCase();
--- a/services/sync/tests/unit/test_engine.js
+++ b/services/sync/tests/unit/test_engine.js
@@ -9,17 +9,17 @@ Cu.import("resource://services-sync/util
function SteamStore(engine) {
Store.call(this, "Steam", engine);
this.wasWiped = false;
}
SteamStore.prototype = {
__proto__: Store.prototype,
- wipe: function() {
+ wipe() {
this.wasWiped = true;
}
};
function SteamTracker(name, engine) {
Tracker.call(this, name || "Steam", engine);
}
SteamTracker.prototype = {
@@ -31,34 +31,34 @@ function SteamEngine(name, service) {
this.wasReset = false;
this.wasSynced = false;
}
SteamEngine.prototype = {
__proto__: Engine.prototype,
_storeObj: SteamStore,
_trackerObj: SteamTracker,
- _resetClient: function () {
+ _resetClient() {
this.wasReset = true;
},
- _sync: function () {
+ _sync() {
this.wasSynced = true;
}
};
var engineObserver = {
topics: [],
- observe: function(subject, topic, data) {
+ observe(subject, topic, data) {
do_check_eq(data, "steam");
this.topics.push(topic);
},
- reset: function() {
+ reset() {
this.topics = [];
}
};
Observers.add("weave:engine:reset-client:start", engineObserver);
Observers.add("weave:engine:reset-client:finish", engineObserver);
Observers.add("weave:engine:wipe-client:start", engineObserver);
Observers.add("weave:engine:wipe-client:finish", engineObserver);
Observers.add("weave:engine:sync:start", engineObserver);
@@ -77,17 +77,17 @@ add_task(async function test_score() {
_("Engine.score corresponds to tracker.score and is readonly");
let engine = new SteamEngine("Steam", Service);
do_check_eq(engine.score, 0);
engine._tracker.score += 5;
do_check_eq(engine.score, 5);
try {
engine.score = 10;
- } catch(ex) {
+ } catch (ex) {
// Setting an attribute that has a getter produces an error in
// Firefox <= 3.6 and is ignored in later versions. Either way,
// the attribute's value won't change.
}
do_check_eq(engine.score, 5);
});
add_task(async function test_resetClient() {
--- a/services/sync/tests/unit/test_engine_abort.js
+++ b/services/sync/tests/unit/test_engine_abort.js
@@ -9,33 +9,33 @@ Cu.import("resource://testing-common/ser
Cu.import("resource://testing-common/services/sync/utils.js");
add_task(async function test_processIncoming_abort() {
_("An abort exception, raised in applyIncoming, will abort _processIncoming.");
let engine = new RotaryEngine(Service);
let collection = new ServerCollection();
let id = Utils.makeGUID();
- let payload = encryptPayload({id: id, denomination: "Record No. " + id});
+ let payload = encryptPayload({id, denomination: "Record No. " + id});
collection.insert(id, payload);
let server = sync_httpd_setup({
"/1.1/foo/storage/rotary": collection.handler()
});
await SyncTestingInfrastructure(server);
generateNewKeys(Service.collectionKeys);
_("Create some server data.");
let meta_global = Service.recordManager.set(engine.metaURL,
new WBORecord(engine.metaURL));
meta_global.payload.engines = {rotary: {version: engine.version,
syncID: engine.syncID}};
_("Fake applyIncoming to abort.");
- engine._store.applyIncoming = function (record) {
+ engine._store.applyIncoming = function(record) {
let ex = {code: Engine.prototype.eEngineAbortApplyIncoming,
cause: "Nooo"};
_("Throwing: " + JSON.stringify(ex));
throw ex;
};
_("Trying _processIncoming. It will throw after aborting.");
let err;
--- a/services/sync/tests/unit/test_errorhandler_1.js
+++ b/services/sync/tests/unit/test_errorhandler_1.js
@@ -85,17 +85,17 @@ add_identity_test(this, async function t
let expected = isConfiguredWithLegacyIdentity() ?
LOGIN_FAILED_LOGIN_REJECTED : LOGIN_FAILED_NETWORK_ERROR;
do_check_eq(Status.login, expected);
do_check_false(Service.isLoggedIn);
// Clean up.
- Utils.nextTick(function () {
+ Utils.nextTick(function() {
Service.startOver();
server.stop(deferred.resolve);
});
}
Svc.Obs.add("weave:service:login:error", onLoginError);
}
// Make sync fail due to login rejected.
@@ -366,17 +366,17 @@ add_identity_test(this, function test_sh
add_identity_test(this, async function test_shouldReportError_master_password() {
_("Test error ignored due to locked master password");
let server = EHTestsCommon.sync_httpd_setup();
await EHTestsCommon.setUp(server);
// Monkey patch Service.verifyLogin to imitate
// master password being locked.
Service._verifyLogin = Service.verifyLogin;
- Service.verifyLogin = function () {
+ Service.verifyLogin = function() {
Status.login = MASTER_PASSWORD_LOCKED;
return false;
};
setLastSync(NON_PROLONGED_ERROR_DURATION);
Service.sync();
do_check_false(errorHandler.shouldReportError());
--- a/services/sync/tests/unit/test_errorhandler_2.js
+++ b/services/sync/tests/unit/test_errorhandler_2.js
@@ -130,17 +130,17 @@ add_task(async function test_sync_prolon
do_check_eq(Status.service, SYNC_FAILED);
do_check_eq(Status.sync, PROLONGED_SYNC_FAILURE);
do_check_true(errorHandler.didReportProlongedError);
await promiseStopServer(server);
clean();
});
-add_identity_test(this, async function test_info_collections_login_prolonged_server_maintenance_error(){
+add_identity_test(this, async function test_info_collections_login_prolonged_server_maintenance_error() {
// Test info/collections prolonged server maintenance errors are reported.
let server = EHTestsCommon.sync_httpd_setup();
await EHTestsCommon.setUp(server);
await configureIdentity({username: "broken.info"}, server);
let backoffInterval;
Svc.Obs.add("weave:service:backoff:interval", function observe(subject, data) {
@@ -162,17 +162,17 @@ add_identity_test(this, async function t
do_check_eq(Status.service, SYNC_FAILED);
do_check_eq(Status.sync, PROLONGED_SYNC_FAILURE);
do_check_true(errorHandler.didReportProlongedError);
clean();
await promiseStopServer(server);
});
-add_identity_test(this, async function test_meta_global_login_prolonged_server_maintenance_error(){
+add_identity_test(this, async function test_meta_global_login_prolonged_server_maintenance_error() {
// Test meta/global prolonged server maintenance errors are reported.
let server = EHTestsCommon.sync_httpd_setup();
await EHTestsCommon.setUp(server);
await configureIdentity({username: "broken.meta"}, server);
let backoffInterval;
Svc.Obs.add("weave:service:backoff:interval", function observe(subject, data) {
@@ -194,17 +194,17 @@ add_identity_test(this, async function t
do_check_eq(Status.service, SYNC_FAILED);
do_check_eq(Status.sync, PROLONGED_SYNC_FAILURE);
do_check_true(errorHandler.didReportProlongedError);
clean();
await promiseStopServer(server);
});
-add_identity_test(this, async function test_download_crypto_keys_login_prolonged_server_maintenance_error(){
+add_identity_test(this, async function test_download_crypto_keys_login_prolonged_server_maintenance_error() {
// Test crypto/keys prolonged server maintenance errors are reported.
let server = EHTestsCommon.sync_httpd_setup();
await EHTestsCommon.setUp(server);
await configureIdentity({username: "broken.keys"}, server);
// Force re-download of keys
Service.collectionKeys.clear();
@@ -227,17 +227,17 @@ add_identity_test(this, async function t
do_check_eq(Status.service, SYNC_FAILED);
do_check_eq(Status.sync, PROLONGED_SYNC_FAILURE);
do_check_true(errorHandler.didReportProlongedError);
clean();
await promiseStopServer(server);
});
-add_identity_test(this, async function test_upload_crypto_keys_login_prolonged_server_maintenance_error(){
+add_identity_test(this, async function test_upload_crypto_keys_login_prolonged_server_maintenance_error() {
// Test crypto/keys prolonged server maintenance errors are reported.
let server = EHTestsCommon.sync_httpd_setup();
// Start off with an empty account, do not upload a key.
await configureIdentity({username: "broken.keys"}, server);
let backoffInterval;
Svc.Obs.add("weave:service:backoff:interval", function observe(subject, data) {
@@ -259,17 +259,17 @@ add_identity_test(this, async function t
do_check_eq(Status.service, SYNC_FAILED);
do_check_eq(Status.sync, PROLONGED_SYNC_FAILURE);
do_check_true(errorHandler.didReportProlongedError);
clean();
await promiseStopServer(server);
});
-add_identity_test(this, async function test_wipeServer_login_prolonged_server_maintenance_error(){
+add_identity_test(this, async function test_wipeServer_login_prolonged_server_maintenance_error() {
// Test that we report prolonged server maintenance errors that occur whilst
// wiping the server.
let server = EHTestsCommon.sync_httpd_setup();
// Start off with an empty account, do not upload a key.
await configureIdentity({username: "broken.wipe"}, server);
let backoffInterval;
@@ -292,17 +292,17 @@ add_identity_test(this, async function t
do_check_eq(Status.service, SYNC_FAILED);
do_check_eq(Status.sync, PROLONGED_SYNC_FAILURE);
do_check_true(errorHandler.didReportProlongedError);
clean();
await promiseStopServer(server);
});
-add_identity_test(this, async function test_wipeRemote_prolonged_server_maintenance_error(){
+add_identity_test(this, async function test_wipeRemote_prolonged_server_maintenance_error() {
// Test that we report prolonged server maintenance errors that occur whilst
// wiping all remote devices.
let server = EHTestsCommon.sync_httpd_setup();
server.registerPathHandler("/1.1/broken.wipe/storage/catapult", EHTestsCommon.service_unavailable);
await configureIdentity({username: "broken.wipe"}, server);
EHTestsCommon.generateAndUploadKeys();
@@ -527,17 +527,17 @@ add_identity_test(this, async function t
do_check_eq(Status.service, LOGIN_FAILED);
do_check_eq(Status.login, SERVER_MAINTENANCE);
do_check_false(errorHandler.didReportProlongedError);
clean();
await promiseStopServer(server);
});
-add_identity_test(this, async function test_wipeRemote_syncAndReportErrors_server_maintenance_error(){
+add_identity_test(this, async function test_wipeRemote_syncAndReportErrors_server_maintenance_error() {
// Test that we report prolonged server maintenance errors that occur whilst
// wiping all remote devices.
let server = EHTestsCommon.sync_httpd_setup();
await configureIdentity({username: "broken.wipe"}, server);
EHTestsCommon.generateAndUploadKeys();
let engine = engineManager.get("catapult");
--- a/services/sync/tests/unit/test_errorhandler_eol.js
+++ b/services/sync/tests/unit/test_errorhandler_eol.js
@@ -23,17 +23,17 @@ function baseHandler(eolCode, request, r
function handler513(request, response) {
let statusCode = 513;
let status = "Upgrade Required";
let body = "{}";
baseHandler("hard-eol", request, response, statusCode, status, body);
}
function handler200(eolCode) {
- return function (request, response) {
+ return function(request, response) {
let statusCode = 200;
let status = "OK";
let body = "{\"meta\": 123456789010}";
baseHandler(eolCode, request, response, statusCode, status, body);
};
}
function sync_httpd_setup(infoHandler) {
--- a/services/sync/tests/unit/test_errorhandler_filelog.js
+++ b/services/sync/tests/unit/test_errorhandler_filelog.js
@@ -83,17 +83,17 @@ add_test(function test_logOnSuccess_fals
// Fake a successful sync.
Svc.Obs.notify("weave:service:sync:finish");
});
function readFile(file, callback) {
NetUtil.asyncFetch({
uri: NetUtil.newURI(file),
loadUsingSystemPrincipal: true
- }, function (inputStream, statusCode, request) {
+ }, function(inputStream, statusCode, request) {
let data = NetUtil.readInputStreamToString(inputStream,
inputStream.available());
callback(statusCode, data);
});
}
add_test(function test_logOnSuccess_true() {
Svc.Prefs.set("log.appender.file.logOnSuccess", true);
@@ -109,24 +109,24 @@ add_test(function test_logOnSuccess_true
let entries = logsdir.directoryEntries;
do_check_true(entries.hasMoreElements());
let logfile = entries.getNext().QueryInterface(Ci.nsILocalFile);
do_check_eq(logfile.leafName.slice(-4), ".txt");
do_check_true(logfile.leafName.startsWith("success-sync-"), logfile.leafName);
do_check_false(entries.hasMoreElements());
// Ensure the log message was actually written to file.
- readFile(logfile, function (error, data) {
+ readFile(logfile, function(error, data) {
do_check_true(Components.isSuccessCode(error));
do_check_neq(data.indexOf(MESSAGE), -1);
// Clean up.
try {
logfile.remove(false);
- } catch(ex) {
+ } catch (ex) {
dump("Couldn't delete file: " + ex + "\n");
// Stupid Windows box.
}
Svc.Prefs.resetBranch("");
run_next_test();
});
});
@@ -176,24 +176,24 @@ add_test(function test_sync_error_logOnE
let entries = logsdir.directoryEntries;
do_check_true(entries.hasMoreElements());
let logfile = entries.getNext().QueryInterface(Ci.nsILocalFile);
do_check_eq(logfile.leafName.slice(-4), ".txt");
do_check_true(logfile.leafName.startsWith("error-sync-"), logfile.leafName);
do_check_false(entries.hasMoreElements());
// Ensure the log message was actually written to file.
- readFile(logfile, function (error, data) {
+ readFile(logfile, function(error, data) {
do_check_true(Components.isSuccessCode(error));
do_check_neq(data.indexOf(MESSAGE), -1);
// Clean up.
try {
logfile.remove(false);
- } catch(ex) {
+ } catch (ex) {
dump("Couldn't delete file: " + ex + "\n");
// Stupid Windows box.
}
Svc.Prefs.resetBranch("");
});
});
@@ -243,24 +243,24 @@ add_test(function test_login_error_logOn
let entries = logsdir.directoryEntries;
do_check_true(entries.hasMoreElements());
let logfile = entries.getNext().QueryInterface(Ci.nsILocalFile);
do_check_eq(logfile.leafName.slice(-4), ".txt");
do_check_true(logfile.leafName.startsWith("error-sync-"), logfile.leafName);
do_check_false(entries.hasMoreElements());
// Ensure the log message was actually written to file.
- readFile(logfile, function (error, data) {
+ readFile(logfile, function(error, data) {
do_check_true(Components.isSuccessCode(error));
do_check_neq(data.indexOf(MESSAGE), -1);
// Clean up.
try {
logfile.remove(false);
- } catch(ex) {
+ } catch (ex) {
dump("Couldn't delete file: " + ex + "\n");
// Stupid Windows box.
}
Svc.Prefs.resetBranch("");
});
});
@@ -288,24 +288,24 @@ add_test(function test_errorLog_dumpAddo
let entries = logsdir.directoryEntries;
do_check_true(entries.hasMoreElements());
let logfile = entries.getNext().QueryInterface(Ci.nsILocalFile);
do_check_eq(logfile.leafName.slice(-4), ".txt");
do_check_true(logfile.leafName.startsWith("error-sync-"), logfile.leafName);
do_check_false(entries.hasMoreElements());
// Ensure we logged some addon list (which is probably empty)
- readFile(logfile, function (error, data) {
+ readFile(logfile, function(error, data) {
do_check_true(Components.isSuccessCode(error));
do_check_neq(data.indexOf("Addons installed"), -1);
// Clean up.
try {
logfile.remove(false);
- } catch(ex) {
+ } catch (ex) {
dump("Couldn't delete file: " + ex + "\n");
// Stupid Windows box.
}
Svc.Prefs.resetBranch("");
});
});
@@ -339,25 +339,25 @@ add_test(function test_logErrorCleanup_a
Svc.Obs.add("services-tests:common:log-manager:cleanup-logs", function onCleanupLogs() {
Svc.Obs.remove("services-tests:common:log-manager:cleanup-logs", onCleanupLogs);
// Only the newest created log file remains.
let entries = logsdir.directoryEntries;
do_check_true(entries.hasMoreElements());
let logfile = entries.getNext().QueryInterface(Ci.nsILocalFile);
- do_check_true(oldLogs.every(function (e) {
+ do_check_true(oldLogs.every(function(e) {
return e != logfile.leafName;
}));
do_check_false(entries.hasMoreElements());
// Clean up.
try {
logfile.remove(false);
- } catch(ex) {
+ } catch (ex) {
dump("Couldn't delete file: " + ex + "\n");
// Stupid Windows box.
}
Svc.Prefs.resetBranch("");
run_next_test();
});
--- a/services/sync/tests/unit/test_errorhandler_sync_checkServerError.js
+++ b/services/sync/tests/unit/test_errorhandler_sync_checkServerError.js
@@ -37,23 +37,23 @@ function sync_httpd_setup() {
syncID: catapultEngine.syncID}};
// Track these using the collections helper, which keeps modified times
// up-to-date.
let clientsColl = new ServerCollection({}, true);
let keysWBO = new ServerWBO("keys");
let globalWBO = new ServerWBO("global", {storageVersion: STORAGE_VERSION,
syncID: Utils.makeGUID(),
- engines: engines});
+ engines});
let handlers = {
"/1.1/johndoe/info/collections": collectionsHelper.handler,
- "/1.1/johndoe/storage/meta/global": upd("meta", globalWBO.handler()),
+ "/1.1/johndoe/storage/meta/global": upd("meta", globalWBO.handler()),
"/1.1/johndoe/storage/clients": upd("clients", clientsColl.handler()),
- "/1.1/johndoe/storage/crypto/keys": upd("crypto", keysWBO.handler())
+ "/1.1/johndoe/storage/crypto/keys": upd("crypto", keysWBO.handler())
};
return httpd_setup(handlers);
}
async function setUp(server) {
await configureIdentity({username: "johndoe"}, server);
new FakeCryptoService();
}
@@ -101,17 +101,17 @@ add_identity_test(this, async function t
const BACKOFF = 42;
let engine = engineManager.get("catapult");
engine.enabled = true;
engine.exception = {status: 503,
headers: {"retry-after": BACKOFF}};
let backoffInterval;
- Svc.Obs.add("weave:service:backoff:interval", function (subject) {
+ Svc.Obs.add("weave:service:backoff:interval", function(subject) {
backoffInterval = subject;
});
try {
do_check_false(Status.enforceBackoff);
do_check_true(generateAndUploadKeys(server));
--- a/services/sync/tests/unit/test_extension_storage_crypto.js
+++ b/services/sync/tests/unit/test_extension_storage_crypto.js
@@ -15,18 +15,17 @@ Cu.import("resource://services-sync/util
* @param {function} f
* The function to call.
*/
function* throwsGen(constraint, f) {
let threw = false;
let exception;
try {
yield* f();
- }
- catch (e) {
+ } catch (e) {
threw = true;
exception = e;
}
ok(threw, "did not throw an exception");
const debuggingMessage = `got ${exception}, expected ${constraint}`;
let message = exception;
@@ -52,33 +51,33 @@ class StaticKeyEncryptionRemoteTransform
this.keyBundle = keyBundle;
}
getKeys() {
return Promise.resolve(this.keyBundle);
}
}
const BORING_KB = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
-const STRETCHED_KEY = CryptoUtils.hkdf(BORING_KB, undefined, `testing storage.sync encryption`, 2*32);
+const STRETCHED_KEY = CryptoUtils.hkdf(BORING_KB, undefined, `testing storage.sync encryption`, 2 * 32);
const KEY_BUNDLE = {
sha256HMACHasher: Utils.makeHMACHasher(Ci.nsICryptoHMAC.SHA256, Utils.makeHMACKey(STRETCHED_KEY.slice(0, 32))),
encryptionKeyB64: btoa(STRETCHED_KEY.slice(32, 64)),
};
const transformer = new StaticKeyEncryptionRemoteTransformer(KEY_BUNDLE);
add_task(function* test_encryption_transformer_roundtrip() {
const POSSIBLE_DATAS = [
"string",
2, // number
[1, 2, 3], // array
{key: "value"}, // object
];
for (let data of POSSIBLE_DATAS) {
- const record = {data: data, id: "key-some_2D_key", key: "some-key"};
+ const record = {data, id: "key-some_2D_key", key: "some-key"};
deepEqual(record, yield transformer.decode(yield transformer.encode(record)));
}
});
add_task(function* test_refuses_to_decrypt_tampered() {
const encryptedRecord = yield transformer.encode({data: [1, 2, 3], id: "key-some_2D_key", key: "some-key"});
const tamperedHMAC = Object.assign({}, encryptedRecord, {hmac: "0000000000000000000000000000000000000000000000000000000000000001"});
--- a/services/sync/tests/unit/test_forms_tracker.js
+++ b/services/sync/tests/unit/test_forms_tracker.js
@@ -12,20 +12,20 @@ function run_test() {
let tracker = engine._tracker;
// Don't do asynchronous writes.
tracker.persistChangedIDs = false;
do_check_empty(tracker.changedIDs);
Log.repository.rootLogger.addAppender(new Log.DumpAppender());
function addEntry(name, value) {
- engine._store.create({name: name, value: value});
+ engine._store.create({name, value});
}
function removeEntry(name, value) {
- guid = engine._findDupe({name: name, value: value});
+ guid = engine._findDupe({name, value});
engine._store.remove({id: guid});
}
try {
_("Create an entry. Won't show because we haven't started tracking yet");
addEntry("name", "John Doe");
do_check_empty(tracker.changedIDs);
--- a/services/sync/tests/unit/test_fxa_migration.js
+++ b/services/sync/tests/unit/test_fxa_migration.js
@@ -41,17 +41,17 @@ function configureLegacySync() {
const PASSPHRASE = "abcdeabcdeabcdeabcdeabcdea";
setBasicCredentials(USER, "password", PASSPHRASE);
let onRequest = function(request, response) {
// ideally we'd only do this while a legacy user is configured, but WTH.
response.setHeader("x-weave-alert", JSON.stringify({code: "soft-eol"}));
}
- let server = new SyncServer({onRequest: onRequest});
+ let server = new SyncServer({onRequest});
server.registerUser(USER, "password");
server.createContents(USER, contents);
server.start();
Service.serverURL = server.baseURI;
Service.clusterURL = server.baseURI;
Service.identity.username = USER;
Service._updateCachedURLs();
--- a/services/sync/tests/unit/test_fxa_node_reassignment.js
+++ b/services/sync/tests/unit/test_fxa_node_reassignment.js
@@ -75,17 +75,17 @@ function prepareServer(cbAfterTokenFetch
// 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) {
+ getTokenFromBrowserIDAssertion(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;
@@ -139,34 +139,34 @@ async function syncAndExpectNodeReassign
}
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 () {
+ 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 we really do get a 401 (but we can only do that if we are
// already logged in, as the login process is what sets up the URLs)
if (Service.isLoggedIn) {
_("Making request to " + url + " which should 401");
let request = new RESTRequest(url);
- request.get(function () {
+ request.get(function() {
do_check_eq(request.response.status, 401);
Utils.nextTick(onwards);
});
} else {
_("Skipping preliminary validation check for a 401 as we aren't logged in");
Utils.nextTick(onwards);
}
await deferred.promise;
--- a/services/sync/tests/unit/test_history_engine.js
+++ b/services/sync/tests/unit/test_history_engine.js
@@ -23,35 +23,35 @@ add_task(async function test_processInco
Svc.Prefs.set("client.type", "mobile");
Service.engineManager.register(HistoryEngine);
// A collection that logs each GET
let collection = new ServerCollection();
collection.get_log = [];
collection._get = collection.get;
- collection.get = function (options) {
+ collection.get = function(options) {
this.get_log.push(options);
return this._get(options);
};
let server = sync_httpd_setup({
"/1.1/foo/storage/history": collection.handler()
});
await SyncTestingInfrastructure(server);
// Let's create some 234 server side history records. They're all at least
// 10 minutes old.
let visitType = Ci.nsINavHistoryService.TRANSITION_LINK;
for (var i = 0; i < 234; i++) {
let id = 'record-no' + ("00" + i).slice(-3);
- let modified = Date.now()/1000 - 60*(i+10);
+ let modified = Date.now() / 1000 - 60 * (i + 10);
let payload = encryptPayload({
- id: id,
+ id,
histUri: "http://foo/bar?" + id,
title: id,
sortindex: i,
visits: [{date: (modified - 5) * 1000000, type: visitType}],
deleted: false});
let wbo = new ServerWBO(id, payload);
wbo.modified = modified;
--- a/services/sync/tests/unit/test_hmac_error.js
+++ b/services/sync/tests/unit/test_hmac_error.js
@@ -4,19 +4,19 @@
Cu.import("resource://services-sync/engines.js");
Cu.import("resource://services-sync/service.js");
Cu.import("resource://services-sync/util.js");
Cu.import("resource://testing-common/services/sync/rotaryengine.js");
Cu.import("resource://testing-common/services/sync/utils.js");
// Track HMAC error counts.
var hmacErrorCount = 0;
-(function () {
+(function() {
let hHE = Service.handleHMACEvent;
- Service.handleHMACEvent = function () {
+ Service.handleHMACEvent = function() {
hmacErrorCount++;
return hHE.call(Service);
};
})();
function shared_setup() {
hmacErrorCount = 0;
@@ -32,32 +32,32 @@ function shared_setup() {
do_check_eq(1, Service.engineManager.getEnabled().length);
let engines = {rotary: {version: engine.version,
syncID: engine.syncID},
clients: {version: Service.clientsEngine.version,
syncID: Service.clientsEngine.syncID}};
// Common server objects.
- let global = new ServerWBO("global", {engines: engines});
+ let global = new ServerWBO("global", {engines});
let keysWBO = new ServerWBO("keys");
let rotaryColl = new ServerCollection({}, true);
let clientsColl = new ServerCollection({}, true);
return [engine, rotaryColl, clientsColl, keysWBO, global];
}
add_task(async function hmac_error_during_404() {
_("Attempt to replicate the HMAC error setup.");
let [engine, rotaryColl, clientsColl, keysWBO, global] = shared_setup();
// Hand out 404s for crypto/keys.
let keysHandler = keysWBO.handler();
let key404Counter = 0;
- let keys404Handler = function (request, response) {
+ let keys404Handler = function(request, response) {
if (key404Counter > 0) {
let body = "Not Found";
response.setStatusLine(request.httpVersion, 404, body);
response.bodyOutputStream.write(body, body.length);
key404Counter--;
return;
}
keysHandler(request, response);
@@ -118,17 +118,17 @@ add_task(async function hmac_error_durin
delete collectionsHelper.collections.rotary;
delete collectionsHelper.collections.crypto;
delete collectionsHelper.collections.clients;
_("Deleted server data.");
}
let should401 = false;
function upd401(coll, handler) {
- return function (request, response) {
+ return function(request, response) {
if (should401 && (request.method != "DELETE")) {
on401();
should401 = false;
let body = "\"reassigned!\"";
response.setStatusLine(request.httpVersion, 401, "Node reassignment.");
response.bodyOutputStream.write(body, body.length);
return;
}
--- a/services/sync/tests/unit/test_httpd_sync_server.js
+++ b/services/sync/tests/unit/test_httpd_sync_server.js
@@ -10,17 +10,17 @@ function run_test() {
}
add_test(function test_creation() {
// Explicit callback for this one.
let server = new SyncServer({
__proto__: SyncServerCallback,
});
do_check_true(!!server); // Just so we have a check.
- server.start(null, function () {
+ server.start(null, function() {
_("Started on " + server.port);
server.stop(run_next_test);
});
});
add_test(function test_url_parsing() {
let server = new SyncServer();
@@ -72,24 +72,24 @@ function localRequest(server, path) {
_("url: " + url);
return new RESTRequest(url);
}
add_test(function test_basic_http() {
let server = new SyncServer();
server.registerUser("john", "password");
do_check_true(server.userExists("john"));
- server.start(null, function () {
+ server.start(null, function() {
_("Started on " + server.port);
- Utils.nextTick(function () {
+ Utils.nextTick(function() {
let req = localRequest(server, "/1.1/john/storage/crypto/keys");
_("req is " + req);
- req.get(function (err) {
+ req.get(function(err) {
do_check_eq(null, err);
- Utils.nextTick(function () {
+ Utils.nextTick(function() {
server.stop(run_next_test);
});
});
});
});
});
add_test(function test_info_collections() {
@@ -98,44 +98,44 @@ add_test(function test_info_collections(
});
function responseHasCorrectHeaders(r) {
do_check_eq(r.status, 200);
do_check_eq(r.headers["content-type"], "application/json");
do_check_true("x-weave-timestamp" in r.headers);
}
server.registerUser("john", "password");
- server.start(null, function () {
- Utils.nextTick(function () {
+ server.start(null, function() {
+ Utils.nextTick(function() {
let req = localRequest(server, "/1.1/john/info/collections");
- req.get(function (err) {
+ req.get(function(err) {
// Initial info/collections fetch is empty.
do_check_eq(null, err);
responseHasCorrectHeaders(this.response);
do_check_eq(this.response.body, "{}");
- Utils.nextTick(function () {
+ Utils.nextTick(function() {
// When we PUT something to crypto/keys, "crypto" appears in the response.
function cb(err) {
do_check_eq(null, err);
responseHasCorrectHeaders(this.response);
let putResponseBody = this.response.body;
_("PUT response body: " + JSON.stringify(putResponseBody));
req = localRequest(server, "/1.1/john/info/collections");
- req.get(function (err) {
+ req.get(function(err) {
do_check_eq(null, err);
responseHasCorrectHeaders(this.response);
let expectedColl = server.getCollection("john", "crypto");
do_check_true(!!expectedColl);
let modified = expectedColl.timestamp;
do_check_true(modified > 0);
do_check_eq(putResponseBody, modified);
do_check_eq(JSON.parse(this.response.body).crypto, modified);
- Utils.nextTick(function () {
+ Utils.nextTick(function() {
server.stop(run_next_test);
});
});
}
let payload = JSON.stringify({foo: "bar"});
localRequest(server, "/1.1/john/storage/crypto/keys").put(payload, cb);
});
});
@@ -158,95 +158,95 @@ add_test(function test_storage_request()
let coll = server.user("john").collection("crypto");
do_check_true(!!coll);
_("We're tracking timestamps.");
do_check_true(coll.timestamp >= creation);
function retrieveWBONotExists(next) {
let req = localRequest(server, keysURL);
- req.get(function (err) {
+ req.get(function(err) {
_("Body is " + this.response.body);
_("Modified is " + this.response.newModified);
do_check_eq(null, err);
do_check_eq(this.response.status, 404);
do_check_eq(this.response.body, "Not found");
Utils.nextTick(next);
});
}
function retrieveWBOExists(next) {
let req = localRequest(server, foosURL);
- req.get(function (err) {
+ req.get(function(err) {
_("Body is " + this.response.body);
_("Modified is " + this.response.newModified);
let parsedBody = JSON.parse(this.response.body);
do_check_eq(parsedBody.id, "foos");
do_check_eq(parsedBody.modified, coll.wbo("foos").modified);
do_check_eq(JSON.parse(parsedBody.payload).foo, "bar");
Utils.nextTick(next);
});
}
function deleteWBONotExists(next) {
let req = localRequest(server, keysURL);
- server.callback.onItemDeleted = function (username, collection, wboID) {
+ server.callback.onItemDeleted = function(username, collection, wboID) {
do_throw("onItemDeleted should not have been called.");
};
- req.delete(function (err) {
+ req.delete(function(err) {
_("Body is " + this.response.body);
_("Modified is " + this.response.newModified);
do_check_eq(this.response.status, 200);
delete server.callback.onItemDeleted;
Utils.nextTick(next);
});
}
function deleteWBOExists(next) {
let req = localRequest(server, foosURL);
- server.callback.onItemDeleted = function (username, collection, wboID) {
+ server.callback.onItemDeleted = function(username, collection, wboID) {
_("onItemDeleted called for " + collection + "/" + wboID);
delete server.callback.onItemDeleted;
do_check_eq(username, "john");
do_check_eq(collection, "crypto");
do_check_eq(wboID, "foos");
Utils.nextTick(next);
};
- req.delete(function (err) {
+ req.delete(function(err) {
_("Body is " + this.response.body);
_("Modified is " + this.response.newModified);
do_check_eq(this.response.status, 200);
});
}
function deleteStorage(next) {
_("Testing DELETE on /storage.");
let now = server.timestamp();
_("Timestamp: " + now);
let req = localRequest(server, storageURL);
- req.delete(function (err) {
+ req.delete(function(err) {
_("Body is " + this.response.body);
_("Modified is " + this.response.newModified);
let parsedBody = JSON.parse(this.response.body);
do_check_true(parsedBody >= now);
do_check_empty(server.users["john"].collections);
Utils.nextTick(next);
});
}
function getStorageFails(next) {
_("Testing that GET on /storage fails.");
let req = localRequest(server, storageURL);
- req.get(function (err) {
+ req.get(function(err) {
do_check_eq(this.response.status, 405);
do_check_eq(this.response.headers["allow"], "DELETE");
Utils.nextTick(next);
});
}
function getMissingCollectionWBO(next) {
_("Testing that fetching a WBO from an on-existent collection 404s.");
let req = localRequest(server, storageURL + "/foobar/baz");
- req.get(function (err) {
+ req.get(function(err) {
do_check_eq(this.response.status, 404);
Utils.nextTick(next);
});
}
server.start(null,
Async.chain(
retrieveWBONotExists,
@@ -264,22 +264,22 @@ add_test(function test_storage_request()
add_test(function test_x_weave_records() {
let server = new SyncServer();
server.registerUser("john", "password");
server.createContents("john", {
crypto: {foos: {foo: "bar"},
bars: {foo: "baz"}}
});
- server.start(null, function () {
+ server.start(null, function() {
let wbo = localRequest(server, "/1.1/john/storage/crypto/foos");
- wbo.get(function (err) {
+ wbo.get(function(err) {
// WBO fetches don't have one.
do_check_false("x-weave-records" in this.response.headers);
let col = localRequest(server, "/1.1/john/storage/crypto");
- col.get(function (err) {
+ col.get(function(err) {
// Collection fetches do.
do_check_eq(this.response.headers["x-weave-records"], "2");
server.stop(run_next_test);
});
});
});
});
--- a/services/sync/tests/unit/test_interval_triggers.js
+++ b/services/sync/tests/unit/test_interval_triggers.js
@@ -58,17 +58,17 @@ function run_test() {
}
add_identity_test(this, async function test_successful_sync_adjustSyncInterval() {
_("Test successful sync calling adjustSyncInterval");
let syncSuccesses = 0;
function onSyncFinish() {
_("Sync success.");
syncSuccesses++;
- };
+ }
Svc.Obs.add("weave:service:sync:finish", onSyncFinish);
let server = sync_httpd_setup();
await setUp(server);
// Confirm defaults
do_check_false(scheduler.idle);
do_check_false(scheduler.numClients > 1);
@@ -143,17 +143,17 @@ add_identity_test(this, async function t
_("Test non-idle, numClients > 1, incoming items => immediateInterval.");
// idle == false && numClients > 1 && hasIncomingItems == true
scheduler.hasIncomingItems = true;
Service.sync();
do_check_eq(syncSuccesses, 8);
do_check_false(scheduler.idle);
do_check_true(scheduler.numClients > 1);
- do_check_false(scheduler.hasIncomingItems); //gets reset to false
+ do_check_false(scheduler.hasIncomingItems); // gets reset to false
do_check_eq(scheduler.syncInterval, scheduler.immediateInterval);
Svc.Obs.remove("weave:service:sync:finish", onSyncFinish);
Service.startOver();
await promiseStopServer(server);
});
add_identity_test(this, async function test_unsuccessful_sync_adjustSyncInterval() {
@@ -248,17 +248,17 @@ add_identity_test(this, async function t
_("Test non-idle, numClients > 1, incoming items => immediateInterval.");
// idle == false && numClients > 1 && hasIncomingItems == true
scheduler.hasIncomingItems = true;
Service.sync();
do_check_eq(syncFailures, 8);
do_check_false(scheduler.idle);
do_check_true(scheduler.numClients > 1);
- do_check_false(scheduler.hasIncomingItems); //gets reset to false
+ do_check_false(scheduler.hasIncomingItems); // gets reset to false
do_check_eq(scheduler.syncInterval, scheduler.immediateInterval);
Service.startOver();
Svc.Obs.remove("weave:service:sync:error", onSyncError);
await promiseStopServer(server);
});
add_identity_test(this, async function test_back_triggers_sync() {
@@ -329,17 +329,17 @@ add_identity_test(this, async function t
// being adjusted in the next call to scheduleNextSync().
let server = sync_httpd_setup();
await setUp(server);
let syncSuccesses = 0;
function onSyncFinish() {
_("Sync success.");
syncSuccesses++;
- };
+ }
Svc.Obs.add("weave:service:sync:finish", onSyncFinish);
// After first sync call, syncInterval & syncTimer are singleDeviceInterval.
Service.sync();
do_check_eq(syncSuccesses, 1);
do_check_false(scheduler.numClients > 1);
do_check_eq(scheduler.syncInterval, scheduler.singleDeviceInterval);
do_check_eq(scheduler.syncTimer.delay, scheduler.singleDeviceInterval);
@@ -405,17 +405,17 @@ add_test(function test_adjust_timer_larg
do_check_eq(scheduler.syncInterval, scheduler.singleDeviceInterval);
scheduler.scheduleNextSync();
// Ensure timer delay remains as the small interval.
do_check_neq(scheduler.nextSync, 0);
do_check_true(scheduler.syncTimer.delay <= scheduler.activeInterval);
- //SyncSchedule.
+ // SyncSchedule.
Service.startOver();
run_next_test();
});
add_test(function test_adjust_timer_smaller_syncInterval() {
_("Test current timout > syncInterval period && nextSync != 0, syncInterval is used.");
scheduler.scheduleNextSync();
@@ -429,12 +429,12 @@ add_test(function test_adjust_timer_smal
do_check_eq(scheduler.syncInterval, scheduler.activeInterval);
scheduler.scheduleNextSync();
// Ensure smaller timer delay is used.
do_check_neq(scheduler.nextSync, 0);
do_check_true(scheduler.syncTimer.delay <= scheduler.activeInterval);
- //SyncSchedule.
+ // SyncSchedule.
Service.startOver();
run_next_test();
});
--- a/services/sync/tests/unit/test_jpakeclient.js
+++ b/services/sync/tests/unit/test_jpakeclient.js
@@ -545,17 +545,17 @@ add_test(function test_error_delayNotSup
}
});
snd.pairWithPIN("01234567" + cid, true);
});
add_test(function test_sendAndComplete_notPaired() {
let snd = new JPAKEClient({__proto__: BaseController});
- do_check_throws(function () {
+ do_check_throws(function() {
snd.sendAndComplete(DATA);
});
run_next_test();
});
add_test(function tearDown() {
server.stop(run_next_test);
--- a/services/sync/tests/unit/test_keys.js
+++ b/services/sync/tests/unit/test_keys.js
@@ -149,17 +149,17 @@ add_test(function test_keymanager() {
let key = Utils.makeHMACKey(Utils.decodeKeyBase32(testKey));
let encryptKey = sha256HMAC(sha256inputE, key);
let sha256inputH = encryptKey + HMAC_INPUT + username + "\x02";
let hmacKey = sha256HMAC(sha256inputH, key);
// Encryption key is stored in base64 for WeaveCrypto convenience.
do_check_eq(encryptKey, new SyncKeyBundle(username, testKey).encryptionKey);
- do_check_eq(hmacKey, new SyncKeyBundle(username, testKey).hmacKey);
+ do_check_eq(hmacKey, new SyncKeyBundle(username, testKey).hmacKey);
// Test with the same KeyBundle for both.
let obj = new SyncKeyBundle(username, testKey);
do_check_eq(hmacKey, obj.hmacKey);
do_check_eq(encryptKey, obj.encryptionKey);
run_next_test();
});
@@ -187,17 +187,17 @@ add_test(function test_collections_manag
let default_hmac64 = Svc.Crypto.generateRandomKey();
let bookmarks_key64 = Svc.Crypto.generateRandomKey();
let bookmarks_hmac64 = Svc.Crypto.generateRandomKey();
storage_keys.cleartext = {
"default": [default_key64, default_hmac64],
"collections": {"bookmarks": [bookmarks_key64, bookmarks_hmac64]},
};
- storage_keys.modified = Date.now()/1000;
+ storage_keys.modified = Date.now() / 1000;
storage_keys.id = "keys";
log.info("Encrypting storage keys...");
// Use passphrase (sync key) itself to encrypt the key bundle.
storage_keys.encrypt(keyBundle);
// Sanity checking.
@@ -259,17 +259,17 @@ add_test(function test_collections_manag
/*
* Checking for update times.
*/
let info_collections = {};
do_check_true(collectionKeys.updateNeeded(info_collections));
info_collections["crypto"] = 5000;
do_check_false(collectionKeys.updateNeeded(info_collections));
- info_collections["crypto"] = 1 + (Date.now()/1000); // Add one in case computers are fast!
+ info_collections["crypto"] = 1 + (Date.now() / 1000); // Add one in case computers are fast!
do_check_true(collectionKeys.updateNeeded(info_collections));
collectionKeys.lastModified = null;
do_check_true(collectionKeys.updateNeeded({}));
/*
* Check _compareKeyBundleCollections.
*/
--- a/services/sync/tests/unit/test_node_reassignment.js
+++ b/services/sync/tests/unit/test_node_reassignment.js
@@ -122,45 +122,45 @@ async function syncAndExpectNodeReassign
// Track whether we fetched node/weave. We want to wait for the second
// sync to finish so that we're cleaned up for the next test, so don't
// run_next_test in the node handler.
nodeFetched = false;
// Verify that the client requests a node reassignment.
// Install a node handler to watch for these requests.
- installNodeHandler(server, function () {
+ installNodeHandler(server, function() {
nodeFetched = true;
});
// 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 () {
+ waitForZeroTimer(function() {
_("Second sync nextTick.");
do_check_true(nodeFetched);
Service.startOver();
server.stop(deferred.resolve);
});
}
Svc.Obs.add(firstNotification, onFirstSync);
Service.sync();
}
// Make sure that it works!
let request = new RESTRequest(url);
- request.get(function () {
+ request.get(function() {
do_check_eq(request.response.status, 401);
Utils.nextTick(onwards);
});
await deferred.promise;
}
add_task(async function test_momentary_401_engine() {
_("Test a failure for engine URLs that's resolved by reassignment.");
@@ -318,17 +318,17 @@ add_task(async function test_loop_avoida
// Track whether we fetched node/weave. We want to wait for the second
// sync to finish so that we're cleaned up for the next test, so don't
// run_next_test in the node handler.
nodeFetched = false;
// Verify that the client requests a node reassignment.
// Install a node handler to watch for these requests.
- installNodeHandler(server, function () {
+ installNodeHandler(server, function() {
nodeFetched = true;
});
// Update the timestamp.
now = Date.now();
}
function onSecondSync() {
@@ -363,17 +363,17 @@ add_task(async function test_loop_avoida
function onThirdSync() {
Svc.Obs.remove(thirdNotification, onThirdSync);
// That'll do for now; no more syncs.
Service.scheduler.clearSyncTriggers();
// Make absolutely sure that any event listeners are done with their work
// before we proceed.
- waitForZeroTimer(function () {
+ waitForZeroTimer(function() {
_("Third sync nextTick.");
do_check_false(getReassigned());
do_check_true(nodeFetched);
Service.startOver();
server.stop(deferred.resolve);
});
}
@@ -457,17 +457,17 @@ add_task(async function test_loop_avoida
// Track whether we fetched node/weave. We want to wait for the second
// sync to finish so that we're cleaned up for the next test, so don't
// run_next_test in the node handler.
nodeFetched = false;
// Verify that the client requests a node reassignment.
// Install a node handler to watch for these requests.
- installNodeHandler(server, function () {
+ installNodeHandler(server, function() {
nodeFetched = true;
});
// Update the timestamp.
now = Date.now();
}
function onSecondSync() {
@@ -503,17 +503,17 @@ add_task(async function test_loop_avoida
function onThirdSync() {
Svc.Obs.remove(thirdNotification, onThirdSync);
// That'll do for now; no more syncs.
Service.scheduler.clearSyncTriggers();
// Make absolutely sure that any event listeners are done with their work
// before we proceed.
- waitForZeroTimer(function () {
+ waitForZeroTimer(function() {
_("Third sync nextTick.");
do_check_false(getReassigned());
do_check_true(nodeFetched);
afterSuccessfulSync();
});
}
Svc.Obs.add(firstNotification, onFirstSync);
--- a/services/sync/tests/unit/test_password_store.js
+++ b/services/sync/tests/unit/test_password_store.js
@@ -12,17 +12,17 @@ function checkRecord(name, record, expec
let engine = Service.engineManager.get("passwords");
let store = engine._store;
let count = {};
let logins = Services.logins.findLogins(count, record.hostname,
record.formSubmitURL, null);
_("Record" + name + ":" + JSON.stringify(logins));
- _("Count" + name + ":" + count.value);
+ _("Count" + name + ":" + count.value);
do_check_eq(count.value, expectedCount);
if (expectedCount > 0) {
do_check_true(!!store.getAllIDs()[record.id]);
let stored_record = logins[0].QueryInterface(Ci.nsILoginMetaInfo);
if (timeCreated !== undefined) {
@@ -45,20 +45,20 @@ function checkRecord(name, record, expec
function changePassword(name, hostname, password, expectedCount, timeCreated,
expectedTimeCreated, timePasswordChanged,
expectedTimePasswordChanged, insert, recordIsUpdated) {
const BOGUS_GUID = "zzzzzz" + hostname;
let record = {id: BOGUS_GUID,
- hostname: hostname,
+ hostname,
formSubmitURL: hostname,
username: "john",
- password: password,
+ password,
usernameField: "username",
passwordField: "password"};
if (timeCreated !== undefined) {
record.timeCreated = timeCreated;
}
if (timePasswordChanged !== undefined) {
@@ -124,17 +124,17 @@ function test_apply_same_record_with_dif
100, 100, timePasswordChanged, true);
timePasswordChanged = changePassword("A", "http://a.tn", "password", 1, 100,
100, 800, timePasswordChanged, true,
true);
timePasswordChanged = changePassword("A", "http://a.tn", "password", 1, 500,
100, 800, timePasswordChanged, true,
true);
timePasswordChanged = changePassword("A", "http://a.tn", "password2", 1, 500,
- 100, 1536213005222, timePasswordChanged,
+ 100, 1536213005222, timePasswordChanged,
true, true);
timePasswordChanged = changePassword("A", "http://a.tn", "password2", 1, 500,
100, 800, timePasswordChanged, true, true);
}
function run_test() {
initTestLogging("Trace");
@@ -191,9 +191,9 @@ function run_test() {
test_apply_multiple_records_with_times();
test_apply_same_record_with_different_times();
} finally {
store.wipe();
}
-}
\ No newline at end of file
+}
--- a/services/sync/tests/unit/test_places_guid_downgrade.js
+++ b/services/sync/tests/unit/test_places_guid_downgrade.js
@@ -29,17 +29,17 @@ function removePlacesDatabase() {
file.append(kDBName);
try {
file.remove(false);
} catch (ex) {
// Windows is awesome. NOT.
}
}
-Svc.Obs.add("places-shutdown", function () {
+Svc.Obs.add("places-shutdown", function() {
do_timeout(0, removePlacesDatabase);
});
// Verify initial database state. Function borrowed from places tests.
add_test(function test_initial_state() {
_("Verify initial setup: v11 database is available");
--- a/services/sync/tests/unit/test_postqueue.js
+++ b/services/sync/tests/unit/test_postqueue.js
@@ -3,17 +3,17 @@
let { PostQueue } = Cu.import("resource://services-sync/record.js", {});
initTestLogging("Trace");
function makeRecord(nbytes) {
// make a string 2-bytes less - the added quotes will make it correct.
return {
- toJSON: () => "x".repeat(nbytes-2),
+ toJSON: () => "x".repeat(nbytes - 2),
}
}
function makePostQueue(config, lastModTime, responseGenerator) {
let stats = {
posts: [],
}
let poster = (data, headers, batch, commit) => {
@@ -80,17 +80,17 @@ add_test(function test_max_post_bytes_no
pq.flush(true);
deepEqual(stats.posts, [
{
nbytes: 43, // 43 for the first post
commit: false,
headers: [["x-if-unmodified-since", time]],
batch: "true",
- },{
+ }, {
nbytes: 22,
commit: false, // we know we aren't in a batch, so never commit.
headers: [["x-if-unmodified-since", time + 100]],
batch: null,
}
]);
equal(pq.lastModified, time + 200);
@@ -120,17 +120,17 @@ add_test(function test_max_post_records_
pq.flush(true);
deepEqual(stats.posts, [
{
nbytes: 43, // 43 for the first post
commit: false,
batch: "true",
headers: [["x-if-unmodified-since", time]],
- },{
+ }, {
nbytes: 22,
commit: false, // we know we aren't in a batch, so never commit.
batch: null,
headers: [["x-if-unmodified-since", time + 100]],
}
]);
equal(pq.lastModified, time + 200);
@@ -197,17 +197,17 @@ add_test(function test_max_post_bytes_ba
pq.flush(true);
deepEqual(stats.posts, [
{
nbytes: 43, // 43 for the first post
commit: false,
batch: "true",
headers: [['x-if-unmodified-since', time]],
- },{
+ }, {
nbytes: 22,
commit: true,
batch: 1234,
headers: [['x-if-unmodified-since', time]],
}
]);
equal(pq.lastModified, time + 200);
@@ -254,29 +254,29 @@ add_test(function test_max_post_bytes_ba
pq.flush(true);
deepEqual(stats.posts, [
{
nbytes: 43, // 43 for the first post
commit: false,
batch: "true",
headers: [['x-if-unmodified-since', time0]],
- },{
+ }, {
// second post of 22 bytes in the first batch, committing it.
nbytes: 22,
commit: true,
batch: 1234,
headers: [['x-if-unmodified-since', time0]],
}, {
// 3rd post of 43 bytes in a new batch, not yet committing it.
nbytes: 43,
commit: false,
batch: "true",
headers: [['x-if-unmodified-since', time1]],
- },{
+ }, {
// 4th post of 22 bytes in second batch, committing it.
nbytes: 22,
commit: true,
batch: 5678,
headers: [['x-if-unmodified-since', time1]],
},
]);
@@ -312,17 +312,17 @@ add_test(function test_max_post_bytes_ba
pq.flush(true);
deepEqual(stats.posts, [
{
nbytes: 43, // 43 for the first post
commit: false,
batch: "true",
headers: [['x-if-unmodified-since', time]],
- },{
+ }, {
nbytes: 22,
commit: true,
batch: 1234,
headers: [['x-if-unmodified-since', time]],
}
]);
equal(pq.lastModified, time + 200);
@@ -364,17 +364,17 @@ add_test(function test_huge_record() {
pq.flush(true);
deepEqual(stats.posts, [
{
nbytes: 43, // 43 for the first post
commit: false,
batch: "true",
headers: [['x-if-unmodified-since', time]],
- },{
+ }, {
nbytes: 22,
commit: true,
batch: 1234,
headers: [['x-if-unmodified-since', time]],
}
]);
equal(pq.lastModified, time + 200);
@@ -426,30 +426,30 @@ add_test(function test_max_records_batch
pq.flush(true);
deepEqual(stats.posts, [
{ // 3 records
nbytes: 64,
commit: false,
batch: "true",
headers: [['x-if-unmodified-since', time0]],
- },{ // 2 records -- end batch1
+ }, { // 2 records -- end batch1
nbytes: 43,
commit: true,
batch: 1234,
headers: [['x-if-unmodified-since', time0]],
}, { // 3 records
nbytes: 64,
commit: false,
batch: "true",
headers: [['x-if-unmodified-since', time1]],
- },{ // 1 record -- end batch2
+ }, { // 1 record -- end batch2
nbytes: 22,
commit: true,
batch: 5678,
headers: [['x-if-unmodified-since', time1]],
},
]);
equal(pq.lastModified, time1 + 200);
run_next_test();
-});
\ No newline at end of file
+});
--- a/services/sync/tests/unit/test_records_crypto.js
+++ b/services/sync/tests/unit/test_records_crypto.js
@@ -61,18 +61,17 @@ add_task(async function test_records_cry
let payload = cryptoWrap.decrypt(keyBundle);
do_check_eq(payload.stuff, "my payload here");
do_check_neq(payload, cryptoWrap.payload); // wrap.data.payload is the encrypted one
log.info("Make sure multiple decrypts cause failures");
let error = "";
try {
payload = cryptoWrap.decrypt(keyBundle);
- }
- catch(ex) {
+ } catch (ex) {
error = ex;
}
do_check_eq(error, "No ciphertext: nothing to decrypt?");
log.info("Re-encrypting the record with alternate payload");
cryptoWrap.cleartext.stuff = "another payload";
cryptoWrap.encrypt(keyBundle);
@@ -84,30 +83,28 @@ add_task(async function test_records_cry
do_check_neq(firstIV, secondIV);
log.info("Make sure differing ids cause failures");
cryptoWrap.encrypt(keyBundle);
cryptoWrap.data.id = "other";
error = "";
try {
cryptoWrap.decrypt(keyBundle);
- }
- catch(ex) {
+ } catch (ex) {
error = ex;
}
do_check_eq(error, "Record id mismatch: resource != other");
log.info("Make sure wrong hmacs cause failures");
cryptoWrap.encrypt(keyBundle);
cryptoWrap.hmac = "foo";
error = "";
try {
cryptoWrap.decrypt(keyBundle);
- }
- catch(ex) {
+ } catch (ex) {
error = ex;
}
do_check_eq(error.substr(0, 42), "Record SHA256 HMAC mismatch: should be foo");
// Checking per-collection keys and default key handling.
generateNewKeys(Service.collectionKeys);
let bu = "http://localhost:8080/storage/bookmarks/foo";
@@ -167,13 +164,12 @@ add_task(async function test_records_cry
payload = {
default: Service.collectionKeys._default.keyPairB64,
collections: {}
};
// Verify that not passing `modified` doesn't throw
emptyKeys.setContents(payload, null);
log.info("Done!");
- }
- finally {
+ } finally {
await promiseStopServer(server);
}
});
--- a/services/sync/tests/unit/test_records_wbo.js
+++ b/services/sync/tests/unit/test_records_wbo.js
@@ -19,19 +19,19 @@ function test_toJSON() {
_("Verify that the JSON representation contains the WBO properties, but not TTL.");
let json = JSON.parse(JSON.stringify(wbo));
do_check_eq(json.modified, 12345);
do_check_eq(json.sortindex, 42);
do_check_eq(json.payload, "{}");
do_check_false("ttl" in json);
_("Set a TTL, make sure it's present in the JSON representation.");
- wbo.ttl = 30*60;
+ wbo.ttl = 30 * 60;
json = JSON.parse(JSON.stringify(wbo));
- do_check_eq(json.ttl, 30*60);
+ do_check_eq(json.ttl, 30 * 60);
}
function test_fetch() {
let record = {id: "asdf-1234-asdf-1234",
modified: 2454725.98283,
payload: JSON.stringify({cheese: "roquefort"})};
let record2 = {id: "record2",
--- a/services/sync/tests/unit/test_resource.js
+++ b/services/sync/tests/unit/test_resource.js
@@ -93,17 +93,17 @@ function server_json(metadata, response)
response.setStatusLine(metadata.httpVersion, 200, "OK");
response.bodyOutputStream.write(body, body.length);
}
const TIMESTAMP = 1274380461;
function server_timestamp(metadata, response) {
let body = "Thank you for your request";
- response.setHeader("X-Weave-Timestamp", ''+TIMESTAMP, false);
+ response.setHeader("X-Weave-Timestamp", '' + TIMESTAMP, false);
response.setStatusLine(metadata.httpVersion, 200, "OK");
response.bodyOutputStream.write(body, body.length);
}
function server_backoff(metadata, response) {
let body = "Hey, back off!";
response.setHeader("X-Weave-Backoff", '600', false);
response.setStatusLine(metadata.httpVersion, 200, "OK");
@@ -204,17 +204,17 @@ function run_test() {
do_check_true(content.success);
// res.data has been updated with the result from the request
do_check_eq(res.data, content);
// Observe logging messages.
logger = res._log;
let dbg = logger.debug;
let debugMessages = [];
- logger.debug = function (msg) {
+ logger.debug = function(msg) {
debugMessages.push(msg);
dbg.call(this, msg);
}
// Since we didn't receive proper JSON data, accessing content.obj
// will result in a SyntaxError from JSON.parse.
// Furthermore, we'll have logged.
let didThrow = false;
@@ -410,17 +410,17 @@ function run_test() {
do_check_eq(quotaValue, 1048576);
_("Error handling in _request() preserves exception information");
let error;
let res11 = new Resource("http://localhost:12345/does/not/exist");
try {
content = res11.get();
- } catch(ex) {
+ } catch (ex) {
error = ex;
}
do_check_eq(error.result, Cr.NS_ERROR_CONNECTION_REFUSED);
do_check_eq(error.message, "NS_ERROR_CONNECTION_REFUSED");
do_check_eq(typeof error.stack, "string");
_("Checking handling of errors in onProgress.");
let res18 = new Resource(server.baseURI + "/json");
--- a/services/sync/tests/unit/test_resource_async.js
+++ b/services/sync/tests/unit/test_resource_async.js
@@ -93,17 +93,17 @@ function server_json(metadata, response)
response.setStatusLine(metadata.httpVersion, 200, "OK");
response.bodyOutputStream.write(body, body.length);
}
const TIMESTAMP = 1274380461;
function server_timestamp(metadata, response) {
let body = "Thank you for your request";
- response.setHeader("X-Weave-Timestamp", ''+TIMESTAMP, false);
+ response.setHeader("X-Weave-Timestamp", '' + TIMESTAMP, false);
response.setStatusLine(metadata.httpVersion, 200, "OK");
response.bodyOutputStream.write(body, body.length);
}
function server_backoff(metadata, response) {
let body = "Hey, back off!";
response.setHeader("X-Weave-Backoff", '600', false);
response.setStatusLine(metadata.httpVersion, 200, "OK");
@@ -145,17 +145,17 @@ function server_headers(metadata, respon
}
let body = JSON.stringify(headers);
response.setStatusLine(metadata.httpVersion, 200, "OK");
response.bodyOutputStream.write(body, body.length);
}
var quotaValue;
Observers.add("weave:service:quota:remaining",
- function (subject) { quotaValue = subject; });
+ function(subject) { quotaValue = subject; });
function run_test() {
logger = Log.repository.getLogger('Test');
Log.repository.rootLogger.addAppender(new Log.DumpAppender());
Svc.Prefs.set("network.numRetries", 1); // speed up test
run_next_test();
}
@@ -168,17 +168,17 @@ add_test(function test_proxy_auth_redire
let server = httpd_setup({
"/open": server_open,
"/pac2": server_pac
});
PACSystemSettings.PACURI = server.baseURI + "/pac2";
installFakePAC();
let res = new AsyncResource(server.baseURI + "/open");
- res.get(function (error, result) {
+ res.get(function(error, result) {
do_check_true(!error);
do_check_true(pacFetched);
do_check_true(fetched);
do_check_eq("This path exists", result);
pacFetched = fetched = false;
uninstallFakePAC();
server.stop(run_next_test);
});
@@ -256,29 +256,29 @@ add_test(function test_members() {
do_check_eq(res.data, null);
run_next_test();
});
add_test(function test_get() {
_("GET a non-password-protected resource");
let res = new AsyncResource(server.baseURI + "/open");
- res.get(function (error, content) {
+ res.get(function(error, content) {
do_check_eq(error, null);
do_check_eq(content, "This path exists");
do_check_eq(content.status, 200);
do_check_true(content.success);
// res.data has been updated with the result from the request
do_check_eq(res.data, content);
// Observe logging messages.
let logger = res._log;
let dbg = logger.debug;
let debugMessages = [];
- logger.debug = function (msg) {
+ logger.debug = function(msg) {
debugMessages.push(msg);
dbg.call(this, msg);
}
// Since we didn't receive proper JSON data, accessing content.obj
// will result in a SyntaxError from JSON.parse
let didThrow = false;
try {
@@ -304,45 +304,45 @@ add_test(function test_basicauth() {
do_check_eq(res1.headers["authorization"], "Basic foobar");
run_next_test();
});
add_test(function test_get_protected_fail() {
_("GET a password protected resource (test that it'll fail w/o pass, no throw)");
let res2 = new AsyncResource(server.baseURI + "/protected");
- res2.get(function (error, content) {
+ res2.get(function(error, content) {
do_check_eq(error, null);
do_check_eq(content, "This path exists and is protected - failed");
do_check_eq(content.status, 401);
do_check_false(content.success);
run_next_test();
});
});
add_test(function test_get_protected_success() {
_("GET a password protected resource");
let identity = new IdentityManager();
let auth = identity.getBasicResourceAuthenticator("guest", "guest");
let res3 = new AsyncResource(server.baseURI + "/protected");
res3.authenticator = auth;
do_check_eq(res3.authenticator, auth);
- res3.get(function (error, content) {
+ res3.get(function(error, content) {
do_check_eq(error, null);
do_check_eq(content, "This path exists and is protected");
do_check_eq(content.status, 200);
do_check_true(content.success);
run_next_test();
});
});
add_test(function test_get_404() {
_("GET a non-existent resource (test that it'll fail, but not throw)");
let res4 = new AsyncResource(server.baseURI + "/404");
- res4.get(function (error, content) {
+ res4.get(function(error, content) {
do_check_eq(error, null);
do_check_eq(content, "File not found");
do_check_eq(content.status, 404);
do_check_false(content.success);
// Check some headers of the 404 response
do_check_eq(content.headers.connection, "close");
do_check_eq(content.headers.server, "httpd.js");
@@ -362,270 +362,270 @@ add_test(function test_put_string() {
do_check_eq(res_upload.data, content);
run_next_test();
});
});
add_test(function test_put_object() {
_("PUT to a resource (object)");
let res_upload = new AsyncResource(server.baseURI + "/upload");
- res_upload.put(sample_data, function (error, content) {
+ res_upload.put(sample_data, function(error, content) {
do_check_eq(error, null);
do_check_eq(content, "Valid data upload via PUT");
do_check_eq(content.status, 200);
do_check_eq(res_upload.data, content);
run_next_test();
});
});
add_test(function test_put_data_string() {
_("PUT without data arg (uses resource.data) (string)");
let res_upload = new AsyncResource(server.baseURI + "/upload");
res_upload.data = JSON.stringify(sample_data);
- res_upload.put(function (error, content) {
+ res_upload.put(function(error, content) {
do_check_eq(error, null);
do_check_eq(content, "Valid data upload via PUT");
do_check_eq(content.status, 200);
do_check_eq(res_upload.data, content);
run_next_test();
});
});
add_test(function test_put_data_object() {
_("PUT without data arg (uses resource.data) (object)");
let res_upload = new AsyncResource(server.baseURI + "/upload");
res_upload.data = sample_data;
- res_upload.put(function (error, content) {
+ res_upload.put(function(error, content) {
do_check_eq(error, null);
do_check_eq(content, "Valid data upload via PUT");
do_check_eq(content.status, 200);
do_check_eq(res_upload.data, content);
run_next_test();
});
});
add_test(function test_post_string() {
_("POST to a resource (string)");
let res_upload = new AsyncResource(server.baseURI + "/upload");
- res_upload.post(JSON.stringify(sample_data), function (error, content) {
+ res_upload.post(JSON.stringify(sample_data), function(error, content) {
do_check_eq(error, null);
do_check_eq(content, "Valid data upload via POST");
do_check_eq(content.status, 200);
do_check_eq(res_upload.data, content);
run_next_test();
});
});
add_test(function test_post_object() {
_("POST to a resource (object)");
let res_upload = new AsyncResource(server.baseURI + "/upload");
- res_upload.post(sample_data, function (error, content) {
+ res_upload.post(sample_data, function(error, content) {
do_check_eq(error, null);
do_check_eq(content, "Valid data upload via POST");
do_check_eq(content.status, 200);
do_check_eq(res_upload.data, content);
run_next_test();
});
});
add_test(function test_post_data_string() {
_("POST without data arg (uses resource.data) (string)");
let res_upload = new AsyncResource(server.baseURI + "/upload");
res_upload.data = JSON.stringify(sample_data);
- res_upload.post(function (error, content) {
+ res_upload.post(function(error, content) {
do_check_eq(error, null);
do_check_eq(content, "Valid data upload via POST");
do_check_eq(content.status, 200);
do_check_eq(res_upload.data, content);
run_next_test();
});
});
add_test(function test_post_data_object() {
_("POST without data arg (uses resource.data) (object)");
let res_upload = new AsyncResource(server.baseURI + "/upload");
res_upload.data = sample_data;
- res_upload.post(function (error, content) {
+ res_upload.post(function(error, content) {
do_check_eq(error, null);
do_check_eq(content, "Valid data upload via POST");
do_check_eq(content.status, 200);
do_check_eq(res_upload.data, content);
run_next_test();
});
});
add_test(function test_delete() {
_("DELETE a resource");
let res6 = new AsyncResource(server.baseURI + "/delete");
- res6.delete(function (error, content) {
+ res6.delete(function(error, content) {
do_check_eq(error, null);
do_check_eq(content, "This resource has been deleted");
do_check_eq(content.status, 200);
run_next_test();
});
});
add_test(function test_json_body() {
_("JSON conversion of response body");
let res7 = new AsyncResource(server.baseURI + "/json");
- res7.get(function (error, content) {
+ res7.get(function(error, content) {
do_check_eq(error, null);
do_check_eq(content, JSON.stringify(sample_data));
do_check_eq(content.status, 200);
do_check_eq(JSON.stringify(content.obj), JSON.stringify(sample_data));
run_next_test();
});
});
add_test(function test_weave_timestamp() {
_("X-Weave-Timestamp header updates AsyncResource.serverTime");
// Before having received any response containing the
// X-Weave-Timestamp header, AsyncResource.serverTime is null.
do_check_eq(AsyncResource.serverTime, null);
let res8 = new AsyncResource(server.baseURI + "/timestamp");
- res8.get(function (error, content) {
+ res8.get(function(error, content) {
do_check_eq(error, null);
do_check_eq(AsyncResource.serverTime, TIMESTAMP);
run_next_test();
});
});
add_test(function test_get_no_headers() {
_("GET: no special request headers");
let res_headers = new AsyncResource(server.baseURI + "/headers");
- res_headers.get(function (error, content) {
+ res_headers.get(function(error, content) {
do_check_eq(error, null);
do_check_eq(content, '{}');
run_next_test();
});
});
add_test(function test_put_default_content_type() {
_("PUT: Content-Type defaults to text/plain");
let res_headers = new AsyncResource(server.baseURI + "/headers");
- res_headers.put('data', function (error, content) {
+ res_headers.put('data', function(error, content) {
do_check_eq(error, null);
do_check_eq(content, JSON.stringify({"content-type": "text/plain"}));
run_next_test();
});
});
add_test(function test_post_default_content_type() {
_("POST: Content-Type defaults to text/plain");
let res_headers = new AsyncResource(server.baseURI + "/headers");
- res_headers.post('data', function (error, content) {
+ res_headers.post('data', function(error, content) {
do_check_eq(error, null);
do_check_eq(content, JSON.stringify({"content-type": "text/plain"}));
run_next_test();
});
});
add_test(function test_setHeader() {
_("setHeader(): setting simple header");
let res_headers = new AsyncResource(server.baseURI + "/headers");
res_headers.setHeader('X-What-Is-Weave', 'awesome');
do_check_eq(res_headers.headers['x-what-is-weave'], 'awesome');
- res_headers.get(function (error, content) {
+ res_headers.get(function(error, content) {
do_check_eq(error, null);
do_check_eq(content, JSON.stringify({"x-what-is-weave": "awesome"}));
run_next_test();
});
});
add_test(function test_setHeader_overwrite() {
_("setHeader(): setting multiple headers, overwriting existing header");
let res_headers = new AsyncResource(server.baseURI + "/headers");
res_headers.setHeader('X-WHAT-is-Weave', 'more awesomer');
res_headers.setHeader('X-Another-Header', 'hello world');
do_check_eq(res_headers.headers['x-what-is-weave'], 'more awesomer');
do_check_eq(res_headers.headers['x-another-header'], 'hello world');
- res_headers.get(function (error, content) {
+ res_headers.get(function(error, content) {
do_check_eq(error, null);
do_check_eq(content, JSON.stringify({"x-another-header": "hello world",
"x-what-is-weave": "more awesomer"}));
run_next_test();
});
});
add_test(function test_headers_object() {
_("Setting headers object");
let res_headers = new AsyncResource(server.baseURI + "/headers");
res_headers.headers = {};
- res_headers.get(function (error, content) {
+ res_headers.get(function(error, content) {
do_check_eq(error, null);
do_check_eq(content, "{}");
run_next_test();
});
});
add_test(function test_put_override_content_type() {
_("PUT: override default Content-Type");
let res_headers = new AsyncResource(server.baseURI + "/headers");
res_headers.setHeader('Content-Type', 'application/foobar');
do_check_eq(res_headers.headers['content-type'], 'application/foobar');
- res_headers.put('data', function (error, content) {
+ res_headers.put('data', function(error, content) {
do_check_eq(error, null);
do_check_eq(content, JSON.stringify({"content-type": "application/foobar"}));
run_next_test();
});
});
add_test(function test_post_override_content_type() {
_("POST: override default Content-Type");
let res_headers = new AsyncResource(server.baseURI + "/headers");
res_headers.setHeader('Content-Type', 'application/foobar');
- res_headers.post('data', function (error, content) {
+ res_headers.post('data', function(error, content) {
do_check_eq(error, null);
do_check_eq(content, JSON.stringify({"content-type": "application/foobar"}));
run_next_test();
});
});
add_test(function test_weave_backoff() {
_("X-Weave-Backoff header notifies observer");
let backoffInterval;
function onBackoff(subject, data) {
backoffInterval = subject;
}
Observers.add("weave:service:backoff:interval", onBackoff);
let res10 = new AsyncResource(server.baseURI + "/backoff");
- res10.get(function (error, content) {
+ res10.get(function(error, content) {
do_check_eq(error, null);
do_check_eq(backoffInterval, 600);
run_next_test();
});
});
add_test(function test_quota_error() {
_("X-Weave-Quota-Remaining header notifies observer on successful requests.");
let res10 = new AsyncResource(server.baseURI + "/quota-error");
- res10.get(function (error, content) {
+ res10.get(function(error, content) {
do_check_eq(error, null);
do_check_eq(content.status, 400);
do_check_eq(quotaValue, undefined); // HTTP 400, so no observer notification.
run_next_test();
});
});
add_test(function test_quota_notice() {
let res10 = new AsyncResource(server.baseURI + "/quota-notice");
- res10.get(function (error, content) {
+ res10.get(function(error, content) {
do_check_eq(error, null);
do_check_eq(content.status, 200);
do_check_eq(quotaValue, 1048576);
run_next_test();
});
});
add_test(function test_preserve_exceptions() {
_("Error handling in ChannelListener etc. preserves exception information");
let res11 = new AsyncResource("http://localhost:12345/does/not/exist");
- res11.get(function (error, content) {
+ res11.get(function(error, content) {
do_check_neq(error, null);
do_check_eq(error.result, Cr.NS_ERROR_CONNECTION_REFUSED);
do_check_eq(error.message, "NS_ERROR_CONNECTION_REFUSED");
run_next_test();
});
});
add_test(function test_xpc_exception_handling() {
@@ -633,17 +633,17 @@ add_test(function test_xpc_exception_han
let res14 = new AsyncResource(server.baseURI + "/json");
res14._onProgress = function(rec) {
// Provoke an XPC exception without a Javascript wrapper.
Services.io.newURI("::::::::");
};
let warnings = [];
res14._log.warn = function(msg) { warnings.push(msg); };
- res14.get(function (error, content) {
+ res14.get(function(error, content) {
do_check_eq(error.result, Cr.NS_ERROR_MALFORMED_URI);
do_check_eq(error.message, "NS_ERROR_MALFORMED_URI");
do_check_eq(content, null);
do_check_eq(warnings.pop(),
"Got exception calling onProgress handler during fetch of " +
server.baseURI + "/json");
run_next_test();
@@ -654,33 +654,33 @@ add_test(function test_js_exception_hand
_("JS exception handling inside fetches.");
let res15 = new AsyncResource(server.baseURI + "/json");
res15._onProgress = function(rec) {
throw "BOO!";
};
let warnings = [];
res15._log.warn = function(msg) { warnings.push(msg); };
- res15.get(function (error, content) {
+ res15.get(function(error, content) {
do_check_eq(error.result, Cr.NS_ERROR_XPC_JS_THREW_STRING);
do_check_eq(error.message, "NS_ERROR_XPC_JS_THREW_STRING");
do_check_eq(content, null);
do_check_eq(warnings.pop(),
"Got exception calling onProgress handler during fetch of " +
server.baseURI + "/json");
run_next_test();
});
});
add_test(function test_timeout() {
_("Ensure channel timeouts are thrown appropriately.");
let res19 = new AsyncResource(server.baseURI + "/json");
res19.ABORT_TIMEOUT = 0;
- res19.get(function (error, content) {
+ res19.get(function(error, content) {
do_check_eq(error.result, Cr.NS_ERROR_NET_TIMEOUT);
run_next_test();
});
});
add_test(function test_uri_construction() {
_("Testing URI construction.");
let args = [];
@@ -708,17 +708,17 @@ add_test(function test_not_sending_cooki
do_check_false(metadata.hasHeader("Cookie"));
}
let cookieSer = Cc["@mozilla.org/cookieService;1"]
.getService(Ci.nsICookieService);
let uri = CommonUtils.makeURI(server.baseURI);
cookieSer.setCookieString(uri, null, "test=test; path=/;", null);
let res = new AsyncResource(server.baseURI + "/test");
- res.get(function (error) {
+ res.get(function(error) {
do_check_null(error);
do_check_true(this.response.success);
do_check_eq("COOKIE!", this.response.body);
server.stop(run_next_test);
});
});
/**
--- a/services/sync/tests/unit/test_resource_header.js
+++ b/services/sync/tests/unit/test_resource_header.js
@@ -30,19 +30,19 @@ function contentHandler(metadata, respon
_("Extracted headers. " + auth + ", " + foo);
response.setHeader("Content-Type", "text/plain");
response.bodyOutputStream.write(BODY, BODY.length);
}
// Set a proxy function to cause an internal redirect.
function triggerRedirect() {
- const PROXY_FUNCTION = "function FindProxyForURL(url, host) {" +
+ const PROXY_FUNCTION = "function FindProxyForURL(url, host) {" +
" return 'PROXY a_non_existent_domain_x7x6c572v:80; " +
- "PROXY localhost:" + HTTP_PORT + "';" +
+ "PROXY localhost:" + HTTP_PORT + "';" +
"}";
let prefsService = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService);
let prefs = prefsService.getBranch("network.proxy.");
prefs.setIntPref("type", 2);
prefs.setCharPref("autoconfig_url", "data:text/plain," + PROXY_FUNCTION);
}
--- a/services/sync/tests/unit/test_resource_ua.js
+++ b/services/sync/tests/unit/test_resource_ua.js
@@ -55,17 +55,17 @@ add_test(function test_fetchInfo() {
do_check_eq(ua, expectedUA + ".desktop");
ua = "";
run_next_test();
});
add_test(function test_desktop_post() {
_("Testing direct Resource POST.");
let r = new AsyncResource(server.baseURI + "/1.1/johndoe/storage/meta/global");
- r.post("foo=bar", function (error, content) {
+ r.post("foo=bar", function(error, content) {
_("User-Agent: " + ua);
do_check_eq(ua, expectedUA + ".desktop");
ua = "";
run_next_test();
});
});
add_test(function test_desktop_get() {
@@ -79,17 +79,17 @@ add_test(function test_desktop_get() {
run_next_test();
});
});
add_test(function test_mobile_get() {
_("Testing mobile.");
Svc.Prefs.set("client.type", "mobile");
let r = new AsyncResource(server.baseURI + "/1.1/johndoe/storage/meta/global");
- r.get(function (error, content) {
+ r.get(function(error, content) {
_("User-Agent: " + ua);
do_check_eq(ua, expectedUA + ".mobile");
ua = "";
run_next_test();
});
});
add_test(function tear_down() {
--- a/services/sync/tests/unit/test_sendcredentials_controller.js
+++ b/services/sync/tests/unit/test_sendcredentials_controller.js
@@ -26,19 +26,19 @@ function make_sendCredentials_test(topic
let jpakeclient = {
sendAndComplete: function sendAndComplete(data) {
// Verify that the controller unregisters itself as an observer
// when the exchange is complete by faking another notification.
do_check_false(sendAndCompleteCalled);
sendAndCompleteCalled = true;
// Verify it sends the correct data.
- do_check_eq(data.account, Service.identity.account);
- do_check_eq(data.password, Service.identity.basicPassword);
- do_check_eq(data.synckey, Service.identity.syncKey);
+ do_check_eq(data.account, Service.identity.account);
+ do_check_eq(data.password, Service.identity.basicPassword);
+ do_check_eq(data.synckey, Service.identity.syncKey);
do_check_eq(data.serverURL, Service.serverURL);
this.controller.onComplete();
// Verify it schedules a sync for the expected interval.
let expectedInterval = Service.scheduler.activeInterval;
do_check_true(Service.scheduler.nextSync - Date.now() <= expectedInterval);
// Signal the end of another sync. We shouldn't be registered anymore,
--- a/services/sync/tests/unit/test_service_detect_upgrade.js
+++ b/services/sync/tests/unit/test_service_detect_upgrade.js
@@ -77,18 +77,17 @@ add_test(function v4_upgrade() {
_("Old meta/global: " + JSON.stringify(meta_global));
meta_global.payload = JSON.stringify({"syncID": "foooooooooooooooooooooooooo",
"storageVersion": STORAGE_VERSION + 1});
collections.meta = Date.now() / 1000;
_("New meta/global: " + JSON.stringify(meta_global));
Service.recordManager.set(Service.metaURL, meta_global);
try {
Service.sync();
- }
- catch (ex) {
+ } catch (ex) {
}
do_check_eq(Service.status.sync, VERSION_OUT_OF_DATE);
}
// See what happens when we bump the storage version.
_("Syncing after server has been upgraded.");
test_out_of_date();
@@ -170,17 +169,17 @@ add_test(function v4_upgrade() {
let oldTabsModified = collections.tabs;
Service.login("johndoe", "ilovejane", passphrase);
Service.sync();
_("New key should have forced upload of data.");
_("Tabs: " + oldTabsModified + " < " + collections.tabs);
_("Clients: " + oldClientsModified + " < " + collections.clients);
do_check_true(collections.clients > oldClientsModified);
- do_check_true(collections.tabs > oldTabsModified);
+ do_check_true(collections.tabs > oldTabsModified);
_("... and keys will now match.");
retrieve_and_compare_default(true);
// Clean up.
Service.startOver();
} finally {
@@ -267,18 +266,17 @@ add_test(function v5_upgrade() {
generateNewKeys(Service.collectionKeys);
// Now sync and see what happens. It should be a version fail, not a crypto
// fail.
_("Logging in.");
try {
Service.login("johndoe", "ilovejane", passphrase);
- }
- catch (e) {
+ } catch (e) {
_("Exception: " + e);
}
_("Status: " + Service.status);
do_check_false(Service.isLoggedIn);
do_check_eq(VERSION_OUT_OF_DATE, Service.status.sync);
// Clean up.
Service.startOver();
--- a/services/sync/tests/unit/test_service_getStorageInfo.js
+++ b/services/sync/tests/unit/test_service_getStorageInfo.js
@@ -26,17 +26,17 @@ function run_test() {
}
add_test(function test_success() {
let handler = httpd_handler(200, "OK", JSON.stringify(collections));
let server = httpd_setup({"/1.1/johndoe/info/collections": handler});
Service.serverURL = server.baseURI + "/";
Service.clusterURL = server.baseURI + "/";
- let request = Service.getStorageInfo("collections", function (error, info) {
+ let request = Service.getStorageInfo("collections", function(error, info) {
do_check_eq(error, null);
do_check_true(Utils.deepEquals(info, collections));
// Ensure that the request is sent off with the right bits.
do_check_true(basic_auth_matches(handler.request,
Service.identity.username,
Service.identity.basicPassword));
let expectedUA = Services.appinfo.name + "/" + Services.appinfo.version +
@@ -46,49 +46,49 @@ add_test(function test_success() {
do_check_eq(handler.request.getHeader("User-Agent"), expectedUA);
server.stop(run_next_test);
});
do_check_true(request instanceof RESTRequest);
});
add_test(function test_invalid_type() {
- do_check_throws(function () {
- Service.getStorageInfo("invalid", function (error, info) {
+ do_check_throws(function() {
+ Service.getStorageInfo("invalid", function(error, info) {
do_throw("Shouldn't get here!");
});
});
run_next_test();
});
add_test(function test_network_error() {
- Service.getStorageInfo(INFO_COLLECTIONS, function (error, info) {
+ Service.getStorageInfo(INFO_COLLECTIONS, function(error, info) {
do_check_eq(error.result, Cr.NS_ERROR_CONNECTION_REFUSED);
do_check_eq(info, null);
run_next_test();
});
});
add_test(function test_http_error() {
let handler = httpd_handler(500, "Oh noez", "Something went wrong!");
let server = httpd_setup({"/1.1/johndoe/info/collections": handler});
Service.serverURL = server.baseURI + "/";
Service.clusterURL = server.baseURI + "/";
- let request = Service.getStorageInfo(INFO_COLLECTIONS, function (error, info) {
+ let request = Service.getStorageInfo(INFO_COLLECTIONS, function(error, info) {
do_check_eq(error.status, 500);
do_check_eq(info, null);
server.stop(run_next_test);
});
});
add_test(function test_invalid_json() {
let handler = httpd_handler(200, "OK", "Invalid JSON");
let server = httpd_setup({"/1.1/johndoe/info/collections": handler});
Service.serverURL = server.baseURI + "/";
Service.clusterURL = server.baseURI + "/";
- let request = Service.getStorageInfo(INFO_COLLECTIONS, function (error, info) {
+ let request = Service.getStorageInfo(INFO_COLLECTIONS, function(error, info) {
do_check_eq(error.name, "SyntaxError");
do_check_eq(info, null);
server.stop(run_next_test);
});
});
--- a/services/sync/tests/unit/test_service_login.js
+++ b/services/sync/tests/unit/test_service_login.js
@@ -4,17 +4,17 @@
Cu.import("resource://gre/modules/Log.jsm");
Cu.import("resource://services-sync/constants.js");
Cu.import("resource://services-sync/service.js");
Cu.import("resource://services-sync/policies.js");
Cu.import("resource://services-sync/util.js");
Cu.import("resource://testing-common/services/sync/utils.js");
function login_handling(handler) {
- return function (request, response) {
+ return function(request, response) {
if (basic_auth_matches(request, "johndoe", "ilovejane") ||
basic_auth_matches(request, "janedoe", "ilovejohn")) {
handler(request, response);
} else {
let body = "Unauthorized";
response.setStatusLine(request.httpVersion, 401, "Unauthorized");
response.setHeader("Content-Type", "text/plain");
response.bodyOutputStream.write(body, body.length);
@@ -53,19 +53,19 @@ function setup() {
let server = httpd_setup({
"/1.1/johndoe/info/collections": login_handling(johnHelper.handler),
"/1.1/janedoe/info/collections": login_handling(janeHelper.handler),
// We need these handlers because we test login, and login
// is where keys are generated or fetched.
// TODO: have Jane fetch her keys, not generate them...
"/1.1/johndoe/storage/crypto/keys": johnU("crypto", new ServerWBO("keys").handler()),
- "/1.1/johndoe/storage/meta/global": johnU("meta", new ServerWBO("global").handler()),
+ "/1.1/johndoe/storage/meta/global": johnU("meta", new ServerWBO("global").handler()),
"/1.1/janedoe/storage/crypto/keys": janeU("crypto", new ServerWBO("keys").handler()),
- "/1.1/janedoe/storage/meta/global": janeU("meta", new ServerWBO("global").handler())
+ "/1.1/janedoe/storage/meta/global": janeU("meta", new ServerWBO("global").handler())
});
Service.serverURL = server.baseURI;
return server;
}
add_test(function test_login_logout() {
let server = setup();
--- a/services/sync/tests/unit/test_service_migratePrefs.js
+++ b/services/sync/tests/unit/test_service_migratePrefs.js
@@ -13,17 +13,17 @@ function test_migrate_logging() {
do_check_eq(Svc.Prefs.get("log.appender.file.logOnSuccess"), false);
Service._migratePrefs();
do_check_eq("Warn", Svc.Prefs.get("log.appender.file.level"));
do_check_true(Svc.Prefs.get("log.appender.file.logOnSuccess"));
do_check_eq(Svc.Prefs.get("log.appender.debugLog"), undefined);
do_check_eq(Svc.Prefs.get("log.appender.debugLog.enabled"), undefined);
-};
+}
function run_test() {
_("Set some prefs on the old branch");
let globalPref = new Preferences("");
globalPref.set("extensions.weave.hello", "world");
globalPref.set("extensions.weave.number", 42);
globalPref.set("extensions.weave.yes", true);
globalPref.set("extensions.weave.no", false);
--- a/services/sync/tests/unit/test_service_passwordUTF8.js
+++ b/services/sync/tests/unit/test_service_passwordUTF8.js
@@ -15,17 +15,17 @@ var basicauth = {};
basicauth[LOWBYTES] = "Basic am9obmRvZTr/////";
basicauth[Utils.encodeUTF8(JAPANESE)] = "Basic am9obmRvZTrjk7/jl7/jm7/jn78=";
// Global var for the server password, read by info_collections(),
// modified by change_password().
var server_password;
function login_handling(handler) {
- return function (request, response) {
+ return function(request, response) {
let basic = basicauth[server_password];
if (basic && (request.getHeader("Authorization") == basic)) {
handler(request, response);
} else {
let body = "Unauthorized";
response.setStatusLine(request.httpVersion, 401, "Unauthorized");
response.setHeader("WWW-Authenticate", 'Basic realm="secret"', false);
@@ -58,17 +58,17 @@ function run_test() {
let upd = collectionsHelper.with_updated_collection;
let collections = collectionsHelper.collections;
ensureLegacyIdentityManager();
do_test_pending();
let server = httpd_setup({
"/1.1/johndoe/info/collections": login_handling(collectionsHelper.handler),
- "/1.1/johndoe/storage/meta/global": upd("meta", new ServerWBO("global").handler()),
+ "/1.1/johndoe/storage/meta/global": upd("meta", new ServerWBO("global").handler()),
"/1.1/johndoe/storage/crypto/keys": upd("crypto", new ServerWBO("keys").handler()),
"/user/1.0/johndoe/password": change_password
});
setBasicCredentials("johndoe", JAPANESE, "irrelevant");
Service.serverURL = server.baseURI;
try {
--- a/services/sync/tests/unit/test_service_startOver.js
+++ b/services/sync/tests/unit/test_service_startOver.js
@@ -9,17 +9,17 @@ Cu.import("resource://testing-common/ser
function BlaEngine() {
SyncEngine.call(this, "Bla", Service);
}
BlaEngine.prototype = {
__proto__: SyncEngine.prototype,
removed: false,
- removeClientData: function() {
+ removeClientData() {
this.removed = true;
}
};
Service.engineManager.register(BlaEngine);
--- a/services/sync/tests/unit/test_service_startup.js
+++ b/services/sync/tests/unit/test_service_startup.js
@@ -33,17 +33,17 @@ function run_test() {
do_check_true(Utils.deepEquals(engines.map(engine => engine.name),
['tabs', 'bookmarks', 'forms', 'history']));
_("Observers are notified of startup");
do_test_pending();
do_check_false(Service.status.ready);
do_check_false(xps.ready);
- Observers.add("weave:service:ready", function (subject, data) {
+ Observers.add("weave:service:ready", function(subject, data) {
do_check_true(Service.status.ready);
do_check_true(xps.ready);
// Clean up.
Svc.Prefs.resetBranch("");
do_test_finished();
});
}
--- a/services/sync/tests/unit/test_service_sync_401.js
+++ b/services/sync/tests/unit/test_service_sync_401.js
@@ -3,17 +3,17 @@
Cu.import("resource://services-sync/constants.js");
Cu.import("resource://services-sync/policies.js");
Cu.import("resource://services-sync/service.js");
Cu.import("resource://services-sync/util.js");
Cu.import("resource://testing-common/services/sync/utils.js");
function login_handling(handler) {
- return function (request, response) {
+ return function(request, response) {
if (request.hasHeader("Authorization") &&
request.getHeader("Authorization").includes('Hawk id="id"')) {
handler(request, response);
} else {
let body = "Unauthorized";
response.setStatusLine(request.httpVersion, 401, "Unauthorized");
response.bodyOutputStream.write(body, body.length);
}
@@ -25,31 +25,31 @@ add_task(async function run_test() {
Log.repository.rootLogger.addAppender(new Log.DumpAppender());
let collectionsHelper = track_collections_helper();
let upd = collectionsHelper.with_updated_collection;
let collections = collectionsHelper.collections;
let server = httpd_setup({
"/1.1/johndoe/storage/crypto/keys": upd("crypto", new ServerWBO("keys").handler()),
- "/1.1/johndoe/storage/meta/global": upd("meta", new ServerWBO("global").handler()),
+ "/1.1/johndoe/storage/meta/global": upd("meta", new ServerWBO("global").handler()),
"/1.1/johndoe/info/collections": login_handling(collectionsHelper.handler)
});
const GLOBAL_SCORE = 42;
try {
_("Set up test fixtures.");
await SyncTestingInfrastructure(server, "johndoe", "ilovejane");
Service.scheduler.globalScore = GLOBAL_SCORE;
// Avoid daily ping
Svc.Prefs.set("lastPing", Math.floor(Date.now() / 1000));
let threw = false;
- Svc.Obs.add("weave:service:sync:error", function (subject, data) {
+ Svc.Obs.add("weave:service:sync:error", function(subject, data) {
threw = true;
});
_("Initial state: We're successfully logged in.");
Service.login();
do_check_true(Service.isLoggedIn);
do_check_eq(Service.status.login, LOGIN_SUCCEEDED);
--- a/services/sync/tests/unit/test_service_sync_locked.js
+++ b/services/sync/tests/unit/test_service_sync_locked.js
@@ -10,17 +10,17 @@ function run_test() {
let info = [];
function augmentLogger(old) {
let d = old.debug;
let i = old.info;
// For the purposes of this test we don't need to do full formatting
// of the 2nd param, as the ones we care about are always strings.
old.debug = function(m, p) { debug.push(p ? m + ": " + p : m); d.call(old, m, p); }
- old.info = function(m, p) { info.push(p ? m + ": " + p : m); i.call(old, m, p); }
+ old.info = function(m, p) { info.push(p ? m + ": " + p : m); i.call(old, m, p); }
return old;
}
Log.repository.rootLogger.addAppender(new Log.DumpAppender());
augmentLogger(Service._log);
// Avoid daily ping
--- a/services/sync/tests/unit/test_service_sync_remoteSetup.js
+++ b/services/sync/tests/unit/test_service_sync_remoteSetup.js
@@ -155,17 +155,17 @@ function run_test() {
Service.recordManager.set(Service.metaURL, { isNew: false });
do_check_false(Service._remoteSetup(makeOutdatedMeta()));
do_check_eq(Service.status.sync, "");
mock.restore();
metaColl.delete({});
_("Do an initial sync.");
- let beforeSync = Date.now()/1000;
+ let beforeSync = Date.now() / 1000;
Service.sync();
_("Checking that remoteSetup returns true.");
do_check_true(Service._remoteSetup());
_("Verify that the meta record was uploaded.");
do_check_eq(meta_global.data.syncID, Service.syncID);
do_check_eq(meta_global.data.storageVersion, STORAGE_VERSION);
@@ -219,17 +219,17 @@ function run_test() {
// Try to screw up HMAC calculation.
// Re-encrypt keys with a new random keybundle, and upload them to the
// server, just as might happen with a second client.
_("Attempting to screw up HMAC by re-encrypting keys.");
let keys = Service.collectionKeys.asWBO();
let b = new BulkKeyBundle("hmacerror");
b.generateRandom();
- collections.crypto = keys.modified = 100 + (Date.now()/1000); // Future modification time.
+ collections.crypto = keys.modified = 100 + (Date.now() / 1000); // Future modification time.
keys.encrypt(b);
keys.upload(Service.resource(Service.cryptoKeysURL));
do_check_false(Service.verifyAndFetchSymmetricKeys());
do_check_eq(Service.status.login, LOGIN_FAILED_INVALID_PASSPHRASE);
} finally {
Svc.Prefs.resetBranch("");
server.stop(do_test_finished);
--- a/services/sync/tests/unit/test_service_verifyLogin.js
+++ b/services/sync/tests/unit/test_service_verifyLogin.js
@@ -3,17 +3,17 @@
Cu.import("resource://gre/modules/Log.jsm");
Cu.import("resource://services-sync/constants.js");
Cu.import("resource://services-sync/service.js");
Cu.import("resource://services-sync/util.js");
Cu.import("resource://testing-common/services/sync/utils.js");
function login_handling(handler) {
- return function (request, response) {
+ return function(request, response) {
if (basic_auth_matches(request, "johndoe", "ilovejane")) {
handler(request, response);
} else {
let body = "Unauthorized";
response.setStatusLine(request.httpVersion, 401, "Unauthorized");
response.bodyOutputStream.write(body, body.length);
}
};
@@ -35,28 +35,28 @@ function run_test() {
Services.logins.removeAllLogins();
let johnHelper = track_collections_helper();
let johnU = johnHelper.with_updated_collection;
let johnColls = johnHelper.collections;
do_test_pending();
let server;
- function weaveHandler (request, response) {
+ function weaveHandler(request, response) {
response.setStatusLine(request.httpVersion, 200, "OK");
let body = server.baseURI + "/api/";
response.bodyOutputStream.write(body, body.length);
}
server = httpd_setup({
"/api/1.1/johndoe/info/collections": login_handling(johnHelper.handler),
"/api/1.1/janedoe/info/collections": service_unavailable,
"/api/1.1/johndoe/storage/crypto/keys": johnU("crypto", new ServerWBO("keys").handler()),
- "/api/1.1/johndoe/storage/meta/global": johnU("meta", new ServerWBO("global").handler()),
+ "/api/1.1/johndoe/storage/meta/global": johnU("meta", new ServerWBO("global").handler()),
"/user/1.0/johndoe/node/weave": weaveHandler,
});
try {
Service.serverURL = server.baseURI;
_("Force the initial state.");
Service.status.service = STATUS_OK;
--- a/services/sync/tests/unit/test_service_wipeServer.js
+++ b/services/sync/tests/unit/test_service_wipeServer.js
@@ -9,17 +9,17 @@ Cu.import("resource://services-sync/serv
// configure the identity we use for this test.
const identityConfig = makeIdentityConfig({username: "johndoe"});
function FakeCollection() {
this.deleted = false;
}
FakeCollection.prototype = {
- handler: function() {
+ handler() {
let self = this;
return function(request, response) {
let body = "";
self.timestamp = new_timestamp();
let timestamp = "" + self.timestamp;
if (request.method == "DELETE") {
body = timestamp;
self.deleted = true;
@@ -100,17 +100,17 @@ add_identity_test(this, async function t
do_check_false(steam_coll.deleted);
do_check_false(diesel_coll.deleted);
_("wipeServer() will happily ignore the non-existent collection, delete the 'steam' collection and abort after an receiving an error on the 'petrol' collection.");
let error;
try {
Service.wipeServer(["non-existent", "steam", "petrol", "diesel"]);
do_throw("Should have thrown!");
- } catch(ex) {
+ } catch (ex) {
error = ex;
}
_("wipeServer() threw this exception: " + error);
do_check_eq(error.status, 503);
_("wipeServer stopped deleting after encountering an error with the 'petrol' collection, thus only 'steam' has been deleted.");
do_check_true(steam_coll.deleted);
do_check_false(diesel_coll.deleted);
--- a/services/sync/tests/unit/test_syncedtabs.js
+++ b/services/sync/tests/unit/test_syncedtabs.js
@@ -102,17 +102,17 @@ add_task(async function test_clientWithT
guid_mobile: {
clientName: "My Phone",
tabs: [],
}
});
let clients = await SyncedTabs.getTabClients();
equal(clients.length, 2);
- clients.sort((a, b) => { return a.name.localeCompare(b.name);});
+ clients.sort((a, b) => { return a.name.localeCompare(b.name); });
equal(clients[0].tabs.length, 1);
equal(clients[0].tabs[0].url, "http://foo.com/");
equal(clients[0].tabs[0].icon, "http://foo.com/favicon");
// second client has no tabs.
equal(clients[1].tabs.length, 0);
});
add_task(async function test_staleClientWithTabs() {
@@ -152,17 +152,17 @@ add_task(async function test_staleClient
}, {
guid_stale_mobile: false,
guid_stale_desktop: false,
// We should always use the device name from the clients collection, instead
// of the possibly stale tabs collection.
guid_stale_name_desktop: "My Laptop",
});
let clients = await SyncedTabs.getTabClients();
- clients.sort((a, b) => { return a.name.localeCompare(b.name);});
+ clients.sort((a, b) => { return a.name.localeCompare(b.name); });
equal(clients.length, 3);
equal(clients[0].name, "My Desktop");
equal(clients[0].tabs.length, 1);
equal(clients[0].tabs[0].url, "http://foo.com/");
equal(clients[1].name, "My Laptop");
equal(clients[1].tabs.length, 1);
equal(clients[1].tabs[0].url, "https://example.edu/");
equal(clients[2].name, "My Phone");
@@ -179,17 +179,17 @@ add_task(async function test_clientWithT
urlHistory: ["http://foo.com/"],
icon: "http://foo.com/favicon",
}],
},
});
let clients = await SyncedTabs.getTabClients();
equal(clients.length, 1);
- clients.sort((a, b) => { return a.name.localeCompare(b.name);});
+ clients.sort((a, b) => { return a.name.localeCompare(b.name); });
equal(clients[0].tabs.length, 1);
equal(clients[0].tabs[0].url, "http://foo.com/");
// expect the default favicon (empty string) due to the pref being false.
equal(clients[0].tabs[0].icon, "");
Services.prefs.clearUserPref("services.sync.syncedTabs.showRemoteIcons");
});
add_task(async function test_filter() {
--- a/services/sync/tests/unit/test_syncengine_sync.js
+++ b/services/sync/tests/unit/test_syncengine_sync.js
@@ -337,19 +337,19 @@ add_task(async function test_processInco
let engine = makeRotaryEngine();
engine._store.items = {newerserver: "New data, but not as new as server!",
olderidentical: "Older but identical",
updateclient: "Got data?",
original: "Original Entry",
long_original: "Long Original Entry",
nukeme: "Nuke me!"};
// Make this record 1 min old, thus older than the one on the server
- engine._tracker.addChangedID('newerserver', Date.now()/1000 - 60);
+ engine._tracker.addChangedID('newerserver', Date.now() / 1000 - 60);
// This record has been changed 2 mins later than the one on the server
- engine._tracker.addChangedID('olderidentical', Date.now()/1000);
+ engine._tracker.addChangedID('olderidentical', Date.now() / 1000);
let meta_global = Service.recordManager.set(engine.metaURL,
new WBORecord(engine.metaURL));
meta_global.payload.engines = {rotary: {version: engine.version,
syncID: engine.syncID}};
try {
@@ -609,28 +609,28 @@ add_task(async function test_processInco
Svc.Prefs.set("client.type", "mobile");
Service.identity.username = "foo";
// A collection that logs each GET
let collection = new ServerCollection();
collection.get_log = [];
collection._get = collection.get;
- collection.get = function (options) {
+ collection.get = function(options) {
this.get_log.push(options);
return this._get(options);
};
// Let's create some 234 server side records. They're all at least
// 10 minutes old.
for (let i = 0; i < 234; i++) {
let id = 'record-no-' + i;
- let payload = encryptPayload({id: id, denomination: "Record No. " + i});
+ let payload = encryptPayload({id, denomination: "Record No. " + i});
let wbo = new ServerWBO(id, payload);
- wbo.modified = Date.now()/1000 - 60*(i+10);
+ wbo.modified = Date.now() / 1000 - 60 * (i + 10);
collection.insertWBO(wbo);
}
let server = sync_httpd_setup({
"/1.1/foo/storage/rotary": collection.handler()
});
let syncTesting = await SyncTestingInfrastructure(server);
@@ -656,22 +656,22 @@ add_task(async function test_processInco
// kind of parameters were made.
do_check_eq(collection.get_log.length,
Math.ceil(234 / MOBILE_BATCH_SIZE) + 1);
do_check_eq(collection.get_log[0].full, 1);
do_check_eq(collection.get_log[0].limit, MOBILE_BATCH_SIZE);
do_check_eq(collection.get_log[1].full, undefined);
do_check_eq(collection.get_log[1].limit, undefined);
for (let i = 1; i <= Math.floor(234 / MOBILE_BATCH_SIZE); i++) {
- do_check_eq(collection.get_log[i+1].full, 1);
- do_check_eq(collection.get_log[i+1].limit, undefined);
+ do_check_eq(collection.get_log[i + 1].full, 1);
+ do_check_eq(collection.get_log[i + 1].limit, undefined);
if (i < Math.floor(234 / MOBILE_BATCH_SIZE))
- do_check_eq(collection.get_log[i+1].ids.length, MOBILE_BATCH_SIZE);
+ do_check_eq(collection.get_log[i + 1].ids.length, MOBILE_BATCH_SIZE);
else
- do_check_eq(collection.get_log[i+1].ids.length, 234 % MOBILE_BATCH_SIZE);
+ do_check_eq(collection.get_log[i + 1].ids.length, 234 % MOBILE_BATCH_SIZE);
}
} finally {
await cleanAndGo(engine, server);
}
});
@@ -690,19 +690,19 @@ add_task(async function test_processInco
throw "Abort on fourth call!";
}
return this._get.apply(this, arguments);
};
// Let's create three batches worth of server side records.
for (var i = 0; i < MOBILE_BATCH_SIZE * 3; i++) {
let id = 'record-no-' + i;
- let payload = encryptPayload({id: id, denomination: "Record No. " + id});
+ let payload = encryptPayload({id, denomination: "Record No. " + id});
let wbo = new ServerWBO(id, payload);
- wbo.modified = Date.now()/1000 + 60 * (i - MOBILE_BATCH_SIZE * 3);
+ wbo.modified = Date.now() / 1000 + 60 * (i - MOBILE_BATCH_SIZE * 3);
collection.insertWBO(wbo);
}
let engine = makeRotaryEngine();
engine.enabled = true;
let server = sync_httpd_setup({
"/1.1/foo/storage/rotary": collection.handler()
@@ -756,17 +756,17 @@ add_task(async function test_processInco
collection.insert('scotsman',
encryptPayload({id: 'scotsman',
denomination: "Flying Scotsman"}));
collection.insert('rekolok',
encryptPayload({id: 'rekolok',
denomination: "Rekonstruktionslokomotive"}));
for (let i = 0; i < 3; i++) {
let id = 'failed' + i;
- let payload = encryptPayload({id: id, denomination: "Record No. " + i});
+ let payload = encryptPayload({id, denomination: "Record No. " + i});
let wbo = new ServerWBO(id, payload);
wbo.modified = LASTSYNC - 10;
collection.insertWBO(wbo);
}
collection.wbo("flying").modified =
collection.wbo("scotsman").modified = LASTSYNC - 10;
collection._wbos.rekolok.modified = LASTSYNC + 10;
@@ -815,28 +815,28 @@ add_task(async function test_processInco
_("Ensure that a number of incoming items less than applyIncomingBatchSize is still applied.");
Service.identity.username = "foo";
// Engine that doesn't like the first and last record it's given.
const APPLY_BATCH_SIZE = 10;
let engine = makeRotaryEngine();
engine.applyIncomingBatchSize = APPLY_BATCH_SIZE;
engine._store._applyIncomingBatch = engine._store.applyIncomingBatch;
- engine._store.applyIncomingBatch = function (records) {
+ engine._store.applyIncomingBatch = function(records) {
let failed1 = records.shift();
let failed2 = records.pop();
this._applyIncomingBatch(records);
return [failed1.id, failed2.id];
};
// Let's create less than a batch worth of server side records.
let collection = new ServerCollection();
for (let i = 0; i < APPLY_BATCH_SIZE - 1; i++) {
let id = 'record-no-' + i;
- let payload = encryptPayload({id: id, denomination: "Record No. " + id});
+ let payload = encryptPayload({id, denomination: "Record No. " + id});
collection.insert(id, payload);
}
let server = sync_httpd_setup({
"/1.1/foo/storage/rotary": collection.handler()
});
let syncTesting = await SyncTestingInfrastructure(server);
@@ -872,27 +872,27 @@ add_task(async function test_processInco
const APPLY_BATCH_SIZE = 10;
// Engine that applies records in batches.
let engine = makeRotaryEngine();
engine.applyIncomingBatchSize = APPLY_BATCH_SIZE;
let batchCalls = 0;
engine._store._applyIncomingBatch = engine._store.applyIncomingBatch;
- engine._store.applyIncomingBatch = function (records) {
+ engine._store.applyIncomingBatch = function(records) {
batchCalls += 1;
do_check_eq(records.length, APPLY_BATCH_SIZE);
this._applyIncomingBatch.apply(this, arguments);
};
// Let's create three batches worth of server side records.
let collection = new ServerCollection();
for (let i = 0; i < APPLY_BATCH_SIZE * 3; i++) {
let id = 'record-no-' + i;
- let payload = encryptPayload({id: id, denomination: "Record No. " + id});
+ let payload = encryptPayload({id, denomination: "Record No. " + id});
collection.insert(id, payload);
}
let server = sync_httpd_setup({
"/1.1/foo/storage/rotary": collection.handler()
});
let syncTesting = await SyncTestingInfrastructure(server);
@@ -925,26 +925,26 @@ add_task(async function test_processInco
const APPLY_BATCH_SIZE = 5;
const NUMBER_OF_RECORDS = 15;
// Engine that fails the first record.
let engine = makeRotaryEngine();
engine.applyIncomingBatchSize = APPLY_BATCH_SIZE;
engine._store._applyIncomingBatch = engine._store.applyIncomingBatch;
- engine._store.applyIncomingBatch = function (records) {
+ engine._store.applyIncomingBatch = function(records) {
engine._store._applyIncomingBatch(records.slice(1));
return [records[0].id];
};
// Create a batch of server side records.
let collection = new ServerCollection();
for (var i = 0; i < NUMBER_OF_RECORDS; i++) {
let id = 'record-no-' + i;
- let payload = encryptPayload({id: id, denomination: "Record No. " + id});
+ let payload = encryptPayload({id, denomination: "Record No. " + id});
collection.insert(id, payload);
}
let server = sync_httpd_setup({
"/1.1/foo/storage/rotary": collection.handler()
});
let syncTesting = await SyncTestingInfrastructure(server);
@@ -1015,26 +1015,26 @@ add_task(async function test_processInco
const APPLY_BATCH_SIZE = 4;
const NUMBER_OF_RECORDS = 14;
// Engine that fails the first 2 records.
let engine = makeRotaryEngine();
engine.mobileGUIDFetchBatchSize = engine.applyIncomingBatchSize = APPLY_BATCH_SIZE;
engine._store._applyIncomingBatch = engine._store.applyIncomingBatch;
- engine._store.applyIncomingBatch = function (records) {
+ engine._store.applyIncomingBatch = function(records) {
engine._store._applyIncomingBatch(records.slice(2));
return [records[0].id, records[1].id];
};
// Create a batch of server side records.
let collection = new ServerCollection();
for (var i = 0; i < NUMBER_OF_RECORDS; i++) {
let id = 'record-no-' + i;
- let payload = encryptPayload({id: id, denomination: "Record No. " + i});
+ let payload = encryptPayload({id, denomination: "Record No. " + i});
collection.insert(id, payload);
}
let server = sync_httpd_setup({
"/1.1/foo/storage/rotary": collection.handler()
});
let syncTesting = await SyncTestingInfrastructure(server);
@@ -1098,19 +1098,19 @@ add_task(async function test_processInco
_("Ensure that failed records from _reconcile and applyIncomingBatch are refetched.");
Service.identity.username = "foo";
// Let's create three and a bit batches worth of server side records.
let collection = new ServerCollection();
const NUMBER_OF_RECORDS = MOBILE_BATCH_SIZE * 3 + 5;
for (let i = 0; i < NUMBER_OF_RECORDS; i++) {
let id = 'record-no-' + i;
- let payload = encryptPayload({id: id, denomination: "Record No. " + id});
+ let payload = encryptPayload({id, denomination: "Record No. " + id});
let wbo = new ServerWBO(id, payload);
- wbo.modified = Date.now()/1000 + 60 * (i - MOBILE_BATCH_SIZE * 3);
+ wbo.modified = Date.now() / 1000 + 60 * (i - MOBILE_BATCH_SIZE * 3);
collection.insertWBO(wbo);
}
// Engine that batches but likes to throw on a couple of records,
// two in each batch: the even ones fail in reconcile, the odd ones
// in applyIncoming.
const BOGUS_RECORDS = ["record-no-" + 42,
"record-no-" + 23,
@@ -1126,17 +1126,17 @@ add_task(async function test_processInco
engine.__reconcile = engine._reconcile;
engine._reconcile = function _reconcile(record) {
if (BOGUS_RECORDS.indexOf(record.id) % 2 == 0) {
throw "I don't like this record! Baaaaaah!";
}
return this.__reconcile.apply(this, arguments);
};
engine._store._applyIncoming = engine._store.applyIncoming;
- engine._store.applyIncoming = function (record) {
+ engine._store.applyIncoming = function(record) {
if (BOGUS_RECORDS.indexOf(record.id) % 2 == 1) {
throw "I don't like this record! Baaaaaah!";
}
return this._applyIncoming.apply(this, arguments);
};
// Keep track of requests made of a collection.
let count = 0;
@@ -1244,17 +1244,17 @@ add_task(async function test_processInco
collection._wbos.scotsman = new ServerWBO(
'scotsman', encryptPayload({id: 'scotsman',
denomination: "Flying Scotsman"}));
collection._wbos.nodecrypt = new ServerWBO("nodecrypt", "Decrypt this!");
collection._wbos.nodecrypt2 = new ServerWBO("nodecrypt2", "Decrypt this!");
// Patch the fake crypto service to throw on the record above.
Svc.Crypto._decrypt = Svc.Crypto.decrypt;
- Svc.Crypto.decrypt = function (ciphertext) {
+ Svc.Crypto.decrypt = function(ciphertext) {
if (ciphertext == "Decrypt this!") {
throw "Derp! Cipher finalized failed. Im ur crypto destroyin ur recordz.";
}
return this._decrypt.apply(this, arguments);
};
// Some broken records also exist locally.
let engine = makeRotaryEngine();
@@ -1534,32 +1534,32 @@ add_task(async function test_uploadOutgo
engine._uploadOutgoing();
// Ensure all records have been uploaded.
for (i = 0; i < 234; i++) {
do_check_true(!!collection.payload('record-no-' + i));
}
// Ensure that the uploads were performed in batches of MAX_UPLOAD_RECORDS.
- do_check_eq(noOfUploads, Math.ceil(234/MAX_UPLOAD_RECORDS));
+ do_check_eq(noOfUploads, Math.ceil(234 / MAX_UPLOAD_RECORDS));
} finally {
await cleanAndGo(engine, server);
}
});
add_task(async function test_uploadOutgoing_largeRecords() {
_("SyncEngine._uploadOutgoing throws on records larger than MAX_UPLOAD_BYTES");
Service.identity.username = "foo";
let collection = new ServerCollection();
let engine = makeRotaryEngine();
engine.allowSkippedRecord = false;
- engine._store.items["large-item"] = "Y".repeat(MAX_UPLOAD_BYTES*2);
+ engine._store.items["large-item"] = "Y".repeat(MAX_UPLOAD_BYTES * 2);
engine._tracker.addChangedID("large-item", 0);
collection.insert("large-item");
let meta_global = Service.recordManager.set(engine.metaURL,
new WBORecord(engine.metaURL));
meta_global.payload.engines = {rotary: {version: engine.version,
syncID: engine.syncID}};
@@ -1656,17 +1656,17 @@ add_task(async function test_syncFinish_
return orig.apply(this, arguments);
};
}(collection.delete));
// Create a bunch of records on the server
let now = Date.now();
for (var i = 0; i < 234; i++) {
let id = 'record-no-' + i;
- let payload = encryptPayload({id: id, denomination: "Record No. " + i});
+ let payload = encryptPayload({id, denomination: "Record No. " + i});
let wbo = new ServerWBO(id, payload);
wbo.modified = now / 1000 - 60 * (i + 110);
collection.insertWBO(wbo);
}
let server = httpd_setup({
"/1.1/foo/storage/rotary": collection.handler()
});
@@ -1848,17 +1848,17 @@ add_task(async function test_syncapplied
const NUMBER_OF_RECORDS = 10;
let engine = makeRotaryEngine();
// Create a batch of server side records.
let collection = new ServerCollection();
for (var i = 0; i < NUMBER_OF_RECORDS; i++) {
let id = 'record-no-' + i;
- let payload = encryptPayload({id: id, denomination: "Record No. " + id});
+ let payload = encryptPayload({id, denomination: "Record No. " + id});
collection.insert(id, payload);
}
let server = httpd_setup({
"/1.1/foo/storage/rotary": collection.handler()
});
let syncTesting = await SyncTestingInfrastructure(server);
--- a/services/sync/tests/unit/test_syncscheduler.js
+++ b/services/sync/tests/unit/test_syncscheduler.js
@@ -203,23 +203,23 @@ add_identity_test(this, async function t
Svc.Obs.add("weave:service:login:error", function onLoginError() {
Svc.Obs.remove("weave:service:login:error", onLoginError);
loginFailed = true;
});
let rescheduleInterval = false;
let oldScheduleAtInterval = SyncScheduler.prototype.scheduleAtInterval;
- SyncScheduler.prototype.scheduleAtInterval = function (interval) {
+ SyncScheduler.prototype.scheduleAtInterval = function(interval) {
rescheduleInterval = true;
do_check_eq(interval, MASTER_PASSWORD_LOCKED_RETRY_INTERVAL);
};
let oldVerifyLogin = Service.verifyLogin;
- Service.verifyLogin = function () {
+ Service.verifyLogin = function() {
Status.login = MASTER_PASSWORD_LOCKED;
return false;
};
let server = sync_httpd_setup();
await setUp(server);
Service.sync();
--- a/services/sync/tests/unit/test_syncstoragerequest.js
+++ b/services/sync/tests/unit/test_syncstoragerequest.js
@@ -45,33 +45,33 @@ add_test(function test_user_agent_mobile
Svc.Prefs.set("client.type", "mobile");
let expectedUA = Services.appinfo.name + "/" + Services.appinfo.version +
" (" + httpProtocolHandler.oscpu + ")" +
" FxSync/" + WEAVE_VERSION + "." +
Services.appinfo.appBuildID + ".mobile";
let request = new SyncStorageRequest(server.baseURI + "/resource");
- request.get(function (error) {
+ request.get(function(error) {
do_check_eq(error, null);
do_check_eq(this.response.status, 200);
do_check_eq(handler.request.getHeader("User-Agent"), expectedUA);
Svc.Prefs.resetBranch("");
server.stop(run_next_test);
});
});
add_test(function test_auth() {
let handler = httpd_handler(200, "OK");
let server = httpd_setup({"/resource": handler});
setBasicCredentials("johndoe", "ilovejane", "XXXXXXXXX");
let request = Service.getStorageRequest(server.baseURI + "/resource");
- request.get(function (error) {
+ request.get(function(error) {
do_check_eq(error, null);
do_check_eq(this.response.status, 200);
do_check_true(basic_auth_matches(handler.request, "johndoe", "ilovejane"));
Svc.Prefs.reset("");
server.stop(run_next_test);
});
@@ -85,17 +85,17 @@ add_test(function test_weave_timestamp()
function handler(request, response) {
response.setHeader("X-Weave-Timestamp", "" + TIMESTAMP, false);
response.setStatusLine(request.httpVersion, 200, "OK");
}
let server = httpd_setup({"/resource": handler});
do_check_eq(SyncStorageRequest.serverTime, undefined);
let request = new SyncStorageRequest(server.baseURI + "/resource");
- request.get(function (error) {
+ request.get(function(error) {
do_check_eq(error, null);
do_check_eq(this.response.status, 200);
do_check_eq(SyncStorageRequest.serverTime, TIMESTAMP);
delete SyncStorageRequest.serverTime;
server.stop(run_next_test);
});
});
@@ -111,17 +111,17 @@ add_test(function test_weave_backoff() {
let backoffInterval;
Svc.Obs.add("weave:service:backoff:interval", function onBackoff(subject) {
Svc.Obs.remove("weave:service:backoff:interval", onBackoff);
backoffInterval = subject;
});
let request = new SyncStorageRequest(server.baseURI + "/resource");
- request.get(function (error) {
+ request.get(function(error) {
do_check_eq(error, null);
do_check_eq(this.response.status, 200);
do_check_eq(backoffInterval, 600);
server.stop(run_next_test);
});
});
/**
@@ -136,17 +136,17 @@ add_test(function test_weave_quota_notic
let quotaValue;
Svc.Obs.add("weave:service:quota:remaining", function onQuota(subject) {
Svc.Obs.remove("weave:service:quota:remaining", onQuota);
quotaValue = subject;
});
let request = new SyncStorageRequest(server.baseURI + "/resource");
- request.get(function (error) {
+ request.get(function(error) {
do_check_eq(error, null);
do_check_eq(this.response.status, 200);
do_check_eq(quotaValue, 1048576);
server.stop(run_next_test);
});
});
/**
@@ -161,17 +161,17 @@ add_test(function test_weave_quota_error
let quotaValue;
function onQuota(subject) {
quotaValue = subject;
}
Svc.Obs.add("weave:service:quota:remaining", onQuota);
let request = new SyncStorageRequest(server.baseURI + "/resource");
- request.get(function (error) {
+ request.get(function(error) {
do_check_eq(error, null);
do_check_eq(this.response.status, 400);
do_check_eq(quotaValue, undefined);
Svc.Obs.remove("weave:service:quota:remaining", onQuota);
server.stop(run_next_test);
});
});
@@ -182,38 +182,38 @@ add_test(function test_abort() {
response.setHeader("X-Weave-Backoff", '600', false);
response.setStatusLine(request.httpVersion, 200, "OK");
}
let server = httpd_setup({"/resource": handler});
let request = new SyncStorageRequest(server.baseURI + "/resource");
// Aborting a request that hasn't been sent yet is pointless and will throw.
- do_check_throws(function () {
+ do_check_throws(function() {
request.abort();
});
function throwy() {
do_throw("Shouldn't have gotten here!");
}
Svc.Obs.add("weave:service:backoff:interval", throwy);
Svc.Obs.add("weave:service:quota:remaining", throwy);
request.onProgress = request.onComplete = throwy;
request.get();
request.abort();
do_check_eq(request.status, request.ABORTED);
// Aborting an already aborted request is pointless and will throw.
- do_check_throws(function () {
+ do_check_throws(function() {
request.abort();
});
- Utils.nextTick(function () {
+ Utils.nextTick(function() {
// Verify that we didn't try to process any of the values.
do_check_eq(SyncStorageRequest.serverTime, undefined);
Svc.Obs.remove("weave:service:backoff:interval", throwy);
Svc.Obs.remove("weave:service:quota:remaining", throwy);
server.stop(run_next_test);
});
--- a/services/sync/tests/unit/test_tab_engine.js
+++ b/services/sync/tests/unit/test_tab_engine.js
@@ -51,17 +51,17 @@ add_test(function test_getOpenURLs() {
add_task(async function test_tab_engine_skips_incoming_local_record() {
_("Ensure incoming records that match local client ID are never applied.");
let [engine, store] = getMocks();
let localID = engine.service.clientsEngine.localID;
let apply = store.applyIncoming;
let applied = [];
- store.applyIncoming = function (record) {
+ store.applyIncoming = function(record) {
notEqual(record.id, localID, "Only apply tab records from remote clients");
applied.push(record);
apply.call(store, record);
}
let collection = new ServerCollection();
_("Creating remote tab record with local client ID");
@@ -85,17 +85,17 @@ add_task(async function test_tab_engine_
new WBORecord(engine.metaURL));
meta_global.payload.engines = {tabs: {version: engine.version,
syncID: engine.syncID}};
generateNewKeys(Service.collectionKeys);
let promiseFinished = new Promise(resolve => {
let syncFinish = engine._syncFinish;
- engine._syncFinish = function () {
+ engine._syncFinish = function() {
equal(applied.length, 1, "Remote client record was applied");
equal(applied[0].id, remoteID, "Remote client ID matches");
syncFinish.call(engine);
resolve();
}
});
--- a/services/sync/tests/unit/test_tab_store.js
+++ b/services/sync/tests/unit/test_tab_store.js
@@ -90,17 +90,17 @@ function test_createRecord() {
let record;
store.getTabState = mockGetTabState;
store.shouldSkipWindow = mockShouldSkipWindow;
store.getWindowEnumerator = mockGetWindowEnumerator.bind(this, "http://foo.com", 1, 1);
let tabs = store.getAllTabs();
let tabsize = JSON.stringify(tabs[0]).length;
- let numtabs = Math.ceil(20000./77.);
+ let numtabs = Math.ceil(20000. / 77.);
store.getWindowEnumerator = mockGetWindowEnumerator.bind(this, "http://foo.com", 1, 1);
record = store.createRecord("fake-guid");
ok(record instanceof TabSetRecord);
equal(record.tabs.length, 1);
_("create a big record");
store.getWindowEnumerator = mockGetWindowEnumerator.bind(this, "http://foo.com", 1, numtabs);
--- a/services/sync/tests/unit/test_tab_tracker.js
+++ b/services/sync/tests/unit/test_tab_tracker.js
@@ -7,30 +7,30 @@ Cu.import("resource://services-sync/util
var clientsEngine = Service.clientsEngine;
function fakeSvcWinMediator() {
// actions on windows are captured in logs
let logs = [];
delete Services.wm;
Services.wm = {
- getEnumerator: function() {
+ getEnumerator() {
return {
cnt: 2,
- hasMoreElements: function() {
+ hasMoreElements() {
return this.cnt-- > 0;
},
- getNext: function() {
+ getNext() {
let elt = {addTopics: [], remTopics: [], numAPL: 0, numRPL: 0};
logs.push(elt);
return {
- addEventListener: function(topic) {
+ addEventListener(topic) {
elt.addTopics.push(topic);
},
- removeEventListener: function(topic) {
+ removeEventListener(topic) {
elt.remTopics.push(topic);
},
gBrowser: {
addProgressListener() {
elt.numAPL++;
},
removeProgressListener() {
elt.numRPL++;
@@ -91,17 +91,17 @@ function run_test() {
_("Test tab listener");
for (let evttype of ["TabOpen", "TabClose", "TabSelect"]) {
// Pretend we just synced.
tracker.clearChangedIDs();
do_check_false(tracker.modified);
// Send a fake tab event
- tracker.onTab({type: evttype , originalTarget: evttype});
+ tracker.onTab({type: evttype, originalTarget: evttype});
do_check_true(tracker.modified);
do_check_true(Utils.deepEquals(Object.keys(engine.getChangedIDs()),
[clientsEngine.localID]));
}
// Pretend we just synced.
tracker.clearChangedIDs();
do_check_false(tracker.modified);
--- a/services/sync/tests/unit/test_telemetry.js
+++ b/services/sync/tests/unit/test_telemetry.js
@@ -72,17 +72,17 @@ Service.engineManager.unregister("addons
add_identity_test(this, async function test_basic() {
let helper = track_collections_helper();
let upd = helper.with_updated_collection;
await configureIdentity({ username: "johndoe" });
let handlers = {
"/1.1/johndoe/info/collections": helper.handler,
"/1.1/johndoe/storage/crypto/keys": upd("crypto", new ServerWBO("keys").handler()),
- "/1.1/johndoe/storage/meta/global": upd("meta", new ServerWBO("global").handler())
+ "/1.1/johndoe/storage/meta/global": upd("meta", new ServerWBO("global").handler())
};
let collections = ["clients", "bookmarks", "forms", "history", "passwords", "prefs", "tabs"];
for (let coll of collections) {
handlers["/1.1/johndoe/storage/" + coll] = upd(coll, new ServerCollection({}, true).handler());
}
@@ -118,17 +118,17 @@ add_task(async function test_processInco
engine.toFetch = [BOGUS_GUID];
let error, pingPayload, fullPing;
try {
await sync_engine_and_validate_telem(engine, true, (errPing, fullErrPing) => {
pingPayload = errPing;
fullPing = fullErrPing;
});
- } catch(ex) {
+ } catch (ex) {
error = ex;
}
ok(!!error);
ok(!!pingPayload);
equal(fullPing.uid, "f".repeat(32)); // as setup by SyncTestingInfrastructure
deepEqual(pingPayload.failureReason, {
name: "othererror",
@@ -480,17 +480,17 @@ add_identity_test(this, async function t
let oldSubmit = telem.submit;
let server;
try {
let handlers = {
"/1.1/johndoe/info/collections": helper.handler,
"/1.1/johndoe/storage/crypto/keys": upd("crypto", new ServerWBO("keys").handler()),
- "/1.1/johndoe/storage/meta/global": upd("meta", new ServerWBO("global").handler())
+ "/1.1/johndoe/storage/meta/global": upd("meta", new ServerWBO("global").handler())
};
let collections = ["clients", "bookmarks", "forms", "history", "passwords", "prefs", "tabs"];
for (let coll of collections) {
handlers["/1.1/johndoe/storage/" + coll] = upd(coll, new ServerCollection({}, true).handler());
}
--- a/services/sync/tests/unit/test_utils_catch.js
+++ b/services/sync/tests/unit/test_utils_catch.js
@@ -2,55 +2,55 @@ Cu.import("resource://services-sync/util
Cu.import("resource://services-sync/service.js");
function run_test() {
_("Make sure catch when copied to an object will correctly catch stuff");
let ret, rightThis, didCall, didThrow, wasTen, wasLocked;
let obj = {
catch: Utils.catch,
_log: {
- debug: function(str) {
+ debug(str) {
didThrow = str.search(/^Exception/) == 0;
},
- info: function(str) {
+ info(str) {
wasLocked = str.indexOf("Cannot start sync: already syncing?") == 0;
}
},
- func: function() {
+ func() {
return this.catch(function() {
rightThis = this == obj;
didCall = true;
return 5;
})();
},
- throwy: function() {
+ throwy() {
return this.catch(function() {
rightThis = this == obj;
didCall = true;
throw 10;
})();
},
- callbacky: function() {
+ callbacky() {
return this.catch(function() {
rightThis = this == obj;
didCall = true;
throw 10;
}, function(ex) {
wasTen = (ex == 10)
})();
},
- lockedy: function() {
+ lockedy() {
return this.catch(function() {
rightThis = this == obj;
didCall = true;
- throw("Could not acquire lock.");
+ throw ("Could not acquire lock.");
})();
}
};
_("Make sure a normal call will call and return");
rightThis = didCall = didThrow = wasLocked = false;
ret = obj.func();
do_check_eq(ret, 5);
--- a/services/sync/tests/unit/test_utils_json.js
+++ b/services/sync/tests/unit/test_utils_json.js
@@ -61,18 +61,18 @@ add_test(function test_nonexistent_file(
do_check_eq(val, undefined);
run_next_test();
}));
});
add_test(function test_save_logging() {
_("Verify that writes are logged.");
let trace;
- Utils.jsonSave("log", {_log: {trace: function(msg) { trace = msg; }}},
- "hi", ensureThrows(function () {
+ Utils.jsonSave("log", {_log: {trace(msg) { trace = msg; }}},
+ "hi", ensureThrows(function() {
do_check_true(!!trace);
run_next_test();
}));
});
add_test(function test_load_logging() {
_("Verify that reads and read errors are logged.");
@@ -88,20 +88,20 @@ add_test(function test_load_logging() {
.createInstance(Ci.nsIConverterOutputStream);
stream.init(fos, "UTF-8", 4096, 0x0000);
stream.writeString("invalid json!");
stream.close();
let trace, debug;
let obj = {
_log: {
- trace: function(msg) {
+ trace(msg) {
trace = msg;
},
- debug: function(msg) {
+ debug(msg) {
debug = msg;
}
}
};
Utils.jsonLoad("log", obj, ensureThrows(function(val) {
do_check_true(!val);
do_check_true(!!trace);
do_check_true(!!debug);
--- a/services/sync/tests/unit/test_utils_lock.js
+++ b/services/sync/tests/unit/test_utils_lock.js
@@ -8,40 +8,40 @@ function do_check_begins(thing, startsWi
do_throw(thing + " doesn't begin with " + startsWith);
}
function run_test() {
let ret, rightThis, didCall;
let state, lockState, lockedState, unlockState;
let obj = {
_lock: Utils.lock,
- lock: function() {
+ lock() {
lockState = ++state;
if (this._locked) {
lockedState = ++state;
return false;
}
this._locked = true;
return true;
},
- unlock: function() {
+ unlock() {
unlockState = ++state;
this._locked = false;
},
- func: function() {
+ func() {
return this._lock("Test utils lock",
function() {
rightThis = this == obj;
didCall = true;
return 5;
})();
},
- throwy: function() {
+ throwy() {
return this._lock("Test utils lock throwy",
function() {
rightThis = this == obj;
didCall = true;
this.throwy();
})();
}
};
@@ -58,18 +58,17 @@ function run_test() {
do_check_eq(state, 2);
_("Make sure code that calls locked code throws");
ret = null;
rightThis = didCall = false;
try {
ret = obj.throwy();
do_throw("throwy internal call should have thrown!");
- }
- catch(ex) {
+ } catch (ex) {
// Should throw an Error, not a string.
do_check_begins(ex, "Could not acquire lock");
}
do_check_eq(ret, null);
do_check_true(rightThis);
do_check_true(didCall);
_("Lock should be called twice so state 3 is skipped");
do_check_eq(lockState, 4);
--- a/services/sync/tests/unit/test_utils_notify.js
+++ b/services/sync/tests/unit/test_utils_notify.js
@@ -1,40 +1,40 @@
_("Make sure notify sends out the right notifications");
Cu.import("resource://services-sync/util.js");
function run_test() {
let ret, rightThis, didCall;
let obj = {
notify: Utils.notify("foo:"),
_log: {
- trace: function() {}
+ trace() {}
},
- func: function() {
+ func() {
return this.notify("bar", "baz", function() {
rightThis = this == obj;
didCall = true;
return 5;
})();
},
- throwy: function() {
+ throwy() {
return this.notify("bad", "one", function() {
rightThis = this == obj;
didCall = true;
throw 10;
})();
}
};
let state = 0;
let makeObs = function(topic) {
let obj = {
- observe: function(subject, topic, data) {
+ observe(subject, topic, data) {
this.state = ++state;
this.subject = subject;
this.topic = topic;
this.data = data;
}
};
Svc.Obs.add(topic, obj);
@@ -70,18 +70,17 @@ function run_test() {
ret = null;
rightThis = didCall = false;
let ts = makeObs("foo:bad:start");
let tf = makeObs("foo:bad:finish");
let te = makeObs("foo:bad:error");
try {
ret = obj.throwy();
do_throw("throwy should have thrown!");
- }
- catch(ex) {
+ } catch (ex) {
do_check_eq(ex, 10);
}
do_check_eq(ret, null);
do_check_true(rightThis);
do_check_true(didCall);
do_check_eq(ts.state, 3);
do_check_eq(ts.subject, undefined);
--- a/services/sync/tests/unit/test_warn_on_truncated_response.js
+++ b/services/sync/tests/unit/test_warn_on_truncated_response.js
@@ -23,17 +23,17 @@ function contentHandler(request, respons
response.setHeader("Content-Type", "text/plain");
response.setStatusLine(request.httpVersion, 200, "OK");
response.bodyOutputStream.write(BODY, contentLength);
}
function getWarningMessages(log) {
let warnMessages = [];
let warn = log.warn;
- log.warn = function (message) {
+ log.warn = function(message) {
let regEx = /The response body\'s length of: \d+ doesn\'t match the header\'s content-length of: \d+/i
if (message.match(regEx)) {
warnMessages.push(message);
}
warn.call(log, message);
}
return warnMessages;
}
@@ -55,17 +55,17 @@ add_test(function test_resource_logs_con
add_test(function test_async_resource_logs_content_length_mismatch() {
_("Issuing request.");
let httpServer = httpd_setup({"/content": contentHandler});
let asyncResource = new AsyncResource(httpServer.baseURI + "/content");
let warnMessages = getWarningMessages(asyncResource._log);
- asyncResource.get(function (error, content) {
+ asyncResource.get(function(error, content) {
equal(error, null);
equal(content, BODY);
notEqual(warnMessages.length, 0, "test that warning was logged");
notEqual(content.length, contentLength);
httpServer.stop(run_next_test);
});
});
@@ -80,16 +80,16 @@ add_test(function test_sync_storage_requ
// nsIConverterInputStream is used and the data read from channel's stream
// isn't truncated at the null byte mark (\u0000). Therefore the
// content-length mismatch being tested for doesn't occur. Setting it to
// a falsy value results in an nsIScriptableInputStream being used to read
// the stream, which stops reading at the null byte mark resulting in a
// content-length mismatch.
request.charset = "";
- request.get(function (error) {
+ request.get(function(error) {
equal(error, null);
equal(this.response.body, BODY);
notEqual(warnMessages.length, 0, "test that a warning was logged");
notEqual(BODY.length, contentLength);
httpServer.stop(run_next_test);
});
});
--- a/services/sync/tps/extensions/tps/components/tps-cmdline.js
+++ b/services/sync/tps/extensions/tps/components/tps-cmdline.js
@@ -64,39 +64,39 @@ TPSCmdLineHandler.prototype = {
ios.manageOfflineStatus = false;
ios.offline = false;
Components.utils.import("resource://tps/tps.jsm");
Components.utils.import("resource://tps/quit.js", TPS);
let uri = cmdLine.resolveURI(uristr).spec;
TPS.RunTestPhase(uri, phase, logfile, options);
- //cmdLine.preventDefault = true;
+ // cmdLine.preventDefault = true;
},
helpInfo : " --tps <file> Run TPS tests with the given test file.\n" +
" --tpsphase <phase> Run the specified phase in the TPS test.\n" +
" --tpslogfile <file> Logfile for TPS output.\n" +
" --ignore-unused-engines Don't load engines not used in tests.\n",
};
var TPSCmdLineFactory = {
- createInstance : function(outer, iid) {
+ createInstance(outer, iid) {
if (outer != null) {
throw new Error(Components.results.NS_ERROR_NO_AGGREGATION);
}
return new TPSCmdLineHandler().QueryInterface(iid);
}
};
var TPSCmdLineModule = {
- registerSelf : function(compMgr, fileSpec, location, type) {
+ registerSelf(compMgr, fileSpec, location, type) {
compMgr = compMgr.QueryInterface(nsIComponentRegistrar);
compMgr.registerFactoryLocation(TPS_CMDLINE_CLSID,
"TPS CommandLine Service",
TPS_CMDLINE_CONTRACTID,
fileSpec,
location,
type);
@@ -105,40 +105,40 @@ var TPSCmdLineModule = {
catman.addCategoryEntry("command-line-argument-handlers",
"TPS command line handler",
TPS_CMDLINE_CONTRACTID, true, true);
catman.addCategoryEntry("command-line-handler",
"m-tps",
TPS_CMDLINE_CONTRACTID, true, true);
},
- unregisterSelf : function(compMgr, fileSpec, location) {
+ unregisterSelf(compMgr, fileSpec, location) {
compMgr = compMgr.QueryInterface(nsIComponentRegistrar);
compMgr.unregisterFactoryLocation(TPS_CMDLINE_CLSID, fileSpec);
catman = Components.classes[CATMAN_CONTRACTID].getService(nsICategoryManager);
catman.deleteCategoryEntry("command-line-argument-handlers",
"TPS command line handler", true);
catman.deleteCategoryEntry("command-line-handler",
"m-tps", true);
},
- getClassObject : function(compMgr, cid, iid) {
+ getClassObject(compMgr, cid, iid) {
if (cid.equals(TPS_CMDLINE_CLSID)) {
return TPSCmdLineFactory;
}
if (!iid.equals(Components.interfaces.nsIFactory)) {
throw new Error(Components.results.NS_ERROR_NOT_IMPLEMENTED);
}
throw new Error(Components.results.NS_ERROR_NO_INTERFACE);
},
- canUnload : function(compMgr) {
+ canUnload(compMgr) {
return true;
}
};
/**
* XPCOMUtils.generateNSGetFactory was introduced in Mozilla 2 (Firefox 4).
* XPCOMUtils.generateNSGetModule is for Mozilla 1.9.2 (Firefox 3.6).
*/
--- a/services/sync/tps/extensions/tps/resource/logger.jsm
+++ b/services/sync/tps/extensions/tps/resource/logger.jsm
@@ -11,28 +11,27 @@ var EXPORTED_SYMBOLS = ["Logger"];
const {classes: Cc, interfaces: Ci, utils: Cu} = Components;
var Logger = {
_foStream: null,
_converter: null,
_potentialError: null,
- init: function (path) {
+ init(path) {
if (this._converter != null) {
// we're already open!
return;
}
let prefs = Cc["@mozilla.org/preferences-service;1"]
.getService(Ci.nsIPrefBranch);
if (path) {
prefs.setCharPref("tps.logfile", path);
- }
- else {
+ } else {
path = prefs.getCharPref("tps.logfile");
}
this._file = Cc["@mozilla.org/file/local;1"]
.createInstance(Ci.nsILocalFile);
this._file.initWithPath(path);
var exists = this._file.exists();
@@ -43,106 +42,105 @@ var Logger = {
var fileflags = exists ? 0x02 | 0x08 | 0x10 : 0x02 | 0x08 | 0x20;
this._foStream.init(this._file, fileflags, 0666, 0);
this._converter = Cc["@mozilla.org/intl/converter-output-stream;1"]
.createInstance(Ci.nsIConverterOutputStream);
this._converter.init(this._foStream, "UTF-8", 0, 0);
},
- write: function (data) {
+ write(data) {
if (this._converter == null) {
Cu.reportError(
"TPS Logger.write called with _converter == null!");
return;
}
this._converter.writeString(data);
},
- close: function () {
+ close() {
if (this._converter != null) {
this._converter.close();
this._converter = null;
this._foStream = null;
}
},
- AssertTrue: function(bool, msg, showPotentialError) {
+ AssertTrue(bool, msg, showPotentialError) {
if (bool) {
return;
}
if (showPotentialError && this._potentialError) {
msg += "; " + this._potentialError;
this._potentialError = null;
}
throw new Error("ASSERTION FAILED! " + msg);
},
- AssertFalse: function(bool, msg, showPotentialError) {
+ AssertFalse(bool, msg, showPotentialError) {
return this.AssertTrue(!bool, msg, showPotentialError);
},
- AssertEqual: function(val1, val2, msg) {
+ AssertEqual(val1, val2, msg) {
if (val1 != val2)
throw new Error("ASSERTION FAILED! " + msg + "; expected " +
JSON.stringify(val2) + ", got " + JSON.stringify(val1));
},
- log: function (msg, withoutPrefix) {
+ log(msg, withoutPrefix) {
dump(msg + "\n");
if (withoutPrefix) {
this.write(msg + "\n");
- }
- else {
+ } else {
function pad(n, len) {
let s = "0000" + n;
return s.slice(-len);
}
let now = new Date();
- let year = pad(now.getFullYear(), 4);
- let month = pad(now.getMonth() + 1, 2);
- let day = pad(now.getDate(), 2);
- let hour = pad(now.getHours(), 2);
- let minutes = pad(now.getMinutes(), 2);
- let seconds = pad(now.getSeconds(), 2);
+ let year = pad(now.getFullYear(), 4);
+ let month = pad(now.getMonth() + 1, 2);
+ let day = pad(now.getDate(), 2);
+ let hour = pad(now.getHours(), 2);
+ let minutes = pad(now.getMinutes(), 2);
+ let seconds = pad(now.getSeconds(), 2);
let ms = pad(now.getMilliseconds(), 3);
this.write(year + "-" + month + "-" + day + " " +
hour + ":" + minutes + ":" + seconds + "." + ms + " " +
msg + "\n");
}
},
- clearPotentialError: function() {
+ clearPotentialError() {
this._potentialError = null;
},
- logPotentialError: function(msg) {
+ logPotentialError(msg) {
this._potentialError = msg;
},
- logLastPotentialError: function(msg) {
+ logLastPotentialError(msg) {
var message = msg;
if (this._potentialError) {
message = this._poentialError;
this._potentialError = null;
}
this.log("CROSSWEAVE ERROR: " + message);
},
- logError: function (msg) {
+ logError(msg) {
this.log("CROSSWEAVE ERROR: " + msg);
},
- logInfo: function (msg, withoutPrefix) {
+ logInfo(msg, withoutPrefix) {
if (withoutPrefix)
this.log(msg, true);
else
this.log("CROSSWEAVE INFO: " + msg);
},
- logPass: function (msg) {
+ logPass(msg) {
this.log("CROSSWEAVE TEST PASS: " + msg);
},
};
--- a/services/sync/tps/extensions/tps/resource/modules/bookmarks.jsm
+++ b/services/sync/tps/extensions/tps/resource/modules/bookmarks.jsm
@@ -29,18 +29,17 @@ var DumpBookmarks = function TPS_Bookmar
cb(error);
});
cb.wait();
};
/**
* extend, causes a child object to inherit from a parent
*/
-function extend(child, supertype)
-{
+function extend(child, supertype) {
child.prototype.__proto__ = supertype.prototype;
}
/**
* PlacesItemProps object, holds properties for places items
*/
function PlacesItemProps(props) {
this.location = null;
@@ -88,17 +87,17 @@ PlacesItem.prototype = {
_bookmarkFolders: {
"places": "placesRoot",
"menu": "bookmarksMenuFolder",
"tags": "tagFolder",
"unfiled": "unfiledBookmarksFolder",
"toolbar": "toolbarFolder",
},
- toString: function() {
+ toString() {
var that = this;
var props = ['uri', 'title', 'location', 'folder', 'feedUri', 'siteUri', 'livemark'];
var string = (this.props.type ? this.props.type + " " : "") +
"(" +
(function() {
var ret = [];
for (var i in props) {
if (that.props[props[i]]) {
@@ -125,27 +124,27 @@ PlacesItem.prototype = {
* @param type The type of the item to find, or null to match any item;
* this is one of the values listed at
* https://developer.mozilla.org/en/nsINavHistoryResultNode#Constants
* @param title The title of the item to find, or null to match any title
* @param uri The uri of the item to find, or null to match any uri
*
* @return the node id if the item was found, otherwise -1
*/
- GetPlacesNodeId: function (folder, type, title, uri) {
+ GetPlacesNodeId(folder, type, title, uri) {
let node_id = -1;
let options = PlacesUtils.history.getNewQueryOptions();
let query = PlacesUtils.history.getNewQuery();
query.setFolders([folder], 1);
let result = PlacesUtils.history.executeQuery(query, options);
let rootNode = result.root;
rootNode.containerOpen = true;
- for (let j = 0; j < rootNode.childCount; j ++) {
+ for (let j = 0; j < rootNode.childCount; j++) {
let node = rootNode.getChild(j);
if (node.title == title) {
if (type == null || type == undefined || node.type == type)
if (uri == undefined || uri == null || node.uri.spec == uri.spec)
node_id = node.itemId;
}
}
rootNode.containerOpen = false;
@@ -161,17 +160,17 @@ PlacesItem.prototype = {
* @param itemName The name of the other object; this may be any kind of
* places item
* @param relativePos The relative position of the other object. If -1,
* it means the other object should precede this one, if +1,
* the other object should come after this one
* @return true if this object is immediately adjacent to the other object,
* otherwise false
*/
- IsAdjacentTo: function(itemName, relativePos) {
+ IsAdjacentTo(itemName, relativePos) {
Logger.AssertTrue(this.props.folder_id != -1 && this.props.item_id != -1,
"Either folder_id or item_id was invalid");
let other_id = this.GetPlacesNodeId(this.props.folder_id, null, itemName);
Logger.AssertTrue(other_id != -1, "item " + itemName + " not found");
let other_pos = PlacesUtils.bookmarks.getItemIndex(other_id);
let this_pos = PlacesUtils.bookmarks.getItemIndex(this.props.item_id);
if (other_pos + relativePos != this_pos) {
Logger.logPotentialError("Invalid position - " +
@@ -185,93 +184,91 @@ PlacesItem.prototype = {
/**
* GetItemIndex
*
* Gets the item index for this places item.
*
* @return the item index, or -1 if there's an error
*/
- GetItemIndex: function() {
+ GetItemIndex() {
if (this.props.item_id == -1)
return -1;
return PlacesUtils.bookmarks.getItemIndex(this.props.item_id);
},
/**
* GetFolder
*
* Gets the folder id for the specified bookmark folder
*
* @param location The full path of the folder, which must begin
* with one of the bookmark root folders
* @return the folder id if the folder is found, otherwise -1
*/
- GetFolder: function(location) {
+ GetFolder(location) {
let folder_parts = location.split("/");
if (!(folder_parts[0] in this._bookmarkFolders)) {
return -1;
}
let folder_id = PlacesUtils.bookmarks[this._bookmarkFolders[folder_parts[0]]];
for (let i = 1; i < folder_parts.length; i++) {
let subfolder_id = this.GetPlacesNodeId(
folder_id,
Ci.nsINavHistoryResultNode.RESULT_TYPE_FOLDER,
folder_parts[i]);
if (subfolder_id == -1) {
return -1;
- }
- else {
+ } else {
folder_id = subfolder_id;
}
}
return folder_id;
},
/**
* CreateFolder
*
* Creates a bookmark folder.
*
* @param location The full path of the folder, which must begin
* with one of the bookmark root folders
* @return the folder id if the folder was created, otherwise -1
*/
- CreateFolder: function(location) {
+ CreateFolder(location) {
let folder_parts = location.split("/");
if (!(folder_parts[0] in this._bookmarkFolders)) {
return -1;
}
let folder_id = PlacesUtils.bookmarks[this._bookmarkFolders[folder_parts[0]]];
for (let i = 1; i < folder_parts.length; i++) {
let subfolder_id = this.GetPlacesNodeId(
folder_id,
Ci.nsINavHistoryResultNode.RESULT_TYPE_FOLDER,
folder_parts[i]);
if (subfolder_id == -1) {
folder_id = PlacesUtils.bookmarks.createFolder(folder_id,
folder_parts[i], -1);
- }
- else {
+ } else {
folder_id = subfolder_id;
}
}
return folder_id;
},
/**
* GetOrCreateFolder
*
* Locates the specified folder; if not found it is created.
*
* @param location The full path of the folder, which must begin
* with one of the bookmark root folders
* @return the folder id if the folder was found or created, otherwise -1
*/
- GetOrCreateFolder: function(location) {
+ GetOrCreateFolder(location) {
folder_id = this.GetFolder(location);
if (folder_id == -1)
folder_id = this.CreateFolder(location);
return folder_id;
},
/**
* CheckDescription
@@ -279,17 +276,17 @@ PlacesItem.prototype = {
* Compares the description of this places item with an expected
* description.
*
* @param expectedDescription The description this places item is
* expected to have
* @return true if the actual and expected descriptions match, or if
* there is no expected description; otherwise false
*/
- CheckDescription: function(expectedDescription) {
+ CheckDescription(expectedDescription) {
if (expectedDescription != null) {
let description = "";
if (PlacesUtils.annotations.itemHasAnnotation(this.props.item_id,
"bookmarkProperties/description")) {
description = PlacesUtils.annotations.getItemAnnotation(
this.props.item_id, "bookmarkProperties/description");
}
if (description != expectedDescription) {
@@ -310,17 +307,17 @@ PlacesItem.prototype = {
* @param before The name of the places item that this item should be
before, or null if this check should be skipped
* @param after The name of the places item that this item should be
after, or null if this check should be skipped
* @param last_item_pos The index of the places item above this one,
* or null if this check should be skipped
* @return true if this item is in the correct position, otherwise false
*/
- CheckPosition: function(before, after, last_item_pos) {
+ CheckPosition(before, after, last_item_pos) {
if (after)
if (!this.IsAdjacentTo(after, 1)) return false;
if (before)
if (!this.IsAdjacentTo(before, -1)) return false;
if (last_item_pos != null && last_item_pos > -1) {
if (this.GetItemIndex() != last_item_pos + 1) {
Logger.logPotentialError("Item not found at the expected index, got " +
this.GetItemIndex() + ", expected " + (last_item_pos + 1) + " for " +
@@ -336,17 +333,17 @@ PlacesItem.prototype = {
*
* Moves this places item to a different folder.
*
* @param location The full path of the folder to which to move this
* places item, which must begin with one of the bookmark root
* folders; if null, no changes are made
* @return nothing if successful, otherwise an exception is thrown
*/
- SetLocation: function(location) {
+ SetLocation(location) {
if (location != null) {
let newfolder_id = this.GetOrCreateFolder(location);
Logger.AssertTrue(newfolder_id != -1, "Location " + location +
" doesn't exist; can't change item's location");
PlacesUtils.bookmarks.moveItem(this.props.item_id, newfolder_id, -1);
this.props.folder_id = newfolder_id;
}
},
@@ -355,17 +352,17 @@ PlacesItem.prototype = {
* SetDescription
*
* Updates the description for this places item.
*
* @param description The new description to set; if null, no changes are
* made
* @return nothing
*/
- SetDescription: function(description) {
+ SetDescription(description) {
if (description != null) {
if (description != "")
PlacesUtils.annotations.setItemAnnotation(this.props.item_id,
"bookmarkProperties/description",
description,
0,
PlacesUtils.annotations.EXPIRE_NEVER);
else
@@ -380,17 +377,17 @@ PlacesItem.prototype = {
* Updates the position of this places item within this item's current
* folder. Use SetLocation to change folders.
*
* @param position The new index this item should be moved to; if null,
* no changes are made; if -1, this item is moved to the bottom of
* the current folder
* @return nothing if successful, otherwise an exception is thrown
*/
- SetPosition: function(position) {
+ SetPosition(position) {
if (position != null) {
let newposition = -1;
if (position != -1) {
newposition = this.GetPlacesNodeId(this.props.folder_id,
null, position);
Logger.AssertTrue(newposition != -1, "position " + position +
" is invalid; unable to change position");
newposition = PlacesUtils.bookmarks.getItemIndex(newposition);
@@ -402,17 +399,17 @@ PlacesItem.prototype = {
/**
* Update the title of this places item
*
* @param title The new title to set for this item; if null, no changes
* are made
* @return nothing
*/
- SetTitle: function(title) {
+ SetTitle(title) {
if (title != null) {
PlacesUtils.bookmarks.setItemTitle(this.props.item_id, title);
}
},
};
/**
* Bookmark class constructor. Initializes instance properties.
@@ -432,43 +429,43 @@ Bookmark.prototype = {
* SetKeyword
*
* Update this bookmark's keyword.
*
* @param keyword The keyword to set for this bookmark; if null, no
* changes are made
* @return nothing
*/
- SetKeyword: function(keyword) {
+ SetKeyword(keyword) {
if (keyword != null) {
// Mirror logic from PlacesSyncUtils's updateBookmarkMetadata
let entry = Async.promiseSpinningly(PlacesUtils.keywords.fetch({
url: this.props.uri,
}));
if (entry) {
Async.promiseSpinningly(PlacesUtils.keywords.remove(entry));
}
Async.promiseSpinningly(PlacesUtils.keywords.insert({
- keyword: keyword,
+ keyword,
url: this.props.uri
}));
}
},
/**
* SetLoadInSidebar
*
* Updates this bookmark's loadInSidebar property.
*
* @param loadInSidebar if true, the loadInSidebar property will be set,
* if false, it will be cleared, and any other value will result
* in no change
* @return nothing
*/
- SetLoadInSidebar: function(loadInSidebar) {
+ SetLoadInSidebar(loadInSidebar) {
if (loadInSidebar == true)
PlacesUtils.annotations.setItemAnnotation(this.props.item_id,
"bookmarkProperties/loadInSidebar",
true,
0,
PlacesUtils.annotations.EXPIRE_NEVER);
else if (loadInSidebar == false)
PlacesUtils.annotations.removeItemAnnotation(this.props.item_id,
@@ -479,31 +476,31 @@ Bookmark.prototype = {
* SetTitle
*
* Updates this bookmark's title.
*
* @param title The new title to set for this boomark; if null, no changes
* are made
* @return nothing
*/
- SetTitle: function(title) {
+ SetTitle(title) {
if (title)
PlacesUtils.bookmarks.setItemTitle(this.props.item_id, title);
},
/**
* SetUri
*
* Updates this bookmark's URI.
*
* @param uri The new URI to set for this boomark; if null, no changes
* are made
* @return nothing
*/
- SetUri: function(uri) {
+ SetUri(uri) {
if (uri) {
let newURI = Services.io.newURI(uri);
PlacesUtils.bookmarks.changeBookmarkURI(this.props.item_id, newURI);
}
},
/**
* SetTags
@@ -511,33 +508,33 @@ Bookmark.prototype = {
* Updates this bookmark's tags.
*
* @param tags An array of tags which should be associated with this
* bookmark; any previous tags are removed; if this param is null,
* no changes are made. If this param is an empty array, all
* tags are removed from this bookmark.
* @return nothing
*/
- SetTags: function(tags) {
+ SetTags(tags) {
if (tags != null) {
let URI = Services.io.newURI(this.props.uri);
PlacesUtils.tagging.untagURI(URI, null);
if (tags.length > 0)
PlacesUtils.tagging.tagURI(URI, tags);
}
},
/**
* Create
*
* Creates the bookmark described by this object's properties.
*
* @return the id of the created bookmark
*/
- Create: function() {
+ Create() {
this.props.folder_id = this.GetOrCreateFolder(this.props.location);
Logger.AssertTrue(this.props.folder_id != -1, "Unable to create " +
"bookmark, error creating folder " + this.props.location);
let bookmarkURI = Services.io.newURI(this.props.uri);
this.props.item_id = PlacesUtils.bookmarks.insertBookmark(this.props.folder_id,
bookmarkURI,
-1,
this.props.title);
@@ -551,17 +548,17 @@ Bookmark.prototype = {
/**
* Update
*
* Updates this bookmark's properties according the properties on this
* object's 'updateProps' property.
*
* @return nothing
*/
- Update: function() {
+ Update() {
Logger.AssertTrue(this.props.item_id != -1 && this.props.item_id != null,
"Invalid item_id during Remove");
this.SetDescription(this.updateProps.description);
this.SetLoadInSidebar(this.updateProps.loadInSidebar);
this.SetTitle(this.updateProps.title);
this.SetUri(this.updateProps.uri);
this.SetKeyword(this.updateProps.keyword);
this.SetTags(this.updateProps.tags);
@@ -571,17 +568,17 @@ Bookmark.prototype = {
/**
* Find
*
* Locates the bookmark which corresponds to this object's properties.
*
* @return the bookmark id if the bookmark was found, otherwise -1
*/
- Find: function() {
+ Find() {
this.props.folder_id = this.GetFolder(this.props.location);
if (this.props.folder_id == -1) {
Logger.logError("Unable to find folder " + this.props.location);
return -1;
}
let bookmarkTitle = this.props.title;
this.props.item_id = this.GetPlacesNodeId(this.props.folder_id,
null,
@@ -625,18 +622,17 @@ Bookmark.prototype = {
tags.sort();
this.props.tags.sort();
if (JSON.stringify(tags) != JSON.stringify(this.props.tags)) {
Logger.logPotentialError("Wrong tags - expected: " +
JSON.stringify(this.props.tags) + ", actual: " +
JSON.stringify(tags) + " for " + this.toString());
return -1;
}
- }
- catch (e) {
+ } catch (e) {
Logger.logPotentialError("error processing tags " + e);
return -1;
}
}
if (!this.CheckPosition(this.props.before,
this.props.after,
this.props.last_item_pos))
return -1;
@@ -646,17 +642,17 @@ Bookmark.prototype = {
/**
* Remove
*
* Removes this bookmark. The bookmark should have been located previously
* by a call to Find.
*
* @return nothing
*/
- Remove: function() {
+ Remove() {
Logger.AssertTrue(this.props.item_id != -1 && this.props.item_id != null,
"Invalid item_id during Remove");
PlacesUtils.bookmarks.removeItem(this.props.item_id);
},
};
extend(Bookmark, PlacesItem);
@@ -674,17 +670,17 @@ function BookmarkFolder(props) {
BookmarkFolder.prototype = {
/**
* Create
*
* Creates the bookmark folder described by this object's properties.
*
* @return the id of the created bookmark folder
*/
- Create: function() {
+ Create() {
this.props.folder_id = this.GetOrCreateFolder(this.props.location);
Logger.AssertTrue(this.props.folder_id != -1, "Unable to create " +
"folder, error creating parent folder " + this.props.location);
this.props.item_id = PlacesUtils.bookmarks.createFolder(this.props.folder_id,
this.props.folder,
-1);
this.SetDescription(this.props.description);
return this.props.folder_id;
@@ -693,17 +689,17 @@ BookmarkFolder.prototype = {
/**
* Find
*
* Locates the bookmark folder which corresponds to this object's
* properties.
*
* @return the folder id if the folder was found, otherwise -1
*/
- Find: function() {
+ Find() {
this.props.folder_id = this.GetFolder(this.props.location);
if (this.props.folder_id == -1) {
Logger.logError("Unable to find folder " + this.props.location);
return -1;
}
this.props.item_id = this.GetPlacesNodeId(
this.props.folder_id,
Ci.nsINavHistoryResultNode.RESULT_TYPE_FOLDER,
@@ -720,32 +716,32 @@ BookmarkFolder.prototype = {
/**
* Remove
*
* Removes this folder. The folder should have been located previously
* by a call to Find.
*
* @return nothing
*/
- Remove: function() {
+ Remove() {
Logger.AssertTrue(this.props.item_id != -1 && this.props.item_id != null,
"Invalid item_id during Remove");
PlacesUtils.bookmarks.removeFolderChildren(this.props.item_id);
PlacesUtils.bookmarks.removeItem(this.props.item_id);
},
/**
* Update
*
* Updates this bookmark's properties according the properties on this
* object's 'updateProps' property.
*
* @return nothing
*/
- Update: function() {
+ Update() {
Logger.AssertTrue(this.props.item_id != -1 && this.props.item_id != null,
"Invalid item_id during Update");
this.SetLocation(this.updateProps.location);
this.SetPosition(this.updateProps.position);
this.SetTitle(this.updateProps.folder);
this.SetDescription(this.updateProps.description);
},
};
@@ -766,26 +762,26 @@ function Livemark(props) {
Livemark.prototype = {
/**
* Create
*
* Creates the livemark described by this object's properties.
*
* @return the id of the created livemark
*/
- Create: function() {
+ Create() {
this.props.folder_id = this.GetOrCreateFolder(this.props.location);
Logger.AssertTrue(this.props.folder_id != -1, "Unable to create " +
"folder, error creating parent folder " + this.props.location);
let siteURI = null;
if (this.props.siteUri != null)
siteURI = Services.io.newURI(this.props.siteUri);
let livemarkObj = {parentId: this.props.folder_id,
title: this.props.livemark,
- siteURI: siteURI,
+ siteURI,
feedURI: Services.io.newURI(this.props.feedUri),
index: PlacesUtils.bookmarks.DEFAULT_INDEX};
// Until this can handle asynchronous creation, we need to spin.
let spinningCb = Async.makeSpinningCallback();
PlacesUtils.livemarks.addLivemark(livemarkObj).then(
aLivemark => { spinningCb(null, [Components.results.NS_OK, aLivemark]) },
@@ -804,17 +800,17 @@ Livemark.prototype = {
/**
* Find
*
* Locates the livemark which corresponds to this object's
* properties.
*
* @return the item id if the livemark was found, otherwise -1
*/
- Find: function() {
+ Find() {
this.props.folder_id = this.GetFolder(this.props.location);
if (this.props.folder_id == -1) {
Logger.logError("Unable to find folder " + this.props.location);
return -1;
}
this.props.item_id = this.GetPlacesNodeId(
this.props.folder_id,
Ci.nsINavHistoryResultNode.RESULT_TYPE_FOLDER,
@@ -858,34 +854,34 @@ Livemark.prototype = {
/**
* Update
*
* Updates this livemark's properties according the properties on this
* object's 'updateProps' property.
*
* @return nothing
*/
- Update: function() {
+ Update() {
Logger.AssertTrue(this.props.item_id != -1 && this.props.item_id != null,
"Invalid item_id during Update");
this.SetLocation(this.updateProps.location);
this.SetPosition(this.updateProps.position);
this.SetTitle(this.updateProps.livemark);
return true;
},
/**
* Remove
*
* Removes this livemark. The livemark should have been located previously
* by a call to Find.
*
* @return nothing
*/
- Remove: function() {
+ Remove() {
Logger.AssertTrue(this.props.item_id != -1 && this.props.item_id != null,
"Invalid item_id during Remove");
PlacesUtils.bookmarks.removeItem(this.props.item_id);
},
};
extend(Livemark, PlacesItem);
@@ -903,34 +899,34 @@ function Separator(props) {
Separator.prototype = {
/**
* Create
*
* Creates the bookmark separator described by this object's properties.
*
* @return the id of the created separator
*/
- Create: function () {
+ Create() {
this.props.folder_id = this.GetOrCreateFolder(this.props.location);
Logger.AssertTrue(this.props.folder_id != -1, "Unable to create " +
"folder, error creating parent folder " + this.props.location);
this.props.item_id = PlacesUtils.bookmarks.insertSeparator(this.props.folder_id,
-1);
return this.props.item_id;
},
/**
* Find
*
* Locates the bookmark separator which corresponds to this object's
* properties.
*
* @return the item id if the separator was found, otherwise -1
*/
- Find: function () {
+ Find() {
this.props.folder_id = this.GetFolder(this.props.location);
if (this.props.folder_id == -1) {
Logger.logError("Unable to find folder " + this.props.location);
return -1;
}
if (this.props.before == null && this.props.last_item_pos == null) {
Logger.logPotentialError("Separator requires 'before' attribute if it's the" +
"first item in the list");
@@ -942,60 +938,56 @@ Separator.prototype = {
null,
this.props.before);
if (other_id == -1) {
Logger.logPotentialError("Can't find places item " + this.props.before +
" for locating separator");
return -1;
}
expected_pos = PlacesUtils.bookmarks.getItemIndex(other_id) - 1;
- }
- else {
+ } else {
expected_pos = this.props.last_item_pos + 1;
}
this.props.item_id = PlacesUtils.bookmarks.getIdForItemAt(this.props.folder_id,
expected_pos);
if (this.props.item_id == -1) {
Logger.logPotentialError("No separator found at position " + expected_pos);
- }
- else {
- if (PlacesUtils.bookmarks.getItemType(this.props.item_id) !=
+ } else if (PlacesUtils.bookmarks.getItemType(this.props.item_id) !=
PlacesUtils.bookmarks.TYPE_SEPARATOR) {
Logger.logPotentialError("Places item at position " + expected_pos +
" is not a separator");
return -1;
}
- }
return this.props.item_id;
},
/**
* Update
*
* Updates this separator's properties according the properties on this
* object's 'updateProps' property.
*
* @return nothing
*/
- Update: function() {
+ Update() {
Logger.AssertTrue(this.props.item_id != -1 && this.props.item_id != null,
"Invalid item_id during Update");
this.SetLocation(this.updateProps.location);
this.SetPosition(this.updateProps.position);
return true;
},
/**
* Remove
*
* Removes this separator. The separator should have been located
* previously by a call to Find.
*
* @return nothing
*/
- Remove: function() {
+ Remove() {
Logger.AssertTrue(this.props.item_id != -1 && this.props.item_id != null,
"Invalid item_id during Update");
PlacesUtils.bookmarks.removeItem(this.props.item_id);
},
};
extend(Separator, PlacesItem);
--- a/services/sync/tps/extensions/tps/resource/modules/forms.jsm
+++ b/services/sync/tps/extensions/tps/resource/modules/forms.jsm
@@ -141,29 +141,29 @@ FormData.prototype = {
* hours_to_us
*
* Converts hours since present to microseconds since epoch.
*
* @param hours The number of hours since the present time (e.g., 0 is
* 'now', and -1 is 1 hour ago)
* @return the corresponding number of microseconds since the epoch
*/
- hours_to_us: function(hours) {
+ hours_to_us(hours) {
return this.usSinceEpoch + (hours * 60 * 60 * 1000 * 1000);
},
/**
* Create
*
* If this FormData object doesn't exist in the moz_formhistory database,
* add it. Throws on error.
*
* @return nothing
*/
- Create: function() {
+ Create() {
Logger.AssertTrue(this.fieldname != null && this.value != null,
"Must specify both fieldname and value");
return FormDB.getDataForValue(this.fieldname, this.value).then(formdata => {
if (!formdata) {
// this item doesn't exist yet in the db, so we need to insert it
return FormDB.insertValue(this.fieldname, this.value,
this.hours_to_us(this.date));
@@ -179,17 +179,17 @@ FormData.prototype = {
/**
* Find
*
* Attempts to locate an entry in the moz_formhistory database that
* matches the fieldname and value for this FormData object.
*
* @return true if this entry exists in the database, otherwise false
*/
- Find: function() {
+ Find() {
return FormDB.getDataForValue(this.fieldname, this.value).then(formdata => {
let status = formdata != null;
if (status) {
/*
//form history dates currently not synced! bug 552531
let us = this.hours_to_us(this.date);
status = Logger.AssertTrue(
us >= formdata.firstUsed && us <= formdata.lastUsed,
@@ -206,14 +206,14 @@ FormData.prototype = {
/**
* Remove
*
* Removes the row represented by this FormData instance from the
* moz_formhistory database.
*
* @return nothing
*/
- Remove: function() {
+ Remove() {
/* Right now Weave doesn't handle this correctly, see bug 568363.
*/
return FormDB.remove(this.id);
},
};
--- a/services/sync/tps/extensions/tps/resource/modules/history.jsm
+++ b/services/sync/tps/extensions/tps/resource/modules/history.jsm
@@ -96,23 +96,23 @@ var HistoryEntry = {
*
* Adds visits for a uri to the history database. Throws on error.
*
* @param item An object representing one or more visits to a specific uri
* @param usSinceEpoch The number of microseconds from Epoch to
* the time the current Crossweave run was started
* @return nothing
*/
- Add: function(item, usSinceEpoch) {
+ Add(item, usSinceEpoch) {
Logger.AssertTrue("visits" in item && "uri" in item,
"History entry in test file must have both 'visits' " +
"and 'uri' properties");
let uri = Services.io.newURI(item.uri);
let place = {
- uri: uri,
+ uri,
visits: []
};
for (let visit of item.visits) {
place.visits.push({
visitDate: usSinceEpoch + (visit.date * 60 * 60 * 1000 * 1000),
transitionType: visit.type
});
}
@@ -140,17 +140,17 @@ var HistoryEntry = {
*
* Finds visits for a uri to the history database. Throws on error.
*
* @param item An object representing one or more visits to a specific uri
* @param usSinceEpoch The number of microseconds from Epoch to
* the time the current Crossweave run was started
* @return true if all the visits for the uri are found, otherwise false
*/
- Find: function(item, usSinceEpoch) {
+ Find(item, usSinceEpoch) {
Logger.AssertTrue("visits" in item && "uri" in item,
"History entry in test file must have both 'visits' " +
"and 'uri' properties");
let curvisits = this._getVisits(item.uri);
for (let visit of curvisits) {
for (let itemvisit of item.visits) {
let expectedDate = itemvisit.date * 60 * 60 * 1000 * 1000
+ usSinceEpoch;
@@ -175,33 +175,30 @@ var HistoryEntry = {
*
* Removes visits from the history database. Throws on error.
*
* @param item An object representing items to delete
* @param usSinceEpoch The number of microseconds from Epoch to
* the time the current Crossweave run was started
* @return nothing
*/
- Delete: function(item, usSinceEpoch) {
+ Delete(item, usSinceEpoch) {
if ("uri" in item) {
let uri = Services.io.newURI(item.uri);
PlacesUtils.history.removePage(uri);
- }
- else if ("host" in item) {
+ } else if ("host" in item) {
PlacesUtils.history.removePagesFromHost(item.host, false);
- }
- else if ("begin" in item && "end" in item) {
+ } else if ("begin" in item && "end" in item) {
let cb = Async.makeSpinningCallback();
let msSinceEpoch = parseInt(usSinceEpoch / 1000);
let filter = {
beginDate: new Date(msSinceEpoch + (item.begin * 60 * 60 * 1000)),
endDate: new Date(msSinceEpoch + (item.end * 60 * 60 * 1000))
};
PlacesUtils.history.removeVisitsByFilter(filter)
.catch(ex => Logger.AssertTrue(false, "An error occurred while deleting history: " + ex))
- .then(result => {cb(null, result)}, err => {cb(err)});
+ .then(result => { cb(null, result) }, err => { cb(err) });
Async.waitForSyncCallback(cb);
- }
- else {
+ } else {
Logger.AssertTrue(false, "invalid entry in delete history");
}
},
};
--- a/services/sync/tps/extensions/tps/resource/modules/passwords.jsm
+++ b/services/sync/tps/extensions/tps/resource/modules/passwords.jsm
@@ -55,35 +55,34 @@ function PasswordProps(props) {
*/
function Password(props) {
this.props = new PasswordProps(props);
if ("changes" in props) {
this.updateProps = new PasswordProps(props);
for (var prop in props.changes)
if (prop in this.updateProps)
this.updateProps[prop] = props.changes[prop];
- }
- else {
+ } else {
this.updateProps = null;
}
}
/**
* Password instance methods.
*/
Password.prototype = {
/**
* Create
*
* Adds a password entry to the login manager for the password
* represented by this object's properties. Throws on error.
*
* @return the new login guid
*/
- Create: function() {
+ Create() {
let login = new nsLoginInfo(this.props.hostname, this.props.submitURL,
this.props.realm, this.props.username,
this.props.password,
this.props.usernameField,
this.props.passwordField);
Services.logins.addLogin(login);
login.QueryInterface(Ci.nsILoginMetaInfo);
return login.guid;
@@ -92,17 +91,17 @@ Password.prototype = {
/**
* Find
*
* Finds a password entry in the login manager, for the password
* represented by this object's properties.
*
* @return the guid of the password if found, otherwise -1
*/
- Find: function() {
+ Find() {
let logins = Services.logins.findLogins({},
this.props.hostname,
this.props.submitURL,
this.props.realm);
for (var i = 0; i < logins.length; i++) {
if (logins[i].username == this.props.username &&
logins[i].password == this.props.password &&
logins[i].usernameField == this.props.usernameField &&
@@ -119,17 +118,17 @@ Password.prototype = {
*
* Updates an existing password entry in the login manager with
* new properties. Throws on error. The 'old' properties are this
* object's properties, the 'new' properties are the properties in
* this object's 'updateProps' object.
*
* @return nothing
*/
- Update: function() {
+ Update() {
let oldlogin = new nsLoginInfo(this.props.hostname,
this.props.submitURL,
this.props.realm,
this.props.username,
this.props.password,
this.props.usernameField,
this.props.passwordField);
let newlogin = new nsLoginInfo(this.updateProps.hostname,
@@ -145,17 +144,17 @@ Password.prototype = {
/**
* Remove
*
* Removes an entry from the login manager for a password which
* matches this object's properties. Throws on error.
*
* @return nothing
*/
- Remove: function() {
+ Remove() {
let login = new nsLoginInfo(this.props.hostname,
this.props.submitURL,
this.props.realm,
this.props.username,
this.props.password,
this.props.usernameField,
this.props.passwordField);
Services.logins.removeLogin(login);
--- a/services/sync/tps/extensions/tps/resource/modules/prefs.jsm
+++ b/services/sync/tps/extensions/tps/resource/modules/prefs.jsm
@@ -18,17 +18,17 @@ var prefs = Cc["@mozilla.org/preferences
Cu.import("resource://tps/logger.jsm");
/**
* Preference class constructor
*
* Initializes instance properties.
*/
-function Preference (props) {
+function Preference(props) {
Logger.AssertTrue("name" in props && "value" in props,
"Preference must have both name and value");
this.name = props.name;
this.value = props.value;
}
/**
@@ -38,25 +38,24 @@ Preference.prototype = {
/**
* Modify
*
* Sets the value of the preference this.name to this.value.
* Throws on error.
*
* @return nothing
*/
- Modify: function() {
+ Modify() {
// Determine if this pref is actually something Weave even looks at.
let weavepref = WEAVE_PREF_PREFIX + this.name;
try {
let syncPref = prefs.getBoolPref(weavepref);
if (!syncPref)
prefs.setBoolPref(weavepref, true);
- }
- catch(e) {
+ } catch (e) {
Logger.AssertTrue(false, "Weave doesn't sync pref " + this.name);
}
// Modify the pref; throw an exception if the pref type is different
// than the value type specified in the test.
let prefType = prefs.getPrefType(this.name);
switch (prefType) {
case Ci.nsIPrefBranch.PREF_INT:
@@ -81,34 +80,33 @@ Preference.prototype = {
* Find
*
* Verifies that the preference this.name has the value
* this.value. Throws on error, or if the pref's type or value
* doesn't match.
*
* @return nothing
*/
- Find: function() {
+ Find() {
// Read the pref value.
let value;
try {
let prefType = prefs.getPrefType(this.name);
- switch(prefType) {
+ switch (prefType) {
case Ci.nsIPrefBranch.PREF_INT:
value = prefs.getIntPref(this.name);
break;
case Ci.nsIPrefBranch.PREF_STRING:
value = prefs.getCharPref(this.name);
break;
case Ci.nsIPrefBranch.PREF_BOOL:
value = prefs.getBoolPref(this.name);
break;
}
- }
- catch (e) {
+ } catch (e) {
Logger.AssertTrue(false, "Error accessing pref " + this.name);
}
// Throw an exception if the current and expected values aren't of
// the same type, or don't have the same values.
Logger.AssertEqual(typeof(value), typeof(this.value),
"Value types don't match");
Logger.AssertEqual(value, this.value, "Preference values don't match");
--- a/services/sync/tps/extensions/tps/resource/modules/tabs.jsm
+++ b/services/sync/tps/extensions/tps/resource/modules/tabs.jsm
@@ -18,17 +18,17 @@ var BrowserTabs = {
* Add
*
* Opens a new tab in the current browser window for the
* given uri. Throws on error.
*
* @param uri The uri to load in the new tab
* @return nothing
*/
- Add: function(uri, fn) {
+ Add(uri, fn) {
// Open the uri in a new tab in the current browser window, and calls
// the callback fn from the tab's onload handler.
let wm = Cc["@mozilla.org/appshell/window-mediator;1"]
.getService(Ci.nsIWindowMediator);
let mainWindow = wm.getMostRecentWindow("navigator:browser");
let newtab = mainWindow.getBrowser().addTab(uri);
mainWindow.getBrowser().selectedTab = newtab;
let win = mainWindow.getBrowser().getBrowserForTab(newtab);
@@ -41,17 +41,17 @@ var BrowserTabs = {
* Finds the specified uri and title in Weave's list of remote tabs
* for the specified profile.
*
* @param uri The uri of the tab to find
* @param title The page title of the tab to find
* @param profile The profile to search for tabs
* @return true if the specified tab could be found, otherwise false
*/
- Find: function(uri, title, profile) {
+ Find(uri, title, profile) {
// Find the uri in Weave's list of tabs for the given profile.
let engine = Weave.Service.engineManager.get("tabs");
for (let [guid, client] of Object.entries(engine.getAllClients())) {
if (!client.tabs) {
continue;
}
for (let key in client.tabs) {
let tab = client.tabs[key];
--- a/services/sync/tps/extensions/tps/resource/modules/windows.jsm
+++ b/services/sync/tps/extensions/tps/resource/modules/windows.jsm
@@ -18,17 +18,17 @@ var BrowserWindows = {
/**
* Add
*
* Opens a new window. Throws on error.
*
* @param aPrivate The private option.
* @return nothing
*/
- Add: function(aPrivate, fn) {
+ Add(aPrivate, fn) {
let wm = Cc["@mozilla.org/appshell/window-mediator;1"]
.getService(Ci.nsIWindowMediator);
let mainWindow = wm.getMostRecentWindow("navigator:browser");
let win = mainWindow.OpenBrowserWindow({private: aPrivate});
win.addEventListener("load", function onLoad() {
win.removeEventListener("load", onLoad, false);
fn.call(win);
}, false);
--- a/services/sync/tps/extensions/tps/resource/quit.js
+++ b/services/sync/tps/extensions/tps/resource/quit.js
@@ -16,48 +16,44 @@ function canQuitApplication() {
var cancelQuit = Components.classes["@mozilla.org/supports-PRBool;1"]
.createInstance(Components.interfaces.nsISupportsPRBool);
Services.obs.notifyObservers(cancelQuit, "quit-application-requested", null);
// Something aborted the quit process.
if (cancelQuit.data) {
return false;
}
- }
- catch (ex) {}
+ } catch (ex) {}
return true;
}
function goQuitApplication() {
if (!canQuitApplication()) {
return false;
}
const kAppStartup = '@mozilla.org/toolkit/app-startup;1';
const kAppShell = '@mozilla.org/appshell/appShellService;1';
- var appService;
- var forceQuit;
+ var appService;
+ var forceQuit;
if (kAppStartup in Components.classes) {
appService = Components.classes[kAppStartup]
.getService(Components.interfaces.nsIAppStartup);
forceQuit = Components.interfaces.nsIAppStartup.eForceQuit;
- }
- else if (kAppShell in Components.classes) {
+ } else if (kAppShell in Components.classes) {
appService = Components.classes[kAppShell].
getService(Components.interfaces.nsIAppShellService);
forceQuit = Components.interfaces.nsIAppShellService.eForceQuit;
- }
- else {
+ } else {
throw new Error('goQuitApplication: no AppStartup/appShell');
}
try {
appService.quit(forceQuit);
- }
- catch(ex) {
+ } catch (ex) {
throw new Error('goQuitApplication: ' + ex);
}
return true;
}
--- a/services/sync/tps/extensions/tps/resource/tps.jsm
+++ b/services/sync/tps/extensions/tps/resource/tps.jsm
@@ -132,27 +132,26 @@ var TPS = {
// Check if Firefox Accounts is enabled
let service = Cc["@mozilla.org/weave/service;1"]
.getService(Components.interfaces.nsISupports)
.wrappedJSObject;
this.fxaccounts_enabled = service.fxAccountsEnabled;
this.delayAutoSync();
- OBSERVER_TOPICS.forEach(function (aTopic) {
+ OBSERVER_TOPICS.forEach(function(aTopic) {
Services.obs.addObserver(this, aTopic, true);
}, this);
// Configure some logging prefs for Sync itself.
Weave.Svc.Prefs.set("log.appender.dump", "Debug");
// Import the appropriate authentication module
if (this.fxaccounts_enabled) {
Cu.import("resource://tps/auth/fxaccounts.jsm", module);
- }
- else {
+ } else {
Cu.import("resource://tps/auth/sync.jsm", module);
}
},
DumpError(msg, exc = null) {
this._errors++;
let errInfo;
if (exc) {
@@ -167,17 +166,17 @@ var TPS = {
QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver,
Ci.nsISupportsWeakReference]),
observe: function TPS__observe(subject, topic, data) {
try {
Logger.logInfo("----------event observed: " + topic);
- switch(topic) {
+ switch (topic) {
case "private-browsing":
Logger.logInfo("private browsing " + data);
break;
case "profile-before-change":
OBSERVER_TOPICS.forEach(function(topic) {
Services.obs.removeObserver(this, topic);
}, this);
@@ -205,35 +204,34 @@ var TPS = {
this.delayAutoSync();
// If this is the first sync error, retry...
if (this._syncErrors === 0) {
Logger.logInfo("Sync error; retrying...");
this._syncErrors++;
Utils.nextTick(this.RunNextTestAction, this);
- }
- else {
+ } else {
this._triggeredSync = false;
this.DumpError("Sync error; aborting test");
return;
}
break;
case "weave:service:sync:finish":
this._syncActive = false;
this._syncErrors = 0;
this._triggeredSync = false;
this.delayAutoSync();
// Wait a second before continuing, otherwise we can get
// 'sync not complete' errors.
- Utils.namedTimer(function () {
+ Utils.namedTimer(function() {
this.FinishAsyncOperation();
}, 1000, this, "postsync");
break;
case "weave:service:sync:start":
// Ensure that the sync operation has been started by TPS
if (!this._triggeredSync) {
@@ -246,20 +244,19 @@ var TPS = {
case "weave:engine:start-tracking":
this._isTracking = true;
break;
case "weave:engine:stop-tracking":
this._isTracking = false;
break;
}
- }
- catch (e) {
+ } catch (e) {
this.DumpError("Observer failed", e);
- return;
+
}
},
/**
* Given that we cannot complely disable the automatic sync operations, we
* massively delay the next sync. Sync operations have to only happen when
* directly called via TPS.Sync()!
*/
@@ -285,52 +282,52 @@ var TPS = {
}
},
quit: function TPS__quit() {
this._requestedQuit = true;
this.goQuitApplication();
},
- HandleWindows: function (aWindow, action) {
+ HandleWindows(aWindow, action) {
Logger.logInfo("executing action " + action.toUpperCase() +
" on window " + JSON.stringify(aWindow));
- switch(action) {
+ switch (action) {
case ACTION_ADD:
BrowserWindows.Add(aWindow.private, function(win) {
Logger.logInfo("window finished loading");
this.FinishAsyncOperation();
}.bind(this));
break;
}
Logger.logPass("executing action " + action.toUpperCase() + " on windows");
},
- HandleTabs: function (tabs, action) {
+ HandleTabs(tabs, action) {
this._tabsAdded = tabs.length;
this._tabsFinished = 0;
for (let tab of tabs) {
Logger.logInfo("executing action " + action.toUpperCase() +
" on tab " + JSON.stringify(tab));
- switch(action) {
+ switch (action) {
case ACTION_ADD:
// When adding tabs, we keep track of how many tabs we're adding,
// and wait until we've received that many onload events from our
// new tabs before continuing
let that = this;
let taburi = tab.uri;
BrowserTabs.Add(tab.uri, function() {
that._tabsFinished++;
Logger.logInfo("tab for " + taburi + " finished loading");
if (that._tabsFinished == that._tabsAdded) {
Logger.logInfo("all tabs loaded, continuing...");
// Wait a second before continuing to be sure tabs can be synced,
// otherwise we can get 'error locating tab'
- Utils.namedTimer(function () {
+ Utils.namedTimer(function() {
that.FinishAsyncOperation();
}, 1000, this, "postTabsOpening");
}
});
break;
case ACTION_VERIFY:
Logger.AssertTrue(typeof(tab.profile) != "undefined",
"profile must be defined when verifying tabs");
@@ -346,42 +343,42 @@ var TPS = {
break;
default:
Logger.AssertTrue(false, "invalid action: " + action);
}
}
Logger.logPass("executing action " + action.toUpperCase() + " on tabs");
},
- HandlePrefs: function (prefs, action) {
+ HandlePrefs(prefs, action) {
for (let pref of prefs) {
Logger.logInfo("executing action " + action.toUpperCase() +
" on pref " + JSON.stringify(pref));
let preference = new Preference(pref);
- switch(action) {
+ switch (action) {
case ACTION_MODIFY:
preference.Modify();
break;
case ACTION_VERIFY:
preference.Find();
break;
default:
Logger.AssertTrue(false, "invalid action: " + action);
}
}
Logger.logPass("executing action " + action.toUpperCase() + " on pref");
},
- HandleForms: function (data, action) {
+ HandleForms(data, action) {
this.shouldValidateForms = true;
for (let datum of data) {
Logger.logInfo("executing action " + action.toUpperCase() +
" on form entry " + JSON.stringify(datum));
let formdata = new FormData(datum, this._usSinceEpoch);
- switch(action) {
+ switch (action) {
case ACTION_ADD:
Async.promiseSpinningly(formdata.Create());
break;
case ACTION_DELETE:
Async.promiseSpinningly(formdata.Remove());
break;
case ACTION_VERIFY:
Logger.AssertTrue(Async.promiseSpinningly(formdata.Find()),
@@ -394,22 +391,22 @@ var TPS = {
default:
Logger.AssertTrue(false, "invalid action: " + action);
}
}
Logger.logPass("executing action " + action.toUpperCase() +
" on formdata");
},
- HandleHistory: function (entries, action) {
+ HandleHistory(entries, action) {
try {
for (let entry of entries) {
Logger.logInfo("executing action " + action.toUpperCase() +
" on history entry " + JSON.stringify(entry));
- switch(action) {
+ switch (action) {
case ACTION_ADD:
HistoryEntry.Add(entry, this._usSinceEpoch);
break;
case ACTION_DELETE:
HistoryEntry.Delete(entry, this._usSinceEpoch);
break;
case ACTION_VERIFY:
Logger.AssertTrue(HistoryEntry.Find(entry, this._usSinceEpoch),
@@ -420,24 +417,23 @@ var TPS = {
"Uri visits found in history database, but they shouldn't be");
break;
default:
Logger.AssertTrue(false, "invalid action: " + action);
}
}
Logger.logPass("executing action " + action.toUpperCase() +
" on history");
- }
- catch(e) {
+ } catch (e) {
DumpHistory();
- throw(e);
+ throw (e);
}
},
- HandlePasswords: function (passwords, action) {
+ HandlePasswords(passwords, action) {
this.shouldValidatePasswords = true;
try {
for (let password of passwords) {
let password_id = -1;
Logger.logInfo("executing action " + action.toUpperCase() +
" on password " + JSON.stringify(password));
let passwordOb = new Password(password);
switch (action) {
@@ -462,30 +458,29 @@ var TPS = {
}
break;
default:
Logger.AssertTrue(false, "invalid action: " + action);
}
}
Logger.logPass("executing action " + action.toUpperCase() +
" on passwords");
- }
- catch(e) {
+ } catch (e) {
DumpPasswords();
- throw(e);
+ throw (e);
}
},
- HandleAddons: function (addons, action, state) {
+ HandleAddons(addons, action, state) {
this.shouldValidateAddons = true;
for (let entry of addons) {
Logger.logInfo("executing action " + action.toUpperCase() +
" on addon " + JSON.stringify(entry));
let addon = new Addon(this, entry);
- switch(action) {
+ switch (action) {
case ACTION_ADD:
addon.install();
break;
case ACTION_DELETE:
addon.uninstall();
break;
case ACTION_VERIFY:
Logger.AssertTrue(addon.find(state), 'addon ' + addon.id + ' not found');
@@ -499,17 +494,17 @@ var TPS = {
default:
throw new Error("Unknown action for add-on: " + action);
}
}
Logger.logPass("executing action " + action.toUpperCase() +
" on addons");
},
- HandleBookmarks: function (bookmarks, action) {
+ HandleBookmarks(bookmarks, action) {
this.shouldValidateBookmarks = true;
try {
let items = [];
for (let folder in bookmarks) {
let last_item_pos = -1;
for (let bookmark of bookmarks[folder]) {
Logger.clearPotentialError();
let placesItem;
@@ -529,69 +524,64 @@ var TPS = {
placesItem = new BookmarkFolder(bookmark);
else if ("livemark" in bookmark)
placesItem = new Livemark(bookmark);
else if ("separator" in bookmark)
placesItem = new Separator(bookmark);
if (action == ACTION_ADD) {
item_id = placesItem.Create();
- }
- else {
+ } else {
item_id = placesItem.Find();
if (action == ACTION_VERIFY_NOT) {
Logger.AssertTrue(item_id == -1,
"places item exists but it shouldn't: " +
JSON.stringify(bookmark));
- }
- else
+ } else
Logger.AssertTrue(item_id != -1, "places item not found", true);
}
last_item_pos = placesItem.GetItemIndex();
items.push(placesItem);
}
}
if (action == ACTION_DELETE || action == ACTION_MODIFY) {
for (let item of items) {
Logger.logInfo("executing action " + action.toUpperCase() +
" on bookmark " + JSON.stringify(item));
- switch(action) {
+ switch (action) {
case ACTION_DELETE:
item.Remove();
break;
case ACTION_MODIFY:
if (item.updateProps != null)
item.Update();
break;
}
}
}
Logger.logPass("executing action " + action.toUpperCase() +
" on bookmarks");
- }
- catch (e) {
+ } catch (e) {
DumpBookmarks();
- throw(e);
+ throw (e);
}
},
MozmillEndTestListener: function TPS__MozmillEndTestListener(obj) {
Logger.logInfo("mozmill endTest: " + JSON.stringify(obj));
if (obj.failed > 0) {
this.DumpError('mozmill test failed, name: ' + obj.name + ', reason: ' + JSON.stringify(obj.fails));
- return;
- }
- else if ('skipped' in obj && obj.skipped) {
+
+ } else if ('skipped' in obj && obj.skipped) {
this.DumpError('mozmill test failed, name: ' + obj.name + ', reason: ' + obj.skipped_reason);
- return;
- }
- else {
+
+ } else {
Utils.namedTimer(function() {
this.FinishAsyncOperation();
}, 2000, this, "postmozmilltest");
}
},
MozmillSetTestListener: function TPS__MozmillSetTestListener(obj) {
Logger.logInfo("mozmill setTest: " + obj.name);
@@ -728,17 +718,17 @@ var TPS = {
ValidateForms() {
return this.ValidateCollection("forms", FormValidator);
},
ValidateAddons() {
return this.ValidateCollection("addons", AddonValidator);
},
- RunNextTestAction: function() {
+ RunNextTestAction() {
try {
if (this._currentAction >=
this._phaselist[this._currentPhase].length) {
// Run necessary validations and then finish up
if (this.shouldValidateBookmarks) {
this.ValidateBookmarks();
}
if (this.shouldValidatePasswords) {
@@ -774,18 +764,17 @@ var TPS = {
Logger.logInfo("starting action: " + action[0].name);
action[0].apply(this, action.slice(1));
// if we're in an async operation, don't continue on to the next action
if (this._operations_pending)
return;
this._currentAction++;
- }
- catch(e) {
+ } catch (e) {
if (Async.isShutdownException(e)) {
if (this._requestedQuit) {
Logger.logInfo("Sync aborted due to requested shutdown");
} else {
this.DumpError("Sync aborted due to shutdown, but we didn't request it");
}
} else {
this.DumpError("RunNextTestAction failed", e);
@@ -859,17 +848,17 @@ var TPS = {
* String URI of the file to open.
* @param phase
* String name of the phase to run.
* @param logpath
* String path of the log file to write to.
* @param options
* Object defining addition run-time options.
*/
- RunTestPhase: function (file, phase, logpath, options) {
+ RunTestPhase(file, phase, logpath, options) {
try {
let settings = options || {};
Logger.init(logpath);
Logger.logInfo("Sync version: " + WEAVE_VERSION);
Logger.logInfo("Firefox buildid: " + Services.appinfo.appBuildID);
Logger.logInfo("Firefox version: " + Services.appinfo.version);
Logger.logInfo("Firefox source revision: " + (AppConstants.SOURCE_REVISION_URL || "unknown"));
@@ -889,19 +878,19 @@ var TPS = {
// We only want to do this if we modified the bookmarks this phase.
this.shouldValidateBookmarks = false;
// Always give Sync an extra tick to initialize. If we waited for the
// service:ready event, this is required to ensure all handlers have
// executed.
Utils.nextTick(this._executeTestPhase.bind(this, file, phase, settings));
- } catch(e) {
+ } catch (e) {
this.DumpError("RunTestPhase failed", e);
- return;
+
}
},
/**
* Executes a single test phase.
*
* This is called by RunTestPhase() after the environment is validated.
*/
@@ -952,20 +941,19 @@ var TPS = {
Logger.logInfo("setting client.name to " + this.phases[this._currentPhase]);
Weave.Svc.Prefs.set("client.name", this.phases[this._currentPhase]);
this._interceptSyncTelemetry();
// start processing the test actions
this._currentAction = 0;
- }
- catch(e) {
+ } catch (e) {
this.DumpError("_executeTestPhase failed", e);
- return;
+
}
},
/**
* Override sync telemetry functions so that we can detect errors generating
* the sync ping, and count how many pings we report.
*/
_interceptSyncTelemetry() {
@@ -1178,18 +1166,17 @@ var TPS = {
Logger.logInfo("Executing Sync" + (wipeAction ? ": " + wipeAction : ""));
// Force a wipe action if requested. In case of an initial sync the pref
// will be overwritten by Sync itself (see bug 992198), so ensure that we
// also handle it via the "weave:service:setup-complete" notification.
if (wipeAction) {
this._syncWipeAction = wipeAction;
Weave.Svc.Prefs.set("firstSync", wipeAction);
- }
- else {
+ } else {
Weave.Svc.Prefs.reset("firstSync");
}
this.Login(false);
++this._syncCount;
this._triggeredSync = true;
this.StartAsyncOperation();