/usr/lib/thunderbird-addons/extensions/{e2fda1a4-762b-4020-b5ad-a41df1933103}/calendar-js/calAlarmService.js is in xul-ext-lightning 1:24.4.0+build1-0ubuntu1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 | /* 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/. */
Components.utils.import("resource://calendar/modules/calUtils.jsm");
Components.utils.import("resource://calendar/modules/calAlarmUtils.jsm");
Components.utils.import("resource://gre/modules/Services.jsm");
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
const kHoursBetweenUpdates = 6;
const kSleepMonitorInterval = 60000;
const kSleepMonitorTolerance = 1000;
function nowUTC() {
return cal.jsDateToDateTime(new Date()).getInTimezone(cal.UTC());
}
function newTimerWithCallback(aCallback, aDelay, aRepeating) {
let timer = Components.classes["@mozilla.org/timer;1"]
.createInstance(Components.interfaces.nsITimer);
timer.initWithCallback(aCallback,
aDelay,
(aRepeating ? timer.TYPE_REPEATING_PRECISE : timer.TYPE_ONE_SHOT));
return timer;
}
function calAlarmService() {
this.wrappedJSObject = this;
this.mLoadedCalendars = {};
this.mTimerMap = {};
this.mObservers = new calListenerBag(Components.interfaces.calIAlarmServiceObserver);
this.mSleepMonitor = {
service: this,
interval: kSleepMonitorInterval,
timer: null,
expected: null,
checkExpected: function sm_checkExpected() {
let now = Date.now();
if (now - this.expected > kSleepMonitorTolerance) {
cal.LOG("[calAlarmService] Sleep cycle detected, reloading alarms");
this.service.shutdown();
this.service.startup();
} else {
this.expected = now + this.interval;
}
},
start: function sm_start() {
this.stop();
this.expected = Date.now() + this.interval;
this.timer = newTimerWithCallback(this.checkExpected.bind(this),
this.interval, true);
},
stop: function sm_stop() {
if (this.timer) {
this.timer.cancel();
this.timer = null;
}
}
};
this.calendarObserver = {
alarmService: this,
QueryInterface: XPCOMUtils.generateQI([Components.interfaces.calIObserver]),
// calIObserver:
onStartBatch: function() { },
onEndBatch: function() { },
onLoad: function co_onLoad(calendar) {
// ignore any onLoad events until initial getItems() call of startup has finished:
if (calendar && this.alarmService.mLoadedCalendars[calendar.id]) {
// a refreshed calendar signals that it has been reloaded
// (and cannot notify detailed changes), thus reget all alarms of it:
this.alarmService.initAlarms([calendar]);
}
},
onAddItem: function(aItem) {
this.alarmService.addAlarmsForOccurrences(aItem);
},
onModifyItem: function(aNewItem, aOldItem) {
if (!aNewItem.recurrenceId) {
// deleting an occurrence currently calls modifyItem(newParent, *oldOccurrence*)
aOldItem = aOldItem.parentItem;
}
this.onDeleteItem(aOldItem);
this.onAddItem(aNewItem);
},
onDeleteItem: function(aDeletedItem) {
this.alarmService.removeAlarmsForOccurrences(aDeletedItem);
},
onError: function(aCalendar, aErrNo, aMessage) {},
onPropertyChanged: function(aCalendar, aName, aValue, aOldValue) {
switch (aName) {
case "suppressAlarms":
case "disabled":
this.alarmService.initAlarms([aCalendar]);
break;
}
},
onPropertyDeleting: function(aCalendar, aName) {
this.onPropertyChanged(aCalendar, aName);
}
};
this.calendarManagerObserver = {
alarmService: this,
QueryInterface: XPCOMUtils.generateQI([Components.interfaces.calICalendarManagerObserver]),
onCalendarRegistered: function(aCalendar) {
this.alarmService.observeCalendar(aCalendar);
// initial refresh of alarms for new calendar:
this.alarmService.initAlarms([aCalendar]);
},
onCalendarUnregistering: function(aCalendar) {
// XXX todo: we need to think about calendar unregistration;
// there may still be dangling items (-> alarm dialog),
// dismissing those alarms may write data...
this.alarmService.unobserveCalendar(aCalendar);
},
onCalendarDeleting: function(aCalendar) {}
};
}
const calAlarmServiceClassID = Components.ID("{7a9200dd-6a64-4fff-a798-c5802186e2cc}");
const calAlarmServiceInterfaces = [
Components.interfaces.calIAlarmService,
Components.interfaces.nsIObserver
];
calAlarmService.prototype = {
mRangeStart: null,
mRangeEnd: null,
mUpdateTimer: null,
mStarted: false,
mTimerMap: null,
mObservers: null,
mTimezone: null,
classID: calAlarmServiceClassID,
QueryInterface: XPCOMUtils.generateQI(calAlarmServiceInterfaces),
classInfo: XPCOMUtils.generateCI({
classID: calAlarmServiceClassID,
contractID: "@mozilla.org/calendar/alarm-service;1",
classDescription: "Calendar Alarm Service",
interfaces: calAlarmServiceInterfaces,
flags: Components.interfaces.nsIClassInfo.SINGLETON
}),
/**
* nsIObserver
*/
observe: function cAS_observe(aSubject, aTopic, aData) {
// This will also be called on app-startup, but nothing is done yet, to
// prevent unwanted dialogs etc. See bug 325476 and 413296
if (aTopic == "profile-after-change" || aTopic == "wake_notification") {
this.shutdown();
this.startup();
}
if (aTopic == "xpcom-shutdown") {
this.shutdown();
}
},
/**
* calIAlarmService APIs
*/
get timezone() {
// TODO Do we really need this? Do we ever set the timezone to something
// different than the default timezone?
return this.mTimezone || calendarDefaultTimezone();
},
set timezone(aTimezone) {
return (this.mTimezone = aTimezone);
},
snoozeAlarm: function cAS_snoozeAlarm(aItem, aAlarm, aDuration) {
// Right now we only support snoozing all alarms for the given item for
// aDuration.
// Make sure we're working with the parent, otherwise we'll accidentally
// create an exception
let newEvent = aItem.parentItem.clone();
let alarmTime = nowUTC();
// Set the last acknowledged time to now.
newEvent.alarmLastAck = alarmTime;
alarmTime = alarmTime.clone();
alarmTime.addDuration(aDuration);
if (aItem.parentItem != aItem) {
// This is the *really* hard case where we've snoozed a single
// instance of a recurring event. We need to not only know that
// there was a snooze, but also which occurrence was snoozed. Part
// of me just wants to create a local db of snoozes here...
newEvent.setProperty("X-MOZ-SNOOZE-TIME-" + aItem.recurrenceId.nativeTime,
alarmTime.icalString);
} else {
newEvent.setProperty("X-MOZ-SNOOZE-TIME", alarmTime.icalString);
}
// calling modifyItem will cause us to get the right callback
// and update the alarm properly
return newEvent.calendar.modifyItem(newEvent, aItem.parentItem, null);
},
dismissAlarm: function cAS_dismissAlarm(aItem, aAlarm) {
let now = nowUTC();
// We want the parent item, otherwise we're going to accidentally create an
// exception. We've relnoted (for 0.1) the slightly odd behavior this can
// cause if you move an event after dismissing an alarm
let oldParent = aItem.parentItem;
let newParent = oldParent.clone();
newParent.alarmLastAck = now;
// Make sure to clear out any snoozes that were here.
if (aItem.recurrenceId) {
newParent.deleteProperty("X-MOZ-SNOOZE-TIME-" + aItem.recurrenceId.nativeTime);
} else {
newParent.deleteProperty("X-MOZ-SNOOZE-TIME");
}
return newParent.calendar.modifyItem(newParent, oldParent, null);
},
addObserver: function cAS_addObserver(aObserver) {
this.mObservers.add(aObserver);
},
removeObserver: function cAS_removeObserver(aObserver) {
this.mObservers.remove(aObserver);
},
startup: function cAS_startup() {
if (this.mStarted) {
return;
}
Services.obs.addObserver(this, "profile-after-change", false);
Services.obs.addObserver(this, "xpcom-shutdown", false);
Services.obs.addObserver(this, "wake_notification", false);
/* Tell people that we're alive so they can start monitoring alarms.
*/
let notifier = Components.classes["@mozilla.org/embedcomp/appstartup-notifier;1"]
.getService(Components.interfaces.nsIObserver);
notifier.observe(null, "alarm-service-startup", null);
getCalendarManager().addObserver(this.calendarManagerObserver);
for each (let calendar in getCalendarManager().getCalendars({})) {
this.observeCalendar(calendar);
}
/* set up a timer to update alarms every N hours */
let timerCallback = {
alarmService: this,
notify: function timer_notify() {
let now = nowUTC();
let start;
if (!this.alarmService.mRangeEnd) {
// This is our first search for alarms. We're going to look for
// alarms +/- 1 month from now. If someone sets an alarm more than
// a month ahead of an event, or doesn't start Sunbird/Lightning
// for a month, they'll miss some, but that's a slim chance
start = now.clone();
start.month -= 1;
this.alarmService.mRangeStart = start.clone();
} else {
// This is a subsequent search, so we got all the past alarms before
start = this.alarmService.mRangeEnd.clone();
}
let until = now.clone();
until.month += 1;
// We don't set timers for every future alarm, only those within 6 hours
let end = now.clone();
end.hour += kHoursBetweenUpdates;
this.alarmService.mRangeEnd = end.getInTimezone(UTC());
this.alarmService.findAlarms(getCalendarManager().getCalendars({}),
start, until);
}
};
timerCallback.notify();
this.mUpdateTimer = newTimerWithCallback(timerCallback, kHoursBetweenUpdates * 3600000, true);
// The sleep monitor needs to be started on platforms that don't support wake_notification
if (Services.appinfo.OS != "WINNT" && Services.appinfo.OS != "Darwin") {
cal.LOG("[calAlarmService] Starting sleep monitor.");
this.mSleepMonitor.start();
}
this.mStarted = true;
},
shutdown: function cAS_shutdown() {
if (!this.mStarted) {
return;
}
/* tell people that we're no longer running */
let notifier = Components.classes["@mozilla.org/embedcomp/appstartup-notifier;1"]
.getService(Components.interfaces.nsIObserver);
notifier.observe(null, "alarm-service-shutdown", null);
if (this.mUpdateTimer) {
this.mUpdateTimer.cancel();
this.mUpdateTimer = null;
}
let calmgr = cal.getCalendarManager();
calmgr.removeObserver(this.calendarManagerObserver);
// Stop observing all calendars. This will also clear the timers.
for each (let calendar in calmgr.getCalendars({})) {
this.unobserveCalendar(calendar);
}
this.mRangeEnd = null;
Services.obs.removeObserver(this, "profile-after-change");
Services.obs.removeObserver(this, "xpcom-shutdown");
Services.obs.removeObserver(this, "wake_notification");
this.mSleepMonitor.stop();
this.mStarted = false;
},
observeCalendar: function cAS_observeCalendar(calendar) {
calendar.addObserver(this.calendarObserver);
},
unobserveCalendar: function cAS_unobserveCalendar(calendar) {
calendar.removeObserver(this.calendarObserver);
this.disposeCalendarTimers([calendar]);
this.mObservers.notify("onRemoveAlarmsByCalendar", [calendar]);
},
addAlarmsForItem: function cAS_addAlarmsForItem(aItem) {
if (cal.isToDo(aItem) && aItem.isCompleted) {
// If this is a task and it is completed, don't add the alarm.
return;
}
let showMissed = cal.getPrefSafe("calendar.alarms.showmissed", true);
let alarms = aItem.getAlarms({});
for each (let alarm in alarms) {
let alarmDate = cal.alarms.calculateAlarmDate(aItem, alarm);
if (!alarmDate || alarm.action != "DISPLAY") {
// Only take care of DISPLAY alarms with an alarm date.
continue;
}
// Handle all day events. This is kinda weird, because they don't have
// a well defined startTime. We just consider the start/end to be
// midnight in the user's timezone.
if (alarmDate.isDate) {
alarmDate = alarmDate.getInTimezone(this.timezone);
alarmDate.isDate = false;
}
alarmDate = alarmDate.getInTimezone(UTC());
// Check for snooze
let snoozeDate;
if (aItem.parentItem != aItem) {
snoozeDate = aItem.parentItem.getProperty("X-MOZ-SNOOZE-TIME-" + aItem.recurrenceId.nativeTime)
} else {
snoozeDate = aItem.getProperty("X-MOZ-SNOOZE-TIME");
}
if (snoozeDate && !(snoozeDate instanceof Components.interfaces.calIDateTime)) {
snoozeDate = cal.createDateTime(snoozeDate);
}
// an alarm can only be snoozed to a later time, if earlier it's from another alarm.
if (snoozeDate && snoozeDate.compare(alarmDate) > 0) {
// If the alarm was snoozed, the snooze time is more important.
alarmDate = snoozeDate;
}
let now = nowUTC();
if (alarmDate.timezone.isFloating) {
now = cal.now();
now.timezone = floating();
}
if (alarmDate.compare(now) >= 0) {
// We assume that future alarms haven't been acknowledged
// Delay is in msec, so don't forget to multiply
let timeout = alarmDate.subtractDate(now).inSeconds * 1000;
// No sense in keeping an extra timeout for an alarm thats past
// our range.
let timeUntilRefresh = this.mRangeEnd.subtractDate(now).inSeconds * 1000;
if (timeUntilRefresh < timeout) {
continue;
}
this.addTimer(aItem, alarm, timeout);
} else if (showMissed) {
// This alarm is in the past. See if it has been previously ack'd.
let lastAck = aItem.alarmLastAck || aItem.parentItem.alarmLastAck;
if (lastAck && lastAck.compare(alarmDate) >= 0) {
// The alarm was previously dismissed or snoozed, no further
// action required.
continue;
} else {
// The alarm was not snoozed or dismissed, fire it now.
this.alarmFired(aItem, alarm);
}
}
}
},
removeAlarmsForItem: function cAS_removeAlarmsForItem(aItem) {
// make sure already fired alarms are purged out of the alarm window:
this.mObservers.notify("onRemoveAlarmsByItem", [aItem]);
// Purge alarms specifically for this item (i.e exception)
for each (let alarm in aItem.getAlarms({})) {
this.removeTimer(aItem, alarm);
}
},
getOccurrencesInRange: function cAS_getOccurrencesInRange(aItem) {
// We search 1 month in each direction for alarms. Therefore,
// we need occurrences between initial start date and 1 month from now
let until = nowUTC();
until.month += 1;
if (aItem && aItem.recurrenceInfo) {
return aItem.recurrenceInfo.getOccurrences(this.mRangeStart, until, 0, {});
} else {
return cal.checkIfInRange(aItem, this.mRangeStart, until) ? [aItem] : [];
}
},
addAlarmsForOccurrences: function cAS_addAlarmsForOccurrences(aParentItem) {
let occs = this.getOccurrencesInRange(aParentItem);
// Add an alarm for each occurrence
occs.forEach(this.addAlarmsForItem, this);
},
removeAlarmsForOccurrences: function cAS_removeAlarmsForOccurrences(aParentItem) {
let occs = this.getOccurrencesInRange(aParentItem);
// Remove alarm for each occurrence
occs.forEach(this.removeAlarmsForItem, this);
},
addTimer: function cAS_addTimer(aItem, aAlarm, aTimeout) {
this.mTimerMap[aItem.calendar.id] =
this.mTimerMap[aItem.calendar.id] || {};
this.mTimerMap[aItem.calendar.id][aItem.hashId] =
this.mTimerMap[aItem.calendar.id][aItem.hashId] || {};
let self = this;
let alarmTimerCallback = {
notify: function aTC_notify() {
self.alarmFired(aItem, aAlarm);
}
};
let timer = newTimerWithCallback(alarmTimerCallback, aTimeout, false);
this.mTimerMap[aItem.calendar.id][aItem.hashId][aAlarm.icalString] = timer;
},
removeTimer: function cAS_removeTimers(aItem, aAlarm) {
/* Is the calendar in the timer map */
if (aItem.calendar.id in this.mTimerMap &&
/* ...and is the item in the calendar map */
aItem.hashId in this.mTimerMap[aItem.calendar.id] &&
/* ...and is the alarm in the item map ? */
aAlarm.icalString in this.mTimerMap[aItem.calendar.id][aItem.hashId]) {
let timer = this.mTimerMap[aItem.calendar.id][aItem.hashId][aAlarm.icalString];
timer.cancel();
// Remove the alarm from the item map
delete this.mTimerMap[aItem.calendar.id][aItem.hashId][aAlarm.icalString];
// If the item map is empty, remove it from the calendar map
if (this.mTimerMap[aItem.calendar.id][aItem.hashId].toSource() == "({})") {
delete this.mTimerMap[aItem.calendar.id][aItem.hashId];
}
// If the calendar map is empty, remove it from the timer map
if (this.mTimerMap[aItem.calendar.id].toSource() == "({})") {
delete this.mTimerMap[aItem.calendar.id];
}
}
},
disposeCalendarTimers: function cAS_removeCalendarTimers(aCalendars) {
for each (let calendar in aCalendars) {
if (calendar.id in this.mTimerMap) {
for each (let itemTimerMap in this.mTimerMap[calendar.id]) {
for each (let timer in itemTimerMap) {
timer.cancel();
}
}
delete this.mTimerMap[calendar.id]
}
}
},
findAlarms: function cAS_findAlarms(aCalendars, aStart, aUntil) {
let getListener = {
alarmService: this,
onOperationComplete: function cAS_fA_onOperationComplete(aCalendar,
aStatus,
aOperationType,
aId,
aDetail) {
// calendar has been loaded, so until now, onLoad events can be ignored:
this.alarmService.mLoadedCalendars[aCalendar.id] = true;
// notify observers that the alarms for the calendar have been loaded
this.alarmService.mObservers.notify("onAlarmsLoaded", [aCalendar]);
},
onGetResult: function cAS_fA_onGetResult(aCalendar,
aStatus,
aItemType,
aDetail,
aCount,
aItems) {
for each (let item in aItems) {
// assure we don't fire alarms twice, handle removed alarms as far as we can:
// e.g. we cannot purge removed items from ics files. XXX todo.
this.alarmService.removeAlarmsForItem(item);
this.alarmService.addAlarmsForItem(item);
}
}
};
const calICalendar = Components.interfaces.calICalendar;
let filter = calICalendar.ITEM_FILTER_COMPLETED_ALL |
calICalendar.ITEM_FILTER_CLASS_OCCURRENCES |
calICalendar.ITEM_FILTER_TYPE_ALL;
for each (let calendar in aCalendars) {
// assuming that suppressAlarms does not change anymore until refresh:
if (!calendar.getProperty("suppressAlarms") &&
!calendar.getProperty("disabled")) {
calendar.getItems(filter, 0, aStart, aUntil, getListener);
}
}
},
initAlarms: function cAS_initAlarms(aCalendars) {
// Purge out all alarm timers belonging to the refreshed/loaded calendar:
this.disposeCalendarTimers(aCalendars);
// Purge out all alarms from dialog belonging to the refreshed/loaded calendar:
this.mObservers.notify("onRemoveAlarmsByCalendar", aCalendars);
// Total refresh similar to startup. We're going to look for
// alarms +/- 1 month from now. If someone sets an alarm more than
// a month ahead of an event, or doesn't start Sunbird/Lightning
// for a month, they'll miss some, but that's a slim chance
let start = nowUTC();
let until = start.clone();
start.month -= 1;
until.month += 1;
this.findAlarms(aCalendars, start, until);
},
alarmFired: function cAS_alarmFired(aItem, aAlarm) {
if (!aItem.calendar.getProperty("suppressAlarms") &&
!aItem.calendar.getProperty("disabled") &&
aItem.getProperty("STATUS") != "CANCELLED") {
this.mObservers.notify("onAlarm", [aItem, aAlarm]);
}
}
};
|