/usr/lib/thunderbird-addons/extensions/{e2fda1a4-762b-4020-b5ad-a41df1933103}/calendar-js/calWcapCalendarItems.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 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 | /* 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/calAlarmUtils.jsm");
Components.utils.import("resource://calendar/modules/calIteratorUtils.jsm");
calWcapCalendar.prototype.encodeAttendee =
function calWcapCalendar_encodeAttendee(att) {
if (LOG_LEVEL > 2) {
log("attendee.icalProperty.icalString=" + att.icalProperty.icalString, this);
}
function encodeAttr(val, attr, params) {
if (val && val.length > 0) {
if (params.length > 0) {
params += "^";
}
if (attr) {
params += (attr + "=");
}
params += encodeURIComponent(val);
}
return params;
}
let params = encodeAttr(att.rsvp, "RSVP", "");
params = encodeAttr(att.participationStatus, "PARTSTAT", params);
params = encodeAttr(att.role, "ROLE", params);
var cn = att.commonName;
if (cn) {
params = encodeAttr(cn.replace(/[;:]/g, " "), "CN", params); // remove ';' and ':' from CN
}
return encodeAttr(att.id, null, params);
};
calWcapCalendar.prototype.getRecurrenceParams =
function calWcapCalendar_getRecurrenceParams(item, out_rrules, out_rdates, out_exrules, out_exdates) {
// recurrences:
out_rrules.value = [];
out_rdates.value = [];
out_exrules.value = [];
out_exdates.value = [];
if (item.recurrenceInfo) {
var rItems = item.recurrenceInfo.getRecurrenceItems({});
for each (var rItem in rItems) {
var isNeg = rItem.isNegative;
let rRuleInstance = cal.wrapInstance(rItem, Components.interfaces.calIRecurrenceRule);
let rDateInstance = cal.wrapInstance(rItem, Components.interfaces.calIRecurrenceDate);
if (rRuleInstance) {
var rule = ("\"" + encodeURIComponent(rRuleInstance.icalProperty.valueAsIcalString) + "\"");
if (isNeg) {
out_exrules.value.push(rule);
} else {
out_rrules.value.push(rule);
}
} else if (rDateInstance) {
// cs does not accept DATEs here:
if (isNeg) {
out_exdates.value.push(getIcalUTC(ensureDateTime(rDateInstance.date)));
} else {
out_rdates.value.push(getIcalUTC(ensureDateTime(rDateInstance.date)));
}
} else {
this.notifyError(NS_ERROR_UNEXPECTED,
"don\'t know how to handle this recurrence item: " + rItem.valueAsIcalString);
}
}
}
};
function sameStringSet(list, list_) {
return (list.length == list_.length &&
list.every( function everyFunc(x) {
return list_.some(
function someFunc(y) { return x == y; } );
}));
}
calWcapCalendar.prototype.encodeRecurrenceParams =
function calWcapCalendar_encodeRecurrenceParams(item, oldItem, excludeExdates) {
var rrules = {};
var rdates = {};
var exrules = {};
var exdates = {};
this.getRecurrenceParams(item, rrules, rdates, exrules, exdates);
if (oldItem) {
// actually only write changes if an old item has been changed, because
// cs recreates the whole series if a rule has changed.
// xxx todo: one problem is left when a master only holds EXDATEs,
// and effectively no item is present anymore.
// cs seems not to clean up automatically, but it does when
// when deleting an occurrence {id, rec-id}!
// So this still leaves the question open why deleteOccurrence
// does not directly call deleteItem rather than modifyItem,
// which leads to a much cleaner usage.
// I assume this mimic has been chosen for easier undo/redo
// support (Undo would then have to distinguish whether
// it has previously deleted an occurrence or ordinary item:
// - entering an exception again
// - or adding an item)
// Currently it can just modifyItem(newItem/oldItem) back.
var rrules_ = {};
var rdates_ = {};
var exrules_ = {};
var exdates_ = {};
this.getRecurrenceParams(oldItem, rrules_, rdates_, exrules_, exdates_);
if (sameStringSet(rrules.value, rrules_.value)) {
rrules.value = null; // don't write
}
if (sameStringSet(rdates.value, rdates_.value)) {
rdates.value = null; // don't write
}
if (sameStringSet(exrules.value, exrules.value)) {
exrules.value = null; // don't write
}
if (excludeExdates || sameStringSet(exdates.value, exdates_.value)) {
exdates.value = null; // don't write
}
}
var ret = "";
if (rrules.value) {
ret += ("&rrules=" + rrules.value.join(";"));
}
if (rdates.value) {
ret += ("&rdates=" + rdates.value.join(";"));
}
if (exrules.value) {
ret += ("&exrules=" + exrules.value.join(";"));
}
if (!excludeExdates && exdates.value) {
ret += ("&exdates=" + exdates.value.join(";"));
}
return ret;
// xxx todo:
// rchange=1: expand recurrences,
// or whether to replace the rrule, ambiguous documentation!!!
// check with store(with no uid) upon adoptItem() which behaves strange
// if rchange=0 is set!
};
calWcapCalendar.prototype.getAlarmParams =
function calWcapCalendar_getAlarmParams(item) {
let params = null;
// xxx TODO ALARMSUPPORT check if WCAP supports multiple alarms
let alarms = item.getAlarms({}).filter(function(x) x.action == "EMAIL");
let alarm = alarms.length > 0 && alarms[0];
if (alarm) {
let alarmStart = cal.alarms.calculateAlarmOffset(item, alarm);
if (alarm.related == alarm.ALARM_RELATED_END) {
// cs does not support explicit RELATED=END when
// both start|entry and end|due are written
let dur = item.duration;
if (dur) { // both given
alarmStart = alarmStart.clone();
alarmStart.addDuration(dur);
} // else only end|due is set, alarm makes little sense though
}
let emails = "";
if (item.hasProperty("alarmEmailAddress")) {
emails = encodeURIComponent(item.getProperty("alarmEmailAddress"));
} else {
emails = this.session.getDefaultAlarmEmails({}).map(encodeURIComponent).join(";");
}
if (emails.length > 0) {
params = ("&alarmStart=" + alarmStart.icalString);
params += ("&alarmEmails=" + emails);
}
// else popup
}
if (!params) { // clear popup, email alarm:
params = "&alarmStart=&alarmPopup=&alarmEmails=";
}
return params;
};
// why ever, X-S1CS-EMAIL is unsupported though documented
// for get_calprops... WTF.
function getCalId(att) {
return (att ? att.getProperty("X-S1CS-CALID") : null);
}
function getAttendeeByCalId(atts, calId) {
for each (var att in atts) {
if (getCalId(att) == calId) {
return att;
}
}
return null;
}
calWcapCalendar.prototype.isInvitation =
function calWcapCalendar_isInvitation(item) {
if (!this.session.isLoggedIn) {
return false; // don't know
}
var calId = this.calId;
var orgCalId = getCalId(item.organizer);
if (!orgCalId || (orgCalId == calId)) {
return false;
}
return (this.getInvitedAttendee(item) != null);
};
calWcapCalendar.prototype.getInvitedAttendee =
function calWcapCalendar_getInvitedAttendee(item) {
var att = getAttendeeByCalId(item.getAttendees({}), this.calId);
if (!att) { // try to find mail address
var ar = this.session.getUserPreferences("X-NSCP-WCAP-PREF-mail");
if (ar.length > 0 && ar[0].length > 0) {
att = item.getAttendeeById("mailto:" + ar[0]);
}
}
return att;
};
calWcapCalendar.prototype.canNotify =
function calWcapCalendar_canNotify(method, item) {
if (!this.session.isLoggedIn) {
return false;
}
var calId = this.calId;
switch (method) {
case "REQUEST":
case "CANCEL":
// when creating new items, mind that organizer's id
return (!item.organizer || // might yet not be set
(item.organizer.id == calId) || // or is set to raw calId
(getCalId(item.organizer) == calId));
case "REPLY": // only if we we're invited from cs, and find matching X-S1CS-CALID:
return (getAttendeeByCalId(item.getAttendees({}), calId) != null);
default:
return false;
}
};
function equalDatetimes(one, two) {
return ((!one && !two) ||
(one && two &&
(one.isDate == two.isDate) &&
(one.compare(two) == 0)));
}
function identicalDatetimes(one, two) {
return ((!one && !two) ||
(equalDatetimes(one, two) &&
compareObjects(one.timezone, two.timezone)));
}
// @return null if nothing has changed else value to be written
function diffProperty(newItem, oldItem, propName) {
var val = newItem.getProperty(propName);
var oldVal = (oldItem ? oldItem.getProperty(propName) : null);
if (val === null) {
// force being set when - no old item, eg when adding new item
// - property is to be deleted
if (!oldItem || oldVal) {
val = "";
}
} else {
val = val.replace(/(\r\n)|\n/g, "\r\n");
if (oldVal) {
oldVal = oldVal.replace(/(\r\n)|\n/g, "\r\n");
}
if (val == oldVal) {
val = null;
}
}
return val;
}
const METHOD_PUBLISH = 1;
const METHOD_REQUEST = 2;
const METHOD_REPLY = 4;
const METHOD_CANCEL = 8;
const METHOD_UPDATE = 256;
calWcapCalendar.prototype.storeItem =
function calWcapCalendar_storeItem(bAddItem, item, oldItem, request) {
var this_ = this;
var bIsEvent = isEvent(item);
var bIsParent = isParent(item);
var method = METHOD_PUBLISH;
var bNoSmtpNotify = false;
var params = "";
var calId = this.calId;
if (!bAddItem && this.isInvitation(item)) { // REPLY
method = METHOD_REPLY;
var att = getAttendeeByCalId(item.getAttendees({}), calId);
if (att) {
log("attendee: " + att.icalProperty.icalString, this);
var oldAtt = null;
if (oldItem) {
oldAtt = getAttendeeByCalId(oldItem.getAttendees({}), calId);
}
if (!oldAtt || (att.participationStatus != oldAtt.participationStatus)) {
// REPLY first for just this calendar:
params += ("&attendees=PARTSTAT=" + att.participationStatus +
"^" + encodeURIComponent(att.id));
}
}
} else { // PUBLISH, REQUEST
// workarounds for server bugs concerning recurrences/exceptions:
// - if first occurrence is an exception
// and an EXDATE for that occurrence ought to be written,
// then the master item's data is replaced with that EXDATEd exception. WTF.
// - if start/end date is being written on master, the previously EXDATEd
// exception overwrites master, why ever.
// So in these cases: write all data of master.
var bIsAllDay = false;
if (bIsEvent) {
var dtstart = item.startDate;
var dtend = item.endDate;
bIsAllDay = (dtstart.isDate && dtend.isDate);
if (!oldItem || !identicalDatetimes(dtstart, oldItem.startDate)
|| !identicalDatetimes(dtend, oldItem.endDate)) {
params += ("&dtstart=" + getIcalUTC(dtstart)); // timezone will be set with tzid param
params += ("&dtend=" + getIcalUTC(dtend));
params += (bIsAllDay ? "&isAllDay=1" : "&isAllDay=0");
if (bIsParent && item.recurrenceInfo) {
oldItem = null; // recurrence/exceptions hack: write whole master
}
}
} else { // calITodo
// xxx todo: dtstart is mandatory for cs, so if this is
// undefined, assume an allDay todo???
var dtstart = item.entryDate;
var dtend = item.dueDate;
// cs bug: enforce DUE (set to DTSTART) if alarm is set
if (!dtend && item.getAlarms({}).length) {
dtend = dtstart;
}
bIsAllDay = (dtstart && dtstart.isDate);
if (!oldItem || !identicalDatetimes(dtstart, oldItem.entryDate)
|| !identicalDatetimes(dtend, oldItem.dueDate)) {
params += ("&dtstart=" + getIcalUTC(dtstart)); // timezone will be set with tzid param
params += ("&due=" + getIcalUTC(dtend)); // timezone will be set with tzid param
params += (bIsAllDay ? "&isAllDay=1" : "&isAllDay=0");
if (bIsParent && item.recurrenceInfo) {
oldItem = null; // recurrence/exceptions hack: write whole master
}
}
}
if (bIsParent) {
var recParams = this.encodeRecurrenceParams(item, oldItem, !bAddItem /* exclude EXDATEs */);
if (recParams.length > 0) {
oldItem = null; // recurrence/exceptions hack: write whole master
params += recParams;
}
}
function getOrgId(item) {
return (item && item.organizer && item.organizer.id ? item.organizer.id : null);
}
var orgCalId = getCalId(item.organizer);
if (!orgCalId) { // new events yet don't have X-S1CS-CALID set on ORGANIZER or this is outbound iTIP
var orgId = getOrgId(item);
if (!orgId || (orgId.toLowerCase().replace(/^mailto:/, "") == this.ownerId.toLowerCase())) {
orgCalId = calId; // own event
} // else outbound
}
var attendees = item.getAttendees({});
if (attendees.length > 0) {
// xxx todo: why ever, X-S1CS-EMAIL is unsupported though documented for calprops... WTF.
function encodeAttendees(atts) {
function attendeeSort(one, two) {
one = one.id;
two = two.id;
if (one == two) {
return 0;
}
return (one < two ? -1 : 1);
}
atts = atts.concat([]);
atts.sort(attendeeSort);
return atts.map(this_.encodeAttendee, this_).join(";");
}
var attParam = encodeAttendees(attendees);
if (!oldItem || attParam != encodeAttendees(oldItem.getAttendees({}))) {
params += ("&attendees=" + attParam);
}
if (orgCalId == calId) {
method = METHOD_REQUEST;
} else {
method = METHOD_UPDATE;
bNoSmtpNotify = true;
}
} else if (oldItem && oldItem.getAttendees({}).length > 0) {
// else using just PUBLISH
params += "&attendees="; // clear attendees
}
if (orgCalId) {
if (!oldItem || (orgCalId != getCalId(oldItem.organizer))) {
params += ("&orgCalid=" + encodeURIComponent(orgCalId));
}
} else { // might be a copy of an iTIP invitation:
var orgEmail = getOrgId(item);
if (!oldItem || (getOrgId(oldItem) != orgEmail)) {
params += ("&orgEmail=" + encodeURIComponent(orgEmail));
}
}
var val = item.title;
if (!oldItem || val != oldItem.title) {
params += ("&summary=" + encodeURIComponent(val));
}
let categories = item.getCategories({});
function encodeCategories(cats) {
cats = cats.concat([]);
cats.sort();
return cats.join(";");
}
let catParam = encodeCategories(categories);
if (!oldItem || catParam != encodeCategories(oldItem.getCategories({}))) {
params += ("&categories=" + catParam);
}
val = diffProperty(item, oldItem, "DESCRIPTION");
if (val !== null) {
params += ("&desc=" + encodeURIComponent(val));
}
val = diffProperty(item, oldItem, "LOCATION");
if (val !== null) {
params += ("&location=" + encodeURIComponent(val));
}
val = diffProperty(item, oldItem, "URL");
if (val !== null) {
params += ("&icsUrl=" + encodeURIComponent(val));
}
// xxx todo: default prio is 0 (5 in sjs cs)
val = item.priority;
if (!oldItem || val != oldItem.priority) {
params += ("&priority=" + encodeURIComponent(val));
}
function getPrivacy(item) {
return ((item.privacy && item.privacy != "") ? item.privacy : "PUBLIC");
}
var icsClass = getPrivacy(item);
if (!oldItem || icsClass != getPrivacy(oldItem)) {
params += ("&icsClass=" + icsClass);
}
if (!oldItem || item.status != oldItem.status) {
switch (item.status) {
case "CONFIRMED": params += "&status=0"; break;
case "CANCELLED": params += "&status=1"; break;
case "TENTATIVE": params += "&status=2"; break;
case "NEEDS-ACTION": params += "&status=3"; break;
case "COMPLETED": params += "&status=4"; break;
case "IN-PROCESS": params += "&status=5"; break;
case "DRAFT": params += "&status=6"; break;
case "FINAL": params += "&status=7"; break;
default: // reset to default
params += (bIsEvent ? "&status=0" : "&status=3");
break;
}
}
val = diffProperty(item, oldItem, "TRANSP");
if (val !== null) {
switch (val) {
case "TRANSPARENT":
params += "&transparent=1";
break;
case "OPAQUE":
params += "&transparent=0";
break;
default:
params += ("&transparent=" + (((icsClass == "PRIVATE") || bIsAllDay) ? "1" : "0"));
break;
}
}
if (!bIsEvent) {
if (!oldItem || item.percentComplete != oldItem.percentComplete) {
params += ("&percent=" + item.percentComplete.toString(10));
}
if (!oldItem || !equalDatetimes(item.completedDate, oldItem.completedDate)) {
params += ("&completed=" + getIcalUTC(item.completedDate));
}
}
// attachment urls:
function getAttachments(item) {
var ret = "";
var attachments = item.attachments;
if (attachments) {
var strings = [];
for each (var att in attachements) {
let wrappedAtt = cal.wrapInstance(att, Components.interfaces.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_);
}
}
strings.sort();
ret += strings.join(";");
}
return ret;
}
var val = getAttachments(item);
if (!oldItem || val != getAttachments(oldItem)) {
params += ("&attachments=" + val);
}
} // PUBLISH, REQUEST
var alarmParams = this.getAlarmParams(item);
if (!oldItem || (this.getAlarmParams(oldItem) != alarmParams)) {
if ((method == METHOD_REQUEST) && params.length == 0) {
// assure no email notifications about this change:
bNoSmtpNotify = true;
}
params += alarmParams;
}
if (params.length == 0) {
log("no change at all.", this);
if (LOG_LEVEL > 2) {
log("old item:\n" + oldItem.icalString + "\n\nnew item:\n" + item.icalString, this);
}
request.execRespFunc(null, item);
} else {
// cs does not support separate timezones for start and end, just pick one for tzid param:
var someDate = (item.startDate || item.entryDate || item.dueDate);
if (someDate && !someDate.timezone.isUTC) {
params += ("&tzid=" + encodeURIComponent(this.getAlignedTzid(someDate.timezone)));
}
if (item.id) {
params += ("&uid=" + encodeURIComponent(item.id));
}
// be picky about create/modify, if possible:
// WCAP_STORE_TYPE_CREATE, WCAP_STORE_TYPE_MODIFY
if (bAddItem) {
params += "&storetype=1";
} else if (oldItem) {
params += "&storetype=2";
} // else we don't know exactly, so don't check
if (bIsParent) {
params += "&mod=4"; // THIS AND ALL INSTANCES
} else {
params += ("&mod=1&rid=" + getIcalUTC(ensureDateTime(item.recurrenceId))); // THIS INSTANCE
}
params += ("&method=" + method);
if (bNoSmtpNotify) {
params += "&smtp=0&smtpNotify=0¬ify=0";
}
params += "&replace=1"; // (update) don't append to any lists
params += "&fetch=1&relativealarm=1&compressed=1&recurring=1";
params += "&emailorcalid=1&fmt-out=text%2Fcalendar";
function netRespFunc(err, icalRootComp) {
if (err) {
throw err;
}
var items = this_.parseItems(icalRootComp, calICalendar.ITEM_FILTER_ALL_ITEMS,
0, null, null, true /* bLeaveMutable */);
if (items.length != 1) {
this_.notifyError(NS_ERROR_UNEXPECTED,
"unexpected number of items: " + items.length);
}
var newItem = items[0];
this_.tunnelXProps(newItem, item);
newItem.makeImmutable();
// invalidate cached results:
delete this_.m_cachedResults;
// xxx todo: may log request status
request.execRespFunc(null, newItem);
}
this.issueNetworkRequest(request, netRespFunc, stringToIcal,
bIsEvent ? "storeevents" : "storetodos", params,
calIWcapCalendar.AC_COMP_READ |
calIWcapCalendar.AC_COMP_WRITE);
}
};
calWcapCalendar.prototype.tunnelXProps =
function calWcapCalendar_tunnelXProps(destItem, srcItem) {
// xxx todo: temp workaround for bug in calItemBase.js
if (!isParent(srcItem)) {
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 {
var prop = enumerator.getNext().QueryInterface(Components.interfaces.nsIProperty);
var name = prop.name;
if (name.indexOf("X-MOZ-") == 0) {
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
}
// fallthru intended
default:
if (LOG_LEVEL > 1) {
log("tunneling " + name + "=" + prop.value, this);
}
destItem.setProperty(name, prop.value);
break;
}
}
} catch (exc) {
logError(exc, this);
}
}
};
calWcapCalendar.prototype.adoptItem =
function calWcapCalendar_adoptItem(item, listener) {
var this_ = this;
var request = new calWcapRequest(
function adoptItem_resp(request, err, newItem) {
this_.notifyOperationComplete(listener,
getResultCode(err),
calIOperationListener.ADD,
err ? item.id : newItem.id,
err ? err : newItem);
if (!err && this_ == this_.superCalendar) {
this_.notifyObservers("onAddItem", [newItem]);
}
},
log("adoptItem() call: " + item.title, this));
try {
this.storeItem(true /* bAddItem */, item, null, request);
} catch (exc) {
request.execRespFunc(exc);
}
return request;
}
calWcapCalendar.prototype.addItem =
function calWcapCalendar_addItem(item, listener) {
this.adoptItem(item.clone(), listener);
};
calWcapCalendar.prototype.modifyItem =
function calWcapCalendar_modifyItem(newItem, oldItem, listener) {
var this_ = this;
var request = new calWcapRequest(
function modifyItem_resp(request, err, item) {
this_.notifyOperationComplete(listener,
getResultCode(err),
calIOperationListener.MODIFY,
newItem.id, err ? err : item);
if (!err && this_ == this_.superCalendar) {
this_.notifyObservers("onModifyItem", [item, oldItem]);
}
},
log("modifyItem() call: " + newItem.id, this));
try {
if (!newItem.id) {
throw new Components.Exception("new item has no id!");
}
var oldItem_ = oldItem;
if (isParent(newItem)) {
// Due to a cs bug, EXDATEs cannot be passed with store, thus make a two-step delete then store.
// First check if EXDATEs are passed or have been modified:
var exdates = {};
this.getRecurrenceParams(newItem, {}, {}, {}, exdates);
if (oldItem) {
var exdates_ = {};
this.getRecurrenceParams(oldItem_, {}, {}, {}, exdates_);
// only use added elements
exdates.value = exdates.value.filter(
function(elem) { return !exdates_.value.some(function(elem_) { return elem_ == elem; }); });
} // else in case no oldItem is passed, nevertheless try to delete the EXDATEs
if (exdates.value.length > 0) {
var params = "&uid=";
// all deletes on the same item:
for (var i = exdates.value.length; i--;) {
params += encodeURIComponent(newItem.id);
if (i > 0) {
params += ";";
}
}
params += ("&mod=1&rid=" + exdates.value.join(";"));
var orgCalId = getCalId(newItem.organizer);
if (!orgCalId || (orgCalId != this.calId)) {
// item does not belong to this user, so don't notify:
params += "&smtp=0&smtpNotify=0¬ify=0";
}
params += "&fmt-out=text%2Fxml";
request.lockPending();
this.issueNetworkRequest(request,
function netResp(err, xml) {
try {
// ignore any error and continue storing the item:
if (LOG_LEVEL > 0) {
log("modifyItem EXDATEs: " +
(xml ? getWcapRequestStatusString(xml) : "failed!"), this_);
}
// invalidate cached results:
delete this_.m_cachedResults;
this_.storeItem(false /* bAddItem */, newItem, oldItem_, request);
} finally {
request.unlockPending();
}
},
stringToXml, isEvent(newItem) ? "deleteevents_by_id" : "deletetodos_by_id",
params, calIWcapCalendar.AC_COMP_WRITE);
return request;
}
} else if (oldItem && !oldItem.parentItem.recurrenceInfo.getExceptionFor(newItem.recurrenceId)) {
// pass null for oldItem when creating new exceptions, write whole item:
oldItem_ = null;
}
this.storeItem(false /* bAddItem */, newItem, oldItem_, request);
} catch (exc) {
request.execRespFunc(exc);
}
return request;
};
calWcapCalendar.prototype.deleteItem =
function calWcapCalendar_deleteItem(item, listener) {
var this_ = this;
var request = new calWcapRequest(
function deleteItem_resp(request, err) {
// xxx todo: need to notify about each deleted item if multiple?
this_.notifyOperationComplete(listener,
getResultCode(err),
calIOperationListener.DELETE,
item.id, err ? err : item);
if (!err && this_ == this_.superCalendar) {
this_.notifyObservers("onDeleteItem", [item]);
}
},
log("deleteItem() call: " + item.id, this));
try {
if (!item.id) {
throw new Components.Exception("no item id!");
}
var params = ("&uid=" + encodeURIComponent(item.id));
if (isParent(item)) { // delete THIS AND ALL:
params += "&mod=4&rid=0";
} else { // delete THIS INSTANCE:
// cs does not accept DATE here:
params += ("&mod=1&rid=" + getIcalUTC(ensureDateTime(item.recurrenceId)));
}
var orgCalId = getCalId(item.organizer);
if (!orgCalId || (orgCalId != this.calId)) {
// item does not belong to this user, so don't notify:
params += "&smtp=0&smtpNotify=0¬ify=0";
}
params += "&fmt-out=text%2Fxml";
this.issueNetworkRequest(request,
function netResp(err, xml) {
if (err) {
throw err;
}
// invalidate cached results:
delete this_.m_cachedResults;
if (LOG_LEVEL > 0) {
log("deleteItem(): " + getWcapRequestStatusString(xml), this_);
}
},
stringToXml, isEvent(item) ? "deleteevents_by_id" : "deletetodos_by_id",
params, calIWcapCalendar.AC_COMP_WRITE);
} catch (exc) {
request.execRespFunc(exc);
}
return request;
};
calWcapCalendar.prototype.patchTimezone = function calWcapCalendar_patchTimezone(subComp, attr, xpropOrTz) {
var dt = subComp[attr];
// if TZID parameter present (all-day items), it takes precedence:
if (dt && (dt.timezone.isUTC || dt.timezone.isFloating)) {
if (LOG_LEVEL > 2) {
log(attr + " is " + dt, this);
}
var tz;
if (typeof(xpropOrTz) == "string") {
var tzid = subComp.getFirstProperty(xpropOrTz);
if (tzid) {
tz = this.session.getTimezone(tzid.value);
ASSERT(tz, "timezone not found: " + tzid);
}
} else {
tz = xpropOrTz;
}
if (tz) {
if (LOG_LEVEL > 2) {
log("patching " + xpropOrTz + ": from " +
dt + " to " + dt.getInTimezone(tz), this);
}
dt = dt.getInTimezone(tz);
subComp[attr] = dt;
}
}
return dt;
}
calWcapCalendar.prototype.parseItems = function calWcapCalendar_parseItems(
icalRootComp, itemFilter, maxResults, rangeStart, rangeEnd, bLeaveMutable) {
let items = [];
let unexpandedItems = [];
let uid2parent = {};
let excItems = [];
let fakedParents = {};
let componentType = "ANY";
switch (itemFilter & calICalendar.ITEM_FILTER_TYPE_ALL) {
case calICalendar.ITEM_FILTER_TYPE_TODO:
componentType = "VTODO";
break;
case calICalendar.ITEM_FILTER_TYPE_EVENT:
componentType = "VEVENT";
break;
}
let recurrenceBound = this.session.recurrenceBound;
let count = 0;
for (let subComp in cal.ical.calendarComponentIterator(icalRootComp, componentType)) {
let organizer = subComp.getFirstProperty("ORGANIZER");
if (organizer && organizer.getParameter("SENT-BY")) { // has SENT-BY
// &emailorcalid=1 sets wrong email, workaround setting calid...
let id = organizer.getParameter("X-S1CS-CALID");
if (id) {
organizer.value = id;
}
}
let dtstart = this.patchTimezone(subComp, "startTime", "X-NSCP-DTSTART-TZID");
let item = null;
switch (subComp.componentType) {
case "VEVENT": {
this.patchTimezone(subComp, "endTime", dtstart ? dtstart.timezone : "X-NSCP-DTEND-TZID");
item = createEvent();
item.icalComponent = subComp;
break;
}
case "VTODO": {
this.patchTimezone(subComp, "dueTime", dtstart ? dtstart.timezone : "X-NSCP-DUE-TZID");
item = createTodo();
item.icalComponent = subComp;
switch (itemFilter & calICalendar.ITEM_FILTER_COMPLETED_ALL) {
case calICalendar.ITEM_FILTER_COMPLETED_YES:
if (!item.isCompleted) {
item = null;
}
break;
case calICalendar.ITEM_FILTER_COMPLETED_NO:
if (item.isCompleted) {
item = null;
}
break;
}
break;
}
}
if (item) {
if (!item.title) {
// assumed to look at a subscribed calendar,
// so patch title for private items:
switch (item.privacy) {
case "PRIVATE":
item.title = g_privateItemTitle;
break;
case "CONFIDENTIAL":
item.title = g_confidentialItemTitle;
break;
}
}
item.calendar = this.superCalendar;
let rid = item.recurrenceId;
if (rid) {
rid = rid.getInTimezone(dtstart.timezone);
item.recurrenceId = rid;
if (LOG_LEVEL > 1) {
log("exception item: " + item.title +
"\nrid=" + getIcalUTC(rid) +
"\nitem.id=" + item.id, this);
}
excItems.push(item);
} else if (item.recurrenceInfo) {
unexpandedItems.push(item);
uid2parent[item.id] = item;
} else if ((maxResults == 0 || items.length < maxResults) &&
checkIfInRange(item, rangeStart, rangeEnd)) {
if (LOG_LEVEL > 2) {
log("item: " + item.title + "\n" + item.icalString, this);
}
if (!bLeaveMutable) {
item.makeImmutable();
}
items.push(item);
}
}
}
// tag "exceptions", i.e. items with rid:
for each (let item in excItems) {
let parent = uid2parent[item.id];
if (!parent) { // a parentless one, fake a master and override it's occurrence
parent = isEvent(item) ? createEvent() : createTodo();
parent.id = item.id;
parent.calendar = this.superCalendar;
parent.setProperty("DTSTART", item.recurrenceId);
parent.setProperty("X-MOZ-FAKED-MASTER", "1"); // this tag might be useful in the future
parent.recurrenceInfo = 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);
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:
let rid = item.recurrenceId.getInTimezone(recStartDate.timezone);
rid.isDate = true;
item.recurrenceId = rid;
}
parent.recurrenceInfo.modifyException(item, true);
}
if (itemFilter & calICalendar.ITEM_FILTER_CLASS_OCCURRENCES) {
for each (let item in unexpandedItems) {
if (maxResults != 0 && items.length >= maxResults) {
break;
}
let recStartDate = item.recurrenceStartDate;
if (recStartDate && !recStartDate.isDate) {
recStartDate = null;
}
let recItems = item.recurrenceInfo.getRecurrenceItems({});
for each (let recItem in recItems) {
// cs bug: workaround missing COUNT
let rRuleInstance = cal.wrapInstance(recItem, Components.interfaces.calIRecurrenceRule);
let rDateInstance = cal.wrapInstance(recItem, Components.interfaces.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:
// get into startDate's timezone before cutting:
recItem = rDateInstance;
let date = recItem.date.getInTimezone(recStartDate.timezone);
date.isDate = true;
recItem.date = date;
}
}
if (!bLeaveMutable) {
item.makeImmutable();
}
let occurrences = item.recurrenceInfo.getOccurrences(rangeStart, rangeEnd,
maxResults == 0 ? 0 : maxResults - items.length,
{});
if (LOG_LEVEL > 1) {
log("item: " + item.title + " has " + occurrences.length.toString() + " occurrences.", this);
if (LOG_LEVEL > 2) {
log("master item: " + item.title + "\n" + item.icalString, this);
for each (let occ in occurrences) {
log("item: " + occ.title + "\n" + occ.icalString, this);
}
}
}
// only proxies returned:
items = items.concat(occurrences);
}
} else {
if (maxResults != 0 &&
(items.length + unexpandedItems.length) > maxResults) {
unexpandedItems.length = (maxResults - items.length);
}
if (!bLeaveMutable) {
for each (let item in unexpandedItems) {
item.makeImmutable();
}
}
if (LOG_LEVEL > 2) {
for each (let item in unexpandedItems) {
log("item: " + item.title + "\n" + item.icalString, this);
}
}
items = items.concat(unexpandedItems);
}
if (LOG_LEVEL > 1) {
log("parseItems(): returning " + items.length + " items", this);
}
return items;
};
calWcapCalendar.prototype.getItem =
function calWcapCalendar_getItem(id, listener) {
var this_ = this;
var request = new calWcapRequest(
function getItem_resp(request, err, item) {
if (checkErrorCode(err, calIWcapErrors.WCAP_FETCH_EVENTS_BY_ID_FAILED) ||
checkErrorCode(err, calIWcapErrors.WCAP_COMPONENT_NOT_FOUND)) {
// querying by id is a valid use case, even if no item is returned:
err = NS_OK;
}
this_.notifyOperationComplete(listener,
getResultCode(err),
calIOperationListener.GET,
item ? item.id : null,
err || item);
},
log("getItem() call: id=" + id, this));
try {
if (!id) {
throw new Components.Exception("no item id!");
}
var params = "&relativealarm=1&compressed=1&recurring=1";
params += "&emailorcalid=1&fmt-out=text%2Fcalendar&uid=";
params += encodeURIComponent(id);
function notifyResult(icalRootComp) {
var items = this_.parseItems(icalRootComp, calICalendar.ITEM_FILTER_ALL_ITEMS, 0, null, null);
if (items.length < 1) {
throw new Components.Exception("no such item!");
}
if (items.length > 1) {
this_.notifyError(NS_ERROR_UNEXPECTED,
"unexpected number of items: " + items.length);
}
if (listener) {
listener.onGetResult(this_.superCalendar, NS_OK,
calIItemBase, log("getItem(): success. id=" + id, this_),
items.length, items);
}
request.execRespFunc(null, items[0]);
};
// most common: try events first
this.issueNetworkRequest(
request,
function fetchEventById_resp(err, icalRootComp) {
if (err) {
if (!checkErrorCode(err, calIWcapErrors.WCAP_FETCH_EVENTS_BY_ID_FAILED) &&
!checkErrorCode(err, calIWcapErrors.WCAP_COMPONENT_NOT_FOUND)) {
throw err;
}
// try todos:
this_.issueNetworkRequest(
request,
function fetchTodosById_resp(err, icalRootComp) {
if (err)
throw err;
notifyResult(icalRootComp);
},
stringToIcal, "fetchtodos_by_id", params, calIWcapCalendar.AC_COMP_READ);
} else {
notifyResult(icalRootComp);
}
},
stringToIcal, "fetchevents_by_id", params, calIWcapCalendar.AC_COMP_READ);
} catch (exc) {
request.execRespFunc(exc);
}
return request;
};
function getItemFilterParams(itemFilter) {
var params = "";
switch (itemFilter & calICalendar.ITEM_FILTER_TYPE_ALL) {
case calICalendar.ITEM_FILTER_TYPE_TODO:
params += "&component-type=todo";
break;
case calICalendar.ITEM_FILTER_TYPE_EVENT:
params += "&component-type=event";
break;
}
var compstate = "";
// if (itemFilter & calIWcapCalendar.ITEM_FILTER_REPLY_DECLINED)
// compstate += ";REPLY-DECLINED";
// if (itemFilter & calIWcapCalendar.ITEM_FILTER_REPLY_ACCEPTED)
// compstate += ";REPLY-ACCEPTED";
// if (itemFilter & calIWcapCalendar.ITEM_FILTER_REQUEST_COMPLETED)
// compstate += ";REQUEST-COMPLETED";
if (itemFilter & calICalendar.ITEM_FILTER_REQUEST_NEEDS_ACTION) {
compstate += ";REQUEST-NEEDS-ACTION";
}
// if (itemFilter & calIWcapCalendar.ITEM_FILTER_REQUEST_NEEDSNOACTION) {
// compstate += ";REQUEST-NEEDSNOACTION";
// }
// if (itemFilter & calIWcapCalendar.ITEM_FILTER_REQUEST_PENDING)
// compstate += ";REQUEST-PENDING";
// if (itemFilter & calIWcapCalendar.ITEM_FILTER_REQUEST_WAITFORREPLY)
// compstate += ";REQUEST-WAITFORREPLY";
if (compstate.length > 0) {
params += ("&compstate=" + compstate.substr(1));
}
return params;
}
calWcapCalendar.prototype.getItems =
function calWcapCalendar_getItems(itemFilter, maxResults, rangeStart, rangeEnd, listener) {
rangeStart = ensureDateTime(rangeStart);
rangeEnd = ensureDateTime(rangeEnd);
var zRangeStart = getIcalUTC(rangeStart);
var zRangeEnd = getIcalUTC(rangeEnd);
var this_ = this;
var request = new calWcapRequest(
function getItems_resp(request, err, data) {
log("getItems() complete: " + errorToString(err), this_);
this_.notifyOperationComplete(listener,
getResultCode(err),
calIOperationListener.GET,
null,
err);
},
log("getItems():\n\titemFilter=0x" + itemFilter.toString(0x10) +
",\n\tmaxResults=" + maxResults +
",\n\trangeStart=" + zRangeStart +
",\n\trangeEnd=" + zRangeEnd, this));
if (this.aboutToBeUnregistered) {
// limiting the amount of network traffic while unregistering
log("being unregistered, no results.", this);
request.execRespFunc(null, []);
return request;
}
// m_cachedResults holds the last data revtrieval. This is expecially useful when
// switching on multiple subcriptions: the composite calendar multiplexes getItems()
// calls to all composited calendars over and over again, most often on the same
// date range (as the user usually looks at the same view).
// This will most likely vanish when a better caching is implemented in the views,
// or WCAP local storage caching has sufficient performance.
// The cached results will be invalidated after 2 minutes to reflect incoming invitations.
if (CACHE_LAST_RESULTS > 0 && this.m_cachedResults) {
for each (var entry in this.m_cachedResults) {
if ((itemFilter == entry.itemFilter) &&
equalDatetimes(rangeStart, entry.rangeStart) &&
equalDatetimes(rangeEnd, entry.rangeEnd)) {
log("reusing last getItems() cached data.", this);
if (listener) {
listener.onGetResult(
this.superCalendar, NS_OK, calIItemBase,
"getItems()", entry.results.length, entry.results);
}
request.execRespFunc(null, entry.results);
return request;
}
}
}
try {
var params = ("&relativealarm=1&compressed=1&recurring=1&emailorcalid=1&fmt-out=text%2Fcalendar");
// setting component-type, compstate filters:
params += getItemFilterParams(itemFilter);
if (maxResults > 0) {
params += ("&maxResults=" + maxResults);
}
params += ("&dtstart=" + zRangeStart);
params += ("&dtend=" + zRangeEnd);
this.issueNetworkRequest(
request,
function netResp(err, icalRootComp) {
if (err) {
if (checkErrorCode(err, calIWcapErrors.WCAP_ACCESS_DENIED_TO_CALENDAR)) {
// try free-busy times:
if (listener &&
(itemFilter & calICalendar.ITEM_FILTER_TYPE_EVENT) &&
rangeStart && rangeEnd) {
var freeBusyListener = { // calIGenericOperationListener:
onResult: function freeBusyListener_onResult(request, result) {
if (!Components.isSuccessCode(request.status)) {
throw request.status;
}
var items = [];
for each (var entry in result) {
var item = createEvent();
item.id = (g_busyPhantomItemUuidPrefix + getIcalUTC(entry.interval.start));
item.calendar = this_.superCalendar;
item.title = g_busyItemTitle;
item.startDate = entry.interval.start;
item.endDate = entry.interval.end;
item.makeImmutable();
items.push(item);
}
listener.onGetResult(this_.superCalendar, NS_OK, calIItemBase,
"getItems()/free-busy", items.length, items);
}
};
request.attachSubRequest(
this_.session.getFreeBusyIntervals(
this_.calId, rangeStart, rangeEnd, calIFreeBusyInterval.BUSY_ALL,
freeBusyListener));
}
} else {
throw err;
}
} else if (listener) {
var items = this_.parseItems(
icalRootComp, itemFilter, maxResults,
rangeStart, rangeEnd);
if (CACHE_LAST_RESULTS > 0) {
// auto invalidate after X minutes:
if (!this_.m_cachedResultsTimer) {
var callback = {
notify: function notify(timer) {
if (!this_.m_cachedResults) {
return;
}
var now = (new Date()).getTime();
// sort out old entries:
var entries = [];
for (var i = 0; i < this_.m_cachedResults.length; ++i) {
var entry = this_.m_cachedResults[i];
if ((now - entry.stamp) < (CACHE_LAST_RESULTS_INVALIDATE * 1000)) {
entries.push(entry);
} else {
log("invalidating cached entry:\n\trangeStart=" +
getIcalUTC(entry.rangeStart) + "\n\trangeEnd=" +
getIcalUTC(entry.rangeEnd), this_);
}
}
this_.m_cachedResults = entries;
}
};
// sort out freq:
var 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.initWithCallback(callback, freq * 1000,
Components.interfaces.nsITimer.TYPE_REPEATING_SLACK);
}
if (!this_.m_cachedResults) {
this_.m_cachedResults = [];
}
var entry = {
stamp: (new Date()).getTime(),
itemFilter: itemFilter,
rangeStart: (rangeStart ? rangeStart.clone() : null),
rangeEnd: (rangeEnd ? rangeEnd.clone() : null),
results: items
};
this_.m_cachedResults.unshift(entry);
if (this_.m_cachedResults.length > CACHE_LAST_RESULTS) {
this_.m_cachedResults.length = CACHE_LAST_RESULTS;
}
}
listener.onGetResult(this_.superCalendar, NS_OK, calIItemBase, "getItems()", items.length, items);
}
},
stringToIcal, "fetchcomponents_by_range", params, calIWcapCalendar.AC_COMP_READ);
} catch (exc) {
request.execRespFunc(exc);
}
return request;
};
calWcapCalendar.prototype.offlineStorage = null;
calWcapCalendar.prototype.resetLog =
function calWcapCalendar_resetLog() {
this.deleteProperty("replay.last_stamp");
};
calWcapCalendar.prototype.replayChangesOn =
function calWcapCalendar_replayChangesOn(listener) {
var this_ = this;
var itemFilter = calICalendar.ITEM_FILTER_ALL_ITEMS;
var dtFrom = getDatetimeFromIcalString(this.getProperty("replay.last_stamp"));
var now = getTime(); // new stamp for this sync
var request_ = new calWcapRequest(
function replayChangesOn_resp(request, err) {
if (err) {
logError("error replaying changes: " + errorToString(err));
this_.notifyError(err);
} else {
log("replay succeeded.", this_);
this_.setProperty("replay.last_stamp", getIcalUTC(now));
log("new replay stamp: " + getIcalUTC(now), this_);
}
if (listener) {
listener.onResult(request, null);
}
},
log("replayChangesOn():\n\titemFilter=0x" + itemFilter.toString(0x10) +
"\n\tdtFrom=" + getIcalUTC(dtFrom), this));
try {
var writeListener = {
onGetResult: function() {},
onOperationComplete: function(aCalendar, status, opType, id, detail) {
if (!Components.isSuccessCode(status)) {
request.execRespFunc(status); // any error on writing breaks whole operation
}
}
};
var request = new calWcapRequest(
function netFinishedRespFunc(err, data) {
var modifiedIds = {};
for each (var item in request.m_modifiedItems) {
var dtCreated = item.getProperty("CREATED");
var bAdd = (!dtCreated || !dtFrom || dtCreated.compare(dtFrom) >= 0);
modifiedIds[item.id] = true;
if (bAdd) {
log("replayChangesOn(): new item " + item.id, this_);
if (this_.offlineStorage) {
this_.offlineStorage.addItem(item, writeListener);
}
} else {
log("replayChangesOn(): modified item " + item.id, this_);
if (this_.offlineStorage) {
this_.modifyItem(item, null, writeListener);
}
}
}
for each (var item in request.m_deletedItems) {
// don't delete anything that has been touched by lastmods:
if (modifiedIds[item.id]) {
log("replayChangesOn(): skipping deletion of " + item.id, this_);
} else if (isParent(item)) {
log("replayChangesOn(): deleted item " + item.id, this_);
if (this_.offlineStorage) {
this_.offlineStorage.deleteItem(item, writeListener);
}
} else { // modify parent instead of
// straight-forward deleteItem(). WTF.
var parent = item.parentItem.clone();
parent.recurrenceInfo.removeOccurrenceAt(item.recurrenceId);
log("replayChangesOn(): modified parent "+ parent.id, this_);
if (this_.offlineStorage) {
this_.offlineStorage.modifyItem(parent, item, writeListener);
}
}
}
}, "replayChangesOn() netFinishedRespFunc");
request_.attachSubRequest(request);
// assure being logged in to calc server times:
this.session.getSessionId(
request,
function getSessionId_resp(err, sessionId) {
try {
if (err) {
throw err;
}
var params = ("&relativealarm=1&compressed=1&recurring=1" +
"&emailorcalid=1&fmt-out=text%2Fcalendar");
if (dtFrom) {
dtFrom = this_.session.getServerTime(dtFrom);
}
params += ("&dtstart=" + getIcalUTC(dtFrom));
params += ("&dtend=" + getIcalUTC(this_.session.getServerTime(now)));
log("replayChangesOn(): getting last modifications...", this_);
this_.issueNetworkRequest(
request,
function modifiedNetResp(err, icalRootComp) {
if (err) {
throw err;
}
request.m_modifiedItems = this_.parseItems(icalRootComp,
calICalendar.ITEM_FILTER_ALL_ITEMS,
0, null, null);
},
stringToIcal, "fetchcomponents_by_lastmod",
params + getItemFilterParams(itemFilter),
calIWcapCalendar.AC_COMP_READ);
log("replayChangesOn(): getting deleted items...", this_);
this_.issueNetworkRequest(
request,
function modifiedNetResp(err, icalRootComp) {
if (err) {
throw err;
}
request.m_deletedItems = this_.parseItems(icalRootComp,
calICalendar.ITEM_FILTER_ALL_ITEMS,
0, null, null);
},
stringToIcal, "fetch_deletedcomponents",
params + getItemFilterParams(itemFilter & // only component types
calICalendar.ITEM_FILTER_TYPE_ALL),
calIWcapCalendar.AC_COMP_READ);
} catch (exc) {
request.execRespFunc(exc);
}
});
} catch (exc) {
request_.execRespFunc(exc);
}
return request_;
};
|