Fork vobject
This commit is contained in:
parent
735bec6be2
commit
126a31c82a
@ -49,7 +49,7 @@ from http import client
|
||||
from urllib.parse import unquote, urlparse
|
||||
from xml.etree import ElementTree as ET
|
||||
|
||||
import vobject
|
||||
import radicale_vobject as vobject
|
||||
|
||||
from radicale import auth, config, log, rights, storage, web, xmlutils
|
||||
|
||||
|
@ -44,7 +44,7 @@ from math import log
|
||||
from random import getrandbits
|
||||
from tempfile import NamedTemporaryFile, TemporaryDirectory
|
||||
|
||||
import vobject
|
||||
import radicale_vobject as vobject
|
||||
|
||||
if sys.version_info >= (3, 5):
|
||||
# HACK: Avoid import cycle for Python < 3.5
|
||||
|
8
radicale_vobject/ACKNOWLEDGEMENTS.txt
Normal file
8
radicale_vobject/ACKNOWLEDGEMENTS.txt
Normal file
@ -0,0 +1,8 @@
|
||||
Enormous thanks to:
|
||||
Jeffrey Harris, for his incredible work on the original package
|
||||
Tim Baxter, for all his work maintaining vobject over the past few years
|
||||
Adieu, for keeping things alive on github
|
||||
Kristian Glass, for his enormous help with testing and Python3 matters
|
||||
Gustavo Niemeyer, for all his work on dateutil
|
||||
Dave Cridland, for helping talk about vobject and working on vcard
|
||||
TJ Gabbour, for putting his heart into parsing
|
202
radicale_vobject/LICENSE-2.0.txt
Normal file
202
radicale_vobject/LICENSE-2.0.txt
Normal file
@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
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.
|
7
radicale_vobject/README.md
Normal file
7
radicale_vobject/README.md
Normal file
@ -0,0 +1,7 @@
|
||||
# Radicale VObject
|
||||
|
||||
Fork of [VObject](https://github.com/eventable/vobject).
|
||||
|
||||
Radicale VObject is licensed under the [Apache 2.0 license](http://www.apache.org/licenses/LICENSE-2.0).
|
||||
|
||||
Upstream git commit: [c4ae08b767](https://github.com/eventable/vobject/commit/c4ae08b7678bfdeec3c6b2dcbf74d383fd27ed14)
|
88
radicale_vobject/__init__.py
Normal file
88
radicale_vobject/__init__.py
Normal file
@ -0,0 +1,88 @@
|
||||
"""
|
||||
VObject Overview
|
||||
================
|
||||
vobject parses vCard or vCalendar files, returning a tree of Python objects.
|
||||
It also provids an API to create vCard or vCalendar data structures which
|
||||
can then be serialized.
|
||||
|
||||
Parsing existing streams
|
||||
------------------------
|
||||
Streams containing one or many L{Component<base.Component>}s can be
|
||||
parsed using L{readComponents<base.readComponents>}. As each Component
|
||||
is parsed, vobject will attempt to give it a L{Behavior<behavior.Behavior>}.
|
||||
If an appropriate Behavior is found, any base64, quoted-printable, or
|
||||
backslash escaped data will automatically be decoded. Dates and datetimes
|
||||
will be transformed to datetime.date or datetime.datetime instances.
|
||||
Components containing recurrence information will have a special rruleset
|
||||
attribute (a dateutil.rrule.rruleset instance).
|
||||
|
||||
Validation
|
||||
----------
|
||||
L{Behavior<behavior.Behavior>} classes implement validation for
|
||||
L{Component<base.Component>}s. To validate, an object must have all
|
||||
required children. There (TODO: will be) a toggle to raise an exception or
|
||||
just log unrecognized, non-experimental children and parameters.
|
||||
|
||||
Creating objects programatically
|
||||
--------------------------------
|
||||
A L{Component<base.Component>} can be created from scratch. No encoding
|
||||
is necessary, serialization will encode data automatically. Factory
|
||||
functions (TODO: will be) available to create standard objects.
|
||||
|
||||
Serializing objects
|
||||
-------------------
|
||||
Serialization:
|
||||
- Looks for missing required children that can be automatically generated,
|
||||
like a UID or a PRODID, and adds them
|
||||
- Encodes all values that can be automatically encoded
|
||||
- Checks to make sure the object is valid (unless this behavior is
|
||||
explicitly disabled)
|
||||
- Appends the serialized object to a buffer, or fills a new
|
||||
buffer and returns it
|
||||
|
||||
Examples
|
||||
--------
|
||||
|
||||
>>> import datetime
|
||||
>>> import dateutil.rrule as rrule
|
||||
>>> x = iCalendar()
|
||||
>>> x.add('vevent')
|
||||
<VEVENT| []>
|
||||
>>> x
|
||||
<VCALENDAR| [<VEVENT| []>]>
|
||||
>>> v = x.vevent
|
||||
>>> utc = icalendar.utc
|
||||
>>> v.add('dtstart').value = datetime.datetime(2004, 12, 15, 14, tzinfo = utc)
|
||||
>>> v
|
||||
<VEVENT| [<DTSTART{}2004-12-15 14:00:00+00:00>]>
|
||||
>>> x
|
||||
<VCALENDAR| [<VEVENT| [<DTSTART{}2004-12-15 14:00:00+00:00>]>]>
|
||||
>>> newrule = rrule.rruleset()
|
||||
>>> newrule.rrule(rrule.rrule(rrule.WEEKLY, count=2, dtstart=v.dtstart.value))
|
||||
>>> v.rruleset = newrule
|
||||
>>> list(v.rruleset)
|
||||
[datetime.datetime(2004, 12, 15, 14, 0, tzinfo=tzutc()), datetime.datetime(2004, 12, 22, 14, 0, tzinfo=tzutc())]
|
||||
>>> v.add('uid').value = "randomuid@MYHOSTNAME"
|
||||
>>> print x.serialize()
|
||||
BEGIN:VCALENDAR
|
||||
VERSION:2.0
|
||||
PRODID:-//PYVOBJECT//NONSGML Version 1//EN
|
||||
BEGIN:VEVENT
|
||||
UID:randomuid@MYHOSTNAME
|
||||
DTSTART:20041215T140000Z
|
||||
RRULE:FREQ=WEEKLY;COUNT=2
|
||||
END:VEVENT
|
||||
END:VCALENDAR
|
||||
|
||||
"""
|
||||
|
||||
from .base import newFromBehavior, readOne, readComponents
|
||||
from . import icalendar, vcard
|
||||
|
||||
|
||||
def iCalendar():
|
||||
return newFromBehavior('vcalendar', '2.0')
|
||||
|
||||
|
||||
def vCard():
|
||||
return newFromBehavior('vcard', '3.0')
|
1217
radicale_vobject/base.py
Normal file
1217
radicale_vobject/base.py
Normal file
File diff suppressed because it is too large
Load Diff
174
radicale_vobject/behavior.py
Normal file
174
radicale_vobject/behavior.py
Normal file
@ -0,0 +1,174 @@
|
||||
from . import base
|
||||
|
||||
|
||||
#------------------------ Abstract class for behavior --------------------------
|
||||
class Behavior(object):
|
||||
"""
|
||||
Behavior (validation, encoding, and transformations) for vobjects.
|
||||
|
||||
Abstract class to describe vobject options, requirements and encodings.
|
||||
|
||||
Behaviors are used for root components like VCALENDAR, for subcomponents
|
||||
like VEVENT, and for individual lines in components.
|
||||
|
||||
Behavior subclasses are not meant to be instantiated, all methods should
|
||||
be classmethods.
|
||||
|
||||
@cvar name:
|
||||
The uppercase name of the object described by the class, or a generic
|
||||
name if the class defines behavior for many objects.
|
||||
@cvar description:
|
||||
A brief excerpt from the RFC explaining the function of the component or
|
||||
line.
|
||||
@cvar versionString:
|
||||
The string associated with the component, for instance, 2.0 if there's a
|
||||
line like VERSION:2.0, an empty string otherwise.
|
||||
@cvar knownChildren:
|
||||
A dictionary with uppercased component/property names as keys and a
|
||||
tuple (min, max, id) as value, where id is the id used by
|
||||
L{registerBehavior}, min and max are the limits on how many of this child
|
||||
must occur. None is used to denote no max or no id.
|
||||
@cvar quotedPrintable:
|
||||
A boolean describing whether the object should be encoded and decoded
|
||||
using quoted printable line folding and character escaping.
|
||||
@cvar defaultBehavior:
|
||||
Behavior to apply to ContentLine children when no behavior is found.
|
||||
@cvar hasNative:
|
||||
A boolean describing whether the object can be transformed into a more
|
||||
Pythonic object.
|
||||
@cvar isComponent:
|
||||
A boolean, True if the object should be a Component.
|
||||
@cvar sortFirst:
|
||||
The lower-case list of children which should come first when sorting.
|
||||
@cvar allowGroup:
|
||||
Whether or not vCard style group prefixes are allowed.
|
||||
"""
|
||||
name = ''
|
||||
description = ''
|
||||
versionString = ''
|
||||
knownChildren = {}
|
||||
quotedPrintable = False
|
||||
defaultBehavior = None
|
||||
hasNative = False
|
||||
isComponent = False
|
||||
allowGroup = False
|
||||
forceUTC = False
|
||||
sortFirst = []
|
||||
|
||||
def __init__(self):
|
||||
err = "Behavior subclasses are not meant to be instantiated"
|
||||
raise base.VObjectError(err)
|
||||
|
||||
@classmethod
|
||||
def validate(cls, obj, raiseException=False, complainUnrecognized=False):
|
||||
"""Check if the object satisfies this behavior's requirements.
|
||||
|
||||
@param obj:
|
||||
The L{ContentLine<base.ContentLine>} or
|
||||
L{Component<base.Component>} to be validated.
|
||||
@param raiseException:
|
||||
If True, raise a L{base.ValidateError} on validation failure.
|
||||
Otherwise return a boolean.
|
||||
@param complainUnrecognized:
|
||||
If True, fail to validate if an uncrecognized parameter or child is
|
||||
found. Otherwise log the lack of recognition.
|
||||
|
||||
"""
|
||||
if not cls.allowGroup and obj.group is not None:
|
||||
err = "{0} has a group, but this object doesn't support groups".format(obj)
|
||||
raise base.VObjectError(err)
|
||||
if isinstance(obj, base.ContentLine):
|
||||
return cls.lineValidate(obj, raiseException, complainUnrecognized)
|
||||
elif isinstance(obj, base.Component):
|
||||
count = {}
|
||||
for child in obj.getChildren():
|
||||
if not child.validate(raiseException, complainUnrecognized):
|
||||
return False
|
||||
name = child.name.upper()
|
||||
count[name] = count.get(name, 0) + 1
|
||||
for key, val in cls.knownChildren.items():
|
||||
if count.get(key, 0) < val[0]:
|
||||
if raiseException:
|
||||
m = "{0} components must contain at least {1} {2}"
|
||||
raise base.ValidateError(m .format(cls.name, val[0], key))
|
||||
return False
|
||||
if val[1] and count.get(key, 0) > val[1]:
|
||||
if raiseException:
|
||||
m = "{0} components cannot contain more than {1} {2}"
|
||||
raise base.ValidateError(m.format(cls.name, val[1], key))
|
||||
return False
|
||||
return True
|
||||
else:
|
||||
err = "{0} is not a Component or Contentline".format(obj)
|
||||
raise base.VObjectError(err)
|
||||
|
||||
@classmethod
|
||||
def lineValidate(cls, line, raiseException, complainUnrecognized):
|
||||
"""Examine a line's parameters and values, return True if valid."""
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def decode(cls, line):
|
||||
if line.encoded:
|
||||
line.encoded = 0
|
||||
|
||||
@classmethod
|
||||
def encode(cls, line):
|
||||
if not line.encoded:
|
||||
line.encoded = 1
|
||||
|
||||
@classmethod
|
||||
def transformToNative(cls, obj):
|
||||
"""
|
||||
Turn a ContentLine or Component into a Python-native representation.
|
||||
|
||||
If appropriate, turn dates or datetime strings into Python objects.
|
||||
Components containing VTIMEZONEs turn into VtimezoneComponents.
|
||||
|
||||
"""
|
||||
return obj
|
||||
|
||||
@classmethod
|
||||
def transformFromNative(cls, obj):
|
||||
"""
|
||||
Inverse of transformToNative.
|
||||
"""
|
||||
raise base.NativeError("No transformFromNative defined")
|
||||
|
||||
@classmethod
|
||||
def generateImplicitParameters(cls, obj):
|
||||
"""Generate any required information that don't yet exist."""
|
||||
pass
|
||||
|
||||
@classmethod
|
||||
def serialize(cls, obj, buf, lineLength, validate=True):
|
||||
"""
|
||||
Set implicit parameters, do encoding, return unicode string.
|
||||
|
||||
If validate is True, raise VObjectError if the line doesn't validate
|
||||
after implicit parameters are generated.
|
||||
|
||||
Default is to call base.defaultSerialize.
|
||||
|
||||
"""
|
||||
|
||||
cls.generateImplicitParameters(obj)
|
||||
if validate:
|
||||
cls.validate(obj, raiseException=True)
|
||||
|
||||
if obj.isNative:
|
||||
transformed = obj.transformFromNative()
|
||||
undoTransform = True
|
||||
else:
|
||||
transformed = obj
|
||||
undoTransform = False
|
||||
|
||||
out = base.defaultSerialize(transformed, buf, lineLength)
|
||||
if undoTransform:
|
||||
obj.transformToNative()
|
||||
return out
|
||||
|
||||
@classmethod
|
||||
def valueRepr(cls, line):
|
||||
"""return the representation of the given content line value"""
|
||||
return line.value
|
2068
radicale_vobject/icalendar.py
Normal file
2068
radicale_vobject/icalendar.py
Normal file
File diff suppressed because it is too large
Load Diff
377
radicale_vobject/vcard.py
Normal file
377
radicale_vobject/vcard.py
Normal file
@ -0,0 +1,377 @@
|
||||
"""Definitions and behavior for vCard 3.0"""
|
||||
|
||||
import codecs
|
||||
|
||||
from . import behavior
|
||||
|
||||
from .base import ContentLine, registerBehavior, backslashEscape, str_
|
||||
from .icalendar import stringToTextValues, DateOrDateTimeBehavior
|
||||
|
||||
|
||||
# Python 3 no longer has a basestring type, so....
|
||||
try:
|
||||
basestring = basestring
|
||||
except NameError:
|
||||
basestring = (str, bytes)
|
||||
|
||||
# ------------------------ vCard structs ---------------------------------------
|
||||
|
||||
|
||||
class Name(object):
|
||||
def __init__(self, family='', given='', additional='', prefix='',
|
||||
suffix=''):
|
||||
"""
|
||||
Each name attribute can be a string or a list of strings.
|
||||
"""
|
||||
self.family = family
|
||||
self.given = given
|
||||
self.additional = additional
|
||||
self.prefix = prefix
|
||||
self.suffix = suffix
|
||||
|
||||
@staticmethod
|
||||
def toString(val):
|
||||
"""
|
||||
Turn a string or array value into a string.
|
||||
"""
|
||||
if type(val) in (list, tuple):
|
||||
return ' '.join(val)
|
||||
return val
|
||||
|
||||
def __str__(self):
|
||||
eng_order = ('prefix', 'given', 'additional', 'family', 'suffix')
|
||||
out = ' '.join(self.toString(getattr(self, val)) for val in eng_order)
|
||||
return str_(out)
|
||||
|
||||
def __repr__(self):
|
||||
return "<Name: {0!s}>".format(self.__str__())
|
||||
|
||||
def __eq__(self, other):
|
||||
try:
|
||||
return (self.family == other.family and
|
||||
self.given == other.given and
|
||||
self.additional == other.additional and
|
||||
self.prefix == other.prefix and
|
||||
self.suffix == other.suffix)
|
||||
except:
|
||||
return False
|
||||
|
||||
|
||||
class Address(object):
|
||||
def __init__(self, street='', city='', region='', code='',
|
||||
country='', box='', extended=''):
|
||||
"""
|
||||
Each name attribute can be a string or a list of strings.
|
||||
"""
|
||||
self.box = box
|
||||
self.extended = extended
|
||||
self.street = street
|
||||
self.city = city
|
||||
self.region = region
|
||||
self.code = code
|
||||
self.country = country
|
||||
|
||||
@staticmethod
|
||||
def toString(val, join_char='\n'):
|
||||
"""
|
||||
Turn a string or array value into a string.
|
||||
"""
|
||||
if type(val) in (list, tuple):
|
||||
return join_char.join(val)
|
||||
return val
|
||||
|
||||
lines = ('box', 'extended', 'street')
|
||||
one_line = ('city', 'region', 'code')
|
||||
|
||||
def __str__(self):
|
||||
lines = '\n'.join(self.toString(getattr(self, val))
|
||||
for val in self.lines if getattr(self, val))
|
||||
one_line = tuple(self.toString(getattr(self, val), ' ')
|
||||
for val in self.one_line)
|
||||
lines += "\n{0!s}, {1!s} {2!s}".format(*one_line)
|
||||
if self.country:
|
||||
lines += '\n' + self.toString(self.country)
|
||||
return lines
|
||||
|
||||
def __repr__(self):
|
||||
return "<Address: {0!s}>".format(self)
|
||||
|
||||
def __eq__(self, other):
|
||||
try:
|
||||
return (self.box == other.box and
|
||||
self.extended == other.extended and
|
||||
self.street == other.street and
|
||||
self.city == other.city and
|
||||
self.region == other.region and
|
||||
self.code == other.code and
|
||||
self.country == other.country)
|
||||
except:
|
||||
return False
|
||||
|
||||
|
||||
# ------------------------ Registered Behavior subclasses ----------------------
|
||||
|
||||
class VCardTextBehavior(behavior.Behavior):
|
||||
"""
|
||||
Provide backslash escape encoding/decoding for single valued properties.
|
||||
|
||||
TextBehavior also deals with base64 encoding if the ENCODING parameter is
|
||||
explicitly set to BASE64.
|
||||
"""
|
||||
allowGroup = True
|
||||
base64string = 'B'
|
||||
|
||||
@classmethod
|
||||
def decode(cls, line):
|
||||
"""
|
||||
Remove backslash escaping from line.valueDecode line, either to remove
|
||||
backslash espacing, or to decode base64 encoding. The content line should
|
||||
contain a ENCODING=b for base64 encoding, but Apple Addressbook seems to
|
||||
export a singleton parameter of 'BASE64', which does not match the 3.0
|
||||
vCard spec. If we encouter that, then we transform the parameter to
|
||||
ENCODING=b
|
||||
"""
|
||||
if line.encoded:
|
||||
if 'BASE64' in line.singletonparams:
|
||||
line.singletonparams.remove('BASE64')
|
||||
line.encoding_param = cls.base64string
|
||||
encoding = getattr(line, 'encoding_param', None)
|
||||
if encoding:
|
||||
if isinstance(line.value, bytes):
|
||||
line.value = codecs.decode(line.value, "base64")
|
||||
else:
|
||||
line.value = codecs.decode(line.value.encode("utf-8"), "base64")
|
||||
else:
|
||||
line.value = stringToTextValues(line.value)[0]
|
||||
line.encoded = False
|
||||
|
||||
@classmethod
|
||||
def encode(cls, line):
|
||||
"""
|
||||
Backslash escape line.value.
|
||||
"""
|
||||
if not line.encoded:
|
||||
encoding = getattr(line, 'encoding_param', None)
|
||||
if encoding and encoding.upper() == cls.base64string:
|
||||
if isinstance(line.value, bytes):
|
||||
line.value = codecs.encode(line.value, "base64").decode("utf-8").replace('\n', '')
|
||||
else:
|
||||
line.value = codecs.encode(line.value.encode(encoding), "base64").decode("utf-8")
|
||||
else:
|
||||
line.value = backslashEscape(line.value)
|
||||
line.encoded = True
|
||||
|
||||
|
||||
class VCardBehavior(behavior.Behavior):
|
||||
allowGroup = True
|
||||
defaultBehavior = VCardTextBehavior
|
||||
|
||||
|
||||
class VCard3_0(VCardBehavior):
|
||||
"""
|
||||
vCard 3.0 behavior.
|
||||
"""
|
||||
name = 'VCARD'
|
||||
description = 'vCard 3.0, defined in rfc2426'
|
||||
versionString = '3.0'
|
||||
isComponent = True
|
||||
sortFirst = ('version', 'prodid', 'uid')
|
||||
knownChildren = {
|
||||
'N': (0, 1, None), # min, max, behaviorRegistry id
|
||||
'FN': (1, None, None),
|
||||
'VERSION': (1, 1, None), # required, auto-generated
|
||||
'PRODID': (0, 1, None),
|
||||
'LABEL': (0, None, None),
|
||||
'UID': (0, None, None),
|
||||
'ADR': (0, None, None),
|
||||
'ORG': (0, None, None),
|
||||
'PHOTO': (0, None, None),
|
||||
'CATEGORIES': (0, None, None),
|
||||
'REV': (0, 1, None),
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def generateImplicitParameters(cls, obj):
|
||||
"""
|
||||
Create PRODID, VERSION, and VTIMEZONEs if needed.
|
||||
|
||||
VTIMEZONEs will need to exist whenever TZID parameters exist or when
|
||||
datetimes with tzinfo exist.
|
||||
"""
|
||||
if not hasattr(obj, 'version'):
|
||||
obj.add(ContentLine('VERSION', [], cls.versionString))
|
||||
registerBehavior(VCard3_0, default=True)
|
||||
|
||||
|
||||
class FN(VCardTextBehavior):
|
||||
name = "FN"
|
||||
description = 'Formatted name'
|
||||
registerBehavior(FN)
|
||||
|
||||
|
||||
class Label(VCardTextBehavior):
|
||||
name = "Label"
|
||||
description = 'Formatted address'
|
||||
registerBehavior(Label)
|
||||
|
||||
|
||||
class REV(DateOrDateTimeBehavior):
|
||||
name = "REV"
|
||||
description = 'Current revision of this vCard'
|
||||
registerBehavior(REV)
|
||||
|
||||
wacky_apple_photo_serialize = True
|
||||
REALLY_LARGE = 1E50
|
||||
|
||||
|
||||
class Photo(VCardTextBehavior):
|
||||
name = "Photo"
|
||||
description = 'Photograph'
|
||||
|
||||
@classmethod
|
||||
def valueRepr(cls, line):
|
||||
return " (BINARY PHOTO DATA at 0x{0!s}) ".format(id(line.value))
|
||||
|
||||
@classmethod
|
||||
def serialize(cls, obj, buf, lineLength, validate):
|
||||
"""
|
||||
Apple's Address Book is *really* weird with images, it expects
|
||||
base64 data to have very specific whitespace. It seems Address Book
|
||||
can handle PHOTO if it's not wrapped, so don't wrap it.
|
||||
"""
|
||||
if wacky_apple_photo_serialize:
|
||||
lineLength = REALLY_LARGE
|
||||
VCardTextBehavior.serialize(obj, buf, lineLength, validate)
|
||||
|
||||
registerBehavior(Photo)
|
||||
|
||||
|
||||
def toListOrString(string):
|
||||
stringList = stringToTextValues(string)
|
||||
if len(stringList) == 1:
|
||||
return stringList[0]
|
||||
else:
|
||||
return stringList
|
||||
|
||||
|
||||
def splitFields(string):
|
||||
"""
|
||||
Return a list of strings or lists from a Name or Address.
|
||||
"""
|
||||
return [toListOrString(i) for i in
|
||||
stringToTextValues(string, listSeparator=';', charList=';')]
|
||||
|
||||
|
||||
def toList(stringOrList):
|
||||
if isinstance(stringOrList, basestring):
|
||||
return [stringOrList]
|
||||
return stringOrList
|
||||
|
||||
|
||||
def serializeFields(obj, order=None):
|
||||
"""
|
||||
Turn an object's fields into a ';' and ',' seperated string.
|
||||
|
||||
If order is None, obj should be a list, backslash escape each field and
|
||||
return a ';' separated string.
|
||||
"""
|
||||
fields = []
|
||||
if order is None:
|
||||
fields = [backslashEscape(val) for val in obj]
|
||||
else:
|
||||
for field in order:
|
||||
escapedValueList = [backslashEscape(val) for val in
|
||||
toList(getattr(obj, field))]
|
||||
fields.append(','.join(escapedValueList))
|
||||
return ';'.join(fields)
|
||||
|
||||
|
||||
NAME_ORDER = ('family', 'given', 'additional', 'prefix', 'suffix')
|
||||
ADDRESS_ORDER = ('box', 'extended', 'street', 'city', 'region', 'code',
|
||||
'country')
|
||||
|
||||
|
||||
class NameBehavior(VCardBehavior):
|
||||
"""
|
||||
A structured name.
|
||||
"""
|
||||
hasNative = True
|
||||
|
||||
@staticmethod
|
||||
def transformToNative(obj):
|
||||
"""
|
||||
Turn obj.value into a Name.
|
||||
"""
|
||||
if obj.isNative:
|
||||
return obj
|
||||
obj.isNative = True
|
||||
obj.value = Name(**dict(zip(NAME_ORDER, splitFields(obj.value))))
|
||||
return obj
|
||||
|
||||
@staticmethod
|
||||
def transformFromNative(obj):
|
||||
"""
|
||||
Replace the Name in obj.value with a string.
|
||||
"""
|
||||
obj.isNative = False
|
||||
obj.value = serializeFields(obj.value, NAME_ORDER)
|
||||
return obj
|
||||
registerBehavior(NameBehavior, 'N')
|
||||
|
||||
|
||||
class AddressBehavior(VCardBehavior):
|
||||
"""
|
||||
A structured address.
|
||||
"""
|
||||
hasNative = True
|
||||
|
||||
@staticmethod
|
||||
def transformToNative(obj):
|
||||
"""
|
||||
Turn obj.value into an Address.
|
||||
"""
|
||||
if obj.isNative:
|
||||
return obj
|
||||
obj.isNative = True
|
||||
obj.value = Address(**dict(zip(ADDRESS_ORDER, splitFields(obj.value))))
|
||||
return obj
|
||||
|
||||
@staticmethod
|
||||
def transformFromNative(obj):
|
||||
"""
|
||||
Replace the Address in obj.value with a string.
|
||||
"""
|
||||
obj.isNative = False
|
||||
obj.value = serializeFields(obj.value, ADDRESS_ORDER)
|
||||
return obj
|
||||
registerBehavior(AddressBehavior, 'ADR')
|
||||
|
||||
|
||||
class OrgBehavior(VCardBehavior):
|
||||
"""
|
||||
A list of organization values and sub-organization values.
|
||||
"""
|
||||
hasNative = True
|
||||
|
||||
@staticmethod
|
||||
def transformToNative(obj):
|
||||
"""
|
||||
Turn obj.value into a list.
|
||||
"""
|
||||
if obj.isNative:
|
||||
return obj
|
||||
obj.isNative = True
|
||||
obj.value = splitFields(obj.value)
|
||||
return obj
|
||||
|
||||
@staticmethod
|
||||
def transformFromNative(obj):
|
||||
"""
|
||||
Replace the list in obj.value with a string.
|
||||
"""
|
||||
if not obj.isNative:
|
||||
return obj
|
||||
obj.isNative = False
|
||||
obj.value = serializeFields(obj.value)
|
||||
return obj
|
||||
registerBehavior(OrgBehavior, 'ORG')
|
@ -6,4 +6,4 @@ python-tag = py3
|
||||
|
||||
[tool:pytest]
|
||||
addopts = --flake8 --isort --cov radicale -r s
|
||||
norecursedirs = dist .cache .git build Radicale.egg-info .eggs venv
|
||||
norecursedirs = dist .cache .git build Radicale.egg-info .eggs venv radicale_vobject
|
||||
|
4
setup.py
Normal file → Executable file
4
setup.py
Normal file → Executable file
@ -63,10 +63,10 @@ setup(
|
||||
"Radicale-%s.tar.gz" % VERSION),
|
||||
license="GNU GPL v3",
|
||||
platforms="Any",
|
||||
packages=["radicale"],
|
||||
packages=["radicale", "radicale_vobject"],
|
||||
package_data={"radicale": WEB_FILES},
|
||||
entry_points={"console_scripts": ["radicale = radicale.__main__:run"]},
|
||||
install_requires=["vobject==0.9.5", "python-dateutil==2.6.1"],
|
||||
install_requires=["python-dateutil==2.6.1"],
|
||||
setup_requires=pytest_runner,
|
||||
tests_require=tests_require,
|
||||
extras_require={
|
||||
|
Loading…
Reference in New Issue
Block a user