././@PaxHeader 0000000 0000000 0000000 00000000033 00000000000 011451 x ustar 00 0000000 0000000 27 mtime=1574455519.232302
caldav-0.6.2/ 0000755 0016331 0016331 00000000000 00000000000 013540 5 ustar 00tobias tobias 0000000 0000000 ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1568132280.0
caldav-0.6.2/COPYING.APACHE 0000644 0016331 0016331 00000026136 00000000000 015523 0 ustar 00tobias tobias 0000000 0000000
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.
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1568132280.0
caldav-0.6.2/COPYING.GPL 0000644 0016331 0016331 00000104513 00000000000 015220 0 ustar 00tobias tobias 0000000 0000000 GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1568132280.0
caldav-0.6.2/ChangeLog 0000644 0016331 0016331 00000057730 00000000000 015326 0 ustar 00tobias tobias 0000000 0000000 2019-05-29 Tobias Brox
* .travis.yml - xandikos cannot be installed on python2.7, but we still want to run the available tests
* caldav/lib/error.py - ProppatchError was not defined, ref https://github.com/python-caldav/caldav/issues/54. Also added a common base class DAVError, and made sure the error referenced in #54 will never reappear, even if new methods are added to DAVClient.
* tests/test_caldav.py - testing that the bug referenced in #54 has been properly plugged in caldav/lib/error.py
* caldav/elements/cdav.py - fixing a retention problem - the timezone fixes done recently was not compatible with python 2.7 nor 3.5.
* caldav/objects.py - revisiting https://github.com/python-caldav/caldav/issues/54 - "... is not None" feels more kosher than "... != None", and added TODO-comment that we need to do more research when those variables are None. Bugfix on the error handling for multi-status-return, should return the specific error code and error message found, not the "207 Multi-Status".
* setup.py - reintroducing dependencies pytz and tzlocal - but only for old python versions
* tests/conf.py - test_xandikos should be defaulted to False if xandikos not present (as it can never be present on 2.7)
* tests/test_cdav.py - make the test python2.7-compatible (though some of the testing is a bit moot, as same code path is used in code and in test)
2019-05-28 Tobias Brox
* .travis.yml - ref https://github.com/python-caldav/caldav/issues/57, fixing automated test runs after each commit and on each pull request.
* setup.py - new default tests depends on xandikos
* tests/conf.py - new defaults - testing towards external unreliable public test servers are disabled by default, an internal xandikos server is set up and tests are by default run towards that one
* tests/conf_private.py.EXAMPLE - new file, setting an example on how to run tests towards personal servers
* tests/test_caldav.py - added a test class that spawns a xandikos server instance and runs the functional test suite towards it. Unfortunately it only works under python3. Ref https://github.com/python-caldav/caldav/issues/46
2019-05-19 Jelmer Vernooij
* caldav/objects.py - bugfixing
2019-05-19 Achim Herwig
* README.md - proper documentation of the dual licensing, ref https://github.com/python-caldav/caldav/issues/60
2019-05-17 Achim Herwig
* caldav/objects.py - bugfixing
* caldav/elements/cdav.py - more work on timezone handling, ref https://github.com/python-caldav/caldav/issues/55 https://github.com/python-caldav/caldav/issues/52 https://github.com/python-caldav/caldav/pull/59 etc
2019-05-06 Tobias Brox
* caldav/objects.py - yet another attempt on fixing the timezone handling mess, ref https://github.com/python-caldav/caldav/issues/55 https://github.com/python-caldav/caldav/issues/52 etc
2019-04-21 Mark Meijer
* caldav/objects.py - fixes (or workarounds?) that solves real-world issues with iCloud and MS Exchange. Ref https://github.com/python-caldav/caldav/pull/56
2019-04-09 Cyril Robert
* setup.py - Update to 0.6.1 to fix a tagging issue
2019-04-06 Achim Herwig
* caldav/objects.py - bugfix, ref #52
2019-03-11 Tomáš Chvátal
* MANIFEST.in - Include tests and changelog in pypi sdist tarball, ref https://github.com/python-caldav/caldav/pull/49
2019-03-11 Tobias Brox
* caldav/objects.py - bugfix: accept text/calendar (required for fetching calendar items from the xandikos server, ref https://github.com/python-caldav/caldav/issues/40
2019-03-10 Tobias Brox
* setup.py - pushed the version number to 0.6.0, preparing for release
* ChangeLog - updated with most of the activity since 2017-02
* caldav/objects.py - "expand" in the date_search should be optional.
2019-03-09 Tobias Brox
* caldav/objects.py - preparing for introducing support for the icalendar module and making the vobject support a legacy thing. Delaying instantiation of vobject. Compatibility fix required by the xandikos server implementation.
2019-03-08 Tobias Brox
* caldav/elements/cdav.py - proper timezone support, the support made by Alghost was not following the standard, and caused breakage with one of the servers. Caveat: In 0.5.0, a timestamp date_search was assumed to be UTC, with the patch from Alghost a timestamp without tzinfo was passed without any time zone info (and possibly interpreted to be in the same time zone as the caldav server), with this patch it's assumed to be in the clients local timezone. Backward compatibility may be slightly broken (and test results may depend on the time zone the tests are run under)
* setup.py - now we're dependent on pytz and tzlocal
* caldav/object.py - some caldav servers don't want to give us all pending TODOs in one query. Working around it. Credits to mayjs for pointing out this issue and attempting to solve it.
* test/caldav_test.py - letting one of the VTODO items in the test file be without a defined STATUS.
2018-12-05 Notmarrco
* caldav/elements/dav.py - add GetEtag
2018-09-13 Diane Trout
* setup.py - move out test dependencies
2017-12-28 Earl Chew
* caldav/objects.py - bugfix
2017-12-25 Earl Chew
* caldav/elements/cdav.py - allow Expand tag to be used with open-ended start
2017-12-04 Will Ross
* example/icloud_example.py - misc cleanup
2017-11-20 Matthias Bilger
* caldav/lib/namespace.py - Added Apple ical namespace and properties
2017-08-09 Ian Bottomley
* example/icloud_example.py - some code snippet showing one way to access calendaring information through iCloud
2017-06-01 Andrei Martsinchyk
* caldav/objects.py - Bugfixing and tweaking, ref https://github.com/python-caldav/caldav/issues/11
2017-05-30 Tobias Brox
* caldav/davclient.py - bugfix, ref
https://github.com/python-caldav/caldav/issues/12 and
https://github.com/python-caldav/caldav/issues/7
Credits to Andrei Martsinchyk
2017-05-06 Johannes Ammon
* tests/test_caldav.py - bugfixing, introducing six library, disabling warnings
* caldav/davclient.py - introducing six library
* caldav/element/base.py - introducing six library
* caldav/lib/python_utilities.py - introducing six library
* caldav/lib/url.py - introducing six library
* tests/proxy.py - introducing six library
* * - PEP8
2017-02-03 Tobias Brox
* setup.py - bugfix, credits to slavkoja
2017-01-26 Tobias Brox
* tests/test_caldav.py - support for unique calendar IDs in the
test framework. Should make it possible to run tests in parallell
against the same server and user
2017-01-26 Phyks (Lucas Verney)
* caldav/objects.py - enhancement: add the ability to add events to
calendar using directly a vobject object, and not necessarily an ical
string.
2017-01-24 Tobias Brox
* caldav/objects.py - bugfix: uid handling while fetching
elements, ref
https://bitbucket.org/cyrilrbt/caldav/issues/54/wrong-uid-fetching-in-calendarevent_by_uid
- credits to Lucas Verney
* tests/conf.py - make it easier to override the public test
servers and run tests exclusively against custom test servers
2017-01-23 Cyril Roberts
* README.md - Changed the documentation to follow github
standards, while moving the project from bitbucket/hg to
github/git
2017-01-22 Tobias Brox
* caldav/objects.py - bugfix: after a zimbra upgrade, tests started breaking again as the data from the server was urlencoded. Merged in bugfix for bitbucket issue #46
2017-01-03 Tobias Brox
* caldav/elements/cdav.py, caldav/objects.py: found a
Calendar-Collection tag that was nowhere to be found in the RFC,
and that also caused tests to break against some caldav servers.
2016-05-15 Alex Martin
* caldav/objects.py - bugfix, ref pull request #21
2016-10-07 Benedykt Przybyło
* caldav/elements/cdav.py - bugfix, Fixed namespace for Mkcalendar.
2016-04-25 Tobias Brox
* caldav/objects.py - adjustments for changes in the vobject module
2016-04-07 Johan Olofsson
* caldav/objects.py - add a displayName prop query to the
calendars() method, ref issue #51
2016-03-09 Rian Hunter
* caldav/objects.py - added todo_by_uid() method
2016-02-03 Johan Olofsson
* caldav/objects.py - add a displayName prop query to the
calendars() method, ref issue #51
2016-01-20 Tobias Brox
* setup.py - missing shebang, problem observed by jbar@freenode, #calendar-cli
* caldav/objects.py - bugfix for problem observed by jbar@freenode, #calendar-cli
2015-11-16 Tobias Brox
* caldav/objects.py, caldav/elements/cdav.py - attempt on solving bitbucket issue #40
2015-08-15 Tobias Brox
* caldav/objects.py, caldav/__init__.py - vobjects did not support
python3, so move the "import"-statement so everything not
dependent on vobjects can work under python3.
2015-08-11 Tobias Brox
* caldav/objects.py - support for http return code 207 multi status from server
2015-05-21 Jochen Sprickerhof
* caldav/objects.py - proper fix for issue #43
2015-05-20 Tobias Brox
* caldav/objects.py - allow copying objects. Needed for the
recurring todo completed functionality in calendar-cli. Fixed
bitbucket issue #43 (compatbility fix). Polishing some error
messages.
2015-05-17 Tobias Brox
* caldav/objects.py - sorting todo events by due date or dstart.
Feature needed by the calendar-cli task management.
2015-04-27 Tobias Brox
* caldav/objects.py - generalized the calendar date search so
todo-events also can be searched by date. The calendar-cli task
handling depends on this.
2015-04-25 Tobias Brox
* caldav/objects.py - generalized the code a bit, added a
method object_by_uid and made event_by_uid a wrapper around this
one. Added improved sorting functionality. The task handling in
calendar-cli is dependent on those features.
2015-04-21 Tobias Brox
* caldav/elements/cdav.py - now support for the free-busy-query element.
* caldav/objects.py - added FreeBusy and Journal objects, plus
calendar methods to retrieve them, and for adding journal entries.
* caldav/tests/test_caldav.py - added tests to add and fetch
journal entries, and to request freebusy information.
2015-04-16 Tobias Brox
* caldav/lib/error.py - added error class for the propfind method.
Made a dict index for method name -> exception class.
* caldav/elements/cdav.py - bugfix - "negate-condition", not
"negate" in the TextMatch class. Added
SupportedCalendarComponentSet class.
* caldav/elements/davclient.py - obscured the API a bit by
allowing a dummy parameter to be passed to various methods. Not
very nice, but needed for the refactoring work in objects.py.
* caldav/objects.py - VTODO support, new class for Todo-items with
method for completing the task. Calendar creation methods takes a
list of supported element types as optional parameter. Quite some
refactoring, consolidating similar-looking code. Minor bugfix
with the event date search - asking for an expanded event list
with an open end date is not supported by all server
implementations, for obvious reasons. Brushed up some docstrings
and prefixed some internal methods with underscore.
* caldav/tests/test_caldav.py - VTODO support, test code that
creates a task list, adds todo-items to it, completes todo-items,
list them out and deletes todo-items.
2015-04-01 Tobias Brox
* caldav/objects.py - started working on VTODO support
* caldav/tests/test_caldav.py - started working on VTODO support
2015-04-01 Tobias Brox
* caldav/lib/url.py - work on python3-support
* tests/conf.py - work on python3-support
2015-03-29 Tobias Brox
* caldav/objects.py - work on iCloud support. Solves issue #38,
read-only access to iCloud seems to work. Writing still fails,
ref issue #40.
2015-03-19 Tobias Brox
* tests/conf.py - ignore ImportError when importing conf_private,
but not other exceptions. This way conf_private will be ignored
if it doesn't exist, but if there are syntax error, nosetest should
bark.
2015-03-15 Tobias Brox
* caldav/lib/python_utilities.py - fixing broken charset
2015-02-26 Jack Laxson
* setup.py - remove sphinx from install_requires as it is huge and only used
for generating the documentation.
2015-02-23 Luke
* Interceptable logging
2015-02-16 Luke
* python3 support
2015-02-14 Tobias Brox
* tests/test_caldav.py - new test that deletes events
2015-01-24 Tobias Brox
* caldav/davclient.py - support for digest auth and self-signed
SSL certs, re issue #26 and #34.
* tests/test_caldav.py - more generic URL checks to discover
owncloud and baikal servers.
2015-01-21 Tobias Brox
* caldav/lib/url.py - workaround: "unauth"-method added port
":None" if no port were given.
2015-01-19 Tobias Brox
* caldav/lib/url.py - added method strip_trailing_slash
* caldav/objects.py - test breakages on several server
implementations after the trailing slashes were removed. Made a
workaround, though this issue should be investigated better.
2014-05-27 Christian Roeder
* caldav/davclient.py - RFC compliance fix; Use capitalised Depth:
Header
2014-05-27 Tobias Brox
* caldav/lib/url.py - Workaround for Zimbra; Zimbra generates
non-ascii URLs when using non-ascii characters in the calendar
name, hence the URL library must accept non-ascii characters.
2014-05-27 Tobias Brox
* setup.py - include the requests library dependency
2014-05-20 Christian Roeder
* caldav/lib/url.py - Do not remove trailing slashes of all URLs.
According to the RFC, all collection URLs should end with a
trailing slash, though most caldav server implementations will
handle URLs with and without trailing slashes the same.
2014-05-11 Abdul Rehman Gani
* caldav/davclient.py - Change to use the requests library. Fixes
several compatibility-issues, i.e. with iCloud a get_properties
call would fail with a Path Handling exception. Happens when
httplib specifies the netloc in the HTTP request, and the returned
xml has the base path equal to that netloc instead of the path.
2014-04-13 Abdul Rehman Gani
* caldav/davclient.py - Removed extraneous parameter passed to
getresponse(); bugfix in a section not covered by test code
2014-03-14 Tobias Brox
* General - more verbose documentation
* caldav/test_caldav.py - added an exception for OwnCloud, it does
not support open-ended date searches
2014-03-12 Tobias Brox
* setup.py - version bump (0.2.2)
* caldav/lib/url.py - battle hardening
* caldav/objects.py - allowing for relative URLs to be used
* caldav/test_caldav.py - test that relative URLs works as expected
* caldav/test_caldav.py - test that the URL library is robust
2014-03-07 Tobias Brox
* caldav/davclient.py - minor api difference; it feels more
object-oriented to write principal = client.principal() than
principal = Principal(client)
* caldav/tests/test_caldav.py - work to reflect the above
* docs/source/index.rst - work to reflect the above
* docs/source/index.rst - added documentation that the tests may
fail if several test runs are performed simultaneously
* caldav/davclient.py - support for unicode and utf8
* caldav/lib/url.py - support for unicode and utf8
* caldav/objects.py - minor doc enhancement
* tests/test_caldav.py - load an event or a calendar by the URL
* tests/test_caldav.py - test calendar.events()
* tests/test_caldav.py - test utf8 and unicode
* docs/source/index.rst - documentation on how to run the test
suite towards private calendar servers
* setup.py - version bump (0.2.1)
2014-03-01 Tobias Brox
* caldav/lib/url.py (make): function for backward compatibility
* tests/: more test code, including backward compatibility test
2014-02-16 Tobias Brox
* caldav/lib/namespace.py: fixing issue
https://bitbucket.org/cyrilrbt/caldav/issue/29/centos59-minifix
2013-12-12 Tobias Brox
* caldav/objects.py (Calendar): compatibility hack for zimbra -
gotcha! Use Calendar display name in the Calendar URL instead of
Calendar ID.
* caldav/objects.py: internal change - _create method now returns
nothing, but sets self.url and self.id instead.
2013-12-11 Tobias Brox
* caldav/objects.py (DAVObject): convenience fix - made client a
conditional parameter to __init__. Defaults to parent.client if
parent is given.
* caldav/objects.py (Calendar): convenience fix - made methods
Calendar.event_by_uid and Calendar.event_by_url. Calendar.event
is an alias to Calendar.event_by_uid for backwards compatibility.
Those methods also loads the object from the remote server (hmmm
... does that make sense, it's inconsistent with the
CalendarSet.calendar method)
* caldav/objects.py (Event): a potential compatibility fix - when
creating an event, some servers seems to want the uid to match the
URL (zimbra will yield 302 on the PUT request). However, I wasn't
able to GET the event from zimbra, neither before nor after this
fix :-(
* caldav/elements/cdav.py: compatibility fix - collation
"i; octet" (with whitespace) not recognized by baikal. "i;octet"
(without whitespace) is OK.
2013-12-08 Tobias Brox
* caldav/objects.py (Calendar): Convenience fix: method add_event
for making it easier to add events. Better error handling; if
calendar creation succeeds but setting calendar name fails, delete
the calendar before raising the exception.
* caldav/objects.py (Event): Bugfix for zimbra - 302 is now an
acceptable return code when creating a new event.
2013-12-07 Tobias Brox
* caldav/davclient.py (DAVClient.request, DAVResponse): Full HTTP
communication is now available in debug logs
* caldav/davclient.py (DAVClient.__init__): Username and password
can now (optionally) be given as separate parameters instead of as
a part of the configuration URL
* caldav/objects.py: By now it's sufficient to pass the base URL
while initializing the DAVClient object. The library will find
the principal URL and home calendar set URL through GETPROP
* caldav/objects.py (Calendar): workaround for problem that
calendar name didn't get set on some (all?) caldav servers.
* caldav/objects.py (Principal, CalendarSet): created a method
calendar() to make it easier to generate a calendar object
(without server-side communication), and make_calendar for
creating a new calendar at the server side.
* tests/test_caldav.py: all broken tests have been disabled.
Temporary made smaller tests to demonstrate what is actually
working on all caldav servers I've tested against (Zimbra,
DAViCal, Baikal and SoGo).
* caldav/objects.py (DAVObject): (internal change) set __str__ and
__repr__ to make debugging easier
* caldav/objects.py: (internal change) Since the principal path and the calendar
home set path are different on most CALDav server implementations,
a new class CalendarSet has been made.
* caldav/lib/url.py: (internal change) Complete rewrite and
API-change. internally all URLs are now handled as objects
* caldav/objects.py (Principal): (internal change) made it
possible to set principal.calendar_home_set (hardly useful except
for from the unit testing code).
* All files: misc minor changes to reflect all the changes above.
2011-01-22 Cyril Robert
* caldav/elements/cdav.py (Expand.__init__,
TimeRange.__init__) : Fixed strftime fmt.
2010-10-09 Cyril Robert
* All files: Made PEP8 compliant
2010-10-04 Olivier Larchevêque
* caldav/davclient.py (DAVClient.request): fix headers merge before sending request
* caldav/objects.py (Event.__init__): fix for respecting davobject signature
2010-07-15 Cyril Robert
* caldav/davclient.py (DAVClient.__init__): Fixed an issue with usernames
that contain a '@'.
Thanks to the reporter of issue #2
2010-07-07 Mark Meyer
* caldav/elements/cdav.py: Add Calendar, representing the calendar
resource type.
* caldav/objects.py (DAVObject.children): Pull in code from
_get_properties to enable PROPFINDs for properties with complex
values.
* caldav/objects.py (DAVObject.properties): Add a warning message.
* caldav/objects.py (Principal.calendars): retrieve only child
collections that have a cdav.Calendar property.
2010-07-06 Mark Meyer
* caldav/objects.py (DAVObject.save): Use idiomatic
NotImplementedError and add a docstring
* caldav/davclient.py (DAVObject.request): raise error on a http
unauthorized (400) condition.
2010-07-06 Cyril Robert
* caldav/elements/base.py (BaseElement.__add__): Removed unnecessary
verification.
* caldav/objects.py: Merged all methods from caldav.lib.commands.
* caldav/commands.py: Removed, no longer needed.
2010-07-05 Cyril Robert
* caldav/lib/commands.py (date_search): Fixed a typo.
* caldav/lib/error.py (AuthorizationError): Added AuthorizationError.
* caldav/davclient.py (DAVClient.request): Added 403 error handling.
* caldav/davclient.py (DAVClient.__init__): Always pass proper Content-Type
and Accept headers to the server. This is required by at least davical.
Thanks to http://bitbucket.org/ofosos (all of the above)
2010-07-02 Cyril Robert
* caldav/lib/commands.py (get_properties): Merged patch from issue #1.
Thanks to http://bitbucket.org/ofosos
2010-06-29 Cyril Robert
* caldav/elements/*.py: New files, definition for many dav and caldav
elements to introduce a somewhat major refactoring.
* caldav/davclient.py (DAVClient.propfind): Fixed documentation.
* caldav/lib/commands.py: Major changes throughout the file to make use of
the newly defined classes.
* caldav/objects.py: Many small changes to the documentation an the usage
of the ns method.
2010-06-14 Cyril Robert
* caldav/davclient.py (DAVClient.put): Added a new "headers" parameter.
* caldav/lib/commands.py (create_event): Added headers for content-type.
* caldav/lib/commands.py: Added basic error management throughout the file.
* caldav/objects.py: Minor improvements.
* caldav/lib/error.py: New file, contains error definitions.
2010-06-09 Cyril Robert
* caldav/davclient.py (DAVClient.__init__, DAVClient.request): Added
support for an optional http proxy.
* tests/test_caldav.py (TestCalDAV.testProxy): Added a new test for the
new proxy option.
* tests/test_caldav.py (TestCalDAV.testSSL): Added one more test.
* caldav/lib/commands.py (uid_search): Added new method.
* caldav/objects.py (Calendar.event): Added new method to find an event by
its UID.
* tests/test_caldav.py: Added a quick test for the new methods
2010-06-07 Cyril Robert
* caldav/lib/commands.py (children, date_search): Removed instanciation of
children / events, it should be done in objects.
* caldav/objects.py (Calendar.events, Principal.calendars,
Calendar.date_search): Made changes according to the new commands.children
method. Moved ugly import.
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1568132280.0
caldav-0.6.2/MANIFEST.in 0000644 0016331 0016331 00000000076 00000000000 015301 0 ustar 00tobias tobias 0000000 0000000 include COPYING.*
include ChangeLog
recursive-include tests *
././@PaxHeader 0000000 0000000 0000000 00000000033 00000000000 011451 x ustar 00 0000000 0000000 27 mtime=1574455519.232302
caldav-0.6.2/PKG-INFO 0000644 0016331 0016331 00000001246 00000000000 014640 0 ustar 00tobias tobias 0000000 0000000 Metadata-Version: 1.1
Name: caldav
Version: 0.6.2
Summary: CalDAV (RFC4791) client library
Home-page: http://bitbucket.org/cyrilrbt/caldav
Author: Cyril Robert
Author-email: cyril@hippie.io
License: GPL
Description: UNKNOWN
Platform: UNKNOWN
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: GNU General Public License (GPL)
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python
Classifier: Topic :: Office/Business :: Scheduling
Classifier: Topic :: Software Development :: Libraries :: Python Modules
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1568132280.0
caldav-0.6.2/README.md 0000644 0016331 0016331 00000000530 00000000000 015015 0 ustar 00tobias tobias 0000000 0000000 # caldav
This project is a CalDAV ([RFC4791](http://www.ietf.org/rfc/rfc4791.txt)) client library for Python.
* [Pypi](http://pypi.python.org/pypi/caldav)
* [Documentation](http://packages.python.org/caldav)
Caldav is dual-licensed under the [GNU GENERAL PUBLIC LICENSE Version 3](COPYING.GPL) and the [Apache License 2.0](COPYING.APACHE). ././@PaxHeader 0000000 0000000 0000000 00000000033 00000000000 011451 x ustar 00 0000000 0000000 27 mtime=1574455519.222302
caldav-0.6.2/caldav/ 0000755 0016331 0016331 00000000000 00000000000 014772 5 ustar 00tobias tobias 0000000 0000000 ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1568132280.0
caldav-0.6.2/caldav/__init__.py 0000644 0016331 0016331 00000000734 00000000000 017107 0 ustar 00tobias tobias 0000000 0000000 #!/usr/bin/env python
from .davclient import DAVClient
from .objects import *
# possibly a bug in the tBaxter fork of vobject, this one has to be
# imported explicitly to make sure the attribute behaviour gets
# correctly loaded:
from vobject import icalendar
import logging
# Silence notification of no default logging handler
log = logging.getLogger("caldav")
class NullHandler(logging.Handler):
def emit(self, record):
pass
log.addHandler(NullHandler())
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1568132280.0
caldav-0.6.2/caldav/davclient.py 0000644 0016331 0016331 00000020145 00000000000 017317 0 ustar 00tobias tobias 0000000 0000000 #!/usr/bin/env python
# -*- encoding: utf-8 -*-
import logging
import re
import requests
import six
from caldav.lib.python_utilities import to_wire
from lxml import etree
from caldav.lib import error
from caldav.lib.url import URL
from caldav.objects import Principal
if six.PY3:
from urllib.parse import unquote
else:
from urlparse import unquote
log = logging.getLogger('caldav')
class DAVResponse:
"""
This class is a response from a DAV request. It is instantiated from
the DAVClient class. End users of the library should not need to
know anything about this class. Since we often get XML responses,
it tries to parse it into `self.tree`
"""
raw = ""
reason = ""
tree = None
headers = {}
status = 0
def __init__(self, response):
self.raw = response.content
self.headers = response.headers
self.status = response.status_code
self.reason = response.reason
log.debug("response headers: " + str(self.headers))
log.debug("response status: " + str(self.status))
log.debug("raw response: " + str(self.raw))
try:
self.tree = etree.XML(self.raw)
except:
self.tree = None
class DAVClient:
"""
Basic client for webdav, uses the requests lib; gives access to
low-level operations towards the caldav server.
Unless you have special needs, you should probably care most about
the __init__ and principal methods.
"""
proxy = None
url = None
def __init__(self, url, proxy=None, username=None, password=None,
auth=None, ssl_verify_cert=True):
"""
Sets up a HTTPConnection object towards the server in the url.
Parameters:
* url: A fully qualified url: `scheme://user:pass@hostname:port`
* proxy: A string defining a proxy server: `hostname:port`
* username and password should be passed as arguments or in the URL
* auth and ssl_verify_cert is passed to requests.request.
** ssl_verify_cert can be the path of a CA-bundle or False.
"""
log.debug("url: " + str(url))
self.url = URL.objectify(url)
# Prepare proxy info
if proxy is not None:
self.proxy = proxy
# requests library expects the proxy url to have a scheme
if re.match('^.*://', proxy) is None:
self.proxy = self.url.scheme + '://' + proxy
# add a port is one is not specified
# TODO: this will break if using basic auth and embedding
# username:password in the proxy URL
p = self.proxy.split(":")
if len(p) == 2:
self.proxy += ':8080'
log.debug("init - proxy: %s" % (self.proxy))
# Build global headers
self.headers = {"User-Agent": "Mozilla/5.0",
"Content-Type": "text/xml",
"Accept": "text/xml, text/calendar"}
if self.url.username is not None:
username = unquote(self.url.username)
password = unquote(self.url.password)
self.username = username
self.password = password
self.auth = auth
# TODO: it's possible to force through a specific auth method here,
# but no test code for this.
self.ssl_verify_cert = ssl_verify_cert
self.url = self.url.unauth()
log.debug("self.url: " + str(url))
def principal(self):
"""
Convenience method, it gives a bit more object-oriented feel to
write client.principal() than Principal(client).
This method returns a :class:`caldav.Principal` object, with
higher-level methods for dealing with the principals
calendars.
"""
return Principal(self)
def propfind(self, url=None, props="", depth=0):
"""
Send a propfind request.
Parameters:
* url: url for the root of the propfind.
* props = (xml request), properties we want
* depth: maximum recursion depth
Returns
* DAVResponse
"""
return self.request(url or self.url, "PROPFIND", props,
{'Depth': str(depth)})
def proppatch(self, url, body, dummy=None):
"""
Send a proppatch request.
Parameters:
* url: url for the root of the propfind.
* body: XML propertyupdate request
* dummy: compatibility parameter
Returns
* DAVResponse
"""
return self.request(url, "PROPPATCH", body)
def report(self, url, query="", depth=0):
"""
Send a report request.
Parameters:
* url: url for the root of the propfind.
* query: XML request
* depth: maximum recursion depth
Returns
* DAVResponse
"""
return self.request(url, "REPORT", query,
{'Depth': str(depth), "Content-Type":
"application/xml; charset=\"utf-8\""})
def mkcol(self, url, body, dummy=None):
"""
Send a mkcol request.
Parameters:
* url: url for the root of the mkcol
* body: XML request
* dummy: compatibility parameter
Returns
* DAVResponse
"""
return self.request(url, "MKCOL", body)
def mkcalendar(self, url, body="", dummy=None):
"""
Send a mkcalendar request.
Parameters:
* url: url for the root of the mkcalendar
* body: XML request
* dummy: compatibility parameter
Returns
* DAVResponse
"""
return self.request(url, "MKCALENDAR", body)
def put(self, url, body, headers={}):
"""
Send a put request.
"""
return self.request(url, "PUT", body, headers)
def delete(self, url):
"""
Send a delete request.
"""
return self.request(url, "DELETE")
def request(self, url, method="GET", body="", headers={}):
"""
Actually sends the request
"""
# objectify the url
url = URL.objectify(url)
proxies = None
if self.proxy is not None:
proxies = {url.scheme: self.proxy}
log.debug("using proxy - %s" % (proxies))
# ensure that url is a unicode string
url = str(url)
combined_headers = dict(self.headers)
combined_headers.update(headers)
if body is None or body == "" and "Content-Type" in combined_headers:
del combined_headers["Content-Type"]
log.debug(
"sending request - method={0}, url={1}, headers={2}\nbody:\n{3}"
.format(method, url, combined_headers, body))
auth = None
if self.auth is None and self.username is not None:
auth = requests.auth.HTTPDigestAuth(self.username, self.password)
else:
auth = self.auth
r = requests.request(method, url, data=to_wire(body),
headers=combined_headers, proxies=proxies,
auth=auth, verify=self.ssl_verify_cert)
response = DAVResponse(r)
# If server supports BasicAuth and not DigestAuth, let's try again:
if response.status == 401 and self.auth is None and auth is not None:
auth = requests.auth.HTTPBasicAuth(self.username, self.password)
r = requests.request(method, url, data=to_wire(body),
headers=combined_headers, proxies=proxies,
auth=auth, verify=self.ssl_verify_cert)
response = DAVResponse(r)
# this is an error condition the application wants to know
if response.status == requests.codes.forbidden or \
response.status == requests.codes.unauthorized:
ex = error.AuthorizationError()
ex.url = url
ex.reason = response.reason
raise ex
# let's save the auth object and remove the user/pass information
if not self.auth and auth:
self.auth = auth
del self.username
del self.password
return response
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 011452 x ustar 00 0000000 0000000 28 mtime=1574455519.2256353
caldav-0.6.2/caldav/elements/ 0000755 0016331 0016331 00000000000 00000000000 016606 5 ustar 00tobias tobias 0000000 0000000 ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1568132280.0
caldav-0.6.2/caldav/elements/__init__.py 0000644 0016331 0016331 00000000062 00000000000 020715 0 ustar 00tobias tobias 0000000 0000000 #!/usr/bin/env python
# -*- encoding: utf-8 -*-
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1568132280.0
caldav-0.6.2/caldav/elements/base.py 0000644 0016331 0016331 00000003706 00000000000 020100 0 ustar 00tobias tobias 0000000 0000000 #!/usr/bin/env python
# -*- encoding: utf-8 -*-
from lxml import etree
from six import PY3
from caldav.lib.namespace import nsmap
from caldav.lib.python_utilities import to_unicode
class BaseElement(object):
children = None
tag = None
value = None
attributes = None
def __init__(self, name=None, value=None):
self.children = []
self.attributes = {}
value = to_unicode(value)
self.value = None
if name is not None:
self.attributes['name'] = name
if value is not None:
self.value = value
def __add__(self, other):
return self.append(other)
def __str__(self):
utf8 = etree.tostring(self.xmlelement(), encoding="utf-8",
xml_declaration=True, pretty_print=True)
if PY3:
return str(utf8, 'utf-8')
return utf8
def xmlelement(self):
root = etree.Element(self.tag, nsmap=nsmap)
if self.value is not None:
root.text = self.value
if len(self.attributes) > 0:
for k in list(self.attributes.keys()):
root.set(k, self.attributes[k])
self.xmlchildren(root)
return root
def xmlchildren(self, root):
for c in self.children:
root.append(c.xmlelement())
def append(self, element):
try:
iter(element)
self.children.extend(element)
except TypeError:
self.children.append(element)
return self
class NamedBaseElement(BaseElement):
def __init__(self, name=None):
super(NamedBaseElement, self).__init__(name=name)
def xmlelement(self):
if self.attributes.get('name') is None:
raise Exception("name attribute must be defined")
return super(NamedBaseElement, self).xmlelement()
class ValuedBaseElement(BaseElement):
def __init__(self, value=None):
super(ValuedBaseElement, self).__init__(value=value)
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1568132280.0
caldav-0.6.2/caldav/elements/cdav.py 0000644 0016331 0016331 00000010153 00000000000 020075 0 ustar 00tobias tobias 0000000 0000000 #!/usr/bin/env python
# -*- encoding: utf-8 -*-
from datetime import datetime
try:
from datetime import timezone
utc_tz = timezone.utc
except:
import pytz
utc_tz = pytz.utc
from caldav.lib.namespace import ns
from .base import BaseElement, NamedBaseElement, ValuedBaseElement
def _to_utc_date_string(ts):
# type (Union[date,datetime]]) -> str
"""coerce datetimes to UTC (assume localtime if nothing is given)"""
if (isinstance(ts, datetime)):
try:
## in python 3.6 and higher, ts.astimezone() will assume a
## naive timestamp is localtime (and so do we)
ts = ts.astimezone(utc_tz)
except:
## in python 2.7 and 3.5, ts.astimezone() will fail on
## naive timestamps, but we'd like to assume they are
## localtime
import tzlocal
ts = tzlocal.get_localzone().localize(ts).astimezone(utc_tz)
return ts.strftime("%Y%m%dT%H%M%SZ")
# Operations
class CalendarQuery(BaseElement):
tag = ns("C", "calendar-query")
class FreeBusyQuery(BaseElement):
tag = ns("C", "free-busy-query")
class Mkcalendar(BaseElement):
tag = ns("C", "mkcalendar")
# Filters
class Filter(BaseElement):
tag = ns("C", "filter")
class CompFilter(NamedBaseElement):
tag = ns("C", "comp-filter")
class PropFilter(NamedBaseElement):
tag = ns("C", "prop-filter")
class ParamFilter(NamedBaseElement):
tag = ns("C", "param-filter")
# Conditions
class TextMatch(ValuedBaseElement):
tag = ns("C", "text-match")
def __init__(self, value, collation="i;octet", negate=False):
super(TextMatch, self).__init__(value=value)
self.attributes['collation'] = collation
if negate:
self.attributes['negate-condition'] = "yes"
class TimeRange(BaseElement):
tag = ns("C", "time-range")
def __init__(self, start=None, end=None):
## start and end should be an icalendar "date with UTC time",
## ref https://tools.ietf.org/html/rfc4791#section-9.9
super(TimeRange, self).__init__()
if start is not None:
self.attributes['start'] = _to_utc_date_string(start)
if end is not None:
self.attributes['end'] = _to_utc_date_string(end)
class NotDefined(BaseElement):
tag = ns("C", "is-not-defined")
# Components / Data
class CalendarData(BaseElement):
tag = ns("C", "calendar-data")
class Expand(BaseElement):
tag = ns("C", "expand")
def __init__(self, start, end=None):
super(Expand, self).__init__()
if start is not None:
self.attributes['start'] = _to_utc_date_string(start)
if end is not None:
self.attributes['end'] = _to_utc_date_string(end)
class Comp(NamedBaseElement):
tag = ns("C", "comp")
# Uhhm ... can't find any references to calendar-collection in rfc4791.txt
# and newer versions of baikal gives 403 forbidden when this one is
# encountered
# class CalendarCollection(BaseElement):
# tag = ns("C", "calendar-collection")
# Properties
class CalendarHomeSet(BaseElement):
tag = ns("C", "calendar-home-set")
# calendar resource type, see rfc4791, sec. 4.2
class Calendar(BaseElement):
tag = ns("C", "calendar")
class CalendarDescription(ValuedBaseElement):
tag = ns("C", "calendar-description")
class CalendarTimeZone(ValuedBaseElement):
tag = ns("C", "calendar-timezone")
class SupportedCalendarComponentSet(ValuedBaseElement):
tag = ns("C", "supported-calendar-component-set")
class SupportedCalendarData(ValuedBaseElement):
tag = ns("C", "supported-calendar-data")
class MaxResourceSize(ValuedBaseElement):
tag = ns("C", "max-resource-size")
class MinDateTime(ValuedBaseElement):
tag = ns("C", "min-date-time")
class MaxDateTime(ValuedBaseElement):
tag = ns("C", "max-date-time")
class MaxInstances(ValuedBaseElement):
tag = ns("C", "max-instances")
class MaxAttendeesPerInstance(ValuedBaseElement):
tag = ns("C", "max-attendees-per-instance")
# This seems redundant, it redefines line 107
# class SupportedCalendarComponentSet(BaseElement):
# tag = ns("C", "supported-calendar-component-set")
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1568132280.0
caldav-0.6.2/caldav/elements/dav.py 0000644 0016331 0016331 00000002005 00000000000 017727 0 ustar 00tobias tobias 0000000 0000000 #!/usr/bin/env python
# -*- encoding: utf-8 -*-
from caldav.lib.namespace import ns
from .base import BaseElement, ValuedBaseElement
# Operations
class Propfind(BaseElement):
tag = ns("D", "propfind")
class PropertyUpdate(BaseElement):
tag = ns("D", "propertyupdate")
class Mkcol(BaseElement):
tag = ns("D", "mkcol")
# Filters
# Conditions
# Components / Data
class Prop(BaseElement):
tag = ns("D", "prop")
class Collection(BaseElement):
tag = ns("D", "collection")
class Set(BaseElement):
tag = ns("D", "set")
# Properties
class ResourceType(BaseElement):
tag = ns("D", "resourcetype")
class DisplayName(ValuedBaseElement):
tag = ns("D", "displayname")
class GetEtag(ValuedBaseElement):
tag = ns("D", "getetag")
class Href(BaseElement):
tag = ns("D", "href")
class Response(BaseElement):
tag = ns("D", "response")
class Status(BaseElement):
tag = ns("D", "status")
class CurrentUserPrincipal(BaseElement):
tag = ns("D", "current-user-principal")
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1568132280.0
caldav-0.6.2/caldav/elements/ical.py 0000644 0016331 0016331 00000000455 00000000000 020074 0 ustar 00tobias tobias 0000000 0000000 #!/usr/bin/env python
# -*- encoding: utf-8 -*-
from caldav.lib.namespace import ns
from .base import BaseElement, ValuedBaseElement
# Properties
class CalendarColor(ValuedBaseElement):
tag = ns("I", "calendar-color")
class CalendarOrder(ValuedBaseElement):
tag = ns("I", "calendar-order")
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 011452 x ustar 00 0000000 0000000 28 mtime=1574455519.2256353
caldav-0.6.2/caldav/lib/ 0000755 0016331 0016331 00000000000 00000000000 015540 5 ustar 00tobias tobias 0000000 0000000 ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1568132280.0
caldav-0.6.2/caldav/lib/__init__.py 0000644 0016331 0016331 00000000000 00000000000 017637 0 ustar 00tobias tobias 0000000 0000000 ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1568132280.0
caldav-0.6.2/caldav/lib/error.py 0000644 0016331 0016331 00000002230 00000000000 017240 0 ustar 00tobias tobias 0000000 0000000 #!/usr/bin/env python
# -*- encoding: utf-8 -*-
from collections import defaultdict
class AuthorizationError(Exception):
"""
The client encountered an HTTP 403 error and is passing it on
to the user. The url property will contain the url in question,
the reason property will contain the excuse the server sent.
"""
url = None
reason = "PHP at work[tm]"
def __str__(self):
return "AuthorizationError at '%s', reason '%s'" % \
(self.url, self.reason)
class DAVError(Exception):
pass
class PropsetError(DAVError):
pass
class ProppatchError(DAVError):
pass
class PropfindError(DAVError):
pass
class ReportError(DAVError):
pass
class MkcolError(DAVError):
pass
class MkcalendarError(DAVError):
pass
class PutError(DAVError):
pass
class DeleteError(DAVError):
pass
class NotFoundError(DAVError):
pass
exception_by_method = defaultdict(lambda: DAVError)
for method in ('delete', 'put', 'mkcalendar', 'mkcol', 'report', 'propset',
'propfind', 'proppatch'):
exception_by_method[method] = \
locals()[method[0].upper() + method[1:] + 'Error']
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1568132280.0
caldav-0.6.2/caldav/lib/namespace.py 0000644 0016331 0016331 00000001105 00000000000 020043 0 ustar 00tobias tobias 0000000 0000000 #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# nsmap2 is ref https://bitbucket.org/cyrilrbt/caldav/issue/29/centos59-minifi
# This looks wrong - should think more about it at a later stage.
# -- Tobias Brox, 2014-02-1
nsmap = {
"D": "DAV",
"C": "urn:ietf:params:xml:ns:caldav",
"I": "http://apple.com/ns/ical/",
}
nsmap2 = {
"D": "DAV:",
"C": "urn:ietf:params:xml:ns:caldav",
"I": "http://apple.com/ns/ical/",
}
def ns(prefix, tag=None):
name = "{%s}" % nsmap2[prefix]
if tag is not None:
name = "%s%s" % (name, tag)
return name
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1568132280.0
caldav-0.6.2/caldav/lib/python_utilities.py 0000644 0016331 0016331 00000001353 00000000000 021530 0 ustar 00tobias tobias 0000000 0000000 from six import string_types, PY3
def isPython3():
""" Deprecated. Use six.PY3 """
return PY3
def to_wire(text):
if text and isinstance(text, string_types) and PY3:
text = bytes(text, 'utf-8')
elif not PY3:
text = to_unicode(text).encode('utf-8')
return text
def to_local(text):
if text is not None and not isinstance(text, string_types):
text = text.decode('utf-8')
return text
def to_str(text):
if text and not isinstance(text, string_types):
text = text.decode('utf-8')
return text
def to_unicode(text):
if (text and isinstance(text, string_types) and not PY3 and
not isinstance(text, unicode)):
text = unicode(text, 'utf-8')
return text
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1568132280.0
caldav-0.6.2/caldav/lib/url.py 0000644 0016331 0016331 00000014156 00000000000 016723 0 ustar 00tobias tobias 0000000 0000000 #!/usr/bin/env python
# -*- encoding: utf-8 -*-
from six import PY3
from caldav.lib.python_utilities import to_unicode
if PY3:
from urllib.parse import ParseResult, SplitResult, urlparse
else:
from urlparse import ParseResult, SplitResult
from urlparse import urlparse
def uc2utf8(input):
# argh! this feels wrong, but seems to be needed.
if not PY3 and type(input) == unicode:
return input.encode('utf-8')
else:
return input
class URL:
"""
This class is for wrapping URLs into objects. It's used
internally in the library, end users should not need to know
anything about this class. All methods that accept URLs can be
fed either with an URL object, a string or an urlparse.ParsedURL
object.
Addresses may be one out of three:
1) a path relative to the DAV-root, i.e. "someuser/calendar" may
refer to
"http://my.davical-server.example.com/caldav.php/someuser/calendar".
2) an absolute path, i.e. "/caldav.php/someuser/calendar"
3) a fully qualified URL, i.e.
"http://someuser:somepass@my.davical-server.example.com/caldav.php/someuser/calendar".
Remark that hostname, port, user, pass is typically given when
instantiating the DAVClient object and cannot be overridden later.
As of 2013-11, some methods in the caldav library expected strings
and some expected urlParseResult objects, some expected
fully qualified URLs and most expected absolute paths. The purpose
of this class is to ensure consistency and at the same time
maintaining backward compatibility. Basically, all methods should
accept any kind of URL.
"""
def __init__(self, url):
if isinstance(url, ParseResult) or isinstance(url, SplitResult):
self.url_parsed = url
self.url_raw = None
else:
self.url_raw = url
self.url_parsed = None
def __bool__(self):
if self.url_raw or self.url_parsed:
return True
else:
return False
def __ne__(self, other):
return not self == other
def __eq__(self, other):
if str(self) == str(other):
return True
# The URLs could have insignificant differences
me = self.canonical()
if hasattr(other, 'canonical'):
other = other.canonical()
return str(me) == str(other)
# TODO: better naming? Will return url if url is already an URL
# object, else will instantiate a new URL object
@classmethod
def objectify(self, url):
if url is None:
return None
if isinstance(url, URL):
return url
else:
return URL(url)
# To deal with all kind of methods/properties in the ParseResult
# class
def __getattr__(self, attr):
if self.url_parsed is None:
self.url_parsed = urlparse(self.url_raw)
if hasattr(self.url_parsed, attr):
return getattr(self.url_parsed, attr)
else:
return getattr(self.__unicode__(), attr)
# returns the url in text format
def __str__(self):
if PY3:
return self.__unicode__()
return self.__unicode__().encode('utf-8')
# returns the url in text format
def __unicode__(self):
if self.url_raw is None:
self.url_raw = self.url_parsed.geturl()
if isinstance(self.url_raw, str):
return to_unicode(self.url_raw)
else:
return to_unicode(str(self.url_raw))
def __repr__(self):
return "URL(%s)" % str(self)
def strip_trailing_slash(self):
if str(self)[-1] == '/':
return URL.objectify(str(self)[:-1])
else:
return self
def is_auth(self):
return self.username is not None
def unauth(self):
if not self.is_auth():
return self
return URL.objectify(ParseResult(
self.scheme,
'%s:%s' % (self.hostname,
self.port or {'https': 443, 'http': 80}[self.scheme]),
self.path.replace('//', '/'), self.params, self.query,
self.fragment))
def canonical(self):
"""
a canonical URL ... remove authentication details, make sure there
are no double slashes, and to make sure the URL is always the same,
run it through the urlparser
"""
url = self.unauth()
# this is actually already done in the unauth method ...
if '//' in url.path:
raise NotImplementedError("remove the double slashes")
# This looks like a noop - but it may have the side effect
# that urlparser be run (actually not - unauth ensures we
# have an urlParseResult object)
url.scheme
# make sure to delete the string version
url.url_raw = None
return url
def join(self, path):
"""
assumes this object is the base URL or base path. If the path
is relative, it should be appended to the base. If the path
is absolute, it should be added to the connection details of
self. If the path already contains connection details and the
connection details differ from self, raise an error.
"""
pathAsString = str(path)
if not path or not pathAsString:
return self
path = URL.objectify(path)
if (
(path.scheme and self.scheme and path.scheme != self.scheme) or
(path.hostname and self.hostname and
path.hostname != self.hostname) or
(path.port and self.port and path.port != self.port)
):
raise ValueError("%s can't be joined with %s" % (self, path))
if path.path[0] == '/':
ret_path = uc2utf8(path.path)
else:
sep = "/"
if self.path.endswith("/"):
sep = ""
ret_path = "%s%s%s" % (self.path, sep, uc2utf8(path.path))
return URL(ParseResult(
self.scheme or path.scheme, self.netloc or path.netloc, ret_path,
path.params, path.query, path.fragment))
def make(url):
"""Backward compatibility"""
return URL.objectify(url)
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1568132280.0
caldav-0.6.2/caldav/lib/vcal.py 0000644 0016331 0016331 00000000724 00000000000 017042 0 ustar 00tobias tobias 0000000 0000000 #!/usr/bin/env python
# -*- encoding: utf-8 -*-
import re
from caldav.lib.python_utilities import to_local
def fix(event):
fixed = re.sub('COMPLETED:(\d+)\s', 'COMPLETED:\g<1>T120000Z',
to_local(event))
# The following line fixes a data bug in some Google Calendar events
fixed = re.sub('CREATED:00001231T000000Z',
'CREATED:19700101T000000Z', fixed)
fixed = re.sub(r"\\+('\")", r"\1", fixed)
return fixed
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1568132280.0
caldav-0.6.2/caldav/objects.py 0000644 0016331 0016331 00000111537 00000000000 017005 0 ustar 00tobias tobias 0000000 0000000 #!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
A "DAV object" is anything we get from the caldav server or push into the
caldav server, notably principal, calendars and calendar events.
"""
import vobject
import uuid
import re
from datetime import datetime, date
from lxml import etree
try:
# noinspection PyCompatibility
from urllib.parse import unquote
except ImportError:
from urllib import unquote
try:
from typing import Union, Optional
TimeStamp = Optional[Union[date,datetime]]
except:
pass
from caldav.lib import error, vcal
from caldav.lib.url import URL
from caldav.elements import dav, cdav
from caldav.lib.python_utilities import to_unicode
def errmsg(r):
"""Utility for formatting a response xml tree to an error string"""
return "%s %s\n\n%s" % (r.status, r.reason, r.raw)
class DAVObject(object):
"""
Base class for all DAV objects. Can be instantiated by a client
and an absolute or relative URL, or from the parent object.
"""
id = None
url = None
client = None
parent = None
name = None
def __init__(self, client=None, url=None, parent=None, name=None, id=None,
**extra):
"""
Default constructor.
Parameters:
* client: A DAVClient instance
* url: The url for this object. May be a full URL or a relative URL.
* parent: The parent object - used when creating objects
* name: A displayname
* id: The resource id (UID for an Event)
"""
if client is None and parent is not None:
client = parent.client
self.client = client
self.parent = parent
self.name = name
self.id = id
self.extra_init_options = extra
# url may be a path relative to the caldav root
if client and url:
self.url = client.url.join(url)
else:
self.url = URL.objectify(url)
@property
def canonical_url(self):
return str(self.url.unauth())
def children(self, type=None):
"""
List children, using a propfind (resourcetype) on the parent object,
at depth = 1.
"""
c = []
depth = 1
properties = {}
props = [dav.ResourceType(), dav.DisplayName()]
response = self._query_properties(props, depth)
properties = self._handle_prop_response(
response=response, props=props, type=type, what='tag')
for path in list(properties.keys()):
resource_type = properties[path][dav.ResourceType.tag]
resource_name = properties[path][dav.DisplayName.tag]
if resource_type == type or type is None:
# TODO: investigate the RFCs thoroughly - why does a "get
# members of this collection"-request also return the
# collection URL itself?
# And why is the strip_trailing_slash-method needed?
# The collection URL should always end with a slash according
# to RFC 2518, section 5.2.
if (self.url.strip_trailing_slash() !=
self.url.join(path).strip_trailing_slash()):
c.append((self.url.join(path), resource_type,
resource_name))
return c
def _query_properties(self, props=None, depth=0):
"""
This is an internal method for doing a propfind query. It's a
result of code-refactoring work, attempting to consolidate
similar-looking code into a common method.
"""
root = None
# build the propfind request
if props is not None and len(props) > 0:
prop = dav.Prop() + props
root = dav.Propfind() + prop
return self._query(root, depth)
def _query(self, root=None, depth=0, query_method='propfind', url=None,
expected_return_value=None):
"""
This is an internal method for doing a query. It's a
result of code-refactoring work, attempting to consolidate
similar-looking code into a common method.
"""
# ref https://bitbucket.org/cyrilrbt/caldav/issues/46 -
# COMPATIBILITY ISSUE. The lines below seems to solve real
# world problems, though I believe it's the wrong place to
# inject the missing slash.
# TODO: find out why the slash is missing and fix
# it properly.
# Background: Collection URLs ends with a slash,
# non-collection URLs does not end with a slash. If the
# slash is missing, Servers MAY pretend it's present (RFC
# 4918, section 5.2, collection resources), hence only some
# few servers break when the slash is missing. RFC 4918
# specifies that collection URLs end with a slash while
# non-collection URLs should not end with a slash.
if url is None:
url = self.url
if not url.endswith('/'):
url = URL(str(url) + '/')
body = ""
if root:
body = etree.tostring(root.xmlelement(), encoding="utf-8",
xml_declaration=True)
ret = getattr(self.client, query_method)(
url, body, depth)
if ret.status == 404:
raise error.NotFoundError(errmsg(ret))
if ((expected_return_value is not None and
ret.status != expected_return_value) or
ret.status >= 400):
raise error.exception_by_method[query_method](errmsg(ret))
return ret
def _handle_prop_response(self, response, props=[], type=None,
what='text'):
"""
Internal method to massage an XML response into a dict. (This
method is a result of some code refactoring work, attempting
to consolidate similar-looking code)
"""
properties = {}
# All items should be in a element
for r in response.tree.findall('.//' + dav.Response.tag):
status = r.find('.//' + dav.Status.tag)
## TODO: status should never be None, this needs more research.
## added here as it solves real-world issues, ref
## https://github.com/python-caldav/caldav/pull/56
if status is not None:
if (' 200 ' not in status.text and
' 207 ' not in status.text and
' 404 ' not in status.text):
raise error.ReportError(errmsg(response))
# TODO: may be wrong error class
href = unquote(r.find('.//' + dav.Href.tag).text)
properties[href] = {}
for p in props:
t = r.find(".//" + p.tag)
if t is None:
val = None
elif t is not None and list(t):
if type is not None:
val = t.find(".//" + type)
else:
val = t.find(".//*")
if val is not None:
val = getattr(val, what)
else:
val = None
else:
val = t.text
properties[href][p.tag] = val
return properties
def get_properties(self, props=None, depth=0):
"""
Get properties (PROPFIND) for this object. Works only for
properties, that don't have complex types.
Parameters:
* props = [dav.ResourceType(), dav.DisplayName(), ...]
Returns:
* {proptag: value, ...}
"""
rc = None
response = self._query_properties(props, depth)
properties = self._handle_prop_response(response, props)
path = unquote(self.url.path)
if path.endswith('/'):
exchange_path = path[:-1]
else:
exchange_path = path + '/'
if path in properties:
rc = properties[path]
elif exchange_path in properties:
rc = properties[exchange_path]
else:
raise Exception("The CalDAV server you are using has "
"a problem with path handling.")
return rc
def set_properties(self, props=None):
"""
Set properties (PROPPATCH) for this object.
* props = [dav.DisplayName('name'), ...]
Returns:
* self
"""
props = [] if props is None else props
prop = dav.Prop() + props
set = dav.Set() + prop
root = dav.PropertyUpdate() + set
r = self._query(root, query_method='proppatch')
statuses = r.tree.findall(".//" + dav.Status.tag)
for s in statuses:
if ' 200 ' not in s.text:
raise error.PropsetError(s.text)
return self
def save(self):
"""
Save the object. This is an abstract method, that all classes
derived .from DAVObject implement.
Returns:
* self
"""
raise NotImplementedError()
def delete(self):
"""
Delete the object.
"""
if self.url is not None:
r = self.client.delete(self.url)
# TODO: find out why we get 404
if r.status not in (200, 204, 404):
raise error.DeleteError(errmsg(r))
def __str__(self):
return str(self.url)
def __repr__(self):
return "%s(%s)" % (self.__class__.__name__, self.url)
class CalendarSet(DAVObject):
def calendars(self):
"""
List all calendar collections in this set.
Returns:
* [Calendar(), ...]
"""
cals = []
data = self.children(cdav.Calendar.tag)
for c_url, c_type, c_name in data:
cals.append(Calendar(self.client, c_url, parent=self, name=c_name))
return cals
def make_calendar(self, name=None, cal_id=None,
supported_calendar_component_set=None):
"""
Utility method for creating a new calendar.
Parameters:
* name: the name of the new calendar
* cal_id: the uuid of the new calendar
* supported_calendar_component_set: what kind of objects
(EVENT, VTODO, VFREEBUSY, VJOURNAL) the calendar should handle.
Should be set to ['VTODO'] when creating a task list in Zimbra -
in most other cases the default will be OK.
Returns:
* Calendar(...)-object
"""
return Calendar(
self.client, name=name, parent=self, id=cal_id,
supported_calendar_component_set=supported_calendar_component_set
).save()
def calendar(self, name=None, cal_id=None):
"""
The calendar method will return a calendar object. It will not
initiate any communication with the server.
Parameters:
* name: return the calendar with this name
* cal_id: return the calendar with this calendar id
Returns:
* Calendar(...)-object
"""
return Calendar(self.client, name=name, parent=self,
url=self.url.join(cal_id), id=cal_id)
class Principal(DAVObject):
"""
This class represents a DAV Principal. It doesn't do much, except
keep track of the URLs for the calendar-home-set, etc.
A principal MUST have a non-empty DAV:displayname property
(defined in Section 13.2 of [RFC2518]),
and a DAV:resourcetype property (defined in Section 13.9 of [RFC2518]).
Additionally, a principal MUST report the DAV:principal XML element
in the value of the DAV:resourcetype property.
"""
def __init__(self, client=None, url=None):
"""
Returns a Principal.
Parameters:
* client: a DAVClient() oject
* url: Deprecated - for backwards compatibility purposes only.
If url is not given, deduct principal path as well as calendar home set
path from doing propfinds.
"""
self.client = client
self._calendar_home_set = None
# backwards compatibility.
if url is not None:
self.url = client.url.join(URL.objectify(url))
else:
self.url = self.client.url
cup = self.get_properties([dav.CurrentUserPrincipal()])
self.url = self.client.url.join(
URL.objectify(cup['{DAV:}current-user-principal']))
def make_calendar(self, name=None, cal_id=None,
supported_calendar_component_set=None):
"""
Convenience method, bypasses the self.calendar_home_set object.
See CalendarSet.make_calendar for details.
"""
return self.calendar_home_set.make_calendar(
name, cal_id,
supported_calendar_component_set=supported_calendar_component_set)
def calendar(self, name=None, cal_id=None):
"""
The calendar method will return a calendar object.
It will not initiate any communication with the server.
"""
return self.calendar_home_set.calendar(name, cal_id)
@property
def calendar_home_set(self):
if not self._calendar_home_set:
chs = self.get_properties([cdav.CalendarHomeSet()])
self.calendar_home_set = chs[
'{urn:ietf:params:xml:ns:caldav}calendar-home-set']
return self._calendar_home_set
@calendar_home_set.setter
def calendar_home_set(self, url):
if isinstance(url, CalendarSet):
self._calendar_home_set = url
return
sanitized_url = URL.objectify(url)
## TODO: sanitized_url should never be None, this needs more
## research. added here as it solves real-world issues, ref
## https://github.com/python-caldav/caldav/pull/56
if sanitized_url is not None:
if (sanitized_url.hostname and
sanitized_url.hostname != self.client.url.hostname):
# icloud (and others?) having a load balanced system,
# where each principal resides on one named host
self.client.url = sanitized_url
self._calendar_home_set = CalendarSet(
self.client, self.client.url.join(sanitized_url))
def calendars(self):
"""
Return the principials calendars
"""
return self.calendar_home_set.calendars()
class Calendar(DAVObject):
"""
The `Calendar` object is used to represent a calendar collection.
Refer to the RFC for details: http://www.ietf.org/rfc/rfc4791.txt
"""
def _create(self, name, id=None, supported_calendar_component_set=None):
"""
Create a new calendar with display name `name` in `parent`.
"""
if id is None:
id = str(uuid.uuid1())
self.id = id
path = self.parent.url.join(id)
self.url = path
# TODO: mkcalendar seems to ignore the body on most servers?
# at least the name doesn't get set this way.
# zimbra gives 500 (!) if body is omitted ...
# ehm ... this element seems non-existent in the RFC?
# Breaks with baikal, too ...
# cal = cdav.CalendarCollection()
# coll = dav.Collection() # + cal # also breaks on baikal,
# # and probably not needed?
# type = dav.ResourceType() ## probably not needed?
prop = dav.Prop() # + [type,]
if name:
display_name = dav.DisplayName(name)
prop += [display_name, ]
if supported_calendar_component_set:
sccs = cdav.SupportedCalendarComponentSet()
for scc in supported_calendar_component_set:
sccs += cdav.Comp(scc)
prop += sccs
set = dav.Set() + prop
mkcol = cdav.Mkcalendar() + set
r = self._query(root=mkcol, query_method='mkcalendar', url=path,
expected_return_value=201)
# COMPATIBILITY ISSUE
# name should already be set, but we've seen caldav servers failing
# on setting the DisplayName on calendar creation
# (DAViCal, Zimbra, ...). Better to be explicit.
if name:
try:
self.set_properties([display_name])
except:
self.delete()
raise
# Special hack for Zimbra! The calendar we've made exists at
# the specified URL, and we can do operations like ls, even
# PUT an event to the calendar. Zimbra will enforce that the
# event uuid matches the event url, and return either 201 or
# 302 - but alas, try to do a GET towards the event and we
# get 404! But turn around and replace the calendar ID with
# the calendar name in the URL and hey ... it works!
# TODO: write test cases for calendars with non-trivial
# names and calendars with names already matching existing
# calendar urls and ensure they pass.
zimbra_url = self.parent.url.join(name)
try:
ret = self.client.request(zimbra_url)
if ret.status == 404:
raise error.NotFoundError
# special hack for radicale.
# It will happily accept any calendar-URL without returning 404.
ret = self.client.request(self.parent.url.join(
'ANYTHINGGOESHEREthisshouldforsurereturn404'))
if ret.status == 404:
# insane server
self.url = zimbra_url
except error.NotFoundError:
# sane server
pass
def add_event(self, ical):
"""
Add a new event to the calendar, with the given ical.
Parameters:
* ical - ical object (text)
"""
return Event(self.client, data=ical, parent=self).save()
def add_todo(self, ical):
"""
Add a new task to the calendar, with the given ical.
Parameters:
* ical - ical object (text)
"""
return Todo(self.client, data=ical, parent=self).save()
def add_journal(self, ical):
"""
Add a new journal entry to the calendar, with the given ical.
Parameters:
* ical - ical object (text)
"""
return Journal(self.client, data=ical, parent=self).save()
def save(self):
"""
The save method for a calendar is only used to create it, for now.
We know we have to create it when we don't have a url.
Returns:
* self
"""
if self.url is None:
self._create(name=self.name, id=self.id, **self.extra_init_options)
if not self.url.endswith('/'):
self.url = URL.objectify(str(self.url) + '/')
return self
def date_search(self, start, end=None, compfilter="VEVENT", expand="maybe"):
# type (TimeStamp, TimeStamp, str, str) -> CalendarObjectResource
"""
Search events by date in the calendar. Recurring events are
expanded if they are occuring during the specified time frame
and if an end timestamp is given.
Parameters:
* start = datetime.today().
* end = same as above.
* compfilter = defaults to events only. Set to None to fetch all
calendar components.
* expand - should recurrent events be expanded? (to preserve
backward-compatibility the default "maybe" will be changed into True
unless the date_search is open-ended)
Returns:
* [CalendarObjectResource(), ...]
"""
matches = []
# build the request
## for backward compatibility - expand should be false
## in an open-ended date search, otherwise true
if expand == 'maybe':
expand = end
# Some servers will raise an error if we send the expand flag
# but don't set any end-date - expand doesn't make much sense
# if we have one recurring event describing an indefinite
# series of events. I think it's appropriate to raise an error
# in this case.
if not end and expand:
raise error.ReportError("an open-ended date search cannot be expanded")
elif expand:
data = cdav.CalendarData() + cdav.Expand(start, end)
else:
data = cdav.CalendarData()
prop = dav.Prop() + data
query = cdav.TimeRange(start, end)
if compfilter:
query = cdav.CompFilter(compfilter) + query
vcalendar = cdav.CompFilter("VCALENDAR") + query
filter = cdav.Filter() + vcalendar
root = cdav.CalendarQuery() + [prop, filter]
response = self._query(root, 1, 'report')
results = self._handle_prop_response(
response=response, props=[cdav.CalendarData()])
for r in results:
matches.append(
Event(self.client, url=self.url.join(r),
data=results[r][cdav.CalendarData.tag], parent=self))
return matches
def freebusy_request(self, start, end):
"""
Search the calendar, but return only the free/busy information.
Parameters:
* start = datetime.today().
* end = same as above.
Returns:
* [FreeBusy(), ...]
"""
root = cdav.FreeBusyQuery() + [cdav.TimeRange(start, end)]
response = self._query(root, 1, 'report')
return FreeBusy(self, response.raw)
def _fetch_todos(self, filters):
# ref https://www.ietf.org/rfc/rfc4791.txt, section 7.8.9
matches = []
# build the request
data = cdav.CalendarData()
prop = dav.Prop() + data
vcalendar = cdav.CompFilter("VCALENDAR") + filters
filter = cdav.Filter() + vcalendar
root = cdav.CalendarQuery() + [prop, filter]
response = self._query(root, 1, 'report')
results = self._handle_prop_response(
response=response, props=[cdav.CalendarData()])
for r in results:
matches.append(
Todo(self.client, url=self.url.join(r),
data=results[r][cdav.CalendarData.tag], parent=self))
return matches
def todos(self, sort_keys=('due', 'priority'), include_completed=False,
sort_key=None):
"""
fetches a list of todo events.
Parameters:
* sort_keys: use this field in the VTODO for sorting (iterable of
lower case string, i.e. ('priority','due')).
* include_completed: boolean -
by default, only pending tasks are listed
* sort_key: DEPRECATED, for backwards compatibility with version 0.4.
"""
if sort_key:
sort_keys = (sort_key,)
if not include_completed:
vnotcompleted = cdav.TextMatch('COMPLETED', negate=True)
vnotcancelled = cdav.TextMatch('CANCELLED', negate=True)
vstatusNotCompleted = cdav.PropFilter('STATUS') + vnotcompleted
vstatusNotCancelled = cdav.PropFilter('STATUS') + vnotcancelled
vstatusNotDefined = cdav.PropFilter('STATUS') + cdav.NotDefined()
vnocompletedate = cdav.PropFilter('COMPLETED') + cdav.NotDefined()
filters1 = (cdav.CompFilter("VTODO") + vnocompletedate +
vstatusNotCompleted + vstatusNotCancelled)
## This query is quite much in line with https://tools.ietf.org/html/rfc4791#section-7.8.9
matches1 = self._fetch_todos(filters1)
## However ... some server implementations (i.e. NextCloud
## and Baikal) will yield "false" on a negated TextMatch
## if the field is not defined. Hence, for those
## implementations we need to turn back and ask again
## ... do you have any VTODOs for us where the STATUS
## field is not defined? (ref
## https://github.com/python-caldav/caldav/issues/14)
filters2 = (cdav.CompFilter("VTODO") + vnocompletedate +
vstatusNotDefined)
matches2 = self._fetch_todos(filters2)
## For most caldav servers, everything in matches2 already exists
## in matches1. We need to make a union ...
match_set = set()
matches = []
for todo in matches1 + matches2:
if not str(todo.url) in match_set:
match_set.add(str(todo.url))
## and still, Zimbra seems to deliver too many TODOs on the
## filter2 ... let's do some post-filtering in case the
## server fails in filtering things the right way
if (not '\nCOMPLETED:' in todo.data and
not '\nSTATUS:COMPLETED' in todo.data and
not '\nSTATUS:CANCELLED' in todo.data):
matches.append(todo)
else:
filters = cdav.CompFilter("VTODO")
matches = self._fetch_todos(filters)
def sort_key_func(x):
ret = []
vtodo = x.instance.vtodo
defaults = {
'due': '2050-01-01',
'dtstart': '1970-01-01',
'priority': '0',
# JA: why compare datetime.strftime('%F%H%M%S')
# JA: and not simply datetime?
# tobixen: probably it was made like this because we can get
# both dates and timestamps from the objects.
# Python will yield an exception if trying to compare
# a timestamp with a date.
'isnt_overdue':
not (hasattr(vtodo, 'due') and
vtodo.due.value.strftime('%F%H%M%S') <
datetime.now().strftime('%F%H%M%S')),
'hasnt_started':
(hasattr(vtodo, 'dtstart') and
vtodo.dtstart.value.strftime('%F%H%M%S') >
datetime.now().strftime('%F%H%M%S'))
}
for sort_key in sort_keys:
val = getattr(vtodo, sort_key, None)
if val is None:
ret.append(defaults.get(sort_key, '0'))
continue
val = val.value
if hasattr(val, 'strftime'):
ret.append(val.strftime('%F%H%M%S'))
else:
ret.append(val)
return ret
if sort_keys:
matches.sort(key=sort_key_func)
return matches
def _calendar_comp_class_by_data(self, data):
for line in data.split('\n'):
if line == 'BEGIN:VEVENT':
return Event
if line == 'BEGIN:VTODO':
return Todo
if line == 'BEGIN:VJOURNAL':
return Journal
if line == 'BEGIN:VFREEBUSY':
return FreeBusy
def event_by_url(self, href, data=None):
"""
Returns the event with the given URL
"""
return Event(url=href, data=data, parent=self).load()
def object_by_uid(self, uid, comp_filter=None):
"""
Get one event from the calendar.
Parameters:
* uid: the event uid
Returns:
* Event() or None
"""
data = cdav.CalendarData()
prop = dav.Prop() + data
query = cdav.TextMatch(uid)
query = cdav.PropFilter("UID") + query
if comp_filter:
query = comp_filter + query
vcalendar = cdav.CompFilter("VCALENDAR") + query
filter = cdav.Filter() + vcalendar
root = cdav.CalendarQuery() + [prop, filter]
response = self._query(root, 1, 'report')
if response.status == 404:
raise error.NotFoundError(errmsg(response))
elif response.status == 400:
raise error.ReportError(errmsg(response))
items_found = response.tree.findall(".//" + dav.Response.tag)
for r in items_found:
href = unquote(r.find(".//" + dav.Href.tag).text)
data = unquote(r.find(".//" + cdav.CalendarData.tag).text)
# Ref Lucas Verney, we've actually done a substring search, if the
# uid given in the query is short (i.e. just "0") we're likely to
# get false positives back from the server.
#
# Long uids are folded, so splice the lines together here before
# attempting a match.
item_uid = re.search(r'\nUID:((.|\n[ \t])*)\n', data)
if (not item_uid or
re.sub(r'\n[ \t]', '', item_uid.group(1)) != uid):
continue
return self._calendar_comp_class_by_data(data)(
self.client, url=URL.objectify(href), data=data, parent=self)
raise error.NotFoundError(errmsg(response))
def todo_by_uid(self, uid):
return self.object_by_uid(uid, comp_filter=cdav.CompFilter("VTODO"))
def event_by_uid(self, uid):
return self.object_by_uid(uid, comp_filter=cdav.CompFilter("VEVENT"))
# alias for backward compatibility
event = event_by_uid
def events(self):
"""
List all events from the calendar.
Returns:
* [Event(), ...]
"""
all = []
data = cdav.CalendarData()
prop = dav.Prop() + data
vevent = cdav.CompFilter("VEVENT")
vcalendar = cdav.CompFilter("VCALENDAR") + vevent
filter = cdav.Filter() + vcalendar
root = cdav.CalendarQuery() + [prop, filter]
response = self._query(root, 1, query_method='report')
results = self._handle_prop_response(
response, props=[cdav.CalendarData()])
for r in results:
all.append(Event(
self.client, url=self.url.join(r),
data=results[r][cdav.CalendarData.tag], parent=self))
return all
def journals(self):
"""
List all journals from the calendar.
Returns:
* [Journal(), ...]
"""
# TODO: this is basically a copy of events() - can we do more
# refactoring and consolidation here? Maybe it's wrong to do
# separate methods for journals, todos and events?
all = []
data = cdav.CalendarData()
prop = dav.Prop() + data
vevent = cdav.CompFilter("VJOURNAL")
vcalendar = cdav.CompFilter("VCALENDAR") + vevent
filter = cdav.Filter() + vcalendar
root = cdav.CalendarQuery() + [prop, filter]
response = self._query(root, 1, query_method='report')
results = self._handle_prop_response(
response, props=[cdav.CalendarData()])
for r in results:
all.append(Journal(
self.client, url=self.url.join(r),
data=results[r][cdav.CalendarData.tag], parent=self))
return all
class CalendarObjectResource(DAVObject):
"""
Ref RFC 4791, section 4.1, a "Calendar Object Resource" can be an
event, a todo-item, a journal entry, or a free/busy entry
"""
_vobject_instance = None
_data = None
def __init__(self, client=None, url=None, data=None, parent=None, id=None):
"""
CalendarObjectResource has an additional parameter for its constructor:
* data = "...", vCal data for the event
"""
DAVObject.__init__(self, client=client, url=url, parent=parent, id=id)
if data is not None:
self.data = data
def copy(self, keep_uid=False, new_parent=None):
"""
Events, todos etc can be copied within the same calendar, to another
calendar or even to another caldav server
"""
return self.__class__(
parent=new_parent or self.parent,
data=self.data,
id=self.id if keep_uid else str(uuid.uuid1()))
def load(self):
"""
Load the object from the caldav server.
"""
r = self.client.request(self.url)
if r.status == 404:
raise error.NotFoundError(errmsg(r))
self.data = vcal.fix(r.raw)
return self
def _create(self, data, id=None, path=None):
if id is None and path is not None and str(path).endswith('.ics'):
id = re.search('(/|^)([^/]*).ics', str(path)).group(2)
elif id is None:
for obj_type in ('vevent', 'vtodo', 'vjournal', 'vfreebusy'):
obj = None
if hasattr(self.vobject_instance, obj_type):
obj = getattr(self.vobject_instance, obj_type)
elif self.vobject_instance.name.lower() == obj_type:
obj = self.vobject_instance
if obj is not None:
id = obj.uid.value
break
else:
for obj_type in ('vevent', 'vtodo', 'vjournal', 'vfreebusy'):
obj = None
if hasattr(self.vobject_instance, obj_type):
obj = getattr(self.vobject_instance, obj_type)
elif self.vobject_instance.name.lower() == obj_type:
obj = self.vobject_instance
if obj is not None:
if not hasattr(obj, 'uid'):
obj.add('uid')
obj.uid = id
break
if path is None:
path = id + ".ics"
path = self.parent.url.join(path)
r = self.client.put(path, data,
{"Content-Type": 'text/calendar; charset="utf-8"'})
if r.status == 302:
path = [x[1] for x in r.headers if x[0] == 'location'][0]
elif not (r.status in (204, 201)):
raise error.PutError(errmsg(r))
self.url = URL.objectify(path)
self.id = id
def save(self):
"""
Save the object, can be used for creation and update.
Returns:
* self
"""
if self._vobject_instance is None and self._data is None:
return self
path = self.url.path if self.url else None
if self._vobject_instance is None:
## ref https://github.com/python-caldav/caldav/issues/43
## we don't want to use vobject unless needed, but
## sometimes the caldav server may balk on slightly
## non-conforming icalendar data. We'll just throw in a
## try-send-data-except-wash-through-vobject-logic here.
try:
self._create(self._data, self.id, path)
except error.PutError:
self._create(self.vobject_instance.serialize(), self.id, path)
else:
self._create(self._vobject_instance.serialize(), self.id, path)
return self
def __str__(self):
return "%s: %s" % (self.__class__.__name__, self.url)
def _set_data(self, data):
if type(data).__module__.startswith("vobject"):
self._data = self._vobject_instance
self._vobject_instance = data
else:
self._data = vcal.fix(data)
self._vobject_instance = None
#self._instance = vobject.readOne(to_unicode(self._data))
return self
def _get_data(self):
return self._data
data = property(_get_data, _set_data,
doc="vCal representation of the object")
def _set_vobject_instance(self, inst):
self._vobject_instance = inst
self._data = inst.serialize()
return self
def _get_vobject_instance(self):
if not self._vobject_instance and self._data:
self._vobject_instance = vobject.readOne(to_unicode(self._data))
return self._vobject_instance
vobject_instance = property(_get_vobject_instance, _set_vobject_instance,
doc="vobject instance of the object")
## for backward-compatibility
instance = vobject_instance
class Event(CalendarObjectResource):
"""
The `Event` object is used to represent an event (VEVENT).
"""
pass
class Journal(CalendarObjectResource):
"""
The `Journal` object is used to represent a journal entry (VJOURNAL).
"""
pass
class FreeBusy(CalendarObjectResource):
"""
The `FreeBusy` object is used to represent a freebusy response from the
server.
"""
def __init__(self, parent, data):
"""
A freebusy response object has no URL or ID (TODO: reconsider the
class hierarchy? most of the inheritated methods are moot and
will fail?). Raw response can be accessed through self.data,
instantiated vobject as self.vobject_instance.
"""
CalendarObjectResource.__init__(self, client=parent.client, url=None,
data=data, parent=parent, id=None)
class Todo(CalendarObjectResource):
"""
The `Todo` object is used to represent a todo item (VTODO).
"""
def complete(self, completion_timestamp=None):
"""
Marks the task as completed.
Parameters:
* completion_timestamp - datetime object. Defaults to
datetime.now().
"""
if not completion_timestamp:
completion_timestamp = datetime.now()
if not hasattr(self.vobject_instance.vtodo, 'status'):
self.vobject_instance.vtodo.add('status')
self.vobject_instance.vtodo.status.value = 'COMPLETED'
self.vobject_instance.vtodo.add('completed').value = completion_timestamp
self.save()
././@PaxHeader 0000000 0000000 0000000 00000000033 00000000000 011451 x ustar 00 0000000 0000000 27 mtime=1574455519.222302
caldav-0.6.2/caldav.egg-info/ 0000755 0016331 0016331 00000000000 00000000000 016464 5 ustar 00tobias tobias 0000000 0000000 ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1574455519.0
caldav-0.6.2/caldav.egg-info/PKG-INFO 0000644 0016331 0016331 00000001246 00000000000 017564 0 ustar 00tobias tobias 0000000 0000000 Metadata-Version: 1.1
Name: caldav
Version: 0.6.2
Summary: CalDAV (RFC4791) client library
Home-page: http://bitbucket.org/cyrilrbt/caldav
Author: Cyril Robert
Author-email: cyril@hippie.io
License: GPL
Description: UNKNOWN
Platform: UNKNOWN
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: GNU General Public License (GPL)
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python
Classifier: Topic :: Office/Business :: Scheduling
Classifier: Topic :: Software Development :: Libraries :: Python Modules
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1574455519.0
caldav-0.6.2/caldav.egg-info/SOURCES.txt 0000644 0016331 0016331 00000001307 00000000000 020351 0 ustar 00tobias tobias 0000000 0000000 COPYING.APACHE
COPYING.GPL
ChangeLog
MANIFEST.in
README.md
setup.cfg
setup.py
caldav/__init__.py
caldav/davclient.py
caldav/objects.py
caldav.egg-info/PKG-INFO
caldav.egg-info/SOURCES.txt
caldav.egg-info/dependency_links.txt
caldav.egg-info/not-zip-safe
caldav.egg-info/requires.txt
caldav.egg-info/top_level.txt
caldav/elements/__init__.py
caldav/elements/base.py
caldav/elements/cdav.py
caldav/elements/dav.py
caldav/elements/ical.py
caldav/lib/__init__.py
caldav/lib/error.py
caldav/lib/namespace.py
caldav/lib/python_utilities.py
caldav/lib/url.py
caldav/lib/vcal.py
tests/__init__.py
tests/_test_absolute.py
tests/conf.py
tests/conf_private.py.EXAMPLE
tests/proxy.py
tests/test_caldav.py
tests/test_cdav.py ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1574455519.0
caldav-0.6.2/caldav.egg-info/dependency_links.txt 0000644 0016331 0016331 00000000001 00000000000 022532 0 ustar 00tobias tobias 0000000 0000000
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1574455519.0
caldav-0.6.2/caldav.egg-info/not-zip-safe 0000644 0016331 0016331 00000000001 00000000000 020712 0 ustar 00tobias tobias 0000000 0000000
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1574455519.0
caldav-0.6.2/caldav.egg-info/requires.txt 0000644 0016331 0016331 00000000032 00000000000 021057 0 ustar 00tobias tobias 0000000 0000000 vobject
lxml
requests
six
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1574455519.0
caldav-0.6.2/caldav.egg-info/top_level.txt 0000644 0016331 0016331 00000000007 00000000000 021213 0 ustar 00tobias tobias 0000000 0000000 caldav
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 011452 x ustar 00 0000000 0000000 28 mtime=1574455519.2356353
caldav-0.6.2/setup.cfg 0000644 0016331 0016331 00000000276 00000000000 015366 0 ustar 00tobias tobias 0000000 0000000 [nosetests]
detailed-errors = 1
with-coverage = 1
cover-package = caldav
[build_sphinx]
source-dir = docs/source
build-dir = docs/build
all_files = 1
[egg_info]
tag_build =
tag_date = 0
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1568132280.0
caldav-0.6.2/setup.py 0000755 0016331 0016331 00000003044 00000000000 015256 0 ustar 00tobias tobias 0000000 0000000 #!/usr/bin/python
# -*- encoding: utf-8 -*-
from setuptools import setup, find_packages
version = '0.6.2'
if __name__ == '__main__':
## For python 2.7 and 3.5 we depend on pytz and tzlocal. For 3.6 and up, batteries are included.
try:
import datetime
from datetime import timezone
datetime.datetime.now().astimezone()
extra_packages = []
except:
extra_packages = ['pytz', 'tzlocal']
setup(
name='caldav',
version=version,
description="CalDAV (RFC4791) client library",
classifiers=["Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: GNU General "
"Public License (GPL)",
"License :: OSI Approved :: Apache Software License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Topic :: Office/Business :: Scheduling",
"Topic :: Software Development :: Libraries "
":: Python Modules"],
keywords='',
author='Cyril Robert',
author_email='cyril@hippie.io',
url='http://bitbucket.org/cyrilrbt/caldav',
license='GPL',
packages=find_packages(exclude=['tests']),
include_package_data=True,
zip_safe=False,
install_requires=['vobject', 'lxml', 'requests', 'six'] + extra_packages,
tests_require=['nose', 'coverage', 'tzlocal', 'pytz', 'xandikos']
)
././@PaxHeader 0000000 0000000 0000000 00000000033 00000000000 011451 x ustar 00 0000000 0000000 27 mtime=1574455519.232302
caldav-0.6.2/tests/ 0000755 0016331 0016331 00000000000 00000000000 014702 5 ustar 00tobias tobias 0000000 0000000 ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1568132280.0
caldav-0.6.2/tests/__init__.py 0000644 0016331 0016331 00000000000 00000000000 017001 0 ustar 00tobias tobias 0000000 0000000 ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1568132280.0
caldav-0.6.2/tests/_test_absolute.py 0000644 0016331 0016331 00000002412 00000000000 020267 0 ustar 00tobias tobias 0000000 0000000 # encoding: utf-8
import datetime
import caldav
class TestRadicale(object):
SUMMARIES = set(('Godspeed You! Black Emperor at '
'Cirque Royal / Koninklijk Circus',
'Standard - GBA'))
DTSTART = set((datetime.datetime(2011, 3, 4, 20, 0),
datetime.datetime(2011, 1, 15, 20, 0)))
def setup(self):
URL = 'http://localhost:8080/nicoe/perso/'
self.client = caldav.DAVClient(URL)
self.calendar = caldav.objects.Calendar(self.client, URL)
def test_eventslist(self):
events = self.calendar.events()
assert len(events) == 2
summaries, dtstart = set(), set()
for event in events:
event.load()
vobj = event.instance
summaries.add(vobj.vevent.summary.value)
dtstart.add(vobj.vevent.dtstart.value)
assert summaries == self.SUMMARIES
assert dtstart == self.DTSTART
class TestTryton(object):
def setup(self):
URL = 'http://admin:admin@localhost:9080/caldav/Calendars/Test'
self.client = caldav.DAVClient(URL)
self.calendar = caldav.objects.Calendar(self.client, URL)
def test_eventslist(self):
events = self.calendar.events()
assert len(events) == 1
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1568179401.0
caldav-0.6.2/tests/conf.py 0000644 0016331 0016331 00000005615 00000000000 016210 0 ustar 00tobias tobias 0000000 0000000 #!/usr/bin/env python
# -*- encoding: utf-8 -*-
## YOU SHOULD MOST LIKELY NOT EDIT THIS FILE!
## Make a conf_private.py for personal configuration.
## Check conf_private.py.EXAMPLE
####################################
# Import personal test server config
####################################
try:
from .conf_private import only_private ## legacy compatibility
test_public_test_servers = only_private
except ImportError:
try:
from .conf_private import public_test_servers
test_public_test_servers = only_private
except ImportError:
test_public_test_servers = False
try:
from .conf_private import caldav_servers
except ImportError:
caldav_servers = []
try:
from .conf_private import test_private_test_servers
if not test_private_test_servers:
caldav_servers = []
except ImportError:
pass
try:
from .conf_private import test_xandikos, xandikos_host, xandikos_port
except ImportError:
try:
import xandikos
test_xandikos = True
except:
test_xandikos = False
xandikos_host = 'localhost'
xandikos_port = 8993 ## random port above 8000
#####################
# Public test servers
#####################
## As of 2019-09, all of those are down. Will try to fix Real Soon.
if False:
#if test_public_test_servers:
## TODO: this one is set up on emphemeral storage on OpenShift and
## then configured manually through the webui installer, it will
## most likely only work for some few days until it's down again.
## It's needed to hard-code the configuration into
## https://github.com/python-caldav/baikal
caldav_servers.append({
"url": "http://baikal-caldav-servers.cloudapps.bitbit.net/html/cal.php/",
"username": "baikaluser",
"password": "asdf"})
# bedework:
# * todos and journals are not properly supported -
# ref https://github.com/Bedework/bedework/issues/5
# * propfind fails to return resourcetype,
# ref https://github.com/Bedework/bedework/issues/110
# * date search on recurrences of recurring events doesn't work
# (not reported yet - TODO)
caldav_servers.append({
"url": "http://bedework-caldav-servers.cloudapps.bitbit.net/ucaldav/",
"username": "vbede",
"password": "bedework",
"nojournal": True,
"notodo": True,
"nopropfind": True,
"norecurring": True})
caldav_servers.append({
"url": "http://xandikos-caldav-servers.cloudapps.bitbit.net/",
"username": "user1",
"password": "password1",
"norecurring": True
})
# radicale
caldav_servers.append({
"url": "http://radicale-caldav-servers.cloudapps.bitbit.net/",
"username": "testuser",
"password": "123",
"nofreebusy": True,
"nodefaultcalendar": True,
"noproxy": True
})
proxy = "127.0.0.1:8080"
proxy_noport = "127.0.0.1"
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1568132280.0
caldav-0.6.2/tests/conf_private.py.EXAMPLE 0000644 0016331 0016331 00000004416 00000000000 021032 0 ustar 00tobias tobias 0000000 0000000 ## PRIVATE CALDAV SERVER(S) TO RUN TESTS TOWARDS
## Make a list of your own servers/accounts that you'd like to run the
## test towards. Running the test suite towards a personal account
## should generally be safe, it should not mess up with content there
## and it should clean up after itself, but don't sue me if anything
## goes wrong ...
caldav_servers = [
{
## This is all that is really needed - url, username and
## password. The username and password may also be passed in
## the URL itself (like
## https://sam_i_am:hunter2@server.example.ccom/)
'url': 'https://some.server.example.com',
'username': 'testuser',
'password': 'hunter2',
## There are some boolean options that may be passed i.e. to
## skip tests (many CalDAV server features are marked as
## optional in the RFC, for one thing), to skip verifying SSL
## certificate, etc. Leave the list blank on first attempt, then
## add things as needed.
#'nocalendarnotfound': True,
#'nodefaultcalendar: True,
#'noproxy': True,
#'nojournal': True,
#'nofreebusy': True.
#'notodo': True,
#'nopropfind': True,
#'norecurring': True,
#'ssl_cert_verify': False
}]
## MASTER SWITCHES FOR TEST SERVER SETUP
## With those configuration switches, pre-configured test servers in conf.py
## can be turned on or off
## test_public_test_servers - Use the list of common public test
## servers from conf.py. This has proven to be unreliable and
## fragile, hence the default has now been flipped to False. It's
## very important to run through all the different server
## implementations and try to figure out of all breakages before any
## major release - and it ought to be done before any minor release as well.
test_public_test_servers = False
## test_private_test_servers - test using the list configured above in this file.
test_private_test_servers = True
## test_xandikos - since the xandikos caldav server implementation is
## written in python and can be instantiated quite easily, this will
## be the default caldav implementation to test towards ... but, unfortunately
## it works only with python 3.4 and higher
test_xandikos = True
## DEPRECATED - only_private is superceded by test_public_servers,
## left here for backward-compatibility.
#only_private=False
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1568132280.0
caldav-0.6.2/tests/proxy.py 0000644 0016331 0016331 00000025775 00000000000 016455 0 ustar 00tobias tobias 0000000 0000000 #!/usr/bin/python
"""Tiny HTTP Proxy.
This module implements GET, HEAD, POST, PUT and DELETE methods
on BaseHTTPServer, and behaves as an HTTP proxy. The CONNECT
method is also implemented experimentally, but has not been
tested yet.
Any help will be greatly appreciated. SUZUKI Hisao
2009/11/23 - Modified by Mitko Haralanov
* Added very simple FTP file retrieval
* Added custom logging methods
* Added code to make this a standalone application
"""
import ftplib
import getopt
import logging
import logging.handlers
import os
import select
import signal
import socket
import sys
import threading
from six import PY3
from types import FrameType, CodeType
from time import sleep
from caldav.lib.python_utilities import to_wire, to_local
if PY3:
from urllib import parse
from urllib.parse import urlparse, urlunparse
from http.server import BaseHTTPRequestHandler, HTTPServer
from socketserver import ThreadingMixIn
else:
from urlparse import urlparse as parse
from urlparse import urlparse, urlunparse
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from SocketServer import ThreadingMixIn
__version__ = "0.3.1"
DEFAULT_LOG_FILENAME = "proxy.log"
class ProxyHandler (BaseHTTPRequestHandler):
__base = BaseHTTPRequestHandler
__base_handle = __base.handle
server_version = "TinyHTTPProxy/" + __version__
rbufsize = 0 # self.rfile Be unbuffered
def handle(self):
(ip, port) = self.client_address
self.server.logger.log(logging.INFO, "Request from '%s'", ip)
if hasattr(self, 'allowed_clients') and ip not in self.allowed_clients:
self.raw_requestline = self.rfile.readline()
if self.parse_request():
self.send_error(403)
else:
self.__base_handle()
def _connect_to(self, netloc, soc):
i = netloc.find(':')
if i >= 0:
host_port = netloc[:i], int(netloc[i + 1:])
else:
host_port = netloc, 80
self.server.logger.log(
logging.INFO, "connect to %s:%d", host_port[0], host_port[1])
try:
soc.connect(host_port)
except socket.error as arg:
try:
msg = arg[1]
except:
msg = arg
self.send_error(404, msg)
return 0
return 1
def do_CONNECT(self):
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
if self._connect_to(self.path, soc):
self.log_request(200)
self.wfile.write(self.protocol_version +
" 200 Connection established\r\n")
self.wfile.write("Proxy-agent: %s\r\n" % self.version_string())
self.wfile.write("\r\n")
self._read_write(soc, 300)
finally:
soc.close()
self.connection.close()
def do_GET(self):
(scm, netloc, path, params, query, fragment) = urlparse(
self.path, 'http')
if scm not in ('http', 'ftp') or fragment or not netloc:
self.send_error(400, "bad url %s" % self.path)
return
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
if scm == 'http':
if self._connect_to(netloc, soc):
self.log_request()
soc.send(to_wire("%s %s %s\r\n" % (
self.command,
urlunparse(('', '', path, params, query, '')),
self.request_version)))
self.headers['Connection'] = 'close'
del self.headers['Proxy-Connection']
for key_val in list(self.headers.items()):
soc.send(to_wire("%s: %s\r\n" % key_val))
soc.send(to_wire("\r\n"))
self._read_write(soc)
elif scm == 'ftp':
# fish out user and password information
i = netloc.find('@')
if i >= 0:
login_info, netloc = netloc[:i], netloc[i + 1:]
try:
user, passwd = login_info.split(':', 1)
except ValueError:
user, passwd = "anonymous", None
else:
user, passwd = "anonymous", None
self.log_request()
try:
ftp = ftplib.FTP(netloc)
ftp.login(user, passwd)
if self.command == "GET":
ftp.retrbinary("RETR %s" % path, self.connection.send)
ftp.quit()
except Exception as e:
self.server.logger.log(
logging.WARNING, "FTP Exception: %s", e)
finally:
soc.close()
self.connection.close()
def _read_write(self, soc, max_idling=20, local=False):
iw = [self.connection, soc]
local_data = ""
ow = []
count = 0
while 1:
count += 1
(ins, _, exs) = select.select(iw, ow, iw, 1)
if exs:
break
if ins:
for i in ins:
if i is soc:
out = self.connection
else:
out = soc
data = i.recv(8192)
if data:
if local:
local_data += data
else:
out.send(data)
count = 0
if count == max_idling:
break
if local:
return to_local(local_data)
return None
do_HEAD = do_GET
do_POST = do_GET
do_PUT = do_GET
do_DELETE = do_GET
do_PROPFIND = do_GET
def log_message(self, format, *args):
self.server.logger.log(
logging.INFO, "%s %s", self.address_string(), format % args)
def log_error(self, format, *args):
self.server.logger.log(
logging.ERROR, "%s %s", self.address_string(), format % args)
class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
def __init__(self, server_address, RequestHandlerClass, logger=None):
HTTPServer.__init__(self, server_address, RequestHandlerClass)
self.logger = logger
class NonThreadingHTTPServer(HTTPServer):
def __init__(self, server_address, RequestHandlerClass, logger=None):
HTTPServer.__init__(self, server_address, RequestHandlerClass)
self.logger = logger
def logSetup(filename, log_size, daemon):
logger = logging.getLogger("TinyHTTPProxy")
logger.setLevel(logging.INFO)
if not filename:
if not daemon:
# display to the screen
handler = logging.StreamHandler()
else:
handler = logging.handlers.RotatingFileHandler(
DEFAULT_LOG_FILENAME, maxBytes=(log_size * (1 << 20)),
backupCount=5)
else:
handler = logging.handlers.RotatingFileHandler(
filename, maxBytes=(log_size * (1 << 20)), backupCount=5)
fmt = logging.Formatter("[%(asctime)-12s.%(msecs)03d] "
"%(levelname)-8s {%(name)s %(threadName)s}"
" %(message)s",
"%Y-%m-%d %H:%M:%S")
handler.setFormatter(fmt)
logger.addHandler(handler)
return logger
def usage(msg=None):
if msg:
print(msg)
print(sys.argv[0],
"[-p port] [-l logfile] [-dh] [allowed_client_name ...]]")
print()
print(" -p - Port to bind to")
print(" -l - Path to logfile. If not specified, STDOUT is used")
print(" -d - Run in the background")
print()
def handler(signo, frame):
while frame and isinstance(frame, FrameType):
if frame.f_code and isinstance(frame.f_code, CodeType):
if "run_event" in frame.f_code.co_varnames:
frame.f_locals["run_event"].set()
return
frame = frame.f_back
def daemonize(logger):
class DevNull(object):
def __init__(self): self.fd = os.open("/dev/null", os.O_WRONLY)
def write(self, *args, **kwargs): return 0
def read(self, *args, **kwargs): return 0
def fileno(self): return self.fd
def close(self): os.close(self.fd)
class ErrorLog:
def __init__(self, obj): self.obj = obj
def write(self, string): self.obj.log(logging.ERROR, string)
def read(self, *args, **kwargs): return 0
def close(self): pass
if os.fork() != 0:
# allow the child pid to instanciate the server
# class
sleep(1)
sys.exit(0)
os.setsid()
fd = os.open('/dev/null', os.O_RDONLY)
if fd != 0:
os.dup2(fd, 0)
os.close(fd)
null = DevNull()
log = ErrorLog(logger)
sys.stdout = null
sys.stderr = log
sys.stdin = null
fd = os.open('/dev/null', os.O_WRONLY)
# if fd != 1: os.dup2(fd, 1)
os.dup2(sys.stdout.fileno(), 1)
if fd != 2:
os.dup2(fd, 2)
if fd not in (1, 2):
os.close(fd)
def main():
logfile = None
daemon = False
max_log_size = 20
port = 8080
allowed = []
run_event = threading.Event()
local_hostname = socket.gethostname()
try:
opts, args = getopt.getopt(sys.argv[1:], "l:dhp:", [])
except getopt.GetoptError as e:
usage(str(e))
return 1
for opt, value in opts:
if opt == "-p": port = int(value)
if opt == "-l": logfile = value
if opt == "-d": daemon = not daemon
if opt == "-h":
usage()
return 0
# setup the log file
logger = logSetup(logfile, max_log_size, daemon)
if daemon:
daemonize(logger)
signal.signal(signal.SIGINT, handler)
if args:
allowed = []
for name in args:
client = socket.gethostbyname(name)
allowed.append(client)
logger.log(logging.INFO, "Accept: %s (%s)" % (client, name))
ProxyHandler.allowed_clients = allowed
else:
logger.log(logging.INFO, "Any clients will be served...")
server_address = (socket.gethostbyname(local_hostname), port)
ProxyHandler.protocol = "HTTP/1.0"
httpd = ThreadingHTTPServer(server_address, ProxyHandler, logger)
sa = httpd.socket.getsockname()
print("Servering HTTP on", sa[0], "port", sa[1])
req_count = 0
while not run_event.isSet():
try:
httpd.handle_request()
req_count += 1
if req_count == 1000:
logger.log(logging.INFO, "Number of active threads: %s",
threading.activeCount())
req_count = 0
except select.error as e:
if e[0] == 4 and run_event.isSet():
pass
else:
logger.log(logging.CRITICAL, "Errno: %d - %s", e[0], e[1])
logger.log(logging.INFO, "Server shutdown")
return 0
if __name__ == '__main__':
sys.exit(main())
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1568132280.0
caldav-0.6.2/tests/test_caldav.py 0000644 0016331 0016331 00000115705 00000000000 017556 0 ustar 00tobias tobias 0000000 0000000 #!/usr/bin/env python
# -*- encoding: utf-8 -*-
import logging
import threading
import time
import vobject
import uuid
import tempfile
from datetime import datetime
from six import PY3
from nose.tools import assert_equal, assert_not_equal, assert_raises
from nose.plugins.skip import SkipTest
from requests.packages import urllib3
from .conf import caldav_servers, proxy, proxy_noport, test_xandikos, xandikos_port, xandikos_host
from .proxy import ProxyHandler, NonThreadingHTTPServer
from caldav.davclient import DAVClient
from caldav.objects import (Principal, Calendar, Event, DAVObject,
CalendarSet, FreeBusy)
from caldav.lib.url import URL
from caldav.lib import url
from caldav.lib import error
from caldav.elements import dav, cdav
from caldav.lib.python_utilities import to_local, to_str
if test_xandikos:
from xandikos.web import XandikosBackend, XandikosApp
from wsgiref.simple_server import make_server
if PY3:
from urllib.parse import urlparse
else:
from urlparse import urlparse
log = logging.getLogger("caldav")
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
ev1 = """BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Example Corp.//CalDAV Client//EN
BEGIN:VEVENT
UID:20010712T182145Z-123401@example.com
DTSTAMP:20060712T182145Z
DTSTART:20060714T170000Z
DTEND:20060715T040000Z
SUMMARY:Bastille Day Party
END:VEVENT
END:VCALENDAR
"""
ev2 = """BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Example Corp.//CalDAV Client//EN
BEGIN:VEVENT
UID:20010712T182145Z-123401@example.com
DTSTAMP:20070712T182145Z
DTSTART:20070714T170000Z
DTEND:20070715T040000Z
SUMMARY:Bastille Day Party +1year
END:VEVENT
END:VCALENDAR
"""
# example from http://www.rfc-editor.org/rfc/rfc5545.txt
evr = """BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Example Corp.//CalDAV Client//EN
BEGIN:VEVENT
UID:19970901T130000Z-123403@example.com
DTSTAMP:19970901T130000Z
DTSTART;VALUE=DATE:19971102
SUMMARY:Our Blissful Anniversary
TRANSP:TRANSPARENT
CLASS:CONFIDENTIAL
CATEGORIES:ANNIVERSARY,PERSONAL,SPECIAL OCCASION
RRULE:FREQ=YEARLY
END:VEVENT
END:VCALENDAR"""
# example from http://www.rfc-editor.org/rfc/rfc5545.txt
todo = """BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Example Corp.//CalDAV Client//EN
BEGIN:VTODO
UID:20070313T123432Z-456553@example.com
DTSTAMP:20070313T123432Z
DUE;VALUE=DATE:20070501
SUMMARY:Submit Quebec Income Tax Return for 2006
CLASS:CONFIDENTIAL
CATEGORIES:FAMILY,FINANCE
STATUS:NEEDS-ACTION
END:VTODO
END:VCALENDAR"""
# example from RFC2445, 4.6.2
todo2 = """BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Example Corp.//CalDAV Client//EN
BEGIN:VTODO
UID:19970901T130000Z-123404@host.com
DTSTAMP:19970901T130000Z
DTSTART:19970415T133000Z
DUE:19970416T045959Z
SUMMARY:1996 Income Tax Preparation
CLASS:CONFIDENTIAL
CATEGORIES:FAMILY,FINANCE
PRIORITY:2
STATUS:NEEDS-ACTION
END:VTODO
END:VCALENDAR"""
todo3 = """
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Example Corp.//CalDAV Client//EN
BEGIN:VTODO
UID:19970901T130000Z-123405@host.com
DTSTAMP:19970901T130000Z
DTSTART:19970415T133000Z
DUE:19970516T045959Z
SUMMARY:1996 Income Tax Preparation
CLASS:CONFIDENTIAL
CATEGORIES:FAMILY,FINANCE
PRIORITY:1
END:VTODO
END:VCALENDAR"""
todo4 = """
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Example Corp.//CalDAV Client//EN
BEGIN:VTODO
UID:19970901T130000Z-123406@host.com
DTSTAMP:19970901T130000Z
SUMMARY:1996 Income Tax Preparation
CLASS:CONFIDENTIAL
CATEGORIES:FAMILY,FINANCE
PRIORITY:1
STATUS:NEEDS-ACTION
END:VTODO
END:VCALENDAR"""
# example from http://www.kanzaki.com/docs/ical/vjournal.html
journal = """
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Example Corp.//CalDAV Client//EN
BEGIN:VJOURNAL
UID:19970901T130000Z-123405@example.com
DTSTAMP:19970901T130000Z
DTSTART;VALUE=DATE:19970317
SUMMARY:Staff meeting minutes
DESCRIPTION:1. Staff meeting: Participants include Joe\, Lisa
and Bob. Aurora project plans were reviewed. There is currently
no budget reserves for this project. Lisa will escalate to
management. Next meeting on Tuesday.\n
END:VJOURNAL
END:VCALENDAR
"""
class RepeatedFunctionalTestsBaseClass(object):
"""This is a class with functional tests (tests that goes through
basic functionality and actively communicates with third parties)
that we want to repeat for all configured caldav_servers.
(what a truely ugly name for this class - any better ideas?)
NOTE: this tests relies heavily on the assumption that we can create
calendars on the remote caldav server, but the RFC says ...
Support for MKCALENDAR on the server is only RECOMMENDED and not
REQUIRED because some calendar stores only support one calendar per
user (or principal), and those are typically pre-created for each
account.
On iCloud I've been denied creating a calendar. Creating a
calendar through the WebUI works, and creating an event through
the library fails, so I don't think the problem is lack of
MKCALENDAR support.
On Radicale, apparently there is some bug with MKCALENDAR, ref
https://github.com/Kozea/Radicale/issues/330
"""
def setup(self):
logging.debug("############## test setup")
if self.server_params.get('unique_calendar_ids', False):
self.testcal_id = 'testcalendar-' + str(uuid.uuid4())
self.testcal_id2 = 'testcalendar-' + str(uuid.uuid4())
else:
self.testcal_id = "pythoncaldav-test"
self.testcal_id2 = "pythoncaldav-test2"
self.conn_params = self.server_params.copy()
for x in list(self.conn_params.keys()):
if x not in ('url', 'proxy', 'username', 'password',
'ssl_verify_cert'):
self.conn_params.pop(x)
self.caldav = DAVClient(**self.conn_params)
self.principal = self.caldav.principal()
logging.debug("## going to tear down old test calendars, "
"in case teardown wasn't properly executed "
"last time tests were run")
self._teardown()
logging.debug("##############################")
logging.debug("############## test setup done")
logging.debug("##############################")
def teardown(self):
logging.debug("############################")
logging.debug("############## test teardown")
logging.debug("############################")
self._teardown()
logging.debug("############## test teardown done")
def _teardown(self):
for combos in (('Yep', self.testcal_id),
('Yep', self.testcal_id2),
('Yølp', self.testcal_id),
('Yep', 'Yep'),
('Yølp', 'Yølp')):
try:
cal = self.principal.calendar(name="Yep",
cal_id=self.testcal_id)
cal.delete()
except:
pass
def testPropfind(self):
"""
Test of the propfind methods. (This is sort of redundant, since
this is implicitly run by the setup)
"""
# ResourceType MUST be defined, and SHOULD be returned on a propfind
# for "allprop" if I have the permission to see it.
# So, no ResourceType returned seems like a bug in bedework
if 'nopropfind' in self.server_params:
raise SkipTest("Skipping propfind test, "
"re test suite configuration. "
"Perhaps the caldav server is not adhering to "
"the standards")
# first a raw xml propfind to the root URL
foo = self.caldav.propfind(
self.principal.url,
props=''
''
' '
'')
assert('resourcetype' in to_local(foo.raw))
# next, the internal _query_properties, returning an xml tree ...
foo2 = self.principal._query_properties([dav.Status(), ])
assert('resourcetype' in to_local(foo.raw))
# TODO: more advanced asserts
def testGetCalendarHomeSet(self):
chs = self.principal.get_properties([cdav.CalendarHomeSet()])
assert '{urn:ietf:params:xml:ns:caldav}calendar-home-set' in chs
def testGetDefaultCalendar(self):
if 'nodefaultcalendar' in self.server_params:
raise SkipTest("Skipping GetDefaultCalendar, caldav server has no default calendar for the user?")
assert_not_equal(len(self.principal.calendars()), 0)
def testGetCalendar(self):
# Create calendar
c = self.principal.make_calendar(name="Yep", cal_id=self.testcal_id)
assert_not_equal(c.url, None)
assert_not_equal(len(self.principal.calendars()), 0)
def testProxy(self):
if self.caldav.url.scheme == 'https' or 'noproxy' in self.server_params:
raise SkipTest("Skipping %s.testProxy as the TinyHTTPProxy "
"implementation doesn't support https")
server_address = ('127.0.0.1', 8080)
proxy_httpd = NonThreadingHTTPServer(
server_address, ProxyHandler, logging.getLogger("TinyHTTPProxy"))
threadobj = threading.Thread(target=proxy_httpd.serve_forever)
try:
threadobj.start()
assert(threadobj.is_alive())
conn_params = self.conn_params.copy()
conn_params['proxy'] = proxy
c = DAVClient(**conn_params)
p = c.principal()
assert_not_equal(len(p.calendars()), 0)
finally:
proxy_httpd.shutdown()
# this should not be necessary, but I've observed some failures
if threadobj.is_alive():
time.sleep(0.05)
assert(not threadobj.is_alive())
threadobj = threading.Thread(target=proxy_httpd.serve_forever)
try:
threadobj.start()
assert(threadobj.is_alive())
conn_params = self.conn_params.copy()
conn_params['proxy'] = proxy_noport
c = DAVClient(**conn_params)
p = c.principal()
assert_not_equal(len(p.calendars()), 0)
assert(threadobj.is_alive())
finally:
proxy_httpd.shutdown()
# this should not be necessary
if threadobj.is_alive():
time.sleep(0.05)
assert(not threadobj.is_alive())
def testPrincipal(self):
collections = self.principal.calendars()
if 'principal_url' in self.server_params:
assert_equal(self.principal.url,
self.server_params['principal_url'])
for c in collections:
assert_equal(c.__class__.__name__, "Calendar")
def testCreateDeleteCalendar(self):
c = self.principal.make_calendar(name="Yep", cal_id=self.testcal_id)
assert_not_equal(c.url, None)
events = c.events()
assert_equal(len(events), 0)
events = self.principal.calendar(
name="Yep", cal_id=self.testcal_id).events()
# huh ... we're quite constantly getting out a list with one item,
# the URL for the caldav server. This needs to be investigated,
# it is surely a bug in our code.
# Anyway, better to ignore it now than to have broken test code.
assert_equal(len(events), 0)
c.delete()
# verify that calendar does not exist - this breaks with zimbra :-(
# (also breaks with radicale, which by default creates a new calendar)
# COMPATIBILITY PROBLEM - todo, look more into it
if 'nocalendarnotfound' not in self.server_params:
assert_raises(
error.NotFoundError,
self.principal.calendar(
name="Yep", cal_id=self.testcal_id).events)
def testCreateCalendarAndEvent(self):
c = self.principal.make_calendar(name="Yep", cal_id=self.testcal_id)
# add event
c.add_event(ev1)
# c.events() should give a full list of events
events = c.events()
assert_equal(len(events), 1)
# We should be able to access the calender through the URL
c2 = Calendar(client=self.caldav, url=c.url)
events2 = c2.events()
assert_equal(len(events2), 1)
assert_equal(events2[0].url, events[0].url)
def testCreateCalendarAndEventFromVobject(self):
c = self.principal.make_calendar(name="Yep", cal_id=self.testcal_id)
# add event from vobject data
ve1 = vobject.readOne(ev1)
c.add_event(ve1)
# c.events() should give a full list of events
events = c.events()
assert_equal(len(events), 1)
# We should be able to access the calender through the URL
c2 = Calendar(client=self.caldav, url=c.url)
events2 = c2.events()
assert_equal(len(events2), 1)
assert_equal(events2[0].url, events[0].url)
def testCreateJournalListAndJournalEntry(self):
"""
This test demonstrates the support for journals.
* It will create a journal list
* It will add some journal entries to it
* It will list out all journal entries
"""
if 'nojournal' in self.server_params:
# COMPATIBILITY TODO: read the RFC. sabredav/owncloud:
# got the error: "This calendar only supports VEVENT,
# VTODO. We found a VJOURNAL". Should probably learn
# that some other way. (why doesn't make_calendar break?
# what does the RFC say on that?) Same with zimbra,
# though different error.
raise SkipTest("Journal testing skipped due to test configuration")
c = self.principal.make_calendar(
name="Yep", cal_id=self.testcal_id,
supported_calendar_component_set=['VJOURNAL'])
j1 = c.add_journal(journal)
journals = c.journals()
assert_equal(len(journals), 1)
todos = c.todos()
events = c.events()
assert_equal(todos + events, [])
def testCreateTaskListAndTodo(self):
"""
This test demonstrates the support for task lists.
* It will create a "task list"
* It will add a task to it
* Verify the cal.todos() method
* Verify that cal.events() method returns nothing
"""
# bedeworks does not support VTODO
if 'notodo' in self.server_params:
raise SkipTest("VTODO testing skipped due to test configuration")
# For all servers I've tested against except Zimbra, it's
# possible to create a calendar and add todo-items to it.
# Zimbra has separate calendars and task lists, and it's not
# allowed to put TODO-tasks into the calendar. We need to
# tell Zimbra that the new "calendar" is a task list. This
# is done though the supported_calendar_compontent_set
# property - hence the extra parameter here:
logging.info("Creating calendar Yep for tasks")
c = self.principal.make_calendar(
name="Yep", cal_id=self.testcal_id,
supported_calendar_component_set=['VTODO'])
# add todo-item
logging.info("Adding todo item to calendar Yep")
t1 = c.add_todo(todo)
# c.todos() should give a full list of todo items
logging.info("Fetching the full list of todo items (should be one)")
todos = c.todos()
todos2 = c.todos(include_completed=True)
assert_equal(len(todos), 1)
assert_equal(len(todos2), 1)
logging.info("Fetching the events (should be none)")
# c.events() should NOT return todo-items
events = c.events()
assert_equal(len(events), 0)
def testTodos(self):
"""
This test will excercise the cal.todos() method,
and in particular the sort_keys attribute.
* It will list out all pending tasks, sorted by due date
* It will list out all pending tasks, sorted by priority
"""
# bedeworks does not support VTODO
if 'notodo' in self.server_params:
raise SkipTest("VTODO testing skipped due to test configuration")
c = self.principal.make_calendar(
name="Yep", cal_id=self.testcal_id,
supported_calendar_component_set=['VTODO'])
# add todo-item
t1 = c.add_todo(todo)
t2 = c.add_todo(todo2)
t3 = c.add_todo(todo3)
todos = c.todos()
assert_equal(len(todos), 3)
def uids(lst):
return [x.instance.vtodo.uid for x in lst]
assert_equal(uids(todos), uids([t2, t3, t1]))
todos = c.todos(sort_keys=('priority',))
def pri(lst):
return [x.instance.vtodo.priority.value for x in lst
if hasattr(x.instance.vtodo, 'priority')]
assert_equal(pri(todos), pri([t3, t2]))
todos = c.todos(sort_keys=('summary', 'priority',))
assert_equal(uids(todos), uids([t3, t2, t1]))
def testTodoDatesearch(self):
"""
Let's see how the date search method works for todo events
"""
# bedeworks does not support VTODO
if 'notodo' in self.server_params:
raise SkipTest("VTODO testing skipped due to test configuration")
c = self.principal.make_calendar(
name="Yep", cal_id=self.testcal_id,
supported_calendar_component_set=['VTODO'])
# add todo-item
t1 = c.add_todo(todo)
t2 = c.add_todo(todo2)
t3 = c.add_todo(todo3)
t4 = c.add_todo(todo4)
todos = c.todos()
assert_equal(len(todos), 4)
notodos = c.date_search( # default compfilter is events
start=datetime(1997, 4, 14), end=datetime(2015, 5, 14),
expand=False)
assert(not notodos)
# Now, this is interesting. 2 events have dtstart set, 3 has
# due set and 1 has neither due nor dtstart set. None has
# duration set. What will a date search yield?
todos = c.date_search(
start=datetime(1997, 4, 14), end=datetime(2015, 5, 14),
compfilter='VTODO', expand=False)
# The RFCs are pretty clear on this. rfc5545 states:
# A "VTODO" calendar component without the "DTSTART" and "DUE" (or
# "DURATION") properties specifies a to-do that will be associated
# with each successive calendar date, until it is completed.
# and RFC4791, section 9.9 also says that events without
# dtstart or due should be counted. Since we have "expand"
# set, it could even imply that we should get two VTODO items
# our for each day in the time range! In any case, less than
# 4 todos returned is a breach of the RFCs.
# TODO: prod the caldav server implementators about the RFC
# breakages.
# This is probably correct, and most server implementations
# give this:
# assert_equal(len(todos), 4)
# ... but some caldav implementations yields 2 and 3:
assert(len(todos) >= 2)
def testTodoCompletion(self):
"""
Will check that todo-items can be completed and deleted
"""
# bedeworks does not support VTODO
if 'notodo' in self.server_params:
raise SkipTest("VTODO testing skipped due to test configuration")
c = self.principal.make_calendar(
name="Yep", cal_id=self.testcal_id,
supported_calendar_component_set=['VTODO'])
# add todo-items
t1 = c.add_todo(todo)
t2 = c.add_todo(todo2)
t3 = c.add_todo(todo3)
# There are now three todo-items at the calendar
todos = c.todos()
assert_equal(len(todos), 3)
# Complete one of them
t3.complete()
# There are now two todo-items at the calendar
todos = c.todos()
assert_equal(len(todos), 2)
# The historic todo-item can still be accessed
todos = c.todos(include_completed=True)
assert_equal(len(todos), 3)
t2.delete()
# ... the deleted one is gone ...
todos = c.todos(include_completed=True)
assert_equal(len(todos), 2)
# date search should not include completed events ... hum.
# TODO, fixme.
# todos = c.date_search(
# start=datetime(1990, 4, 14), end=datetime(2015,5,14),
# compfilter='VTODO', hide_completed_todos=True)
# assert_equal(len(todos), 1)
def testUtf8Event(self):
c = self.principal.make_calendar(name="Yølp", cal_id=self.testcal_id)
# add event
e1 = c.add_event(
ev1.replace("Bastille Day Party", "Bringebærsyltetøyfestival"))
events = c.events()
todos = c.todos()
assert_equal(len(todos), 0)
# COMPATIBILITY PROBLEM - todo, look more into it
if 'zimbra' not in str(c.url):
assert_equal(len(events), 1)
def testUnicodeEvent(self):
c = self.principal.make_calendar(name="Yølp", cal_id=self.testcal_id)
# add event
e1 = c.add_event(to_str(
ev1.replace("Bastille Day Party", "Bringebærsyltetøyfestival")))
# c.events() should give a full list of events
events = c.events()
# COMPATIBILITY PROBLEM - todo, look more into it
if 'zimbra' not in str(c.url):
assert_equal(len(events), 1)
def testSetCalendarProperties(self):
c = self.principal.make_calendar(name="Yep", cal_id=self.testcal_id)
assert_not_equal(c.url, None)
props = c.get_properties([dav.DisplayName(), ])
assert_equal("Yep", props[dav.DisplayName.tag])
# Creating a new calendar with different ID but with existing name
# - fails on zimbra only.
# This is OK to fail.
if 'zimbra' in str(c.url):
assert_raises(Exception, self.principal.make_calendar,
"Yep", self.testcal_id2)
else:
# This may fail, and if it fails, add an exception to the test
# (see the "if" above)
cc = self.principal.make_calendar("Yep", self.testcal_id2)
cc.delete()
c.set_properties([dav.DisplayName("hooray"), ])
props = c.get_properties([dav.DisplayName(), ])
assert_equal(props[dav.DisplayName.tag], "hooray")
# Creating a new calendar with different ID and old name, this should
# work, shouldn't it?
# ... ouch, now it fails with a 409 on zimbra (it didn't fail
# earlier)
if not 'zimbra' in str(c.url):
cc = self.principal.make_calendar(
name="Yep", cal_id=self.testcal_id2).save()
assert_not_equal(cc.url, None)
cc.delete()
def testLookupEvent(self):
"""
Makes sure we can add events and look them up by URL and ID
"""
# Create calendar
c = self.principal.make_calendar(name="Yep", cal_id=self.testcal_id)
assert_not_equal(c.url, None)
# add event
e1 = c.add_event(ev1)
assert_not_equal(e1.url, None)
# Verify that we can look it up, both by URL and by ID
e2 = c.event_by_url(e1.url)
e3 = c.event_by_uid("20010712T182145Z-123401@example.com")
assert_equal(e2.instance.vevent.uid, e1.instance.vevent.uid)
assert_equal(e3.instance.vevent.uid, e1.instance.vevent.uid)
# Knowing the URL of an event, we should be able to get to it
# without going through a calendar object
e4 = Event(client=self.caldav, url=e1.url)
e4.load()
assert_equal(e4.instance.vevent.uid, e1.instance.vevent.uid)
assert_raises(error.NotFoundError, c.event_by_uid, "0")
c.add_event(evr)
assert_raises(error.NotFoundError, c.event_by_uid, "0")
def testDeleteEvent(self):
"""
Makes sure we can add events and delete them
"""
# Create calendar
c = self.principal.make_calendar(name="Yep", cal_id=self.testcal_id)
assert_not_equal(c.url, None)
# add event
e1 = c.add_event(ev1)
assert_not_equal(e1.url, None)
# delete event
e1.delete()
# Verify that we can't look it up, both by URL and by ID
assert_raises(error.NotFoundError, c.event_by_url, e1.url)
assert_raises(
error.NotFoundError, c.event_by_uid,
"20010712T182145Z-123401@example.com")
def testDateSearchAndFreeBusy(self):
"""
Verifies that date search works with a non-recurring event
Also verifies that it's possible to change a date of a
non-recurring event
"""
# Create calendar, add event ...
c = self.principal.make_calendar(name="Yep", cal_id=self.testcal_id)
assert_not_equal(c.url, None)
e = c.add_event(ev1)
# .. and search for it.
r = c.date_search(datetime(2006, 7, 13, 17, 00, 00),
datetime(2006, 7, 15, 17, 00, 00), expand=False)
assert_equal(e.instance.vevent.uid, r[0].instance.vevent.uid)
assert_equal(len(r), 1)
# ev2 is same UID, but one year ahead.
# The timestamp should change.
e.data = ev2
e.save()
r = c.date_search(datetime(2006, 7, 13, 17, 00, 00),
datetime(2006, 7, 15, 17, 00, 00), expand=False)
assert_equal(len(r), 0)
r = c.date_search(datetime(2007, 7, 13, 17, 00, 00),
datetime(2007, 7, 15, 17, 00, 00), expand=False)
assert_equal(len(r), 1)
# date search without closing date should also find it
r = c.date_search(datetime(2007, 7, 13, 17, 00, 00), expand=False)
assert_equal(len(r), 1)
# Lets try a freebusy request as well
if 'nofreebusy' in self.server_params:
raise SkipTest("FreeBusy test skipped - not supported by server?")
freebusy = c.freebusy_request(datetime(2007, 7, 13, 17, 00, 00),
datetime(2007, 7, 15, 17, 00, 00))
# TODO: assert something more complex on the return object
assert(isinstance(freebusy, FreeBusy))
assert(freebusy.instance.vfreebusy)
def testRecurringDateSearch(self):
"""
This is more sanity testing of the server side than testing of the
library per se. How will it behave if we serve it a recurring
event?
"""
if 'norecurring' in self.server_params:
raise SkipTest("recurring date search test skipped due to "
"test configuration")
c = self.principal.make_calendar(name="Yep", cal_id=self.testcal_id)
# evr is a yearly event starting at 1997-02-11
e = c.add_event(evr)
r = c.date_search(datetime(2008, 11, 1, 17, 00, 00),
datetime(2008, 11, 3, 17, 00, 00), expand=True)
assert_equal(len(r), 1)
assert_equal(r[0].data.count("END:VEVENT"), 1)
r = c.date_search(datetime(2008, 11, 1, 17, 00, 00),
datetime(2009, 11, 3, 17, 00, 00), expand=True)
assert_equal(len(r), 1)
# So much for standards ... seems like different servers
# behaves differently
# COMPATIBILITY PROBLEMS - look into it
if "RRULE" in r[0].data and "BEGIN:STANDARD" not in r[0].data:
assert_equal(r[0].data.count("END:VEVENT"), 1)
else:
assert_equal(r[0].data.count("END:VEVENT"), 2)
# The recurring events should not be expanded when using the
# events() method
r = c.events()
assert_equal(len(r), 1)
def testBackwardCompatibility(self):
"""
Tobias Brox has done some API changes - but this thing should
still be backward compatible.
"""
if 'backwards_compatibility_url' not in self.server_params:
return
caldav = DAVClient(self.server_params['backwards_compatibility_url'])
principal = Principal(
caldav, self.server_params['backwards_compatibility_url'])
c = Calendar(
caldav, name="Yep", parent=principal,
id=self.testcal_id).save()
assert_not_equal(c.url, None)
c.set_properties([dav.DisplayName("hooray"), ])
props = c.get_properties([dav.DisplayName(), ])
assert_equal(props[dav.DisplayName.tag], "hooray")
cc = Calendar(caldav, name="Yep", parent=principal).save()
assert_not_equal(cc.url, None)
cc.delete()
e = Event(caldav, data=ev1, parent=c).save()
assert_not_equal(e.url, None)
ee = Event(caldav, url=url.make(e.url), parent=c)
ee.load()
assert_equal(e.instance.vevent.uid, ee.instance.vevent.uid)
r = c.date_search(datetime(2006, 7, 13, 17, 00, 00),
datetime(2006, 7, 15, 17, 00, 00), expand=False)
assert_equal(e.instance.vevent.uid, r[0].instance.vevent.uid)
assert_equal(len(r), 1)
all = c.events()
assert_equal(len(all), 1)
e2 = Event(caldav, data=ev2, parent=c).save()
assert_not_equal(e.url, None)
tmp = c.event("20010712T182145Z-123401@example.com")
assert_equal(e2.instance.vevent.uid, tmp.instance.vevent.uid)
r = c.date_search(datetime(2007, 7, 13, 17, 00, 00),
datetime(2007, 7, 15, 17, 00, 00), expand=False)
assert_equal(len(r), 1)
e.data = ev2
e.save()
r = c.date_search(datetime(2007, 7, 13, 17, 00, 00),
datetime(2007, 7, 15, 17, 00, 00), expand=False)
# for e in r: print(e.data)
assert_equal(len(r), 1)
e.instance = e2.instance
e.save()
r = c.date_search(datetime(2007, 7, 13, 17, 00, 00),
datetime(2007, 7, 15, 17, 00, 00), expand=False)
# for e in r: print(e.data)
assert_equal(len(r), 1)
def testObjects(self):
# TODO: description ... what are we trying to test for here?
o = DAVObject(self.caldav)
assert_raises(Exception, o.save)
# We want to run all tests in the above class through all caldav_servers;
# and I don't really want to create a custom nose test loader. The
# solution here seems to be to generate one child class for each
# caldav_url, and inject it into the module namespace. TODO: This is
# very hacky. If there are better ways to do it, please let me know.
# (maybe a custom nose test loader really would be the better option?)
# -- Tobias Brox , 2013-10-10
_servernames = set()
for _caldav_server in caldav_servers:
# create a unique identifier out of the server domain name
_parsed_url = urlparse(_caldav_server['url'])
_servername = (_parsed_url.hostname.replace('.', '_') +
str(_parsed_url.port or ''))
while _servername in _servernames:
_servername = _servername + '_'
_servernames.add(_servername)
# create a classname and a class
_classname = 'TestForServer_' + _servername
# inject the new class into this namespace
vars()[_classname] = type(
_classname, (RepeatedFunctionalTestsBaseClass,),
{'server_params': _caldav_server})
class TestLocalXandikos(RepeatedFunctionalTestsBaseClass):
"""
Sets up a local Xandikos server and Runs the functional tests towards it
"""
def setup(self):
if not test_xandikos:
raise SkipTest("Skipping Xadikos test due to configuration")
self.serverdir = tempfile.TemporaryDirectory()
self.serverdir.__enter__()
## TODO - we should do something with the access logs from Xandikos
self.backend = XandikosBackend(path=self.serverdir.name)
self.backend.create_principal('/sometestuser/', create_defaults=True)
self.xandikos_server = make_server(xandikos_host, xandikos_port, XandikosApp(self.backend, '/sometestuser/'))
self.xandikos_thread = threading.Thread(target=self.xandikos_server.serve_forever)
self.xandikos_thread.start()
self.server_params = {'url': 'http://%s:%i/sometestuser/' % (xandikos_host, xandikos_port), 'username': 'user1', 'password': 'password1'}
## TODO: this should go away eventually. Ref https://github.com/jelmer/xandikos/issues/102 support for expanded search for recurring events has been fixed in the master branch of xandikos.
self.server_params['norecurring'] = True
RepeatedFunctionalTestsBaseClass.setup(self)
def teardown(self):
if not test_xandikos:
return
self.xandikos_server.shutdown()
self.xandikos_server.socket.close()
i=0
while (self.xandikos_thread.is_alive()):
time.sleep(0.05)
i+=1
assert(i<100)
self.serverdir.__exit__(None, None, None)
RepeatedFunctionalTestsBaseClass.teardown(self)
class TestCalDAV:
"""
Test class for "pure" unit tests (small internal tests, testing that
a small unit of code works as expected, without any third party
dependencies)
"""
def testCalendar(self):
"""
Principal.calendar() and CalendarSet.calendar() should create
Calendar objects without initiating any communication with the
server. Calendar.event() should create Event object without
initiating any communication with the server.
DAVClient.__init__ also doesn't do any communication
Principal.__init__ as well, if the principal_url is given
Principal.calendar_home_set needs to be set or the server will be queried
"""
cal_url = "http://me:hunter2@calendar.example:80/"
client = DAVClient(url=cal_url)
principal = Principal(client, cal_url + "me/")
principal.calendar_home_set = cal_url + "me/calendars/"
# calendar_home_set is actually a CalendarSet object
assert(isinstance(principal.calendar_home_set, CalendarSet))
calendar1 = principal.calendar(name="foo", cal_id="bar")
calendar2 = principal.calendar_home_set.calendar(
name="foo", cal_id="bar")
assert_equal(calendar1.url, calendar2.url)
assert_equal(
calendar1.url, "http://calendar.example:80/me/calendars/bar")
# principal.calendar_home_set can also be set to an object
# This should be noop
principal.calendar_home_set = principal.calendar_home_set
calendar1 = principal.calendar(name="foo", cal_id="bar")
assert_equal(calendar1.url, calendar2.url)
# When building a calendar from a relative URL and a client,
# the relative URL should be appended to the base URL in the client
calendar1 = Calendar(client, 'someoneelse/calendars/main_calendar')
calendar2 = Calendar(client,
'http://me:hunter2@calendar.example:80/someoneelse/calendars/main_calendar')
assert_equal(calendar1.url, calendar2.url)
def testFailedQuery(self):
"""
ref https://github.com/python-caldav/caldav/issues/54
"""
cal_url = "http://me:hunter2@calendar.example:80/"
client = DAVClient(url=cal_url)
calhome = CalendarSet(client, cal_url + "me/")
## syntesize a failed response
class FailedResp:
pass
failedresp = FailedResp()
failedresp.status = 400
failedresp.reason = "you are wrong"
failedresp.raw = "your request does not adhere to standards"
## synthesize a new http method
calhome.client.unknown_method = lambda url, body, depth: failedresp
## call it.
assert_raises(error.DAVError, calhome._query, query_method='unknown_method')
def testDefaultClient(self):
"""When no client is given to a DAVObject, but the parent is given,
parent.client will be used"""
cal_url = "http://me:hunter2@calendar.example:80/"
client = DAVClient(url=cal_url)
calhome = CalendarSet(client, cal_url + "me/")
calendar = Calendar(parent=calhome)
assert_equal(calendar.client, calhome.client)
def testURL(self):
"""Exercising the URL class"""
long_url = "http://foo:bar@www.example.com:8080/caldav.php/?foo=bar"
# 1) URL.objectify should return a valid URL object almost no matter
# what's thrown in
url0 = URL.objectify(None)
url0b= URL.objectify("")
url1 = URL.objectify(long_url)
url2 = URL.objectify(url1)
url3 = URL.objectify("/bar")
url4 = URL.objectify(urlparse(str(url1)))
url5 = URL.objectify(urlparse("/bar"))
# 2) __eq__ works well
assert_equal(url1, url2)
assert_equal(url1, url4)
assert_equal(url3, url5)
# 3) str will always return the URL
assert_equal(str(url1), long_url)
assert_equal(str(url3), "/bar")
assert_equal(str(url4), long_url)
assert_equal(str(url5), "/bar")
# 4) join method
url6 = url1.join(url2)
url7 = url1.join(url3)
url8 = url1.join(url4)
url9 = url1.join(url5)
urlA = url1.join("someuser/calendar")
urlB = url5.join(url1)
assert_equal(url6, url1)
assert_equal(url7, "http://foo:bar@www.example.com:8080/bar")
assert_equal(url8, url1)
assert_equal(url9, url7)
assert_equal(urlA, "http://foo:bar@www.example.com:8080/caldav.php/someuser/calendar")
assert_equal(urlB, url1)
assert_raises(ValueError, url1.join, "http://www.google.com")
# 4b) join method, with URL as input parameter
url6 = url1.join(URL.objectify(url2))
url7 = url1.join(URL.objectify(url3))
url8 = url1.join(URL.objectify(url4))
url9 = url1.join(URL.objectify(url5))
urlA = url1.join(URL.objectify("someuser/calendar"))
urlB = url5.join(URL.objectify(url1))
url6b= url6.join(url0)
url6c= url6.join(url0b)
url6d= url6.join(None)
for url6alt in (url6b, url6c, url6d):
assert_equal(url6, url6alt)
assert_equal(url6, url1)
assert_equal(url7, "http://foo:bar@www.example.com:8080/bar")
assert_equal(url8, url1)
assert_equal(url9, url7)
assert_equal(urlA, "http://foo:bar@www.example.com:8080/caldav.php/someuser/calendar")
assert_equal(urlB, url1)
assert_raises(ValueError, url1.join, "http://www.google.com")
# 5) all urlparse methods will work. always.
assert_equal(url1.scheme, 'http')
assert_equal(url2.path, '/caldav.php/')
assert_equal(url7.username, 'foo')
assert_equal(url5.path, '/bar')
urlC = URL.objectify("https://www.example.com:443/foo")
assert_equal(urlC.port, 443)
# 6) is_auth returns True if the URL contains a username.
assert_equal(urlC.is_auth(), False)
assert_equal(url7.is_auth(), True)
# 7) unauth() strips username/password
assert_equal(url7.unauth(), 'http://www.example.com:8080/bar')
def testFilters(self):
filter = \
cdav.Filter().append(
cdav.CompFilter("VCALENDAR").append(
cdav.CompFilter("VEVENT").append(
cdav.PropFilter("UID").append(
[cdav.TextMatch("pouet", negate=True)]))))
# print(filter)
crash = cdav.CompFilter()
value = None
try:
value = str(crash)
except:
pass
if value is not None:
raise Exception("This should have crashed")
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1568132280.0
caldav-0.6.2/tests/test_cdav.py 0000644 0016331 0016331 00000003070 00000000000 017230 0 ustar 00tobias tobias 0000000 0000000 import datetime
import pytz
import tzlocal
from caldav.elements.cdav import _to_utc_date_string
SOMEWHERE_REMOTE = pytz.timezone('Brazil/DeNoronha') # UTC-2 and no DST
def test_to_utc_date_string_date():
input = datetime.date(2019, 5, 14)
res = _to_utc_date_string(input)
assert res == '20190514T000000Z'
def test_to_utc_date_string_utc():
input = datetime.datetime(2019, 5, 14, 21, 10, 23, 23, tzinfo=pytz.utc)
try:
res = _to_utc_date_string(input.astimezone())
except:
## old python does not support astimezone() without a parameter given
res = _to_utc_date_string(input.astimezone(tzlocal.get_localzone()))
assert res == '20190514T211023Z'
def test_to_utc_date_string_dt_with_pytz_tzinfo():
input = datetime.datetime(2019, 5, 14, 21, 10, 23, 23)
res = _to_utc_date_string(SOMEWHERE_REMOTE.localize(input))
assert res == '20190514T231023Z'
def test_to_utc_date_string_dt_with_local_tz():
input = datetime.datetime(2019, 5, 14, 21, 10, 23, 23)
try:
res = _to_utc_date_string(input.astimezone())
except:
res = _to_utc_date_string(tzlocal.get_localzone().localize(input))
exp_dt = tzlocal.get_localzone().localize(input).astimezone(pytz.utc)
exp = exp_dt.strftime("%Y%m%dT%H%M%SZ")
assert res == exp
def test_to_utc_date_string_naive_dt():
input = datetime.datetime(2019, 5, 14, 21, 10, 23, 23)
res = _to_utc_date_string(input)
exp_dt = tzlocal.get_localzone().localize(input).astimezone(pytz.utc)
exp = exp_dt.strftime("%Y%m%dT%H%M%SZ")
assert res == exp