本文整理汇总了Python中pycalendar.datetime.PyCalendarDateTime.getToday方法的典型用法代码示例。如果您正苦于以下问题:Python PyCalendarDateTime.getToday方法的具体用法?Python PyCalendarDateTime.getToday怎么用?Python PyCalendarDateTime.getToday使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pycalendar.datetime.PyCalendarDateTime
的用法示例。
在下文中一共展示了PyCalendarDateTime.getToday方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _doRefresh
# 需要导入模块: from pycalendar.datetime import PyCalendarDateTime [as 别名]
# 或者: from pycalendar.datetime.PyCalendarDateTime import getToday [as 别名]
def _doRefresh(tzpath, xmlfile, tzdb, tzvers):
"""
Refresh data from IANA.
"""
print("Downloading latest data from IANA")
if tzvers:
path = "https://www.iana.org/time-zones/repository/releases/tzdata%s.tar.gz" % (tzvers,)
else:
path = "https://www.iana.org/time-zones/repository/tzdata-latest.tar.gz"
data = urllib.urlretrieve(path)
print("Extract data at: %s" % (data[0]))
rootdir = tempfile.mkdtemp()
zonedir = os.path.join(rootdir, "tzdata")
os.mkdir(zonedir)
with tarfile.open(data[0], "r:gz") as t:
t.extractall(zonedir)
# Get the version from the Makefile
try:
makefile = open(os.path.join(zonedir, "Makefile")).read()
lines = makefile.splitlines()
for line in lines:
if line.startswith("VERSION="):
tzvers = line[8:].strip()
break
except IOError:
pass
if not tzvers:
tzvers = PyCalendarDateTime.getToday().getText()
print("Converting data (version: %s) at: %s" % (tzvers, zonedir,))
startYear = 1800
endYear = PyCalendarDateTime.getToday().getYear() + 10
PyCalendar.sProdID = "-//calendarserver.org//Zonal//EN"
zonefiles = "northamerica", "southamerica", "europe", "africa", "asia", "australasia", "antarctica", "etcetera", "backward"
parser = tzconvert()
for file in zonefiles:
parser.parse(os.path.join(zonedir, file))
parser.generateZoneinfoFiles(os.path.join(rootdir, "zoneinfo"), startYear, endYear, filterzones=())
print("Copy new zoneinfo to destination: %s" % (tzpath,))
z = FilePath(os.path.join(rootdir, "zoneinfo"))
tz = FilePath(tzpath)
z.copyTo(tz)
print("Updating XML file at: %s" % (xmlfile,))
tzdb.readDatabase()
tzdb.updateDatabase()
print("Current total: %d" % (len(tzdb.timezones),))
print("Total Changed: %d" % (tzdb.changeCount,))
if tzdb.changeCount:
print("Changed:")
for k in sorted(tzdb.changed):
print(" %s" % (k,))
versfile = os.path.join(os.path.dirname(xmlfile), "version.txt")
print("Updating version file at: %s" % (versfile,))
with open(versfile, "w") as f:
f.write(TimezoneCache.IANA_VERSION_PREFIX + tzvers)
示例2: updateToCurrentYear
# 需要导入模块: from pycalendar.datetime import PyCalendarDateTime [as 别名]
# 或者: from pycalendar.datetime.PyCalendarDateTime import getToday [as 别名]
def updateToCurrentYear(data):
"""
Update the supplied iCalendar data so that all dates are updated to the current year.
"""
nowYear = PyCalendarDateTime.getToday().getYear()
return data % {"now": nowYear}
示例3: setUpCalendarStore
# 需要导入模块: from pycalendar.datetime import PyCalendarDateTime [as 别名]
# 或者: from pycalendar.datetime.PyCalendarDateTime import getToday [as 别名]
def setUpCalendarStore(test):
test.root = FilePath(test.mktemp())
test.root.createDirectory()
storeRootPath = test.storeRootPath = test.root.child("store")
calendarPath = storeRootPath.child("calendars").child("__uids__")
calendarPath.parent().makedirs()
storePath.copyTo(calendarPath)
# Set year values to current year
nowYear = PyCalendarDateTime.getToday().getYear()
for home in calendarPath.child("ho").child("me").children():
if not home.basename().startswith("."):
for calendar in home.children():
if not calendar.basename().startswith("."):
for resource in calendar.children():
if resource.basename().endswith(".ics"):
resource.setContent(resource.getContent() % {"now": nowYear})
testID = test.id()
test.calendarStore = CalendarStore(
storeRootPath,
{"push": test.notifierFactory} if test.notifierFactory else {},
buildDirectory(),
quota=deriveQuota(test),
)
test.txn = test.calendarStore.newTransaction(testID + "(old)")
assert test.calendarStore is not None, "No calendar store?"
示例4: command_purgeOldEvents
# 需要导入模块: from pycalendar.datetime import PyCalendarDateTime [as 别名]
# 或者: from pycalendar.datetime.PyCalendarDateTime import getToday [as 别名]
def command_purgeOldEvents(self, command):
"""
Convert RetainDays from the command dictionary into a date, then purge
events older than that date.
@param command: the dictionary parsed from the plist read from stdin
@type command: C{dict}
"""
retainDays = command.get("RetainDays", DEFAULT_RETAIN_DAYS)
cutoff = PyCalendarDateTime.getToday()
cutoff.setDateOnly(False)
cutoff.offsetDay(-retainDays)
eventCount = (yield PurgeOldEventsService.purgeOldEvents(self.store, cutoff, DEFAULT_BATCH_SIZE))
self.respond(command, {'EventsRemoved' : eventCount, "RetainDays" : retainDays})
示例5: purgeAttachments
# 需要导入模块: from pycalendar.datetime import PyCalendarDateTime [as 别名]
# 或者: from pycalendar.datetime.PyCalendarDateTime import getToday [as 别名]
def purgeAttachments(cls, store, uuid, days, limit, dryrun, verbose):
service = cls(store)
service.uuid = uuid
if days > 0:
cutoff = PyCalendarDateTime.getToday()
cutoff.setDateOnly(False)
cutoff.offsetDay(-days)
service.cutoff = cutoff
else:
service.cutoff = None
service.batchSize = limit
service.dryrun = dryrun
service.verbose = verbose
result = (yield service.doWork())
returnValue(result)
示例6:
# 需要导入模块: from pycalendar.datetime import PyCalendarDateTime [as 别名]
# 或者: from pycalendar.datetime.PyCalendarDateTime import getToday [as 别名]
from twext.enterprise.dal.syntax import Update, Delete
from twext.web2.http_headers import MimeType
from twisted.internet.defer import inlineCallbacks, returnValue
from twistedcaldav.config import config
from twistedcaldav.test.util import StoreTestCase
from twistedcaldav.vcard import Component as VCardComponent
from txdav.common.datastore.sql_tables import schema
from txdav.common.datastore.test.util import populateCalendarsFrom
import os
now = PyCalendarDateTime.getToday().getYear()
OLD_ICS = """BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Apple Inc.//iCal 4.0.1//EN
CALSCALE:GREGORIAN
BEGIN:VTIMEZONE
TZID:US/Pacific
BEGIN:STANDARD
TZOFFSETFROM:-0700
RRULE:FREQ=YEARLY;UNTIL=20061029T090000Z;BYMONTH=10;BYDAY=-1SU
DTSTART:19621028T020000
TZNAME:PST
TZOFFSETTO:-0800
END:STANDARD
BEGIN:DAYLIGHT
示例7: generateFreeBusyInfo
# 需要导入模块: from pycalendar.datetime import PyCalendarDateTime [as 别名]
# 或者: from pycalendar.datetime.PyCalendarDateTime import getToday [as 别名]
def generateFreeBusyInfo(
calresource,
fbinfo,
timerange,
matchtotal,
excludeuid=None,
organizer=None,
organizerPrincipal=None,
same_calendar_user=False,
servertoserver=False,
event_details=None,
logItems=None,
):
"""
Run a free busy report on the specified calendar collection
accumulating the free busy info for later processing.
@param calresource: the L{Calendar} for a calendar collection.
@param fbinfo: the array of busy periods to update.
@param timerange: the L{TimeRange} for the query.
@param matchtotal: the running total for the number of matches.
@param excludeuid: a C{str} containing a UID value to exclude any
components with that UID from contributing to free-busy.
@param organizer: a C{str} containing the value of the ORGANIZER property
in the VFREEBUSY request. This is used in conjunction with the UID
value to process exclusions.
@param same_calendar_user: a C{bool} indicating whether the calendar user
requesting the free-busy information is the same as the calendar user
being targeted.
@param servertoserver: a C{bool} indicating whether we are doing a local or
remote lookup request.
@param event_details: a C{list} into which to store extended VEVENT details if not C{None}
@param logItems: a C{dict} to store logging info to
"""
# First check the privilege on this collection
# TODO: for server-to-server we bypass this right now as we have no way to authorize external users.
# TODO: actually we by pass altogether by assuming anyone can check anyone else's freebusy
# May need organizer principal
organizer_record = calresource.directoryService().recordWithCalendarUserAddress(organizer) if organizer else None
organizer_uid = organizer_record.uid if organizer_record else ""
# Free busy is per-user
attendee_uid = calresource.viewerHome().uid()
attendee_record = calresource.directoryService().recordWithUID(attendee_uid)
# Get the timezone property from the collection.
tz = calresource.getTimezone()
# Look for possible extended free busy information
rich_options = {
"organizer": False,
"delegate": False,
"resource": False,
}
do_event_details = False
if event_details is not None and organizer_record is not None and attendee_record is not None:
# Get the principal of the authorized user which may be different from the organizer if a delegate of
# the organizer is making the request
authz_uid = organizer_uid
authz_record = organizer_record
if hasattr(calresource._txn, "_authz_uid") and calresource._txn._authz_uid != organizer_uid:
authz_uid = calresource._txn._authz_uid
authz_record = calresource.directoryService().recordWithUID(authz_uid)
# Check if attendee is also the organizer or the delegate doing the request
if attendee_uid in (organizer_uid, authz_uid):
do_event_details = True
rich_options["organizer"] = True
# Check if authorized user is a delegate of attendee
proxy = (yield authz_record.isProxyFor(attendee_record))
if config.Scheduling.Options.DelegeteRichFreeBusy and proxy:
do_event_details = True
rich_options["delegate"] = True
# Check if attendee is room or resource
if config.Scheduling.Options.RoomResourceRichFreeBusy and attendee_record.getCUType() in ("RESOURCE", "ROOM",):
do_event_details = True
rich_options["resource"] = True
# Try cache
resources = (yield FBCacheEntry.getCacheEntry(calresource, attendee_uid, timerange)) if config.EnableFreeBusyCache else None
if resources is None:
caching = False
if config.EnableFreeBusyCache:
# Log extended item
if logItems is not None:
logItems["fb-uncached"] = logItems.get("fb-uncached", 0) + 1
# We want to cache a large range of time based on the current date
cache_start = normalizeToUTC(PyCalendarDateTime.getToday() + PyCalendarDuration(days=0 - config.FreeBusyCacheDaysBack))
cache_end = normalizeToUTC(PyCalendarDateTime.getToday() + PyCalendarDuration(days=config.FreeBusyCacheDaysForward))
# If the requested time range would fit in our allowed cache range, trigger the cache creation
if compareDateTime(timerange.start, cache_start) >= 0 and compareDateTime(timerange.end, cache_end) <= 0:
cache_timerange = TimeRange(start=cache_start.getText(), end=cache_end.getText())
#.........这里部分代码省略.........
示例8: doExpand
# 需要导入模块: from pycalendar.datetime import PyCalendarDateTime [as 别名]
# 或者: from pycalendar.datetime.PyCalendarDateTime import getToday [as 别名]
def doExpand(self, request):
"""
Expand a timezone within specified start/end dates.
"""
tzids = request.args.get("tzid", ())
if len(tzids) != 1:
raise HTTPError(JSONResponse(
responsecode.BAD_REQUEST,
{
"error": "invalid-tzid",
"description": "Invalid tzid query parameter",
},
))
try:
start = request.args.get("start", ())
if len(start) > 1:
raise ValueError()
elif len(start) == 1:
start = PyCalendarDateTime.parseText(start[0])
else:
start = PyCalendarDateTime.getToday()
start.setDay(1)
start.setMonth(1)
except ValueError:
raise HTTPError(JSONResponse(
responsecode.BAD_REQUEST,
{
"error": "invalid-start",
"description": "Invalid start query parameter",
}
))
try:
end = request.args.get("end", ())
if len(end) > 1:
raise ValueError()
elif len(end) == 1:
end = PyCalendarDateTime.parseText(end[0])
else:
end = PyCalendarDateTime.getToday()
end.setDay(1)
end.setMonth(1)
end.offsetYear(10)
if end <= start:
raise ValueError()
except ValueError:
raise HTTPError(JSONResponse(
responsecode.BAD_REQUEST,
{
"error": "invalid-end",
"description": "Invalid end query parameter",
}
))
tzid = tzids[0]
tzdata = self.timezones.getTimezone(tzid)
if tzdata is None:
raise HTTPError(JSONResponse(
responsecode.NOT_FOUND,
{
"error": "missing-tzid",
"description": "Tzid could not be found",
}
))
# Now do the expansion (but use a cache to avoid re-calculating TZs)
observances = self.expandcache.get((tzid, start, end), None)
if observances is None:
observances = tzexpandlocal(tzdata, start, end)
self.expandcache[(tzid, start, end)] = observances
# Turn into JSON
result = {
"dtstamp": self.timezones.dtstamp,
"observances": [
{
"name": name,
"onset": onset.getXMLText(),
"utc-offset-from": utc_offset_from,
"utc-offset-to": utc_offset_to,
} for onset, utc_offset_from, utc_offset_to, name in observances
],
}
return JSONResponse(responsecode.OK, result)
示例9: indexedSearch
# 需要导入模块: from pycalendar.datetime import PyCalendarDateTime [as 别名]
# 或者: from pycalendar.datetime.PyCalendarDateTime import getToday [as 别名]
def indexedSearch(self, filter, useruid='', fbtype=False):
"""
Finds resources matching the given qualifiers.
@param filter: the L{Filter} for the calendar-query to execute.
@return: a L{Deferred} which fires with an iterable of tuples for each
resource matching the given C{qualifiers}. The tuples are C{(name,
uid, type)}, where C{name} is the resource name, C{uid} is the
resource UID, and C{type} is the resource iCalendar component type.
"""
# Detect which style of parameter-generation we're using. Naming is a
# little off here, because the reason we're using the numeric one is
# that it happens to be used by the oracle binding that we're using,
# whereas the postgres binding happens to use the 'pyformat' (e.g. %s)
# parameter style.
if self.calendar._txn.paramstyle == 'numeric':
generator = oraclesqlgenerator
else:
generator = postgresqlgenerator
# Make sure we have a proper Filter element and get the partial SQL
# statement to use.
if isinstance(filter, calendarqueryfilter.Filter):
qualifiers = calendarquery.sqlcalendarquery(
filter, self.calendar._resourceID, useruid, fbtype,
generator=generator
)
if qualifiers is not None:
today = PyCalendarDateTime.getToday()
# Determine how far we need to extend the current expansion of
# events. If we have an open-ended time-range we will expand
# one year past the start. That should catch bounded
# recurrences - unbounded will have been indexed with an
# "infinite" value always included.
maxDate, isStartDate = filter.getmaxtimerange()
if maxDate:
maxDate = maxDate.duplicate()
maxDate.offsetDay(1)
maxDate.setDateOnly(True)
upperLimit = today + PyCalendarDuration(days=config.FreeBusyIndexExpandMaxDays)
if maxDate > upperLimit:
raise TimeRangeUpperLimit(upperLimit)
if isStartDate:
maxDate += PyCalendarDuration(days=365)
# Determine if the start date is too early for the restricted range we
# are applying. If it is today or later we don't need to worry about truncation
# in the past.
minDate, _ignore_isEndDate = filter.getmintimerange()
if minDate >= today:
minDate = None
if minDate is not None and config.FreeBusyIndexLowerLimitDays:
truncateLowerLimit = today - PyCalendarDuration(days=config.FreeBusyIndexLowerLimitDays)
if minDate < truncateLowerLimit:
raise TimeRangeLowerLimit(truncateLowerLimit)
if maxDate is not None or minDate is not None:
yield self.testAndUpdateIndex(minDate, maxDate)
else:
# We cannot handle this filter in an indexed search
raise IndexedSearchException()
else:
qualifiers = None
# Perform the search
if qualifiers is None:
rowiter = yield self.bruteForceSearch()
else:
if fbtype:
# For a free-busy time-range query we return all instances
rowiter = yield self._txn.execSQL(
"""
select DISTINCT
CALENDAR_OBJECT.RESOURCE_NAME,
CALENDAR_OBJECT.ICALENDAR_UID,
CALENDAR_OBJECT.ICALENDAR_TYPE,
CALENDAR_OBJECT.ORGANIZER,
TIME_RANGE.FLOATING, TIME_RANGE.START_DATE,
TIME_RANGE.END_DATE, TIME_RANGE.FBTYPE,
TIME_RANGE.TRANSPARENT, TRANSPARENCY.TRANSPARENT
""" +
qualifiers[0],
qualifiers[1]
)
else:
rowiter = yield self._txn.execSQL(
"""
select
DISTINCT CALENDAR_OBJECT.RESOURCE_NAME,
CALENDAR_OBJECT.ICALENDAR_UID,
CALENDAR_OBJECT.ICALENDAR_TYPE
""" +
qualifiers[0],
qualifiers[1]
)
# Check result for missing resources
#.........这里部分代码省略.........
示例10: test_calendar_query_time_range
# 需要导入模块: from pycalendar.datetime import PyCalendarDateTime [as 别名]
# 或者: from pycalendar.datetime.PyCalendarDateTime import getToday [as 别名]
def test_calendar_query_time_range(self):
"""
Partial retrieval of events by time range.
(CalDAV-access-09, section 7.6.1)
"""
calendar_properties = (
davxml.GETETag(),
caldavxml.CalendarData(
caldavxml.CalendarComponent(
caldavxml.AllProperties(),
caldavxml.CalendarComponent(
caldavxml.Property(name="X-ABC-GUID"),
caldavxml.Property(name="UID"),
caldavxml.Property(name="DTSTART"),
caldavxml.Property(name="DTEND"),
caldavxml.Property(name="DURATION"),
caldavxml.Property(name="EXDATE"),
caldavxml.Property(name="EXRULE"),
caldavxml.Property(name="RDATE"),
caldavxml.Property(name="RRULE"),
caldavxml.Property(name="LOCATION"),
caldavxml.Property(name="SUMMARY"),
name="VEVENT",
),
caldavxml.CalendarComponent(
caldavxml.AllProperties(),
caldavxml.AllComponents(),
name="VTIMEZONE",
),
name="VCALENDAR",
),
),
)
query_timerange = caldavxml.TimeRange(
start="%04d1001T000000Z" % (PyCalendarDateTime.getToday().getYear(),),
end="%04d1101T000000Z" % (PyCalendarDateTime.getToday().getYear(),),
)
query = caldavxml.CalendarQuery(
davxml.PropertyContainer(*calendar_properties),
caldavxml.Filter(
caldavxml.ComponentFilter(
caldavxml.ComponentFilter(
query_timerange,
name="VEVENT",
),
name="VCALENDAR",
),
),
)
def got_xml(doc):
if not isinstance(doc.root_element, davxml.MultiStatus):
self.fail("REPORT response XML root element is not multistatus: %r" % (doc.root_element,))
for response in doc.root_element.childrenOfType(davxml.PropertyStatusResponse):
properties_to_find = [p.qname() for p in calendar_properties]
for propstat in response.childrenOfType(davxml.PropertyStatus):
status = propstat.childOfType(davxml.Status)
properties = propstat.childOfType(davxml.PropertyContainer).children
if status.code != responsecode.OK:
self.fail("REPORT failed (status %s) to locate properties: %r"
% (status.code, properties))
for property in properties:
qname = property.qname()
if qname in properties_to_find:
properties_to_find.remove(qname)
else:
self.fail("REPORT found property we didn't ask for: %r" % (property,))
if isinstance(property, caldavxml.CalendarData):
cal = property.calendar()
instances = cal.expandTimeRanges(query_timerange.end)
vevents = [x for x in cal.subcomponents() if x.name() == "VEVENT"]
if not calendarqueryfilter.TimeRange(query_timerange).matchinstance(vevents[0], instances):
self.fail("REPORT property %r returned calendar %s outside of request time range %r"
% (property, property.calendar, query_timerange))
return self.calendar_query("/calendar_query_time_range/", query, got_xml)
示例11: _add_to_db
# 需要导入模块: from pycalendar.datetime import PyCalendarDateTime [as 别名]
# 或者: from pycalendar.datetime.PyCalendarDateTime import getToday [as 别名]
def _add_to_db(self, name, calendar, cursor = None, expand_until=None, reCreate=False):
"""
Records the given calendar resource in the index with the given name.
Resource names and UIDs must both be unique; only one resource name may
be associated with any given UID and vice versa.
NB This method does not commit the changes to the db - the caller
MUST take care of that
@param name: the name of the resource to add.
@param calendar: a L{Calendar} object representing the resource
contents.
"""
uid = calendar.resourceUID()
organizer = calendar.getOrganizer()
if not organizer:
organizer = ""
# Decide how far to expand based on the component
doInstanceIndexing = False
master = calendar.masterComponent()
if master is None or not calendar.isRecurring():
# When there is no master we have a set of overridden components - index them all.
# When there is one instance - index it.
expand = PyCalendarDateTime(2100, 1, 1, 0, 0, 0, tzid=PyCalendarTimezone(utc=True))
doInstanceIndexing = True
else:
# If migrating or re-creating or config option for delayed indexing is off, always index
if reCreate or not config.FreeBusyIndexDelayedExpand:
doInstanceIndexing = True
# Duration into the future through which recurrences are expanded in the index
# by default. This is a caching parameter which affects the size of the index;
# it does not affect search results beyond this period, but it may affect
# performance of such a search.
expand = (PyCalendarDateTime.getToday() +
PyCalendarDuration(days=config.FreeBusyIndexExpandAheadDays))
if expand_until and expand_until > expand:
expand = expand_until
# Maximum duration into the future through which recurrences are expanded in the
# index. This is a caching parameter which affects the size of the index; it
# does not affect search results beyond this period, but it may affect
# performance of such a search.
#
# When a search is performed on a time span that goes beyond that which is
# expanded in the index, we have to open each resource which may have data in
# that time period. In order to avoid doing that multiple times, we want to
# cache those results. However, we don't necessarily want to cache all
# occurrences into some obscenely far-in-the-future date, so we cap the caching
# period. Searches beyond this period will always be relatively expensive for
# resources with occurrences beyond this period.
if expand > (PyCalendarDateTime.getToday() +
PyCalendarDuration(days=config.FreeBusyIndexExpandMaxDays)):
raise IndexedSearchException()
# Always do recurrence expansion even if we do not intend to index - we need this to double-check the
# validity of the iCalendar recurrence data.
try:
instances = calendar.expandTimeRanges(expand, ignoreInvalidInstances=reCreate)
recurrenceLimit = instances.limit
except InvalidOverriddenInstanceError, e:
log.err("Invalid instance %s when indexing %s in %s" % (e.rid, name, self.resource,))
raise
示例12: in
# 需要导入模块: from pycalendar.datetime import PyCalendarDateTime [as 别名]
# 或者: from pycalendar.datetime.PyCalendarDateTime import getToday [as 别名]
elif opt in ("-n", "--dry-run"):
dryrun = True
elif opt in ("-f", "--config"):
configFileName = arg
else:
raise NotImplementedError(opt)
if args:
cls.usage("Too many arguments: %s" % (args,))
if dryrun:
verbose = True
cutoff = PyCalendarDateTime.getToday()
cutoff.setDateOnly(False)
cutoff.offsetDay(-days)
cls.cutoff = cutoff
cls.batchSize = batchSize
cls.dryrun = dryrun
cls.verbose = verbose
utilityMain(
configFileName,
cls,
verbose=debug,
)
@classmethod
示例13: checkAttendeeAutoReply
# 需要导入模块: from pycalendar.datetime import PyCalendarDateTime [as 别名]
# 或者: from pycalendar.datetime.PyCalendarDateTime import getToday [as 别名]
def checkAttendeeAutoReply(self, calendar, automode):
"""
Check whether a reply to the given iTIP message is needed and if so make the
appropriate changes to the calendar data. Changes are only made for the case
where the PARTSTAT of the attendee is NEEDS-ACTION - i.e., any existing state
is left unchanged. This allows, e.g., proxies to decline events that would
otherwise have been auto-accepted and those stay declined as non-schedule-change
updates are received.
@param calendar: the iTIP message to process
@type calendar: L{Component}
@param automode: the auto-schedule mode for the recipient
@type automode: C{str}
@return: C{tuple} of C{bool}, C{bool}, C{str} indicating whether changes were made, whether the inbox item
should be added, and the new PARTSTAT.
"""
# First ignore the none mode
if automode == "none":
returnValue((False, True, "",))
elif not automode or automode == "default":
automode = config.Scheduling.Options.AutoSchedule.DefaultMode
log.debug("ImplicitProcessing - recipient '%s' processing UID: '%s' - checking for auto-reply with mode: %s" % (self.recipient.cuaddr, self.uid, automode,))
cuas = self.recipient.principal.calendarUserAddresses()
# First expand current one to get instances (only go 1 year into the future)
default_future_expansion_duration = PyCalendarDuration(days=config.Scheduling.Options.AutoSchedule.FutureFreeBusyDays)
expand_max = PyCalendarDateTime.getToday() + default_future_expansion_duration
instances = calendar.expandTimeRanges(expand_max, ignoreInvalidInstances=True)
# We are goin g to ignore auto-accept processing for anything more than a day old (actually use -2 days
# to add some slop to account for possible timezone offsets)
min_date = PyCalendarDateTime.getToday()
min_date.offsetDay(-2)
allOld = True
# Cache the current attendee partstat on the instance object for later use, and
# also mark whether the instance time slot would be free
for instance in instances.instances.itervalues():
attendee = instance.component.getAttendeeProperty(cuas)
instance.partstat = attendee.parameterValue("PARTSTAT", "NEEDS-ACTION") if attendee else None
instance.free = True
instance.active = (instance.end > min_date)
if instance.active:
allOld = False
# If every instance is in the past we punt right here so we don't waste time on freebusy lookups etc.
# There will be no auto-accept and no inbox item stored (so as not to waste storage on items that will
# never be processed).
if allOld:
returnValue((False, False, "",))
# Extract UID from primary component as we want to ignore this one if we match it
# in any calendars.
comp = calendar.mainComponent(allow_multiple=True)
uid = comp.propertyValue("UID")
# Now compare each instance time-range with the index and see if there is an overlap
calendars = (yield self._getCalendarsToMatch())
for calURL in calendars:
testcal = (yield self.request.locateResource(calURL))
# Get the timezone property from the collection, and store in the query filter
# for use during the query itself.
has_prop = (yield testcal.hasProperty((caldav_namespace, "calendar-timezone"), self.request))
if has_prop:
tz = (yield testcal.readProperty((caldav_namespace, "calendar-timezone"), self.request))
tzinfo = tz.calendar().gettimezone()
else:
tzinfo = PyCalendarTimezone(utc=True)
# Now do search for overlapping time-range and set instance.free based
# on whether there is an overlap or not
for instance in instances.instances.itervalues():
if instance.partstat == "NEEDS-ACTION" and instance.free and instance.active:
try:
# First list is BUSY, second BUSY-TENTATIVE, third BUSY-UNAVAILABLE
fbinfo = ([], [], [])
def makeTimedUTC(dt):
dt = dt.duplicate()
if dt.isDateOnly():
dt.setDateOnly(False)
dt.setHHMMSS(0, 0, 0)
if dt.floating():
dt.setTimezone(tzinfo)
dt.adjustToUTC()
return dt
tr = caldavxml.TimeRange(
start=str(makeTimedUTC(instance.start)),
end=str(makeTimedUTC(instance.end)),
)
yield report_common.generateFreeBusyInfo(self.request, testcal, fbinfo, tr, 0, uid, servertoserver=True)
#.........这里部分代码省略.........