summaryrefslogtreecommitdiffstats
path: root/comm/calendar/test/browser/providers/head.js
blob: bf58302131cecbee5c48c9f6e13fb7cd3a1806a5 (plain)
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
/* 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/. */

SimpleTest.requestCompleteLog();

var { cal } = ChromeUtils.import("resource:///modules/calendar/calUtils.jsm");
var { CalendarTestUtils } = ChromeUtils.import(
  "resource://testing-common/calendar/CalendarTestUtils.jsm"
);
var { handleDeleteOccurrencePrompt } = ChromeUtils.import(
  "resource://testing-common/calendar/CalendarUtils.jsm"
);

var { saveAndCloseItemDialog, setData } = ChromeUtils.import(
  "resource://testing-common/calendar/ItemEditingHelpers.jsm"
);

let calendarObserver = {
  QueryInterface: ChromeUtils.generateQI(["calIObserver"]),

  /* calIObserver */

  _batchCount: 0,
  _batchRequired: true,
  onStartBatch(calendar) {
    info(`onStartBatch ${calendar?.id} ${++this._batchCount}`);
    Assert.equal(
      calendar,
      this._expectedCalendar,
      "onStartBatch should occur on the expected calendar"
    );
  },
  onEndBatch(calendar) {
    info(`onEndBatch ${calendar?.id} ${this._batchCount--}`);
    Assert.equal(
      calendar,
      this._expectedCalendar,
      "onEndBatch should occur on the expected calendar"
    );
  },
  onLoad(calendar) {
    info(`onLoad ${calendar.id}`);
    Assert.equal(calendar, this._expectedCalendar, "onLoad should occur on the expected calendar");
    if (this._onLoadPromise) {
      this._onLoadPromise.resolve();
    }
  },
  onAddItem(item) {
    info(`onAddItem ${item.calendar.id} ${item.id}`);
    if (this._batchRequired) {
      Assert.equal(this._batchCount, 1, "onAddItem must occur in a batch");
    }
  },
  onModifyItem(newItem, oldItem) {
    info(`onModifyItem ${newItem.calendar.id} ${newItem.id}`);
    if (this._batchRequired) {
      Assert.equal(this._batchCount, 1, "onModifyItem must occur in a batch");
    }
  },
  onDeleteItem(deletedItem) {
    info(`onDeleteItem ${deletedItem.calendar.id} ${deletedItem.id}`);
  },
  onError(calendar, errNo, message) {},
  onPropertyChanged(calendar, name, value, oldValue) {},
  onPropertyDeleting(calendar, name) {},
};

/**
 * Create and register a calendar.
 *
 * @param {string} type - The calendar provider to use.
 * @param {string} url - URL of the server.
 * @param {boolean} useCache - Should this calendar have offline storage?
 * @returns {calICalendar}
 */
function createCalendar(type, url, useCache) {
  let calendar = cal.manager.createCalendar(type, Services.io.newURI(url));
  calendar.name = type + (useCache ? " with cache" : " without cache");
  calendar.id = cal.getUUID();
  calendar.setProperty("cache.enabled", useCache);
  calendar.setProperty("calendar-main-default", true);

  cal.manager.registerCalendar(calendar);
  calendar = cal.manager.getCalendarById(calendar.id);
  calendarObserver._expectedCalendar = calendar;
  calendar.addObserver(calendarObserver);

  info(`Created calendar ${calendar.id}`);
  return calendar;
}

/**
 * Unregister a calendar.
 *
 * @param {calICalendar} calendar
 */
function removeCalendar(calendar) {
  calendar.removeObserver(calendarObserver);
  cal.manager.removeCalendar(calendar);
}

let alarmService = Cc["@mozilla.org/calendar/alarm-service;1"].getService(Ci.calIAlarmService);

let alarmObserver = {
  QueryInterface: ChromeUtils.generateQI(["calIAlarmServiceObserver"]),

  /* calIAlarmServiceObserver */

  _alarmCount: 0,
  onAlarm(item, alarm) {
    info("onAlarm");
    this._alarmCount++;
  },
  onRemoveAlarmsByItem(item) {},
  onRemoveAlarmsByCalendar(calendar) {},
  onAlarmsLoaded(calendar) {},
};
alarmService.addObserver(alarmObserver);
registerCleanupFunction(async () => {
  alarmService.removeObserver(alarmObserver);
});

/**
 * Tests the creation, firing, dismissal, modification and deletion of an event with an alarm.
 * Also checks that the number of events in the unifinder is correct at each stage.
 *
 * Passing this test requires the active calendar to fire notifications in the correct sequence.
 */
async function runTestAlarms() {
  let today = cal.dtz.now();
  let start = today.clone();
  start.day++;
  start.hour = start.minute = start.second = 0;
  let end = start.clone();
  end.hour++;
  let repeatUntil = start.clone();
  repeatUntil.day += 15;

  await CalendarTestUtils.setCalendarView(window, "multiweek");
  await CalendarTestUtils.goToToday(window);
  Assert.equal(window.unifinderTreeView.rowCount, 0, "unifinder event count");

  alarmObserver._alarmCount = 0;

  let alarmDialogPromise = BrowserTestUtils.promiseAlertDialog(
    undefined,
    "chrome://calendar/content/calendar-alarm-dialog.xhtml",
    {
      async callback(alarmWindow) {
        info("Alarm dialog opened");
        let alarmDocument = alarmWindow.document;

        let list = alarmDocument.getElementById("alarm-richlist");
        let items = list.querySelectorAll(`richlistitem[is="calendar-alarm-widget-richlistitem"]`);
        await TestUtils.waitForCondition(() => items.length);
        Assert.equal(items.length, 1);

        await new Promise(resolve => alarmWindow.setTimeout(resolve, 500));

        let dismissButton = alarmDocument.querySelector("#alarm-dismiss-all-button");
        EventUtils.synthesizeMouseAtCenter(dismissButton, {}, alarmWindow);
      },
    }
  );
  let { dialogWindow, iframeWindow } = await CalendarTestUtils.editNewEvent(window);
  await setData(dialogWindow, iframeWindow, {
    title: "test event",
    startdate: start,
    starttime: start,
    enddate: end,
    endtime: end,
    reminder: "2days",
    repeat: "weekly",
  });

  await saveAndCloseItemDialog(dialogWindow);
  await alarmDialogPromise;
  info("Alarm dialog closed");

  await new Promise(r => setTimeout(r, 2000));
  Assert.equal(window.unifinderTreeView.rowCount, 1, "there should be one event in the unifinder");

  Assert.equal(
    [...Services.wm.getEnumerator("Calendar:AlarmWindow")].length,
    0,
    "alarm dialog did not reappear"
  );
  Assert.equal(alarmObserver._alarmCount, 1, "only one alarm");
  alarmObserver._alarmCount = 0;

  let eventBox = await CalendarTestUtils.multiweekView.waitForItemAt(
    window,
    start.weekday == 0 ? 2 : 1, // Sunday's event is next week.
    start.weekday + 1,
    1
  );
  Assert.ok(!!eventBox.item.parentItem.alarmLastAck);

  ({ dialogWindow, iframeWindow } = await CalendarTestUtils.editItemOccurrences(window, eventBox));
  await setData(dialogWindow, iframeWindow, {
    title: "modified test event",
    repeat: "weekly",
    repeatuntil: repeatUntil,
  });

  await saveAndCloseItemDialog(dialogWindow);

  Assert.equal(window.unifinderTreeView.rowCount, 1, "there should be one event in the unifinder");

  Services.focus.focusedWindow = window;

  await new Promise(resolve => setTimeout(resolve, 2000));
  Assert.equal(
    [...Services.wm.getEnumerator("Calendar:AlarmWindow")].length,
    0,
    "alarm dialog should not reappear"
  );
  Assert.equal(alarmObserver._alarmCount, 0, "there should not be any remaining alarms");
  alarmObserver._alarmCount = 0;

  eventBox = await CalendarTestUtils.multiweekView.waitForItemAt(
    window,
    start.weekday == 0 ? 2 : 1, // Sunday's event is next week.
    start.weekday + 1,
    1
  );
  Assert.ok(!!eventBox.item.parentItem.alarmLastAck);

  EventUtils.synthesizeMouseAtCenter(eventBox, {}, window);
  eventBox.focus();
  window.calendarController.onSelectionChanged({ detail: window.currentView().getSelectedItems() });
  await handleDeleteOccurrencePrompt(window, window.currentView(), true);

  await CalendarTestUtils.multiweekView.waitForNoItemAt(
    window,
    start.weekday == 0 ? 2 : 1, // Sunday's event is next week.
    start.weekday + 1,
    1
  );
  Assert.equal(window.unifinderTreeView.rowCount, 0, "there should be no events in the unifinder");
}

const syncItem1Name = "holy cow, a new item!";
const syncItem2Name = "a changed item";

let syncChangesTest = {
  async setUp() {
    await CalendarTestUtils.openCalendarTab(window);

    if (document.getElementById("today-pane-panel").collapsed) {
      EventUtils.synthesizeMouseAtCenter(
        document.getElementById("calendar-status-todaypane-button"),
        {}
      );
    }

    if (document.getElementById("agenda-panel").collapsed) {
      EventUtils.synthesizeMouseAtCenter(document.getElementById("today-pane-cycler-next"), {});
    }
  },

  get part1Item() {
    let today = cal.dtz.now();
    let start = today.clone();
    start.day += 9 - start.weekday;
    start.hour = 13;
    start.minute = start.second = 0;
    let end = start.clone();
    end.hour++;

    return CalendarTestUtils.dedent`
      BEGIN:VCALENDAR
      BEGIN:VEVENT
      UID:ad0850e5-8020-4599-86a4-86c90af4e2cd
      SUMMARY:${syncItem1Name}
      DTSTART:${start.icalString}
      DTEND:${end.icalString}
      END:VEVENT
      END:VCALENDAR
      `;
  },

  async runPart1() {
    await CalendarTestUtils.setCalendarView(window, "multiweek");
    await CalendarTestUtils.goToToday(window);

    // Sanity check that we have not already synchronized and that there is no
    // existing item.
    Assert.ok(
      !CalendarTestUtils.multiweekView.getItemAt(window, 2, 3, 1),
      "there should be no existing item in the calendar"
    );

    // Synchronize.
    EventUtils.synthesizeMouseAtCenter(document.getElementById("refreshCalendar"), {});

    // Verify that the item we added appears in the calendar view.
    let item = await CalendarTestUtils.multiweekView.waitForItemAt(window, 2, 3, 1);
    Assert.equal(item.item.title, syncItem1Name, "view should include newly-added item");

    // Verify that the today pane updates and shows the item we added.
    await TestUtils.waitForCondition(() => window.TodayPane.agenda.rowCount == 1);
    Assert.equal(
      getTodayPaneItemTitle(0),
      syncItem1Name,
      "today pane should include newly-added item"
    );
    Assert.ok(
      !window.TodayPane.agenda.rows[0].nextElementSibling,
      "there should be no additional items in the today pane"
    );
  },

  get part2Item() {
    let today = cal.dtz.now();
    let start = today.clone();
    start.day += 10 - start.weekday;
    start.hour = 9;
    start.minute = start.second = 0;
    let end = start.clone();
    end.hour++;

    return CalendarTestUtils.dedent`
      BEGIN:VCALENDAR
      BEGIN:VEVENT
      UID:ad0850e5-8020-4599-86a4-86c90af4e2cd
      SUMMARY:${syncItem2Name}
      DTSTART:${start.icalString}
      DTEND:${end.icalString}
      END:VEVENT
      END:VCALENDAR
      `;
  },

  async runPart2() {
    // Sanity check that we have not already synchronized and that there is no
    // existing item.
    Assert.ok(
      !CalendarTestUtils.multiweekView.getItemAt(window, 2, 4, 1),
      "there should be no existing item on the specified day"
    );

    // Synchronize.
    EventUtils.synthesizeMouseAtCenter(document.getElementById("refreshCalendar"), {});

    // Verify that the item has updated in the calendar view.
    await CalendarTestUtils.multiweekView.waitForNoItemAt(window, 2, 3, 1);
    let item = await CalendarTestUtils.multiweekView.waitForItemAt(window, 2, 4, 1);
    Assert.equal(item.item.title, syncItem2Name, "view should show updated item");

    // Verify that the today pane updates and shows the updated item.
    await TestUtils.waitForCondition(
      () => window.TodayPane.agenda.rowCount == 1 && getTodayPaneItemTitle(0) != syncItem1Name
    );
    Assert.equal(getTodayPaneItemTitle(0), syncItem2Name, "today pane should show updated item");
    Assert.ok(
      !window.TodayPane.agenda.rows[0].nextElementSibling,
      "there should be no additional items in the today pane"
    );
  },

  async runPart3() {
    // Synchronize via the calendar context menu.
    await calendarListContextMenu(
      document.querySelector("#calendar-list > li:nth-child(2)"),
      "list-calendar-context-reload"
    );

    // Verify that the item is removed from the calendar view.
    await CalendarTestUtils.multiweekView.waitForNoItemAt(window, 2, 3, 1);
    await CalendarTestUtils.multiweekView.waitForNoItemAt(window, 2, 4, 1);

    // Verify that the item is removed from the today pane.
    await TestUtils.waitForCondition(() => window.TodayPane.agenda.rowCount == 0);
  },
};

function getTodayPaneItemTitle(idx) {
  const row = window.TodayPane.agenda.rows[idx];
  return row.querySelector(".agenda-listitem-title").textContent;
}

async function calendarListContextMenu(target, menuItem) {
  await new Promise(r => setTimeout(r));
  window.focus();
  await TestUtils.waitForCondition(
    () => Services.focus.focusedWindow == window,
    "waiting for window to be focused"
  );

  let contextMenu = document.getElementById("list-calendars-context-menu");
  let shownPromise = BrowserTestUtils.waitForEvent(contextMenu, "popupshown");
  EventUtils.synthesizeMouseAtCenter(target, { type: "contextmenu" });
  await shownPromise;

  if (menuItem) {
    let hiddenPromise = BrowserTestUtils.waitForEvent(contextMenu, "popuphidden");
    contextMenu.activateItem(document.getElementById(menuItem));
    await hiddenPromise;
  }
}