# HG changeset patch # User Martin Schroeder # Date 1537658413 -7200 # Node ID 4ae0c5713dfecf37275060a0695be6702906adfd # Parent e43a224cdaddcfa1434c0f3d2689e88bb680fe29 Bug 1458367 - Mass replace the Components.interface/Components.utils uses with Ci/Cu in Calendar. r=MakeMyDay diff --git a/calendar/base/backend/calBackendLoader.js b/calendar/base/backend/calBackendLoader.js --- a/calendar/base/backend/calBackendLoader.js +++ b/calendar/base/backend/calBackendLoader.js @@ -11,26 +11,26 @@ function calBackendLoader() { try { this.loadBackend(); } catch (e) { dump(`### Error loading backend:${e.filename || e.fileName}:${e.lineNumber}: ${e}\n`); } } var calBackendLoaderClassID = Components.ID("{0314c271-7168-40fa-802e-83c8c46a557e}"); -var calBackendLoaderInterfaces = [Components.interfaces.nsIObserver]; +var calBackendLoaderInterfaces = [Ci.nsIObserver]; calBackendLoader.prototype = { classID: calBackendLoaderClassID, QueryInterface: XPCOMUtils.generateQI(calBackendLoaderInterfaces), classInfo: XPCOMUtils.generateCI({ classID: calBackendLoaderClassID, contractID: "@mozilla.org/calendar/backend-loader;1", classDescription: "Calendar Backend Loader", interfaces: calBackendLoaderInterfaces, - flags: Components.interfaces.nsIClassInfo.SINGLETON + flags: Ci.nsIClassInfo.SINGLETON }), loaded: false, observe: function() { // Nothing to do here, just need the entry so this is instanciated }, @@ -49,17 +49,17 @@ calBackendLoader.prototype = { }; // Load ical.js backend let scope = {}; Services.scriptloader.loadSubScript("resource://calendar/components/calICALJSComponents.js", scope); // Register the icaljs components. We used to unregisterFactory, but this caused all // sorts of problems. Just registering over it seems to work quite fine. - let registrar = Components.manager.QueryInterface(Components.interfaces.nsIComponentRegistrar); + let registrar = Components.manager.QueryInterface(Ci.nsIComponentRegistrar); for (let [contractID, classID] of Object.entries(contracts)) { let newClassID = Components.ID(classID); let newFactory = lazyFactoryFor(scope, newClassID); registrar.registerFactory(newClassID, "", contractID, newFactory); } dump("[calBackendLoader] Using Lightning's icaljs backend\n"); } else { diff --git a/calendar/base/backend/icaljs/calDateTime.js b/calendar/base/backend/icaljs/calDateTime.js --- a/calendar/base/backend/icaljs/calDateTime.js +++ b/calendar/base/backend/icaljs/calDateTime.js @@ -8,17 +8,17 @@ ChromeUtils.import("resource://gre/modul var UNIX_TIME_TO_PRTIME = 1000000; function calDateTime(innerObject) { this.wrappedJSObject = this; this.innerObject = innerObject || ICAL.Time.epochTime.clone(); } -var calDateTimeInterfaces = [Components.interfaces.calIDateTime]; +var calDateTimeInterfaces = [Ci.calIDateTime]; var calDateTimeClassID = Components.ID("{36783242-ec94-4d8a-9248-d2679edd55b9}"); calDateTime.prototype = { QueryInterface: XPCOMUtils.generateQI(calDateTimeInterfaces), classID: calDateTimeClassID, classInfo: XPCOMUtils.generateCI({ contractID: "@mozilla.org/calendar/datetime;1", classDescription: "Describes a Date/Time Object", classID: calDateTimeClassID, diff --git a/calendar/base/backend/icaljs/calDuration.js b/calendar/base/backend/icaljs/calDuration.js --- a/calendar/base/backend/icaljs/calDuration.js +++ b/calendar/base/backend/icaljs/calDuration.js @@ -5,17 +5,17 @@ ChromeUtils.import("resource://calendar/modules/ical.js"); ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); function calDuration(innerObject) { this.innerObject = innerObject || new ICAL.Duration(); this.wrappedJSObject = this; } -var calDurationInterfaces = [Components.interfaces.calIDuration]; +var calDurationInterfaces = [Ci.calIDuration]; var calDurationClassID = Components.ID("{7436f480-c6fc-4085-9655-330b1ee22288}"); calDuration.prototype = { QueryInterface: XPCOMUtils.generateQI(calDurationInterfaces), classID: calDurationClassID, classInfo: XPCOMUtils.generateCI({ contractID: "@mozilla.org/calendar/duration;1", classDescription: "Calendar Duration Object", classID: calDurationClassID, diff --git a/calendar/base/backend/icaljs/calICSService.js b/calendar/base/backend/icaljs/calICSService.js --- a/calendar/base/backend/icaljs/calICSService.js +++ b/calendar/base/backend/icaljs/calICSService.js @@ -6,17 +6,17 @@ ChromeUtils.import("resource://calendar/ ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); ChromeUtils.import("resource://calendar/modules/calUtils.jsm"); function calIcalProperty(innerObject) { this.innerObject = innerObject || new ICAL.Property(); this.wrappedJSObject = this; } -var calIcalPropertyInterfaces = [Components.interfaces.calIIcalProperty]; +var calIcalPropertyInterfaces = [Ci.calIIcalProperty]; var calIcalPropertyClassID = Components.ID("{423ac3f0-f612-48b3-953f-47f7f8fd705b}"); calIcalProperty.prototype = { QueryInterface: XPCOMUtils.generateQI(calIcalPropertyInterfaces), classID: calIcalPropertyClassID, classInfo: XPCOMUtils.generateCI({ contractID: "@mozilla.org/calendar/ical-property;1", classDescription: "Wrapper for a libical property", classID: calIcalPropertyClassID, @@ -208,17 +208,17 @@ calIcalProperty.prototype = { }; function calIcalComponent(innerObject) { this.innerObject = innerObject || new ICAL.Component(); this.wrappedJSObject = this; this.mReferencedZones = {}; } -var calIcalComponentInterfaces = [Components.interfaces.calIIcalComponent]; +var calIcalComponentInterfaces = [Ci.calIIcalComponent]; var calIcalComponentClassID = Components.ID("{51ac96fd-1279-4439-a85b-6947b37f4cea}"); calIcalComponent.prototype = { QueryInterface: XPCOMUtils.generateQI(calIcalComponentInterfaces), classID: calIcalComponentClassID, classInfo: XPCOMUtils.generateCI({ contractID: "@mozilla.org/calendar/ical-component;1", classDescription: "Wrapper for a icaljs component", classID: calIcalComponentClassID, @@ -294,17 +294,17 @@ calIcalComponent.prototype = { set categories(val) { this.innerObject.updatePropertyWithValue("categories", val); }, get URL() { return this.innerObject.getFirstPropertyValue("url"); }, set URL(val) { this.innerObject.updatePropertyWithValue("url", val); }, get priority() { // If there is no value for this integer property, then we must return // the designated INVALID_VALUE. - const INVALID_VALUE = Components.interfaces.calIIcalComponent.INVALID_VALUE; + const INVALID_VALUE = Ci.calIIcalComponent.INVALID_VALUE; let prop = this.innerObject.getFirstProperty("priority"); let val = prop ? prop.getFirstValue() : null; return (val === null ? INVALID_VALUE : val); }, set priority(val) { this.innerObject.updatePropertyWithValue("priority", val); }, _setTimeAttr: function(propName, val) { let prop = this.innerObject.updatePropertyWithValue(propName, val); @@ -439,75 +439,75 @@ calIcalComponent.prototype = { getReferencedTimezones: function(aCount) { let vals = Object.keys(this.mReferencedZones).map(timezone => this.mReferencedZones[timezone]); aCount.value = vals.length; return vals; }, serializeToICSStream: function() { - let unicodeConverter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"] - .createInstance(Components.interfaces.nsIScriptableUnicodeConverter); + let unicodeConverter = Cc["@mozilla.org/intl/scriptableunicodeconverter"] + .createInstance(Ci.nsIScriptableUnicodeConverter); unicodeConverter.charset = "UTF-8"; return unicodeConverter.convertToInputStream(this.innerObject.toString()); } }; function calICSService() { this.wrappedJSObject = this; } -var calICSServiceInterfaces = [Components.interfaces.calIICSService]; +var calICSServiceInterfaces = [Ci.calIICSService]; var calICSServiceClassID = Components.ID("{c61cb903-4408-41b3-bc22-da0b27efdfe1}"); calICSService.prototype = { QueryInterface: XPCOMUtils.generateQI(calICSServiceInterfaces), classID: calICSServiceClassID, classInfo: XPCOMUtils.generateCI({ contractID: "@mozilla.org/calendar/ics-service;1", classDescription: "ICS component and property service", classID: calICSServiceClassID, - interfaces: [Components.interfaces.calIICSService] + interfaces: [Ci.calIICSService] }), parseICS: function(serialized, tzProvider) { // TODO ical.js doesn't support tz providers, but this is usually null // or our timezone service anyway. let comp = ICAL.parse(serialized); return new calIcalComponent(new ICAL.Component(comp)); }, parseICSAsync: function(serialized, tzProvider, listener) { // There are way too many error checking messages here, but I had so // much pain with this method that I don't want it to break again. try { let worker = new ChromeWorker("resource://calendar/calendar-js/calICSService-worker.js"); worker.onmessage = function(event) { - let rc = Components.results.NS_ERROR_FAILURE; + let rc = Cr.NS_ERROR_FAILURE; let icalComp = null; try { rc = event.data.rc; icalComp = new calIcalComponent(new ICAL.Component(event.data.data)); if (!Components.isSuccessCode(rc)) { cal.ERROR("[calICSService] Error in parser worker: " + data); } } catch (e) { cal.ERROR("[calICSService] Exception parsing item: " + e); } listener.onParsingComplete(rc, icalComp); }; worker.onerror = function(event) { cal.ERROR("[calICSService] Error in parser worker: " + event.message); - listener.onParsingComplete(Components.results.NS_ERROR_FAILURE, null); + listener.onParsingComplete(Cr.NS_ERROR_FAILURE, null); }; worker.postMessage(serialized); } catch (e) { // If an error occurs above, the calling code will hang. Catch the exception just in case cal.ERROR("[calICSService] Error starting parsing worker: " + e); - listener.onParsingComplete(Components.results.NS_ERROR_FAILURE, null); + listener.onParsingComplete(Cr.NS_ERROR_FAILURE, null); } }, createIcalComponent: function(kind) { return new calIcalComponent(new ICAL.Component(kind.toLowerCase())); }, createIcalProperty: function(kind) { diff --git a/calendar/base/backend/icaljs/calPeriod.js b/calendar/base/backend/icaljs/calPeriod.js --- a/calendar/base/backend/icaljs/calPeriod.js +++ b/calendar/base/backend/icaljs/calPeriod.js @@ -5,17 +5,17 @@ ChromeUtils.import("resource://calendar/modules/ical.js"); ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); function calPeriod(innerObject) { this.innerObject = innerObject || new ICAL.Period({}); this.wrappedJSObject = this; } -var calPeriodInterfaces = [Components.interfaces.calIPeriod]; +var calPeriodInterfaces = [Ci.calIPeriod]; var calPeriodClassID = Components.ID("{394a281f-7299-45f7-8b1f-cce21258972f}"); calPeriod.prototype = { QueryInterface: XPCOMUtils.generateQI(calPeriodInterfaces), classID: calPeriodClassID, classInfo: XPCOMUtils.generateCI({ contractID: "@mozilla.org/calendar/period;1", classDescription: "A period between two dates", classID: calPeriodClassID, diff --git a/calendar/base/backend/icaljs/calRecurrenceRule.js b/calendar/base/backend/icaljs/calRecurrenceRule.js --- a/calendar/base/backend/icaljs/calRecurrenceRule.js +++ b/calendar/base/backend/icaljs/calRecurrenceRule.js @@ -6,17 +6,17 @@ ChromeUtils.import("resource://calendar/ ChromeUtils.import("resource://calendar/modules/calUtils.jsm"); ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); function calRecurrenceRule(innerObject) { this.innerObject = innerObject || new ICAL.Recur(); this.wrappedJSObject = this; } -var calRecurrenceRuleInterfaces = [Components.interfaces.calIRecurrenceRule]; +var calRecurrenceRuleInterfaces = [Ci.calIRecurrenceRule]; var calRecurrenceRuleClassID = Components.ID("{df19281a-5389-4146-b941-798cb93a7f0d}"); calRecurrenceRule.prototype = { QueryInterface: XPCOMUtils.generateQI(calRecurrenceRuleInterfaces), classID: calRecurrenceRuleClassID, classInfo: XPCOMUtils.generateCI({ contractID: "@mozilla.org/calendar/recurrence-rule;1", classDescription: "Calendar Recurrence Rule", classID: calRecurrenceRuleClassID, @@ -39,17 +39,17 @@ calRecurrenceRule.prototype = { }, getOccurrences: function(aStartTime, aRangeStart, aRangeEnd, aMaxCount, aCount) { aStartTime = unwrapSingle(ICAL.Time, aStartTime); aRangeStart = unwrapSingle(ICAL.Time, aRangeStart); aRangeEnd = unwrapSingle(ICAL.Time, aRangeEnd); if (!aMaxCount && !aRangeEnd && this.count == 0 && this.until == null) { - throw Components.results.NS_ERROR_INVALID_ARG; + throw Cr.NS_ERROR_INVALID_ARG; } let occurrences = []; let rangeStart = aRangeStart.clone(); rangeStart.isDate = false; let dtend = null; @@ -112,17 +112,17 @@ calRecurrenceRule.prototype = { get type() { return this.innerObject.freq; }, set type(val) { this.innerObject.freq = val; }, get interval() { return this.innerObject.interval; }, set interval(val) { this.innerObject.interval = val; }, get count() { if (!this.isByCount) { - throw Components.results.NS_ERROR_FAILURE; + throw Cr.NS_ERROR_FAILURE; } return this.innerObject.count || -1; }, set count(val) { this.innerObject.count = (val && val > 0 ? val : null); }, get untilDate() { if (this.innerObject.until) { return new calDateTime(this.innerObject.until); diff --git a/calendar/base/content/agenda-listbox.js b/calendar/base/content/agenda-listbox.js --- a/calendar/base/content/agenda-listbox.js +++ b/calendar/base/content/agenda-listbox.js @@ -590,17 +590,17 @@ agendaListbox.setupContextMenu = functio * * @param aStart (optional) The start date for the item query. * @param aEnd (optional) The end date for the item query. * @param aCalendar (optional) If specified, the single calendar from * which the refresh will occur. */ agendaListbox.refreshCalendarQuery = function(aStart, aEnd, aCalendar) { let refreshJob = { - QueryInterface: XPCOMUtils.generateQI([Components.interfaces.calIOperationListener]), + QueryInterface: XPCOMUtils.generateQI([Ci.calIOperationListener]), agendaListbox: this, calendar: null, calId: null, operation: null, cancelled: false, onOperationComplete: function(aOpCalendar, aStatus, aOperationType, aId, aDateTime) { if (this.agendaListbox.mPendingRefreshJobs.has(this.calId)) { @@ -618,17 +618,17 @@ agendaListbox.refreshCalendarQuery = fun } for (let item of aItems) { this.agendaListbox.addItem(item); } }, cancel: function() { this.cancelled = true; - let operation = cal.wrapInstance(this.operation, Components.interfaces.calIOperation); + let operation = cal.wrapInstance(this.operation, Ci.calIOperation); if (operation && operation.isPending) { operation.cancel(); this.operation = null; } }, execute: function() { if (!(aStart || aEnd || aCalendar)) { @@ -663,17 +663,17 @@ agendaListbox.refreshCalendarQuery = fun this.agendaListbox.mPendingRefreshJobs.delete(this.calId); } } this.calendar = aCalendar; let filter = this.calendar.ITEM_FILTER_CLASS_OCCURRENCES | this.calendar.ITEM_FILTER_TYPE_EVENT; let operation = this.calendar.getItems(filter, 0, aStart, aEnd, this); - operation = cal.wrapInstance(operation, Components.interfaces.calIOperation); + operation = cal.wrapInstance(operation, Ci.calIOperation); if (operation && operation.isPending) { this.operation = operation; this.agendaListbox.mPendingRefreshJobs.set(this.calId, this); } } }; refreshJob.execute(); @@ -864,20 +864,20 @@ agendaListbox.calendarOpListener = { age /** * Calendar and composite observer, used to keep agenda listbox up to date. * @see calIObserver * @see calICompositeObserver */ agendaListbox.calendarObserver = { agendaListbox: agendaListbox }; agendaListbox.calendarObserver.QueryInterface = function(aIID) { - if (!aIID.equals(Components.interfaces.calIObserver) && - !aIID.equals(Components.interfaces.calICompositeObserver) && - !aIID.equals(Components.interfaces.nsISupports)) { - throw Components.results.NS_ERROR_NO_INTERFACE; + if (!aIID.equals(Ci.calIObserver) && + !aIID.equals(Ci.calICompositeObserver) && + !aIID.equals(Ci.nsISupports)) { + throw Cr.NS_ERROR_NO_INTERFACE; } return this; }; // calIObserver: agendaListbox.calendarObserver.onStartBatch = function() { }; @@ -1099,18 +1099,17 @@ function scheduleNextCurrentEventUpdate( // Add observer Services.obs.addObserver(wakeObserver, "wake_notification"); // Remove observer on unload window.addEventListener("unload", () => { Services.obs.removeObserver(wakeObserver, "wake_notification"); }); - gEventTimer = Components.classes["@mozilla.org/timer;1"] - .createInstance(Components.interfaces.nsITimer); + gEventTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer); } gEventTimer.initWithCallback(udCallback, aMsUntil, gEventTimer.TYPE_ONE_SHOT); } /** * Gets a right value for calendar.agendaListbox.soondays preference, avoid * erroneus values edited in the lightning.js preference file **/ diff --git a/calendar/base/content/agenda-listbox.xml b/calendar/base/content/agenda-listbox.xml --- a/calendar/base/content/agenda-listbox.xml +++ b/calendar/base/content/agenda-listbox.xml @@ -199,18 +199,18 @@ { this.onResize(this); }; this.viewBroadcaster.addEventListener(this.getAttribute("type") + "viewresized", this.mResizeHandler, true); // add a preference observer to monitor changes Services.prefs.addObserver("calendar.", this.mPrefObserver); @@ -261,18 +261,18 @@ ]]> { let attributeValue = Preferences.get("calendar.view.useSystemColors", false) && "true"; setElementValue(win.document.documentElement, attributeValue, "systemcolors"); }); } } }; @@ -175,18 +173,18 @@ function migrateCalendarUI() { calbar.insertItem("calendar-appmenu-button"); let taskbar = document.getElementById("task-toolbar2"); taskbar.insertItem("task-appmenu-button"); } if (currentUIVersion < 2) { // If the user has customized the event/task window dialog toolbar, // we copy that custom set of toolbar items to the event/task tab // toolbar and add the app menu button and a spring for alignment. - let xulStore = Components.classes["@mozilla.org/xul/xulstore;1"] - .getService(Components.interfaces.nsIXULStore); + let xulStore = Cc["@mozilla.org/xul/xulstore;1"] + .getService(Ci.nsIXULStore); let uri = "chrome://calendar/content/calendar-event-dialog.xul"; if (xulStore.hasValue(uri, "event-toolbar", "currentset")) { let windowSet = xulStore.getValue(uri, "event-toolbar", "currentset"); let items = "calendar-item-appmenu-button"; if (!windowSet.includes("spring")) { items = "spring," + items; } @@ -200,18 +198,18 @@ function migrateCalendarUI() { // loaded into the DOM so the toolbar's currentset // attribute does not yet match the new currentSet. tabBar.setAttribute("currentset", tabSet); } } if (currentUIVersion < 3) { // Rename toolbar button id "button-save" to // "button-saveandclose" in customized toolbars - let xulStore = Components.classes["@mozilla.org/xul/xulstore;1"] - .getService(Components.interfaces.nsIXULStore); + let xulStore = Cc["@mozilla.org/xul/xulstore;1"] + .getService(Ci.nsIXULStore); let windowUri = "chrome://calendar/content/calendar-event-dialog.xul"; let tabUri = "chrome://messenger/content/messenger.xul"; if (xulStore.hasValue(windowUri, "event-toolbar", "currentset")) { let windowSet = xulStore.getValue(windowUri, "event-toolbar", "currentset"); let newSet = windowSet.replace("button-save", "button-saveandclose"); xulStore.setValue(windowUri, "event-toolbar", "currentset", newSet); } diff --git a/calendar/base/content/calendar-clipboard.js b/calendar/base/content/calendar-clipboard.js --- a/calendar/base/content/calendar-clipboard.js +++ b/calendar/base/content/calendar-clipboard.js @@ -140,17 +140,17 @@ function pasteFromClipboard() { let flavor = {}; let data = {}; trans.getAnyTransferData(flavor, data, {}); data = data.value.QueryInterface(Ci.nsISupportsString).data; switch (flavor.value) { case "text/calendar": case "text/unicode": { let icsParser = Cc["@mozilla.org/calendar/ics-parser;1"] - .createInstance(Ci.calIIcsParser); + .createInstance(Ci.calIIcsParser); try { icsParser.parseString(data); } catch (e) { // Ignore parser errors from the clipboard data, if it fails // there will just be 0 items. } let items = icsParser.getItems({}); diff --git a/calendar/base/content/calendar-dnd-listener.js b/calendar/base/content/calendar-dnd-listener.js --- a/calendar/base/content/calendar-dnd-listener.js +++ b/calendar/base/content/calendar-dnd-listener.js @@ -27,19 +27,19 @@ var itemConversion = { aItem.calendar = getSelectedCalendar(); aItem.title = aMsgHdr.mime2DecodedSubject; cal.dtz.setDefaultStartEndHour(aItem); cal.alarms.setDefaultValues(aItem); let messenger = Cc["@mozilla.org/messenger;1"] - .createInstance(Ci.nsIMessenger); + .createInstance(Ci.nsIMessenger); let streamListener = Cc["@mozilla.org/network/sync-stream-listener;1"] - .createInstance(Ci.nsISyncStreamListener); + .createInstance(Ci.nsISyncStreamListener); messenger.messageServiceFromURI(msgUri).streamMessage(msgUri, streamListener, null, null, false, "", false); @@ -211,17 +211,17 @@ calDNDBaseObserver.prototype = { }, /** * Action to take when dropping the event. */ onDrop: function(aEvent, aTransferData, aDragSession) { let transferable = Cc["@mozilla.org/widget/transferable;1"] - .createInstance(Ci.nsITransferable); + .createInstance(Ci.nsITransferable); transferable.init(null); transferable.addDataFlavor("text/calendar"); transferable.addDataFlavor("text/x-moz-url"); transferable.addDataFlavor("text/x-moz-message"); transferable.addDataFlavor("text/unicode"); transferable.addDataFlavor("application/x-moz-file"); aDragSession.getData(transferable, 0); @@ -246,60 +246,60 @@ calDNDBaseObserver.prototype = { switch (bestFlavor.value) { case "text/calendar": { if (AppConstants.platform == "macosx") { // Mac likes to convert all \r to \n, we need to reverse this. data = data.data.replace(/\n\n/g, "\r\n"); } let parser = Cc["@mozilla.org/calendar/ics-parser;1"] - .createInstance(Components.interfaces.calIIcsParser); + .createInstance(Ci.calIIcsParser); parser.parseString(data); this.onDropItems( parser.getItems({}).concat(parser.getParentlessItems({})) ); break; } case "text/unicode": { let droppedUrl = this.retrieveURLFromData(data, bestFlavor.value); if (!droppedUrl) { return; } let url = Services.io.newURI(droppedUrl); let localFileInstance = Cc["@mozilla.org/file/local;1"] - .createInstance(Ci.nsIFile); + .createInstance(Ci.nsIFile); localFileInstance.initWithPath(url.path); let inputStream = Cc["@mozilla.org/network/file-input-stream;1"] - .createInstance(Ci.nsIFileInputStream); + .createInstance(Ci.nsIFileInputStream); inputStream.init(localFileInstance, MODE_RDONLY, parseInt("0444", 8), {}); try { // XXX support csv let importer = Cc["@mozilla.org/calendar/import;1?type=ics"] - .getService(Ci.calIImporter); + .getService(Ci.calIImporter); let items = importer.importFromStream(inputStream, {}); this.onDropItems(items); } finally { inputStream.close(); } break; } case "application/x-moz-file-promise": case "text/x-moz-url": { let uri = Services.io.newURI(data.toString()); let loader = Cc["@mozilla.org/network/unichar-stream-loader;1"] - .createInstance(Ci.nsIUnicharStreamLoader); + .createInstance(Ci.nsIUnicharStreamLoader); let channel = Services.io.newChannelFromURI2(uri, null, Services.scriptSecurityManager.getSystemPrincipal(), null, Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, Ci.nsIContentPolicy.TYPE_OTHER); channel.loadFlags |= Ci.nsIRequest.LOAD_BYPASS_CACHE; @@ -315,17 +315,17 @@ calDNDBaseObserver.prototype = { if (!charset || charset.length == 0) { charset = "UTF-8"; } return charset; }, onStreamComplete: function(loader, context, status, unicharString) { let parser = Cc["@mozilla.org/calendar/ics-parser;1"] - .createInstance(Ci.calIIcsParser); + .createInstance(Ci.calIIcsParser); parser.parseString(unicharString); self.onDropItems(parser.getItems({}).concat(parser.getParentlessItems({}))); } }; try { loader.init(listener, Ci.nsIUnicharStreamLoader.DEFAULT_SEGMENT_SIZE); channel.asyncOpen(loader, null); @@ -549,17 +549,17 @@ calTaskButtonDNDObserver.prototype = { * Invoke a drag session for the passed item. The passed box will be used as a * source. * * @param aItem The item to drag. * @param aXULBox The XUL box to invoke the drag session from. */ function invokeEventDragSession(aItem, aXULBox) { let transfer = Cc["@mozilla.org/widget/transferable;1"] - .createInstance(Ci.nsITransferable); + .createInstance(Ci.nsITransferable); transfer.init(null); transfer.addDataFlavor("text/calendar"); let flavourProvider = { QueryInterface: XPCOMUtils.generateQI([Ci.nsIFlavorDataProvider]), item: aItem, getFlavorData: function(aInTransferable, aInFlavor, aOutData, aOutDataLen) { @@ -578,28 +578,28 @@ function invokeEventDragSession(aItem, a transfer.setTransferData("application/vnd.x-moz-cal-event", flavourProvider, 0); } else if (cal.item.isToDo(aItem)) { transfer.addDataFlavor("application/vnd.x-moz-cal-task"); transfer.setTransferData("application/vnd.x-moz-cal-task", flavourProvider, 0); } // Also set some normal data-types, in case we drag into another app let serializer = Cc["@mozilla.org/calendar/ics-serializer;1"] - .createInstance(Ci.calIIcsSerializer); + .createInstance(Ci.calIIcsSerializer); serializer.addItems([aItem], 1); let supportsString = Cc["@mozilla.org/supports-string;1"] - .createInstance(Ci.nsISupportsString); + .createInstance(Ci.nsISupportsString); supportsString.data = serializer.serializeToString(); transfer.setTransferData("text/calendar", supportsString, supportsString.data.length * 2); transfer.setTransferData("text/unicode", supportsString, supportsString.data.length * 2); let action = Ci.nsIDragService.DRAGDROP_ACTION_MOVE; let mutArray = Cc["@mozilla.org/array;1"] - .createInstance(Ci.nsIMutableArray); + .createInstance(Ci.nsIMutableArray); mutArray.appendElement(transfer); aXULBox.sourceObject = aItem; try { cal.getDragService().invokeDragSession(aXULBox, mutArray, null, action); } catch (error) { // Nothing done here because we only have to catch an exception that occurs when dragging // is cancelled with ESC. This is an odd behaviour of the nativeDragService which we have // have to cover. diff --git a/calendar/base/content/calendar-extract.js b/calendar/base/content/calendar-extract.js --- a/calendar/base/content/calendar-extract.js +++ b/calendar/base/content/calendar-extract.js @@ -6,19 +6,19 @@ ChromeUtils.import("resource://calendar/ ChromeUtils.import("resource://calendar/modules/calUtils.jsm"); ChromeUtils.import("resource://gre/modules/Preferences.jsm"); ChromeUtils.import("resource://gre/modules/Services.jsm"); var calendarExtract = { onShowLocaleMenu: function(target) { let localeList = document.getElementById(target.id); let langs = []; - let chrome = Components.classes["@mozilla.org/chrome/chrome-registry;1"] - .getService(Components.interfaces.nsIXULChromeRegistry); - chrome.QueryInterface(Components.interfaces.nsIToolkitChromeRegistry); + let chrome = Cc["@mozilla.org/chrome/chrome-registry;1"] + .getService(Ci.nsIXULChromeRegistry) + .QueryInterface(Ci.nsIToolkitChromeRegistry); let locales = chrome.getLocalesForPackage("calendar"); let langRegex = /^(([^-]+)-*(.*))$/; while (locales.hasMore()) { let localeParts = langRegex.exec(locales.getNext()); let langName = localeParts[2]; try { @@ -65,20 +65,19 @@ var calendarExtract = { let locale = event.target.value; this.extractFromEmail(isEvent, true, locale); }, extractFromEmail: function(isEvent, fixedLang, fixedLocale) { // TODO would be nice to handle multiple selected messages, // though old conversion functionality didn't let message = gFolderDisplay.selectedMessage; - let messenger = Components.classes["@mozilla.org/messenger;1"] - .createInstance(Components.interfaces.nsIMessenger); - let listener = Components.classes["@mozilla.org/network/sync-stream-listener;1"] - .createInstance(Components.interfaces.nsISyncStreamListener); + let messenger = Cc["@mozilla.org/messenger;1"].createInstance(Ci.nsIMessenger); + let listener = Cc["@mozilla.org/network/sync-stream-listener;1"] + .createInstance(Ci.nsISyncStreamListener); let uri = message.folder.getUriForMsg(message); messenger.messageServiceFromURI(uri) .streamMessage(uri, listener, null, null, false, ""); let folder = message.folder; let title = message.mime2DecodedSubject; let content = folder.getMsgTextFromStream(listener.inputStream, message.Charset, 65536, diff --git a/calendar/base/content/calendar-invitations-manager.js b/calendar/base/content/calendar-invitations-manager.js --- a/calendar/base/content/calendar-invitations-manager.js +++ b/calendar/base/content/calendar-invitations-manager.js @@ -124,17 +124,17 @@ InvitationsManager.prototype = { gInvitationsRequestManager.cancelPendingRequests(); this.updateStartDate(); this.deleteAllItems(); let cals = cal.getCalendarManager().getCalendars({}); let opListener = { - QueryInterface: XPCOMUtils.generateQI([Components.interfaces.calIOperationListener]), + QueryInterface: XPCOMUtils.generateQI([Ci.calIOperationListener]), mCount: cals.length, mRequestManager: gInvitationsRequestManager, mInvitationsManager: this, mHandledItems: {}, // calIOperationListener onOperationComplete: function(aCalendar, aStatus, @@ -145,25 +145,25 @@ InvitationsManager.prototype = { this.mInvitationsManager.mItemList.sort((a, b) => { return a.startDate.compare(b.startDate); }); for (let listener of listeners) { try { if (this.mInvitationsManager.mItemList.length) { // Only call if there are actually items listener.onGetResult(null, - Components.results.NS_OK, - Components.interfaces.calIItemBase, + Cr.NS_OK, + Ci.calIItemBase, null, this.mInvitationsManager.mItemList.length, this.mInvitationsManager.mItemList); } listener.onOperationComplete(null, - Components.results.NS_OK, - Components.interfaces.calIOperationListener.GET, + Cr.NS_OK, + Ci.calIOperationListener.GET, null, null); } catch (exc) { cal.ERROR(exc); } } } }, @@ -198,24 +198,24 @@ InvitationsManager.prototype = { // temporary hack unless calCachedCalendar supports REQUEST_NEEDS_ACTION filter: calendar = calendar.getProperty("cache.uncachedCalendar"); if (!calendar) { opListener.onOperationComplete(); continue; } try { - calendar = calendar.QueryInterface(Components.interfaces.calICalendar); + calendar = calendar.QueryInterface(Ci.calICalendar); let endDate = this.mStartDate.clone(); endDate.year += 1; - let operation = calendar.getItems(Components.interfaces.calICalendar.ITEM_FILTER_REQUEST_NEEDS_ACTION | - Components.interfaces.calICalendar.ITEM_FILTER_TYPE_ALL | + let operation = calendar.getItems(Ci.calICalendar.ITEM_FILTER_REQUEST_NEEDS_ACTION | + Ci.calICalendar.ITEM_FILTER_TYPE_ALL | // we need to retrieve by occurrence to properly filter exceptions, // should be fixed with bug 416975 - Components.interfaces.calICalendar.ITEM_FILTER_CLASS_OCCURRENCES, + Ci.calICalendar.ITEM_FILTER_CLASS_OCCURRENCES, 0, this.mStartDate, endDate /* we currently cannot pass null here, because of bug 416975 */, opListener); gInvitationsRequestManager.addRequestStatus(calendar, operation); } catch (exc) { opListener.onOperationComplete(); cal.ERROR(exc); } @@ -263,24 +263,24 @@ InvitationsManager.prototype = { processJobQueue: function(queue, jobQueueFinishedCallBack) { // TODO: undo/redo function operationListener(mgr, queueCallback, oldItem_) { this.mInvitationsManager = mgr; this.mJobQueueFinishedCallBack = queueCallback; this.mOldItem = oldItem_; } operationListener.prototype = { - QueryInterface: XPCOMUtils.generateQI([Components.interfaces.calIOperationListener]), + QueryInterface: XPCOMUtils.generateQI([Ci.calIOperationListener]), onOperationComplete: function(aCalendar, aStatus, aOperationType, aId, aDetail) { if (Components.isSuccessCode(aStatus) && - aOperationType == Components.interfaces.calIOperationListener.MODIFY) { + aOperationType == Ci.calIOperationListener.MODIFY) { cal.itip.checkAndSend(aOperationType, aDetail, this.mOldItem); this.mInvitationsManager.deleteItem(aDetail); this.mInvitationsManager.addItem(aDetail); } this.mInvitationsManager.mJobsPending--; if (this.mInvitationsManager.mJobsPending == 0 && this.mJobQueueFinishedCallBack) { this.mJobQueueFinishedCallBack(); @@ -405,16 +405,16 @@ InvitationsManager.prototype = { * Checks if the item is valid for the invitation manager. Checks if the * item is in the range of the invitation manager and if the item is a valid * invitation. * * @param item The item to check * @return A boolean indicating if the item is a valid invitation. */ validateItem: function(item) { - if (item.calendar instanceof Components.interfaces.calISchedulingSupport && + if (item.calendar instanceof Ci.calISchedulingSupport && !item.calendar.isInvitation(item)) { return false; // exclude if organizer has invited himself } let start = item[cal.dtz.startDateProp(item)] || item[cal.dtz.endDateProp(item)]; return cal.itip.isOpenInvitation(item) && start.compare(this.mStartDate) >= 0; } }; diff --git a/calendar/base/content/calendar-item-editing.js b/calendar/base/content/calendar-item-editing.js --- a/calendar/base/content/calendar-item-editing.js +++ b/calendar/base/content/calendar-item-editing.js @@ -466,17 +466,17 @@ function openEventDialog(calendarItem, c }; // the dialog will reset this to auto when it is done loading. window.setCursor("wait"); // ask the provide if this item is an invitation. if this is the case // we'll open the summary dialog since the user is not allowed to change // the details of the item. - let wrappedCalendar = cal.wrapInstance(calendar, Components.interfaces.calISchedulingSupport); + let wrappedCalendar = cal.wrapInstance(calendar, Ci.calISchedulingSupport); let isInvitation = wrappedCalendar && wrappedCalendar.isInvitation(calendarItem); // open the dialog modeless let url; let isEditable = mode == "modify" && !isInvitation && cal.acl.userCanModifyItem(calendarItem); if (cal.acl.isCalendarWritable(calendar) && (mode == "new" || isEditable)) { if (args.inTab) { url = args.useNewItemUI ? "chrome://lightning/content/html-item-editing/lightning-item-iframe.html" @@ -585,17 +585,17 @@ function promptOccurrenceModification(aI } switch (type) { case MODIFY_PARENT: pastItems = items.map(item => item.parentItem); break; case MODIFY_FOLLOWING: // TODO tbd in a different bug - throw Components.results.NS_ERROR_NOT_IMPLEMENTED; + throw Cr.NS_ERROR_NOT_IMPLEMENTED; case MODIFY_OCCURRENCE: pastItems = items; break; case CANCEL: // Since we have not set past or futureItem, the return below will // take care. break; } @@ -608,21 +608,20 @@ function promptOccurrenceModification(aI // Undo/Redo code /** * Helper to return the transaction manager service. * * @return The calITransactionManager service. */ function getTransactionMgr() { - return Components.classes["@mozilla.org/calendar/transactionmanager;1"] - .getService(Components.interfaces.calITransactionManager); + return Cc["@mozilla.org/calendar/transactionmanager;1"] + .getService(Ci.calITransactionManager); } - /** * Create and commit a transaction with the given arguments to the transaction * manager. Also updates the undo/redo menu. * * @see calITransactionManager * @param aAction The action to do. * @param aItem The new item to add/modify/delete * @param aCalendar The calendar to do the transaction on diff --git a/calendar/base/content/calendar-management.js b/calendar/base/content/calendar-management.js --- a/calendar/base/content/calendar-management.js +++ b/calendar/base/content/calendar-management.js @@ -26,18 +26,18 @@ function getSelectedCalendar() { /** * Deletes the passed calendar, prompting the user if he really wants to do * this. If there is only one calendar left, no calendar is removed and the user * is not prompted. * * @param aCalendar The calendar to delete. */ function promptDeleteCalendar(aCalendar) { - const nIPS = Components.interfaces.nsIPromptService; - const cICM = Components.interfaces.calICalendarManager; + const nIPS = Ci.nsIPromptService; + const cICM = Ci.calICalendarManager; let calMgr = cal.getCalendarManager(); let calendars = calMgr.getCalendars({}); if (calendars.length <= 1) { // If this is the last calendar, don't delete it. return; } @@ -123,17 +123,17 @@ function initHomeCalendar() { composite.addCalendar(homeCalendar); // Wrapping this in a try/catch block, as if any of the migration code // fails, the app may not load. if (Preferences.get("calendar.migrator.enabled", true)) { try { gDataMigrator.checkAndMigrate(); } catch (e) { - Components.utils.reportError("Migrator error: " + e); + Cu.reportError("Migrator error: " + e); } } return homeCalendar; } /** * Called to clean up the calendar manager for a window. @@ -346,18 +346,18 @@ function showOnlyCalendar(aCalendar) { } } composite.addCalendar(aCalendar); composite.endBatch(); } var compositeObserver = { QueryInterface: XPCOMUtils.generateQI([ - Components.interfaces.calIObserver, - Components.interfaces.calICompositeObserver + Ci.calIObserver, + Ci.calICompositeObserver ]), onStartBatch: function() {}, onEndBatch: function() {}, onAddItem: function() {}, onModifyItem: function() {}, onDeleteItem: function() {}, onError: function() {}, @@ -401,31 +401,31 @@ function openCalendarSubscriptionsDialog "_blank", "chrome,titlebar,modal,resizable"); } /** * Calendar Offline Manager */ var calendarOfflineManager = { - QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsIObserver]), + QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver]), init: function() { if (this.initialized) { - throw Components.results.NS_ERROR_ALREADY_INITIALIZED; + throw Cr.NS_ERROR_ALREADY_INITIALIZED; } Services.obs.addObserver(this, "network:offline-status-changed"); this.updateOfflineUI(!this.isOnline()); this.initialized = true; }, uninit: function() { if (!this.initialized) { - throw Components.results.NS_ERROR_NOT_INITIALIZED; + throw Cr.NS_ERROR_NOT_INITIALIZED; } Services.obs.removeObserver(this, "network:offline-status-changed"); this.initialized = false; }, isOnline: function() { return !Services.io.offline; }, diff --git a/calendar/base/content/calendar-month-view.xml b/calendar/base/content/calendar-month-view.xml --- a/calendar/base/content/calendar-month-view.xml +++ b/calendar/base/content/calendar-month-view.xml @@ -78,18 +78,18 @@ return this.mOccurrence; ]]> aDayEndHour || aDayEndHour * 60 > this.mEndMin) { - throw Components.results.NS_ERROR_INVALID_ARG; + throw Cr.NS_ERROR_INVALID_ARG; } if (this.mDayStartHour != aDayStartHour || this.mDayEndHour != aDayEndHour) { this.mDayEndHour = aDayEndHour; this.mDayStartHour = aDayStartHour; let topbox = document.getAnonymousElementByAttribute(this, "anonid", "topbox"); if (topbox.childNodes.length) { @@ -634,18 +634,18 @@ // bgbox is used mainly for drawing the grid. at some point it may // also be used for all-day events. let otherorient = getOtherOrientation(orient); let configBox = document.getAnonymousElementByAttribute(this, "anonid", "config-box"); configBox.removeAttribute("hidden"); let minSize = configBox.getOptimalMinSize(); configBox.setAttribute("hidden", "true"); - this.mMinDuration = Components.classes["@mozilla.org/calendar/duration;1"] - .createInstance(Components.interfaces.calIDuration); + this.mMinDuration = Cc["@mozilla.org/calendar/duration;1"] + .createInstance(Ci.calIDuration); this.mMinDuration.minutes = Math.trunc(minSize / this.mPixPerMin); let theMin = this.mStartMin; while (theMin < this.mEndMin) { let dur = theMin % 60; theMin += dur; if (dur == 0) { dur = 60; @@ -1796,17 +1796,17 @@ aDayEndMin || aDayEndMin > this.mEndMin) { - throw Components.results.NS_ERROR_INVALID_ARG; + throw Cr.NS_ERROR_INVALID_ARG; } if (this.mDayStartMin != aDayStartMin || this.mDayEndMin != aDayEndMin) { this.mDayStartMin = aDayStartMin; this.mDayEndMin = aDayEndMin; } ]]> @@ -2654,17 +2654,17 @@ ]]> aDayEndMin || aDayEndMin > this.mEndMin) { - throw Components.results.NS_ERROR_INVALID_ARG; + throw Cr.NS_ERROR_INVALID_ARG; } if (this.mDayStartMin != aDayStartMin || this.mDayEndMin != aDayEndMin) { this.mDayStartMin = aDayStartMin; this.mDayEndMin = aDayEndMin; // Also update on the time-bar document.getAnonymousElementByAttribute(this, "anonid", "timebar") @@ -3812,17 +3812,17 @@ ]]> (this.mEndMin - this.mStartMin)) { - throw Components.results.NS_ERROR_INVALID_ARG; + throw Cr.NS_ERROR_INVALID_ARG; } if (this.mVisibleMinutes != aVisibleMinutes) { this.mVisibleMinutes = aVisibleMinutes; } return this.mVisibleMinutes; ]]> diff --git a/calendar/base/content/calendar-statusbar.js b/calendar/base/content/calendar-statusbar.js --- a/calendar/base/content/calendar-statusbar.js +++ b/calendar/base/content/calendar-statusbar.js @@ -14,22 +14,22 @@ ChromeUtils.import("resource://calendar/ var gCalendarStatusFeedback = { mCalendarStep: 0, mCalendarCount: 0, mWindow: null, mStatusText: null, mStatusBar: null, mStatusProgressPanel: null, mThrobber: null, - mProgressMode: Components.interfaces.calIStatusObserver.NO_PROGRESS, + mProgressMode: Ci.calIStatusObserver.NO_PROGRESS, mCurIndex: 0, mInitialized: false, mCalendars: {}, - QueryInterface: XPCOMUtils.generateQI([Components.interfaces.calIStatusObserver]), + QueryInterface: XPCOMUtils.generateQI([Ci.calIStatusObserver]), initialize: function(aWindow) { if (!this.mInitialized) { this.mWindow = aWindow; this.mStatusText = this.mWindow.document.getElementById("statusText"); this.mStatusBar = this.mWindow.document.getElementById("statusbar-icon"); this.mStatusProgressPanel = this.mWindow.document.getElementById("statusbar-progresspanel"); this.mThrobber = this.mWindow.document.getElementById("navigator-throbber"); @@ -41,65 +41,65 @@ var gCalendarStatusFeedback = { this.mStatusText.setAttribute("label", status); }, get spinning() { return this.mProgressMode; }, startMeteors: function(aProgressMode, aCalendarCount) { - if (aProgressMode != Components.interfaces.calIStatusObserver.NO_PROGRESS) { + if (aProgressMode != Ci.calIStatusObserver.NO_PROGRESS) { if (!this.mInitialized) { - Components.utils.reportError("StatusObserver has not been initialized!"); + Cu.reportError("StatusObserver has not been initialized!"); return; } this.mCalendars = {}; this.mCurIndex = 0; if (aCalendarCount) { this.mCalendarCount = this.mCalendarCount + aCalendarCount; this.mCalendarStep = Math.trunc(100 / this.mCalendarCount); } this.mProgressMode = aProgressMode; this.mStatusProgressPanel.removeAttribute("collapsed"); - if (this.mProgressMode == Components.interfaces.calIStatusObserver.DETERMINED_PROGRESS) { + if (this.mProgressMode == Ci.calIStatusObserver.DETERMINED_PROGRESS) { this.mStatusBar.removeAttribute("collapsed"); this.mStatusBar.setAttribute("mode", "determined"); this.mStatusBar.value = 0; let commonStatus = cal.l10n.getCalString("gettingCalendarInfoCommon"); this.showStatusString(commonStatus); } if (this.mThrobber) { this.mThrobber.setAttribute("busy", true); } } }, stopMeteors: function() { if (!this.mInitialized) { return; } - if (this.spinning != Components.interfaces.calIStatusObserver.NO_PROGRESS) { - this.mProgressMode = Components.interfaces.calIStatusObserver.NO_PROGRESS; + if (this.spinning != Ci.calIStatusObserver.NO_PROGRESS) { + this.mProgressMode = Ci.calIStatusObserver.NO_PROGRESS; this.mStatusProgressPanel.collapsed = true; this.mStatusBar.setAttribute("mode", "normal"); this.mStatusBar.value = 0; this.mCalendarCount = 0; this.showStatusString(""); if (this.mThrobber) { this.mThrobber.setAttribute("busy", false); } } }, calendarCompleted: function(aCalendar) { if (!this.mInitialized) { return; } - if (this.spinning != Components.interfaces.calIStatusObserver.NO_PROGRESS) { - if (this.spinning == Components.interfaces.calIStatusObserver.DETERMINED_PROGRESS) { + if (this.spinning != Ci.calIStatusObserver.NO_PROGRESS) { + if (this.spinning == Ci.calIStatusObserver.DETERMINED_PROGRESS) { if (!this.mCalendars[aCalendar.id] || this.mCalendars[aCalendar.id] === undefined) { this.mCalendars[aCalendar.id] = true; this.mStatusBar.value = parseInt(this.mStatusBar.value, 10) + this.mCalendarStep; this.mCurIndex++; let curStatus = cal.l10n.getCalString("gettingCalendarInfoDetail", [this.mCurIndex, this.mCalendarCount]); this.showStatusString(curStatus); } diff --git a/calendar/base/content/calendar-task-editing.js b/calendar/base/content/calendar-task-editing.js --- a/calendar/base/content/calendar-task-editing.js +++ b/calendar/base/content/calendar-task-editing.js @@ -123,17 +123,17 @@ var taskEdit = { }, /** * Handler function to call on keypress for the quick-add textbox. * * @param aEvent The DOM keypress event */ onKeyPress: function(aEvent) { - if (aEvent.keyCode == Components.interfaces.nsIDOMKeyEvent.DOM_VK_RETURN) { + if (aEvent.keyCode == Ci.nsIDOMKeyEvent.DOM_VK_RETURN) { let edit = aEvent.target; if (edit.value && edit.value.length > 0) { let item = cal.createTodo(); setDefaultItemValues(item); item.title = edit.value; edit.value = ""; doTransaction("add", item, item.calendar, null, null); @@ -166,17 +166,17 @@ var taskEdit = { /** * Observer to watch for readonly, disabled and capability changes of the * observed calendar. * * @see calIObserver */ calendarObserver: { - QueryInterface: XPCOMUtils.generateQI([Components.interfaces.calIObserver]), + QueryInterface: XPCOMUtils.generateQI([Ci.calIObserver]), // calIObserver: onStartBatch: function() {}, onEndBatch: function() {}, onLoad: function(aCalendar) {}, onAddItem: function(aItem) {}, onModifyItem: function(aNewItem, aOldItem) {}, onDeleteItem: function(aDeletedItem) {}, @@ -212,18 +212,18 @@ var taskEdit = { * Observer to watch for changes to the selected calendar. * * XXX I think we don't need to implement calIObserver here. * * @see calICompositeObserver */ compositeObserver: { QueryInterface: XPCOMUtils.generateQI([ - Components.interfaces.calIObserver, - Components.interfaces.calICompositeObserver + Ci.calIObserver, + Ci.calICompositeObserver ]), // calIObserver: onStartBatch: function() {}, onEndBatch: function() {}, onLoad: function(aCalendar) {}, onAddItem: function(aItem) {}, onModifyItem: function(aNewItem, aOldItem) {}, diff --git a/calendar/base/content/calendar-task-tree.js b/calendar/base/content/calendar-task-tree.js --- a/calendar/base/content/calendar-task-tree.js +++ b/calendar/base/content/calendar-task-tree.js @@ -163,17 +163,17 @@ function changeMenuForTask(aEvent) { */ function contextChangeTaskProgress(aEvent, aProgress) { if (gTabmail && gTabmail.currentTabInfo.mode.type == "calendarTask") { editToDoStatus(aProgress); } else { startBatchTransaction(); let tasks = getSelectedTasks(aEvent); for (let task of tasks) { - let newTask = task.clone().QueryInterface(Components.interfaces.calITodo); + let newTask = task.clone().QueryInterface(Ci.calITodo); newTask.percentComplete = aProgress; switch (aProgress) { case 0: newTask.isCompleted = false; break; case 100: newTask.isCompleted = true; break; @@ -215,17 +215,17 @@ function contextChangeTaskCalendar(aEven function contextChangeTaskPriority(aEvent, aPriority) { let tabType = gTabmail && gTabmail.currentTabInfo.mode.type; if (tabType == "calendarTask" || tabType == "calendarEvent") { editConfigState({ priority: aPriority }); } else { startBatchTransaction(); let tasks = getSelectedTasks(aEvent); for (let task of tasks) { - let newTask = task.clone().QueryInterface(Components.interfaces.calITodo); + let newTask = task.clone().QueryInterface(Ci.calITodo); newTask.priority = aPriority; doTransaction("modify", newTask, newTask.calendar, task, null); } endBatchTransaction(); } } /** diff --git a/calendar/base/content/calendar-task-tree.xml b/calendar/base/content/calendar-task-tree.xml --- a/calendar/base/content/calendar-task-tree.xml +++ b/calendar/base/content/calendar-task-tree.xml @@ -333,17 +333,17 @@ 75 && task.percentComplete > 0) { // XXX Would be nice if we could use relative widths, // i.e "15ex", but there is no scriptable interface. - return Components.interfaces.nsITreeView.PROGRESS_NORMAL; + return Ci.nsITreeView.PROGRESS_NORMAL; } break; } } - return Components.interfaces.nsITreeView.PROGRESS_NONE; + return Ci.nsITreeView.PROGRESS_NONE; }, /** * Task Tree Events */ onSelect: function(event) {}, onDoubleClick: function(event) { @@ -801,18 +801,18 @@ if (!childElt.value) { return false; } return aRow && aRow.value > -1 && this.binding.mTaskArray[aRow.value]; }, // Helper function to display datetimes _formatDateTime: function(aDateTime) { - let dateFormatter = Components.classes["@mozilla.org/calendar/datetime-formatter;1"] - .getService(Components.interfaces.calIDateTimeFormatter); + let dateFormatter = Cc["@mozilla.org/calendar/datetime-formatter;1"] + .getService(Ci.calIDateTimeFormatter); // datetime is from todo object, it is not a javascript date if (aDateTime && aDateTime.isValid) { let dateTime = aDateTime.getInTimezone(cal.dtz.defaultTimezone); return dateFormatter.formatDateTime(dateTime); } return ""; } @@ -823,18 +823,18 @@ Observer for the calendar event data source. This keeps the unifinder display up to date when the calendar event data is changed --> diff --git a/calendar/base/content/calendar-views.js b/calendar/base/content/calendar-views.js --- a/calendar/base/content/calendar-views.js +++ b/calendar/base/content/calendar-views.js @@ -349,34 +349,32 @@ function scheduleMidnightUpdate(aRefresh // Observer for wake after sleep/hibernate/standby to create new timers and refresh UI let wakeObserver = { observe: function(aSubject, aTopic, aData) { if (aTopic == "wake_notification") { // postpone refresh for another couple of seconds to get netwerk ready: if (this.mTimer) { this.mTimer.cancel(); } else { - this.mTimer = Components.classes["@mozilla.org/timer;1"] - .createInstance(Components.interfaces.nsITimer); + this.mTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer); } this.mTimer.initWithCallback(udCallback, 10 * 1000, - Components.interfaces.nsITimer.TYPE_ONE_SHOT); + Ci.nsITimer.TYPE_ONE_SHOT); } } }; // Add observer Services.obs.addObserver(wakeObserver, "wake_notification"); // Remove observer on unload window.addEventListener("unload", () => { Services.obs.removeObserver(wakeObserver, "wake_notification"); }); - gMidnightTimer = Components.classes["@mozilla.org/timer;1"] - .createInstance(Components.interfaces.nsITimer); + gMidnightTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer); } gMidnightTimer.initWithCallback(udCallback, msUntilTomorrow, gMidnightTimer.TYPE_ONE_SHOT); } /** * Retuns a cached copy of the view stylesheet. * * @return The view stylesheet object. @@ -426,17 +424,17 @@ function updateStyleSheetForViews(aCalen * colors. * * Note we need to keep the categoryPrefBranch variable outside of * initCategories since branch observers only live as long as the branch object * is alive, and out of categoryManagement to avoid cyclic references. */ var categoryPrefBranch; var categoryManagement = { - QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsIObserver]), + QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver]), initCategories: function() { categoryPrefBranch = Services.prefs.getBranch("calendar.category.color."); let categories = categoryPrefBranch.getChildList(""); // Fix illegally formatted category prefs. for (let i in categories) { let category = categories[i]; @@ -671,17 +669,17 @@ function editSelectedEvents() { } /** * Select all events from all calendars. Use with care. */ function selectAllEvents() { let items = []; let listener = { - QueryInterface: XPCOMUtils.generateQI([Components.interfaces.calIOperationListener]), + QueryInterface: XPCOMUtils.generateQI([Ci.calIOperationListener]), onOperationComplete: function(aCalendar, aStatus, aOperationType, aId, aDetail) { currentView().setSelectedItems(items.length, items, false); }, onGetResult: function(aCalendar, aStatus, aItemType, aDetail, aCount, aItems) { for (let item of aItems) { items.push(item); } } diff --git a/calendar/base/content/dialogs/calendar-alarm-dialog.js b/calendar/base/content/dialogs/calendar-alarm-dialog.js --- a/calendar/base/content/dialogs/calendar-alarm-dialog.js +++ b/calendar/base/content/dialogs/calendar-alarm-dialog.js @@ -12,18 +12,18 @@ ChromeUtils.import("resource://gre/modul /** * Helper function to get the alarm service and cache it. * * @return The alarm service component */ function getAlarmService() { if (!("mAlarmService" in window)) { - window.mAlarmService = Components.classes["@mozilla.org/calendar/alarm-service;1"] - .getService(Components.interfaces.calIAlarmService); + window.mAlarmService = Cc["@mozilla.org/calendar/alarm-service;1"] + .getService(Ci.calIAlarmService); } return window.mAlarmService; } /** * Event handler for the 'snooze' event. Snoozes the given alarm by the given * number of minutes using the alarm service. * @@ -212,17 +212,17 @@ function getDuration(aMinutes) { /** * Check whether the snooze period exceeds the current limitation of the AlarmService and prompt * the user with a message if so * @param {calIDuration} aDuration The duration to snooze * @returns {Boolean} */ function aboveSnoozeLimit(aDuration) { - const LIMIT = Components.interfaces.calIAlarmService.MAX_SNOOZE_MONTHS; + const LIMIT = Ci.calIAlarmService.MAX_SNOOZE_MONTHS; let currentTime = cal.dtz.now().getInTimezone(cal.dtz.UTC); let limitTime = currentTime.clone(); limitTime.month += LIMIT; let durationUntilLimit = limitTime.subtractDate(currentTime); if (aDuration.compare(durationUntilLimit) > 0) { let msg = PluralForm.get(LIMIT, cal.l10n.getCalString("alarmSnoozeLimitExceeded")); diff --git a/calendar/base/content/dialogs/calendar-creation.js b/calendar/base/content/dialogs/calendar-creation.js --- a/calendar/base/content/dialogs/calendar-creation.js +++ b/calendar/base/content/dialogs/calendar-creation.js @@ -6,18 +6,18 @@ ChromeUtils.import("resource://calendar/modules/calUtils.jsm"); /** * Shows the filepicker and creates a new calendar with a local file using the ICS * provider. */ function openLocalCalendar() { - const nsIFilePicker = Components.interfaces.nsIFilePicker; - let picker = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker); + const nsIFilePicker = Ci.nsIFilePicker; + let picker = Cc["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker); picker.init(window, cal.l10n.getCalString("Open"), nsIFilePicker.modeOpen); let wildmat = "*.ics"; let description = cal.l10n.getCalString("filterIcs", [wildmat]); picker.appendFilter(description, wildmat); picker.appendFilters(nsIFilePicker.filterAll); picker.open(rv => { if (rv != nsIFilePicker.returnOK || !picker.file) { diff --git a/calendar/base/content/dialogs/calendar-dialog-utils.js b/calendar/base/content/dialogs/calendar-dialog-utils.js --- a/calendar/base/content/dialogs/calendar-dialog-utils.js +++ b/calendar/base/content/dialogs/calendar-dialog-utils.js @@ -77,18 +77,18 @@ function resetDialogId(aDialog) { /** * Apply the persisted properties from xulstore.json on a dialog based on the current dialog id. * This needs to be invoked after changing a dialog id while loading to apply the values for the * new dialog id. * * @param aDialog The Dialog to apply the property values for */ function applyPersitedProperties(aDialog) { - let xulStore = Components.classes["@mozilla.org/xul/xulstore;1"] - .getService(Components.interfaces.nsIXULStore); + let xulStore = Cc["@mozilla.org/xul/xulstore;1"] + .getService(Ci.nsIXULStore); // first we need to detect which properties are persisted let persistedProps = aDialog.getAttribute("persist") || ""; if (persistedProps == "") { return; } let propNames = persistedProps.split(" "); // now let's apply persisted values if applicable for (let propName of propNames) { @@ -220,17 +220,17 @@ function updateReminderDetails() { } var gLastAlarmSelection = 0; function matchCustomReminderToMenuitem(reminder) { let defaultAlarmType = getDefaultAlarmType(); let reminderList = document.getElementById("item-alarm"); let reminderPopup = reminderList.firstChild; - if (reminder.related != Components.interfaces.calIAlarm.ALARM_RELATED_ABSOLUTE && + if (reminder.related != Ci.calIAlarm.ALARM_RELATED_ABSOLUTE && reminder.offset && reminder.action == defaultAlarmType) { // Exactly one reminder thats not absolute, we may be able to match up // popup items. let relation = (reminder.related == reminder.ALARM_RELATED_START ? "START" : "END"); let origin; // If the time duration for offset is 0, means the reminder is '0 minutes before' @@ -357,17 +357,17 @@ function saveReminder(item) { } // If the alarms differ, clear the snooze/dismiss properties if (Object.keys(oldAlarmMap).length > 0) { let cmp = "X-MOZ-SNOOZE-TIME"; // Recurring item alarms potentially have more snooze props, remove them // all. - let propIterator = fixIterator(item.propertyEnumerator, Components.interfaces.nsIProperty); + let propIterator = fixIterator(item.propertyEnumerator, Ci.nsIProperty); let propsToDelete = []; for (let prop of propIterator) { if (prop.name.startsWith(cmp)) { propsToDelete.push(prop.name); } } item.alarmLastAck = null; @@ -539,17 +539,17 @@ function updateLink() { } catch (e) { // No protocol handler for the given protocol, or invalid uri hideOrShow(false); return; } // Only show if its either an internal protcol handler, or its external // and there is an external app for the scheme - handler = cal.wrapInstance(handler, Components.interfaces.nsIExternalProtocolHandler); + handler = cal.wrapInstance(handler, Ci.nsIExternalProtocolHandler); hideOrShow(!handler || handler.externalAppExistsForScheme(uri.scheme)); setTimeout(() => { // HACK the url-link doesn't crop when setting the value in onLoad setElementValue("url-link", itemUrlString); setElementValue("url-link", itemUrlString, "href"); }, 0); } @@ -709,17 +709,17 @@ function determineAttendeesInRow() { * * @param {calIEvent|calIToDo} aItem Item to apply the change on */ function adaptScheduleAgent(aItem) { if (aItem.calendar && aItem.calendar.type == "caldav" && aItem.calendar.getProperty("capabilities.autoschedule.supported")) { let identity = aItem.calendar.getProperty("imip.identity"); let orgEmail = identity && - identity.QueryInterface(Components.interfaces.nsIMsgIdentity).email; + identity.QueryInterface(Ci.nsIMsgIdentity).email; let organizerAction = aItem.organizer && orgEmail && aItem.organizer.id == "mailto:" + orgEmail; if (aItem.calendar.getProperty("forceEmailScheduling")) { cal.LOG("Enforcing clientside email based scheduling."); // for attendees, we change schedule-agent only in case of an // organizer triggered action if (organizerAction) { aItem.getAttendees({}).forEach((aAttendee) => { diff --git a/calendar/base/content/dialogs/calendar-error-prompt.xul b/calendar/base/content/dialogs/calendar-error-prompt.xul --- a/calendar/base/content/dialogs/calendar-error-prompt.xul +++ b/calendar/base/content/dialogs/calendar-error-prompt.xul @@ -19,17 +19,17 @@ onload="loadErrorPrompt()" persist="screenX screenY" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" width="500" xmlns:nc="http://home.netscape.com/NC-rdf#"> diff --git a/calendar/lightning/content/lightning-utils.js b/calendar/lightning/content/lightning-utils.js --- a/calendar/lightning/content/lightning-utils.js +++ b/calendar/lightning/content/lightning-utils.js @@ -44,23 +44,23 @@ function ltnInitMailIdentitiesRow() { addMenuItem(menuPopup, cal.l10n.getLtnString("imipNoIdentity"), "none"); let identities; if (gCalendar && gCalendar.aclEntry && gCalendar.aclEntry.hasAccessControl) { identities = gCalendar.aclEntry.getOwnerIdentities({}); } else { identities = MailServices.accounts.allIdentities; } - for (let identity of fixIterator(identities, Components.interfaces.nsIMsgIdentity)) { + for (let identity of fixIterator(identities, Ci.nsIMsgIdentity)) { addMenuItem(menuPopup, identity.identityName, identity.key); } try { let sel = gCalendar.getProperty("imip.identity"); if (sel) { - sel = sel.QueryInterface(Components.interfaces.nsIMsgIdentity); + sel = sel.QueryInterface(Ci.nsIMsgIdentity); } menuListSelectItem("email-identity-menulist", sel ? sel.key : "none"); } catch (exc) { // Don't select anything if the identity can't be found } } /** diff --git a/calendar/lightning/content/messenger-overlay-sidebar.js b/calendar/lightning/content/messenger-overlay-sidebar.js --- a/calendar/lightning/content/messenger-overlay-sidebar.js +++ b/calendar/lightning/content/messenger-overlay-sidebar.js @@ -206,17 +206,17 @@ var calendarItemTabType = { // Generate and set the tab title. let strName; if (aTab.mode.type == "calendarEvent") { strName = aArgs.calendarEvent.title ? "editEventDialog" : "newEventDialog"; } else if (aTab.mode.type == "calendarTask") { strName = aArgs.calendarEvent.title ? "editTaskDialog" : "newTaskDialog"; } else { - throw Components.results.NS_ERROR_NOT_IMPLEMENTED; + throw Cr.NS_ERROR_NOT_IMPLEMENTED; } // name is "New Event", "Edit Task", etc. let name = cal.l10n.getCalString(strName); aTab.title = name + ": " + (aArgs.calendarEvent.title || name); // allowTabClose prevents the tab from being closed until we ask // the user if they want to save any unsaved changes. aTab.allowTabClose = false; @@ -522,17 +522,17 @@ function ltnFinish() { var FIRST_DELAY_STARTUP = 100; var FIRST_DELAY_RESCHEDULE = 100; var FIRST_DELAY_REGISTER = 10000; var FIRST_DELAY_UNREGISTER = 0; var gInvitationsOperationListener = { mCount: 0, - QueryInterface: XPCOMUtils.generateQI([Components.interfaces.calIOperationListener]), + QueryInterface: XPCOMUtils.generateQI([Ci.calIOperationListener]), onOperationComplete: function(aCalendar, aStatus, aOperationType, aId, aDetail) { let invitationsBox = document.getElementById("calendar-invitations-panel"); if (Components.isSuccessCode(aStatus)) { let value = cal.l10n.getLtnString("invitationsLink.label", [this.mCount]); document.getElementById("calendar-invitations-label").value = value; setElementValue(invitationsBox, this.mCount < 1 && "true", "hidden"); } else { invitationsBox.setAttribute("hidden", "true"); @@ -545,17 +545,17 @@ var gInvitationsOperationListener = { this.mCount += aCount; } } }; var gInvitationsCalendarManagerObserver = { mSideBar: this, - QueryInterface: XPCOMUtils.generateQI([Components.interfaces.calICalendarManagerObserver]), + QueryInterface: XPCOMUtils.generateQI([Ci.calICalendarManagerObserver]), onCalendarRegistered: function(aCalendar) { this.mSideBar.rescheduleInvitationsUpdate(FIRST_DELAY_REGISTER); }, onCalendarUnregistering: function(aCalendar) { this.mSideBar.rescheduleInvitationsUpdate(FIRST_DELAY_UNREGISTER); }, @@ -772,17 +772,17 @@ function moveEventToolbox(aDestination) } /** * Checks if Lightning's binary component was successfully loaded. */ function checkCalendarBinaryComponent() { // Don't even get started if we are running ical.js or the binary component // was successfully loaded. - if ("@mozilla.org/calendar/datetime;1" in Components.classes || + if ("@mozilla.org/calendar/datetime;1" in Cc || Preferences.get("calendar.icaljs", false)) { return; } const THUNDERBIRD_GUID = "{3550f703-e582-4d05-9a08-453d09bdfdc6}"; const SEAMONKEY_GUID = "{92650c4d-4b8e-4d2a-b7eb-24ecf4f6b63a}"; const LIGHTNING_GUID = "{e2fda1a4-762b-4020-b5ad-a41df1933103}"; diff --git a/calendar/lightning/modules/ltnInvitationUtils.jsm b/calendar/lightning/modules/ltnInvitationUtils.jsm --- a/calendar/lightning/modules/ltnInvitationUtils.jsm +++ b/calendar/lightning/modules/ltnInvitationUtils.jsm @@ -81,43 +81,42 @@ ltn.invitation = { * @param {calItipItem} aItipItem The itip item, which containes aEvent. * @return {DOM} The html representation of aEvent. */ createInvitationOverlay: function(aEvent, aItipItem) { // Creates HTML using the Node strings in the properties file let doc = cal.xml.parseFile("chrome://lightning/content/lightning-invitation.xhtml"); let formatter = cal.getDateFormatter(); - let linkConverter = Components.classes["@mozilla.org/txttohtmlconv;1"] - .getService(Components.interfaces.mozITXTToHTMLConv); + let linkConverter = Cc["@mozilla.org/txttohtmlconv;1"].getService(Ci.mozITXTToHTMLConv); let field = function(aField, aContentText, aConvert) { let descr = doc.getElementById("imipHtml-" + aField + "-descr"); if (descr) { let labelText = cal.l10n.getLtnString("imipHtml." + aField); descr.textContent = labelText; } if (aContentText) { let content = doc.getElementById("imipHtml-" + aField + "-content"); doc.getElementById("imipHtml-" + aField + "-row").hidden = false; if (aConvert) { // we convert special characters first to not mix up html conversion - let mode = Components.interfaces.mozITXTToHTMLConv.kEntities; + let mode = Ci.mozITXTToHTMLConv.kEntities; let contentText = linkConverter.scanTXT(aContentText, mode); try { // kGlyphSubstitution may lead to unexpected results when used in scanHTML - mode = Components.interfaces.mozITXTToHTMLConv.kStructPhrase + - Components.interfaces.mozITXTToHTMLConv.kGlyphSubstitution + - Components.interfaces.mozITXTToHTMLConv.kURLs; + mode = Ci.mozITXTToHTMLConv.kStructPhrase + + Ci.mozITXTToHTMLConv.kGlyphSubstitution + + Ci.mozITXTToHTMLConv.kURLs; // eslint-disable-next-line no-unsanitized/property content.innerHTML = linkConverter.scanHTML(contentText, mode); } catch (e) { - mode = Components.interfaces.mozITXTToHTMLConv.kStructPhrase + - Components.interfaces.mozITXTToHTMLConv.kURLs; + mode = Ci.mozITXTToHTMLConv.kStructPhrase + + Ci.mozITXTToHTMLConv.kURLs; // eslint-disable-next-line no-unsanitized/property content.innerHTML = linkConverter.scanHTML(contentText, mode); } } else { content.textContent = aContentText; } } }; @@ -149,17 +148,17 @@ ltn.invitation = { let modifiedOccurrences = []; let dateComptor = function(a, b) { return a.startDate.compare(b.startDate); }; // Show removed instances for (let exc of aEvent.recurrenceInfo.getRecurrenceItems({})) { - if (exc instanceof Components.interfaces.calIRecurrenceDate) { + if (exc instanceof Ci.calIRecurrenceDate) { if (exc.isNegative) { // This is an EXDATE let excDate = exc.date.getInTimezone(kDefaultTimezone); formattedExDates.push(formatter.formatDateTime(excDate)); } else { // This is an RDATE, close enough to a modified occurrence let excItem = aEvent.recurrenceInfo.getOccurrenceFor(exc.date); cal.data.binaryInsert(modifiedOccurrences, excItem, dateComptor, true); @@ -491,18 +490,18 @@ ltn.invitation = { /** * Converts a given unicode text * @param {String} aCharset target character set * @param {String} aSrc unicode text to convert * @return {String} the converted string */ convertFromUnicode: function(aCharset, aSrc) { - let unicodeConverter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"] - .createInstance(Components.interfaces.nsIScriptableUnicodeConverter); + let unicodeConverter = Cc["@mozilla.org/intl/scriptableunicodeconverter"] + .createInstance(Ci.nsIScriptableUnicodeConverter); unicodeConverter.charset = aCharset; return unicodeConverter.ConvertFromUnicode(aSrc); }, /** * Converts a header to a mime encoded header * @param {String} aHeader a header to encode * @param {boolean} aIsEmail if enabled, only the CN but not the email address gets @@ -510,19 +509,17 @@ ltn.invitation = { * @return {String} the encoded string */ encodeMimeHeader: function(aHeader, aIsEmail = false) { let fieldNameLen = aHeader.indexOf(": ") + 2; return MailServices.mimeConverter .encodeMimePartIIStr_UTF8(aHeader, aIsEmail, fieldNameLen, - Components.interfaces - .nsIMimeConverter - .MIME_ENCODED_WORD_SIZE); + Ci.nsIMimeConverter.MIME_ENCODED_WORD_SIZE); }, /** * Parses a counterproposal to extract differences to the existing event * @param {calIEvent|calITodo} aProposedItem The counterproposal * @param {calIEvent|calITodo} aExistingItem The item to compare with * @return {JSObject} Objcet of result and differences of parsing * @return {String} JsObject.result.type Parsing result: OK|OLDVERSION|ERROR|NODIFF diff --git a/calendar/providers/caldav/calDavCalendar.js b/calendar/providers/caldav/calDavCalendar.js --- a/calendar/providers/caldav/calDavCalendar.js +++ b/calendar/providers/caldav/calDavCalendar.js @@ -18,17 +18,17 @@ ChromeUtils.import("resource://calendar/ var xmlHeader = '\n'; var davNS = "DAV:"; var caldavNS = "urn:ietf:params:xml:ns:caldav"; var calservNS = "http://calendarserver.org/ns/"; var MIME_TEXT_CALENDAR = "text/calendar; charset=utf-8"; var MIME_TEXT_XML = "text/xml; charset=utf-8"; -var cIOL = Components.interfaces.calIOperationListener; +var cIOL = Ci.calIOperationListener; function caldavNSResolver(prefix) { /* eslint-disable id-length */ const namespaces = { D: davNS, C: caldavNS, CS: calservNS }; @@ -67,42 +67,36 @@ function calDavCalendar() { this.mProposedCtag = null; // By default, support both events and todos. this.mGenerallySupportedItemTypes = ["VEVENT", "VTODO"]; this.mSupportedItemTypes = this.mGenerallySupportedItemTypes.slice(0); this.mACLProperties = {}; } -// some shorthand -var calICalendar = Components.interfaces.calICalendar; -var calIErrors = Components.interfaces.calIErrors; -var calIFreeBusyInterval = Components.interfaces.calIFreeBusyInterval; -var calICalDavCalendar = Components.interfaces.calICalDavCalendar; - // used in checking calendar URI for (Cal)DAV-ness var kDavResourceTypeNone = 0; var kDavResourceTypeCollection = 1; var kDavResourceTypeCalendar = 2; // used for etag checking var CALDAV_MODIFY_ITEM = "modify"; var CALDAV_DELETE_ITEM = "delete"; var calDavCalendarClassID = Components.ID("{a35fc6ea-3d92-11d9-89f9-00045ace3b8d}"); var calDavCalendarInterfaces = [ - Components.interfaces.calICalendarProvider, - Components.interfaces.nsIInterfaceRequestor, - Components.interfaces.calIFreeBusyProvider, - Components.interfaces.nsIChannelEventSink, - Components.interfaces.calIItipTransport, - Components.interfaces.calISchedulingSupport, - Components.interfaces.calICalendar, - Components.interfaces.calIChangeLog, - calICalDavCalendar, + Ci.calICalendarProvider, + Ci.nsIInterfaceRequestor, + Ci.calIFreeBusyProvider, + Ci.nsIChannelEventSink, + Ci.calIItipTransport, + Ci.calISchedulingSupport, + Ci.calICalendar, + Ci.calIChangeLog, + Ci.calICalDavCalendar, ]; calDavCalendar.prototype = { __proto__: cal.provider.BaseClass.prototype, classID: calDavCalendarClassID, QueryInterface: XPCOMUtils.generateQI(calDavCalendarInterfaces), classInfo: XPCOMUtils.generateCI({ classID: calDavCalendarClassID, contractID: "@mozilla.org/calendar/calendar;1?type=caldav", @@ -126,19 +120,18 @@ calDavCalendar.prototype = { mLastRedirectStatus: null, ensureTargetCalendar: function() { if (!this.isCached && !this.mOfflineStorage) { // If this is a cached calendar, the actual cache is taken care of // by the calCachedCalendar facade. In any other case, we use a // memory calendar to cache things. - this.mOfflineStorage = Components - .classes["@mozilla.org/calendar/calendar;1?type=memory"] - .createInstance(Components.interfaces.calISyncWriteCalendar); + this.mOfflineStorage = Cc["@mozilla.org/calendar/calendar;1?type=memory"] + .createInstance(Ci.calISyncWriteCalendar); this.mOfflineStorage.superCalendar = this; this.mObserver = new calDavObserver(this); this.mOfflineStorage.addObserver(this.mObserver); this.mOfflineStorage.setProperty("relaxedMode", true); } }, @@ -256,17 +249,17 @@ calDavCalendar.prototype = { /** * Ensure that cached items have associated meta data, otherwise server side * changes may not be reflected */ ensureMetaData: function() { let self = this; let refreshNeeded = false; let getMetaListener = { - QueryInterface: XPCOMUtils.generateQI([Components.interfaces.calIOperationListener]), + QueryInterface: XPCOMUtils.generateQI([Ci.calIOperationListener]), onGetResult: function(aCalendar, aStatus, aItemType, aDetail, aCount, aItems) { for (let item of aItems) { if (!(item.id in self.mItemInfoCache)) { let path = self.getItemLocationPath(item); cal.LOG("Adding meta-data for cached item " + item.id); self.mItemInfoCache[item.id] = { etag: null, isNew: false, @@ -282,17 +275,17 @@ calDavCalendar.prototype = { if (refreshNeeded) { // reseting the cached ctag forces an item refresh when // safeRefresh is called later self.mCtag = null; self.mProposedCtag = null; } } }; - this.mOfflineStorage.getItems(calICalendar.ITEM_FILTER_ALL_ITEMS, + this.mOfflineStorage.getItems(Ci.calICalendar.ITEM_FILTER_ALL_ITEMS, 0, null, null, getMetaListener); }, fetchCachedMetaData: function() { cal.LOG("CalDAV: Retrieving server info from cache for " + this.name); let cacheIds = {}; let cacheValues = {}; this.mOfflineStorage.getAllMetaData({}, cacheIds, cacheValues); @@ -306,17 +299,17 @@ calDavCalendar.prototype = { this.mCtag = itemData; this.mProposedCtag = null; this.mOfflineStorage.deleteMetaData("ctag"); } else if (itemId == "webdav-sync-token") { this.mWebdavSyncToken = itemData; this.mOfflineStorage.deleteMetaData("sync-token"); } else if (itemId == "calendar-properties") { this.restoreCalendarProperties(itemData); - this.setProperty("currentStatus", Components.results.NS_OK); + this.setProperty("currentStatus", Cr.NS_OK); if (this.mHaveScheduling || this.hasAutoScheduling || this.hasFreeBusy) { cal.getFreeBusyService().addProvider(this); } } else { let itemDataArray = itemData.split("\u001A"); let etag = itemDataArray[0]; let resourcePath = itemDataArray[1]; let isInboxItem = itemDataArray[2]; @@ -335,17 +328,17 @@ calDavCalendar.prototype = { } } this.ensureMetaData(); }, sendHttpRequest: function(aUri, aUploadData, aContentType, aExisting, aSetupChannelFunc, aFailureFunc, aUseStreamLoader=true) { function oauthCheck(nextMethod, loaderOrRequest /* either the nsIStreamLoader or nsIRequestObserver parameters */) { - let request = (loaderOrRequest.request || loaderOrRequest).QueryInterface(Components.interfaces.nsIHttpChannel); + let request = (loaderOrRequest.request || loaderOrRequest).QueryInterface(Ci.nsIHttpChannel); let error = false; try { let wwwauth = request.getResponseHeader("WWW-Authenticate"); if (wwwauth.startsWith("Bearer") && wwwauth.includes("error=")) { // An OAuth error occurred, we need to reauthenticate. error = true; } } catch (e) { @@ -564,17 +557,17 @@ calDavCalendar.prototype = { if (this.calendarUserAddress) { return this.calendarUserAddress; } // else use configured email identity break; case "organizerCN": return null; // xxx todo case "itip.transport": if (this.hasAutoScheduling || this.hasScheduling) { - return this.QueryInterface(Components.interfaces.calIItipTransport); + return this.QueryInterface(Ci.calIItipTransport); } // else use outbound email-based iTIP (from cal.provider.BaseClass) break; case "capabilities.tasks.supported": return this.supportedItemTypes.includes("VTODO"); case "capabilities.events.supported": return this.supportedItemTypes.includes("VEVENT"); case "capabilities.autoschedule.supported": return this.hasAutoScheduling; @@ -633,40 +626,40 @@ calDavCalendar.prototype = { let method = pure ? "notifyPureOperationComplete" : "notifyOperationComplete"; this[method](aListener, status, cIOL.ADD, aItem.id, detail); }; if (aItem.id == null && aItem.isMutable) { aItem.id = cal.getUUID(); } if (aItem.id == null) { - notifyListener(Components.results.NS_ERROR_FAILURE, + notifyListener(Cr.NS_ERROR_FAILURE, "Can't set ID on non-mutable item to addItem"); return; } if (!cal.item.isItemSupported(aItem, this)) { - notifyListener(Components.results.NS_ERROR_FAILURE, + notifyListener(Cr.NS_ERROR_FAILURE, "Server does not support item type"); return; } let parentItem = aItem.parentItem; parentItem.calendar = this.superCalendar; let locationPath = this.getItemLocationPath(parentItem); let itemUri = this.makeUri(locationPath); cal.LOG("CalDAV: itemUri.spec = " + itemUri.spec); let self = this; let serializedItem = this.getSerializedItem(aItem); let addListener = { onStreamComplete: function(aLoader, aContext, aStatus, aResultLength, aResult) { - let request = aLoader.request.QueryInterface(Components.interfaces.nsIHttpChannel); - let listenerStatus = Components.results.NS_OK; + let request = aLoader.request.QueryInterface(Ci.nsIHttpChannel); + let listenerStatus = Cr.NS_OK; let listenerDetail = parentItem; let responseStatus; try { responseStatus = request.responseStatus; if (self.verboseLogging()) { let str = new TextDecoder().decode(Uint8Array.from(aResult)); cal.LOG("CalDAV: recv: " + (str || "")); @@ -693,46 +686,46 @@ calDavCalendar.prototype = { // Some CalDAV servers will modify items on PUT (add X-props, // for instance) so we'd best re-fetch in order to know // the current state of the item // Observers will be notified in getUpdatedItem() self.getUpdatedItem(parentItem, aListener); return; } else if (responseStatus >= 500 && responseStatus <= 510) { - listenerStatus = Components.results.NS_ERROR_NOT_AVAILABLE; + listenerStatus = Cr.NS_ERROR_NOT_AVAILABLE; listenerDetail = "Server Replied with " + responseStatus; } else if (responseStatus) { // There is a response status, but we haven't handled it yet. Any // error occurring here should consider being handled! cal.ERROR("CalDAV: Unexpected status adding item to " + self.name + ": " + responseStatus + "\n" + serializedItem); - listenerStatus = Components.results.NS_ERROR_FAILURE; + listenerStatus = Cr.NS_ERROR_FAILURE; listenerDetail = "Server Replied with " + responseStatus; } // Still need to visually notify for uncached calendars. if (!self.isCached && !Components.isSuccessCode(listenerStatus)) { - self.reportDavError(calIErrors.DAV_PUT_ERROR, listenerStatus, listenerDetail); + self.reportDavError(Ci.calIErrors.DAV_PUT_ERROR, listenerStatus, listenerDetail); } // Finally, notify listener. notifyListener(listenerStatus, listenerDetail, true); } }; this.sendHttpRequest(itemUri, serializedItem, MIME_TEXT_CALENDAR, null, (channel) => { if (!aIgnoreEtag) { channel.setRequestHeader("If-None-Match", "*", false); } return addListener; }, () => { - notifyListener(Components.results.NS_ERROR_NOT_AVAILABLE, + notifyListener(Cr.NS_ERROR_NOT_AVAILABLE, "Error preparing http channel"); }); }, /** * modifyItem(); required by calICalendar.idl * we actually use doModifyItem() * @@ -752,17 +745,17 @@ calDavCalendar.prototype = { * @param aIgnoreEtag ignore item etag */ doModifyItem: function(aNewItem, aOldItem, aListener, aIgnoreEtag) { let notifyListener = (status, detail, pure=false) => { let method = pure ? "notifyPureOperationComplete" : "notifyOperationComplete"; this[method](aListener, status, cIOL.MODIFY, aNewItem.id, detail); }; if (aNewItem.id == null) { - notifyListener(Components.results.NS_ERROR_FAILURE, + notifyListener(Cr.NS_ERROR_FAILURE, "ID for modifyItem doesn't exist or is null"); return; } let wasInboxItem = this.mItemInfoCache[aNewItem.id].isInboxItem; let newItem_ = aNewItem; aNewItem = aNewItem.parentItem.clone(); @@ -774,18 +767,18 @@ calDavCalendar.prototype = { let eventUri = this.makeUri(this.mItemInfoCache[aNewItem.id].locationPath); let self = this; let modifiedItemICS = this.getSerializedItem(aNewItem); let modListener = { onStreamComplete: function(aLoader, aContext, aStatus, aResultLength, aResult) { - let request = aLoader.request.QueryInterface(Components.interfaces.nsIHttpChannel); - let listenerStatus = Components.results.NS_OK; + let request = aLoader.request.QueryInterface(Ci.nsIHttpChannel); + let listenerStatus = Cr.NS_OK; let listenerDetail = aNewItem; let responseStatus; try { responseStatus = request.responseStatus; if (self.verboseLogging()) { let str = new TextDecoder().decode(Uint8Array.from(aResult)); cal.LOG("CalDAV: recv: " + (str || "")); @@ -815,47 +808,47 @@ calDavCalendar.prototype = { } return; } else if (responseStatus == 412 || responseStatus == 409) { // promptOverwrite will ask the user and then re-request self.promptOverwrite(CALDAV_MODIFY_ITEM, aNewItem, aListener, aOldItem); return; } else if (responseStatus >= 500 && responseStatus <= 510) { - listenerStatus = Components.results.NS_ERROR_NOT_AVAILABLE; + listenerStatus = Cr.NS_ERROR_NOT_AVAILABLE; listenerDetail = "Server Replied with " + responseStatus; } else if (responseStatus) { // There is a response status, but we haven't handled it yet. Any // error occurring here should consider being handled! cal.ERROR("CalDAV: Unexpected status modifying item to " + self.name + ": " + responseStatus + "\n" + modifiedItemICS); - listenerStatus = Components.results.NS_ERROR_FAILURE; + listenerStatus = Cr.NS_ERROR_FAILURE; listenerDetail = "Server Replied with " + responseStatus; } // Still need to visually notify for uncached calendars. if (!self.isCached && !Components.isSuccessCode(listenerStatus)) { - self.reportDavError(calIErrors.DAV_PUT_ERROR, listenerStatus, listenerDetail); + self.reportDavError(Ci.calIErrors.DAV_PUT_ERROR, listenerStatus, listenerDetail); } notifyListener(listenerStatus, listenerDetail, true); } }; this.sendHttpRequest(eventUri, modifiedItemICS, MIME_TEXT_CALENDAR, null, (channel) => { if (!aIgnoreEtag) { channel.setRequestHeader("If-Match", this.mItemInfoCache[aNewItem.id].etag, false); } return modListener; }, () => { - notifyListener(Components.results.NS_ERROR_NOT_AVAILABLE, + notifyListener(Cr.NS_ERROR_NOT_AVAILABLE, "Error preparing http channel"); }); }, /** * deleteItem(); required by calICalendar.idl * the actual deletion is done in doDeleteItem() * @@ -877,43 +870,43 @@ calDavCalendar.prototype = { * */ doDeleteItem: function(aItem, aListener, aIgnoreEtag, aFromInbox, aUri) { let notifyListener = (status, detail, pure=false) => { let method = pure ? "notifyPureOperationComplete" : "notifyOperationComplete"; this[method](aListener, status, cIOL.DELETE, aItem.id, detail); }; if (aItem.id == null) { - notifyListener(Components.results.NS_ERROR_FAILURE, + notifyListener(Cr.NS_ERROR_FAILURE, "ID doesn't exist for deleteItem"); return; } let eventUri; if (aUri) { eventUri = aUri; } else if (aFromInbox || this.mItemInfoCache[aItem.id].isInboxItem) { eventUri = this.makeUri(this.mItemInfoCache[aItem.id].locationPath, this.mInboxUrl); } else { eventUri = this.makeUri(this.mItemInfoCache[aItem.id].locationPath); } if (eventUri.path == this.calendarUri.path) { - notifyListener(Components.results.NS_ERROR_FAILURE, + notifyListener(Cr.NS_ERROR_FAILURE, "eventUri and calendarUri paths are the same, " + "will not go on to delete entire calendar"); return; } let self = this; let delListener = { onStreamComplete: function(aLoader, aContext, aStatus, aResultLength, aResult) { - let request = aLoader.request.QueryInterface(Components.interfaces.nsIHttpChannel); - let listenerStatus = Components.results.NS_OK; + let request = aLoader.request.QueryInterface(Ci.nsIHttpChannel); + let listenerStatus = Cr.NS_OK; let listenerDetail = aItem; let responseStatus; try { responseStatus = request.responseStatus; if (self.verboseLogging()) { let str = new TextDecoder().decode(Uint8Array.from(aResult)); cal.LOG("CalDAV: recv: " + (str || "")); @@ -944,46 +937,46 @@ calDavCalendar.prototype = { } } else if (responseStatus == 412 || responseStatus == 409) { // item has either been modified or deleted by someone else check to see which cal.LOG("CalDAV: Item has been modified on server, checking if it has been deleted"); self.sendHttpRequest(eventUri, null, null, null, (channel) => { channel.requestMethod = "HEAD"; return delListener2; }, () => { - notifyListener(Components.results.NS_ERROR_NOT_AVAILABLE, + notifyListener(Cr.NS_ERROR_NOT_AVAILABLE, "Error preparing http channel"); }); return; } else if (responseStatus >= 500 && responseStatus <= 510) { - listenerStatus = Components.results.NS_ERROR_NOT_AVAILABLE; + listenerStatus = Cr.NS_ERROR_NOT_AVAILABLE; listenerDetail = "Server Replied with " + responseStatus; } else if (responseStatus) { cal.ERROR("CalDAV: Unexpected status deleting item from " + self.name + ": " + responseStatus + "\n" + "uri: " + eventUri.spec); - listenerStatus = Components.results.NS_ERROR_FAILURE; + listenerStatus = Cr.NS_ERROR_FAILURE; listenerDetail = "Server Replied with " + responseStatus; } // Still need to visually notify for uncached calendars. if (!self.isCached && !Components.isSuccessCode(listenerStatus)) { - self.reportDavError(calIErrors.DAV_REMOVE_ERROR, listenerStatus, listenerDetail); + self.reportDavError(Ci.calIErrors.DAV_REMOVE_ERROR, listenerStatus, listenerDetail); } // Finally, notify listener. notifyListener(listenerStatus, listenerDetail); } }; let delListener2 = { onStreamComplete: function(aLoader, aContext, aStatus, aResultLength, aResult) { - let request = aLoader.request.QueryInterface(Components.interfaces.nsIHttpChannel); - let listenerStatus = Components.results.NS_OK; + let request = aLoader.request.QueryInterface(Ci.nsIHttpChannel); + let listenerStatus = Cr.NS_OK; let listenerDetail = aItem; let responseStatus; try { responseStatus = request.responseStatus; if (self.verboseLogging()) { let str = new TextDecoder().decode(Uint8Array.from(aResult)); cal.LOG("CalDAV: recv: " + (str || "")); @@ -993,17 +986,17 @@ calDavCalendar.prototype = { listenerDetail = "Request Failed: " + ex.message; cal.LOG("CalDAV: Request error during add: " + ex); } if (responseStatus == 404) { // Nothing to do (except notify the listener below) // Someone else has already deleted it } else if (responseStatus >= 500 && responseStatus <= 510) { - listenerStatus = Components.results.NS_ERROR_NOT_AVAILABLE; + listenerStatus = Cr.NS_ERROR_NOT_AVAILABLE; listenerDetail = "Server Replied with " + responseStatus; } else if (responseStatus) { // The item still exists. We need to ask the user if he // really wants to delete the item. Remember, we only // made this request since the actual delete gave 409/412 self.promptOverwrite(CALDAV_DELETE_ITEM, aItem, aListener, null); return; } @@ -1021,32 +1014,32 @@ calDavCalendar.prototype = { if (!aIgnoreEtag) { let etag = this.mItemInfoCache[aItem.id].etag; cal.LOG("CalDAV: Will only delete if matches etag " + etag); channel.setRequestHeader("If-Match", etag, false); } channel.requestMethod = "DELETE"; return delListener; }, () => { - notifyListener(Components.results.NS_ERROR_NOT_AVAILABLE, + notifyListener(Cr.NS_ERROR_NOT_AVAILABLE, "Error preparing http channel"); }); }, /** * Add an item to the target calendar * * @param path Item path MUST NOT BE ENCODED * @param calData iCalendar string representation of the item * @param aUri Base URI of the request * @param aListener Listener */ addTargetCalendarItem: function(path, calData, aUri, etag, aListener) { - let parser = Components.classes["@mozilla.org/calendar/ics-parser;1"] - .createInstance(Components.interfaces.calIIcsParser); + let parser = Cc["@mozilla.org/calendar/ics-parser;1"] + .createInstance(Ci.calIIcsParser); // aUri.path may contain double slashes whereas path does not // this confuses our counting, so remove multiple successive slashes let strippedUriPath = aUri.path.replace(/\/{2,}/g, "/"); let uriPathComponentLength = strippedUriPath.split("/").length; try { parser.parseString(calData); } catch (e) { // Warn and continue. @@ -1117,23 +1110,23 @@ calDavCalendar.prototype = { // If we have a listener, then the caller will take care of adding the item // Otherwise, we have to do it ourself // XXX This is quite fragile, but saves us a double modify/add if (aListener) { // In the cached case, notifying operation complete will add the item to the cache if (this.mItemInfoCache[item.id].isNew) { this.notifyOperationComplete(aListener, - Components.results.NS_OK, + Cr.NS_OK, cIOL.ADD, item.id, item); } else { this.notifyOperationComplete(aListener, - Components.results.NS_OK, + Cr.NS_OK, cIOL.MODIFY, item.id, item); } } else { // No listener, we'll have to add it ourselves needsAddModify = true; } @@ -1184,18 +1177,17 @@ calDavCalendar.prototype = { */ finalizeUpdatedItems: function(aChangeLogListener, calendarURI) { cal.LOG("aChangeLogListener=" + aChangeLogListener + "\n" + "calendarURI=" + (calendarURI ? calendarURI.spec : "undefined") + " \n" + "iscached=" + this.isCached + "\n" + "this.mQueuedQueries.length=" + this.mQueuedQueries.length); if (this.isCached) { if (aChangeLogListener) { - aChangeLogListener.onResult({ status: Components.results.NS_OK }, - Components.results.NS_OK); + aChangeLogListener.onResult({ status: Cr.NS_OK }, Cr.NS_OK); } } else { this.mObservers.notify("onLoad", [this]); } if (this.mProposedCtag) { this.mCtag = this.mProposedCtag; this.mProposedCtag = null; @@ -1219,33 +1211,32 @@ calDavCalendar.prototype = { * @param aListener (optional) Listener of the request * @param aChangeLogListener (optional)Listener for cached calendars */ notifyGetFailed: function(errorMsg, aListener, aChangeLogListener) { cal.WARN("CalDAV: Get failed: " + errorMsg); // Notify changelog listener if (this.isCached && aChangeLogListener) { - aChangeLogListener.onResult({ status: Components.results.NS_ERROR_FAILURE }, - Components.results.NS_ERROR_FAILURE); + aChangeLogListener.onResult({ status: Cr.NS_ERROR_FAILURE }, Cr.NS_ERROR_FAILURE); } // Notify operation listener this.notifyOperationComplete(aListener, - Components.results.NS_ERROR_FAILURE, + Cr.NS_ERROR_FAILURE, cIOL.GET, null, errorMsg); // If an error occurrs here, we also need to unqueue the // requests previously queued. while (this.mQueuedQueries.length) { let [, , , , listener] = this.mQueuedQueries.pop(); try { listener.onOperationComplete(this.superCalendar, - Components.results.NS_ERROR_FAILURE, + Cr.NS_ERROR_FAILURE, cIOL.GET, null, errorMsg); } catch (e) { cal.ERROR(e); } } }, @@ -1255,17 +1246,17 @@ calDavCalendar.prototype = { * Use when an outdated copy of the item is in hand. * * @param aItem item to fetch * @param aListener listener for method completion */ getUpdatedItem: function(aItem, aListener, aChangeLogListener) { if (aItem == null) { this.notifyOperationComplete(aListener, - Components.results.NS_ERROR_FAILURE, + Cr.NS_ERROR_FAILURE, cIOL.GET, null, "passed in null item"); return; } let locationPath = this.getItemLocationPath(aItem); let itemUri = this.makeUri(locationPath); @@ -1289,17 +1280,17 @@ calDavCalendar.prototype = { // in calIDateTime aRangeStart, in calIDateTime aRangeEnd, // in calIOperationListener aListener ); getItems: function(aItemFilter, aCount, aRangeStart, aRangeEnd, aListener) { if (this.isCached) { if (this.mOfflineStorage) { this.mOfflineStorage.getItems(...arguments); } else { this.notifyOperationComplete(aListener, - Components.results.NS_OK, + Cr.NS_OK, cIOL.GET, null, null); } } else if (this.checkedServerInfo) { this.mOfflineStorage.getItems(...arguments); } else { this.mQueuedQueries.push(Array.from(arguments)); @@ -1328,17 +1319,17 @@ calDavCalendar.prototype = { if (this.isCached && aChangeLogListener) { aChangeLogListener.onResult({ status: status }, status); } }; if (!this.mACLEntry) { let self = this; let opListener = { - QueryInterface: XPCOMUtils.generateQI([Components.interfaces.calIOperationListener]), + QueryInterface: XPCOMUtils.generateQI([Ci.calIOperationListener]), onGetResult: function(calendar, status, itemType, detail, count, items) { cal.ASSERT(false, "unexpected!"); }, onOperationComplete: function(opCalendar, opStatus, opType, opId, opDetail) { self.mACLEntry = opDetail; self.fillACLProperties(); self.safeRefresh(aChangeLogListener); } @@ -1353,24 +1344,24 @@ calDavCalendar.prototype = { if (this.mAuthScheme == "Digest") { // the auth could have timed out and be in need of renegotiation // we can't risk several calendars doing this simultaneously so // we'll force the renegotiation in a sync query, using OPTIONS to keep // it quick let headchannel = cal.provider.prepHttpChannel(this.makeUri(), null, null, this); headchannel.requestMethod = "OPTIONS"; headchannel.open(); - headchannel.QueryInterface(Components.interfaces.nsIHttpChannel); + headchannel.QueryInterface(Ci.nsIHttpChannel); try { if (headchannel.responseStatus != 200) { throw "OPTIONS returned unexpected status code: " + headchannel.responseStatus; } } catch (e) { cal.WARN("CalDAV: Exception: " + e); - notifyListener(Components.results.NS_ERROR_FAILURE); + notifyListener(Cr.NS_ERROR_FAILURE); } } // Call getUpdatedItems right away if its the first refresh // *OR* if webdav Sync is enabled (It is redundant to send a request // to get the collection tag (getctag) on a calendar if it supports // webdav sync, the sync request will only return data if something // changed). @@ -1388,31 +1379,31 @@ calDavCalendar.prototype = { ""; if (this.verboseLogging()) { cal.LOG("CalDAV: send(" + this.makeUri().spec + "): " + queryXml); } let streamListener = {}; streamListener.onStreamComplete = function(aLoader, aContext, aStatus, aResultLength, aResult) { - let request = aLoader.request.QueryInterface(Components.interfaces.nsIHttpChannel); + let request = aLoader.request.QueryInterface(Ci.nsIHttpChannel); try { cal.LOG("CalDAV: Status " + request.responseStatus + " checking ctag for calendar " + self.name); } catch (ex) { cal.LOG("CalDAV: Error without status on checking ctag for calendar " + self.name); - notifyListener(Components.results.NS_OK); + notifyListener(Cr.NS_OK); return; } if (request.responseStatus == 404) { cal.LOG("CalDAV: Disabling calendar " + self.name + " due to 404"); - notifyListener(Components.results.NS_ERROR_FAILURE); + notifyListener(Cr.NS_ERROR_FAILURE); return; } else if (request.responseStatus == 207 && self.mDisabled) { // Looks like the calendar is there again, check its resource // type first. self.setupAuthentication(aChangeLogListener); return; } @@ -1425,17 +1416,17 @@ calDavCalendar.prototype = { } let multistatus; try { multistatus = cal.xml.parseString(str); } catch (ex) { cal.LOG("CalDAV: Failed to get ctag from server for calendar " + self.name); - notifyListener(Components.results.NS_OK); + notifyListener(Cr.NS_OK); return; } let ctag = caldavXPathFirst(multistatus, "/D:multistatus/D:response/D:propstat/D:prop/CS:getctag/text()"); if (!ctag || ctag != self.mCtag) { // ctag mismatch, need to fetch calendar-data self.mProposedCtag = ctag; self.getUpdatedItems(self.calendarUri, aChangeLogListener); @@ -1445,31 +1436,31 @@ calDavCalendar.prototype = { } } else { if (self.verboseLogging()) { cal.LOG("CalDAV: ctag matches, no need to fetch data for " + "calendar " + self.name); } // Notify the listener, but don't return just yet... - notifyListener(Components.results.NS_OK); + notifyListener(Cr.NS_OK); // ...we may still need to poll the inbox if (self.firstInRealm()) { self.pollInbox(); } } }; this.sendHttpRequest(this.makeUri(), queryXml, MIME_TEXT_XML, null, (channel) => { channel.setRequestHeader("Depth", "0", false); channel.requestMethod = "PROPFIND"; return streamListener; }, () => { - notifyListener(Components.results.NS_ERROR_NOT_AVAILABLE); + notifyListener(Cr.NS_ERROR_NOT_AVAILABLE); }); }, refresh: function() { this.replayChangesOn(null); }, firstInRealm: function() { @@ -1534,18 +1525,17 @@ calDavCalendar.prototype = { } this.sendHttpRequest(requestUri, queryXml, MIME_TEXT_XML, null, (channel) => { channel.requestMethod = "PROPFIND"; channel.setRequestHeader("Depth", "1", false); return new etagsHandler(this, aUri, aChangeLogListener); }, () => { if (aChangeLogListener && this.isCached) { - aChangeLogListener.onResult({ status: Components.results.NS_ERROR_NOT_AVAILABLE }, - Components.results.NS_ERROR_NOT_AVAILABLE); + aChangeLogListener.onResult({ status: Cr.NS_ERROR_NOT_AVAILABLE }, Cr.NS_ERROR_NOT_AVAILABLE); } }, false); }, /** * @see nsIInterfaceRequestor * @see calProviderUtils.jsm */ @@ -1571,17 +1561,17 @@ calDavCalendar.prototype = { setupAuthentication: function(aChangeLogListener) { let self = this; function authSuccess() { self.checkDavResourceType(aChangeLogListener); } function authFailed() { self.setProperty("disabled", "true"); self.setProperty("auto-enabled", "true"); - self.completeCheckServerInfo(aChangeLogListener, Components.results.NS_ERROR_FAILURE); + self.completeCheckServerInfo(aChangeLogListener, Cr.NS_ERROR_FAILURE); } function connect() { // Use the async prompter to avoid multiple master password prompts let promptlistener = { onPromptStart: function() { // Usually this function should be synchronous. The OAuth // connection itself is asynchronous, but if a master // password is prompted it will block on that. @@ -1589,18 +1579,18 @@ calDavCalendar.prototype = { return true; }, onPromptAuthAvailable: function() { self.oauth.connect(authSuccess, authFailed, true); }, onPromptCanceled: authFailed }; - let asyncprompter = Components.classes["@mozilla.org/messenger/msgAsyncPrompter;1"] - .getService(Components.interfaces.nsIMsgAsyncPrompter); + let asyncprompter = Cc["@mozilla.org/messenger/msgAsyncPrompter;1"] + .getService(Ci.nsIMsgAsyncPrompter); asyncprompter.queueAsyncAuthPrompt(self.uri.spec, false, promptlistener); } if (this.mUri.host == "apidata.googleusercontent.com") { if (!this.oauth) { let sessionId = this.id; let pwMgrId = "Google CalDAV v2"; let authTitle = cal.l10n.getAnyString( "global", "commonDialogs", "EnterUserPasswordFor2", [this.name] @@ -1621,17 +1611,17 @@ calDavCalendar.prototype = { get: function() { if (!this.mRefreshToken) { let pass = { value: null }; try { let origin = "oauth:" + sessionId; cal.auth.passwordManagerGet(sessionId, pass, origin, pwMgrId); } catch (e) { // User might have cancelled the master password prompt, thats ok - if (e.result != Components.results.NS_ERROR_ABORT) { + if (e.result != Cr.NS_ERROR_ABORT) { throw e; } } this.mRefreshToken = pass.value; } return this.mRefreshToken; }, set: function(val) { @@ -1640,18 +1630,18 @@ calDavCalendar.prototype = { if (val) { cal.auth.passwordManagerSave(sessionId, val, origin, pwMgrId); } else { cal.auth.passwordManagerRemove(sessionId, origin, pwMgrId); } } catch (e) { // User might have cancelled the master password prompt, or password saving // could be disabled. That is ok, throw for everything else. - if (e.result != Components.results.NS_ERROR_ABORT && - e.result != Components.results.NS_ERROR_NOT_AVAILABLE) { + if (e.result != Cr.NS_ERROR_ABORT && + e.result != Cr.NS_ERROR_NOT_AVAILABLE) { throw e; } } return (this.mRefreshToken = val); }, enumerable: true }); } @@ -1707,36 +1697,35 @@ calDavCalendar.prototype = { ""; if (this.verboseLogging()) { cal.LOG("CalDAV: send: " + queryXml); } let streamListener = {}; streamListener.onStreamComplete = function(aLoader, aContext, aStatus, aResultLength, aResult) { - let request = aLoader.request.QueryInterface(Components.interfaces.nsIHttpChannel); + let request = aLoader.request.QueryInterface(Ci.nsIHttpChannel); try { cal.LOG("CalDAV: Status " + request.responseStatus + " on initial PROPFIND for calendar " + self.name); } catch (ex) { cal.LOG("CalDAV: Error without status on initial PROPFIND for calendar " + self.name); - self.completeCheckServerInfo(aChangeLogListener, - Components.interfaces.calIErrors.DAV_NOT_DAV); + self.completeCheckServerInfo(aChangeLogListener, Ci.calIErrors.DAV_NOT_DAV); return; } let isText = true; if ((isText || request.URI.spec != request.originalURI.spec) && self.mLastRedirectStatus == 301) { // The initial PROPFIND essentially goes against the calendar // collection url. If a 301 Moved Permanently redirect occurred // here, we want to modify the url we use in the future. - let nIPS = Components.interfaces.nsIPromptService; + let nIPS = Ci.nsIPromptService; let promptTitle = cal.l10n.getCalString("caldavRedirectTitle", [self.name]); let promptText = cal.l10n.getCalString("caldavRedirectText", [self.name]) + "\n\n" + request.URI.spec; let button1Title = cal.l10n.getCalString("caldavRedirectDisableCalendar"); let flags = (nIPS.BUTTON_TITLE_YES * nIPS.BUTTON_POS_0) + (nIPS.BUTTON_TITLE_IS_STRING * nIPS.BUTTON_POS_1); @@ -1748,39 +1737,39 @@ calDavCalendar.prototype = { if (res == 0) { // YES let newUri = request.URI; cal.LOG("CalDAV: Migrating url due to redirect: " + self.mUri.spec + " -> " + newUri.spec); self.mUri = newUri; self.setProperty("uri", newUri.spec); } else if (res == 1) { // DISABLE CALENDAR self.setProperty("disabled", "true"); - self.completeCheckServerInfo(aChangeLogListener, Components.results.NS_ERROR_ABORT); + self.completeCheckServerInfo(aChangeLogListener, Cr.NS_ERROR_ABORT); return; } } let responseStatusCategory = Math.floor(request.responseStatus / 100); // 4xx codes, which is either an authentication failure or // something like method not allowed. This is a failure worth // disabling the calendar. if (responseStatusCategory == 4) { self.setProperty("disabled", "true"); self.setProperty("auto-enabled", "true"); - self.completeCheckServerInfo(aChangeLogListener, Components.results.NS_ERROR_ABORT); + self.completeCheckServerInfo(aChangeLogListener, Cr.NS_ERROR_ABORT); return; } // 5xx codes, a server error. This could be a temporary failure, // i.e a backend server being disabled. if (responseStatusCategory == 5) { cal.LOG("CalDAV: Server not available " + request.responseStatus + ", abort sync for calendar " + self.name); - self.completeCheckServerInfo(aChangeLogListener, Components.results.NS_ERROR_ABORT); + self.completeCheckServerInfo(aChangeLogListener, Cr.NS_ERROR_ABORT); return; } let wwwauth; try { wwwauth = request.getRequestHeader("Authorization"); self.mAuthScheme = wwwauth.split(" ")[0]; } catch (ex) { @@ -1801,31 +1790,29 @@ calDavCalendar.prototype = { cal.LOG("CalDAV: realm " + self.mAuthRealm); } let str = new TextDecoder().decode(Uint8Array.from(aResult)); if (!str || request.responseStatus == 404) { // No response, or the calendar no longer exists. cal.LOG("CalDAV: Failed to determine resource type for" + self.name); - self.completeCheckServerInfo(aChangeLogListener, - Components.interfaces.calIErrors.DAV_NOT_DAV); + self.completeCheckServerInfo(aChangeLogListener, Ci.calIErrors.DAV_NOT_DAV); return; } else if (self.verboseLogging()) { cal.LOG("CalDAV: recv: " + str); } let multistatus; try { multistatus = cal.xml.parseString(str); } catch (ex) { cal.LOG("CalDAV: Failed to determine resource type for" + self.name + ": " + ex); - self.completeCheckServerInfo(aChangeLogListener, - Components.interfaces.calIErrors.DAV_NOT_DAV); + self.completeCheckServerInfo(aChangeLogListener, Ci.calIErrors.DAV_NOT_DAV); return; } // check for webdav-sync capability // http://tools.ietf.org/html/draft-daboo-webdav-sync if (caldavXPath(multistatus, "/D:multistatus/D:response/D:propstat/D:prop" + "/D:supported-report-set/D:supported-report/D:report/D:sync-collection")) { cal.LOG("CalDAV: Collection has webdav sync support"); @@ -1880,50 +1867,48 @@ calDavCalendar.prototype = { } else if (caldavXPath(resourceTypeXml[0], "C:calendar")) { resourceType = kDavResourceTypeCalendar; } else if (caldavXPath(resourceTypeXml[0], "D:collection")) { resourceType = kDavResourceTypeCollection; } if (resourceType == kDavResourceTypeNone) { cal.LOG("CalDAV: No resource type received, " + self.name + " doesn't seem to point to a DAV resource"); - self.completeCheckServerInfo(aChangeLogListener, - Components.interfaces.calIErrors.DAV_NOT_DAV); + self.completeCheckServerInfo(aChangeLogListener, Ci.calIErrors.DAV_NOT_DAV); return; } if (resourceType == kDavResourceTypeCollection) { cal.LOG("CalDAV: " + self.name + " points to a DAV resource, but not a CalDAV calendar"); - self.completeCheckServerInfo(aChangeLogListener, - Components.interfaces.calIErrors.DAV_DAV_NOT_CALDAV); + self.completeCheckServerInfo(aChangeLogListener, Ci.calIErrors.DAV_DAV_NOT_CALDAV); return; } if (resourceType == kDavResourceTypeCalendar) { // If this calendar was previously offline we want to recover if (self.mDisabled) { self.mDisabled = false; self.mReadOnly = false; } self.setCalHomeSet(true); self.checkServerCaps(aChangeLogListener); return; } // If we get here something must have gone wrong. Abort with a // general error to avoid an endless loop. - self.completeCheckServerInfo(aChangeLogListener, Components.results.NS_ERROR_FAILURE); + self.completeCheckServerInfo(aChangeLogListener, Cr.NS_ERROR_FAILURE); }; this.sendHttpRequest(this.makeUri(), queryXml, MIME_TEXT_XML, null, (channel) => { channel.setRequestHeader("Depth", "0", false); channel.requestMethod = "PROPFIND"; return streamListener; }, () => { - notifyListener(Components.results.NS_ERROR_NOT_AVAILABLE, + notifyListener(Cr.NS_ERROR_NOT_AVAILABLE, "Error preparing http channel"); }); }, /** * Checks server capabilities. * * setupAuthentication @@ -1938,28 +1923,28 @@ calDavCalendar.prototype = { let self = this; if (this.verboseLogging()) { cal.LOG("CalDAV: send: OPTIONS " + homeSet.spec); } let streamListener = {}; streamListener.onStreamComplete = function(aLoader, aContext, aStatus, aResultLength, aResult) { - let request = aLoader.request.QueryInterface(Components.interfaces.nsIHttpChannel); + let request = aLoader.request.QueryInterface(Ci.nsIHttpChannel); if (request.responseStatus != 200 && request.responseStatus != 204) { if (!calHomeSetUrlRetry && request.responseStatus == 404) { // try again with calendar URL, see https://bugzilla.mozilla.org/show_bug.cgi?id=588799 cal.LOG("CalDAV: Calendar homeset was not found at parent url of calendar URL" + " while querying options " + self.name + ", will try calendar URL itself now"); self.setCalHomeSet(false); self.checkServerCaps(aChangeLogListener, true); } else { cal.LOG("CalDAV: Unexpected status " + request.responseStatus + " while querying options " + self.name); - self.completeCheckServerInfo(aChangeLogListener, Components.results.NS_ERROR_FAILURE); + self.completeCheckServerInfo(aChangeLogListener, Cr.NS_ERROR_FAILURE); } // No further processing needed, we have called subsequent (async) functions above. return; } let dav = null; try { @@ -2012,17 +1997,17 @@ calDavCalendar.prototype = { self.completeCheckServerInfo(aChangeLogListener); } }; this.sendHttpRequest(homeSet, null, null, null, (channel) => { channel.requestMethod = "OPTIONS"; return streamListener; }, () => { - notifyListener(Components.results.NS_ERROR_NOT_AVAILABLE, + notifyListener(Cr.NS_ERROR_NOT_AVAILABLE, "Error preparing http channel"); }); }, /** * Locates the principal namespace. This function should soely be called * from checkServerCaps to find the principal namespace. * @@ -2052,42 +2037,39 @@ calDavCalendar.prototype = { "" + ""; if (this.verboseLogging()) { cal.LOG("CalDAV: send: " + homeSet.spec + "\n" + queryXml); } let streamListener = {}; streamListener.onStreamComplete = function(aLoader, aContext, aStatus, aResultLength, aResult) { - let request = aLoader.request.QueryInterface(Components.interfaces.nsIHttpChannel); + let request = aLoader.request.QueryInterface(Ci.nsIHttpChannel); if (request.responseStatus != 207) { cal.LOG("CalDAV: Unexpected status " + request.responseStatus + " while querying principal namespace for " + self.name); - self.completeCheckServerInfo(aChangeLogListener, - Components.results.NS_ERROR_FAILURE); + self.completeCheckServerInfo(aChangeLogListener, Cr.NS_ERROR_FAILURE); return; } let str = new TextDecoder().decode(Uint8Array.from(aResult)); if (!str) { cal.LOG("CalDAV: Failed to propstat principal namespace for " + self.name); - self.completeCheckServerInfo(aChangeLogListener, - Components.results.NS_ERROR_FAILURE); + self.completeCheckServerInfo(aChangeLogListener, Cr.NS_ERROR_FAILURE); return; } else if (self.verboseLogging()) { cal.LOG("CalDAV: recv: " + str); } let multistatus; try { multistatus = cal.xml.parseString(str); } catch (ex) { cal.LOG("CalDAV: Failed to propstat principal namespace for " + self.name); - self.completeCheckServerInfo(aChangeLogListener, - Components.results.NS_ERROR_FAILURE); + self.completeCheckServerInfo(aChangeLogListener, Cr.NS_ERROR_FAILURE); return; } let pcs = caldavXPath(multistatus, "/D:multistatus/D:response/D:propstat/D:prop/D:principal-collection-set/D:href/text()"); let nsList = []; if (pcs) { nsList = pcs.map(x => self.ensureDecodedPath(x)); } @@ -2095,17 +2077,17 @@ calDavCalendar.prototype = { self.checkPrincipalsNameSpace(nsList, aChangeLogListener); }; this.sendHttpRequest(homeSet, queryXml, MIME_TEXT_XML, null, (channel) => { channel.setRequestHeader("Depth", "0", false); channel.requestMethod = "PROPFIND"; return streamListener; }, () => { - notifyListener(Components.results.NS_ERROR_NOT_AVAILABLE); + notifyListener(Cr.NS_ERROR_NOT_AVAILABLE); }); }, /** * Checks the principals namespace for scheduling info. This function should * soely be called from findPrincipalNS * * setupAuthentication @@ -2177,17 +2159,17 @@ calDavCalendar.prototype = { let requestUri = Services.io.newURI(this.calendarUri.prePath + this.ensureEncodedPath(nextNS)); if (this.verboseLogging()) { cal.LOG("CalDAV: send: " + queryMethod + " " + requestUri.spec + "\n" + queryXml); } let streamListener = {}; streamListener.onStreamComplete = function(aLoader, aContext, aStatus, aResultLength, aResult) { - let request = aLoader.request.QueryInterface(Components.interfaces.nsIHttpChannel); + let request = aLoader.request.QueryInterface(Ci.nsIHttpChannel); let str = new TextDecoder().decode(Uint8Array.from(aResult)); if (!str) { cal.LOG("CalDAV: Failed to report principals namespace for " + self.name); doesntSupportScheduling(); return; } else if (self.verboseLogging()) { cal.LOG("CalDAV: recv: " + str); } @@ -2281,17 +2263,17 @@ calDavCalendar.prototype = { if (queryDepth == 0) { // Set header, doing this for Depth: 1 is not needed since thats the // default. channel.setRequestHeader("Depth", "0", false); } channel.requestMethod = queryMethod; return streamListener; }, () => { - notifyListener(Components.results.NS_ERROR_NOT_AVAILABLE); + notifyListener(Cr.NS_ERROR_NOT_AVAILABLE); }); }, /** * This is called to complete checking the server info. It should be the * final call when checking server options. This will either report the * error or if it is a success then refresh the calendar. * @@ -2302,66 +2284,65 @@ calDavCalendar.prototype = { * checkPrincipalsNameSpace * completeCheckServerInfo * You are here */ completeCheckServerInfo: function(aChangeLogListener, aError) { if (Components.isSuccessCode(aError)) { // "undefined" is a successcode, so all is good this.saveCalendarProperties(); this.checkedServerInfo = true; - this.setProperty("currentStatus", Components.results.NS_OK); + this.setProperty("currentStatus", Cr.NS_OK); if (this.isCached) { this.safeRefresh(aChangeLogListener); } else { this.refresh(); } } else { this.reportDavError(aError); if (this.isCached && aChangeLogListener) { - aChangeLogListener.onResult({ status: Components.results.NS_ERROR_FAILURE }, - Components.results.NS_ERROR_FAILURE); + aChangeLogListener.onResult({ status: Cr.NS_ERROR_FAILURE }, Cr.NS_ERROR_FAILURE); } } }, /** * Called to report a certain DAV error. Strings and modification type are * handled here. */ reportDavError: function(aErrNo, status, extraInfo) { let mapError = {}; - mapError[Components.interfaces.calIErrors.DAV_NOT_DAV] = "dav_notDav"; - mapError[Components.interfaces.calIErrors.DAV_DAV_NOT_CALDAV] = "dav_davNotCaldav"; - mapError[Components.interfaces.calIErrors.DAV_PUT_ERROR] = "itemPutError"; - mapError[Components.interfaces.calIErrors.DAV_REMOVE_ERROR] = "itemDeleteError"; - mapError[Components.interfaces.calIErrors.DAV_REPORT_ERROR] = "disabledMode"; + mapError[Ci.calIErrors.DAV_NOT_DAV] = "dav_notDav"; + mapError[Ci.calIErrors.DAV_DAV_NOT_CALDAV] = "dav_davNotCaldav"; + mapError[Ci.calIErrors.DAV_PUT_ERROR] = "itemPutError"; + mapError[Ci.calIErrors.DAV_REMOVE_ERROR] = "itemDeleteError"; + mapError[Ci.calIErrors.DAV_REPORT_ERROR] = "disabledMode"; let mapModification = {}; - mapModification[Components.interfaces.calIErrors.DAV_NOT_DAV] = false; - mapModification[Components.interfaces.calIErrors.DAV_DAV_NOT_CALDAV] = false; - mapModification[Components.interfaces.calIErrors.DAV_PUT_ERROR] = true; - mapModification[Components.interfaces.calIErrors.DAV_REMOVE_ERROR] = true; - mapModification[Components.interfaces.calIErrors.DAV_REPORT_ERROR] = false; + mapModification[Ci.calIErrors.DAV_NOT_DAV] = false; + mapModification[Ci.calIErrors.DAV_DAV_NOT_CALDAV] = false; + mapModification[Ci.calIErrors.DAV_PUT_ERROR] = true; + mapModification[Ci.calIErrors.DAV_REMOVE_ERROR] = true; + mapModification[Ci.calIErrors.DAV_REPORT_ERROR] = false; let message = mapError[aErrNo]; let localizedMessage; let modificationError = mapModification[aErrNo]; if (!message) { // Only notify if there is a message for this error return; } localizedMessage = cal.l10n.getCalString(message, [this.mUri.spec]); this.mReadOnly = true; this.mDisabled = true; this.notifyError(aErrNo, localizedMessage); this.notifyError(modificationError - ? Components.interfaces.calIErrors.MODIFICATION_FAILED - : Components.interfaces.calIErrors.READ_FAILED, + ? Ci.calIErrors.MODIFICATION_FAILED + : Ci.calIErrors.READ_FAILED, this.buildDetailedMessage(status, extraInfo)); }, buildDetailedMessage: function(status, extraInfo) { if (!status) { return ""; } @@ -2448,31 +2429,31 @@ calDavCalendar.prototype = { cal.LOG("CalDAV: send (Originator=" + organizer + ",Recipient=" + mailto_aCalId + "): " + fbQuery); } let streamListener = {}; streamListener.onStreamComplete = function(aLoader, aContext, aStatus, aResultLength, aResult) { - let request = aLoader.request.QueryInterface(Components.interfaces.nsIHttpChannel); + let request = aLoader.request.QueryInterface(Ci.nsIHttpChannel); let str = new TextDecoder().decode(Uint8Array.from(aResult)); if (!str) { cal.LOG("CalDAV: Failed to parse freebusy response from " + self.name); } else if (self.verboseLogging()) { cal.LOG("CalDAV: recv: " + str); } if (request.responseStatus == 200) { let periodsToReturn = []; let fbTypeMap = {}; - fbTypeMap.FREE = calIFreeBusyInterval.FREE; - fbTypeMap.BUSY = calIFreeBusyInterval.BUSY; - fbTypeMap["BUSY-UNAVAILABLE"] = calIFreeBusyInterval.BUSY_UNAVAILABLE; - fbTypeMap["BUSY-TENTATIVE"] = calIFreeBusyInterval.BUSY_TENTATIVE; + fbTypeMap.FREE = Ci.calIFreeBusyInterval.FREE; + fbTypeMap.BUSY = Ci.calIFreeBusyInterval.BUSY; + fbTypeMap["BUSY-UNAVAILABLE"] = Ci.calIFreeBusyInterval.BUSY_UNAVAILABLE; + fbTypeMap["BUSY-TENTATIVE"] = Ci.calIFreeBusyInterval.BUSY_TENTATIVE; let fbResult; try { fbResult = cal.xml.parseString(str); } catch (ex) { cal.LOG("CalDAV: Could not parse freebusy response " + ex); aListener.onResult(null, null); return; @@ -2494,36 +2475,36 @@ calDavCalendar.prototype = { try { let calComp = cal.getIcsService().parseICS(caldata, null); for (let calFbComp of cal.iterate.icalComponent(calComp)) { let interval; let replyRangeStart = calFbComp.startTime; if (replyRangeStart && (aRangeStart.compare(replyRangeStart) == -1)) { interval = new cal.provider.FreeBusyInterval(aCalId, - calIFreeBusyInterval.UNKNOWN, + Ci.calIFreeBusyInterval.UNKNOWN, aRangeStart, replyRangeStart); periodsToReturn.push(interval); } let replyRangeEnd = calFbComp.endTime; if (replyRangeEnd && (aRangeEnd.compare(replyRangeEnd) == 1)) { interval = new cal.provider.FreeBusyInterval(aCalId, - calIFreeBusyInterval.UNKNOWN, + Ci.calIFreeBusyInterval.UNKNOWN, replyRangeEnd, aRangeEnd); periodsToReturn.push(interval); } for (let fbProp of cal.iterate.icalProperty(calFbComp, "FREEBUSY")) { let fbType = fbProp.getParameter("FBTYPE"); if (fbType) { fbType = fbTypeMap[fbType]; } else { - fbType = calIFreeBusyInterval.BUSY; + fbType = Ci.calIFreeBusyInterval.BUSY; } let parts = fbProp.value.split("/"); let begin = cal.createDateTime(parts[0]); let end; if (parts[1].charAt(0) == "P") { // this is a duration end = begin.clone(); end.addDuration(cal.createDuration(parts[1])); } else { @@ -2551,17 +2532,17 @@ calDavCalendar.prototype = { let fbUri = this.makeUri(null, this.outboxUrl); this.sendHttpRequest(fbUri, fbQuery, MIME_TEXT_CALENDAR, null, (channel) => { channel.requestMethod = "POST"; channel.setRequestHeader("Originator", organizer, false); channel.setRequestHeader("Recipient", mailto_aCalId, false); return streamListener; }, () => { - notifyListener(Components.results.NS_ERROR_NOT_AVAILABLE, + notifyListener(Cr.NS_ERROR_NOT_AVAILABLE, "Error preparing http channel"); }); }, /** * Extract the path from the full spec, if the regexp failed, log * warning and return unaltered path. */ @@ -2642,17 +2623,17 @@ calDavCalendar.prototype = { // processItipReply: function(aItem, aPath) { // modify partstat for in-calendar item // delete item from inbox let self = this; let getItemListener = {}; - getItemListener.QueryInterface = XPCOMUtils.generateQI([Components.interfaces.calIOperationListener]); + getItemListener.QueryInterface = XPCOMUtils.generateQI([Ci.calIOperationListener]); getItemListener.onOperationComplete = function(aCalendar, aStatus, aOperationType, aId, aDetail) { }; getItemListener.onGetResult = function(aCalendar, aStatus, aItemType, aDetail, aCount, aItems) { let itemToUpdate = aItems[0]; if (aItem.recurrenceId && itemToUpdate.recurrenceInfo) { itemToUpdate = itemToUpdate.recurrenceInfo.getOccurrenceFor(aItem.recurrenceId); } let newItem = itemToUpdate.clone(); @@ -2666,17 +2647,17 @@ calDavCalendar.prototype = { newItem.addAttendee(att); } } self.doModifyItem(newItem, itemToUpdate.parentItem /* related to bug 396182 */, modListener, true); }; let modListener = {}; - modListener.QueryInterface = XPCOMUtils.generateQI([Components.interfaces.calIOperationListener]); + modListener.QueryInterface = XPCOMUtils.generateQI([Ci.calIOperationListener]); modListener.onOperationComplete = function(aCalendar, aStatus, aOperationType, aItemId, aDetail) { cal.LOG("CalDAV: status " + aStatus + " while processing iTIP REPLY " + " for " + self.name); // don't delete the REPLY item from inbox unless modifying the master // item was successful if (aStatus == 0) { // aStatus undocumented; 0 seems to indicate no error let delUri = self.calendarUri.clone(); delUri.path = self.ensureEncodedPath(aPath); @@ -2783,32 +2764,32 @@ calDavCalendar.prototype = { if (!attendee) { return false; } // work around BUG 351589, the below just removes RSVP: aItipItem.setAttendeeStatus(attendee.id, attendee.participationStatus); } for (let item of aItipItem.getItemList({})) { - let serializer = Components.classes["@mozilla.org/calendar/ics-serializer;1"] - .createInstance(Components.interfaces.calIIcsSerializer); + let serializer = Cc["@mozilla.org/calendar/ics-serializer;1"] + .createInstance(Ci.calIIcsSerializer); serializer.addItems([item], 1); let methodProp = cal.getIcsService().createIcalProperty("METHOD"); methodProp.value = aItipItem.responseMethod; serializer.addProperty(methodProp); let self = this; let streamListener = { onStreamComplete: function(aLoader, aContext, aStatus, aResultLength, aResult) { - let request = aLoader.request.QueryInterface(Components.interfaces.nsIHttpChannel); + let request = aLoader.request.QueryInterface(Ci.nsIHttpChannel); let status; try { status = request.responseStatus; } catch (ex) { - status = Components.interfaces.calIErrors.DAV_POST_ERROR; + status = Ci.calIErrors.DAV_POST_ERROR; cal.LOG("CalDAV: no response status when sending iTIP for" + self.name); } if (status != 200) { cal.LOG("CalDAV: Sending iTIP failed with status " + status + " for " + self.name); } @@ -2884,77 +2865,77 @@ calDavCalendar.prototype = { this.sendHttpRequest(requestUri, uploadData, MIME_TEXT_CALENDAR, null, (channel) => { channel.requestMethod = "POST"; channel.setRequestHeader("Originator", this.calendarUserAddress, false); for (let recipient of aRecipients) { channel.setRequestHeader("Recipient", recipient.id, true); } return streamListener; }, () => { - notifyListener(Components.results.NS_ERROR_NOT_AVAILABLE, + notifyListener(Cr.NS_ERROR_NOT_AVAILABLE, "Error preparing http channel"); }); } return true; }, mVerboseLogging: undefined, verboseLogging: function() { if (this.mVerboseLogging === undefined) { this.mVerboseLogging = Preferences.get("calendar.debug.log.verbose", false); } return this.mVerboseLogging; }, getSerializedItem: function(aItem) { - let serializer = Components.classes["@mozilla.org/calendar/ics-serializer;1"] - .createInstance(Components.interfaces.calIIcsSerializer); + let serializer = Cc["@mozilla.org/calendar/ics-serializer;1"] + .createInstance(Ci.calIIcsSerializer); serializer.addItems([aItem], 1); let serializedItem = serializer.serializeToString(); if (this.verboseLogging()) { cal.LOG("CalDAV: send: " + serializedItem); } return serializedItem; }, // nsIChannelEventSink implementation asyncOnChannelRedirect: function(aOldChannel, aNewChannel, aFlags, aCallback) { let uploadData; let uploadContent; - if (aOldChannel instanceof Components.interfaces.nsIUploadChannel && - aOldChannel instanceof Components.interfaces.nsIHttpChannel && + if (aOldChannel instanceof Ci.nsIUploadChannel && + aOldChannel instanceof Ci.nsIHttpChannel && aOldChannel.uploadStream) { uploadData = aOldChannel.uploadStream; uploadContent = aOldChannel.getRequestHeader("Content-Type"); } cal.provider.prepHttpChannel(null, uploadData, uploadContent, this, aNewChannel); // Make sure we can get/set headers on both channels. - aNewChannel.QueryInterface(Components.interfaces.nsIHttpChannel); - aOldChannel.QueryInterface(Components.interfaces.nsIHttpChannel); + aNewChannel.QueryInterface(Ci.nsIHttpChannel); + aOldChannel.QueryInterface(Ci.nsIHttpChannel); try { this.mLastRedirectStatus = aOldChannel.responseStatus; } catch (e) { this.mLastRedirectStatus = null; } function copyHeader(aHdr) { try { let hdrValue = aOldChannel.getRequestHeader(aHdr); if (hdrValue) { aNewChannel.setRequestHeader(aHdr, hdrValue, false); } } catch (e) { - if (e.code != Components.results.NS_ERROR_NOT_AVAILIBLE) { + if (e.code != Cr.NS_ERROR_NOT_AVAILIBLE) { // The header could possibly not be availible, ignore that // case but throw otherwise throw e; } } } // If any other header is used, it should be added here. We might want @@ -2965,17 +2946,17 @@ calDavCalendar.prototype = { copyHeader("If-None-Match"); copyHeader("If-Match"); if (aNewChannel.URI.host == "apidata.googleusercontent.com") { copyHeader("Authorization"); } aNewChannel.requestMethod = aOldChannel.requestMethod; - aCallback.onRedirectVerifyCallback(Components.results.NS_OK); + aCallback.onRedirectVerifyCallback(Cr.NS_OK); } }; function calDavObserver(aCalendar) { this.mCalendar = aCalendar; } // Before you spend time trying to find out what this means, please note that diff --git a/calendar/providers/caldav/calDavRequestHandlers.js b/calendar/providers/caldav/calDavRequestHandlers.js --- a/calendar/providers/caldav/calDavRequestHandlers.js +++ b/calendar/providers/caldav/calDavRequestHandlers.js @@ -17,18 +17,17 @@ ChromeUtils.import("resource://gre/modul * @param aBaseUri The URI requested (i.e inbox or collection) * @param aChangeLogListener (optional) for cached calendars, the listener to * notify. */ function etagsHandler(aCalendar, aBaseUri, aChangeLogListener) { this.calendar = aCalendar; this.baseUri = aBaseUri; this.changeLogListener = aChangeLogListener; - this._reader = Components.classes["@mozilla.org/saxparser/xmlreader;1"] - .createInstance(Components.interfaces.nsISAXXMLReader); + this._reader = Cc["@mozilla.org/saxparser/xmlreader;1"].createInstance(Ci.nsISAXXMLReader); this._reader.contentHandler = this; this._reader.errorHandler = this; this._reader.parseAsync(null); this.itemsReported = {}; this.itemsNeedFetching = []; } @@ -40,46 +39,45 @@ etagsHandler.prototype = { baseUri: null, changeLogListener: null, logXML: "", itemsReported: null, itemsNeedFetching: null, QueryInterface: XPCOMUtils.generateQI([ - Components.interfaces.nsISAXContentHandler, - Components.interfaces.nsISAXErrorHandler, - Components.interfaces.nsIRequestObserver, - Components.interfaces.nsIStreamListener + Ci.nsISAXContentHandler, + Ci.nsISAXErrorHandler, + Ci.nsIRequestObserver, + Ci.nsIStreamListener ]), /** * @see nsIStreamListener */ onStartRequest: function(request, context) { - let httpchannel = request.QueryInterface(Components.interfaces.nsIHttpChannel); + let httpchannel = request.QueryInterface(Ci.nsIHttpChannel); let responseStatus; try { responseStatus = httpchannel.responseStatus; } catch (ex) { cal.WARN("CalDAV: No response status getting etags for calendar " + this.calendar.name); } if (responseStatus == 207) { // We only need to parse 207's, anything else is probably a // server error (i.e 50x). httpchannel.contentType = "application/xml"; this._reader.onStartRequest(request, context); } else { cal.LOG("CalDAV: Error fetching item etags"); - this.calendar.reportDavError(Components.interfaces.calIErrors.DAV_REPORT_ERROR); + this.calendar.reportDavError(Ci.calIErrors.DAV_REPORT_ERROR); if (this.calendar.isCached && this.changeLogListener) { - this.changeLogListener.onResult({ status: Components.results.NS_ERROR_FAILURE }, - Components.results.NS_ERROR_FAILURE); + this.changeLogListener.onResult({ status: Cr.NS_ERROR_FAILURE }, Cr.NS_ERROR_FAILURE); } this._reader = null; } }, onStopRequest: async function(request, context, statusCode) { if (this.calendar.verboseLogging()) { cal.LOG("CalDAV: recv: " + this.logXML); @@ -138,18 +136,17 @@ etagsHandler.prototype = { this.baseUri, null, false, null, this.changeLogListener); multiget.doMultiGet(); } else { if (this.calendar.isCached && this.changeLogListener) { - this.changeLogListener.onResult({ status: Components.results.NS_OK }, - Components.results.NS_OK); + this.changeLogListener.onResult({ status: Cr.NS_OK }, Cr.NS_OK); } if (needsRefresh) { this.calendar.mObservers.notify("onLoad", [this.calendar]); } // but do poll the inbox if (this.calendar.mShouldPollInbox && @@ -278,18 +275,17 @@ etagsHandler.prototype = { * @param aBaseUri The URI requested (i.e inbox or collection) * @param aChangeLogListener (optional) for cached calendars, the listener to * notify. */ function webDavSyncHandler(aCalendar, aBaseUri, aChangeLogListener) { this.calendar = aCalendar; this.baseUri = aBaseUri; this.changeLogListener = aChangeLogListener; - this._reader = Components.classes["@mozilla.org/saxparser/xmlreader;1"] - .createInstance(Components.interfaces.nsISAXXMLReader); + this._reader = Cc["@mozilla.org/saxparser/xmlreader;1"].createInstance(Ci.nsISAXXMLReader); this._reader.contentHandler = this; this._reader.errorHandler = this; this._reader.parseAsync(null); this.itemsReported = {}; this.itemsNeedFetching = []; } @@ -304,20 +300,20 @@ webDavSyncHandler.prototype = { isInPropStat: false, changeCount: 0, unhandledErrors: 0, itemsReported: null, itemsNeedFetching: null, additionalSyncNeeded: false, QueryInterface: XPCOMUtils.generateQI([ - Components.interfaces.nsISAXContentHandler, - Components.interfaces.nsISAXErrorHandler, - Components.interfaces.nsIRequestObserver, - Components.interfaces.nsIStreamListener + Ci.nsISAXContentHandler, + Ci.nsISAXErrorHandler, + Ci.nsIRequestObserver, + Ci.nsIStreamListener ]), doWebDAVSync: function() { if (this.calendar.mDisabled) { // check if maybe our calendar has become available this.calendar.setupAuthentication(this.changeLogListener); return; } @@ -353,27 +349,26 @@ webDavSyncHandler.prototype = { // therefore we send both (yuck). channel.setRequestHeader("Depth", "1", false); channel.requestMethod = "REPORT"; return this; }, () => { // Something went wrong with the OAuth token, notify failure if (this.calendar.isCached && this.changeLogListener) { - this.changeLogListener.onResult({ status: Components.results.NS_ERROR_NOT_AVAILABLE }, - Components.results.NS_ERROR_NOT_AVAILABLE); + this.changeLogListener.onResult({ status: Cr.NS_ERROR_NOT_AVAILABLE }, Cr.NS_ERROR_NOT_AVAILABLE); } }, false); }, /** * @see nsIStreamListener */ onStartRequest: function(request, context) { - let httpchannel = request.QueryInterface(Components.interfaces.nsIHttpChannel); + let httpchannel = request.QueryInterface(Ci.nsIHttpChannel); let responseStatus; try { responseStatus = httpchannel.responseStatus; } catch (ex) { cal.WARN("CalDAV: No response status doing webdav sync for calendar " + this.calendar.name); } @@ -389,20 +384,19 @@ webDavSyncHandler.prototype = { // sync token has become invalid and do a refresh cal.LOG("CalDAV: Reseting sync token because server returned status code: " + responseStatus); this._reader = null; this.calendar.mWebdavSyncToken = null; this.calendar.saveCalendarProperties(); this.calendar.safeRefresh(this.changeLogListener); } else { cal.WARN("CalDAV: Error doing webdav sync: " + responseStatus); - this.calendar.reportDavError(Components.interfaces.calIErrors.DAV_REPORT_ERROR); + this.calendar.reportDavError(Ci.calIErrors.DAV_REPORT_ERROR); if (this.calendar.isCached && this.changeLogListener) { - this.changeLogListener.onResult({ status: Components.results.NS_ERROR_FAILURE }, - Components.results.NS_ERROR_FAILURE); + this.changeLogListener.onResult({ status: Cr.NS_ERROR_FAILURE }, Cr.NS_ERROR_FAILURE); } this._reader = null; } }, onStopRequest: function(request, context, statusCode) { if (this.calendar.verboseLogging()) { cal.LOG("CalDAV: recv: " + this.logXML); @@ -450,20 +444,19 @@ webDavSyncHandler.prototype = { if (this.calendar.isCached) { this.calendar.superCalendar.startBatch(); } }, endDocument: function() { if (this.unhandledErrors) { this.calendar.superCalendar.endBatch(); - this.calendar.reportDavError(Components.interfaces.calIErrors.DAV_REPORT_ERROR); + this.calendar.reportDavError(Ci.calIErrors.DAV_REPORT_ERROR); if (this.calendar.isCached && this.changeLogListener) { - this.changeLogListener.onResult({ status: Components.results.NS_ERROR_FAILURE }, - Components.results.NS_ERROR_FAILURE); + this.changeLogListener.onResult({ status: Cr.NS_ERROR_FAILURE }, Cr.NS_ERROR_FAILURE); } return; } if (this.calendar.mWebdavSyncToken == null) { // null token means reset or first refresh indicating we did // a full sync; remove local items that were not returned in this full // sync @@ -651,18 +644,17 @@ webDavSyncHandler.prototype = { * notify. */ function multigetSyncHandler(aItemsNeedFetching, aCalendar, aBaseUri, aNewSyncToken, aAdditionalSyncNeeded, aListener, aChangeLogListener) { this.calendar = aCalendar; this.baseUri = aBaseUri; this.listener = aListener; this.newSyncToken = aNewSyncToken; this.changeLogListener = aChangeLogListener; - this._reader = Components.classes["@mozilla.org/saxparser/xmlreader;1"] - .createInstance(Components.interfaces.nsISAXXMLReader); + this._reader = Cc["@mozilla.org/saxparser/xmlreader;1"].createInstance(Ci.nsISAXXMLReader); this._reader.contentHandler = this; this._reader.errorHandler = this; this._reader.parseAsync(null); this.itemsNeedFetching = aItemsNeedFetching; this.additionalSyncNeeded = aAdditionalSyncNeeded; } multigetSyncHandler.prototype = { currentResponse: null, @@ -674,20 +666,20 @@ multigetSyncHandler.prototype = { changeLogListener: null, logXML: null, unhandledErrors: 0, itemsNeedFetching: null, additionalSyncNeeded: false, timer: null, QueryInterface: XPCOMUtils.generateQI([ - Components.interfaces.nsISAXContentHandler, - Components.interfaces.nsISAXErrorHandler, - Components.interfaces.nsIRequestObserver, - Components.interfaces.nsIStreamListener + Ci.nsISAXContentHandler, + Ci.nsISAXErrorHandler, + Ci.nsIRequestObserver, + Ci.nsIStreamListener ]), doMultiGet: function() { if (this.calendar.mDisabled) { // check if maybe our calendar has become available this.calendar.setupAuthentication(this.changeLogListener); return; } @@ -718,27 +710,26 @@ multigetSyncHandler.prototype = { } this.calendar.sendHttpRequest(requestUri, queryXml, MIME_TEXT_XML, null, (channel) => { channel.requestMethod = "REPORT"; channel.setRequestHeader("Depth", "1", false); return this; }, () => { // Something went wrong with the OAuth token, notify failure if (this.calendar.isCached && this.changeLogListener) { - this.changeLogListener.onResult({ status: Components.results.NS_ERROR_NOT_AVAILABLE }, - Components.results.NS_ERROR_NOT_AVAILABLE); + this.changeLogListener.onResult({ status: Cr.NS_ERROR_NOT_AVAILABLE }, Cr.NS_ERROR_NOT_AVAILABLE); } }, false); }, /** * @see nsIStreamListener */ onStartRequest: function(request, context) { - let httpchannel = request.QueryInterface(Components.interfaces.nsIHttpChannel); + let httpchannel = request.QueryInterface(Ci.nsIHttpChannel); let responseStatus; try { responseStatus = httpchannel.responseStatus; } catch (ex) { cal.WARN("CalDAV: No response status doing multiget for calendar " + this.calendar.name); } @@ -791,34 +782,32 @@ multigetSyncHandler.prototype = { } try { this._reader.onStopRequest(request, context, statusCode); } finally { this._reader = null; } if (this.itemsNeedFetching.length > 0) { cal.LOG("CalDAV: Still need to fetch " + this.itemsNeedFetching.length + " elements."); - this._reader = Components.classes["@mozilla.org/saxparser/xmlreader;1"] - .createInstance(Components.interfaces.nsISAXXMLReader); + this._reader = Cc["@mozilla.org/saxparser/xmlreader;1"].createInstance(Ci.nsISAXXMLReader); this._reader.contentHandler = this; this._reader.errorHandler = this; this._reader.parseAsync(null); let timerCallback = { requestHandler: this, notify: function(timer) { // Call multiget again to get another batch this.requestHandler.doMultiGet(); } }; - this.timer = Components.classes["@mozilla.org/timer;1"] - .createInstance(Components.interfaces.nsITimer); + this.timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer); this.timer.initWithCallback( timerCallback, 0, - Components.interfaces.nsITimer.TYPE_ONE_SHOT + Ci.nsITimer.TYPE_ONE_SHOT ); } }, onDataAvailable: function(request, context, inputStream, offset, count) { if (this._reader) { // No reader means request error this._reader.onDataAvailable(request, context, inputStream, offset, count); diff --git a/calendar/providers/composite/calCompositeCalendar.js b/calendar/providers/composite/calCompositeCalendar.js --- a/calendar/providers/composite/calCompositeCalendar.js +++ b/calendar/providers/composite/calCompositeCalendar.js @@ -7,27 +7,27 @@ ChromeUtils.import("resource://calendar/ // // calCompositeCalendar.js // /** * Calendar specific utility functions */ -var calIOperationListener = Components.interfaces.calIOperationListener; +var calIOperationListener = Ci.calIOperationListener; function calCompositeCalendarObserverHelper(compCalendar) { this.compCalendar = compCalendar; this.pendingLoads = {}; } calCompositeCalendarObserverHelper.prototype = { pendingLoads: null, - QueryInterface: XPCOMUtils.generateQI([Components.interfaces.calIObserver]), + QueryInterface: XPCOMUtils.generateQI([Ci.calIObserver]), onStartBatch: function() { this.compCalendar.mObservers.notify("onStartBatch"); }, onEndBatch: function() { this.compCalendar.mObservers.notify("onEndBatch"); }, @@ -70,27 +70,27 @@ calCompositeCalendarObserverHelper.proto } }; function calCompositeCalendar() { this.mObserverHelper = new calCompositeCalendarObserverHelper(this); this.wrappedJSObject = this; this.mCalendars = []; - this.mCompositeObservers = new cal.data.ObserverSet(Components.interfaces.calICompositeObserver); - this.mObservers = new cal.data.ObserverSet(Components.interfaces.calIObserver); + this.mCompositeObservers = new cal.data.ObserverSet(Ci.calICompositeObserver); + this.mObservers = new cal.data.ObserverSet(Ci.calIObserver); this.mDefaultCalendar = null; this.mStatusObserver = null; } var calCompositeCalendarClassID = Components.ID("{aeff788d-63b0-4996-91fb-40a7654c6224}"); var calCompositeCalendarInterfaces = [ - Components.interfaces.calICalendarProvider, - Components.interfaces.calICalendar, - Components.interfaces.calICompositeCalendar, + Ci.calICalendarProvider, + Ci.calICalendar, + Ci.calICompositeCalendar, ]; calCompositeCalendar.prototype = { classID: calCompositeCalendarClassID, QueryInterface: XPCOMUtils.generateQI(calCompositeCalendarInterfaces), classInfo: XPCOMUtils.generateCI({ classID: calCompositeCalendarClassID, contractID: "@mozilla.org/calendar/calendar;1?type=composite", classDescription: "Composite Calendar Provider", @@ -233,56 +233,56 @@ calCompositeCalendar.prototype = { // calICalendar interface // // Write operations here are forwarded to either the item's // parent calendar, or to the default calendar if one is set. // Get operations are sent to each calendar. // get id() { - throw Components.results.NS_ERROR_NOT_IMPLEMENTED; + throw Cr.NS_ERROR_NOT_IMPLEMENTED; }, set id(id) { - throw Components.results.NS_ERROR_NOT_IMPLEMENTED; + throw Cr.NS_ERROR_NOT_IMPLEMENTED; }, get superCalendar() { // There shouldn't be a superCalendar for the composite return this; }, set superCalendar(val) { - throw Components.results.NS_ERROR_NOT_IMPLEMENTED; + throw Cr.NS_ERROR_NOT_IMPLEMENTED; }, // this could, at some point, return some kind of URI identifying // all the child calendars, thus letting us create nifty calendar // trees. get uri() { - throw Components.results.NS_ERROR_NOT_IMPLEMENTED; + throw Cr.NS_ERROR_NOT_IMPLEMENTED; }, set uri(val) { - throw Components.results.NS_ERROR_NOT_IMPLEMENTED; + throw Cr.NS_ERROR_NOT_IMPLEMENTED; }, get readOnly() { - throw Components.results.NS_ERROR_NOT_IMPLEMENTED; + throw Cr.NS_ERROR_NOT_IMPLEMENTED; }, set readOnly(bool) { - throw Components.results.NS_ERROR_NOT_IMPLEMENTED; + throw Cr.NS_ERROR_NOT_IMPLEMENTED; }, get canRefresh() { return true; }, get name() { - throw Components.results.NS_ERROR_NOT_IMPLEMENTED; + throw Cr.NS_ERROR_NOT_IMPLEMENTED; }, set name(val) { - throw Components.results.NS_ERROR_NOT_IMPLEMENTED; + throw Cr.NS_ERROR_NOT_IMPLEMENTED; }, get type() { return "composite"; }, getProperty: function(aName) { return this.mDefaultCalendar.getProperty(aName); @@ -295,35 +295,35 @@ calCompositeCalendar.prototype = { deleteProperty: function(aName) { return this.mDefaultCalendar.deleteProperty(aName); }, // void addObserver( in calIObserver observer ); mCompositeObservers: null, mObservers: null, addObserver: function(aObserver) { - let wrappedCObserver = cal.wrapInstance(aObserver, Components.interfaces.calICompositeObserver); + let wrappedCObserver = cal.wrapInstance(aObserver, Ci.calICompositeObserver); if (wrappedCObserver) { this.mCompositeObservers.add(wrappedCObserver); } this.mObservers.add(aObserver); }, // void removeObserver( in calIObserver observer ); removeObserver: function(aObserver) { - let wrappedCObserver = cal.wrapInstance(aObserver, Components.interfaces.calICompositeObserver); + let wrappedCObserver = cal.wrapInstance(aObserver, Ci.calICompositeObserver); if (wrappedCObserver) { this.mCompositeObservers.delete(wrappedCObserver); } this.mObservers.delete(aObserver); }, refresh: function() { if (this.mStatusObserver) { - this.mStatusObserver.startMeteors(Components.interfaces.calIStatusObserver.DETERMINED_PROGRESS, this.mCalendars.length); + this.mStatusObserver.startMeteors(Ci.calIStatusObserver.DETERMINED_PROGRESS, this.mCalendars.length); } for (let calendar of this.enabledCalendars) { try { if (calendar.canRefresh) { this.mObserverHelper.pendingLoads[calendar.id] = true; calendar.refresh(); } } catch (e) { @@ -376,25 +376,25 @@ calCompositeCalendar.prototype = { // void getItems( in unsigned long aItemFilter, in unsigned long aCount, // in calIDateTime aRangeStart, in calIDateTime aRangeEnd, // in calIOperationListener aListener ); getItems: function(aItemFilter, aCount, aRangeStart, aRangeEnd, aListener) { // If there are no calendars, then we just call onOperationComplete let enabledCalendars = this.enabledCalendars; if (enabledCalendars.length == 0) { aListener.onOperationComplete(this, - Components.results.NS_OK, + Cr.NS_OK, calIOperationListener.GET, null, null); return null; } if (this.mStatusObserver) { - if (this.mStatusObserver.spinning == Components.interfaces.calIStatusObserver.NO_PROGRESS) { - this.mStatusObserver.startMeteors(Components.interfaces.calIStatusObserver.UNDETERMINED_PROGRESS, -1); + if (this.mStatusObserver.spinning == Ci.calIStatusObserver.NO_PROGRESS) { + this.mStatusObserver.startMeteors(Ci.calIStatusObserver.UNDETERMINED_PROGRESS, -1); } } let cmpListener = new calCompositeGetListenerHelper(this, aListener, aCount); for (let calendar of enabledCalendars) { try { cmpListener.opGroup.add(calendar.getItems(aItemFilter, aCount, @@ -412,17 +412,17 @@ calCompositeCalendar.prototype = { this.mCompositeObservers.notify("onStartBatch"); }, endBatch: function() { this.mCompositeObservers.notify("onEndBatch"); }, get statusDisplayed() { if (this.mStatusObserver) { - return this.mStatusObserver.spinning != Components.interfaces.calIStatusObserver.NO_PROGRESS; + return this.mStatusObserver.spinning != Ci.calIStatusObserver.NO_PROGRESS; } else { return false; } }, setStatusObserver: function(aStatusObserver, aWindow) { this.mStatusObserver = aStatusObserver; if (this.mStatusObserver) { @@ -451,28 +451,28 @@ calCompositeGetListenerHelper.prototype get opGroup() { if (!this.mOpGroup) { this.mOpGroup = new cal.data.OperationGroup(() => { let listener = this.mRealListener; this.mRealListener = null; if (listener) { listener.onOperationComplete( - this, Components.interfaces.calIErrors.OPERATION_CANCELLED, + this, Ci.calIErrors.OPERATION_CANCELLED, calIOperationListener.GET, null, null); if (this.mCompositeCalendar.statusDisplayed) { this.mCompositeCalendar.mStatusObserver.stopMeteors(); } } }); } return this.mOpGroup; }, - QueryInterface: XPCOMUtils.generateQI([Components.interfaces.calIOperationListener]), + QueryInterface: XPCOMUtils.generateQI([Ci.calIOperationListener]), onOperationComplete: function(aCalendar, aStatus, aOperationType, aId, aDetail) { if (!this.mRealListener) { // has been cancelled, ignore any providers firing on this... return; } if (this.mFinished) { dump("+++ calCompositeGetListenerHelper.onOperationComplete: called with mFinished == true!"); @@ -481,17 +481,17 @@ calCompositeGetListenerHelper.prototype if (this.mCompositeCalendar.statusDisplayed) { this.mCompositeCalendar.mStatusObserver.calendarCompleted(aCalendar); } if (!Components.isSuccessCode(aStatus)) { // proxy this to a onGetResult // XXX - do we want to give the real calendar? or this? // XXX - get rid of iid param this.mRealListener.onGetResult(aCalendar, aStatus, - Components.interfaces.nsISupports, + Ci.nsISupports, aDetail, 0, []); } this.mReceivedCompletes++; if (this.mReceivedCompletes == this.mNumQueries) { if (this.mCompositeCalendar.statusDisplayed) { this.mCompositeCalendar.mStatusObserver.stopMeteors(); } diff --git a/calendar/providers/gdata/components/calGoogleCalendar.js b/calendar/providers/gdata/components/calGoogleCalendar.js --- a/calendar/providers/gdata/components/calGoogleCalendar.js +++ b/calendar/providers/gdata/components/calGoogleCalendar.js @@ -10,17 +10,17 @@ ChromeUtils.import("resource://gre/modul ChromeUtils.import("resource://calendar/modules/calUtils.jsm"); ChromeUtils.import("resource://gdata-provider/modules/calUtilsShim.jsm"); ChromeUtils.import("resource://gdata-provider/modules/gdataLogging.jsm"); ChromeUtils.import("resource://gdata-provider/modules/gdataRequest.jsm"); ChromeUtils.import("resource://gdata-provider/modules/gdataSession.jsm"); ChromeUtils.import("resource://gdata-provider/modules/gdataUtils.jsm"); -var cIOL = Components.interfaces.calIOperationListener; +var cIOL = Ci.calIOperationListener; var MIN_REFRESH_INTERVAL = 30; /** * calGoogleCalendar * This Implements a calICalendar Object adapted to the Google Calendar * Provider. * @@ -29,19 +29,19 @@ var MIN_REFRESH_INTERVAL = 30; */ function calGoogleCalendar() { this.initProviderBase(); this.mThrottle = Object.create(null); } var calGoogleCalendarClassID = Components.ID("{d1a6e988-4b4d-45a5-ba46-43e501ea96e3}"); var calGoogleCalendarInterfaces = [ - Components.interfaces.calICalendar, - Components.interfaces.calISchedulingSupport, - Components.interfaces.calIChangeLog + Ci.calICalendar, + Ci.calISchedulingSupport, + Ci.calIChangeLog ]; calGoogleCalendar.prototype = { __proto__: cal.provider.BaseClass.prototype, classID: calGoogleCalendarClassID, QueryInterface: XPCOMUtils.generateQI(calGoogleCalendarInterfaces), classInfo: XPCOMUtils.generateCI({ classDescription: "Google Calendar Provider", @@ -83,18 +83,17 @@ calGoogleCalendar.prototype = { this.setProperty("refreshInterval", 2 * MIN_REFRESH_INTERVAL); } } }, ensureWritable: function() { // Check if calendar is readonly if (this.readOnly) { - const cIE = Components.interfaces.calIErrors; - throw new Components.Exception("", cIE.CAL_IS_READONLY); + throw new Components.Exception("", Ci.calIErrors.CAL_IS_READONLY); } }, get isDefaultCalendar() { return this.mCalendarName ? !this.mCalendarName.endsWith("@group.calendar.google.com") : false; }, /* * implement calICalendar */ @@ -374,17 +373,17 @@ calGoogleCalendar.prototype = { cal.LOG("[calGoogleCalendar] Adding task " + aItem.title); request.uri = this.createTasksURI("tasks"); // Tasks sent with an id will cause a bad request delete itemData.id; } if (!request.uri) { throw Components.Exception("Item type not supported", - Components.results.NS_ERROR_NOT_IMPLEMENTED); + Cr.NS_ERROR_NOT_IMPLEMENTED); } request.setUploadData("application/json; charset=UTF-8", JSON.stringify(itemData)); let data = await this.session.asyncItemRequest(request); // All we need to do now is parse the item and complete the // operation. The cache layer will take care of adding the item @@ -404,20 +403,20 @@ calGoogleCalendar.prototype = { // item. This will add the new item to the calendar. let pcal = cal.async.promisifyCalendar(this.offlineStorage); await pcal.deleteItem(aItem); } return item; })().then((item) => { cal.LOG("[calGoogleCalendar] Adding " + item.title + " succeeded"); this.observers.notify("onAddItem", [item]); - this.notifyOperationComplete(aListener, Components.results.NS_OK, + this.notifyOperationComplete(aListener, Cr.NS_OK, cIOL.ADD, item.id, item); }, (e) => { - let code = e.result || Components.results.NS_ERROR_FAILURE; + let code = e.result || Cr.NS_ERROR_FAILURE; cal.ERROR("[calGoogleCalendar] Adding Item " + aItem.title + " failed:" + code + ": " + e.message); this.notifyPureOperationComplete(aListener, code, cIOL.ADD, aItem.id, e.message); }); return request; }, modifyItem: function(aNewItem, aOldItem, aListener) { @@ -445,17 +444,17 @@ calGoogleCalendar.prototype = { request.addQueryParameter("sendNotifications", "true"); } } else if (cal.item.isToDo(aNewItem)) { request.uri = this.createTasksURI("tasks", aNewItem.id); } if (!request.uri) { throw Components.Exception("Item type not supported", - Components.results.NS_ERROR_NOT_IMPLEMENTED); + Cr.NS_ERROR_NOT_IMPLEMENTED); } request.setUploadData("application/json; charset=UTF-8", JSON.stringify(ItemToJSON(aNewItem, this.offlineStorage))); // Set up etag from storage so we don't overwrite any foreign changes let refItem = aOldItem || aNewItem; let meta = getItemMetadata(this.offlineStorage, refItem) || @@ -504,21 +503,21 @@ calGoogleCalendar.prototype = { } item = modifiedItem; } return item; })().then((item) => { cal.LOG("[calGoogleCalendar] Modifying " + aNewItem.title + " succeeded"); this.observers.notify("onModifyItem", [item, aOldItem]); - this.notifyOperationComplete(aListener, Components.results.NS_OK, + this.notifyOperationComplete(aListener, Cr.NS_OK, cIOL.MODIFY, item.id, item); }, (e) => { - let code = e.result || Components.results.NS_ERROR_FAILURE; - if (code != Components.interfaces.calIErrors.OPERATION_CANCELLED) { + let code = e.result || Cr.NS_ERROR_FAILURE; + if (code != Ci.calIErrors.OPERATION_CANCELLED) { cal.ERROR("[calGoogleCalendar] Modifying item " + aNewItem.title + " failed:" + code + ": " + e.message); } this.notifyPureOperationComplete(aListener, code, cIOL.MODIFY, aNewItem.id, e.message); }); return request; }, @@ -535,17 +534,17 @@ calGoogleCalendar.prototype = { request.addQueryParameter("sendNotifications", "true"); } } else if (cal.item.isToDo(aItem)) { request.uri = this.createTasksURI("tasks", aItem.id); } if (!request.uri) { throw Components.Exception("Item type not supported", - Components.results.NS_ERROR_NOT_IMPLEMENTED); + Cr.NS_ERROR_NOT_IMPLEMENTED); } // Set up etag from storage so we don't overwrite any foreign changes let meta = getItemMetadata(this.offlineStorage, aItem) || getItemMetadata(this.offlineStorage, aItem.parentItem); if (meta && meta.etag) { request.addRequestHeader("If-Match", meta.etag); } else { @@ -564,21 +563,21 @@ calGoogleCalendar.prototype = { } deleteItemMetadata(this.offlineStorage, aItem); return aItem; })().then((item) => { cal.LOG("[calGoogleCalendar] Deleting " + aItem.title + " succeeded"); this.observers.notify("onDeleteItem", [item]); - this.notifyOperationComplete(aListener, Components.results.NS_OK, + this.notifyOperationComplete(aListener, Cr.NS_OK, cIOL.DELETE, item.id, item); }, (e) => { - let code = e.result || Components.results.NS_ERROR_FAILURE; - if (code != Components.interfaces.calIErrors.OPERATION_CANCELLED) { + let code = e.result || Cr.NS_ERROR_FAILURE; + if (code != Ci.calIErrors.OPERATION_CANCELLED) { cal.ERROR("[calGoogleCalendar] Deleting item " + aItem.title + " failed:" + code + ": " + e.message); } this.notifyPureOperationComplete(aListener, code, cIOL.DELETE, aItem.id, e.message); }); return request; }, @@ -659,31 +658,29 @@ calGoogleCalendar.prototype = { onDeleteCalendar: function(aCalendar, aStatus, aDetail) { if (Components.isSuccessCode(aStatus)) { resolve(); } else { reject(aDetail); } } }; - this.mOfflineStorage.QueryInterface(Components.interfaces.calICalendarProvider) + this.mOfflineStorage.QueryInterface(Ci.calICalendarProvider) .deleteCalendar(this.mOfflineStorage, listener); }); }, replayChangesOn: function(aListener) { // Figure out if the user is idle, no need to synchronize if so. - let idleTime = Components.classes["@mozilla.org/widget/idleservice;1"] - .getService(Components.interfaces.nsIIdleService) - .idleTime; + let idleTime = Cc["@mozilla.org/widget/idleservice;1"].getService(Ci.nsIIdleService).idleTime; let maxIdleTime = Preferences.get("calendar.google.idleTime", 300) * 1000; if (maxIdleTime != 0 && idleTime > maxIdleTime) { cal.LOG("[calGoogleCalendar] Skipping refresh since user is idle"); - aListener.onResult({ status: Components.results.NS_OK }, null); + aListener.onResult({ status: Cr.NS_OK }, null); return Promise.resolve(); } // Now that we've determined we are not idle we can continue with the sync. let maxResults = Preferences.get("calendar.google.maxResultsPerRequest", null); // We are going to be making potentially lots of changes to the offline // storage, start a batch operation. @@ -773,20 +770,20 @@ calGoogleCalendar.prototype = { "(tasks) is now: " + tasksRequest.requestDate.toString()); this.setProperty("newLastUpdated.tasks", newLastUpdated); }); }); } return Promise.all([calendarPromise, eventsPromise, tasksPromise]).then(() => { this.mOfflineStorage.endBatch(); - aListener.onResult({ status: Components.results.NS_OK }, null); + aListener.onResult({ status: Cr.NS_OK }, null); }, (e) => { this.mOfflineStorage.endBatch(); - let code = e.result || Components.results.NS_ERROR_FAILURE; + let code = e.result || Cr.NS_ERROR_FAILURE; if (code == calGoogleRequest.RESOURCE_GONE) { cal.LOG("[calGoogleCalendar] Server did not accept " + "incremental update, resetting calendar and " + "starting over."); this.resetSync().then(() => { this.replayChangesOn(aListener); }, (err) => { cal.ERROR("[calGoogleCalendar] Error resetting calendar:\n" + diff --git a/calendar/providers/gdata/content/browserRequest.js b/calendar/providers/gdata/content/browserRequest.js --- a/calendar/providers/gdata/content/browserRequest.js +++ b/calendar/providers/gdata/content/browserRequest.js @@ -5,28 +5,28 @@ ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); ChromeUtils.import("resource://calendar/modules/calUtils.jsm"); ChromeUtils.import("resource://gdata-provider/modules/calUtilsShim.jsm"); /* exported cancelRequest, loadRequestedUrl, reportUserClosed */ -var wpl = Components.interfaces.nsIWebProgressListener; +var wpl = Ci.nsIWebProgressListener; var reporterListener = { _isBusy: false, get securityButton() { delete this.securityButton; return (this.securityButton = document.getElementById("security-button")); }, QueryInterface: XPCOMUtils.generateQI([ - Components.interfaces.nsIWebProgressListener, - Components.interfaces.nsISupportsWeakReference, + Ci.nsIWebProgressListener, + Ci.nsISupportsWeakReference, ]), onStateChange: function(aWebProgress, aRequest, aStateFlags, aStatus) { }, onProgressChange: function(aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress) { }, @@ -77,18 +77,17 @@ function reportUserClosed() { function loadRequestedUrl() { let request = window.arguments[0].wrappedJSObject; document.getElementById("headerMessage").textContent = request.promptText; if (request.iconURI != "") { document.getElementById("headerImage").src = request.iconURI; } let browser = document.getElementById("requestFrame"); - browser.addProgressListener(reporterListener, - Components.interfaces.nsIWebProgress.NOTIFY_ALL); + browser.addProgressListener(reporterListener, Ci.nsIWebProgress.NOTIFY_ALL); let url = request.url; if (url != "") { browser.setAttribute("src", url); document.getElementById("headerMessage").textContent = url; } let dialogMessage = document.getElementById("dialogMessage"); if (request.description) { diff --git a/calendar/providers/gdata/content/gdata-calendar-creation.js b/calendar/providers/gdata/content/gdata-calendar-creation.js --- a/calendar/providers/gdata/content/gdata-calendar-creation.js +++ b/calendar/providers/gdata/content/gdata-calendar-creation.js @@ -18,17 +18,17 @@ ChromeUtils.import("resource://gdata-pro } } function trycatch(func) { return function() { try { return func.apply(this, arguments); } catch (e) { - Components.utils.reportError(e); + Cu.reportError(e); throw e; } }; } let previousUriValue = null; function selectProvider(type) { let isGdata = (type == "gdata"); @@ -201,17 +201,17 @@ ChromeUtils.import("resource://gdata-pro let calendars = [calendarListWidget.mockCalendarHeader] .concat(calcals) .concat([calendarListWidget.mockTaskHeader]) .concat(taskcals); calendarListWidget.calendars = calendars; }, (e) => { - Components.utils.reportError(e); + Cu.reportError(e); }); }); this.gdataCalendarsAdvance = trycatch(() => { let calendarList = document.getElementById("calendar-list"); let calendars = calendarList.selectedCalendars.filter(calendar => !calendar.getProperty("disabled") && !calendar.readOnly); let calMgr = cal.getCalendarManager(); calendars.forEach(calMgr.registerCalendar, calMgr); diff --git a/calendar/providers/gdata/content/gdata-list-tree.xml b/calendar/providers/gdata/content/gdata-list-tree.xml --- a/calendar/providers/gdata/content/gdata-list-tree.xml +++ b/calendar/providers/gdata/content/gdata-list-tree.xml @@ -89,17 +89,17 @@ mem.id = cal.getUUID(); return mem; ]]> 0 0 - XPCOMUtils.generateQI([Components.interfaces.nsITreeView]) + XPCOMUtils.generateQI([Ci.nsITreeView]) 0 ? "yes:" + xpropstr : "no")); } function LOGinterval(aInterval) { - const fbtypes = Components.interfaces.calIFreeBusyInterval; + const fbtypes = Ci.calIFreeBusyInterval; let type; if (aInterval.freeBusyType == fbtypes.FREE) { type = "FREE"; } else if (aInterval.freeBusyType == fbtypes.BUSY) { type = "BUSY"; } else { type = aInterval.freeBusyType + " (UNKNOWN)"; } diff --git a/calendar/providers/gdata/modules/gdataRequest.jsm b/calendar/providers/gdata/modules/gdataRequest.jsm --- a/calendar/providers/gdata/modules/gdataRequest.jsm +++ b/calendar/providers/gdata/modules/gdataRequest.jsm @@ -8,18 +8,16 @@ ChromeUtils.import("resource://gre/modul ChromeUtils.import("resource://gre/modules/Services.jsm"); ChromeUtils.import("resource://gre/modules/PromiseUtils.jsm"); ChromeUtils.import("resource://gre/modules/Preferences.jsm"); ChromeUtils.import("resource://calendar/modules/calUtils.jsm"); ChromeUtils.import("resource://gdata-provider/modules/calUtilsShim.jsm"); -var cIE = Components.interfaces.calIErrors; - var API_BASE = { EVENTS: "https://www.googleapis.com/calendar/v3/", TASKS: "https://www.googleapis.com/tasks/v1/" }; var EXPORTED_SYMBOLS = ["calGoogleRequest", "getCorrectedDate", "API_BASE"]; /** @@ -49,17 +47,17 @@ function calGoogleRequest() { this.wrappedJSObject = this; } calGoogleRequest.ADD = "POST"; calGoogleRequest.MODIFY = "PUT"; calGoogleRequest.DELETE = "DELETE"; calGoogleRequest.GET = "GET"; calGoogleRequest.PATCH = "PATCH"; -var GDATA_ERROR_BASE = Components.interfaces.calIErrors.ERROR_BASE + 0x400; +var GDATA_ERROR_BASE = Ci.calIErrors.ERROR_BASE + 0x400; calGoogleRequest.LOGIN_FAILED = GDATA_ERROR_BASE + 1; calGoogleRequest.CONFLICT_DELETED = GDATA_ERROR_BASE + 2; calGoogleRequest.CONFLICT_MODIFY = GDATA_ERROR_BASE + 3; calGoogleRequest.NOT_MODIFIED = GDATA_ERROR_BASE + 4; calGoogleRequest.QUOTA_FAILURE = GDATA_ERROR_BASE + 5; calGoogleRequest.TOKEN_FAILURE = GDATA_ERROR_BASE + 6; calGoogleRequest.RESOURCE_GONE = GDATA_ERROR_BASE + 7; @@ -68,17 +66,17 @@ calGoogleRequest.prototype = { /* Members */ mUploadContent: null, mUploadData: null, mSession: null, mQueryParameters: null, mType: null, mLoader: null, mDeferred: null, - mStatus: Components.results.NS_OK, + mStatus: Cr.NS_OK, /* Constants */ ADD: calGoogleRequest.ADD, MODIFY: calGoogleRequest.MODIFY, DELETE: calGoogleRequest.DELETE, GET: calGoogleRequest.GET, PATCH: calGoogleRequest.PATCH, @@ -86,20 +84,20 @@ calGoogleRequest.prototype = { method: "GET", id: null, uri: null, calendar: null, reauthenticate: true, requestDate: null, QueryInterface: XPCOMUtils.generateQI([ - Components.interfaces.calIOperation, - Components.interfaces.nsIStreamLoaderObserver, - Components.interfaces.nsIInterfaceRequestor, - Components.interfaces.nsIChannelEventSink + Ci.calIOperation, + Ci.nsIStreamLoaderObserver, + Ci.nsIInterfaceRequestor, + Ci.nsIChannelEventSink ]), /** * Implement calIOperation */ get isPending() { return (this.mLoader && this.mLoader.request != null); }, @@ -127,17 +125,17 @@ calGoogleRequest.prototype = { * GET, ADD, MODIFY, DELETE */ get type() { return this.method; }, set type(val) { let valid = [this.GET, this.ADD, this.MODIFY, this.PATCH, this.DELETE]; if (!valid.includes(val)) { throw new Components.Exception("Invalid request type: " + val, - Components.results.NS_ERROR_ILLEGAL_VALUE); + Cr.NS_ERROR_ILLEGAL_VALUE); } return (this.method = val); }, /** * setUploadData * The HTTP body data for a POST or PUT request. * @@ -199,29 +197,29 @@ calGoogleRequest.prototype = { let uri = Services.io.newURI(uristring); let channel; if ("newChannelFromURI2" in Services.io) { // Lightning 4.3+ channel = Services.io.newChannelFromURI2(uri, null, Services.scriptSecurityManager.getSystemPrincipal(), null, - Components.interfaces.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, - Components.interfaces.nsIContentPolicy.TYPE_OTHER); + Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, + Ci.nsIContentPolicy.TYPE_OTHER); } else { // Lightning 4.2 and older channel = Services.io.newChannelFromURI(uri); } cal.LOG("[calGoogleRequest] Requesting " + this.method + " " + channel.URI.spec); this.prepareChannel(channel); - channel = channel.QueryInterface(Components.interfaces.nsIHttpChannel); + channel = channel.QueryInterface(Ci.nsIHttpChannel); channel.redirectionLimit = 3; this.mLoader = cal.provider.createStreamLoader(); channel.notificationCallbacks = this; cal.provider.sendHttpRequest(this.mLoader, channel, this); } catch (e) { // Let the response function handle the error that happens here this.fail(e.result, e.message); @@ -248,46 +246,46 @@ calGoogleRequest.prototype = { /** * succeed * Call this request's listener with a Success Code and the given Result. * * @param aResult The result Text of this request. */ succeed: function(aResult) { this.mLoader = null; - this.mStatus = Components.results.NS_OK; + this.mStatus = Cr.NS_OK; this.mDeferred.resolve(aResult); this.mDeferred = null; }, /** * prepareChannel * Prepares the passed channel to match this objects properties * * @param aChannel The Channel to be prepared. */ prepareChannel: function(aChannel) { // No caching - aChannel.loadFlags |= Components.interfaces.nsIRequest.LOAD_BYPASS_CACHE; + aChannel.loadFlags |= Ci.nsIRequest.LOAD_BYPASS_CACHE; // Set upload Data if (this.mUploadData) { - let converter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"] - .createInstance(Components.interfaces.nsIScriptableUnicodeConverter); + let converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"] + .createInstance(Ci.nsIScriptableUnicodeConverter); converter.charset = "UTF-8"; let stream = converter.convertToInputStream(this.mUploadData); - aChannel = aChannel.QueryInterface(Components.interfaces.nsIUploadChannel); + aChannel = aChannel.QueryInterface(Ci.nsIUploadChannel); aChannel.setUploadStream(stream, this.mUploadContent, -1); cal.LOG("[calGoogleCalendar] Setting Upload Data (" + this.mUploadContent + "):\n" + this.mUploadData); } - aChannel = aChannel.QueryInterface(Components.interfaces.nsIHttpChannel); + aChannel = aChannel.QueryInterface(Ci.nsIHttpChannel); // Depending on the preference, we will use X-HTTP-Method-Override to // get around some proxies. This will default to true. if (Preferences.get("calendar.google.useHTTPMethodOverride", true) && (this.method == "PUT" || this.method == "DELETE")) { aChannel.requestMethod = "POST"; aChannel.setRequestHeader("X-HTTP-Method-Override", this.method, @@ -332,49 +330,49 @@ calGoogleRequest.prototype = { getInterface: cal.provider.InterfaceRequestor_getInterface, /** * @see nsIChannelEventSink */ asyncOnChannelRedirect: function(aOldChannel, aNewChannel, aFlags, aCallback) { // all we need to do to the new channel is the basic preparation this.prepareChannel(aNewChannel); - aCallback.onRedirectVerifyCallback(Components.results.NS_OK); + aCallback.onRedirectVerifyCallback(Cr.NS_OK); }, /** * @see nsIStreamLoaderObserver */ onStreamComplete: function(aLoader, aContext, aStatus, aResultLength, aResult) { if (!aResult || !Components.isSuccessCode(aStatus)) { this.fail(aStatus, aResult); return; } - let httpChannel = aLoader.request.QueryInterface(Components.interfaces.nsIHttpChannel); + let httpChannel = aLoader.request.QueryInterface(Ci.nsIHttpChannel); // Convert the stream, falling back to utf-8 in case its not given. let result = new TextDecoder(httpChannel.contentCharset || "utf-8").decode(Uint8Array.from(aResult)); if (result === null) { - this.fail(Components.results.NS_ERROR_FAILURE, + this.fail(Cr.NS_ERROR_FAILURE, "Could not convert bytestream to Unicode: " + e); return; } let objData; try { if (result.length) { objData = JSON.parse(result); } else { objData = { status: "No Content" }; } } catch (e) { cal.ERROR("[calGoogleCalendar] Could not parse API response as " + "JSON: " + result); - this.fail(Components.results.NS_ERROR_FAILURE, result); + this.fail(Cr.NS_ERROR_FAILURE, result); } // Calculate Google Clock Skew let serverDate = new Date(httpChannel.getResponseHeader("Date")); let curDate = new Date(); // The utility function getCorrectedDate in calGoogleUtils.js receives // its clock skew seconds from here. The clock skew is updated on each @@ -453,36 +451,36 @@ calGoogleRequest.prototype = { if (this.calendar) { this.calendar.setProperty("disabled", true); this.calendar.setProperty("currentStatus", calGoogleRequest.QUOTA_FAILURE); } this.fail(calGoogleRequest.QUOTA_FAILURE, reason); break; case "insufficientPermissions": if (this.type == this.MODIFY || this.type == this.DELETE || this.type == this.ADD) { - this.fail(cIE.MODIFICATION_FAILED, objData); + this.fail(Ci.calIErrors.MODIFICATION_FAILED, objData); } else { - this.fail(cIE.READ_FAILED, objData); + this.fail(Ci.calIErrors.READ_FAILED, objData); } break; case "authError": case "invalidCredentials": this.mSession.invalidate(); if (this.reauthenticate) { this.reauthenticate = false; this.mSession.asyncItemRequest(this); } else { this.fail(calGoogleRequest.LOGIN_FAILED, reason); } break; default: if (this.calendar) { - this.calendar.setProperty("currentStatus", Components.results.NS_ERROR_FAILURE); + this.calendar.setProperty("currentStatus", Cr.NS_ERROR_FAILURE); } - this.fail(Components.results.NS_ERROR_FAILURE, result); + this.fail(Cr.NS_ERROR_FAILURE, result); break; } break; } case 404: /* The resource was not found on the server, which is also a conflict */ // 404 NOT FOUND: Resource (such as a feed or entry) not found. @@ -518,14 +516,14 @@ calGoogleRequest.prototype = { // Something else went wrong let msg = "A request Error Occurred. Status Code: " + httpChannel.responseStatus + " " + httpChannel.responseStatusText + " Body: " + result; cal.LOG("[calGoogleCalendar] " + msg); - this.fail(Components.results.NS_ERROR_NOT_AVAILABLE, msg); + this.fail(Cr.NS_ERROR_NOT_AVAILABLE, msg); break; } } } }; diff --git a/calendar/providers/gdata/modules/gdataSession.jsm b/calendar/providers/gdata/modules/gdataSession.jsm --- a/calendar/providers/gdata/modules/gdataSession.jsm +++ b/calendar/providers/gdata/modules/gdataSession.jsm @@ -14,18 +14,18 @@ ChromeUtils.import("resource://gre/modul ChromeUtils.import("resource://gre/modules/Timer.jsm"); ChromeUtils.import("resource:///modules/iteratorUtils.jsm"); ChromeUtils.import("resource://calendar/modules/calUtils.jsm"); ChromeUtils.import("resource://gdata-provider/modules/calUtilsShim.jsm"); -var cIFBI = Components.interfaces.calIFreeBusyInterval; -var nIPM = Components.interfaces.nsIPermissionManager; +var cIFBI = Ci.calIFreeBusyInterval; +var nIPM = Ci.nsIPermissionManager; var NOTIFY_TIMEOUT = 60 * 1000; var EXPORTED_SYMBOLS = ["getGoogleSessionManager"]; var gdataSessionMap = new Map(); var calGoogleSessionManager = { /** @@ -152,17 +152,17 @@ calGoogleSession.prototype = { get: function() { if (!this.mRefreshToken) { let pass = { value: null }; try { let origin = "oauth:" + sessionId; cal.auth.passwordManagerGet(sessionId, pass, origin, pwMgrId); } catch (e) { // User might have cancelled the master password prompt, thats ok - if (e.result != Components.results.NS_ERROR_ABORT) { + if (e.result != Cr.NS_ERROR_ABORT) { throw e; } } this.mRefreshToken = pass.value; } return this.mRefreshToken; }, set: function(val) { @@ -171,32 +171,32 @@ calGoogleSession.prototype = { if (val) { cal.auth.passwordManagerSave(sessionId, val, origin, pwMgrId); } else { cal.auth.passwordManagerRemove(sessionId, origin, pwMgrId); } } catch (e) { // User might have cancelled the master password prompt, or password saving // could be disabled. That is ok, throw for everything else. - if (e.result != Components.results.NS_ERROR_ABORT && - e.result != Components.results.NS_ERROR_NOT_AVAILABLE) { + if (e.result != Cr.NS_ERROR_ABORT && + e.result != Cr.NS_ERROR_NOT_AVAILABLE) { throw e; } } return (this.mRefreshToken = val); }, enumerable: true }); // If the user has disabled cookies, we need to add an exception for // Google so authentication works. If the user has explicitly blocked // google.com then we won't overwrite the rule though. if (Preferences.get("network.cookie.cookieBehavior") == 2) { let found = null; - for (let perm of fixIterator(Services.perms.enumerator, Components.interfaces.nsIPermission)) { + for (let perm of fixIterator(Services.perms.enumerator, Ci.nsIPermission)) { if (perm.type == "cookie" && perm.host == "google.com") { found = perm; break; } } if (!found || found.capability != nIPM.DENY_ACTION) { let uri = Services.io.newURI("http://google.com"); @@ -286,18 +286,18 @@ calGoogleSession.prototype = { return true; }, onPromptAuthAvailable: function() { self.oauth.connect(authSuccess, authFailed, true, false); }, onPromptCanceled: authFailed }; - let asyncprompter = Components.classes["@mozilla.org/messenger/msgAsyncPrompter;1"] - .getService(Components.interfaces.nsIMsgAsyncPrompter); + let asyncprompter = Cc["@mozilla.org/messenger/msgAsyncPrompter;1"] + .getService(Ci.nsIMsgAsyncPrompter); asyncprompter.queueAsyncAuthPrompt("googleapi://" + this.id, false, promptlistener); }.bind(this); if (accessToken) { deferred.resolve(accessToken); } else { cal.LOG("[calGoogleCalendar] No access token for " + this.mId + ", refreshing token"); @@ -359,18 +359,17 @@ calGoogleSession.prototype = { return this.mLoginPromise.then(() => { return aRequest.commit(this); }, (e) => { // If the user cancelled the login dialog, then disable the // calendar until the next startup or manual enable. if (aRequest.calendar && e.message == "cancelled") { aRequest.calendar.setProperty("disabled", true); aRequest.calendar.setProperty("auto-enabled", true); - aRequest.calendar.setProperty("currentStatus", - Components.results.NS_ERROR_FAILURE); + aRequest.calendar.setProperty("currentStatus", Cr.NS_ERROR_FAILURE); } throw e; }); } else { // Not logging in and no token, get the login promise and retry. this.mLoginPromise = this.login(); return this.asyncItemRequest(aRequest); @@ -403,32 +402,32 @@ calGoogleSession.prototype = { /** * calIFreeBusyProvider Implementation */ getFreeBusyIntervals: function(aCalId, aRangeStart, aRangeEnd, aBusyTypes, aListener) { let completeSync = (aIntervals) => { cal.LOG("[calGoogleCalendar] Freebusy query for " + aCalId + "suceeded, returning " + aIntervals.length + " intervals"); - aListener.onResult({ status: Components.results.NS_OK }, aIntervals); + aListener.onResult({ status: Cr.NS_OK }, aIntervals); }; let failSync = (aStatus, aMessage) => { cal.LOG("[calGoogleCalendar] Freebusy query for " + aCalId + " failed (" + aStatus + "): " + aMessage); // Usually we would notify with a result, but this causes trouble // with Lightning 3.9 and older. aListener.onResult({ status: aStatus }, null); }; if (!aCalId.includes("@") || !aCalId.includes(".") || !aCalId.toLowerCase().startsWith("mailto:")) { // No valid email, screw it - return failSync(Components.results.NS_ERROR_FAILURE, null); + return failSync(Cr.NS_ERROR_FAILURE, null); } if (aRangeStart) { aRangeStart = aRangeStart.getInTimezone(cal.dtz.UTC); } if (aRangeEnd) { aRangeEnd = aRangeEnd.getInTimezone(cal.dtz.UTC); } @@ -454,32 +453,32 @@ calGoogleSession.prototype = { // Request Parameters this.asyncItemRequest(request).then((aData) => { if ("calendars" in aData && strippedCalId in aData.calendars) { let calData = aData.calendars[strippedCalId]; let reason = calData.errors && calData.errors[0] && calData.errors[0].reason; if (reason) { cal.LOG("[calGoogleCalendar] Could not request freebusy for " + strippedCalId + ": " + reason); - failSync(Components.results.NS_ERROR_FAILURE, reason); + failSync(Cr.NS_ERROR_FAILURE, reason); } else { let utcZone = cal.dtz.UTC; cal.LOG("[calGoogleCalendar] Found " + calData.busy.length + " busy slots within range for " + strippedCalId); let busyRanges = calData.busy.map((entry) => { let start = cal.dtz.fromRFC3339(entry.start, utcZone); let end = cal.dtz.fromRFC3339(entry.end, utcZone); let interval = new cal.provider.FreeBusyInterval(aCalId, cIFBI.BUSY, start, end); LOGinterval(interval); return interval; }); completeSync(busyRanges); } } else { cal.ERROR("[calGoogleCalendar] Invalid freebusy response: " + aData.toSource()); - failSync(Components.results.NS_ERROR_FAILURE, (aData && aData.toSource())); + failSync(Cr.NS_ERROR_FAILURE, (aData && aData.toSource())); } }, (e) => { cal.ERROR("[calGoogleCalendar] Failed freebusy request: " + e); return failSync(request.status, null); }); return request; }, diff --git a/calendar/providers/gdata/modules/gdataUtils.jsm b/calendar/providers/gdata/modules/gdataUtils.jsm --- a/calendar/providers/gdata/modules/gdataUtils.jsm +++ b/calendar/providers/gdata/modules/gdataUtils.jsm @@ -9,18 +9,16 @@ ChromeUtils.import("resource://gdata-pro ChromeUtils.import("resource://gre/modules/Services.jsm"); ChromeUtils.import("resource://gre/modules/Preferences.jsm"); ChromeUtils.import("resource://gre/modules/PromiseUtils.jsm"); ChromeUtils.import("resource://calendar/modules/calUtils.jsm"); ChromeUtils.import("resource://gdata-provider/modules/calUtilsShim.jsm"); -var cIE = Components.interfaces.calIErrors; - var FOUR_WEEKS_IN_MINUTES = 40320; var EXPORTED_SYMBOLS = [ "ItemToJSON", "JSONToItem", "ItemSaver", "checkResolveConflict", "getGoogleId", "getItemMetadata", "saveItemMetadata", "deleteItemMetadata", "migrateItemMetadata", "JSONToAlarm", "dateToJSON", "JSONToDate", @@ -322,17 +320,17 @@ function EventToJSON(aItem, aOfflineStor // eventStatus let status = aItem.status && aItem.status.toLowerCase(); if (status == "cancelled") { // If the status is canceled, then the event will be deleted. Since the // user didn't choose to delete the event, we will protect him and not // allow this status to be set throw new Components.Exception("The status CANCELLED is reserved, delete the event instead!", - Components.results.NS_ERROR_LOSS_OF_SIGNIFICANT_DATA); + Cr.NS_ERROR_LOSS_OF_SIGNIFICANT_DATA); } else if (status == "none") { status = null; } setIf(itemData, "status", status); // Google does not support categories natively, but allows us to store data // as an "extendedProperty", so we do here let categories = cal.category.arrayToString(aItem.getCategories({})); @@ -451,17 +449,17 @@ function EventToJSON(aItem, aOfflineStor if (aItem.recurrenceInfo) { // This is an evil workaround since we don't have a really good system // to save the snooze time for recurring alarms or even retrieve them // from the event. This should change when we have multiple alarms // support. let snoozeObj = {}; let enumerator = aItem.propertyEnumerator; while (enumerator.hasMoreElements()) { - let prop = enumerator.getNext().QueryInterface(Components.interfaces.nsIProperty); + let prop = enumerator.getNext().QueryInterface(Ci.nsIProperty); if (prop.name.substr(0, 18) == "X-MOZ-SNOOZE-TIME-") { // We have a snooze time for a recurring event, add it to our object snoozeObj[prop.name.substr(18)] = prop.value; } } if (Object.keys(snoozeObj).length > 0) { snoozeValue = JSON.stringify(snoozeObj); } @@ -471,17 +469,17 @@ function EventToJSON(aItem, aOfflineStor addExtendedProperty("X-GOOGLE-SNOOZE-RECUR", snoozeValue, true); // recurrence information if (aItem.recurrenceInfo) { itemData.recurrence = []; let recurrenceItems = aItem.recurrenceInfo.getRecurrenceItems({}); for (let ritem of recurrenceItems) { let prop = ritem.icalProperty; - if (ritem instanceof Components.interfaces.calIRecurrenceDate) { + if (ritem instanceof Ci.calIRecurrenceDate) { // EXDATES require special casing, since they might contain // a TZID. To avoid the need for conversion of TZID strings, // convert to UTC before serialization. prop.valueAsDatetime = ritem.date.getInTimezone(cal.dtz.UTC); } itemData.recurrence.push(prop.icalString.trim()); } } else if (aItem.recurrenceId) { @@ -589,18 +587,18 @@ function setupRecurrence(aItem, aRecurre let hasRecurringRules = false; for (let prop = rootComp.getFirstProperty("ANY"); prop; prop = rootComp.getNextProperty("ANY")) { switch (prop.propertyName) { case "RDATE": case "EXDATE": { - let recItem = Components.classes["@mozilla.org/calendar/recurrence-date;1"] - .createInstance(Components.interfaces.calIRecurrenceDate); + let recItem = Cc["@mozilla.org/calendar/recurrence-date;1"] + .createInstance(Ci.calIRecurrenceDate); try { recItem.icalProperty = prop; aItem.recurrenceInfo.appendRecurrenceItem(recItem); hasRecurringRules = true; } catch (e) { cal.ERROR("[calGoogleCalendar] Error parsing " + prop.propertyName + " (" + prop.icalString + "):" + e); @@ -640,17 +638,17 @@ function JSONToAlarm(aEntry, aDefault) { const alarmActionMap = { email: "EMAIL", popup: "DISPLAY", sms: "SMS" }; let alarm = cal.createAlarm(); let alarmOffset = cal.createDuration(); alarm.action = alarmActionMap[aEntry.method] || "DISPLAY"; - alarm.related = Components.interfaces.calIAlarm.ALARM_RELATED_START; + alarm.related = Ci.calIAlarm.ALARM_RELATED_START; alarmOffset.inSeconds = -aEntry.minutes * 60; alarmOffset.normalize(); alarm.offset = alarmOffset; if (aDefault) { alarm.setProperty("X-DEFAULT-ALARM", "TRUE"); } return alarm; @@ -972,17 +970,17 @@ ItemSaver.prototype = { if (aData.kind == "calendar#events") { this.activity.type = "Event"; return this.parseEventStream(aData); } else if (aData.kind == "tasks#tasks") { this.activity.type = "Task"; return this.parseTaskStream(aData); } else { let message = "Invalid Stream type: " + (aData ? aData.kind || aData.toSource() : null); - throw new Components.Exception(message, Components.results.NS_ERROR_FAILURE); + throw new Components.Exception(message, Cr.NS_ERROR_FAILURE); } }, /** * Parse the response from Google's list command into tasks and modify the * calendar's offline storage to reflect those changes. * * @param aData The JS Object from the list response. @@ -1192,56 +1190,54 @@ ItemSaver.prototype = { parent.setProperty("X-MOZ-FAKED-MASTER", "1"); if (!parent.id) { // Exceptions often don't have the iCalUID field set, // we need to fake it from the google id. let meta = this.metaData[exc.hashId]; parent.id = meta.path + "@google.com"; } parent.recurrenceInfo = cal.createRecurrenceInfo(parent); - let rdate = Components.classes["@mozilla.org/calendar/recurrence-date;1"] - .createInstance(Components.interfaces.calIRecurrenceDate); + let rdate = Cc["@mozilla.org/calendar/recurrence-date;1"] + .createInstance(Ci.calIRecurrenceDate); rdate.date = exc.recurrenceId; parent.recurrenceInfo.appendRecurrenceItem(rdate); await this.commitItem(parent); } } } }; /** * A wrapper for nsIActivity to handle the synchronization process. * * @param aCalendar The calendar for this activity. */ function ActivityShell(aCalendar) { this.calendar = aCalendar; - if ("@mozilla.org/activity-process;1" in Components.classes) { + if ("@mozilla.org/activity-process;1" in Cc) { this.init(); } } ActivityShell.prototype = { act: null, actMgr: null, calendar: null, type: null, init: function() { - this.actMgr = Components.classes["@mozilla.org/activity-manager;1"] - .getService(Components.interfaces.nsIActivityManager); - this.act = Components.classes["@mozilla.org/activity-process;1"] - .createInstance(Components.interfaces.nsIActivityProcess); + this.actMgr = Cc["@mozilla.org/activity-manager;1"].getService(Ci.nsIActivityManager); + this.act = Cc["@mozilla.org/activity-process;1"].createInstance(Ci.nsIActivityProcess); this.act.init(getProviderString("syncStatus", this.calendar.name), this); this.act.iconClass = "syncMail"; this.act.contextType = "gdata-calendar"; this.act.contextObj = this.calendar; this.act.contextDisplayText = this.calendar.name; - this.act.state = Components.interfaces.nsIActivityProcess.STATE_INPROGRESS; + this.act.state = Ci.nsIActivityProcess.STATE_INPROGRESS; this.actMgr.addActivity(this.act); }, addProgress: function(units) { if (!this.act) { return; } @@ -1264,17 +1260,17 @@ ActivityShell.prototype = { }, complete: function() { if (!this.act) { return; } let total = this.act.totalWorkUnits; this.act.setProgress("", total, total); - this.act.state = Components.interfaces.nsIActivityProcess.STATE_COMPLETED; + this.act.state = Ci.nsIActivityProcess.STATE_COMPLETED; this.actMgr.removeActivity(this.act.id); } }; /** * Check if the response is a conflict and handle asking the user what to do * about it. Will resolve if there is no conflict or with new item data. * where status is a conflict status, see the end of this function. @@ -1306,17 +1302,17 @@ async function checkResolveConflict(aOpe throw e; } } } else { // The user has decided to throw away changes, use our existing // means to update the item locally. cal.LOG("[calGoogleCalendar] Reload requested, cancelling change of " + aItem.title); aCalendar.superCalendar.refresh(); - throw Components.Exception(null, cIE.OPERATION_CANCELLED); + throw Components.Exception(null, Ci.calIErrors.OPERATION_CANCELLED); } } /** * Get a string from the gdata properties file * * @param aStringName The name of the string within the properties file * @param ...aParams Optional parameters to format the string @@ -1339,17 +1335,17 @@ function monkeyPatch(obj, x, func) { let old = obj[x]; obj[x] = function() { let parent = old.bind(obj); let args = Array.from(arguments); args.unshift(parent); try { return func.apply(obj, args); } catch (e) { - Components.utils.reportError(e); + Cu.reportError(e); throw e; } }; } /** * Returns a promise that resolves after pending events have been processed. */ diff --git a/calendar/providers/ics/calICSCalendar.js b/calendar/providers/ics/calICSCalendar.js --- a/calendar/providers/ics/calICSCalendar.js +++ b/calendar/providers/ics/calICSCalendar.js @@ -12,18 +12,18 @@ ChromeUtils.import("resource://calendar/ // calICSCalendar.js // // This is a non-sync ics file. It reads the file pointer to by uri when set, // then writes it on updates. External changes to the file will be // ignored and overwritten. // // XXX Should do locks, so that external changes are not overwritten. -var calICalendar = Components.interfaces.calICalendar; -var calIErrors = Components.interfaces.calIErrors; +var calICalendar = Ci.calICalendar; +var calIErrors = Ci.calIErrors; function icsNSResolver(prefix) { const ns = { D: "DAV:" }; // eslint-disable-line id-length return ns[prefix] || null; } function icsXPathFirst(aNode, aExpr, aType) { return cal.xml.evalXPathFirst(aNode, aExpr, icsNSResolver, aType); @@ -35,41 +35,41 @@ function calICSCalendar() { this.unmappedComponents = []; this.unmappedProperties = []; this.queue = []; this.mModificationActions = []; } var calICSCalendarClassID = Components.ID("{f8438bff-a3c9-4ed5-b23f-2663b5469abf}"); var calICSCalendarInterfaces = [ - Components.interfaces.calICalendarProvider, - Components.interfaces.calICalendar, - Components.interfaces.calISchedulingSupport, - Components.interfaces.nsIStreamListener, - Components.interfaces.nsIStreamLoaderObserver, - Components.interfaces.nsIChannelEventSink, - Components.interfaces.nsIInterfaceRequestor, + Ci.calICalendarProvider, + Ci.calICalendar, + Ci.calISchedulingSupport, + Ci.nsIStreamListener, + Ci.nsIStreamLoaderObserver, + Ci.nsIChannelEventSink, + Ci.nsIInterfaceRequestor, ]; calICSCalendar.prototype = { __proto__: cal.provider.BaseClass.prototype, classID: calICSCalendarClassID, QueryInterface: XPCOMUtils.generateQI(calICSCalendarInterfaces), classInfo: XPCOMUtils.generateCI({ classID: calICSCalendarClassID, contractID: "@mozilla.org/calendar/calendar;1?type=ics", classDescription: "Calendar ICS provider", interfaces: calICSCalendarInterfaces, }), mObserver: null, locked: false, initICSCalendar: function() { - this.mMemoryCalendar = Components.classes["@mozilla.org/calendar/calendar;1?type=memory"] - .createInstance(Components.interfaces.calICalendar); + this.mMemoryCalendar = Cc["@mozilla.org/calendar/calendar;1?type=memory"] + .createInstance(Ci.calICalendar); this.mMemoryCalendar.superCalendar = this; this.mObserver = new calICSObserver(this); this.mMemoryCalendar.addObserver(this.mObserver); // XXX Not removed }, // // calICalendarProvider interface @@ -105,20 +105,20 @@ calICSCalendar.prototype = { this.mMemoryCalendar.uri = this.mUri; // Use the ioservice, to create a channel, which makes finding the // right hooks to use easier. let channel = Services.io.newChannelFromURI2(this.mUri, null, Services.scriptSecurityManager.getSystemPrincipal(), null, - Components.interfaces.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, - Components.interfaces.nsIContentPolicy.TYPE_OTHER); - let wHttpChannel = cal.wrapInstance(channel, Components.interfaces.nsIHttpChannel); - let wFileChannel = cal.wrapInstance(channel, Components.interfaces.nsIFileChannel); + Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, + Ci.nsIContentPolicy.TYPE_OTHER); + let wHttpChannel = cal.wrapInstance(channel, Ci.nsIHttpChannel); + let wFileChannel = cal.wrapInstance(channel, Ci.nsIFileChannel); if (wHttpChannel) { this.mHooks = new httpHooks(this); } else if (wFileChannel) { this.mHooks = new fileHooks(this); } else { this.mHooks = new dummyHooks(this); } @@ -138,51 +138,51 @@ calICSCalendar.prototype = { }, forceRefresh: function() { this.queue.push({ action: "refresh", forceRefresh: true }); this.processQueue(); }, prepareChannel: function(aChannel, aForceRefresh) { - aChannel.loadFlags |= Components.interfaces.nsIRequest.LOAD_BYPASS_CACHE; + aChannel.loadFlags |= Ci.nsIRequest.LOAD_BYPASS_CACHE; aChannel.notificationCallbacks = this; // Allow the hook to do its work, like a performing a quick check to // see if the remote file really changed. Might save a lot of time this.mHooks.onBeforeGet(aChannel, aForceRefresh); }, createMemoryCalendar: function() { // Create a new calendar, to get rid of all the old events // Don't forget to remove the observer if (this.mMemoryCalendar) { this.mMemoryCalendar.removeObserver(this.mObserver); } - this.mMemoryCalendar = Components.classes["@mozilla.org/calendar/calendar;1?type=memory"] - .createInstance(Components.interfaces.calICalendar); + this.mMemoryCalendar = Cc["@mozilla.org/calendar/calendar;1?type=memory"] + .createInstance(Ci.calICalendar); this.mMemoryCalendar.uri = this.mUri; this.mMemoryCalendar.superCalendar = this; }, doRefresh: function(aForce) { - let prbForce = Components.classes["@mozilla.org/supports-PRBool;1"] - .createInstance(Components.interfaces.nsISupportsPRBool); + let prbForce = Cc["@mozilla.org/supports-PRBool;1"] + .createInstance(Ci.nsISupportsPRBool); prbForce.data = aForce; let channel = Services.io.newChannelFromURI2(this.mUri, null, Services.scriptSecurityManager.getSystemPrincipal(), null, - Components.interfaces.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, - Components.interfaces.nsIContentPolicy.TYPE_OTHER); + Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, + Ci.nsIContentPolicy.TYPE_OTHER); this.prepareChannel(channel, aForce); - let streamLoader = Components.classes["@mozilla.org/network/stream-loader;1"] - .createInstance(Components.interfaces.nsIStreamLoader); + let streamLoader = Cc["@mozilla.org/network/stream-loader;1"] + .createInstance(Ci.nsIStreamLoader); // Lock other changes to the item list. this.lock(); try { streamLoader.init(this); channel.asyncOpen(streamLoader, prbForce); } catch (e) { @@ -190,24 +190,24 @@ calICSCalendar.prototype = { cal.LOG("[calICSCalendar] Error occurred opening channel: " + e); this.unlock(); } }, // nsIChannelEventSink implementation asyncOnChannelRedirect: function(aOldChannel, aNewChannel, aFlags, aCallback) { this.prepareChannel(aNewChannel, true); - aCallback.onRedirectVerifyCallback(Components.results.NS_OK); + aCallback.onRedirectVerifyCallback(Cr.NS_OK); }, // nsIStreamLoaderObserver impl // Listener for download. Parse the downloaded file onStreamComplete: function(loader, ctxt, status, resultLength, result) { - let forceRefresh = ctxt.QueryInterface(Components.interfaces.nsISupportsPRBool).data; + let forceRefresh = ctxt.QueryInterface(Ci.nsISupportsPRBool).data; let cont = false; if (Components.isSuccessCode(status)) { // Allow the hook to get needed data (like an etag) of the channel cont = this.mHooks.onAfterGet(loader.request, forceRefresh); cal.LOG("[calICSCalendar] Loading ICS succeeded, needs further processing: " + cont); } else { // Failure may be due to temporary connection issue, keep old data to @@ -248,18 +248,18 @@ calICSCalendar.prototype = { this.createMemoryCalendar(); this.mObserver.onStartBatch(); // Wrap parsing in a try block. Will ignore errors. That's a good thing // for non-existing or empty files, but not good for invalid files. // That's why we put them in readOnly mode - let parser = Components.classes["@mozilla.org/calendar/ics-parser;1"] - .createInstance(Components.interfaces.calIIcsParser); + let parser = Cc["@mozilla.org/calendar/ics-parser;1"] + .createInstance(Ci.calIIcsParser); let self = this; let listener = { // calIIcsParsingListener onParsingComplete: function(rc, parser_) { try { for (let item of parser_.getItems({})) { self.mMemoryCalendar.adoptItem(item, null); } self.unmappedComponents = parser_.getComponents({}); @@ -284,52 +284,51 @@ calICSCalendar.prototype = { parser.parseString(str, null, listener); }, writeICS: function() { cal.LOG("[calICSCalendar] Commencing write of ICS Calendar " + this.name); this.lock(); try { if (!this.mUri) { - throw Components.results.NS_ERROR_FAILURE; + throw Cr.NS_ERROR_FAILURE; } // makeBackup will call doWriteICS this.makeBackup(this.doWriteICS); } catch (exc) { this.unlock(calIErrors.MODIFICATION_FAILED); throw exc; } }, doWriteICS: function() { cal.LOG("[calICSCalendar] Writing ICS File " + this.uri.spec); let self = this; let listener = { serializer: null, - QueryInterface: XPCOMUtils.generateQI([Components.interfaces.calIOperationListener]), + QueryInterface: XPCOMUtils.generateQI([Ci.calIOperationListener]), onOperationComplete: function(aCalendar, aStatus, aOperationType, aId, aDetail) { let inLastWindowClosingSurvivalArea = false; try { // All events are returned. Now set up a channel and a // streamloader to upload. onStopRequest will be called // once the write has finished let channel = Services.io.newChannelFromURI2(self.mUri, null, Services.scriptSecurityManager.getSystemPrincipal(), null, - Components.interfaces.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, - Components.interfaces.nsIContentPolicy.TYPE_OTHER); + Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, + Ci.nsIContentPolicy.TYPE_OTHER); // Allow the hook to add things to the channel, like a // header that checks etags let notChanged = self.mHooks.onBeforePut(channel); if (notChanged) { channel.notificationCallbacks = self; - let uploadChannel = channel.QueryInterface( - Components.interfaces.nsIUploadChannel); + let uploadChannel = channel.QueryInterface(Ci.nsIUploadChannel); // Serialize let icsStream = this.serializer.serializeToInputStream(); // Upload uploadChannel.setUploadStream(icsStream, "text/calendar", -1); @@ -356,18 +355,18 @@ calICSCalendar.prototype = { self.unlock(calIErrors.MODIFICATION_FAILED); self.forceRefresh(); } }, onGetResult: function(aCalendar, aStatus, aItemType, aDetail, aCount, aItems) { this.serializer.addItems(aItems, aCount); } }; - listener.serializer = Components.classes["@mozilla.org/calendar/ics-serializer;1"] - .createInstance(Components.interfaces.calIIcsSerializer); + listener.serializer = Cc["@mozilla.org/calendar/ics-serializer;1"] + .createInstance(Ci.calIIcsSerializer); for (let comp of this.unmappedComponents) { listener.serializer.addComponent(comp); } for (let prop of this.unmappedProperties) { switch (prop.propertyName) { // we always set the current name and timezone: case "X-WR-CALNAME": case "X-WR-TIMEZONE": @@ -390,28 +389,27 @@ calICSCalendar.prototype = { }, // nsIStreamListener impl // For after publishing. Do error checks here onStartRequest: function(request, ctxt) {}, onDataAvailable: function(request, ctxt, inStream, sourceOffset, count) { // All data must be consumed. For an upload channel, there is // no meaningfull data. So it gets read and then ignored - let scriptableInputStream = - Components.classes["@mozilla.org/scriptableinputstream;1"] - .createInstance(Components.interfaces.nsIScriptableInputStream); + let scriptableInputStream = Cc["@mozilla.org/scriptableinputstream;1"] + .createInstance(Ci.nsIScriptableInputStream); scriptableInputStream.init(inStream); scriptableInputStream.read(-1); }, onStopRequest: function(request, ctxt, status, errorMsg) { ctxt = ctxt.wrappedJSObject; let httpChannel; let requestSucceeded = false; try { - httpChannel = request.QueryInterface(Components.interfaces.nsIHttpChannel); + httpChannel = request.QueryInterface(Ci.nsIHttpChannel); requestSucceeded = httpChannel.requestSucceeded; } catch (e) { // This may fail if it was not a http channel, handled later on. } if (httpChannel) { cal.LOG("[calICSCalendar] channel.requestSucceeded: " + requestSucceeded); } @@ -505,17 +503,17 @@ calICSCalendar.prototype = { if (this.isLocked()) { return; } function modListener(action) { this.mAction = action; } modListener.prototype = { - QueryInterface: XPCOMUtils.generateQI([Components.interfaces.calIOperationListener]), + QueryInterface: XPCOMUtils.generateQI([Ci.calIOperationListener]), onGetResult: function() {}, onOperationComplete: function() { this.mAction.opCompleteArgs = arguments; } }; let a; let writeICS = false; @@ -775,23 +773,23 @@ calICSCalendar.prototype = { purgeOldBackups(); // Now go download the remote file, and store it somewhere local. let channel = Services.io.newChannelFromURI2(this.mUri, null, Services.scriptSecurityManager.getSystemPrincipal(), null, - Components.interfaces.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, - Components.interfaces.nsIContentPolicy.TYPE_OTHER); - channel.loadFlags |= Components.interfaces.nsIRequest.LOAD_BYPASS_CACHE; + Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, + Ci.nsIContentPolicy.TYPE_OTHER); + channel.loadFlags |= Ci.nsIRequest.LOAD_BYPASS_CACHE; channel.notificationCallbacks = this; - let downloader = Components.classes["@mozilla.org/network/downloader;1"] - .createInstance(Ci.nsIDownloader); + let downloader = Cc["@mozilla.org/network/downloader;1"] + .createInstance(Ci.nsIDownloader); let self = this; let listener = { onDownloadComplete: function(opdownloader, request, ctxt, status, result) { if (doInitialBackup) { copyToOverwriting(result, backupDir, makeName("initial")); } if (doDailyBackup) { @@ -900,33 +898,33 @@ dummyHooks.prototype = { }; function httpHooks(calendar) { this.mCalendar = calendar; } httpHooks.prototype = { onBeforeGet: function(aChannel, aForceRefresh) { - let httpchannel = aChannel.QueryInterface(Components.interfaces.nsIHttpChannel); + let httpchannel = aChannel.QueryInterface(Ci.nsIHttpChannel); httpchannel.setRequestHeader("Accept", "text/calendar,text/plain;q=0.8,*/*;q=0.5", false); if (this.mEtag && !aForceRefresh) { // Somehow the webdav header 'If' doesn't work on apache when // passing in a Not, so use the http version here. httpchannel.setRequestHeader("If-None-Match", this.mEtag, false); } else if (!aForceRefresh && this.mLastModified) { // Only send 'If-Modified-Since' if no ETag is available httpchannel.setRequestHeader("If-Modified-Since", this.mLastModified, false); } return true; }, onAfterGet: function(aChannel, aForceRefresh) { - let httpchannel = aChannel.QueryInterface(Components.interfaces.nsIHttpChannel); + let httpchannel = aChannel.QueryInterface(Ci.nsIHttpChannel); let responseStatus = 0; let responseStatusCategory = 0; try { responseStatus = httpchannel.responseStatus; responseStatusCategory = Math.floor(responseStatus / 100); } catch (e) { // Error might have been a temporary connection issue, keep old data to @@ -970,27 +968,27 @@ httpHooks.prototype = { this.mLastModified = null; } return true; }, onBeforePut: function(aChannel) { if (this.mEtag) { - let httpchannel = aChannel.QueryInterface(Components.interfaces.nsIHttpChannel); + let httpchannel = aChannel.QueryInterface(Ci.nsIHttpChannel); // Apache doesn't work correctly with if-match on a PUT method, // so use the webdav header httpchannel.setRequestHeader("If", "([" + this.mEtag + "])", false); } return true; }, onAfterPut: function(aChannel, aRespFunc) { - let httpchannel = aChannel.QueryInterface(Components.interfaces.nsIHttpChannel); + let httpchannel = aChannel.QueryInterface(Ci.nsIHttpChannel); try { this.mEtag = httpchannel.getResponseHeader("ETag"); aRespFunc(); } catch (e) { // There was no ETag header on the response. This means that // putting is not atomic. This is bad. Race conditions can happen, // because there is a time in which we don't know the right // etag. @@ -1018,34 +1016,33 @@ httpHooks.prototype = { "" + ""; let etagChannel = cal.provider.prepHttpChannel(aChannel.URI, queryXml, "text/xml; charset=utf-8", this); etagChannel.setRequestHeader("Depth", "0", false); etagChannel.requestMethod = "PROPFIND"; - let streamLoader = Components.classes["@mozilla.org/network/stream-loader;1"] - .createInstance(Components.interfaces - .nsIStreamLoader); + let streamLoader = Cc["@mozilla.org/network/stream-loader;1"] + .createInstance(Ci.nsIStreamLoader); cal.provider.sendHttpRequest(streamLoader, etagChannel, etagListener); } return true; }, // nsIProgressEventSink onProgress: function(aRequest, aContext, aProgress, aProgressMax) {}, onStatus: function(aRequest, aContext, aStatus, aStatusArg) {}, getInterface: function(aIid) { - if (aIid.equals(Components.interfaces.nsIProgressEventSink)) { + if (aIid.equals(Ci.nsIProgressEventSink)) { return this; } else { - throw Components.results.NS_ERROR_NO_INTERFACE; + throw Cr.NS_ERROR_NO_INTERFACE; } } }; function fileHooks(calendar) { this.mCalendar = calendar; } @@ -1056,41 +1053,41 @@ fileHooks.prototype = { /** * @return * a boolean, false if the previous data should be used (the datastore * didn't change, there might be no data in this GET), true in all * other cases */ onAfterGet: function(aChannel, aForceRefresh) { - let filechannel = aChannel.QueryInterface(Components.interfaces.nsIFileChannel); + let filechannel = aChannel.QueryInterface(Ci.nsIFileChannel); if (this.mtime) { let newMtime = filechannel.file.lastModifiedTime; if (this.mtime == newMtime && !aForceRefresh) { return false; } else { this.mtime = newMtime; return true; } } else { this.mtime = filechannel.file.lastModifiedTime; return true; } }, onBeforePut: function(aChannel) { - let filechannel = aChannel.QueryInterface(Components.interfaces.nsIFileChannel); + let filechannel = aChannel.QueryInterface(Ci.nsIFileChannel); if (this.mtime && this.mtime != filechannel.file.lastModifiedTime) { return false; } else { return true; } }, onAfterPut: function(aChannel, aRespFunc) { - let filechannel = aChannel.QueryInterface(Components.interfaces.nsIFileChannel); + let filechannel = aChannel.QueryInterface(Ci.nsIFileChannel); this.mtime = filechannel.file.lastModifiedTime; aRespFunc(); return true; } }; this.NSGetFactory = XPCOMUtils.generateNSGetFactory([calICSCalendar]); diff --git a/calendar/providers/memory/calMemoryCalendar.js b/calendar/providers/memory/calMemoryCalendar.js --- a/calendar/providers/memory/calMemoryCalendar.js +++ b/calendar/providers/memory/calMemoryCalendar.js @@ -6,29 +6,29 @@ ChromeUtils.import("resource://gre/modul ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); ChromeUtils.import("resource://calendar/modules/calUtils.jsm"); // // calMemoryCalendar.js // -var cICL = Components.interfaces.calIChangeLog; +var cICL = Ci.calIChangeLog; function calMemoryCalendar() { this.initProviderBase(); this.initMemoryCalendar(); } var calMemoryCalendarClassID = Components.ID("{bda0dd7f-0a2f-4fcf-ba08-5517e6fbf133}"); var calMemoryCalendarInterfaces = [ - Components.interfaces.calICalendar, - Components.interfaces.calISchedulingSupport, - Components.interfaces.calIOfflineStorage, - Components.interfaces.calISyncWriteCalendar, - Components.interfaces.calICalendarProvider + Ci.calICalendar, + Ci.calISchedulingSupport, + Ci.calIOfflineStorage, + Ci.calISyncWriteCalendar, + Ci.calICalendarProvider ]; calMemoryCalendar.prototype = { __proto__: cal.provider.BaseClass.prototype, classID: calMemoryCalendarClassID, QueryInterface: XPCOMUtils.generateQI(calMemoryCalendarInterfaces), classInfo: XPCOMUtils.generateCI({ classID: calMemoryCalendarClassID, contractID: "@mozilla.org/calendar/calendar;1?type=memory", @@ -37,17 +37,17 @@ calMemoryCalendar.prototype = { }), mItems: null, mOfflineFlags: null, mObservers: null, mMetaData: null, initMemoryCalendar: function() { - this.mObservers = new cal.data.ObserverSet(Components.interfaces.calIObserver); + this.mObservers = new cal.data.ObserverSet(Ci.calIObserver); this.mItems = {}; this.mOfflineFlags = {}; this.mMetaData = new cal.data.PropertyMap(); }, // // calICalendarProvider interface // @@ -64,17 +64,17 @@ calMemoryCalendar.prototype = { }, deleteCalendar: function(calendar, listener) { calendar = calendar.wrappedJSObject; calendar.mItems = {}; calendar.mMetaData = new cal.data.PropertyMap(); try { - listener.onDeleteCalendar(calendar, Components.results.NS_OK, null); + listener.onDeleteCalendar(calendar, Cr.NS_OK, null); } catch (ex) { // Don't bail out if the listener fails } }, mRelaxedMode: undefined, get relaxedMode() { if (this.mRelaxedMode === undefined) { @@ -105,44 +105,44 @@ calMemoryCalendar.prototype = { addItem: function(aItem, aListener) { let newItem = aItem.clone(); return this.adoptItem(newItem, aListener); }, // void adoptItem( in calIItemBase aItem, in calIOperationListener aListener ); adoptItem: function(aItem, aListener) { if (this.readOnly) { - throw Components.interfaces.calIErrors.CAL_IS_READONLY; + throw Ci.calIErrors.CAL_IS_READONLY; } if (aItem.id == null && aItem.isMutable) { aItem.id = cal.getUUID(); } if (aItem.id == null) { this.notifyOperationComplete(aListener, - Components.results.NS_ERROR_FAILURE, - Components.interfaces.calIOperationListener.ADD, + Cr.NS_ERROR_FAILURE, + Ci.calIOperationListener.ADD, aItem.id, "Can't set ID on non-mutable item to addItem"); return; } // Lines below are commented because of the offline bug 380060, the // memory calendar cannot assume that a new item should not have an ID. // calCachedCalendar could send over an item with an id. /* if (this.mItems[aItem.id] != null) { if (this.relaxedMode) { // we possibly want to interact with the user before deleting delete this.mItems[aItem.id]; } else { this.notifyOperationComplete(aListener, - Components.interfaces.calIErrors.DUPLICATE_ID, - Components.interfaces.calIOperationListener.ADD, + Ci.calIErrors.DUPLICATE_ID, + Ci.calIOperationListener.ADD, aItem.id, "ID already exists for addItem"); return; } } */ let parentItem = aItem.parentItem; @@ -152,38 +152,38 @@ calMemoryCalendar.prototype = { } parentItem.calendar = this.superCalendar; parentItem.makeImmutable(); this.mItems[aItem.id] = parentItem; // notify the listener this.notifyOperationComplete(aListener, - Components.results.NS_OK, - Components.interfaces.calIOperationListener.ADD, + Cr.NS_OK, + Ci.calIOperationListener.ADD, aItem.id, aItem); // notify observers this.mObservers.notify("onAddItem", [aItem]); }, // void modifyItem( in calIItemBase aNewItem, in calIItemBase aOldItem, in calIOperationListener aListener ); modifyItem: function(aNewItem, aOldItem, aListener) { if (this.readOnly) { - throw Components.interfaces.calIErrors.CAL_IS_READONLY; + throw Ci.calIErrors.CAL_IS_READONLY; } if (!aNewItem) { - throw Components.results.NS_ERROR_INVALID_ARG; + throw Cr.NS_ERROR_INVALID_ARG; } let self = this; function reportError(errStr, errId) { self.notifyOperationComplete(aListener, - errId ? errId : Components.results.NS_ERROR_FAILURE, - Components.interfaces.calIOperationListener.MODIFY, + errId ? errId : Cr.NS_ERROR_FAILURE, + Ci.calIOperationListener.MODIFY, aNewItem.id, errStr); return null; } if (!aNewItem.id) { // this is definitely an error return reportError(null, "ID for modifyItem item is null"); @@ -239,113 +239,113 @@ calMemoryCalendar.prototype = { modifiedItem.generation += 1; } } modifiedItem.makeImmutable(); this.mItems[modifiedItem.id] = modifiedItem; this.notifyOperationComplete(aListener, - Components.results.NS_OK, - Components.interfaces.calIOperationListener.MODIFY, + Cr.NS_OK, + Ci.calIOperationListener.MODIFY, modifiedItem.id, modifiedItem); // notify observers this.mObservers.notify("onModifyItem", [modifiedItem, aOldItem]); return null; }, // void deleteItem( in calIItemBase aItem, in calIOperationListener aListener ); deleteItem: function(aItem, aListener) { if (this.readOnly) { this.notifyOperationComplete(aListener, - Components.interfaces.calIErrors.CAL_IS_READONLY, - Components.interfaces.calIOperationListener.DELETE, + Ci.calIErrors.CAL_IS_READONLY, + Ci.calIOperationListener.DELETE, aItem.id, "Calendar is readonly"); return; } if (aItem.id == null) { this.notifyOperationComplete(aListener, - Components.results.NS_ERROR_FAILURE, - Components.interfaces.calIOperationListener.DELETE, + Cr.NS_ERROR_FAILURE, + Ci.calIOperationListener.DELETE, aItem.id, "ID is null in deleteItem"); return; } let oldItem; if (this.relaxedMode) { oldItem = aItem; } else { oldItem = this.mItems[aItem.id]; if (oldItem.generation != aItem.generation) { this.notifyOperationComplete(aListener, - Components.results.NS_ERROR_FAILURE, - Components.interfaces.calIOperationListener.DELETE, + Cr.NS_ERROR_FAILURE, + Ci.calIOperationListener.DELETE, aItem.id, "generation mismatch in deleteItem"); return; } } delete this.mItems[aItem.id]; this.mMetaData.delete(aItem.id); this.notifyOperationComplete(aListener, - Components.results.NS_OK, - Components.interfaces.calIOperationListener.DELETE, + Cr.NS_OK, + Ci.calIOperationListener.DELETE, aItem.id, aItem); // notify observers this.mObservers.notify("onDeleteItem", [oldItem]); }, // void getItem( in string id, in calIOperationListener aListener ); getItem: function(aId, aListener) { if (!aListener) { return; } if (aId == null || this.mItems[aId] == null) { // querying by id is a valid use case, even if no item is returned: this.notifyOperationComplete(aListener, - Components.results.NS_OK, - Components.interfaces.calIOperationListener.GET, + Cr.NS_OK, + Ci.calIOperationListener.GET, aId, null); return; } let item = this.mItems[aId]; let iid = null; if (cal.item.isEvent(item)) { - iid = Components.interfaces.calIEvent; + iid = Ci.calIEvent; } else if (cal.item.isToDo(item)) { - iid = Components.interfaces.calITodo; + iid = Ci.calITodo; } else { this.notifyOperationComplete(aListener, - Components.results.NS_ERROR_FAILURE, - Components.interfaces.calIOperationListener.GET, + Cr.NS_ERROR_FAILURE, + Ci.calIOperationListener.GET, aId, "Can't deduce item type based on QI"); return; } aListener.onGetResult(this.superCalendar, - Components.results.NS_OK, + Cr.NS_OK, iid, null, 1, [item]); this.notifyOperationComplete(aListener, - Components.results.NS_OK, - Components.interfaces.calIOperationListener.GET, + Cr.NS_OK, + Ci.calIOperationListener.GET, aId, null); }, // void getItems( in unsigned long aItemFilter, in unsigned long aCount, // in calIDateTime aRangeStart, in calIDateTime aRangeEnd, // in calIOperationListener aListener ); getItems: function(aItemFilter, aCount, @@ -355,44 +355,44 @@ calMemoryCalendar.prototype = { }); }, getItems_: function(aItemFilter, aCount, aRangeStart, aRangeEnd, aListener) { if (!aListener) { return; } - const calICalendar = Components.interfaces.calICalendar; + const calICalendar = Ci.calICalendar; let itemsFound = []; // // filters // let wantUnrespondedInvitations = ((aItemFilter & calICalendar.ITEM_FILTER_REQUEST_NEEDS_ACTION) != 0); let superCal; try { - superCal = this.superCalendar.QueryInterface(Components.interfaces.calISchedulingSupport); + superCal = this.superCalendar.QueryInterface(Ci.calISchedulingSupport); } catch (exc) { wantUnrespondedInvitations = false; } function checkUnrespondedInvitation(item) { let att = superCal.getInvitedAttendee(item); return att && att.participationStatus == "NEEDS-ACTION"; } // item base type let wantEvents = ((aItemFilter & calICalendar.ITEM_FILTER_TYPE_EVENT) != 0); let wantTodos = ((aItemFilter & calICalendar.ITEM_FILTER_TYPE_TODO) != 0); if (!wantEvents && !wantTodos) { // bail. this.notifyOperationComplete(aListener, - Components.results.NS_ERROR_FAILURE, - Components.interfaces.calIOperationListener.GET, + Cr.NS_ERROR_FAILURE, + Ci.calIOperationListener.GET, null, "Bad aItemFilter passed to getItems"); return; } // completed? let itemCompletedFilter = ((aItemFilter & calICalendar.ITEM_FILTER_COMPLETED_YES) != 0); let itemNotCompletedFilter = ((aItemFilter & calICalendar.ITEM_FILTER_COMPLETED_NO) != 0); @@ -401,23 +401,23 @@ calMemoryCalendar.prototype = { } // return occurrences? let itemReturnOccurrences = ((aItemFilter & calICalendar.ITEM_FILTER_CLASS_OCCURRENCES) != 0); // figure out the return interface type let typeIID = null; if (itemReturnOccurrences) { - typeIID = Components.interfaces.calIItemBase; + typeIID = Ci.calIItemBase; } else if (wantEvents && wantTodos) { - typeIID = Components.interfaces.calIItemBase; + typeIID = Ci.calIItemBase; } else if (wantEvents) { - typeIID = Components.interfaces.calIEvent; + typeIID = Ci.calIEvent; } else if (wantTodos) { - typeIID = Components.interfaces.calITodo; + typeIID = Ci.calITodo; } aRangeStart = cal.dtz.ensureDateTime(aRangeStart); aRangeEnd = cal.dtz.ensureDateTime(aRangeEnd); let requestedFlag = 0; if ((aItemFilter & calICalendar.ITEM_FILTER_OFFLINE_CREATED) != 0) { requestedFlag = cICL.OFFLINE_FLAG_CREATED_RECORD; @@ -483,84 +483,84 @@ calMemoryCalendar.prototype = { itemsFound.push(item); } if (aCount && itemsFound.length >= aCount) { return cal.iterate.forEach.BREAK; } return cal.iterate.forEach.CONTINUE; }, () => { aListener.onGetResult(this.superCalendar, - Components.results.NS_OK, + Cr.NS_OK, typeIID, null, itemsFound.length, itemsFound); this.notifyOperationComplete(aListener, - Components.results.NS_OK, - Components.interfaces.calIOperationListener.GET, + Cr.NS_OK, + Ci.calIOperationListener.GET, null, null); }); }, // // calIOfflineStorage interface // addOfflineItem: function(aItem, aListener) { this.mOfflineFlags[aItem.id] = cICL.OFFLINE_FLAG_CREATED_RECORD; this.notifyOperationComplete(aListener, - Components.results.NS_OK, - Components.interfaces.calIOperationListener.ADD, + Cr.NS_OK, + Ci.calIOperationListener.ADD, aItem.id, aItem); }, modifyOfflineItem: function(aItem, aListener) { let oldFlag = this.mOfflineFlags[aItem.id]; if (oldFlag != cICL.OFFLINE_FLAG_CREATED_RECORD && oldFlag != cICL.OFFLINE_FLAG_DELETED_RECORD) { this.mOfflineFlags[aItem.id] = cICL.OFFLINE_FLAG_MODIFIED_RECORD; } this.notifyOperationComplete(aListener, - Components.results.NS_OK, - Components.interfaces.calIOperationListener.MODIFY, + Cr.NS_OK, + Ci.calIOperationListener.MODIFY, aItem.id, aItem); }, deleteOfflineItem: function(aItem, aListener) { let oldFlag = this.mOfflineFlags[aItem.id]; if (oldFlag == cICL.OFFLINE_FLAG_CREATED_RECORD) { delete this.mItems[aItem.id]; delete this.mOfflineFlags[aItem.id]; } else { this.mOfflineFlags[aItem.id] = cICL.OFFLINE_FLAG_DELETED_RECORD; } this.notifyOperationComplete(aListener, - Components.results.NS_OK, - Components.interfaces.calIOperationListener.DELETE, + Cr.NS_OK, + Ci.calIOperationListener.DELETE, aItem.id, aItem); // notify observers this.observers.notify("onDeleteItem", [aItem]); }, getItemOfflineFlag: function(aItem, aListener) { let flag = (aItem && aItem.id in this.mOfflineFlags ? this.mOfflineFlags[aItem.id] : null); - this.notifyOperationComplete(aListener, Components.results.NS_OK, - Components.interfaces.calIOperationListener.GET, + this.notifyOperationComplete(aListener, Cr.NS_OK, + Ci.calIOperationListener.GET, null, flag); }, resetItemOfflineFlag: function(aItem, aListener) { delete this.mOfflineFlags[aItem.id]; - this.notifyOperationComplete(aListener, Components.results.NS_OK, - Components.interfaces.calIOperationListener.MODIFY, + this.notifyOperationComplete(aListener, Cr.NS_OK, + Ci.calIOperationListener.MODIFY, aItem.id, aItem); }, // // calISyncWriteCalendar interface // setMetaData: function(id, value) { this.mMetaData.set(id, value); diff --git a/calendar/providers/storage/calStorageCalendar.js b/calendar/providers/storage/calStorageCalendar.js --- a/calendar/providers/storage/calStorageCalendar.js +++ b/calendar/providers/storage/calStorageCalendar.js @@ -5,36 +5,36 @@ ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); ChromeUtils.import("resource://gre/modules/Services.jsm"); ChromeUtils.import("resource://calendar/modules/calUtils.jsm"); ChromeUtils.import("resource://calendar/modules/calStorageUpgrade.jsm"); ChromeUtils.import("resource://calendar/modules/calStorageHelpers.jsm"); var USECS_PER_SECOND = 1000000; -var kCalICalendar = Components.interfaces.calICalendar; -var cICL = Components.interfaces.calIChangeLog; +var kCalICalendar = Ci.calICalendar; +var cICL = Ci.calIChangeLog; // // calStorageCalendar // function calStorageCalendar() { this.initProviderBase(); this.mItemCache = {}; this.mRecEventCache = {}; this.mRecTodoCache = {}; } var calStorageCalendarClassID = Components.ID("{b3eaa1c4-5dfe-4c0a-b62a-b3a514218461}"); var calStorageCalendarInterfaces = [ - Components.interfaces.calICalendar, - Components.interfaces.calICalendarProvider, - Components.interfaces.calIOfflineStorage, - Components.interfaces.calISchedulingSupport, - Components.interfaces.calISyncWriteCalendar, + Ci.calICalendar, + Ci.calICalendarProvider, + Ci.calIOfflineStorage, + Ci.calISchedulingSupport, + Ci.calISyncWriteCalendar, ]; calStorageCalendar.prototype = { __proto__: cal.provider.BaseClass.prototype, classID: calStorageCalendarClassID, QueryInterface: XPCOMUtils.generateQI(calStorageCalendarInterfaces), classInfo: XPCOMUtils.generateCI({ classID: calStorageCalendarClassID, contractID: "@mozilla.org/calendar/calendar;1?type=storage", @@ -110,17 +110,17 @@ calStorageCalendar.prototype = { this.prepareStatement(this.mDeleteAllMetaData); this.mDeleteAllMetaData.executeStep(); } finally { this.mDeleteAllMetaData.reset(); } try { if (listener) { - listener.onDeleteCalendar(aCalendar, Components.results.NS_OK, null); + listener.onDeleteCalendar(aCalendar, Cr.NS_OK, null); } } catch (ex) { this.logError("error calling listener.onDeleteCalendar", ex); } }, mRelaxedMode: undefined, get relaxedMode() { @@ -165,17 +165,17 @@ calStorageCalendar.prototype = { // attribute nsIURI uri; get uri() { return this.__proto__.__proto__.__lookupGetter__("uri").call(this); }, set uri(aUri) { // We can only load once if (this.uri) { - throw Components.results.NS_ERROR_FAILURE; + throw Cr.NS_ERROR_FAILURE; } let uri = this.__proto__.__proto__.__lookupSetter__("uri").call(this, aUri); if (!this.mDB && this.uri && this.id) { // Prepare the database as soon as we have an id and an uri. this.prepareInitDB(); } @@ -184,35 +184,35 @@ calStorageCalendar.prototype = { }, /** * Initialize the Database. This should only be called from the uri or id * setter and requires those two attributes to be set. */ prepareInitDB: function() { if (this.uri.schemeIs("file")) { - let fileURL = this.uri.QueryInterface(Components.interfaces.nsIFileURL); + let fileURL = this.uri.QueryInterface(Ci.nsIFileURL); if (!fileURL) { - throw new Components.Exception("Invalid file", Components.results.NS_ERROR_NOT_IMPLEMENTED); + throw new Components.Exception("Invalid file", Cr.NS_ERROR_NOT_IMPLEMENTED); } // open the database this.mDB = Services.storage.openDatabase(fileURL.file); this.mDB.executeSimpleSQL("PRAGMA journal_mode=WAL"); upgradeDB(this.mDB); } else if (this.uri.schemeIs("moz-profile-calendar")) { // This is an old-style moz-profile-calendar. It requires some // migration steps. let localDB = cal.provider.getCalendarDirectory(); localDB.append("local.sqlite"); localDB = Services.storage.openDatabase(localDB); // First, we need to check if this is from 0.9, i.e we need to // migrate from storage.sdb to local.sqlite. - let storageSdb = Services.dirsvc.get("ProfD", Components.interfaces.nsIFile); + let storageSdb = Services.dirsvc.get("ProfD", Ci.nsIFile); storageSdb.append("storage.sdb"); this.mDB = Services.storage.openDatabase(storageSdb); if (this.mDB.tableExists("cal_events")) { cal.LOG("[calStorageCalendar] Migrating storage.sdb -> local.sqlite"); upgradeDB(this.mDB); // upgrade schema before migating data let attachStatement; try { @@ -224,17 +224,17 @@ calStorageCalendar.prototype = { throw exc; } finally { if (attachStatement) { attachStatement.reset(); } } try { // hold lock on storage.sdb until we've migrated data from storage.sdb: - this.mDB.beginTransactionAs(Components.interfaces.mozIStorageConnection.TRANSACTION_EXCLUSIVE); + this.mDB.beginTransactionAs(Ci.mozIStorageConnection.TRANSACTION_EXCLUSIVE); try { if (this.mDB.tableExists("cal_events")) { // check again (with lock) // take over data and drop from storage.sdb tables: for (let table in getSqlTable(DB_SCHEMA_VERSION)) { if (table.substr(0, 4) != "idx_") { this.mDB.executeSimpleSQL("CREATE TABLE local_sqlite." + table + " AS SELECT * FROM " + table + "; DROP TABLE IF EXISTS " + table); @@ -265,17 +265,17 @@ calStorageCalendar.prototype = { // and its regression bug 561735. The first calendar created before // v19 already has a moz-profile-calendar:// uri without an ?id= // parameter (the id in the databse is 0). We need to migrate this // special calendar differently. // WARNING: This is a somewhat fragile process. Great care should be // taken during future schema upgrades to make sure this still // works. - this.mDB.beginTransactionAs(Components.interfaces.mozIStorageConnection.TRANSACTION_EXCLUSIVE); + this.mDB.beginTransactionAs(Ci.mozIStorageConnection.TRANSACTION_EXCLUSIVE); try { /** * Helper function to migrate all tables from one id to the next * * @param db The database to use * @param newCalId The new calendar id to set * @param oldCalId The old calendar id to look for */ @@ -409,36 +409,36 @@ calStorageCalendar.prototype = { let newItem = aItem.clone(); return this.adoptItem(newItem, aListener); }, // void adoptItem( in calIItemBase aItem, in calIOperationListener aListener ); adoptItem: function(aItem, aListener) { if (this.readOnly) { this.notifyOperationComplete(aListener, - Components.interfaces.calIErrors.CAL_IS_READONLY, - Components.interfaces.calIOperationListener.ADD, + Ci.calIErrors.CAL_IS_READONLY, + Ci.calIOperationListener.ADD, null, "Calendar is readonly"); return; } if (aItem.id == null) { // is this an error? Or should we generate an IID? aItem.id = cal.getUUID(); } else { let olditem = this.getItemById(aItem.id); if (olditem) { if (this.relaxedMode) { // we possibly want to interact with the user before deleting this.deleteItemById(aItem.id, true); } else { this.notifyOperationComplete(aListener, - Components.interfaces.calIErrors.DUPLICATE_ID, - Components.interfaces.calIOperationListener.ADD, + Ci.calIErrors.DUPLICATE_ID, + Ci.calIOperationListener.ADD, aItem.id, "ID already exists for addItem"); return; } } } let parentItem = aItem.parentItem; @@ -448,18 +448,18 @@ calStorageCalendar.prototype = { } parentItem.calendar = this.superCalendar; parentItem.makeImmutable(); this.flushItem(parentItem, null); // notify the listener this.notifyOperationComplete(aListener, - Components.results.NS_OK, - Components.interfaces.calIOperationListener.ADD, + Cr.NS_OK, + Ci.calIOperationListener.ADD, aItem.id, aItem); // notify observers this.observers.notify("onAddItem", [aItem]); }, // void modifyItem( in calIItemBase aNewItem, in calIItemBase aOldItem, in calIOperationListener aListener ); @@ -478,31 +478,31 @@ calStorageCalendar.prototype = { }; this.getItemOfflineFlag(aOldItem, offlineJournalFlagListener); }, doModifyItem: function(aNewItem, aOldItem, aListener, offlineFlag) { let oldOfflineFlag = offlineFlag; if (this.readOnly) { this.notifyOperationComplete(aListener, - Components.interfaces.calIErrors.CAL_IS_READONLY, - Components.interfaces.calIOperationListener.MODIFY, + Ci.calIErrors.CAL_IS_READONLY, + Ci.calIOperationListener.MODIFY, null, "Calendar is readonly"); return null; } if (!aNewItem) { - throw Components.results.NS_ERROR_INVALID_ARG; + throw Cr.NS_ERROR_INVALID_ARG; } let self = this; function reportError(errStr, errId) { self.notifyOperationComplete(aListener, - errId ? errId : Components.results.NS_ERROR_FAILURE, - Components.interfaces.calIOperationListener.MODIFY, + errId ? errId : Cr.NS_ERROR_FAILURE, + Ci.calIOperationListener.MODIFY, aNewItem.id, errStr); return null; } if (aNewItem.id == null) { // this is definitely an error return reportError("ID for modifyItem item is null"); @@ -559,57 +559,57 @@ calStorageCalendar.prototype = { } } modifiedItem.makeImmutable(); this.flushItem(modifiedItem, aOldItem); this.setOfflineJournalFlag(aNewItem, oldOfflineFlag); this.notifyOperationComplete(aListener, - Components.results.NS_OK, - Components.interfaces.calIOperationListener.MODIFY, + Cr.NS_OK, + Ci.calIOperationListener.MODIFY, modifiedItem.id, modifiedItem); // notify observers this.observers.notify("onModifyItem", [modifiedItem, aOldItem]); return null; }, // void deleteItem( in string id, in calIOperationListener aListener ); deleteItem: function(aItem, aListener) { if (this.readOnly) { this.notifyOperationComplete(aListener, - Components.interfaces.calIErrors.CAL_IS_READONLY, - Components.interfaces.calIOperationListener.DELETE, + Ci.calIErrors.CAL_IS_READONLY, + Ci.calIOperationListener.DELETE, null, "Calendar is readonly"); return; } if (aItem.parentItem != aItem) { aItem.parentItem.recurrenceInfo.removeExceptionFor(aItem.recurrenceId); // xxx todo: would we want to support this case? Removing an occurrence currently results // in a modifyItem(parent) return; } if (aItem.id == null) { this.notifyOperationComplete(aListener, - Components.results.NS_ERROR_FAILURE, - Components.interfaces.calIOperationListener.DELETE, + Cr.NS_ERROR_FAILURE, + Ci.calIOperationListener.DELETE, null, "ID is null for deleteItem"); return; } this.deleteItemById(aItem.id); this.notifyOperationComplete(aListener, - Components.results.NS_OK, - Components.interfaces.calIOperationListener.DELETE, + Cr.NS_OK, + Ci.calIOperationListener.DELETE, aItem.id, aItem); // notify observers this.observers.notify("onDeleteItem", [aItem]); }, // void getItem( in string id, in calIOperationListener aListener ); @@ -617,45 +617,45 @@ calStorageCalendar.prototype = { if (!aListener) { return; } let item = this.getItemById(aId); if (!item) { // querying by id is a valid use case, even if no item is returned: this.notifyOperationComplete(aListener, - Components.results.NS_OK, - Components.interfaces.calIOperationListener.GET, + Cr.NS_OK, + Ci.calIOperationListener.GET, aId, null); return; } let item_iid = null; if (cal.item.isEvent(item)) { - item_iid = Components.interfaces.calIEvent; + item_iid = Ci.calIEvent; } else if (cal.item.isToDo(item)) { - item_iid = Components.interfaces.calITodo; + item_iid = Ci.calITodo; } else { this.notifyOperationComplete(aListener, - Components.results.NS_ERROR_FAILURE, - Components.interfaces.calIOperationListener.GET, + Cr.NS_ERROR_FAILURE, + Ci.calIOperationListener.GET, aId, "Can't deduce item type based on QI"); return; } aListener.onGetResult(this.superCalendar, - Components.results.NS_OK, + Cr.NS_OK, item_iid, null, 1, [item]); this.notifyOperationComplete(aListener, - Components.results.NS_OK, - Components.interfaces.calIOperationListener.GET, + Cr.NS_OK, + Ci.calIOperationListener.GET, aId, null); }, // void getItems( in unsigned long aItemFilter, in unsigned long aCount, // in calIDateTime aRangeStart, in calIDateTime aRangeEnd, // in calIOperationListener aListener ); getItems: function(aItemFilter, aCount, aRangeStart, aRangeEnd, aListener) { @@ -679,17 +679,17 @@ calStorageCalendar.prototype = { } if (aRangeEnd) { endTime = aRangeEnd.nativeTime; } let wantUnrespondedInvitations = ((aItemFilter & kCalICalendar.ITEM_FILTER_REQUEST_NEEDS_ACTION) != 0); let superCal; try { - superCal = this.superCalendar.QueryInterface(Components.interfaces.calISchedulingSupport); + superCal = this.superCalendar.QueryInterface(Ci.calISchedulingSupport); } catch (exc) { wantUnrespondedInvitations = false; } function checkUnrespondedInvitation(item) { let att = superCal.getInvitedAttendee(item); return (att && (att.participationStatus == "NEEDS-ACTION")); } @@ -698,18 +698,18 @@ calStorageCalendar.prototype = { let asOccurrences = ((aItemFilter & kCalICalendar.ITEM_FILTER_CLASS_OCCURRENCES) != 0); let wantOfflineDeletedItems = ((aItemFilter & kCalICalendar.ITEM_FILTER_OFFLINE_DELETED) != 0); let wantOfflineCreatedItems = ((aItemFilter & kCalICalendar.ITEM_FILTER_OFFLINE_CREATED) != 0); let wantOfflineModifiedItems = ((aItemFilter & kCalICalendar.ITEM_FILTER_OFFLINE_MODIFIED) != 0); if (!wantEvents && !wantTodos) { // nothing to do this.notifyOperationComplete(aListener, - Components.results.NS_OK, - Components.interfaces.calIOperationListener.GET, + Cr.NS_OK, + Ci.calIOperationListener.GET, null, null); return; } // HACK because recurring offline events/todos objects dont have offline_journal information // Hence we need to update the mRecEventCacheOfflineFlags and mRecTodoCacheOfflineFlags hash-tables // It can be an expensive operation but is only used in Online Reconciliation mode @@ -745,17 +745,17 @@ calStorageCalendar.prototype = { } if (theItems) { queuedItems = queuedItems.concat(theItems); } if (queuedItems.length != 0 && (!theItems || queuedItems.length > maxQueueSize)) { aListener.onGetResult(self.superCalendar, - Components.results.NS_OK, + Cr.NS_OK, queuedItemsIID, null, queuedItems.length, queuedItems); queuedItems = []; } } // helper function to handle converting a row to an item, // expanding occurrences, and queue the items for the listener @@ -787,18 +787,18 @@ calStorageCalendar.prototype = { // check the count and send end if count is exceeded function checkCount() { if (aCount && count >= aCount) { // flush queue queueItems(null); // send operation complete self.notifyOperationComplete(aListener, - Components.results.NS_OK, - Components.interfaces.calIOperationListener.GET, + Cr.NS_OK, + Ci.calIOperationListener.GET, null, null); // tell caller we're done return true; } return false; @@ -836,31 +836,31 @@ calStorageCalendar.prototype = { } catch (e) { this.logError("Error selecting non recurring events by range!\n", e); } finally { this.mSelectNonRecurringEventsByRange.reset(); } // Process the non-recurring events: for (let evitem of resultItems) { - count += handleResultItem(evitem, Components.interfaces.calIEvent); + count += handleResultItem(evitem, Ci.calIEvent); if (checkCount()) { return; } } // Process the recurring events from the cache for (let id in this.mRecEventCache) { let evitem = this.mRecEventCache[id]; let cachedJournalFlag = this.mRecEventCacheOfflineFlags[evitem.id] || null; // No need to return flagged unless asked i.e. requestedOfflineJournal == cachedJournalFlag // Return created and modified offline records if requestedOfflineJournal is null alongwith events that have no flag if ((requestedOfflineJournal == null && cachedJournalFlag != cICL.OFFLINE_FLAG_DELETED_RECORD) || (requestedOfflineJournal != null && cachedJournalFlag == requestedOfflineJournal)) { - count += handleResultItem(evitem, Components.interfaces.calIEvent); + count += handleResultItem(evitem, Ci.calIEvent); if (checkCount()) { return; } } } } // if todos are wanted, do them next @@ -894,17 +894,17 @@ calStorageCalendar.prototype = { } catch (e) { this.logError("Error selecting non recurring todos by range", e); } finally { this.mSelectNonRecurringTodosByRange.reset(); } // process the non-recurring todos: for (let todoitem of resultItems) { - count += handleResultItem(todoitem, Components.interfaces.calITodo, checkCompleted); + count += handleResultItem(todoitem, Ci.calITodo, checkCompleted); if (checkCount()) { return; } } // Note: Reading the code, completed *occurrences* seems to be broken, because // only the parent item has been filtered; I fixed that. // Moreover item.todo_complete etc seems to be a leftover... @@ -915,69 +915,69 @@ calStorageCalendar.prototype = { let cachedJournalFlag = this.mRecTodoCacheOfflineFlags[todoitem.id] || null; if ((requestedOfflineJournal == null && (cachedJournalFlag == cICL.OFFLINE_FLAG_MODIFIED_RECORD || cachedJournalFlag == cICL.OFFLINE_FLAG_CREATED_RECORD || cachedJournalFlag == null)) || (requestedOfflineJournal != null && (cachedJournalFlag == requestedOfflineJournal))) { count += handleResultItem(todoitem, - Components.interfaces.calITodo, + Ci.calITodo, checkCompleted); if (checkCount()) { return; } } } } // flush the queue queueItems(null); // and finish this.notifyOperationComplete(aListener, - Components.results.NS_OK, - Components.interfaces.calIOperationListener.GET, + Cr.NS_OK, + Ci.calIOperationListener.GET, null, null); }, getItemOfflineFlag: function(aItem, aListener) { let flag = null; if (aItem) { let aID = aItem.id; let self = this; let listener = { handleResult: function(aResultSet) { let row = aResultSet.getNextRow(); flag = row.getResultByName("offline_journal") || null; }, handleError: function(aError) { self.logError("Error getting offline flag", aError); - aListener.onOperationComplete(self, Components.results.NS_ERROR_FAILURE, - Components.interfaces.calIOperationListener.GET, aItem.id, aItem); + aListener.onOperationComplete(self, Cr.NS_ERROR_FAILURE, + Ci.calIOperationListener.GET, aItem.id, aItem); }, handleCompletion: function(aReason) { - aListener.onOperationComplete(self, Components.results.NS_OK, - Components.interfaces.calIOperationListener.GET, aItem.id, flag); + aListener.onOperationComplete(self, Cr.NS_OK, + Ci.calIOperationListener.GET, aItem.id, flag); } }; if (cal.item.isEvent(aItem)) { this.prepareStatement(this.mSelectEvent); this.mSelectEvent.params.id = aID; this.mSelectEvent.executeAsync(listener); } else if (cal.item.isToDo(aItem)) { this.prepareStatement(this.mSelectTodo); this.mSelectTodo.params.id = aID; this.mSelectTodo.executeAsync(listener); } } else { // It is possible that aItem can be null, flag provided should be null in this case - aListener.onOperationComplete(this, Components.results.NS_OK, - Components.interfaces.calIOperationListener.GET, null, flag); + aListener.onOperationComplete(this, Cr.NS_OK, + Ci.calIOperationListener.GET, null, flag); } }, setOfflineJournalFlag: function(aItem, flag) { let aID = aItem.id; if (cal.item.isEvent(aItem)) { this.prepareStatement(this.mEditEventOfflineFlag); this.mEditEventOfflineFlag.params.id = aID; @@ -1005,81 +1005,81 @@ calStorageCalendar.prototype = { // // calIOfflineStorage interface // addOfflineItem: function(aItem, aListener) { let newOfflineJournalFlag = cICL.OFFLINE_FLAG_CREATED_RECORD; this.setOfflineJournalFlag(aItem, newOfflineJournalFlag); this.notifyOperationComplete(aListener, - Components.results.NS_OK, - Components.interfaces.calIOperationListener.ADD, + Cr.NS_OK, + Ci.calIOperationListener.ADD, aItem.id, aItem); }, modifyOfflineItem: function(aItem, aListener) { let self = this; let opListener = { - QueryInterface: XPCOMUtils.generateQI([Components.interfaces.calIOperationListener]), + QueryInterface: XPCOMUtils.generateQI([Ci.calIOperationListener]), onGetResult: function(calendar, status, itemType, detail, count, items) { }, onOperationComplete: function(calendar, status, opType, id, oldOfflineJournalFlag) { let newOfflineJournalFlag = cICL.OFFLINE_FLAG_MODIFIED_RECORD; if (oldOfflineJournalFlag == cICL.OFFLINE_FLAG_CREATED_RECORD || oldOfflineJournalFlag == cICL.OFFLINE_FLAG_DELETED_RECORD) { // Do nothing since a flag of "created" or "deleted" exists } else { self.setOfflineJournalFlag(aItem, newOfflineJournalFlag); } self.notifyOperationComplete(aListener, - Components.results.NS_OK, - Components.interfaces.calIOperationListener.MODIFY, + Cr.NS_OK, + Ci.calIOperationListener.MODIFY, aItem.id, aItem); } }; this.getItemOfflineFlag(aItem, opListener); }, deleteOfflineItem: function(aItem, aListener) { let self = this; let opListener = { - QueryInterface: XPCOMUtils.generateQI([Components.interfaces.calIOperationListener]), + QueryInterface: XPCOMUtils.generateQI([Ci.calIOperationListener]), onGetResult: function(calendar, status, itemType, detail, count, items) { }, onOperationComplete: function(calendar, status, opType, id, oldOfflineJournalFlag) { if (oldOfflineJournalFlag) { // Delete item if flag is c if (oldOfflineJournalFlag == cICL.OFFLINE_FLAG_CREATED_RECORD) { self.deleteItemById(aItem.id); } else if (oldOfflineJournalFlag == cICL.OFFLINE_FLAG_MODIFIED_RECORD) { self.setOfflineJournalFlag(aItem, cICL.OFFLINE_FLAG_DELETED_RECORD); } } else { self.setOfflineJournalFlag(aItem, cICL.OFFLINE_FLAG_DELETED_RECORD); } self.notifyOperationComplete(aListener, - Components.results.NS_OK, - Components.interfaces.calIOperationListener.DELETE, + Cr.NS_OK, + Ci.calIOperationListener.DELETE, aItem.id, aItem); // notify observers self.observers.notify("onDeleteItem", [aItem]); } }; this.getItemOfflineFlag(aItem, opListener); }, resetItemOfflineFlag: function(aItem, aListener) { this.setOfflineJournalFlag(aItem, null); this.notifyOperationComplete(aListener, - Components.results.NS_OK, - Components.interfaces.calIOperationListener.MODIFY, + Cr.NS_OK, + Ci.calIOperationListener.MODIFY, aItem.id, aItem); }, // // database handling // @@ -1742,17 +1742,17 @@ calStorageCalendar.prototype = { item.title + "' (" + item.id + ")!", e); } finally { selectItem.reset(); } } if (flags & CAL_ITEM_FLAG.HAS_RECURRENCE) { if (item.recurrenceId) { - throw Components.results.NS_ERROR_UNEXPECTED; + throw Cr.NS_ERROR_UNEXPECTED; } let recInfo = cal.createRecurrenceInfo(item); item.recurrenceInfo = recInfo; try { this.prepareStatement(this.mSelectRecurrenceForItem); this.mSelectRecurrenceForItem.params.item_id = item.id; @@ -1769,17 +1769,17 @@ calStorageCalendar.prototype = { } } if (flags & CAL_ITEM_FLAG.HAS_EXCEPTIONS) { // it's safe that we don't run into this branch again for exceptions // (getAdditionalDataForItem->get[Event|Todo]FromRow->getAdditionalDataForItem): // every excepton has a recurrenceId and isn't flagged as CAL_ITEM_FLAG.HAS_EXCEPTIONS if (item.recurrenceId) { - throw Components.results.NS_ERROR_UNEXPECTED; + throw Cr.NS_ERROR_UNEXPECTED; } let rec = item.recurrenceInfo; if (cal.item.isEvent(item)) { this.mSelectEventExceptions.params.id = item.id; this.prepareStatement(this.mSelectEventExceptions); try { @@ -1805,17 +1805,17 @@ calStorageCalendar.prototype = { } } catch (e) { this.logError("Error getting exceptions for task '" + item.title + "' (" + item.id + ")!", e); } finally { this.mSelectTodoExceptions.reset(); } } else { - throw Components.results.NS_ERROR_UNEXPECTED; + throw Cr.NS_ERROR_UNEXPECTED; } } if (flags & CAL_ITEM_FLAG.HAS_ATTACHMENTS) { let selectAttachment = this.mSelectAttachmentsForItem; if (item.recurrenceId != null) { selectAttachment = this.mSelectAttachmentsForItemWithRecurrenceId; this.setDateParamHelper(selectAttachment.params, "recurrence_id", item.recurrenceId); @@ -1882,18 +1882,17 @@ calStorageCalendar.prototype = { }, getRecurrenceItemFromRow: function(row, item) { let ritem; let prop = cal.getIcsService().createIcalPropertyFromString(row.icalString); switch (prop.propertyName) { case "RDATE": case "EXDATE": - ritem = Components.classes["@mozilla.org/calendar/recurrence-date;1"] - .createInstance(Components.interfaces.calIRecurrenceDate); + ritem = Cc["@mozilla.org/calendar/recurrence-date;1"].createInstance(Ci.calIRecurrenceDate); break; case "RRULE": case "EXRULE": ritem = cal.createRecurrenceRule(); break; default: throw "Unknown recurrence item: " + prop.propertyName; } @@ -2003,17 +2002,17 @@ calStorageCalendar.prototype = { flags |= this.writeRelations(item, olditem); flags |= this.writeAlarms(item, olditem); if (cal.item.isEvent(item)) { this.writeEvent(item, olditem, flags); } else if (cal.item.isToDo(item)) { this.writeTodo(item, olditem, flags); } else { - throw Components.results.NS_ERROR_UNEXPECTED; + throw Cr.NS_ERROR_UNEXPECTED; } }, writeEvent: function(item, olditem, flags) { try { this.prepareStatement(this.mInsertEvent); let params = this.mInsertEvent.params; this.setupItemBaseParams(item, olditem, params); @@ -2119,27 +2118,27 @@ calStorageCalendar.prototype = { return 0; }, writeProperty: function(item, propName, propValue) { try { this.prepareStatement(this.mInsertProperty); let params = this.mInsertProperty.params; params.key = propName; - let wPropValue = cal.wrapInstance(propValue, Components.interfaces.calIDateTime); + let wPropValue = cal.wrapInstance(propValue, Ci.calIDateTime); if (wPropValue) { params.value = wPropValue.nativeTime; } else { try { params.value = propValue; } catch (e) { // The storage service throws an NS_ERROR_ILLEGAL_VALUE in // case pval is something complex (i.e not a string or // number). Swallow this error, leaving the value empty. - if (e.result != Components.results.NS_ERROR_ILLEGAL_VALUE) { + if (e.result != Cr.NS_ERROR_ILLEGAL_VALUE) { throw e; } } } params.item_id = item.id; this.setDateParamHelper(params, "recurrence_id", item.recurrenceId); this.mInsertProperty.executeStep(); } finally { @@ -2147,17 +2146,17 @@ calStorageCalendar.prototype = { } }, writeProperties: function(item, olditem) { let ret = 0; let propEnumerator = item.propertyEnumerator; while (propEnumerator.hasMoreElements()) { ret = CAL_ITEM_FLAG.HAS_PROPERTIES; - let prop = propEnumerator.getNext().QueryInterface(Components.interfaces.nsIProperty); + let prop = propEnumerator.getNext().QueryInterface(Ci.nsIProperty); if (item.isPropertyPromoted(prop.name)) { continue; } this.writeProperty(item, prop.name, prop.value); } let cats = item.getCategories({}); if (cats.length > 0) { @@ -2192,17 +2191,17 @@ calStorageCalendar.prototype = { flags |= CAL_ITEM_FLAG.HAS_EXCEPTIONS; // we need to serialize each exid as a separate // event/todo; setupItemBase will handle // writing the recurrenceId for us for (let exid of exceptions) { let ex = rec.getExceptionFor(exid); if (!ex) { - throw Components.results.NS_ERROR_UNEXPECTED; + throw Cr.NS_ERROR_UNEXPECTED; } this.writeItem(ex, null); } } } else if (item.recurrenceId && item.recurrenceId.isDate) { flags |= CAL_ITEM_FLAG.RECURRENCE_ID_ALLDAY; } @@ -2336,17 +2335,17 @@ calStorageCalendar.prototype = { this.executeItemStatement(this.mDeleteMetaData, "item_id", id); try { this.prepareStatement(this.mInsertMetaData); let params = this.mInsertMetaData.params; params.item_id = id; params.value = value; this.mInsertMetaData.executeStep(); } catch (e) { - if (e.result == Components.results.NS_ERROR_ILLEGAL_VALUE) { + if (e.result == Cr.NS_ERROR_ILLEGAL_VALUE) { this.logError("Unknown error!", e); } else { // The storage service throws an NS_ERROR_ILLEGAL_VALUE in // case pval is something complex (i.e not a string or // number). Swallow this error, leaving the value empty. this.logError("Error setting metadata for id " + id + "!", e); } } finally { diff --git a/calendar/providers/storage/calStorageUpgrade.jsm b/calendar/providers/storage/calStorageUpgrade.jsm --- a/calendar/providers/storage/calStorageUpgrade.jsm +++ b/calendar/providers/storage/calStorageUpgrade.jsm @@ -182,17 +182,17 @@ function getVersion(db) { function backupDB(db, currentVersion) { cal.LOG("Storage: Backing up current database..."); try { // Prepare filenames and path let backupFilename = "local.v" + currentVersion + ".sqlite"; let backupPath = cal.provider.getCalendarDirectory(); backupPath.append("backup"); if (!backupPath.exists()) { - backupPath.create(Components.interfaces.nsIFile.DIRECTORY_TYPE, parseInt("0755", 8)); + backupPath.create(Ci.nsIFile.DIRECTORY_TYPE, parseInt("0755", 8)); } // Create a backup file and notify the user via WARN, since LOG will not // be visible unless a pref is set. let file = Services.storage.backupDatabaseFile(db.databaseFile, backupFilename, backupPath); cal.WARN("Storage: Upgrading to v" + DB_SCHEMA_VERSION + ", a backup was written to: " + file.path); } catch (e) { cal.ERROR("Storage: Error creating backup file: " + e); @@ -212,17 +212,17 @@ function upgradeDB(db) { // First, create a backup backupDB(db, version); // Then start the latest upgrader cal.LOG("Storage: Preparing to upgrade v" + version + " to v" + DB_SCHEMA_VERSION); upgrade["v" + DB_SCHEMA_VERSION](db, version); } else if (version > DB_SCHEMA_VERSION) { - throw Components.interfaces.calIErrors.STORAGE_UNKNOWN_SCHEMA_ERROR; + throw Ci.calIErrors.STORAGE_UNKNOWN_SCHEMA_ERROR; } } else { cal.LOG("Storage: Creating tables from scratch"); beginTransaction(db); try { executeSimpleSQL(db, getAllSql()); setDbVersionAndCommit(db, DB_SCHEMA_VERSION); } catch (e) { @@ -603,17 +603,17 @@ function migrateToIcalString(tblData, tb /** * Maps a mozIStorageValueArray to a JS array, converting types correctly. * * @param storArgs The storage value array to convert * @return An array with the arguments as js values. */ function mapStorageArgs(storArgs) { - const mISVA = Components.interfaces.mozIStorageValueArray; + const mISVA = Ci.mozIStorageValueArray; let mappedArgs = []; for (let i = 0; i < storArgs.numEntries; i++) { switch (storArgs.getTypeOfIndex(i)) { case mISVA.VALUE_TYPE_NULL: mappedArgs.push(null); break; case mISVA.VALUE_TYPE_INTEGER: mappedArgs.push(storArgs.getInt64(i)); break; case mISVA.VALUE_TYPE_FLOAT: @@ -1111,17 +1111,17 @@ upgrade.v16 = function(db, version) { mapStorageArgs(storArgs); let alarm = cal.createAlarm(); if (aOffset) { alarm.related = parseInt(aRelated, 10) + 1; alarm.offset = cal.createDuration(); alarm.offset.inSeconds = aOffset; } else if (aAlarmTime) { - alarm.related = Components.interfaces.calIAlarm.ALARM_RELATED_ABSOLUTE; + alarm.related = Ci.calIAlarm.ALARM_RELATED_ABSOLUTE; let alarmDate = cal.createDateTime(); alarmDate.nativeTime = aAlarmTime; if (aTzId == "floating") { // The current calDateTime code assumes that if a // date is floating then we can just assign the new // timezone. I have the feeling this is wrong so I // filed bug 520463. Since we want to release 1.0b1 // soon, I will just fix this on the "client side" @@ -1541,18 +1541,18 @@ upgrade.v22 = function(db, version) { // eslint-disable-next-line no-unused-vars let [aIndex, aType, aIsNegative, aDates, aCount, aEndDate, aInterval, aSecond, aMinute, aHour, aDay, aMonthday, aYearday, aWeekno, aMonth, aSetPos, aTmpFlags] = mapStorageArgs(storArgs); let ritem; if (aType == "x-date") { - ritem = Components.classes["@mozilla.org/calendar/recurrence-date;1"] - .createInstance(Components.interfaces.calIRecurrenceDate); + ritem = Cc["@mozilla.org/calendar/recurrence-date;1"] + .createInstance(Ci.calIRecurrenceDate); ritem.date = textToDate(aDates); ritem.isNegative = !!aIsNegative; } else { ritem = cal.createRecurrenceRule(); ritem.type = aType; ritem.isNegative = !!aIsNegative; if (aCount) { try { diff --git a/calendar/providers/wcap/calWcapCalendar.js b/calendar/providers/wcap/calWcapCalendar.js --- a/calendar/providers/wcap/calWcapCalendar.js +++ b/calendar/providers/wcap/calWcapCalendar.js @@ -17,19 +17,19 @@ function calWcapCalendar(session, calPro this.initProviderBase(); this.m_session = session; this.m_calProps = calProps; } var calWcapCalendarClassID = Components.ID("{cf4d93e5-af79-451a-95f3-109055b32ef0}"); var calWcapCalendarInterfaces = [ calIWcapCalendar, calICalendar, - Components.interfaces.calISchedulingSupport, - Components.interfaces.calIChangeLog, - Components.interfaces.calICalendarProvider, + Ci.calISchedulingSupport, + Ci.calIChangeLog, + Ci.calICalendarProvider, ]; calWcapCalendar.prototype = { __proto__: cal.provider.BaseClass.prototype, classID: calWcapCalendarClassID, QueryInterface: XPCOMUtils.generateQI(calWcapCalendarInterfaces), classInfo: XPCOMUtils.generateCI({ classID: calWcapCalendarClassID, contractID: "@mozilla.org/calendar/calendar;1?type=wcap", @@ -55,19 +55,19 @@ calWcapCalendar.prototype = { return; default: msg = errorToString(err); log("error: " + msg, context); break; } this.__proto__.__proto__.notifyError.apply( this, - err instanceof Components.interfaces.nsIException + err instanceof Ci.nsIException ? [err.result, err.message] - : [isNaN(err) ? Components.results.NS_ERROR_FAILURE : err, msg]); + : [isNaN(err) ? Cr.NS_ERROR_FAILURE : err, msg]); }, notifyError: function(err, msg) { this.notifyError_(err, msg, this); }, // calICalendarProvider: get prefChromeOverlay() { return null; @@ -359,19 +359,19 @@ calWcapCalendar.prototype = { throw new Components.Exception(errorToString(calIWcapErrors.WCAP_ACCESS_DENIED_TO_CALENDAR), calIWcapErrors.WCAP_ACCESS_DENIED_TO_CALENDAR); // xxx todo: throwing different error here, no // calIErrors.CAL_IS_READONLY anymore } }, defineAccessControl: function(userId, accessControlBits) { - throw Components.results.NS_ERROR_NOT_IMPLEMENTED; + throw Cr.NS_ERROR_NOT_IMPLEMENTED; }, resetAccessControl: function(userId) { - throw Components.results.NS_ERROR_NOT_IMPLEMENTED; + throw Cr.NS_ERROR_NOT_IMPLEMENTED; }, getAccessControlDefinitions: function(out_count, out_users, out_accessControlBits) { - throw Components.results.NS_ERROR_NOT_IMPLEMENTED; + throw Cr.NS_ERROR_NOT_IMPLEMENTED; } }; diff --git a/calendar/providers/wcap/calWcapCalendarItems.js b/calendar/providers/wcap/calWcapCalendarItems.js --- a/calendar/providers/wcap/calWcapCalendarItems.js +++ b/calendar/providers/wcap/calWcapCalendarItems.js @@ -36,18 +36,18 @@ calWcapCalendar.prototype.getRecurrenceP out_rrules.value = []; out_rdates.value = []; out_exrules.value = []; out_exdates.value = []; if (item.recurrenceInfo) { let rItems = item.recurrenceInfo.getRecurrenceItems({}); for (let rItem of rItems) { let isNeg = rItem.isNegative; - let rRuleInstance = cal.wrapInstance(rItem, Components.interfaces.calIRecurrenceRule); - let rDateInstance = cal.wrapInstance(rItem, Components.interfaces.calIRecurrenceDate); + let rRuleInstance = cal.wrapInstance(rItem, Ci.calIRecurrenceRule); + let rDateInstance = cal.wrapInstance(rItem, Ci.calIRecurrenceDate); if (rRuleInstance) { let rule = "\"" + encodeURIComponent(rRuleInstance.icalProperty.valueAsIcalString) + "\""; if (isNeg) { out_exrules.value.push(rule); } else { out_rrules.value.push(rule); } } else if (rDateInstance) { @@ -297,17 +297,17 @@ calWcapCalendar.prototype.storeItem = fu }; let getAttachments = (attitem) => { let ret; let attachments = attitem.attachments; if (attachments) { let strings = []; for (let att of attachments) { - let wrappedAtt = cal.wrapInstance(att, Components.interfaces.calIAttachment); + let wrappedAtt = cal.wrapInstance(att, Ci.calIAttachment); if (typeof att == "string") { strings.push(encodeURIComponent(att)); } else if (wrappedAtt && wrappedAtt.uri) { strings.push(encodeURIComponent(wrappedAtt.uri.spec)); } else { // xxx todo logError("only URLs supported as attachment, not: " + att, this); } } @@ -594,17 +594,17 @@ calWcapCalendar.prototype.tunnelXProps = return; } // tunnel alarm X-MOZ-SNOOZE only if alarm is still set: // TODO ALARMSUPPORT still needed when showing alarms as EMAIL for wcap? let hasAlarms = destItem.getAlarms({}).length; let enumerator = srcItem.propertyEnumerator; while (enumerator.hasMoreElements()) { try { - let prop = enumerator.getNext().QueryInterface(Components.interfaces.nsIProperty); + let prop = enumerator.getNext().QueryInterface(Ci.nsIProperty); let name = prop.name; if (name.startsWith("X-MOZ-")) { switch (name) { // keep snooze stamps for occurrences only and if alarm is still set: case "X-MOZ-SNOOZE-TIME": if (!hasAlarms) { break; // alarm has been reset } @@ -920,18 +920,18 @@ calWcapCalendar.prototype.parseItems = f parent.setProperty("DTSTART", item.recurrenceId); parent.setProperty("X-MOZ-FAKED-MASTER", "1"); // this tag might be useful in the future parent.recurrenceInfo = cal.createRecurrenceInfo(parent); fakedParents[item.id] = true; uid2parent[item.id] = parent; items.push(parent); } if (item.id in fakedParents) { - let rdate = Components.classes["@mozilla.org/calendar/recurrence-date;1"] - .createInstance(Components.interfaces.calIRecurrenceDate); + let rdate = Cc["@mozilla.org/calendar/recurrence-date;1"] + .createInstance(Ci.calIRecurrenceDate); rdate.date = item.recurrenceId; parent.recurrenceInfo.appendRecurrenceItem(rdate); } let recStartDate = parent.recurrenceStartDate; if (recStartDate && recStartDate.isDate && !item.recurrenceId.isDate) { // cs ought to return proper all-day RECURRENCE-ID! // get into startDate's timezone before cutting: @@ -951,18 +951,18 @@ calWcapCalendar.prototype.parseItems = f let recStartDate = item.recurrenceStartDate; if (recStartDate && !recStartDate.isDate) { recStartDate = null; } let recItems = item.recurrenceInfo.getRecurrenceItems({}); for (let recItem of recItems) { // cs bug: workaround missing COUNT - let rRuleInstance = cal.wrapInstance(recItem, Components.interfaces.calIRecurrenceRule); - let rDateInstance = cal.wrapInstance(recItem, Components.interfaces.calIRecurrenceDate); + let rRuleInstance = cal.wrapInstance(recItem, Ci.calIRecurrenceRule); + let rDateInstance = cal.wrapInstance(recItem, Ci.calIRecurrenceDate); if (rRuleInstance) { recItem = rRuleInstance; if (!recItem.isFinite && !recItem.isNegative) { recItem.count = recurrenceBound; } } else if (recStartDate && rDateInstance) { // cs bug: always uses DATE-TIME even though the master item is all-day DATE: @@ -1246,20 +1246,19 @@ calWcapCalendar.prototype.getItems = fun } this.m_cachedResults = entries; }.bind(this) }; // sort out freq: let freq = Math.min(20, // default: 20secs Math.max(1, CACHE_LAST_RESULTS_INVALIDATE)); log("cached results sort out timer freq: " + freq, this); - this.m_cachedResultsTimer = Components.classes["@mozilla.org/timer;1"] - .createInstance(Components.interfaces.nsITimer); + this.m_cachedResultsTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer); this.m_cachedResultsTimer.initWithCallback(callback, freq * 1000, - Components.interfaces.nsITimer.TYPE_REPEATING_SLACK); + Ci.nsITimer.TYPE_REPEATING_SLACK); } if (!this.m_cachedResults) { this.m_cachedResults = []; } let cacheEntry = { stamp: (new Date()).getTime(), itemFilter: itemFilter, rangeStart: (rangeStart ? rangeStart.clone() : null), @@ -1307,17 +1306,17 @@ calWcapCalendar.prototype.replayChangesO listener.onResult(request, null); } }, log("replayChangesOn():\n\titemFilter=0x" + itemFilter.toString(0x10) + "\n\tdtFrom=" + getIcalUTC(dtFrom), this)); try { let writeListener = { - QueryInterface: XPCOMUtils.generateQI([Components.interfaces.calIOperationListener]), + QueryInterface: XPCOMUtils.generateQI([Ci.calIOperationListener]), onGetResult: function() {}, onOperationComplete: function(aCalendar, status, opType, id, detail) { if (!Components.isSuccessCode(status)) { request.execRespFunc(status); // any error on writing breaks whole operation } } }; let request = new calWcapRequest( diff --git a/calendar/providers/wcap/calWcapCalendarModule.js b/calendar/providers/wcap/calWcapCalendarModule.js --- a/calendar/providers/wcap/calWcapCalendarModule.js +++ b/calendar/providers/wcap/calWcapCalendarModule.js @@ -15,29 +15,29 @@ ChromeUtils.import("resource://calendar/ ChromeUtils.import("resource://gre/modules/Preferences.jsm"); ChromeUtils.import("resource://gre/modules/Services.jsm"); // // init code for globals, prefs: // // constants: -var NS_OK = Components.results.NS_OK; -var NS_ERROR_UNEXPECTED = Components.results.NS_ERROR_UNEXPECTED; -var nsIException = Components.interfaces.nsIException; -var calIWcapSession = Components.interfaces.calIWcapSession; -var calIWcapCalendar = Components.interfaces.calIWcapCalendar; -var calIWcapErrors = Components.interfaces.calIWcapErrors; -var calICalendar = Components.interfaces.calICalendar; -var calIItemBase = Components.interfaces.calIItemBase; -var calIOperationListener = Components.interfaces.calIOperationListener; -var calIFreeBusyProvider = Components.interfaces.calIFreeBusyProvider; -var calIFreeBusyInterval = Components.interfaces.calIFreeBusyInterval; -var calICalendarSearchProvider = Components.interfaces.calICalendarSearchProvider; -var calIErrors = Components.interfaces.calIErrors; +var NS_OK = Cr.NS_OK; +var NS_ERROR_UNEXPECTED = Cr.NS_ERROR_UNEXPECTED; +var nsIException = Ci.nsIException; +var calIWcapSession = Ci.calIWcapSession; +var calIWcapCalendar = Ci.calIWcapCalendar; +var calIWcapErrors = Ci.calIWcapErrors; +var calICalendar = Ci.calICalendar; +var calIItemBase = Ci.calIItemBase; +var calIOperationListener = Ci.calIOperationListener; +var calIFreeBusyProvider = Ci.calIFreeBusyProvider; +var calIFreeBusyInterval = Ci.calIFreeBusyInterval; +var calICalendarSearchProvider = Ci.calICalendarSearchProvider; +var calIErrors = Ci.calIErrors; // some string resources: var g_privateItemTitle; var g_confidentialItemTitle; var g_busyItemTitle; var g_busyPhantomItemUuidPrefix; // global preferences: diff --git a/calendar/providers/wcap/calWcapErrors.js b/calendar/providers/wcap/calWcapErrors.js --- a/calendar/providers/wcap/calWcapErrors.js +++ b/calendar/providers/wcap/calWcapErrors.js @@ -3,17 +3,17 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* exported checkErrorCode, checkWcapXmlErrno, checkWcapIcalErrno, * errorToString */ ChromeUtils.import("resource://calendar/modules/calUtils.jsm"); -var NS_ERROR_INVALID_ARG = Components.results.NS_ERROR_INVALID_ARG; +var NS_ERROR_INVALID_ARG = Cr.NS_ERROR_INVALID_ARG; // // Common netwerk errors: // var NS_ERROR_MODULE_BASE_OFFSET = 0x45; var NS_ERROR_MODULE_NETWORK = 6; function generateFailure(module, code) { @@ -25,17 +25,17 @@ function generateNetFailure(code) { return generateFailure(NS_ERROR_MODULE_NETWORK, code); } function getResultCode(err) { if (err === undefined || err === null) { return NS_OK; } if (isNaN(err)) { - return (err instanceof nsIException ? err.result : Components.results.NS_ERROR_FAILURE); + return (err instanceof nsIException ? err.result : Cr.NS_ERROR_FAILURE); } return err; } function getErrorModule(err) { let rc = getResultCode(err); return (((rc >>> 16) & 0x7fff) - NS_ERROR_MODULE_BASE_OFFSET); } @@ -336,39 +336,39 @@ function errorToString(err) { // numeric codes: switch (err) { case undefined: case null: case NS_OK: return "NS_OK"; case NS_ERROR_INVALID_ARG: return "NS_ERROR_INVALID_ARG"; - case Components.results.NS_ERROR_NO_INTERFACE: + case Cr.NS_ERROR_NO_INTERFACE: return "NS_ERROR_NO_INTERFACE"; - case Components.results.NS_ERROR_NOT_IMPLEMENTED: + case Cr.NS_ERROR_NOT_IMPLEMENTED: return "NS_ERROR_NOT_IMPLEMENTED"; - case Components.results.NS_ERROR_NOT_AVAILABLE: + case Cr.NS_ERROR_NOT_AVAILABLE: return "NS_ERROR_NOT_AVAILABLE"; - case Components.results.NS_ERROR_FAILURE: + case Cr.NS_ERROR_FAILURE: return "NS_ERROR_FAILURE"; - case Components.results.NS_ERROR_BASE: + case Cr.NS_ERROR_BASE: return "NS_ERROR_BASE"; - case Components.results.NS_ERROR_NOT_INITIALIZED: + case Cr.NS_ERROR_NOT_INITIALIZED: return "NS_ERROR_NOT_INITIALIZED"; - case Components.results.NS_ERROR_ALREADY_INITIALIZED: + case Cr.NS_ERROR_ALREADY_INITIALIZED: return "NS_ERROR_ALREADY_INITIALIZED"; - case Components.results.NS_ERROR_NULL_POINTER: + case Cr.NS_ERROR_NULL_POINTER: return "NS_ERROR_NULL_POINTER"; - case Components.results.NS_ERROR_ABORT: + case Cr.NS_ERROR_ABORT: return "NS_ERROR_ABORT"; - case Components.results.NS_ERROR_UNEXPECTED: + case Cr.NS_ERROR_UNEXPECTED: return "NS_ERROR_UNEXPECTED"; - case Components.results.NS_ERROR_OUT_OF_MEMORY: + case Cr.NS_ERROR_OUT_OF_MEMORY: return "NS_ERROR_OUT_OF_MEMORY"; - case Components.results.NS_ERROR_ILLEGAL_VALUE: + case Cr.NS_ERROR_ILLEGAL_VALUE: return "NS_ERROR_ILLEGAL_VALUE"; default: // probe for WCAP error: try { return wcapErrorToString(err); } catch (exc) { // probe for netwerk error: try { return netErrorToString(err); diff --git a/calendar/providers/wcap/calWcapRequest.js b/calendar/providers/wcap/calWcapRequest.js --- a/calendar/providers/wcap/calWcapRequest.js +++ b/calendar/providers/wcap/calWcapRequest.js @@ -189,20 +189,20 @@ function calWcapNetworkRequest(url, resp this.wrappedJSObject = this; this.m_id = generateRequestId(); this.m_url = url; this.m_respFunc = respFunc; this.m_bLogging = (bLogging === undefined ? true : bLogging); } var calWcapNetworkRequestClassID = Components.ID("{e3c62b37-83cf-41ec-9872-0af9f952430a}"); var calWcapNetworkRequestInterfaces = [ - Components.interfaces.nsIUnicharStreamLoaderObserver, - Components.interfaces.nsIInterfaceRequestor, - Components.interfaces.nsIChannelEventSink, - Components.interfaces.calIOperation, + Ci.nsIUnicharStreamLoaderObserver, + Ci.nsIInterfaceRequestor, + Ci.nsIChannelEventSink, + Ci.calIOperation, ]; calWcapNetworkRequest.prototype = { m_id: 0, m_url: null, m_loader: null, m_respFunc: null, m_bLogging: false, @@ -224,28 +224,28 @@ calWcapNetworkRequest.prototype = { /** * prepareChannel * Prepares the passed channel to match this objects properties * * @param aChannel The Channel to be prepared */ prepareChannel: function(aChannel) { // No caching - aChannel.loadFlags |= Components.interfaces.nsIRequest.LOAD_BYPASS_CACHE; - aChannel = aChannel.QueryInterface(Components.interfaces.nsIHttpChannel); + aChannel.loadFlags |= Ci.nsIRequest.LOAD_BYPASS_CACHE; + aChannel = aChannel.QueryInterface(Ci.nsIHttpChannel); aChannel.requestMethod = "GET"; }, /** * @see nsIChannelEventSink */ asyncOnChannelRedirect: function(aOldChannel, aNewChannel, aFlags, aCallback) { // all we need to do to the new channel is the basic preparation this.prepareChannel(aNewChannel); - aCallback.onRedirectVerifyCallback(Components.results.NS_OK); + aCallback.onRedirectVerifyCallback(Cr.NS_OK); }, /** * @see nsIUnicharStreamLoaderObserver */ onDetermineCharset: function(loader, context, firstSegment, length) { let channel = null; if (loader) { @@ -265,26 +265,26 @@ calWcapNetworkRequest.prototype = { * @see nsIUnicharStreamLoaderObserver */ onStreamComplete: function(aLoader, aContext, aStatus, unicharData) { this.m_loader = null; if (LOG_LEVEL > 0 && this.m_bLogging) { log("status: " + errorToString(aStatus), this); } - if (aStatus != Components.results.NS_OK) { + if (aStatus != Cr.NS_OK) { this.execRespFunc(aStatus); return; } if (LOG_LEVEL > 2 && this.m_bLogging) { log("contentCharset = " + aLoader.charset + "\nrequest result:\n" + unicharData, this); } - let httpChannel = aLoader.channel.QueryInterface(Components.interfaces.nsIHttpChannel); + let httpChannel = aLoader.channel.QueryInterface(Ci.nsIHttpChannel); switch (httpChannel.responseStatus / 100) { case 2: /* 2xx codes */ // Everything worked out, we are done this.execRespFunc(aStatus, unicharData); break; default: { // Something else went wrong let error = "A request Error Occurred. Status Code: " + @@ -397,29 +397,28 @@ function issueNetworkRequest(parentReque parentRequest.attachSubRequest(netRequest); } try { let uri = Services.io.newURI(url); let channel = Services.io.newChannelFromURI2(uri, null, Services.scriptSecurityManager.getSystemPrincipal(), null, - Components.interfaces.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, - Components.interfaces.nsIContentPolicy.TYPE_OTHER); + Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, + Ci.nsIContentPolicy.TYPE_OTHER); netRequest.prepareChannel(channel); - channel = channel.QueryInterface(Components.interfaces.nsIHttpChannel); + channel = channel.QueryInterface(Ci.nsIHttpChannel); channel.redirectionLimit = 3; channel.notificationCallbacks = netRequest; - let loader = Components.classes["@mozilla.org/network/unichar-stream-loader;1"] - .createInstance(Components.interfaces.nsIUnicharStreamLoader); + let loader = Cc["@mozilla.org/network/unichar-stream-loader;1"] + .createInstance(Ci.nsIUnicharStreamLoader); netRequest.m_loader = loader; log("opening channel.", netRequest); - loader.init(netRequest, - Components.interfaces.nsIUnicharStreamLoader.DEFAULT_SEGMENT_SIZE); + loader.init(netRequest, Ci.nsIUnicharStreamLoader.DEFAULT_SEGMENT_SIZE); channel.asyncOpen(loader, null); } catch (exc) { netRequest.execRespFunc(exc); } } function getWcapRequestStatusString(xml) { let str = "request status: "; diff --git a/calendar/providers/wcap/calWcapSession.js b/calendar/providers/wcap/calWcapSession.js --- a/calendar/providers/wcap/calWcapSession.js +++ b/calendar/providers/wcap/calWcapSession.js @@ -105,18 +105,18 @@ function calWcapSession(contextId) { Services.obs.addObserver(this, "quit-application"); cal.getCalendarManager().addObserver(this); } var calWcapSessionClassID = Components.ID("{cbf803fd-4469-4999-ae39-367af1c7b077}"); var calWcapSessionInterfaces = [ calIWcapSession, calIFreeBusyProvider, calICalendarSearchProvider, - Components.interfaces.calITimezoneProvider, - Components.interfaces.calICalendarManagerObserver + Ci.calITimezoneProvider, + Ci.calICalendarManagerObserver ]; calWcapSession.prototype = { classID: calWcapSessionClassID, QueryInterface: XPCOMUtils.generateQI(calWcapSessionInterfaces), classInfo: XPCOMUtils.generateCI({ classID: calWcapSessionClassID, contractID: "@mozilla.org/calendar/wcap/session;1", classDescription: "Sun Java System Calendar Server WCAP Session", @@ -149,17 +149,17 @@ calWcapSession.prototype = { for (let tzid in this.m_serverTimezones) { tzids.push(tzid); } return { // nsIUTF8StringEnumerator: m_index: 0, getNext: function() { if (this.m_index >= tzids) { cal.ASSERT(false, "calWcapSession::timezoneIds enumerator!"); - throw Components.results.NS_ERROR_UNEXPECTED; + throw Cr.NS_ERROR_UNEXPECTED; } return tzids[this.m_index++]; }, hasMore: function() { return (this.m_index < tzids.length); } }; }, @@ -176,17 +176,17 @@ calWcapSession.prototype = { return null; } }, m_serverTimeDiff: null, getServerTime: function(localTime) { if (this.m_serverTimeDiff === null) { throw new Components.Exception("early run into getServerTime()!", - Components.results.NS_ERROR_NOT_AVAILABLE); + Cr.NS_ERROR_NOT_AVAILABLE); } let ret = (localTime ? localTime.clone() : getTime()); ret.addDuration(this.m_serverTimeDiff); return ret; }, m_sessionId: null, m_loginQueue: null, @@ -304,18 +304,18 @@ calWcapSession.prototype = { } else { if (outSavePW.value) { // so try to remove old pw from db first: try { cal.auth.passwordManagerSave(outUser.value, outPW.value, this.uri.spec, "wcap login"); } catch (e) { // User might have cancelled the master password prompt, or password saving // could be disabled. That is ok, throw for everything else. - if (e.result != Components.results.NS_ERROR_ABORT && - e.result != Components.results.NS_ERROR_NOT_AVAILABLE) { + if (e.result != Cr.NS_ERROR_ABORT && + e.result != Cr.NS_ERROR_NOT_AVAILABLE) { throw e; } } } this.credentials.userId = outUser.value; this.credentials.pw = outPW.value; // eslint-disable-line id-length this.setupSession(sessionId, request, (setuperr) => respFunc(setuperr, sessionId)); } @@ -613,17 +613,17 @@ calWcapSession.prototype = { if (!retrievedCals[calId]) { let listener = { onResult: function(oprequest, result) { try { if (!Components.isSuccessCode(oprequest.status)) { throw oprequest.status; } if (result.length < 1) { - throw Components.results.NS_ERROR_UNEXPECTED; + throw Cr.NS_ERROR_UNEXPECTED; } for (let calendar of result) { // user may have dangling users referred in his subscription list, so // retrieve each by each, don't break: try { let thisCalId = calendar.calId; if ((cals[thisCalId] !== undefined) && !retrievedCals[thisCalId]) { retrievedCals[thisCalId] = calendar; diff --git a/calendar/providers/wcap/calWcapUtils.js b/calendar/providers/wcap/calWcapUtils.js --- a/calendar/providers/wcap/calWcapUtils.js +++ b/calendar/providers/wcap/calWcapUtils.js @@ -29,22 +29,21 @@ function initLogging() { LOG_LEVEL = 1; // at least basic logging when calendar.debug.log is set } if (LOG_LEVEL > 0) { let logFileName = getPref("calendar.wcap.log_file", null); if (logFileName) { try { // set up file: - let logFile = Components.classes["@mozilla.org/file/local;1"] - .createInstance(Components.interfaces.nsIFile); + let logFile = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile); logFile.initWithPath(logFileName); // create output stream: - let logFileStream = Components.classes["@mozilla.org/network/file-output-stream;1"] - .createInstance(Components.interfaces.nsIFileOutputStream); + let logFileStream = Cc["@mozilla.org/network/file-output-stream;1"] + .createInstance(Ci.nsIFileOutputStream); logFileStream.init(logFile, 0x02 /* PR_WRONLY */ | 0x08 /* PR_CREATE_FILE */ | (getPref("calendar.wcap.log_file_append", false) ? 0x10 /* PR_APPEND */ : 0x20 /* PR_TRUNCATE */), parseInt("0700", 8) /* read, write, execute/search by owner */, 0 /* unused */); initLogging.mLogFilestream = logFileStream; @@ -105,59 +104,58 @@ function log(msg, context, bForce) { dump(str); if (initLogging.mLogFilestream) { try { // xxx todo? // assuming ANSI chars here, for logging sufficient: initLogging.mLogFilestream.write(str, str.length); } catch (exc) { // catching any io errors here: let err = "error writing log file: " + errorToString(exc); - Components.utils.reportError(exc); + Cu.reportError(exc); Services.console.logStringMessage(err); dump(err + "\n\n"); } } return ret; } else { return msg; } } function logWarning(err, context) { let msg = errorToString(err); - let scriptError = Components.classes["@mozilla.org/scripterror;1"] - .createInstance(Components.interfaces.nsIScriptError); + let scriptError = Cc["@mozilla.org/scripterror;1"].createInstance(Ci.nsIScriptError); scriptError.init(log("warning: " + msg, context, true), null, null, 0, 0, - Components.interfaces.nsIScriptError.warningFlag, + Ci.nsIScriptError.warningFlag, "component javascript"); Services.console.logMessage(scriptError); return msg; } function logError(err, context) { let msg = errorToString(err); - Components.utils.reportError(log("error: " + msg + "\nstack:\n" + cal.STACK(10), context, true)); + Cu.reportError(log("error: " + msg + "\nstack:\n" + cal.STACK(10), context, true)); return msg; } // late-inited service accessors: function getCalendarSearchService() { if (!getCalendarSearchService.m_obj) { - getCalendarSearchService.m_obj = Components.classes["@mozilla.org/calendar/calendarsearch-service;1"] - .getService(Components.interfaces.calICalendarSearchService); + getCalendarSearchService.m_obj = Cc["@mozilla.org/calendar/calendarsearch-service;1"] + .getService(Ci.calICalendarSearchService); } return getCalendarSearchService.m_obj; } function getDomParser() { if (!getDomParser.m_obj) { - getDomParser.m_obj = Components.classes["@mozilla.org/xmlextras/domparser;1"] - .getService(Components.interfaces.nsIDOMParser); + getDomParser.m_obj = Cc["@mozilla.org/xmlextras/domparser;1"] + .getService(Ci.nsIDOMParser); } return getDomParser.m_obj; } function isParent(item) { if (item.id != item.parentItem.id) { throw new Components.Exception("proxy has different id than its parent!"); } diff --git a/calendar/providers/wcap/public/calIWcapCalendar.idl b/calendar/providers/wcap/public/calIWcapCalendar.idl --- a/calendar/providers/wcap/public/calIWcapCalendar.idl +++ b/calendar/providers/wcap/public/calIWcapCalendar.idl @@ -247,22 +247,22 @@ interface calIWcapCalendar : calICalenda // * xxx todo: change the above // * @param accessControlBits access control bits (above AC_ definitions) // * @param listener called when access control bits have been updated // * @return optional object to track operation // */ // calIOperation defineAccessControl( // in string userId, in unsigned long accessControlBits, // in calIGenericOperationListener listener); - + // /** // * To reset a user's access control definition to the default ones // * that everybody is granted. // * In case the user has no specific access control definition, -// * Components.results.NS_ERROR_INVALID_ARG is thrown. +// * Cr.NS_ERROR_INVALID_ARG is thrown. // * // * @param userId user id // * @param listener called when access control bits have been updated // * @return optional object to track operation // */ // calIOperation resetAccessControl( // in string userId, // in calIGenericOperationListener listener); diff --git a/calendar/resources/content/calendarCreation.js b/calendar/resources/content/calendarCreation.js --- a/calendar/resources/content/calendarCreation.js +++ b/calendar/resources/content/calendarCreation.js @@ -73,18 +73,17 @@ function setNotification(aReason) { * the page is set up for the provider. * * @param type The provider type selected */ function onSelectProvider(type) { let cache = document.getElementById("cache"); let tempCal; try { - tempCal = Components.classes["@mozilla.org/calendar/calendar;1?type=" + type] - .createInstance(Components.interfaces.calICalendar); + tempCal = Cc["@mozilla.org/calendar/calendar;1?type=" + type].createInstance(Ci.calICalendar); } catch (e) { // keep tempCal undefined if the calendar can not be created } if (tempCal && tempCal.getProperty("cache.always")) { cache.oldValue = cache.checked; cache.checked = true; cache.disabled = true; diff --git a/calendar/resources/content/datetimepickers/datetimepickers.xml b/calendar/resources/content/datetimepickers/datetimepickers.xml --- a/calendar/resources/content/datetimepickers/datetimepickers.xml +++ b/calendar/resources/content/datetimepickers/datetimepickers.xml @@ -41,17 +41,17 @@ + onkeypress="if (event.keyCode == Ci.nsIDOMKeyEvent.DOM_VK_RETURN) fireGoEvent();"/> [] [] [] diff --git a/calendar/resources/content/publish.js b/calendar/resources/content/publish.js --- a/calendar/resources/content/publish.js +++ b/calendar/resources/content/publish.js @@ -87,17 +87,17 @@ function publishEntireCalendar(aCalendar */ function publishEntireCalendarDialogResponse(CalendarPublishObject, aProgressDialog) { // store the selected remote ics path as a calendar preference CalendarPublishObject.calendar.setProperty("remote-ics-path", CalendarPublishObject.remotePath); let itemArray = []; let getListener = { - QueryInterface: XPCOMUtils.generateQI([Components.interfaces.calIOperationListener]), + QueryInterface: XPCOMUtils.generateQI([Ci.calIOperationListener]), onOperationComplete: function(aCalendar, aStatus, aOperationType, aId, aDetail) { publishItemArray(itemArray, CalendarPublishObject.remotePath, aProgressDialog); }, onGetResult: function(aCalendar, aStatus, aItemType, aDetail, aCount, aItems) { if (!Components.isSuccessCode(aStatus)) { aborted = true; return; } @@ -107,66 +107,64 @@ function publishEntireCalendarDialogResp let itemCopy = aItems[i].clone(); itemArray.push(itemCopy); } } } }; aProgressDialog.onStartUpload(); let oldCalendar = CalendarPublishObject.calendar; - oldCalendar.getItems(Components.interfaces.calICalendar.ITEM_FILTER_ALL_ITEMS, + oldCalendar.getItems(Ci.calICalendar.ITEM_FILTER_ALL_ITEMS, 0, null, null, getListener); } function publishItemArray(aItemArray, aPath, aProgressDialog) { let outputStream; let inputStream; let storageStream; let icsURL = Services.io.newURI(aPath); let channel = Services.io.newChannelFromURI2(icsURL, null, Services.scriptSecurityManager.getSystemPrincipal(), null, - Components.interfaces.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, - Components.interfaces.nsIContentPolicy.TYPE_OTHER); + Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, + Ci.nsIContentPolicy.TYPE_OTHER); if (icsURL.schemeIs("webcal")) { icsURL.scheme = "http"; } if (icsURL.schemeIs("webcals")) { icsURL.scheme = "https"; } switch (icsURL.scheme) { case "http": case "https": - channel = channel.QueryInterface(Components.interfaces.nsIHttpChannel); + channel = channel.QueryInterface(Ci.nsIHttpChannel); break; case "ftp": - channel = channel.QueryInterface(Components.interfaces.nsIFTPChannel); + channel = channel.QueryInterface(Ci.nsIFTPChannel); break; case "file": - channel = channel.QueryInterface(Components.interfaces.nsIFileChannel); + channel = channel.QueryInterface(Ci.nsIFileChannel); break; default: dump("No such scheme\n"); return; } - let uploadChannel = channel.QueryInterface(Components.interfaces.nsIUploadChannel); + let uploadChannel = channel.QueryInterface(Ci.nsIUploadChannel); uploadChannel.notificationCallbacks = notificationCallbacks; - storageStream = Components.classes["@mozilla.org/storagestream;1"] - .createInstance(Components.interfaces.nsIStorageStream); + storageStream = Cc["@mozilla.org/storagestream;1"].createInstance(Ci.nsIStorageStream); storageStream.init(32768, 0xffffffff, null); outputStream = storageStream.getOutputStream(0); - let serializer = Components.classes["@mozilla.org/calendar/ics-serializer;1"] - .createInstance(Components.interfaces.calIIcsSerializer); + let serializer = Cc["@mozilla.org/calendar/ics-serializer;1"].createInstance(Ci.calIIcsSerializer); serializer.addItems(aItemArray, aItemArray.length); // Outlook requires METHOD:PUBLISH property: let methodProp = cal.getIcsService().createIcalProperty("METHOD"); methodProp.value = "PUBLISH"; serializer.addProperty(methodProp); serializer.serializeToStream(outputStream); outputStream.close(); @@ -181,39 +179,39 @@ function publishItemArray(aItemArray, aP cal.l10n.getCalString("otherPutError", [e.message])); } } var notificationCallbacks = { // nsIInterfaceRequestor interface getInterface: function(iid, instance) { - if (iid.equals(Components.interfaces.nsIAuthPrompt)) { + if (iid.equals(Ci.nsIAuthPrompt)) { // use the window watcher service to get a nsIAuthPrompt impl return Services.ww.getNewAuthPrompter(null); } - throw Components.results.NS_ERROR_NO_INTERFACE; + throw Cr.NS_ERROR_NO_INTERFACE; } }; var publishingListener = { - QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsIStreamListener]), + QueryInterface: XPCOMUtils.generateQI([Ci.nsIStreamListener]), onStartRequest: function(request, ctxt) { }, onStopRequest: function(request, ctxt, status, errorMsg) { ctxt.wrappedJSObject.onStopUpload(); let channel; let requestSucceeded; try { - channel = request.QueryInterface(Components.interfaces.nsIHttpChannel); + channel = request.QueryInterface(Ci.nsIHttpChannel); requestSucceeded = channel.requestSucceeded; } catch (e) { // Don't fail if it is not a http channel, will be handled below } if (channel && !requestSucceeded) { let body = cal.l10n.getCalString("httpPutError", [ channel.responseStatus, channel.responseStatusText diff --git a/calendar/test/mozmill/testLocalICS.js b/calendar/test/mozmill/testLocalICS.js --- a/calendar/test/mozmill/testLocalICS.js +++ b/calendar/test/mozmill/testLocalICS.js @@ -64,20 +64,20 @@ function testLocalICS() { event.click(eventid("button-saveandclose")); }); // assert presence in view let eventPath = `/{"tooltip":"itemTooltip","calendar":"${calendarName}"}`; controller.waitForElement(lookupEventBox("day", EVENT_BOX, null, 1, HOUR, eventPath)); // verify in file - let fstream = Components.classes["@mozilla.org/network/file-input-stream;1"] - .createInstance(Components.interfaces.nsIFileInputStream); - let cstream = Components.classes["@mozilla.org/intl/converter-input-stream;1"] - .createInstance(Components.interfaces.nsIConverterInputStream); + let fstream = Cc["@mozilla.org/network/file-input-stream;1"] + .createInstance(Ci.nsIFileInputStream); + let cstream = Cc["@mozilla.org/intl/converter-input-stream;1"] + .createInstance(Ci.nsIConverterInputStream); // wait a moment until file is written controller.waitFor(() => calendarFile.exists()); // read the calendar file and check for the summary fstream.init(calendarFile, -1, 0, 0); cstream.init(fstream, "UTF-8", 0, 0); diff --git a/calendar/test/unit/head_consts.js b/calendar/test/unit/head_consts.js --- a/calendar/test/unit/head_consts.js +++ b/calendar/test/unit/head_consts.js @@ -15,17 +15,17 @@ ChromeUtils.import("resource://gre/modul ChromeUtils.import("resource://testing-common/AppInfo.jsm"); // ChromeUtils.defineModuleGetter(this, "NetUtil", "resource://gre/modules/NetUtil.jsm"); updateAppInfo(); (function() { - let bindir = Services.dirsvc.get("CurProcD", Components.interfaces.nsIFile); + let bindir = Services.dirsvc.get("CurProcD", Ci.nsIFile); if (!AppConstants.NIGHTLY_BUILD) { bindir.append("distribution"); } bindir.append("extensions"); let xpiFile = bindir.clone(); xpiFile.append("{e2fda1a4-762b-4020-b5ad-a41df1933103}.xpi"); @@ -59,80 +59,73 @@ updateAppInfo(); } bindir.append("chrome.manifest"); dump("Loading" + bindir.path + "\n"); Components.manager.autoRegister(bindir); // Make sure to load the backend loader as early as possible, as xpcshell doesn't have the // normal app flow with profile-after-change et al. - Components.classes["@mozilla.org/calendar/backend-loader;1"].getService(); + Cc["@mozilla.org/calendar/backend-loader;1"].getService(); })(); ChromeUtils.import("resource://calendar/modules/calUtils.jsm"); function createDate(aYear, aMonth, aDay, aHasTime, aHour, aMinute, aSecond, aTimezone) { - let date = Cc["@mozilla.org/calendar/datetime;1"] - .createInstance(Ci.calIDateTime); + let date = Cc["@mozilla.org/calendar/datetime;1"].createInstance(Ci.calIDateTime); date.resetTo(aYear, aMonth, aDay, aHour || 0, aMinute || 0, aSecond || 0, aTimezone || cal.dtz.UTC); date.isDate = !aHasTime; return date; } function createEventFromIcalString(icalString) { if (/^BEGIN:VCALENDAR/.test(icalString)) { - let parser = Components.classes["@mozilla.org/calendar/ics-parser;1"] - .createInstance(Components.interfaces.calIIcsParser); + let parser = Cc["@mozilla.org/calendar/ics-parser;1"].createInstance(Ci.calIIcsParser); parser.parseString(icalString); let items = parser.getItems({}); cal.ASSERT(items.length == 1); return items[0]; } else { let event = Cc["@mozilla.org/calendar/event;1"].createInstance(Ci.calIEvent); event.icalString = icalString; return event; } } function createTodoFromIcalString(icalString) { - let todo = Cc["@mozilla.org/calendar/todo;1"] - .createInstance(Ci.calITodo); + let todo = Cc["@mozilla.org/calendar/todo;1"].createInstance(Ci.calITodo); todo.icalString = icalString; return todo; } function getMemoryCal() { - return Cc["@mozilla.org/calendar/calendar;1?type=memory"] - .createInstance(Ci.calISyncWriteCalendar); + return Cc["@mozilla.org/calendar/calendar;1?type=memory"].createInstance(Ci.calISyncWriteCalendar); } function getStorageCal() { // Whenever we get the storage calendar we need to request a profile, // otherwise the cleanup functions will not run do_get_profile(); // create URI let db = Services.dirsvc.get("TmpD", Ci.nsIFile); db.append("test_storage.sqlite"); let uri = Services.io.newFileURI(db); // Make sure timezone service is initialized - Components.classes["@mozilla.org/calendar/timezone-service;1"] - .getService(Components.interfaces.calIStartupService) - .startup(null); + Cc["@mozilla.org/calendar/timezone-service;1"].getService(Ci.calIStartupService).startup(null); // create storage calendar - let stor = Cc["@mozilla.org/calendar/calendar;1?type=storage"] - .createInstance(Ci.calISyncWriteCalendar); + let stor = Cc["@mozilla.org/calendar/calendar;1?type=storage"].createInstance(Ci.calISyncWriteCalendar); stor.uri = uri; stor.id = cal.getUUID(); return stor; } /** * Return an item property as string. * @param aItem @@ -268,17 +261,17 @@ function dedent(strings, ...values) { /** * Read a JSON file and return the JS object */ function readJSONFile(aFile) { let stream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance(Ci.nsIFileInputStream); try { stream.init(aFile, FileUtils.MODE_RDONLY, FileUtils.PERMS_FILE, 0); - let json = Cc["@mozilla.org/dom/json;1"].createInstance(Components.interfaces.nsIJSON); + let json = Cc["@mozilla.org/dom/json;1"].createInstance(Ci.nsIJSON); let data = json.decodeFromStream(stream, stream.available()); return data; } catch (ex) { dump("readJSONFile: Error reading JSON file: " + ex); } finally { stream.close(); } return false; @@ -308,18 +301,17 @@ function do_calendar_startup(callback) { let obs = { observe: function() { Services.obs.removeObserver(this, "calendar-startup-done"); do_test_finished(); executeSoon(callback); } }; - let startupService = Components.classes["@mozilla.org/calendar/startup-service;1"] - .getService(Components.interfaces.nsISupports).wrappedJSObject; + let startupService = Cc["@mozilla.org/calendar/startup-service;1"].getService(Ci.nsISupports).wrappedJSObject; if (startupService.started) { callback(); } else { do_test_pending(); Services.obs.addObserver(obs, "calendar-startup-done"); if (_profileInitialized) { Services.obs.notifyObservers(null, "profile-after-change", "xpcshell-do-get-profile"); diff --git a/calendar/test/unit/test_alarm.js b/calendar/test/unit/test_alarm.js --- a/calendar/test/unit/test_alarm.js +++ b/calendar/test/unit/test_alarm.js @@ -84,17 +84,17 @@ function test_email_alarm() { alarm.description = "description"; equal(alarm.description, "description"); // Set a Summary, REQUIRED for ACTION:EMAIL alarm.summary = "summary"; equal(alarm.summary, "summary"); // Set an offset of some sort - alarm.related = Components.interfaces.calIAlarm.ALARM_RELATED_START; + alarm.related = Ci.calIAlarm.ALARM_RELATED_START; alarm.offset = cal.createDuration(); // Check for at least one attendee let attendee1 = cal.createAttendee(); attendee1.id = "mailto:horst"; let attendee2 = cal.createAttendee(); attendee2.id = "mailto:gustav"; @@ -120,17 +120,17 @@ function test_email_alarm() { // TODO test attachments dump("Done\n"); } function test_audio_alarm() { dump("Testing AUDIO alarms..."); let alarm = cal.createAlarm(); - alarm.related = Components.interfaces.calIAlarm.ALARM_RELATED_ABSOLUTE; + alarm.related = Ci.calIAlarm.ALARM_RELATED_ABSOLUTE; alarm.alarmDate = cal.createDateTime(); // Set ACTION to AUDIO, make sure this was not rejected alarm.action = "AUDIO"; equal(alarm.action, "AUDIO"); // No Description for ACTION:AUDIO alarm.description = "description"; equal(alarm.description, null); @@ -279,17 +279,17 @@ function test_repeat() { } // Check unset value equal(alarm.repeat, 0); equal(alarm.repeatOffset, null); // Check repeatDate alarm = cal.createAlarm(); - alarm.related = Components.interfaces.calIAlarm.ALARM_RELATED_ABSOLUTE; + alarm.related = Ci.calIAlarm.ALARM_RELATED_ABSOLUTE; alarm.alarmDate = cal.createDateTime(); alarm.repeat = 1; alarm.repeatOffset = cal.createDuration(); alarm.repeatOffset.inSeconds = 3600; let date = alarm.alarmDate.clone(); date.second += 3600; equal(alarm.repeatDate.icalString, date.icalString); @@ -403,17 +403,17 @@ function test_immutable() { alarm.makeImmutable(); ok(!alarm.isMutable); // Check each attribute for (let prop in propMap) { try { alarm[prop] = propMap[prop]; } catch (e) { - equal(e.result, Components.results.NS_ERROR_OBJECT_IS_IMMUTABLE); + equal(e.result, Cr.NS_ERROR_OBJECT_IS_IMMUTABLE); continue; } do_throw("Attribute " + prop + " was writable while item was immutable"); } // Functions throws(() => { alarm.setProperty("X-FOO", "changed"); @@ -569,26 +569,26 @@ function test_serialize() { }, /Illegal value/, "Invalid Argument"); } function test_strings() { // Serializing the string shouldn't throw, but we don't really care about // the string itself. let alarm = cal.createAlarm(); alarm.action = "DISPLAY"; - alarm.related = Components.interfaces.calIAlarm.ALARM_RELATED_ABSOLUTE; + alarm.related = Ci.calIAlarm.ALARM_RELATED_ABSOLUTE; alarm.alarmDate = cal.createDateTime(); alarm.toString(); - alarm.related = Components.interfaces.calIAlarm.ALARM_RELATED_START; + alarm.related = Ci.calIAlarm.ALARM_RELATED_START; alarm.offset = cal.createDuration(); alarm.toString(); alarm.toString(cal.createTodo()); - alarm.related = Components.interfaces.calIAlarm.ALARM_RELATED_END; + alarm.related = Ci.calIAlarm.ALARM_RELATED_END; alarm.offset = cal.createDuration(); alarm.toString(); alarm.toString(cal.createTodo()); alarm.offset = cal.createDuration("P1D"); alarm.toString(); alarm.offset = cal.createDuration("PT1H"); diff --git a/calendar/test/unit/test_alarmservice.js b/calendar/test/unit/test_alarmservice.js --- a/calendar/test/unit/test_alarmservice.js +++ b/calendar/test/unit/test_alarmservice.js @@ -7,17 +7,17 @@ ChromeUtils.import("resource://gre/modul var EXPECT_NONE = 0; var EXPECT_FIRED = 1; var EXPECT_TIMER = 2; function do_check_xor(a, b, aMessage) { return ok((a && !b) || (!a && b), aMessage); } var alarmObserver = { - QueryInterface: XPCOMUtils.generateQI([Components.interfaces.calIAlarmServiceObserver]), + QueryInterface: XPCOMUtils.generateQI([Ci.calIAlarmServiceObserver]), service: null, firedMap: {}, expectedMap: {}, pendingOps: {}, onAlarm: function(aItem, aAlarm) { this.firedMap[aItem.hashId] = this.firedMap[aItem.hashId] || {}; @@ -134,19 +134,17 @@ function run_test() { add_test(test_addItems); add_test(test_loadCalendar); add_test(test_modifyItems); run_next_test(); } function initializeAlarmService() { - alarmObserver.service = Components.classes["@mozilla.org/calendar/alarm-service;1"] - .getService(Components.interfaces.calIAlarmService) - .wrappedJSObject; + alarmObserver.service = Cc["@mozilla.org/calendar/alarm-service;1"].getService(Ci.calIAlarmService).wrappedJSObject; ok(!alarmObserver.service.mStarted); alarmObserver.service.startup(null); ok(alarmObserver.service.mStarted); // we need to replace the existing observers with our observer for (let obs of alarmObserver.service.mObservers.values()) { alarmObserver.service.removeObserver(obs); } diff --git a/calendar/test/unit/test_attendee.js b/calendar/test/unit/test_attendee.js --- a/calendar/test/unit/test_attendee.js +++ b/calendar/test/unit/test_attendee.js @@ -168,30 +168,30 @@ function test_properties() { a.isOrganizer = false; a.role = "CHAIR"; a.participationStatus = "DECLINED"; a.userType = "RESOURCE"; // Only X-Props should show up in the enumerator a.setProperty("X-NAME", "X-VALUE"); - for (let x of fixIterator(a.propertyEnumerator, Components.interfaces.nsIProperty)) { + for (let x of fixIterator(a.propertyEnumerator, Ci.nsIProperty)) { equal(x.name, "X-NAME"); equal(x.value, "X-VALUE"); } a.deleteProperty("X-NAME"); - for (let x of fixIterator(a.propertyEnumerator, Components.interfaces.nsIProperty)) { + for (let x of fixIterator(a.propertyEnumerator, Ci.nsIProperty)) { do_throw("Unexpected property " + x.name + " = " + x.value); } a.setProperty("X-NAME", "X-VALUE"); a.setProperty("X-NAME", null); - for (let x of fixIterator(a.propertyEnumerator, Components.interfaces.nsIProperty)) { + for (let x of fixIterator(a.propertyEnumerator, Ci.nsIProperty)) { do_throw("Unexpected property after setting null " + x.name + " = " + x.value); } } function test_doubleParameters() { function testParameters(aAttendees, aExpected) { for (let attendee of aAttendees) { let prop = attendee.icalProperty; diff --git a/calendar/test/unit/test_bug1199942.js b/calendar/test/unit/test_bug1199942.js --- a/calendar/test/unit/test_bug1199942.js +++ b/calendar/test/unit/test_bug1199942.js @@ -54,16 +54,15 @@ function serializeEvent_test() { let attendees = event.getAttendees({}); // check whether all attendees get returned with expected id for (let attendee of attendees) { ok(expectedIds.includes(attendee.id)); } // serialize the event again and check whether the attendees still are in shape - let serializer = Components.classes["@mozilla.org/calendar/ics-serializer;1"] - .createInstance(Components.interfaces.calIIcsSerializer); + let serializer = Cc["@mozilla.org/calendar/ics-serializer;1"].createInstance(Ci.calIIcsSerializer); serializer.addItems([event], [event].length); let serialized = ics_unfoldline(serializer.serializeToString()); for (let id of expectedIds) { ok(serialized.search(id) != -1); } } diff --git a/calendar/test/unit/test_bug350845.js b/calendar/test/unit/test_bug350845.js --- a/calendar/test/unit/test_bug350845.js +++ b/calendar/test/unit/test_bug350845.js @@ -28,17 +28,17 @@ function run_test() { // Enumerator throws(() => { event.getParameterEnumerator("X-UNKNOWN"); }, /Property X-UNKNOWN not set/); // More enumerator let enume = event.getParameterEnumerator("X-FOO"); ok(enume.hasMoreElements()); - let xbar = enume.getNext().QueryInterface(Components.interfaces.nsIProperty); + let xbar = enume.getNext().QueryInterface(Ci.nsIProperty); equal(xbar.name, "X-BAR"); equal(xbar.value, "FNORD"); ok(!enume.hasMoreElements()); // Deletion of parameters when deleting properties event.deleteProperty("X-FOO"); ok(!event.hasProperty("X-FOO")); event.setProperty("X-FOO", "SNORK"); diff --git a/calendar/test/unit/test_calmgr.js b/calendar/test/unit/test_calmgr.js --- a/calendar/test/unit/test_calmgr.js +++ b/calendar/test/unit/test_calmgr.js @@ -32,34 +32,34 @@ add_test(function test_registration() { checkCalendarCount(0, 0, 0); // Create a local memory calendar, ths shouldn't register any calendars let memory = calmgr.createCalendar("memory", Services.io.newURI("moz-memory-calendar://")); checkCalendarCount(0, 0, 0); // Register an observer to test it. let registered = false, unregistered = false, deleted = false, readOnly = false; - let mgrobs = cal.createAdapter(Components.interfaces.calICalendarManagerObserver, { + let mgrobs = cal.createAdapter(Ci.calICalendarManagerObserver, { onCalendarRegistered: function(aCalendar) { if (aCalendar.id == memory.id) { registered = true; } }, onCalendarUnregistering: function(aCalendar) { if (aCalendar.id == memory.id) { unregistered = true; } }, onCalendarDeleting: function(aCalendar) { if (aCalendar.id == memory.id) { deleted = true; } } }); - let calobs = cal.createAdapter(Components.interfaces.calIObserver, { + let calobs = cal.createAdapter(Ci.calIObserver, { onPropertyChanged: function(aCalendar, aName, aValue, aOldValue) { equal(aCalendar.id, memory.id); equal(aName, "readOnly"); readOnly = aValue; } }); memory.addObserver(calobs); calmgr.addObserver(mgrobs); @@ -127,22 +127,22 @@ add_test(function test_calobserver() { // First of all we need a local calendar to work on and some variables let calmgr = cal.getCalendarManager(); let memory = calmgr.createCalendar("memory", Services.io.newURI("moz-memory-calendar://")); let memory2 = calmgr.createCalendar("memory", Services.io.newURI("moz-memory-calendar://")); let calcounter, allcounter; // These observers will end up counting calls which we will use later on - let calobs = cal.createAdapter(Components.interfaces.calIObserver, { + let calobs = cal.createAdapter(Ci.calIObserver, { onAddItem: () => calcounter.addItem++, onModifyItem: () => calcounter.modifyItem++, onDeleteItem: () => calcounter.deleteItem++ }); - let allobs = cal.createAdapter(Components.interfaces.calIObserver, { + let allobs = cal.createAdapter(Ci.calIObserver, { onAddItem: () => allcounter.addItem++, onModifyItem: () => allcounter.modifyItem++, onDeleteItem: () => allcounter.deleteItem++ }); // Set up counters and observers resetCounters(); calmgr.registerCalendar(memory); @@ -218,30 +218,29 @@ add_test(function test_removeModes() { memory.wrappedJSObject.deleteCalendar = function(calendar, listener) { deleteCalled = true; return oldDeleteCalendar.apply(this, arguments); }; } // For better readability const SHOULD_DELETE = true, SHOULD_NOT_DELETE = false; - const cICM = Components.interfaces.calICalendarManager; let calmgr = cal.getCalendarManager(); let memory = calmgr.createCalendar("memory", Services.io.newURI("moz-memory-calendar://")); let baseCalendarCount = calmgr.calendarCount; let removeModes = null; let deleteCalled = false; mockCalendar(memory); checkCounts([], SHOULD_NOT_DELETE, 1); checkCounts(["unsubscribe"], SHOULD_NOT_DELETE, 0); checkCounts(["unsubscribe", "delete"], SHOULD_DELETE, 0); - checkCounts(["unsubscribe", "delete"], SHOULD_NOT_DELETE, 0, cICM.REMOVE_NO_DELETE); + checkCounts(["unsubscribe", "delete"], SHOULD_NOT_DELETE, 0, Ci.calICalendarManager.REMOVE_NO_DELETE); checkCounts(["delete"], SHOULD_DELETE, 0); run_next_test(); }); add_test(function test_calprefs() { let prop; let calmgr = cal.getCalendarManager(); diff --git a/calendar/test/unit/test_data_bags.js b/calendar/test/unit/test_data_bags.js --- a/calendar/test/unit/test_data_bags.js +++ b/calendar/test/unit/test_data_bags.js @@ -32,21 +32,21 @@ function test_property_map() { enumerator.hasMoreElements(); } equal(keys.size, 1); ok(keys.has("key2")); throws(() => { enumerator.getNext(); - }, code => code == Components.results.NS_ERROR_UNEXPECTED); + }, code => code == Cr.NS_ERROR_UNEXPECTED); } function test_listener_set() { - let set = new cal.data.ListenerSet(Components.interfaces.calIOperationListener); + let set = new cal.data.ListenerSet(Ci.calIOperationListener); let listener1Id = null; let listener2Id = null; let listener1 = cal.createAdapter("calIOperationListener", { onOperationComplete: function(aCalendar, aStatus, aOpType, aId, aDetail) { listener1Id = aId; } }); @@ -82,17 +82,17 @@ function test_listener_set() { }); set.add(listener3); set.notify("onOperationComplete", [null, null, null, "test3", null]); equal(called, 1); } function test_observer_set() { - let set = new cal.data.ObserverSet(Components.interfaces.calIObserver); + let set = new cal.data.ObserverSet(Ci.calIObserver); let listenerCountBegin1 = 0; let listenerCountBegin2 = 0; let listenerCountEnd1 = 0; let listenerCountEnd2 = 0; let listener1 = cal.createAdapter("calIObserver", { onStartBatch: function() { listenerCountBegin1++; @@ -143,41 +143,41 @@ function test_observer_set() { } function test_operation_group() { let calledCancel = false; let calledOperationCancel = null; let group = new cal.data.OperationGroup(); ok(group.id.endsWith("-0")); ok(group.isPending); - equal(group.status, Components.results.NS_OK); + equal(group.status, Cr.NS_OK); ok(group.isEmpty); let operation = { id: 123, isPending: true, cancel: (status) => { calledOperationCancel = status; } }; group.add(operation); ok(!group.isEmpty); - group.notifyCompleted(Components.results.NS_ERROR_FAILURE); + group.notifyCompleted(Cr.NS_ERROR_FAILURE); ok(!group.isPending); - equal(group.status, Components.results.NS_ERROR_FAILURE); + equal(group.status, Cr.NS_ERROR_FAILURE); strictEqual(calledOperationCancel, null); group.remove(operation); ok(group.isEmpty); group = new cal.data.OperationGroup(() => { calledCancel = true; }); ok(group.id.endsWith("-1")); group.add(operation); group.cancel(); - equal(group.status, Components.interfaces.calIErrors.OPERATION_CANCELLED); - equal(calledOperationCancel, Components.interfaces.calIErrors.OPERATION_CANCELLED); + equal(group.status, Ci.calIErrors.OPERATION_CANCELLED); + equal(calledOperationCancel, Ci.calIErrors.OPERATION_CANCELLED); ok(calledCancel); } diff --git a/calendar/test/unit/test_datetimeformatter.js b/calendar/test/unit/test_datetimeformatter.js --- a/calendar/test/unit/test_datetimeformatter.js +++ b/calendar/test/unit/test_datetimeformatter.js @@ -44,18 +44,17 @@ add_task(async function formatDate_test( let i = 0; for (let test of data) { i++; Preferences.set("calendar.date.format", test.input.dateformat); let zone = (test.input.timezone == "floating") ? cal.dtz.floating : tzs.getTimezone(test.input.timezone); let date = cal.createDateTime(test.input.datetime).getInTimezone(zone); - let dtFormatter = Components.classes["@mozilla.org/calendar/datetime-formatter;1"] - .getService(Components.interfaces.calIDateTimeFormatter); + let dtFormatter = Cc["@mozilla.org/calendar/datetime-formatter;1"].getService(Ci.calIDateTimeFormatter); let formatted = dtFormatter.formatDate(date); ok( test.expected.includes(formatted), "(test #" + i + ": result '" + formatted + "', expected '" + test.expected + "')" ); } // let's reset the preferences Preferences.set("calendar.timezone.local", tzlocal); @@ -128,18 +127,17 @@ add_task(async function formatDateShort_ let i = 0; for (let test of data) { i++; let zone = (test.input.timezone == "floating") ? cal.dtz.floating : tzs.getTimezone(test.input.timezone); let date = cal.createDateTime(test.input.datetime).getInTimezone(zone); - let dtFormatter = Components.classes["@mozilla.org/calendar/datetime-formatter;1"] - .getService(Components.interfaces.calIDateTimeFormatter); + let dtFormatter = Cc["@mozilla.org/calendar/datetime-formatter;1"].getService(Ci.calIDateTimeFormatter); let formatted = dtFormatter.formatDateShort(date); ok( test.expected.includes(formatted), "(test #" + i + ": result '" + formatted + "', expected '" + test.expected + "')" ); } // let's reset the preferences @@ -213,18 +211,17 @@ add_task(async function formatDateLong_t let i = 0; for (let test of data) { i++; let zone = (test.input.timezone == "floating") ? cal.dtz.floating : tzs.getTimezone(test.input.timezone); let date = cal.createDateTime(test.input.datetime).getInTimezone(zone); - let dtFormatter = Components.classes["@mozilla.org/calendar/datetime-formatter;1"] - .getService(Components.interfaces.calIDateTimeFormatter); + let dtFormatter = Cc["@mozilla.org/calendar/datetime-formatter;1"].getService(Ci.calIDateTimeFormatter); let formatted = dtFormatter.formatDateLong(date); ok( test.expected.includes(formatted), "(test #" + i + ": result '" + formatted + "', expected '" + test.expected + "')" ); } // let's reset the preferences @@ -298,18 +295,17 @@ add_task(async function formatDateWithou let i = 0; for (let test of data) { i++; let zone = (test.input.timezone == "floating") ? cal.dtz.floating : tzs.getTimezone(test.input.timezone); let date = cal.createDateTime(test.input.datetime).getInTimezone(zone); - let dtFormatter = Components.classes["@mozilla.org/calendar/datetime-formatter;1"] - .getService(Components.interfaces.calIDateTimeFormatter); + let dtFormatter = Cc["@mozilla.org/calendar/datetime-formatter;1"].getService(Ci.calIDateTimeFormatter); equal(dtFormatter.formatDateWithoutYear(date), test.expected, "(test #" + i + ")"); } // let's reset the preferences Preferences.set("calendar.timezone.local", tzlocal); Preferences.set("calendar.date.format", dateformat); Preferences.set("intl.regional_prefs.use_os_locales", useOsLocale); }); @@ -358,18 +354,17 @@ add_task(async function formatTime_test( let i = 0; for (let test of data) { i++; let zone = (test.input.timezone == "floating") ? cal.dtz.floating : tzs.getTimezone(test.input.timezone); let date = cal.createDateTime(test.input.datetime).getInTimezone(zone); - let dtFormatter = Components.classes["@mozilla.org/calendar/datetime-formatter;1"] - .getService(Components.interfaces.calIDateTimeFormatter); + let dtFormatter = Cc["@mozilla.org/calendar/datetime-formatter;1"].getService(Ci.calIDateTimeFormatter); let formatted = dtFormatter.formatTime(date); ok( test.expected.includes(formatted), "(test #" + i + ": result '" + formatted + "', expected '" + test.expected + "')" ); } // let's reset the preferences diff --git a/calendar/test/unit/test_deleted_items.js b/calendar/test/unit/test_deleted_items.js --- a/calendar/test/unit/test_deleted_items.js +++ b/calendar/test/unit/test_deleted_items.js @@ -2,35 +2,32 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ function run_test() { do_calendar_startup(run_next_test); } function check_delmgr_call(aFunc) { - const mISSC = Components.interfaces.mozIStorageStatementCallback; - let delmgr = Components.classes["@mozilla.org/calendar/deleted-items-manager;1"] - .getService(Components.interfaces.calIDeletedItems); + let delmgr = Cc["@mozilla.org/calendar/deleted-items-manager;1"].getService(Ci.calIDeletedItems); return new Promise((resolve, reject) => { delmgr.wrappedJSObject.completedNotifier.handleCompletion = (aReason) => { - if (aReason == mISSC.REASON_FINISHED) { + if (aReason == Ci.mozIStorageStatementCallback.REASON_FINISHED) { resolve(); } else { reject(aReason); } }; aFunc(); }); } add_task(async function test_deleted_items() { let calmgr = cal.getCalendarManager(); - let delmgr = Components.classes["@mozilla.org/calendar/deleted-items-manager;1"] - .getService(Components.interfaces.calIDeletedItems); + let delmgr = Cc["@mozilla.org/calendar/deleted-items-manager;1"].getService(Ci.calIDeletedItems); // No items have been deleted, retrieving one should return null. equal(delmgr.getDeletedDate("random"), null); equal(delmgr.getDeletedDate("random", "random"), null); // Make sure the cache is initially flushed and that this doesn't throw an // error. await check_delmgr_call(() => delmgr.flush()); diff --git a/calendar/test/unit/test_freebusy.js b/calendar/test/unit/test_freebusy.js --- a/calendar/test/unit/test_freebusy.js +++ b/calendar/test/unit/test_freebusy.js @@ -7,18 +7,17 @@ function run_test() { } function really_run_test() { test_freebusy(); test_period(); } function test_freebusy() { - let icsService = Components.classes["@mozilla.org/calendar/ics-service;1"] - .getService(Components.interfaces.calIICSService); + let icsService = Cc["@mozilla.org/calendar/ics-service;1"].getService(Ci.calIICSService); // Bug 415987 - FREEBUSY decoding does not support comma-separated entries // (https://bugzilla.mozilla.org/show_bug.cgi?id=415987) let fbVal1 = "20080206T160000Z/PT1H"; let fbVal2 = "20080206T180000Z/PT1H"; let fbVal3 = "20080206T220000Z/PT1H"; let data = "BEGIN:VCALENDAR\n" + @@ -28,18 +27,17 @@ function test_freebusy() { "END:VCALENDAR\n"; let fbComp = icsService.parseICS(data, null).getFirstSubcomponent("VFREEBUSY"); equal(fbComp.getFirstProperty("FREEBUSY").value, fbVal1); equal(fbComp.getNextProperty("FREEBUSY").value, fbVal2); equal(fbComp.getNextProperty("FREEBUSY").value, fbVal3); } function test_period() { - let period = Components.classes["@mozilla.org/calendar/period;1"] - .createInstance(Components.interfaces.calIPeriod); + let period = Cc["@mozilla.org/calendar/period;1"].createInstance(Ci.calIPeriod); period.start = cal.createDateTime("20120101T010101"); period.end = cal.createDateTime("20120101T010102"); equal(period.icalString, "20120101T010101/20120101T010102"); equal(period.duration.icalString, "PT1S"); period.icalString = "20120101T010103/20120101T010104"; diff --git a/calendar/test/unit/test_freebusy_service.js b/calendar/test/unit/test_freebusy_service.js --- a/calendar/test/unit/test_freebusy_service.js +++ b/calendar/test/unit/test_freebusy_service.js @@ -1,17 +1,15 @@ /* 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/. */ ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); -var cIFI = Components.interfaces.calIFreeBusyInterval; -var freebusy = Components.classes["@mozilla.org/calendar/freebusy-service;1"] - .getService(Components.interfaces.calIFreeBusyService); +var freebusy = Cc["@mozilla.org/calendar/freebusy-service;1"].getService(Ci.calIFreeBusyService); function run_test() { do_calendar_startup(really_run_test); } function really_run_test() { test_found(); test_failure(); @@ -32,17 +30,17 @@ function test_found() { let provider2 = { id: 2, called: false, getFreeBusyIntervals: function(aCalId, aStart, aEnd, aTypes, aListener) { ok(!this.called); this.called = true; - let interval = new cal.provider.FreeBusyInterval(aCalId, cIFI.BUSY, aStart, aEnd); + let interval = new cal.provider.FreeBusyInterval(aCalId, Ci.calIFreeBusyInterval.BUSY, aStart, aEnd); aListener.onResult(null, [interval]); } }; provider2.wrappedJSObject = provider2; freebusy.addProvider(provider1); equal(_countProviders(), 1); freebusy.addProvider(provider2); @@ -52,40 +50,41 @@ function test_found() { equal(_getFirstProvider().id, 2); let listener = { called: false, onResult: function(request, result) { equal(result.length, 1); equal(result[0].interval.start.icalString, "20120101T010101"); equal(result[0].interval.end.icalString, "20120102T010101"); - equal(result[0].freeBusyType, cIFI.BUSY); + equal(result[0].freeBusyType, Ci.calIFreeBusyInterval.BUSY); equal(result.length, 1); ok(provider2.called); do_test_finished(); } }; do_test_pending(); freebusy.getFreeBusyIntervals("email", cal.createDateTime("20120101T010101"), cal.createDateTime("20120102T010101"), - cIFI.BUSY_ALL, listener); + Ci.calIFreeBusyInterval.BUSY_ALL, + listener); } function test_failure() { _clearProviders(); let provider = { called: false, getFreeBusyIntervals: function(aCalId, aStart, aEnd, aTypes, aListener) { ok(!this.called); this.called = true; - aListener.onResult({ status: Components.results.NS_ERROR_FAILURE }, "notFound"); + aListener.onResult({ status: Cr.NS_ERROR_FAILURE }, "notFound"); } }; let listener = { onResult: function(request, result) { ok(!this.called); equal(result.length, 0); equal(request.status, 0); @@ -95,41 +94,41 @@ function test_failure() { }; freebusy.addProvider(provider); do_test_pending(); freebusy.getFreeBusyIntervals("email", cal.createDateTime("20120101T010101"), cal.createDateTime("20120102T010101"), - cIFI.BUSY_ALL, + Ci.calIFreeBusyInterval.BUSY_ALL, listener); } function test_cancel() { _clearProviders(); let provider = { - QueryInterface: XPCOMUtils.generateQI([Components.interfaces.calIFreeBusyProvider, Components.interfaces.calIOperation]), + QueryInterface: XPCOMUtils.generateQI([Ci.calIFreeBusyProvider, Ci.calIOperation]), getFreeBusyIntervals: function(aCalId, aStart, aEnd, aTypes, aListener) { Services.tm.currentThread.dispatch({ run: function() { dump("Cancelling freebusy query..."); operation.cancel(); } - }, Components.interfaces.nsIEventTarget.DISPATCH_NORMAL); + }, Ci.nsIEventTarget.DISPATCH_NORMAL); // No listener call, we emulate a long running search // Do return the operation though return this; }, isPending: true, cancelCalled: false, - status: Components.results.NS_OK, + status: Cr.NS_OK, cancel: function() { this.cancelCalled = true; }, }; let listener = { called: false, onResult: function(request, result) { @@ -142,17 +141,17 @@ function test_cancel() { }; freebusy.addProvider(provider); do_test_pending(); let operation = freebusy.getFreeBusyIntervals("email", cal.createDateTime("20120101T010101"), cal.createDateTime("20120102T010101"), - cIFI.BUSY_ALL, + Ci.calIFreeBusyInterval.BUSY_ALL, listener); } // The following functions are not in the interface description and probably // don't need to be. Make assumptions about the implementation instead. function _clearProviders() { freebusy.wrappedJSObject.mProviders = new Set(); diff --git a/calendar/test/unit/test_gdata_provider.js b/calendar/test/unit/test_gdata_provider.js --- a/calendar/test/unit/test_gdata_provider.js +++ b/calendar/test/unit/test_gdata_provider.js @@ -10,17 +10,17 @@ Services.prefs.setBoolPref("calendar.debug.log.verbose", true); let xpiFile; let env = Cc["@mozilla.org/process/environment;1"].getService(Ci.nsIEnvironment); if (env.exists("MOZ_FETCHES_DIR")) { xpiFile = new FileUtils.File(env.get("MOZ_FETCHES_DIR")); xpiFile.append("gdata-provider.en-US.xpi"); } else { - xpiFile = Services.dirsvc.get("CurProcD", Components.interfaces.nsIFile); + xpiFile = Services.dirsvc.get("CurProcD", Ci.nsIFile); xpiFile.append("extensions"); xpiFile.append("{a62ef8ec-5fdc-40c2-873c-223b8a6925cc}"); } dump("Loading " + xpiFile.path + "\n"); let manager = Cc["@mozilla.org/component-manager-extra;1"].getService(Ci.nsIComponentManagerExtra); manager.addLegacyExtensionManifestLocation(xpiFile); })(); @@ -174,17 +174,17 @@ GDataServer.prototype = { { type: "eventCancellation", method: "email" } ] } }; }, waitForLoad: function(aCalendar) { return new Promise((resolve, reject) => { - let observer = cal.createAdapter(Components.interfaces.calIObserver, { + let observer = cal.createAdapter(Ci.calIObserver, { onLoad: function() { let uncached = aCalendar.wrappedJSObject.mUncachedCalendar.wrappedJSObject; aCalendar.removeObserver(observer); if (Components.isSuccessCode(uncached._lastStatus)) { resolve(aCalendar); } else { reject(uncached._lastMessage); @@ -603,18 +603,17 @@ add_task(async function test_dateToJSON( "END:DAYLIGHT", "END:VTIMEZONE", "BEGIN:VEVENT", "UID:123", "DTSTART;TZID=" + tzid + ":20150130T120000", "END:VEVENT", "END:VCALENDAR"].join("\r\n"); - let parser = Components.classes["@mozilla.org/calendar/ics-parser;1"] - .createInstance(Components.interfaces.calIIcsParser); + let parser = Cc["@mozilla.org/calendar/ics-parser;1"].createInstance(Ci.calIIcsParser); parser.parseString(ics); let items = parser.getItems({}); return items[0].startDate; } let date; // no timezone @@ -1563,17 +1562,17 @@ add_task(async function test_conflict_mo MockConflictPrompt.overwrite = false; gServer.events[0].etag = '"3"'; gServer.events[0].summary = "remote change"; try { modifiedItem = await pclient.modifyItem(newItem, item); do_throw("Expected modifyItem to be cancelled"); } catch (e) { // Swallow cancelling the request - if (e != Components.interfaces.calIErrors.OPERATION_CANCELLED) { + if (e != Ci.calIErrors.OPERATION_CANCELLED) { throw e; } } await gServer.waitForLoad(client); item = (await pclient.getAllItems())[0]; equal(gServer.events[0].summary, "remote change"); @@ -1584,17 +1583,17 @@ add_task(async function test_conflict_mo MockConflictPrompt.overwrite = false; gServer.events[0].etag = '"4"'; gServer.events[0].summary = "remote change"; try { await pclient.deleteItem(item); do_throw("Expected deleteItem to be cancelled"); } catch (e) { // Swallow cancelling the request - if (e != Components.interfaces.calIErrors.OPERATION_CANCELLED) { + if (e != Ci.calIErrors.OPERATION_CANCELLED) { throw e; } } await gServer.waitForLoad(client); item = (await pclient.getAllItems())[0]; equal(gServer.events[0].summary, "remote change"); @@ -1652,17 +1651,17 @@ add_task(async function test_conflict_de // Case #2: Deleted on server, modify locally, don't overwrite conflict MockConflictPrompt.overwrite = false; gServer.events = []; try { modifiedItem = await pclient.modifyItem(newItem, item); do_throw("Expected modifyItem to be cancelled"); } catch (e) { // Swallow cancelling the request - if (e != Components.interfaces.calIErrors.OPERATION_CANCELLED) { + if (e != Ci.calIErrors.OPERATION_CANCELLED) { throw e; } } // The next synchronize should cause the event to be deleted locally. coreEvent.status = "cancelled"; gServer.events = [coreEvent]; await gServer.waitForLoad(client); @@ -1681,17 +1680,17 @@ add_task(async function test_conflict_de // Case #3: Deleted on server, delete locally, don't overwrite conflict MockConflictPrompt.overwrite = false; gServer.events = []; try { await pclient.deleteItem(item); do_throw("Expected deleteItem to be cancelled"); } catch (e) { // Swallow cancelling the request - if (e != Components.interfaces.calIErrors.OPERATION_CANCELLED) { + if (e != Ci.calIErrors.OPERATION_CANCELLED) { throw e; } } // The next synchronize should cause the event to be deleted locally. coreEvent.status = "cancelled"; gServer.events = [coreEvent]; await gServer.waitForLoad(client); diff --git a/calendar/test/unit/test_ics_parser.js b/calendar/test/unit/test_ics_parser.js --- a/calendar/test/unit/test_ics_parser.js +++ b/calendar/test/unit/test_ics_parser.js @@ -13,18 +13,17 @@ function really_run_test() { test_failures(); } test_fake_parent(); test_props_comps(); test_timezone(); } function test_props_comps() { - let parser = Components.classes["@mozilla.org/calendar/ics-parser;1"] - .createInstance(Components.interfaces.calIIcsParser); + let parser = Cc["@mozilla.org/calendar/ics-parser;1"].createInstance(Ci.calIIcsParser); let str = [ "BEGIN:VCALENDAR", "X-WR-CALNAME:CALNAME", "BEGIN:VJOURNAL", "LOCATION:BEFORE TIME", "END:VJOURNAL", "BEGIN:VEVENT", "UID:123", @@ -39,46 +38,43 @@ function test_props_comps() { let comps = parser.getComponents({}); equal(comps.length, 1); equal(comps[0].componentType, "VJOURNAL"); equal(comps[0].location, "BEFORE TIME"); } function test_failures() { - let parser = Components.classes["@mozilla.org/calendar/ics-parser;1"] - .createInstance(Components.interfaces.calIIcsParser); + let parser = Cc["@mozilla.org/calendar/ics-parser;1"].createInstance(Ci.calIIcsParser); do_test_pending(); parser.parseString("BOGUS", null, { onParsingComplete: function(rc, opparser) { dump("Note: The previous error message is expected ^^\n"); - equal(rc, Components.results.NS_ERROR_FAILURE); + equal(rc, Cr.NS_ERROR_FAILURE); do_test_finished(); } }); // No real error here, but there is a message... - parser = Components.classes["@mozilla.org/calendar/ics-parser;1"] - .createInstance(Components.interfaces.calIIcsParser); + parser = Cc["@mozilla.org/calendar/ics-parser;1"].createInstance(Ci.calIIcsParser); let str = [ "BEGIN:VWORLD", "BEGIN:VEVENT", "UID:123", "END:VEVENT", "END:VWORLD"].join("\r\n"); dump("Note: The following error message is expected:\n"); parser.parseString(str); equal(parser.getComponents({}).length, 0); equal(parser.getItems({}).length, 0); } function test_fake_parent() { - let parser = Components.classes["@mozilla.org/calendar/ics-parser;1"] - .createInstance(Components.interfaces.calIIcsParser); + let parser = Cc["@mozilla.org/calendar/ics-parser;1"].createInstance(Ci.calIIcsParser); let str = [ "BEGIN:VCALENDAR", "BEGIN:VEVENT", "UID:123", "RECURRENCE-ID:20120101T010101", "DTSTART:20120101T010102", "LOCATION:HELL", @@ -103,18 +99,17 @@ function test_fake_parent() { equal(excs.length, 1); let exc = excs[0]; equal(exc.startDate.icalString, "20120101T010102"); equal(parser.getParentlessItems({})[0], exc); } function test_async() { - let parser = Components.classes["@mozilla.org/calendar/ics-parser;1"] - .createInstance(Components.interfaces.calIIcsParser); + let parser = Cc["@mozilla.org/calendar/ics-parser;1"].createInstance(Ci.calIIcsParser); let str = [ "BEGIN:VCALENDAR", "BEGIN:VTODO", "UID:1", "DTSTART:20120101T010101", "DUE:20120101T010102", "END:VTODO", "BEGIN:VTODO", @@ -146,20 +141,18 @@ function test_async() { }); } function test_timezone() { // TODO } function test_roundtrip() { - let parser = Components.classes["@mozilla.org/calendar/ics-parser;1"] - .createInstance(Components.interfaces.calIIcsParser); - let serializer = Components.classes["@mozilla.org/calendar/ics-serializer;1"] - .createInstance(Components.interfaces.calIIcsSerializer); + let parser = Cc["@mozilla.org/calendar/ics-parser;1"].createInstance(Ci.calIIcsParser); + let serializer = Cc["@mozilla.org/calendar/ics-serializer;1"].createInstance(Ci.calIIcsSerializer); let str = [ "BEGIN:VCALENDAR", "PRODID:-//Mozilla.org/NONSGML Mozilla Calendar V1.1//EN", "VERSION:2.0", "X-PROP:VAL", "BEGIN:VTODO", "UID:1", "DTSTART:20120101T010101", @@ -178,18 +171,17 @@ function test_roundtrip() { parser.getProperties({}).forEach(serializer.addProperty, serializer); parser.getComponents({}).forEach(serializer.addComponent, serializer); equal(serializer.serializeToString().split("\r\n").sort().join("\r\n"), str.split("\r\n").sort().join("\r\n")); // Test parseFromStream - parser = Components.classes["@mozilla.org/calendar/ics-parser;1"] - .createInstance(Components.interfaces.calIIcsParser); + parser = Cc["@mozilla.org/calendar/ics-parser;1"].createInstance(Ci.calIIcsParser); let stream = serializer.serializeToInputStream(); parser.parseFromStream(stream); items = parser.getItems({}); let comps = parser.getComponents({}); let props = parser.getProperties({}); equal(items.length, 1); @@ -198,20 +190,18 @@ function test_roundtrip() { let everything = items[0].icalString.split("\r\n").concat(comps[0].serializeToICS().split("\r\n")); everything.push((props[0].icalString.split("\r\n"))[0]); everything.sort(); equal(everything.join("\r\n"), str.split("\r\n").concat([""]).sort().join("\r\n")); // Test serializeToStream/parseFromStream - parser = Components.classes["@mozilla.org/calendar/ics-parser;1"] - .createInstance(Components.interfaces.calIIcsParser); - let pipe = Components.classes["@mozilla.org/pipe;1"] - .createInstance(Components.interfaces.nsIPipe); + parser = Cc["@mozilla.org/calendar/ics-parser;1"].createInstance(Ci.calIIcsParser); + let pipe = Cc["@mozilla.org/pipe;1"].createInstance(Ci.nsIPipe); pipe.init(true, true, 0, 0, null); serializer.serializeToStream(pipe.outputStream); parser.parseFromStream(pipe.inputStream); items = parser.getItems({}); comps = parser.getComponents({}); props = parser.getProperties({}); diff --git a/calendar/test/unit/test_imip.js b/calendar/test/unit/test_imip.js --- a/calendar/test/unit/test_imip.js +++ b/calendar/test/unit/test_imip.js @@ -5,19 +5,17 @@ ChromeUtils.import("resource://gre/modules/Preferences.jsm"); ChromeUtils.import("resource://gre/modules/Services.jsm"); var calItipEmailTransport = {}; Services.scriptloader.loadSubScript( "resource://calendar/components/calItipEmailTransport.js", calItipEmailTransport); function itipItemForTest(title, seq) { - let itipItem = Components - .classes["@mozilla.org/calendar/itip-item;1"] - .createInstance(Components.interfaces.calIItipItem); + let itipItem = Cc["@mozilla.org/calendar/itip-item;1"].createInstance(Ci.calIItipItem); itipItem.init([ "BEGIN:VCALENDAR", "METHOD:REQUEST", "BEGIN:VEVENT", "SUMMARY:" + title, "SEQUENCE:" + (seq || 0), "END:VEVENT", "END:VCALENDAR" diff --git a/calendar/test/unit/test_items.js b/calendar/test/unit/test_items.js --- a/calendar/test/unit/test_items.js +++ b/calendar/test/unit/test_items.js @@ -16,31 +16,31 @@ function really_run_test() { test_attachment(); test_lastack(); test_categories(); test_alarm(); } function test_aclmanager() { let mockCalendar = { - QueryInterface: XPCOMUtils.generateQI([Components.interfaces.calICalendar]), + QueryInterface: XPCOMUtils.generateQI([Ci.calICalendar]), get superCalendar() { return this; }, get aclManager() { return this; }, getItemEntry: function(item) { if (item.id == "withentry") { return itemEntry; } return null; }, }; let itemEntry = { - QueryInterface: XPCOMUtils.generateQI([Components.interfaces.calIItemACLEntry]), + QueryInterface: XPCOMUtils.generateQI([Ci.calIItemACLEntry]), userCanModify: true, userCanRespond: false, userCanViewAll: true, userCanViewDateAndTime: false, }; let event = cal.createEvent(); event.id = "withentry"; @@ -67,17 +67,17 @@ function test_aclmanager() { equal(event.aclEntry, null); } function test_calendar() { let event = cal.createEvent(); let parentEntry = cal.createEvent(); let mockCalendar = { - QueryInterface: XPCOMUtils.generateQI([Components.interfaces.calICalendar]), + QueryInterface: XPCOMUtils.generateQI([Ci.calICalendar]), id: "one" }; parentEntry.calendar = mockCalendar; event.parentItem = parentEntry; notEqual(event.calendar, null); equal(event.calendar.id, "one"); @@ -159,17 +159,17 @@ function test_categories() { } } function test_alarm() { let e = cal.createEvent(); let alarm = cal.createAlarm(); alarm.action = "DISPLAY"; - alarm.related = Components.interfaces.calIAlarm.ALARM_RELATED_ABSOLUTE; + alarm.related = Ci.calIAlarm.ALARM_RELATED_ABSOLUTE; alarm.alarmDate = cal.createDateTime(); e.addAlarm(alarm); let ecomp = e.icalComponent; let vcomp = ecomp.getFirstSubcomponent("VALARM"); equal(vcomp.serializeToICS(), alarm.icalString); let alarm2 = alarm.clone(); diff --git a/calendar/test/unit/test_ltninvitationutils.js b/calendar/test/unit/test_ltninvitationutils.js --- a/calendar/test/unit/test_ltninvitationutils.js +++ b/calendar/test/unit/test_ltninvitationutils.js @@ -131,18 +131,17 @@ add_task(async function getItipHeader_te method: "", attendees: [""] }, expected: "Event Invitation" }]; let i = 0; for (let test of data) { i++; - let itipItem = Components.classes["@mozilla.org/calendar/itip-item;1"] - .createInstance(Components.interfaces.calIItipItem); + let itipItem = Cc["@mozilla.org/calendar/itip-item;1"].createInstance(Ci.calIItipItem); let item = getIcs(); let sender; if (test.input.method || test.input.method == "") { item = item.replace(/METHOD:REQUEST\r\n/, test.input.method); } if (test.input.attendees.length) { let attendees = test.input.attendees.filter(aAtt => !!aAtt).join("\r\n"); item = item.replace(/(ATTENDEE.+(?:\r\n))/, attendees + "\r\n"); @@ -364,21 +363,19 @@ add_task(async function createInvitation case "attach": item = item.replace(/ATTACH:[^\r]+\r\n/, test.input.attach); break; case "url": item = item.replace(/URL:[^\r]+\r\n/, test.input.url); break; } } - let itipItem = Components.classes["@mozilla.org/calendar/itip-item;1"] - .createInstance(Components.interfaces.calIItipItem); + let itipItem = Cc["@mozilla.org/calendar/itip-item;1"].createInstance(Ci.calIItipItem); itipItem.init(item); - let parser = Components.classes["@mozilla.org/calendar/ics-parser;1"] - .createInstance(Components.interfaces.calIIcsParser); + let parser = Cc["@mozilla.org/calendar/ics-parser;1"].createInstance(Ci.calIIcsParser); parser.parseString(item); let dom = ltn.invitation.createInvitationOverlay(parser.getItems({})[0], itipItem); let observed = dom.getElementById(test.expected.node).innerHTML; // we remove line-breaks and leading white spaces here so we can keep expected test results // above more comprehensive if (test.expected.node.endsWith("-table")) { observed = observed.replace(/(?:\n|\r\n|\r)[ ]{2,}/g, ""); } @@ -395,21 +392,19 @@ add_task(async function compareInvitatio for (let prop of props) { if (Object.keys(aInput).includes(prop)) { let regex = prop.toUpperCase() + (["summary", "location"].includes(prop) ? ":" : ";") + "[^\r]+\r\n"; item = item.replace(new RegExp(regex), aInput[prop]); } } - let itipItem = Components.classes["@mozilla.org/calendar/itip-item;1"] - .createInstance(Components.interfaces.calIItipItem); + let itipItem = Cc["@mozilla.org/calendar/itip-item;1"].createInstance(Ci.calIItipItem); itipItem.init(item); - let parser = Components.classes["@mozilla.org/calendar/ics-parser;1"] - .createInstance(Components.interfaces.calIIcsParser); + let parser = Cc["@mozilla.org/calendar/ics-parser;1"].createInstance(Ci.calIIcsParser); parser.parseString(item); let dom = ltn.invitation.createInvitationOverlay(parser.getItems({})[0], itipItem); return cal.xml.serializeDOM(dom); } let data = [{ input: { previous: { location: "LOCATION:This place\r\n" }, current: { location: "LOCATION:Another location\r\n" }, @@ -640,18 +635,17 @@ add_task(async function getHeaderSection identity.fullName = test.input.identity.fullName || null; identity.replyTo = test.input.identity.replyTo || null; identity.organization = test.input.identity.organization || null; identity.doCc = test.input.identity.doCc || (test.input.identity.cc); identity.doCcList = test.input.identity.cc || null; identity.doBcc = test.input.identity.doBcc || (test.input.identity.bcc); identity.doBccList = test.input.identity.bcc || null; - let composeUtils = Components.classes["@mozilla.org/messengercompose/computils;1"] - .createInstance(Components.interfaces.nsIMsgCompUtils); + let composeUtils = Cc["@mozilla.org/messengercompose/computils;1"].createInstance(Ci.nsIMsgCompUtils); let messageId = composeUtils.msgGenerateMessageId(identity); let header = ltn.invitation.getHeaderSection(messageId, identity, test.input.toList, test.input.subject); // we test Date and Message-ID headers separately to avoid false positives ok(!!header.match(/Date:.+(?:\n|\r\n|\r)/), "(test #" + i + "): date"); ok(!!header.match(/Message-ID:.+(?:\n|\r\n|\r)/), diff --git a/calendar/test/unit/test_providers.js b/calendar/test/unit/test_providers.js --- a/calendar/test/unit/test_providers.js +++ b/calendar/test/unit/test_providers.js @@ -1,14 +1,12 @@ /* 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/. */ -const cIC = Components.interfaces.calICalendar; - var icalStringArray = [ // Comments refer to the range defined in testGetItems(). // 1: one-hour event "BEGIN:VEVENT\n" + "DTSTART:20020402T114500Z\n" + "DTEND:20020402T124500Z\n" + "END:VEVENT\n", // 2: Test a zero-length event with DTSTART and DTEND @@ -439,17 +437,17 @@ async function testOfflineStorage(storag event1 = await pcal.addItem(event1); // Make sure the event is really in the calendar let result = await pcal.getAllItems(); equal(result.length, 1); // When searching for offline added items, there are none - let filter = cIC.ITEM_FILTER_ALL_ITEMS | cIC.ITEM_FILTER_OFFLINE_CREATED; + let filter = Ci.calICalendar.ITEM_FILTER_ALL_ITEMS | Ci.calICalendar.ITEM_FILTER_OFFLINE_CREATED; result = await pcal.getItems(filter, 0, null, null); equal(result.length, 0); // Mark the item as offline added await pcal.addOfflineItem(event1); // Now there should be an offline item result = await pcal.getItems(filter, 0, null, null); @@ -458,45 +456,45 @@ async function testOfflineStorage(storag let event2 = event1.clone(); event2.title = "event2"; event2 = await pcal.modifyItem(event2, event1); await pcal.modifyOfflineItem(event2); // The flag should still be offline added, as it was already marked as such - filter = cIC.ITEM_FILTER_ALL_ITEMS | cIC.ITEM_FILTER_OFFLINE_CREATED; + filter = Ci.calICalendar.ITEM_FILTER_ALL_ITEMS | Ci.calICalendar.ITEM_FILTER_OFFLINE_CREATED; result = await pcal.getItems(filter, 0, null, null); equal(result.length, 1); // Reset the flag await pcal.resetItemOfflineFlag(event2); // No more offline items after resetting the flag - filter = cIC.ITEM_FILTER_ALL_ITEMS | cIC.ITEM_FILTER_OFFLINE_CREATED; + filter = Ci.calICalendar.ITEM_FILTER_ALL_ITEMS | Ci.calICalendar.ITEM_FILTER_OFFLINE_CREATED; result = await pcal.getItems(filter, 0, null, null); equal(result.length, 0); // Setting modify flag without one set should actually set that flag await pcal.modifyOfflineItem(event2); - filter = cIC.ITEM_FILTER_ALL_ITEMS | cIC.ITEM_FILTER_OFFLINE_CREATED; + filter = Ci.calICalendar.ITEM_FILTER_ALL_ITEMS | Ci.calICalendar.ITEM_FILTER_OFFLINE_CREATED; result = await pcal.getItems(filter, 0, null, null); equal(result.length, 0); - filter = cIC.ITEM_FILTER_ALL_ITEMS | cIC.ITEM_FILTER_OFFLINE_MODIFIED; + filter = Ci.calICalendar.ITEM_FILTER_ALL_ITEMS | Ci.calICalendar.ITEM_FILTER_OFFLINE_MODIFIED; result = await pcal.getItems(filter, 0, null, null); equal(result.length, 1); // Setting the delete flag should modify the flag accordingly await pcal.deleteOfflineItem(event2); - filter = cIC.ITEM_FILTER_ALL_ITEMS | cIC.ITEM_FILTER_OFFLINE_MODIFIED; + filter = Ci.calICalendar.ITEM_FILTER_ALL_ITEMS | Ci.calICalendar.ITEM_FILTER_OFFLINE_MODIFIED; result = await pcal.getItems(filter, 0, null, null); equal(result.length, 0); - filter = cIC.ITEM_FILTER_ALL_ITEMS | cIC.ITEM_FILTER_OFFLINE_DELETED; + filter = Ci.calICalendar.ITEM_FILTER_ALL_ITEMS | Ci.calICalendar.ITEM_FILTER_OFFLINE_DELETED; result = await pcal.getItems(filter, 0, null, null); equal(result.length, 1); // Setting the delete flag on an offline added item should remove it await pcal.resetItemOfflineFlag(event2); await pcal.addOfflineItem(event2); await pcal.deleteOfflineItem(event2); result = await pcal.getAllItems(); diff --git a/calendar/test/unit/test_recur.js b/calendar/test/unit/test_recur.js --- a/calendar/test/unit/test_recur.js +++ b/calendar/test/unit/test_recur.js @@ -541,17 +541,17 @@ function test_clone(event) { function test_interface() { let item = makeEvent("DTSTART:20020402T114500Z\n" + "DTEND:20020402T124500Z\n" + "RRULE:FREQ=WEEKLY;COUNT=6;BYDAY=TU,WE\r\n" + "EXDATE:20020403T114500Z\r\n" + "RDATE:20020401T114500Z\r\n"); let rinfo = item.recurrenceInfo; - ok(cal.data.compareObjects(rinfo.item, item, Components.interfaces.calIEvent)); + ok(cal.data.compareObjects(rinfo.item, item, Ci.calIEvent)); // getRecurrenceItems let ritems = rinfo.getRecurrenceItems({}); equal(ritems.length, 3); let checkritems = new Map(ritems.map(ritem => [ritem.icalProperty.propertyName, ritem.icalProperty])); let rparts = new Map(checkritems.get("RRULE").value.split(";").map(value => value.split("=", 2))); equal(rparts.size, 3); @@ -593,40 +593,40 @@ function test_interface() { // appendRecurrenceItems / getRecurrenceItemAt / insertRecurrenceItemAt rinfo.appendRecurrenceItem(ritems[0]); rinfo.appendRecurrenceItem(ritems[1]); rinfo.insertRecurrenceItemAt(ritems[2], 0); ok(cal.data.compareObjects(ritems[2], rinfo.getRecurrenceItemAt(0), - Components.interfaces.calIRecurrenceItem)); + Ci.calIRecurrenceItem)); ok(cal.data.compareObjects(ritems[0], rinfo.getRecurrenceItemAt(1), - Components.interfaces.calIRecurrenceItem)); + Ci.calIRecurrenceItem)); ok(cal.data.compareObjects(ritems[1], rinfo.getRecurrenceItemAt(2), - Components.interfaces.calIRecurrenceItem)); + Ci.calIRecurrenceItem)); // deleteRecurrenceItem rinfo.deleteRecurrenceItem(ritems[0]); ok(!item.icalString.includes("RRULE")); // deleteRecurrenceItemAt rinfo.deleteRecurrenceItemAt(1); itemString = item.icalString; ok(!itemString.includes("EXDATE")); ok(itemString.includes("RDATE")); // insertRecurrenceItemAt with exdate rinfo.insertRecurrenceItemAt(ritems[1], 1); ok(cal.data.compareObjects(ritems[1], rinfo.getRecurrenceItemAt(1), - Components.interfaces.calIRecurrenceItem)); + Ci.calIRecurrenceItem)); rinfo.deleteRecurrenceItem(ritems[1]); // isFinite = true ok(rinfo.isFinite); rinfo.appendRecurrenceItem(ritems[0]); ok(rinfo.isFinite); // isFinite = false diff --git a/calendar/test/unit/test_search_service.js b/calendar/test/unit/test_search_service.js --- a/calendar/test/unit/test_search_service.js +++ b/calendar/test/unit/test_search_service.js @@ -1,17 +1,16 @@ /* 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/. */ ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); -var HINT_EXACT_MATCH = Components.interfaces.calICalendarSearchProvider.HINT_EXACT_MATCH; -var search = Components.classes["@mozilla.org/calendar/calendarsearch-service;1"] - .getService(Components.interfaces.calICalendarSearchService); +var HINT_EXACT_MATCH = Ci.calICalendarSearchProvider.HINT_EXACT_MATCH; +var search = Cc["@mozilla.org/calendar/calendarsearch-service;1"].getService(Ci.calICalendarSearchService); function run_test() { test_found(); test_failure(); test_cancel(); } function test_found() { @@ -89,33 +88,33 @@ function test_failure() { search.searchForCalendars("str", HINT_EXACT_MATCH, 0, listener); ok(listener.called); } function test_cancel() { search.getProviders({}).forEach(search.removeProvider, search); let provider = { - QueryInterface: XPCOMUtils.generateQI([Components.interfaces.calICalendarSearchProvider, Components.interfaces.calIOperation]), + QueryInterface: XPCOMUtils.generateQI([Ci.calICalendarSearchProvider, Ci.calIOperation]), searchForCalendars: function(aStr, aHint, aMax, aListener) { Services.tm.currentThread.dispatch({ run: function() { dump("Cancelling search..."); operation.cancel(); } - }, Components.interfaces.nsIEventTarget.DISPATCH_NORMAL); + }, Ci.nsIEventTarget.DISPATCH_NORMAL); // No listener call, we emulate a long running search // Do return the operation though return this; }, isPending: true, cancelCalled: false, - status: Components.results.NS_OK, + status: Cr.NS_OK, cancel: function() { this.cancelCalled = true; }, }; let listener = { called: false, onResult: function(request, result) { diff --git a/calendar/test/unit/test_startup_service.js b/calendar/test/unit/test_startup_service.js --- a/calendar/test/unit/test_startup_service.js +++ b/calendar/test/unit/test_startup_service.js @@ -1,15 +1,14 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ function run_test() { - let ssvc = Components.classes["@mozilla.org/calendar/startup-service;1"] - .getService(Components.interfaces.nsIObserver); + let ssvc = Cc["@mozilla.org/calendar/startup-service;1"].getService(Ci.nsIObserver); let first = { startup: function(aListener) { second.canStart = true; aListener.onResult(null, Cr.NS_OK); }, shutdown: function(aListener) { ok(this.canStop); diff --git a/calendar/test/unit/test_storage.js b/calendar/test/unit/test_storage.js --- a/calendar/test/unit/test_storage.js +++ b/calendar/test/unit/test_storage.js @@ -69,24 +69,24 @@ function testAttachRoundtrip() { let rel = relations[0]; equal(relations.length, 1); equal(rel.relType, "SIBLING"); equal(rel.relId, "VALUE"); equal(rel.getParameter("FOO"), "BAR"); // Check recurrence item for (let ritem of item.recurrenceInfo.getRecurrenceItems({})) { - if (ritem instanceof Components.interfaces.calIRecurrenceRule) { + if (ritem instanceof Ci.calIRecurrenceRule) { equal(ritem.type, "MONTHLY"); equal(ritem.interval, 2); equal(ritem.count, 5); equal(ritem.isByCount, true); equal(ritem.getComponent("BYDAY", {}).toString(), [2].toString()); equal(ritem.isNegative, false); - } else if (ritem instanceof Components.interfaces.calIRecurrenceDate) { + } else if (ritem instanceof Ci.calIRecurrenceDate) { if (ritem.isNegative) { equal(ritem.date.compare(cal.createDateTime("20120301T010101Z")), 0); } else { equal(ritem.date.compare(cal.createDateTime("20120201T010101Z")), 0); } } else { do_throw("Found unknown recurrence item " + ritem); } diff --git a/calendar/test/unit/test_utils.js b/calendar/test/unit/test_utils.js --- a/calendar/test/unit/test_utils.js +++ b/calendar/test/unit/test_utils.js @@ -115,17 +115,17 @@ function test_OperationGroup() { cancelCalled = true; return true; } let group = new cal.data.OperationGroup(cancelFunc); ok(group.isEmpty); ok(group.id.endsWith("-0")); - equal(group.status, Components.results.NS_OK); + equal(group.status, Cr.NS_OK); equal(group.isPending, true); let completedOp = { isPending: false }; group.add(completedOp); ok(group.isEmpty); equal(group.isPending, true); @@ -147,17 +147,17 @@ function test_OperationGroup() { group.add(pendingOp2); group.remove(pendingOp1); ok(!group.isEmpty); equal(group.isPending, true); group.cancel(); - equal(group.status, Components.interfaces.calIErrors.OPERATION_CANCELLED); + equal(group.status, Ci.calIErrors.OPERATION_CANCELLED); ok(!group.isPending); ok(cancelCalled); ok(pendingOp2.cancelCalled); } function test_sameDay() { let createDate = cal.createDateTime.bind(cal); diff --git a/calendar/test/unit/test_webcal.js b/calendar/test/unit/test_webcal.js --- a/calendar/test/unit/test_webcal.js +++ b/calendar/test/unit/test_webcal.js @@ -28,16 +28,16 @@ function run_test() { function check_webcal_uri(aUri) { let uri = Services.io.newURI(aUri); let channel = Services.io.newChannelFromURI2(uri, null, Services.scriptSecurityManager.getSystemPrincipal(), null, - Components.interfaces.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, - Components.interfaces.nsIContentPolicy.TYPE_OTHER); + Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, + Ci.nsIContentPolicy.TYPE_OTHER); NetUtil.asyncFetch(channel, (data, status, request) => { ok(Components.isSuccessCode(status)); run_next_test(); }); }