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 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165
|
##
# Copyright (c) 2010-2017 Apple Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##
from __future__ import print_function
from caldavclientlibrary.protocol.caldav.definitions import caldavxml
from caldavclientlibrary.protocol.caldav.definitions import csxml
from caldavclientlibrary.protocol.calendarserver.invite import AddInvitees, RemoveInvitee, InviteUser
from caldavclientlibrary.protocol.calendarserver.notifications import InviteNotification
from caldavclientlibrary.protocol.url import URL
from caldavclientlibrary.protocol.utils.xmlhelpers import BetterElementTree
from caldavclientlibrary.protocol.webdav.definitions import davxml
from caldavclientlibrary.protocol.webdav.propfindparser import PropFindParser
from push.amppush import subscribeToIDs
from clientsim.framework.httpclient import StringProducer, readBody
from clientsim.framework.subscribe import Periodical
from clientsim.framework.baseclient import (
IncorrectResponseCode, u2str, BaseClient
)
from pycalendar.datetime import DateTime
from pycalendar.duration import Duration
from pycalendar.timezone import Timezone
from twisted.internet.defer import Deferred, inlineCallbacks, returnValue, \
succeed
from twisted.internet.task import LoopingCall
from twisted.python.log import msg
from twisted.python.util import FancyEqMixin
from twisted.web.http import (
OK, MULTI_STATUS, CREATED, NO_CONTENT, PRECONDITION_FAILED,
MOVED_PERMANENTLY, FORBIDDEN, FOUND, NOT_FOUND
)
from twisted.web.http_headers import Headers
from twistedcaldav.ical import Component, Property
from urlparse import urlparse, urlsplit, urljoin
from uuid import uuid4
from xml.etree.ElementTree import ElementTree, Element, SubElement, QName
from StringIO import StringIO
import json
import os
import random
import shutil
from twisted.python.filepath import FilePath
QName.__repr__ = lambda self: '<QName %r>' % (self.text,)
SUPPORTED_REPORT_SET = '{DAV:}supported-report-set'
def loadRequestBody(clientType, label):
return FilePath(__file__).sibling('request-data').child(clientType).child(label + '.request').getContent()
class MissingCalendarHome(Exception):
"""
Raised when the calendar home for a user is 404
"""
class XMPPPush(object, FancyEqMixin):
"""
This represents an XMPP PubSub location where push notifications for
particular calendar home might be received.
"""
compareAttributes = ('server', 'uri', 'pushkey')
def __init__(self, server, uri, pushkey):
self.server = server
self.uri = uri
self.pushkey = pushkey
class Event(object):
def __init__(self, serializeBasePath, url, etag, component=None):
self.serializeBasePath = serializeBasePath
self.url = url
self.etag = etag
self.scheduleTag = None
if component is not None:
self.component = component
self.uid = component.resourceUID() if component is not None else None
def getUID(self):
"""
Return the UID of the calendar resource.
"""
return self.uid
def serializePath(self):
if self.serializeBasePath:
calendar = os.path.join(self.serializeBasePath, self.url.split("/")[-2])
if not os.path.exists(calendar):
os.makedirs(calendar)
return os.path.join(calendar, self.url.split("/")[-1])
else:
return None
def serialize(self):
"""
Create a dict of the data so we can serialize as JSON.
"""
result = {}
for attr in ("url", "etag", "scheduleTag", "uid",):
result[attr] = getattr(self, attr)
return result
@staticmethod
def deserialize(serializeLocation, data):
"""
Convert dict (deserialized from JSON) into an L{Event}.
"""
event = Event(serializeLocation, None, None)
for attr in ("url", "etag", "scheduleTag", "uid",):
setattr(event, attr, u2str(data[attr]))
return event
@property
def component(self):
"""
Data always read from disk - never cached in the object.
"""
path = self.serializePath()
if path and os.path.exists(path):
with open(path) as f:
comp = Component.fromString(f.read())
return comp
else:
return None
@component.setter
def component(self, component):
"""
Data always written to disk - never cached on the object.
"""
path = self.serializePath()
if path:
if component is None:
os.remove(path)
else:
with open(path, "w") as f:
f.write(str(component))
self.uid = component.resourceUID() if component is not None else None
def removed(self):
"""
Resource no longer exists on the server - remove associated data.
"""
path = self.serializePath()
if path and os.path.exists(path):
os.remove(path)
class Calendar(object):
def __init__(
self, resourceType, componentTypes, name, url, changeToken,
shared=False, sharedByMe=False
):
self.resourceType = resourceType
self.componentTypes = componentTypes
self.name = name
self.url = url
self.changeToken = changeToken
self.events = {}
self.shared = shared
self.sharedByMe = sharedByMe
if self.name is None and self.url is not None:
self.name = self.url.rstrip("/").split("/")[-1]
def serialize(self):
"""
Create a dict of the data so we can serialize as JSON.
"""
result = {}
for attr in ("resourceType", "name", "url", "changeToken", "shared", "sharedByMe"):
result[attr] = getattr(self, attr)
result["componentTypes"] = list(sorted(self.componentTypes))
result["events"] = sorted(self.events.keys())
return result
@staticmethod
def deserialize(data, events):
"""
Convert dict (deserialized from JSON) into an L{Calendar}.
"""
calendar = Calendar(None, None, None, None, None)
for attr in ("resourceType", "name", "url", "changeToken", "shared", "sharedByMe"):
setattr(calendar, attr, u2str(data[attr]))
calendar.componentTypes = set(map(u2str, data["componentTypes"]))
for event in data["events"]:
url = urljoin(calendar.url, event)
if url in events:
calendar.events[event] = events[url]
else:
# Ughh - an event is missing - force changeToken to empty to trigger full resync
calendar.changeToken = ""
return calendar
@staticmethod
def addInviteeXML(uid, summary, readwrite=True):
return AddInvitees(None, '/', [uid], readwrite, summary=summary).request_data.text
@staticmethod
def removeInviteeXML(uid):
invitee = InviteUser()
# Usually an InviteUser is populated through .parseFromUser, but we only care about a uid
invitee.user_uid = uid
return RemoveInvitee(None, '/', invitee).request_data.text
class NotificationCollection(object):
def __init__(self, url, changeToken):
self.url = url
self.changeToken = changeToken
self.notifications = {}
self.name = "notification"
def serialize(self):
"""
Create a dict of the data so we can serialize as JSON.
"""
result = {}
for attr in ("url", "changeToken"):
result[attr] = getattr(self, attr)
result["notifications"] = sorted(self.notifications.keys())
return result
@staticmethod
def deserialize(data, notifications):
"""
Convert dict (deserialized from JSON) into an L{Calendar}.
"""
coll = NotificationCollection(None, None)
for attr in ("url", "changeToken"):
if attr in data:
setattr(coll, attr, u2str(data[attr]))
if "notifications" in data:
for notification in data["notifications"]:
url = urljoin(coll.url, notification)
if url in notifications:
coll.notifications[notification] = notifications[url]
else:
# Ughh - a notification is missing - force changeToken to empty to trigger full resync
coll.changeToken = ""
return coll
class BaseAppleClient(BaseClient):
"""
Implementation of common OS X/iOS client behavior.
"""
_events = None # Cache of events keyed by href
_calendars = None # Cache of calendars keyed by href
_notificationCollection = None # Cache of the notification collection
# The default interval, used if none is specified in external
# configuration.
CALENDAR_HOME_POLL_INTERVAL = 15 * 60
# The maximum number of resources to retrieve in a single multiget
MULTIGET_BATCH_SIZE = 200
# Override and turn on if client supports Sync REPORT
_SYNC_REPORT = False
# Override and turn on if client syncs using time-range queries
_SYNC_TIMERANGE = False
# Override and turn off if client does not support attendee lookups
_ATTENDEE_LOOKUPS = True
# Request body data
_LOAD_PATH = None
_STARTUP_WELL_KNOWN = None
_STARTUP_PRINCIPAL_PROPFIND_INITIAL = None
_STARTUP_PRINCIPAL_PROPFIND = None
_STARTUP_PRINCIPALS_REPORT = None
_STARTUP_PRINCIPAL_EXPAND = None
_STARTUP_PROPPATCH_CALENDAR_COLOR = None
_STARTUP_PROPPATCH_CALENDAR_ORDER = None
_STARTUP_PROPPATCH_CALENDAR_TIMEZONE = None
_POLL_CALENDARHOME_PROPFIND = None
_POLL_CALENDAR_PROPFIND = None
_POLL_CALENDAR_PROPFIND_D1 = None
_POLL_CALENDAR_MULTIGET_REPORT = None
_POLL_CALENDAR_MULTIGET_REPORT_HREF = None
_POLL_CALENDAR_SYNC_REPORT = None
_POLL_NOTIFICATION_PROPFIND = None
_POLL_NOTIFICATION_PROPFIND_D1 = None
_NOTIFICATION_SYNC_REPORT = None
_USER_LIST_PRINCIPAL_PROPERTY_SEARCH = None
_POST_AVAILABILITY = None
_CALENDARSERVER_PRINCIPAL_SEARCH_REPORT = None
email = None
def __init__(
self,
reactor,
server,
serializePath,
record,
auth,
title=None,
calendarHomePollInterval=None,
supportPush=True,
supportAmpPush=True,
principalPathTemplate="/principals/users/{}/",
):
super(BaseAppleClient, self).__init__(
reactor, server, serializePath, record, auth, title=title
)
self.principalPathTemplate = principalPathTemplate
if calendarHomePollInterval is None:
calendarHomePollInterval = self.CALENDAR_HOME_POLL_INTERVAL
self.calendarHomePollInterval = calendarHomePollInterval
self.calendarHomeHref = None
self.supportPush = supportPush
self.supportAmpPush = supportAmpPush
ampPushHosts = self.server.get("ampPushHosts")
if ampPushHosts is None:
ampPushHosts = [urlparse(self.server["uri"])[1].split(":")[0]]
self.ampPushHosts = ampPushHosts
self.ampPushPort = self.server.get("ampPushPort", 62311)
self.serializePath = serializePath
self.supportSync = self._SYNC_REPORT
self.supportNotificationSync = self._NOTIFICATION_SYNC_REPORT
self.supportEnhancedAttendeeAutoComplete = self._CALENDARSERVER_PRINCIPAL_SEARCH_REPORT
# Keep track of the calendars on this account, keys are
# Calendar URIs, values are Calendar instances.
self._calendars = {}
# The principalURL found during discovery
self.principalURL = None
# The principal collection found during startup
self.principalCollection = None
# Keep track of the events on this account, keys are event
# URIs (which are unambiguous across different calendars
# because they start with the uri of the calendar they are
# part of), values are Event instances.
self._events = {}
# Keep track of which calendar homes are being polled
self._checking = set()
# Keep track of XMPP parameters for calendar homes we encounter. This
# dictionary has calendar home URLs as keys and XMPPPush instances as
# values.
self.xmpp = {}
self.ampPushKeys = {}
# Keep track of push factories so we can unsubscribe at shutdown
self._pushFactories = []
# Allow events to go out into the world.
self.catalog = {
"eventChanged": Periodical(),
}
# Keep track of previously downloaded attachments
self._attachments = {}
def _setEvent(self, href, event):
"""
Cache the provided event
"""
self._events[href] = event
calendar, basePath = href.rsplit('/', 1)
self._calendars[calendar + '/'].events[basePath] = event
def _removeEvent(self, href):
"""
Remove event from local cache.
"""
self._events[href].removed()
del self._events[href]
calendar, basePath = href.rsplit('/', 1)
del self._calendars[calendar + '/'].events[basePath]
def _parseMultiStatus(self, response, otherTokens=False):
"""
Parse a <multistatus> - might need to return other top-level elements
in the response - e.g. DAV:sync-token
I{PROPFIND} request for the principal URL.
@type response: C{str}
@rtype: C{cls}
"""
parser = PropFindParser()
parser.parseData(response)
if otherTokens:
return (parser.getResults(), parser.getOthers(),)
else:
return parser.getResults()
_CALENDAR_TYPES = set([
caldavxml.calendar,
caldavxml.schedule_inbox,
])
@inlineCallbacks
def _propfind(self, url, body, depth='0', allowedStatus=(MULTI_STATUS,), method_label=None):
"""
Issue a PROPFIND on the chosen URL
"""
hdrs = Headers({'content-type': ['text/xml']})
if depth is not None:
hdrs.addRawHeader('depth', depth)
response = yield self._request(
allowedStatus,
'PROPFIND',
self.server["uri"] + url.encode('utf-8'),
hdrs,
StringProducer(body),
method_label=method_label,
)
body = yield readBody(response)
result = self._parseMultiStatus(body) if response.code == MULTI_STATUS else None
returnValue((response, result,))
@inlineCallbacks
def _proppatch(self, url, body, method_label=None):
"""
Issue a PROPPATCH on the chosen URL
"""
hdrs = Headers({'content-type': ['text/xml']})
response = yield self._request(
(OK, MULTI_STATUS,),
'PROPPATCH',
self.server["uri"] + url.encode('utf-8'),
hdrs,
StringProducer(body),
method_label=method_label,
)
if response.code == MULTI_STATUS:
body = yield readBody(response)
result = self._parseMultiStatus(body)
returnValue(result)
else:
returnValue(None)
@inlineCallbacks
def _report(self, url, body, depth='0', allowedStatus=(MULTI_STATUS,), otherTokens=False, method_label=None):
"""
Issue a REPORT on the chosen URL
"""
hdrs = Headers({'content-type': ['text/xml']})
if depth is not None:
hdrs.addRawHeader('depth', depth)
response = yield self._request(
allowedStatus,
'REPORT',
self.server["uri"] + url.encode('utf-8'),
hdrs,
StringProducer(body),
method_label=method_label,
)
body = yield readBody(response)
result = self._parseMultiStatus(body, otherTokens) if response.code == MULTI_STATUS else None
returnValue(result)
@inlineCallbacks
def _startupPropfindWellKnown(self):
"""
Issue a PROPFIND on the /.well-known/caldav/ URL
"""
location = "/.well-known/caldav/"
response, result = yield self._propfind(
location,
self._STARTUP_WELL_KNOWN,
allowedStatus=(MULTI_STATUS, MOVED_PERMANENTLY, FOUND,),
method_label="PROPFIND{well-known}",
)
# Follow any redirect
if response.code in (MOVED_PERMANENTLY, FOUND,):
location = response.headers.getRawHeaders("location")[0]
location = urlsplit(location)[2]
response, result = yield self._propfind(
location,
self._STARTUP_WELL_KNOWN,
allowedStatus=(MULTI_STATUS),
method_label="PROPFIND{well-known}",
)
returnValue(result[location])
@inlineCallbacks
def _principalPropfindInitial(self, user):
"""
Issue a PROPFIND on the /principals/users/<uid> URL to retrieve
the /principals/__uids__/<guid> principal URL
"""
principalPath = self.principalPathTemplate.format(user)
_ignore_response, result = yield self._propfind(
principalPath,
self._STARTUP_PRINCIPAL_PROPFIND_INITIAL,
method_label="PROPFIND{find-principal}",
)
returnValue(result[principalPath])
@inlineCallbacks
def _principalPropfind(self):
"""
Issue a PROPFIND on the likely principal URL for the given
user and return a L{Principal} instance constructed from the
response.
"""
_ignore_response, result = yield self._propfind(
self.principalURL,
self._STARTUP_PRINCIPAL_PROPFIND,
method_label="PROPFIND{principal}",
)
returnValue(result[self.principalURL])
def _principalSearchPropertySetReport(self, principalCollectionSet):
"""
Issue a principal-search-property-set REPORT against the chosen URL
"""
return self._report(
principalCollectionSet,
self._STARTUP_PRINCIPALS_REPORT,
allowedStatus=(OK,),
method_label="REPORT{pset}",
)
@inlineCallbacks
def _calendarHomePropfind(self, calendarHomeSet):
"""
Do the poll Depth:1 PROPFIND on the calendar home.
"""
if not calendarHomeSet.endswith('/'):
calendarHomeSet = calendarHomeSet + '/'
_ignore_response, result = yield self._propfind(
calendarHomeSet,
self._POLL_CALENDARHOME_PROPFIND,
depth='1',
method_label="PROPFIND{home}",
)
calendars, notificationCollection = self._extractCalendars(
result, calendarHomeSet
)
returnValue((calendars, notificationCollection, result,))
@inlineCallbacks
def _extractPrincipalDetails(self):
# Using the actual principal URL, retrieve principal information
principal = yield self._principalPropfind()
hrefs = principal.getHrefProperties()
# Remember our outbox and ignore notifications
self.outbox = hrefs[caldavxml.schedule_outbox_URL].toString()
self.notificationURL = None
# Remember our own email-like principal address
self.email = None
self.uuid = None
cuaddrs = hrefs[caldavxml.calendar_user_address_set]
if isinstance(cuaddrs, URL):
cuaddrs = (cuaddrs,)
for cuaddr in cuaddrs:
if cuaddr.toString().startswith(u"mailto:"):
self.email = cuaddr.toString()
elif cuaddr.toString().startswith(u"urn:x-uid"):
self.uuid = cuaddr.toString()
elif cuaddr.toString().startswith(u"urn:uuid") and self.uuid is None:
self.uuid = cuaddr.toString()
if self.email is None:
raise ValueError("Cannot operate without a mail-style principal URL")
# Do another kind of thing I guess
self.principalCollection = hrefs[davxml.principal_collection_set].toString()
yield self._principalSearchPropertySetReport(self.principalCollection)
returnValue(principal)
def _extractCalendars(self, results, calendarHome=None):
"""
Parse a calendar home PROPFIND response and create local state
representing the calendars it contains.
If XMPP push is enabled, also look for and record information about
that from the response.
"""
calendars = []
notificationCollection = None
changeTag = davxml.sync_token if self.supportSync else csxml.getctag
for href in results:
if href == calendarHome:
text = results[href].getTextProperties()
try:
pushkey = text[csxml.pushkey]
except KeyError:
pass
else:
if pushkey:
self.ampPushKeys[href] = pushkey
try:
server = text[csxml.xmpp_server]
uri = text[csxml.xmpp_uri]
pushkey = text[csxml.pushkey]
except KeyError:
pass
else:
if server and uri:
self.xmpp[href] = XMPPPush(server, uri, pushkey)
nodes = results[href].getNodeProperties()
isCalendar = False
isNotifications = False
isShared = False
isSharedByMe = False
resourceType = None
for nodeType in nodes[davxml.resourcetype]:
if nodeType.tag in self._CALENDAR_TYPES:
isCalendar = True
resourceType = nodeType.tag
elif nodeType.tag == csxml.notification:
isNotifications = True
elif nodeType.tag.startswith("{http://calendarserver.org/ns/}shared"):
isShared = True
if nodeType.tag == "{http://calendarserver.org/ns/}shared-owner":
isSharedByMe = True
if isCalendar:
textProps = results[href].getTextProperties()
componentTypes = set()
if nodeType.tag == caldavxml.calendar:
if caldavxml.supported_calendar_component_set in nodes:
for comp in nodes[caldavxml.supported_calendar_component_set]:
componentTypes.add(comp.get("name").upper())
calendars.append(Calendar(
resourceType,
componentTypes,
textProps.get(davxml.displayname, None),
href,
textProps.get(changeTag, None),
shared=isShared,
sharedByMe=isSharedByMe
))
elif isNotifications:
textProps = results[href].getTextProperties()
notificationCollection = NotificationCollection(
href,
textProps.get(changeTag, None)
)
return calendars, notificationCollection
def _updateCalendar(self, calendar, newToken, fetchEvents=True):
"""
Update the local cached data for a calendar in an appropriate manner.
"""
if self.supportSync:
return self._updateCalendar_SYNC(calendar, newToken, fetchEvents=fetchEvents)
else:
return self._updateCalendar_PROPFIND(calendar, newToken)
@inlineCallbacks
def _updateCalendar_PROPFIND(self, calendar, newToken):
"""
Sync a collection by doing a full PROPFIND Depth:1 on it and then sync
the results with local cached data.
"""
# Grab old hrefs prior to the PROPFIND so we sync with the old state. We need this because
# the sim can fire a PUT between the PROPFIND and when process the removals.
old_hrefs = set([calendar.url + child for child in calendar.events.keys()])
_ignore_response, result = yield self._propfind(
calendar.url,
self._POLL_CALENDAR_PROPFIND_D1,
depth='1',
method_label="PROPFIND{calendar}"
)
yield self._updateApplyChanges(calendar, result, old_hrefs)
# Now update calendar to the new token
self._calendars[calendar.url].changeToken = newToken
@inlineCallbacks
def _updateCalendar_SYNC(self, calendar, newToken, fetchEvents=True):
"""
Execute a sync REPORT against a calendar and apply changes to the local cache.
The new token from the changed collection is passed in and must be applied to
the existing calendar once sync is done.
"""
# Grab old hrefs prior to the REPORT so we sync with the old state. We need this because
# the sim can fire a PUT between the REPORT and when process the removals.
old_hrefs = set([calendar.url + child for child in calendar.events.keys()])
# Get changes from sync REPORT (including the other nodes at the top-level
# which will have the new sync token.
fullSync = not calendar.changeToken
result = yield self._report(
calendar.url,
self._POLL_CALENDAR_SYNC_REPORT % {'sync-token': calendar.changeToken},
depth='1',
allowedStatus=(MULTI_STATUS, FORBIDDEN,),
otherTokens=True,
method_label="REPORT{sync}" if calendar.changeToken else "REPORT{sync-init}",
)
if result is None:
if not fullSync:
fullSync = True
result = yield self._report(
calendar.url,
self._POLL_CALENDAR_SYNC_REPORT % {'sync-token': ''},
depth='1',
otherTokens=True,
method_label="REPORT{sync}" if calendar.changeToken else "REPORT{sync-init}",
)
else:
raise IncorrectResponseCode((MULTI_STATUS,), None)
result, others = result
if fetchEvents:
changed = []
for responseHref in result:
if responseHref == calendar.url:
continue
try:
etag = result[responseHref].getTextProperties()[davxml.getetag]
except KeyError:
# XXX Ignore things with no etag? Seems to be dropbox.
continue
# Differentiate a remove vs new/update result
if result[responseHref].getStatus() / 100 == 2:
if responseHref not in self._events:
self._setEvent(responseHref, Event(self.serializeLocation(), responseHref, None))
event = self._events[responseHref]
if event.etag != etag:
changed.append(responseHref)
elif result[responseHref].getStatus() == 404:
self._removeEvent(responseHref)
yield self._updateChangedEvents(calendar, changed)
# Handle removals only when doing an initial sync
if fullSync:
# Detect removed items and purge them
remove_hrefs = old_hrefs - set(changed)
for href in remove_hrefs:
self._removeEvent(href)
# Now update calendar to the new token taken from the report
for node in others:
if node.tag == davxml.sync_token:
newToken = node.text
break
self._calendars[calendar.url].changeToken = newToken
@inlineCallbacks
def _updateApplyChanges(self, calendar, multistatus, old_hrefs):
"""
Given a multistatus for an entire collection, sync the reported items
against the cached items.
"""
# Detect changes and new items
all_hrefs = []
changed_hrefs = []
for responseHref in multistatus:
if responseHref == calendar.url:
continue
all_hrefs.append(responseHref)
try:
etag = multistatus[responseHref].getTextProperties()[davxml.getetag]
except KeyError:
# XXX Ignore things with no etag? Seems to be dropbox.
continue
if responseHref not in self._events:
self._setEvent(responseHref, Event(self.serializeLocation(), responseHref, None))
event = self._events[responseHref]
if event.etag != etag:
changed_hrefs.append(responseHref)
# Retrieve changes
yield self._updateChangedEvents(calendar, changed_hrefs)
# Detect removed items and purge them
remove_hrefs = old_hrefs - set(all_hrefs)
for href in remove_hrefs:
self._removeEvent(href)
@inlineCallbacks
def _updateChangedEvents(self, calendar, changed):
"""
Given a set of changed hrefs, batch multiget them all to update the
local cache.
"""
changed.sort()
while changed:
batchedHrefs = changed[:self.MULTIGET_BATCH_SIZE]
changed = changed[self.MULTIGET_BATCH_SIZE:]
multistatus = yield self._eventReport(calendar.url, batchedHrefs)
for responseHref in batchedHrefs:
try:
res = multistatus[responseHref]
except KeyError:
# Resource might have been deleted
continue
if res.getStatus() == 200:
text = res.getTextProperties()
etag = text[davxml.getetag]
try:
scheduleTag = text[caldavxml.schedule_tag]
except KeyError:
scheduleTag = None
body = text[caldavxml.calendar_data]
self.eventChanged(responseHref, etag, scheduleTag, body)
def eventChanged(self, href, etag, scheduleTag, body):
event = self._events[href]
event.etag = etag
if scheduleTag is not None:
event.scheduleTag = scheduleTag
event.component = Component.fromString(body)
self.catalog["eventChanged"].issue(href)
def _eventReport(self, calendar, events):
# Next do a REPORT on events that might have information
# we don't know about.
hrefs = "".join([self._POLL_CALENDAR_MULTIGET_REPORT_HREF % {'href': event} for event in events])
label_suffix = "small"
if len(events) > 5:
label_suffix = "medium"
if len(events) > 20:
label_suffix = "large"
if len(events) > 75:
label_suffix = "huge"
return self._report(
calendar,
self._POLL_CALENDAR_MULTIGET_REPORT % {'hrefs': hrefs},
depth=None,
method_label="REPORT{multiget-%s}" % (label_suffix,),
)
@inlineCallbacks
def _checkCalendarsForEvents(self, calendarHomeSet, firstTime=False, push=False):
"""
The actions a client does when polling for changes, or in response to a
push notification of a change. There are some actions done on the first poll
we should emulate.
"""
result = True
try:
result = yield self._newOperation("push" if push else "poll", self._poll(calendarHomeSet, firstTime))
finally:
if result:
try:
self._checking.remove(calendarHomeSet)
except KeyError:
pass
returnValue(result)
@inlineCallbacks
def _updateNotifications(self, oldToken, newToken):
fullSync = not oldToken
# Get the list of notification xml resources
result = yield self._report(
self._notificationCollection.url,
self._NOTIFICATION_SYNC_REPORT % {'sync-token': oldToken},
depth='1',
allowedStatus=(MULTI_STATUS, FORBIDDEN,),
otherTokens=True,
method_label="REPORT{sync}" if oldToken else "REPORT{sync-init}",
)
if result is None:
if not fullSync:
fullSync = True
result = yield self._report(
self._notificationCollection.url,
self._NOTIFICATION_SYNC_REPORT % {'sync-token': ''},
depth='1',
otherTokens=True,
method_label="REPORT{sync}" if oldToken else "REPORT{sync-init}",
)
else:
raise IncorrectResponseCode((MULTI_STATUS,), None)
result, _ignore_others = result
# Scan for the sharing invites
inviteNotifications = []
toDelete = []
for responseHref in result:
if responseHref == self._notificationCollection.url:
continue
# try:
# etag = result[responseHref].getTextProperties()[davxml.getetag]
# except KeyError:
# # XXX Ignore things with no etag? Seems to be dropbox.
# continue
toDelete.append(responseHref)
if result[responseHref].getStatus() / 100 == 2:
# Get the notification
response = yield self._request(
OK,
'GET',
self.server["uri"] + responseHref.encode('utf-8'),
method_label="GET{notification}",
)
body = yield readBody(response)
node = ElementTree(file=StringIO(body)).getroot()
if node.tag == str(csxml.notification):
nurl = URL(url=responseHref)
for child in node.getchildren():
if child.tag == str(csxml.invite_notification):
if child.find(str(csxml.invite_noresponse)) is not None:
inviteNotifications.append(
InviteNotification().parseFromNotification(
nurl, child
)
)
# Accept the invites
for notification in inviteNotifications:
# Create an invite-reply
"""
<?xml version="1.0" encoding="UTF-8"?>
<C:invite-reply xmlns:C="http://calendarserver.org/ns/">
<A:href xmlns:A="DAV:">urn:x-uid:10000000-0000-0000-0000-000000000002</A:href>
<C:invite-accepted/>
<C:hosturl>
<A:href xmlns:A="DAV:">/calendars/__uids__/10000000-0000-0000-0000-000000000001/A1DDC58B-651E-4B1C-872A-C6588CA09ADB</A:href>
</C:hosturl>
<C:in-reply-to>d2683fa9-7a50-4390-82bb-cbcea5e0fa86</C:in-reply-to>
<C:summary>to share</C:summary>
</C:invite-reply>
"""
reply = Element(csxml.invite_reply)
href = SubElement(reply, davxml.href)
href.text = notification.user_uid
SubElement(reply, csxml.invite_accepted)
hosturl = SubElement(reply, csxml.hosturl)
href = SubElement(hosturl, davxml.href)
href.text = notification.hosturl
inReplyTo = SubElement(reply, csxml.in_reply_to)
inReplyTo.text = notification.uid
summary = SubElement(reply, csxml.summary)
summary.text = notification.summary
xmldoc = BetterElementTree(reply)
os = StringIO()
xmldoc.writeUTF8(os)
# Post to my calendar home
response = yield self.postXML(
self.calendarHomeHref,
os.getvalue(),
"POST{invite-accept}"
)
# Delete all the notification resources
for responseHref in toDelete:
response = yield self._request(
(NO_CONTENT, NOT_FOUND),
'DELETE',
self.server["uri"] + responseHref.encode('utf-8'),
method_label="DELETE{invite}",
)
self._notificationCollection.changeToken = newToken
@inlineCallbacks
def _poll(self, calendarHomeSet, firstTime):
"""
This gets called during a normal poll or in response to a push
"""
if calendarHomeSet in self._checking:
returnValue(False)
self._checking.add(calendarHomeSet)
calendars, notificationCollection, results = yield self._calendarHomePropfind(calendarHomeSet)
# First time operations
if firstTime:
yield self._pollFirstTime1(results[calendarHomeSet], calendars)
# Normal poll
for cal in calendars:
newToken = cal.changeToken
if cal.url not in self._calendars:
# Calendar seen for the first time - reload it
self._calendars[cal.url] = cal
cal.changeToken = ""
# If this is the first time this run and we have no cached copy
# of this calendar, do an update but don't fetch the events.
# We'll only take notice of ongoing activity and not bother
# with existing events.
yield self._updateCalendar(
self._calendars[cal.url], newToken,
fetchEvents=(not firstTime)
)
elif self._calendars[cal.url].changeToken != newToken:
# Calendar changed - reload it
yield self._updateCalendar(self._calendars[cal.url], newToken)
if notificationCollection is not None:
if self.supportNotificationSync:
if self._notificationCollection:
oldToken = self._notificationCollection.changeToken
else:
oldToken = ""
self._notificationCollection = notificationCollection
newToken = notificationCollection.changeToken
yield self._updateNotifications(oldToken, newToken)
else:
# When there is no sync REPORT, clients have to do a full PROPFIND
# on the notification collection because there is no ctag
self._notificationCollection = notificationCollection
yield self._notificationPropfind(self._notificationCollection.url)
yield self._notificationChangesPropfind(self._notificationCollection.url)
# One time delegate expansion
if firstTime:
yield self._pollFirstTime2()
returnValue(True)
@inlineCallbacks
def _pollFirstTime1(self, homeNode, calendars):
# Detect sync report if needed
if self.supportSync:
nodes = homeNode.getNodeProperties()
syncnodes = nodes[davxml.supported_report_set].findall(
str(davxml.supported_report) + "/" +
str(davxml.report) + "/" +
str(davxml.sync_collection)
)
self.supportSync = len(syncnodes) != 0
# Patch calendar properties
for cal in calendars:
if cal.name != "inbox":
yield self._proppatch(
cal.url,
self._STARTUP_PROPPATCH_CALENDAR_COLOR,
method_label="PROPPATCH{calendar}",
)
yield self._proppatch(
cal.url,
self._STARTUP_PROPPATCH_CALENDAR_ORDER,
method_label="PROPPATCH{calendar}",
)
yield self._proppatch(
cal.url,
self._STARTUP_PROPPATCH_CALENDAR_TIMEZONE,
method_label="PROPPATCH{calendar}",
)
def _pollFirstTime2(self):
return self._principalExpand(self.principalURL)
@inlineCallbacks
def _notificationPropfind(self, notificationURL):
_ignore_response, result = yield self._propfind(
notificationURL,
self._POLL_NOTIFICATION_PROPFIND,
method_label="PROPFIND{notification}",
)
returnValue(result)
@inlineCallbacks
def _notificationChangesPropfind(self, notificationURL):
_ignore_response, result = yield self._propfind(
notificationURL,
self._POLL_NOTIFICATION_PROPFIND_D1,
depth='1',
method_label="PROPFIND{notification-items}",
)
returnValue(result)
@inlineCallbacks
def _principalExpand(self, principalURL):
result = yield self._report(
principalURL,
self._STARTUP_PRINCIPAL_EXPAND,
depth=None,
method_label="REPORT{expand}",
)
returnValue(result)
def startup(self):
raise NotImplementedError
def _calendarCheckLoop(self, calendarHome):
"""
Periodically check the calendar home for changes to calendars.
"""
pollCalendarHome = LoopingCall(
self._checkCalendarsForEvents, calendarHome)
return pollCalendarHome.start(self.calendarHomePollInterval, now=False)
@inlineCallbacks
def _newOperation(self, label, deferred):
before = self.reactor.seconds()
msg(
type="operation",
phase="start",
user=self.record.uid,
client_type=self.title,
client_id=self._client_id,
label=label,
)
try:
result = yield deferred
except IncorrectResponseCode:
# Let this through
success = False
result = None
except:
# Anything else is fatal
raise
else:
success = True
after = self.reactor.seconds()
msg(
type="operation",
phase="end",
duration=after - before,
user=self.record.uid,
client_type=self.title,
client_id=self._client_id,
label=label,
success=success,
)
returnValue(result)
def _receivedPush(self, inboundID, dataChangedTimestamp, priority=5):
for href, id in self.ampPushKeys.iteritems():
if inboundID == id:
self._checkCalendarsForEvents(href, push=True)
break
else:
# somehow we are not subscribed to this id
pass
def _monitorAmpPush(self, home, pushKeys):
"""
Start monitoring for AMP-based push notifications
"""
for host in self.ampPushHosts:
subscribeToIDs(
host, self.ampPushPort, pushKeys,
self._receivedPush, self.reactor
)
@inlineCallbacks
def _unsubscribePubSub(self):
for factory in self._pushFactories:
yield factory.unsubscribeAll()
@inlineCallbacks
def run(self):
"""
Emulate a CalDAV client.
"""
@inlineCallbacks
def startup():
principal = yield self.startup()
hrefs = principal.getHrefProperties()
calendarHome = hrefs[caldavxml.calendar_home_set].toString()
if calendarHome is None:
raise MissingCalendarHome
else:
self.calendarHomeHref = calendarHome
yield self._checkCalendarsForEvents(calendarHome, firstTime=True)
returnValue(calendarHome)
calendarHome = yield self._newOperation("startup: %s" % (self.title,), startup())
yield super(BaseAppleClient, self).run()
# Start monitoring PubSub notifications, if possible.
# _checkCalendarsForEvents populates self.xmpp if it finds
# anything.
if self.supportAmpPush and calendarHome in self.ampPushKeys:
pushKeys = self.ampPushKeys.values()
self._monitorAmpPush(calendarHome, pushKeys)
# Run indefinitely.
yield Deferred()
else:
# This completes when the calendar home poll loop completes, which
# currently it never will except due to an unexpected error.
yield self._calendarCheckLoop(calendarHome)
@inlineCallbacks
def stop(self):
"""
Called before connections are closed, giving a chance to clean up
"""
yield super(BaseAppleClient, self).stop()
self.serialize()
yield self._unsubscribePubSub()
def serializeLocation(self):
"""
Return the path to the directory where data for this user is serialized.
"""
if self.serializePath is None or not os.path.isdir(self.serializePath):
return None
key = "%s-%s" % (self.record.uid, self.title.replace(" ", "_"))
path = os.path.join(self.serializePath, key)
if not os.path.exists(path):
os.mkdir(path)
elif not os.path.isdir(path):
return None
return path
def serialize(self):
"""
Write current state to disk.
"""
path = self.serializeLocation()
if path is None:
return
# Create dict for all the data we need to store
data = {
"principalURL": self.principalURL,
"calendars": [calendar.serialize() for calendar in sorted(self._calendars.values(), key=lambda x:x.name)],
"events": [event.serialize() for event in sorted(self._events.values(), key=lambda x:x.url)],
"notificationCollection": self._notificationCollection.serialize() if self._notificationCollection else {},
"attachments": self._attachments
}
# Write JSON data
with open(os.path.join(path, "index.json"), "w") as f:
json.dump(data, f, indent=2)
def deserialize(self):
"""
Read state from disk.
"""
self._calendars = {}
self._events = {}
self._attachments = {}
path = self.serializeLocation()
if path is None:
return
# Parse JSON data for calendars
try:
with open(os.path.join(path, "index.json")) as f:
data = json.load(f)
except IOError:
return
self.principalURL = data["principalURL"]
# Extract all the events first, then do the calendars (which reference the events)
for event in data["events"]:
event = Event.deserialize(self.serializeLocation(), event)
self._events[event.url] = event
for calendar in data["calendars"]:
calendar = Calendar.deserialize(calendar, self._events)
self._calendars[calendar.url] = calendar
if data.get("notificationCollection"):
self._notificationCollection = NotificationCollection.deserialize(data, {})
self._attachments = data.get("attachments", {})
@inlineCallbacks
def reset(self):
path = self.serializeLocation()
if path is not None and os.path.exists(path):
shutil.rmtree(path)
yield self.startup()
yield self._checkCalendarsForEvents(self.calendarHomeHref)
def _makeSelfAttendee(self):
attendee = Property(
name=u'ATTENDEE',
value=self.email,
params={
'CN': self.record.commonName,
'CUTYPE': 'INDIVIDUAL',
'PARTSTAT': 'ACCEPTED',
},
)
return attendee
def _makeSelfOrganizer(self):
organizer = Property(
name=u'ORGANIZER',
value=self.email,
params={
'CN': self.record.commonName,
},
)
return organizer
@inlineCallbacks
def addEventAttendee(self, href, attendee):
event = self._events[href]
component = event.component
# Trigger auto-complete behavior
yield self._attendeeAutoComplete(component, attendee)
# If the event has no attendees, add ourselves as an attendee.
attendees = list(component.mainComponent().properties('ATTENDEE'))
if len(attendees) == 0:
# First add ourselves as a participant and as the
# organizer. In the future for this event we should
# already have those roles.
component.mainComponent().addProperty(self._makeSelfOrganizer())
component.mainComponent().addProperty(self._makeSelfAttendee())
attendees.append(attendee)
component.mainComponent().addProperty(attendee)
label_suffix = "small"
if len(attendees) > 5:
label_suffix = "medium"
if len(attendees) > 20:
label_suffix = "large"
if len(attendees) > 75:
label_suffix = "huge"
# At last, upload the new event definition
response = yield self._request(
(NO_CONTENT, PRECONDITION_FAILED,),
'PUT',
self.server["uri"] + href.encode('utf-8'),
Headers({
'content-type': ['text/calendar'],
'if-match': [event.etag]}),
StringProducer(component.getTextWithTimezones(includeTimezones=True)),
method_label="PUT{organizer-%s}" % (label_suffix,)
)
# Finally, re-retrieve the event to update the etag
yield self._updateEvent(response, href)
@inlineCallbacks
def _attendeeAutoComplete(self, component, attendee):
if self._ATTENDEE_LOOKUPS:
# Temporarily use some non-test names (some which will return
# many results, and others which will return fewer) because the
# test account names are all too similar
# name = attendee.parameterValue('CN').encode("utf-8")
# prefix = name[:4].lower()
prefix = random.choice([
"chris", "cyru", "dre", "eric", "morg",
"well", "wilfr", "witz"
])
email = attendee.value()
if email.startswith("mailto:"):
email = email[7:]
elif attendee.hasParameter('EMAIL'):
email = attendee.parameterValue('EMAIL').encode("utf-8")
if self.supportEnhancedAttendeeAutoComplete:
# New calendar server enhanced query
search = "<C:search-token>{}</C:search-token>".format(prefix)
body = self._CALENDARSERVER_PRINCIPAL_SEARCH_REPORT.format(
context="attendee", searchTokens=search)
yield self._report(
self.principalCollection,
body,
depth=None,
method_label="REPORT{cpsearch}",
)
else:
# First try to discover some names to supply to the
# auto-completion
yield self._report(
self.principalCollection,
self._USER_LIST_PRINCIPAL_PROPERTY_SEARCH % {
'displayname': prefix,
'email': prefix,
'firstname': prefix,
'lastname': prefix,
},
depth=None,
method_label="REPORT{psearch}",
)
# Now learn about the attendee's availability
yield self.requestAvailability(
component.mainComponent().getStartDateUTC(),
component.mainComponent().getEndDateUTC(),
[self.email, u'mailto:' + email],
[component.resourceUID()]
)
@inlineCallbacks
def changeEventAttendee(self, href, oldAttendee, newAttendee):
event = self._events[href]
component = event.component
# Change the event to have the new attendee instead of the old attendee
component.mainComponent().removeProperty(oldAttendee)
component.mainComponent().addProperty(newAttendee)
okCodes = NO_CONTENT
headers = Headers({
'content-type': ['text/calendar'],
})
if event.scheduleTag is not None:
headers.addRawHeader('if-schedule-tag-match', event.scheduleTag)
okCodes = (NO_CONTENT, PRECONDITION_FAILED,)
attendees = list(component.mainComponent().properties('ATTENDEE'))
label_suffix = "small"
if len(attendees) > 5:
label_suffix = "medium"
if len(attendees) > 20:
label_suffix = "large"
if len(attendees) > 75:
label_suffix = "huge"
response = yield self._request(
okCodes,
'PUT',
self.server["uri"] + href.encode('utf-8'),
headers, StringProducer(component.getTextWithTimezones(includeTimezones=True)),
method_label="PUT{attendee-%s}" % (label_suffix,),
)
# Finally, re-retrieve the event to update the etag
yield self._updateEvent(response, href)
@inlineCallbacks
def deleteEvent(self, href):
"""
Issue a DELETE for the given URL and remove local state
associated with that event.
"""
self._removeEvent(href)
response = yield self._request(
(NO_CONTENT, NOT_FOUND),
'DELETE',
self.server["uri"] + href.encode('utf-8'),
method_label="DELETE{event}",
)
returnValue(response)
@inlineCallbacks
def addEvent(self, href, component, invite=False):
headers = Headers({
'content-type': ['text/calendar'],
})
attendees = list(component.mainComponent().properties('ATTENDEE'))
label_suffix = "small"
if len(attendees) > 5:
label_suffix = "medium"
if len(attendees) > 20:
label_suffix = "large"
if len(attendees) > 75:
label_suffix = "huge"
response = yield self._request(
CREATED,
'PUT',
self.server["uri"] + href.encode('utf-8'),
headers,
StringProducer(component.getTextWithTimezones(includeTimezones=True)),
method_label="PUT{organizer-%s}" % (label_suffix,) if invite else "PUT{event}",
)
self._localUpdateEvent(response, href, component)
@inlineCallbacks
def addInvite(self, href, component):
"""
Add an event that is an invite - i.e., has attendees. We will do attendee lookups and freebusy
checks on each attendee to simulate what happens when an organizer creates a new invite.
"""
# Do lookup and free busy of each attendee (not self)
attendees = list(component.mainComponent().properties('ATTENDEE'))
for attendee in attendees:
if attendee.value() in (self.uuid, self.email):
continue
yield self._attendeeAutoComplete(component, attendee)
# Now do a normal PUT
yield self.addEvent(href, component, invite=True)
@inlineCallbacks
def changeEvent(self, href):
event = self._events[href]
component = event.component
# At last, upload the new event definition
response = yield self._request(
(NO_CONTENT, PRECONDITION_FAILED,),
'PUT',
self.server["uri"] + href.encode('utf-8'),
Headers({
'content-type': ['text/calendar'],
'if-match': [event.etag]
}),
StringProducer(component.getTextWithTimezones(includeTimezones=True)),
method_label="PUT{update}"
)
# Finally, re-retrieve the event to update the etag
yield self._updateEvent(response, href)
def _localUpdateEvent(self, response, href, component):
headers = response.headers
etag = headers.getRawHeaders("etag", [None])[0]
scheduleTag = headers.getRawHeaders("schedule-tag", [None])[0]
event = Event(self.serializeLocation(), href, etag, component)
event.scheduleTag = scheduleTag
self._setEvent(href, event)
def updateEvent(self, href):
return self._updateEvent(None, href)
@inlineCallbacks
def _updateEvent(self, ignored, href):
response = yield self._request(
OK,
'GET',
self.server["uri"] + href.encode('utf-8'),
method_label="GET{event}",
)
headers = response.headers
etag = headers.getRawHeaders('etag')[0]
scheduleTag = headers.getRawHeaders('schedule-tag', [None])[0]
body = yield readBody(response)
self.eventChanged(href, etag, scheduleTag, body)
@inlineCallbacks
def requestAvailability(self, start, end, users, mask=set()):
"""
Issue a VFREEBUSY request for I{roughly} the given date range for the
given users. The date range is quantized to one day. Because of this
it is an error for the range to span more than 24 hours.
@param start: A C{datetime} instance giving the beginning of the
desired range.
@param end: A C{datetime} instance giving the end of the desired range.
@param users: An iterable of user UUIDs which will be included in the
request.
@param mask: An iterable of event UIDs which are to be ignored for the
purposes of this availability lookup.
@return: A C{Deferred} which fires with a C{dict}. Keys in the dict
are user UUIDs (those requested) and values are something else.
"""
outbox = self.server["uri"] + self.outbox
if mask:
maskStr = u'\r\n'.join(['X-CALENDARSERVER-MASK-UID:' + uid
for uid in mask]) + u'\r\n'
else:
maskStr = u''
maskStr = maskStr.encode('utf-8')
attendeeStr = '\r\n'.join(['ATTENDEE:' + uuid.encode('utf-8')
for uuid in users]) + '\r\n'
# iCal issues 24 hour wide vfreebusy requests, starting and ending at 4am.
if start.compareDate(end):
msg("Availability request spanning multiple days (%r to %r), "
"dropping the end date." % (start, end))
start.setTimezone(Timezone.UTCTimezone)
start.setHHMMSS(0, 0, 0)
end = start + Duration(hours=24)
start = start.getText()
end = end.getText()
now = DateTime.getNowUTC().getText()
label_suffix = "small"
if len(users) > 5:
label_suffix = "medium"
if len(users) > 20:
label_suffix = "large"
if len(users) > 75:
label_suffix = "huge"
response = yield self._request(
OK, 'POST', outbox,
Headers({
'content-type': ['text/calendar'],
'originator': [self.email],
'recipient': [u', '.join(users).encode('utf-8')]}),
StringProducer(self._POST_AVAILABILITY % {
'attendees': attendeeStr,
'summary': (u'Availability for %s' % (', '.join(users),)).encode('utf-8'),
'organizer': self.email.encode('utf-8'),
'vfreebusy-uid': str(uuid4()).upper(),
'event-mask': maskStr,
'start': start,
'end': end,
'now': now,
}),
method_label="POST{fb-%s}" % (label_suffix,),
)
body = yield readBody(response)
returnValue(body)
@inlineCallbacks
def postAttachment(self, href, content):
url = self.server["uri"] + "{0}?{1}".format(href, "action=attachment-add")
filename = 'file-{}.txt'.format(len(content))
headers = Headers({
'Content-Disposition': ['attachment; filename="{}"'.format(filename)]
})
response = yield self._request(
CREATED,
'POST',
url,
headers=headers,
body=StringProducer(content),
method_label="POST{attach}"
)
body = yield readBody(response)
# We don't want to download an attachment we uploaded, so look for the
# Cal-Managed-Id: and Location: headers and remember those
managedId = response.headers.getRawHeaders("Cal-Managed-Id")[0]
location = response.headers.getRawHeaders("Location")[0]
self._attachments[managedId] = location
yield self.updateEvent(href)
returnValue(body)
@inlineCallbacks
def getAttachment(self, href, managedId):
# If we've already downloaded this managedId, skip it.
if managedId not in self._attachments:
self._attachments[managedId] = href
yield self._newOperation("download", self._get(href, 200))
@inlineCallbacks
def postXML(self, href, content, label):
headers = Headers({
'content-type': ['text/xml']
})
response = yield self._request(
(OK, CREATED, MULTI_STATUS),
'POST',
self.server["uri"] + href,
headers=headers,
body=StringProducer(content),
method_label=label
)
body = yield readBody(response)
returnValue(body)
class OS_X_10_6(BaseAppleClient):
"""
Implementation of the OS X 10.6 iCal network behavior.
Anything OS X 10.6 iCal does on its own, or any particular
network behaviors it takes in response to a user action, belong on
this class.
Usage-profile based behaviors ("the user modifies an event every
3.2 minutes") belong elsewhere.
"""
_client_type = "OS X 10.6"
USER_AGENT = "DAVKit/4.0.3 (732); CalendarStore/4.0.3 (991); iCal/4.0.3 (1388); Mac OS X/10.6.4 (10F569)"
# The default interval, used if none is specified in external
# configuration. This is also the actual value used by Snow
# Leopard iCal.
CALENDAR_HOME_POLL_INTERVAL = 15 * 60
# The maximum number of resources to retrieve in a single multiget
MULTIGET_BATCH_SIZE = 200
# Override and turn on if client supports Sync REPORT
_SYNC_REPORT = False
# Override and turn on if client syncs using time-range queries
_SYNC_TIMERANGE = False
# Override and turn off if client does not support attendee lookups
_ATTENDEE_LOOKUPS = True
# Request body data
_LOAD_PATH = "OS_X_10_6"
_STARTUP_WELL_KNOWN = loadRequestBody(_LOAD_PATH, 'startup_well_known')
_STARTUP_PRINCIPAL_PROPFIND_INITIAL = loadRequestBody(_LOAD_PATH, 'startup_principal_propfind_initial')
_STARTUP_PRINCIPAL_PROPFIND = loadRequestBody(_LOAD_PATH, 'startup_principal_propfind')
_STARTUP_PRINCIPALS_REPORT = loadRequestBody(_LOAD_PATH, 'startup_principals_report')
_STARTUP_PRINCIPAL_EXPAND = loadRequestBody(_LOAD_PATH, 'startup_principal_expand')
_STARTUP_PROPPATCH_CALENDAR_COLOR = loadRequestBody(_LOAD_PATH, 'startup_calendar_color_proppatch')
_STARTUP_PROPPATCH_CALENDAR_ORDER = loadRequestBody(_LOAD_PATH, 'startup_calendar_order_proppatch')
_STARTUP_PROPPATCH_CALENDAR_TIMEZONE = loadRequestBody(_LOAD_PATH, 'startup_calendar_timezone_proppatch')
_POLL_CALENDARHOME_PROPFIND = loadRequestBody(_LOAD_PATH, 'poll_calendarhome_propfind')
_POLL_CALENDAR_PROPFIND = loadRequestBody(_LOAD_PATH, 'poll_calendar_propfind')
_POLL_CALENDAR_PROPFIND_D1 = loadRequestBody(_LOAD_PATH, 'poll_calendar_propfind_d1')
_POLL_CALENDAR_MULTIGET_REPORT = loadRequestBody(_LOAD_PATH, 'poll_calendar_multiget')
_POLL_CALENDAR_MULTIGET_REPORT_HREF = loadRequestBody(_LOAD_PATH, 'poll_calendar_multiget_hrefs')
_POLL_CALENDAR_SYNC_REPORT = None
_POLL_NOTIFICATION_PROPFIND = loadRequestBody(_LOAD_PATH, 'poll_calendar_propfind')
_POLL_NOTIFICATION_PROPFIND_D1 = loadRequestBody(_LOAD_PATH, 'poll_notification_propfind_d1')
_USER_LIST_PRINCIPAL_PROPERTY_SEARCH = loadRequestBody(_LOAD_PATH, 'user_list_principal_property_search')
_POST_AVAILABILITY = loadRequestBody(_LOAD_PATH, 'post_availability')
@inlineCallbacks
def startup(self):
# Try to read data from disk - if it succeeds self.principalURL will be set
self.deserialize()
if self.principalURL is None:
# PROPFIND principal path to retrieve actual principal-URL
response = yield self._principalPropfindInitial(self.record.uid)
hrefs = response.getHrefProperties()
self.principalURL = hrefs[davxml.principal_URL].toString()
# Using the actual principal URL, retrieve principal information
principal = (yield self._extractPrincipalDetails())
returnValue(principal)
class OS_X_10_7(BaseAppleClient):
"""
Implementation of the OS X 10.7 iCal network behavior.
"""
_client_type = "OS X 10.7"
USER_AGENT = "CalendarStore/5.0.2 (1166); iCal/5.0.2 (1571); Mac OS X/10.7.3 (11D50)"
# The default interval, used if none is specified in external
# configuration. This is also the actual value used by Snow
# Leopard iCal.
CALENDAR_HOME_POLL_INTERVAL = 15 * 60
# The maximum number of resources to retrieve in a single multiget
MULTIGET_BATCH_SIZE = 50
# Override and turn on if client supports Sync REPORT
_SYNC_REPORT = True
# Override and turn on if client syncs using time-range queries
_SYNC_TIMERANGE = False
# Override and turn off if client does not support attendee lookups
_ATTENDEE_LOOKUPS = True
# Request body data
_LOAD_PATH = "OS_X_10_7"
_STARTUP_WELL_KNOWN = loadRequestBody(_LOAD_PATH, 'startup_well_known')
_STARTUP_PRINCIPAL_PROPFIND_INITIAL = loadRequestBody(_LOAD_PATH, 'startup_principal_propfind_initial')
_STARTUP_PRINCIPAL_PROPFIND = loadRequestBody(_LOAD_PATH, 'startup_principal_propfind')
_STARTUP_PRINCIPALS_REPORT = loadRequestBody(_LOAD_PATH, 'startup_principals_report')
_STARTUP_PRINCIPAL_EXPAND = loadRequestBody(_LOAD_PATH, 'startup_principal_expand')
_STARTUP_PROPPATCH_CALENDAR_COLOR = loadRequestBody(_LOAD_PATH, 'startup_calendar_color_proppatch')
_STARTUP_PROPPATCH_CALENDAR_ORDER = loadRequestBody(_LOAD_PATH, 'startup_calendar_order_proppatch')
_STARTUP_PROPPATCH_CALENDAR_TIMEZONE = loadRequestBody(_LOAD_PATH, 'startup_calendar_timezone_proppatch')
_POLL_CALENDARHOME_PROPFIND = loadRequestBody(_LOAD_PATH, 'poll_calendarhome_propfind')
_POLL_CALENDAR_PROPFIND = loadRequestBody(_LOAD_PATH, 'poll_calendar_propfind')
_POLL_CALENDAR_PROPFIND_D1 = loadRequestBody(_LOAD_PATH, 'poll_calendar_propfind_d1')
_POLL_CALENDAR_MULTIGET_REPORT = loadRequestBody(_LOAD_PATH, 'poll_calendar_multiget')
_POLL_CALENDAR_MULTIGET_REPORT_HREF = loadRequestBody(_LOAD_PATH, 'poll_calendar_multiget_hrefs')
_POLL_CALENDAR_SYNC_REPORT = loadRequestBody(_LOAD_PATH, 'poll_calendar_sync')
_POLL_NOTIFICATION_PROPFIND = loadRequestBody(_LOAD_PATH, 'poll_calendar_propfind')
_POLL_NOTIFICATION_PROPFIND_D1 = loadRequestBody(_LOAD_PATH, 'poll_notification_propfind_d1')
_USER_LIST_PRINCIPAL_PROPERTY_SEARCH = loadRequestBody(_LOAD_PATH, 'user_list_principal_property_search')
_POST_AVAILABILITY = loadRequestBody(_LOAD_PATH, 'post_availability')
def _addDefaultHeaders(self, headers):
"""
Add the clients default set of headers to ones being used in a request.
Default is to add User-Agent, sub-classes should override to add other
client specific things, Accept etc.
"""
super(OS_X_10_7, self)._addDefaultHeaders(headers)
headers.setRawHeaders('Accept', ['*/*'])
headers.setRawHeaders('Accept-Language', ['en-us'])
headers.setRawHeaders('Accept-Encoding', ['gzip,deflate'])
headers.setRawHeaders('Connection', ['keep-alive'])
@inlineCallbacks
def startup(self):
# Try to read data from disk - if it succeeds self.principalURL will be set
self.deserialize()
if self.principalURL is None:
# PROPFIND well-known with redirect
response = yield self._startupPropfindWellKnown()
hrefs = response.getHrefProperties()
if davxml.current_user_principal in hrefs:
self.principalURL = hrefs[davxml.current_user_principal].toString()
elif davxml.principal_URL in hrefs:
self.principalURL = hrefs[davxml.principal_URL].toString()
else:
# PROPFIND principal path to retrieve actual principal-URL
response = yield self._principalPropfindInitial(self.record.uid)
hrefs = response.getHrefProperties()
self.principalURL = hrefs[davxml.principal_URL].toString()
# Using the actual principal URL, retrieve principal information
principal = yield self._extractPrincipalDetails()
returnValue(principal)
class OS_X_10_11(BaseAppleClient):
"""
Implementation of the OS X 10.11 Calendar.app network behavior.
"""
_client_type = "OS X 10.11"
USER_AGENT = "Mac+OS+X/10.11 (15A283) CalendarAgent/361"
# The default interval, used if none is specified in external
# configuration. This is also the actual value used by El
# Capital Calendar.app.
CALENDAR_HOME_POLL_INTERVAL = 15 * 60 # in seconds
# The maximum number of resources to retrieve in a single multiget
MULTIGET_BATCH_SIZE = 50
# Override and turn on if client supports Sync REPORT
_SYNC_REPORT = True
# Override and turn off if client does not support attendee lookups
_ATTENDEE_LOOKUPS = True
# Request body data
_LOAD_PATH = "OS_X_10_11"
_STARTUP_WELL_KNOWN = loadRequestBody(_LOAD_PATH, 'startup_well_known_propfind')
_STARTUP_PRINCIPAL_PROPFIND_INITIAL = loadRequestBody(_LOAD_PATH, 'startup_principal_initial_propfind')
_STARTUP_PRINCIPAL_PROPFIND = loadRequestBody(_LOAD_PATH, 'startup_principal_propfind')
_STARTUP_PRINCIPALS_REPORT = loadRequestBody(_LOAD_PATH, 'startup_principals_report')
_STARTUP_PRINCIPAL_EXPAND = loadRequestBody(_LOAD_PATH, 'startup_principal_expand')
_STARTUP_CREATE_CALENDAR = loadRequestBody(_LOAD_PATH, 'startup_create_calendar')
_STARTUP_PROPPATCH_CALENDAR_COLOR = loadRequestBody(_LOAD_PATH, 'startup_calendar_color_proppatch')
# _STARTUP_PROPPATCH_CALENDAR_NAME = loadRequestBody(_LOAD_PATH, 'startup_calendar_displayname_proppatch')
_STARTUP_PROPPATCH_CALENDAR_ORDER = loadRequestBody(_LOAD_PATH, 'startup_calendar_order_proppatch')
_STARTUP_PROPPATCH_CALENDAR_TIMEZONE = loadRequestBody(_LOAD_PATH, 'startup_calendar_timezone_proppatch')
_POLL_CALENDARHOME_PROPFIND = loadRequestBody(_LOAD_PATH, 'poll_calendarhome_depth1_propfind')
_POLL_CALENDAR_PROPFIND = loadRequestBody(_LOAD_PATH, 'poll_calendar_propfind')
_POLL_CALENDAR_PROPFIND_D1 = loadRequestBody(_LOAD_PATH, 'poll_calendar_depth1_propfind')
_POLL_CALENDAR_MULTIGET_REPORT = loadRequestBody('OS_X_10_7', 'poll_calendar_multiget')
_POLL_CALENDAR_MULTIGET_REPORT_HREF = loadRequestBody('OS_X_10_7', 'poll_calendar_multiget_hrefs')
_POLL_CALENDAR_SYNC_REPORT = loadRequestBody('OS_X_10_7', 'poll_calendar_sync')
_POLL_NOTIFICATION_PROPFIND = loadRequestBody(_LOAD_PATH, 'poll_calendar_propfind')
_POLL_NOTIFICATION_PROPFIND_D1 = loadRequestBody(_LOAD_PATH, 'poll_notification_depth1_propfind')
_NOTIFICATION_SYNC_REPORT = loadRequestBody(_LOAD_PATH, 'notification_sync')
_USER_LIST_PRINCIPAL_PROPERTY_SEARCH = loadRequestBody('OS_X_10_7', 'user_list_principal_property_search')
_POST_AVAILABILITY = loadRequestBody('OS_X_10_7', 'post_availability')
_CALENDARSERVER_PRINCIPAL_SEARCH_REPORT = loadRequestBody(_LOAD_PATH, 'principal_search_report')
def _addDefaultHeaders(self, headers):
"""
Add the clients default set of headers to ones being used in a request.
Default is to add User-Agent, sub-classes should override to add other
client specific things, Accept etc.
"""
super(OS_X_10_11, self)._addDefaultHeaders(headers)
headers.setRawHeaders('Accept', ['*/*'])
headers.setRawHeaders('Accept-Language', ['en-us'])
headers.setRawHeaders('Accept-Encoding', ['gzip,deflate'])
headers.setRawHeaders('Connection', ['keep-alive'])
@inlineCallbacks
def startup(self):
# Try to read data from disk - if it succeeds self.principalURL will be set
self.deserialize()
if self.principalURL is None:
# PROPFIND well-known with redirect
response = yield self._startupPropfindWellKnown()
hrefs = response.getHrefProperties()
if davxml.current_user_principal in hrefs:
self.principalURL = hrefs[davxml.current_user_principal].toString()
elif davxml.principal_URL in hrefs:
self.principalURL = hrefs[davxml.principal_URL].toString()
else:
# PROPFIND principal path to retrieve actual principal-URL
response = yield self._principalPropfindInitial(self.record.uid)
hrefs = response.getHrefProperties()
self.principalURL = hrefs[davxml.principal_URL].toString()
# Using the actual principal URL, retrieve principal information
principal = yield self._extractPrincipalDetails()
returnValue(principal)
class iOS_5(BaseAppleClient):
"""
Implementation of the iOS 5 network behavior.
"""
_client_type = "iOS 5"
USER_AGENT = "iOS/5.1 (9B179) dataaccessd/1.0"
# The default interval, used if none is specified in external
# configuration. This is also the actual value used by Snow
# Leopard iCal.
CALENDAR_HOME_POLL_INTERVAL = 15 * 60
# The maximum number of resources to retrieve in a single multiget
MULTIGET_BATCH_SIZE = 50
# Override and turn on if client supports Sync REPORT
_SYNC_REPORT = False
# Override and turn on if client syncs using time-range queries
_SYNC_TIMERANGE = True
# Override and turn off if client does not support attendee lookups
_ATTENDEE_LOOKUPS = False
# Request body data
_LOAD_PATH = "iOS_5"
_STARTUP_WELL_KNOWN = loadRequestBody(_LOAD_PATH, 'startup_well_known')
_STARTUP_PRINCIPAL_PROPFIND_INITIAL = loadRequestBody(_LOAD_PATH, 'startup_principal_propfind_initial')
_STARTUP_PRINCIPAL_PROPFIND = loadRequestBody(_LOAD_PATH, 'startup_principal_propfind')
_STARTUP_PRINCIPALS_REPORT = loadRequestBody(_LOAD_PATH, 'startup_principals_report')
_STARTUP_PROPPATCH_CALENDAR_COLOR = loadRequestBody(_LOAD_PATH, 'startup_calendar_color_proppatch')
_STARTUP_PROPPATCH_CALENDAR_ORDER = loadRequestBody(_LOAD_PATH, 'startup_calendar_order_proppatch')
_POLL_CALENDARHOME_PROPFIND = loadRequestBody(_LOAD_PATH, 'poll_calendarhome_propfind')
_POLL_CALENDAR_PROPFIND = loadRequestBody(_LOAD_PATH, 'poll_calendar_propfind')
_POLL_CALENDAR_VEVENT_TR_QUERY = loadRequestBody(_LOAD_PATH, 'poll_calendar_vevent_tr_query')
_POLL_CALENDAR_VTODO_QUERY = loadRequestBody(_LOAD_PATH, 'poll_calendar_vtodo_query')
_POLL_CALENDAR_PROPFIND_D1 = loadRequestBody(_LOAD_PATH, 'poll_calendar_propfind_d1')
_POLL_CALENDAR_MULTIGET_REPORT = loadRequestBody(_LOAD_PATH, 'poll_calendar_multiget')
_POLL_CALENDAR_MULTIGET_REPORT_HREF = loadRequestBody(_LOAD_PATH, 'poll_calendar_multiget_hrefs')
def _addDefaultHeaders(self, headers):
"""
Add the clients default set of headers to ones being used in a request.
Default is to add User-Agent, sub-classes should override to add other
client specific things, Accept etc.
"""
super(iOS_5, self)._addDefaultHeaders(headers)
headers.setRawHeaders('Accept', ['*/*'])
headers.setRawHeaders('Accept-Language', ['en-us'])
headers.setRawHeaders('Accept-Encoding', ['gzip,deflate'])
headers.setRawHeaders('Connection', ['keep-alive'])
@inlineCallbacks
def _pollFirstTime1(self, homeNode, calendars):
# Patch calendar properties
for cal in calendars:
if cal.name != "inbox":
yield self._proppatch(
cal.url,
self._STARTUP_PROPPATCH_CALENDAR_COLOR,
method_label="PROPPATCH{calendar}",
)
yield self._proppatch(
cal.url,
self._STARTUP_PROPPATCH_CALENDAR_ORDER,
method_label="PROPPATCH{calendar}",
)
def _pollFirstTime2(self):
# Nothing here
return succeed(None)
def _updateCalendar(self, calendar, newToken):
"""
Update the local cached data for a calendar in an appropriate manner.
"""
if calendar.name == "inbox":
# Inbox is done as a PROPFIND Depth:1
return self._updateCalendar_PROPFIND(calendar, newToken)
elif "VEVENT" in calendar.componentTypes:
# VEVENTs done as time-range VEVENT-only queries
return self._updateCalendar_VEVENT(calendar, newToken)
elif "VTODO" in calendar.componentTypes:
# VTODOs done as VTODO-only queries
return self._updateCalendar_VTODO(calendar, newToken)
@inlineCallbacks
def _updateCalendar_VEVENT(self, calendar, newToken):
"""
Sync all locally cached VEVENTs using a VEVENT-only time-range query.
"""
# Grab old hrefs prior to the PROPFIND so we sync with the old state. We need this because
# the sim can fire a PUT between the PROPFIND and when process the removals.
old_hrefs = set([calendar.url + child for child in calendar.events.keys()])
now = DateTime.getNowUTC()
now.setDateOnly(True)
now.offsetMonth(-1) # 1 month back default
result = yield self._report(
calendar.url,
self._POLL_CALENDAR_VEVENT_TR_QUERY % {"start-date": now.getText()},
depth='1',
method_label="REPORT{vevent}",
)
yield self._updateApplyChanges(calendar, result, old_hrefs)
# Now update calendar to the new token
self._calendars[calendar.url].changeToken = newToken
@inlineCallbacks
def _updateCalendar_VTODO(self, calendar, newToken):
"""
Sync all locally cached VTODOs using a VTODO-only query.
"""
# Grab old hrefs prior to the PROPFIND so we sync with the old state. We need this because
# the sim can fire a PUT between the PROPFIND and when process the removals.
old_hrefs = set([calendar.url + child for child in calendar.events.keys()])
result = yield self._report(
calendar.url,
self._POLL_CALENDAR_VTODO_QUERY,
depth='1',
method_label="REPORT{vtodo}",
)
yield self._updateApplyChanges(calendar, result, old_hrefs)
# Now update calendar to the new token
self._calendars[calendar.url].changeToken = newToken
@inlineCallbacks
def startup(self):
# Try to read data from disk - if it succeeds self.principalURL will be set
self.deserialize()
if self.principalURL is None:
# PROPFIND well-known with redirect
response = yield self._startupPropfindWellKnown()
hrefs = response.getHrefProperties()
if davxml.current_user_principal in hrefs:
self.principalURL = hrefs[davxml.current_user_principal].toString()
elif davxml.principal_URL in hrefs:
self.principalURL = hrefs[davxml.principal_URL].toString()
else:
# PROPFIND principal path to retrieve actual principal-URL
response = yield self._principalPropfindInitial(self.record.uid)
hrefs = response.getHrefProperties()
self.principalURL = hrefs[davxml.principal_URL].toString()
# Using the actual principal URL, retrieve principal information
principal = yield self._extractPrincipalDetails()
returnValue(principal)
|