id
int64 0
458k
| file_name
stringlengths 4
119
| file_path
stringlengths 14
227
| content
stringlengths 24
9.96M
| size
int64 24
9.96M
| language
stringclasses 1
value | extension
stringclasses 14
values | total_lines
int64 1
219k
| avg_line_length
float64 2.52
4.63M
| max_line_length
int64 5
9.91M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 7
101
| repo_stars
int64 100
139k
| repo_forks
int64 0
26.4k
| repo_open_issues
int64 0
2.27k
| repo_license
stringclasses 12
values | repo_extraction_date
stringclasses 433
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
11,200
|
delete.py
|
Kozea_Radicale/radicale/storage/multifilesystem/delete.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2014 Jean-Marc Martins
# Copyright © 2012-2017 Guillaume Ayoub
# Copyright © 2017-2018 Unrud <unrud@outlook.com>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
import os
from tempfile import TemporaryDirectory
from typing import Optional
from radicale import pathutils, storage
from radicale.storage.multifilesystem.base import CollectionBase
from radicale.storage.multifilesystem.history import CollectionPartHistory
class CollectionPartDelete(CollectionPartHistory, CollectionBase):
def delete(self, href: Optional[str] = None) -> None:
if href is None:
# Delete the collection
parent_dir = os.path.dirname(self._filesystem_path)
try:
os.rmdir(self._filesystem_path)
except OSError:
with TemporaryDirectory(prefix=".Radicale.tmp-", dir=parent_dir
) as tmp:
os.rename(self._filesystem_path, os.path.join(
tmp, os.path.basename(self._filesystem_path)))
self._storage._sync_directory(parent_dir)
else:
self._storage._sync_directory(parent_dir)
else:
# Delete an item
if not pathutils.is_safe_filesystem_path_component(href):
raise pathutils.UnsafePathError(href)
path = pathutils.path_to_filesystem(self._filesystem_path, href)
if not os.path.isfile(path):
raise storage.ComponentNotFoundError(href)
os.remove(path)
self._storage._sync_directory(os.path.dirname(path))
# Track the change
self._update_history_etag(href, None)
self._clean_history()
| 2,386
|
Python
|
.py
| 50
| 39.12
| 79
| 0.676976
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,201
|
cache.py
|
Kozea_Radicale/radicale/storage/multifilesystem/cache.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2014 Jean-Marc Martins
# Copyright © 2012-2017 Guillaume Ayoub
# Copyright © 2017-2018 Unrud <unrud@outlook.com>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
import contextlib
import os
import pickle
import time
from hashlib import sha256
from typing import BinaryIO, Iterable, NamedTuple, Optional, cast
import radicale.item as radicale_item
from radicale import pathutils, storage
from radicale.log import logger
from radicale.storage.multifilesystem.base import CollectionBase
CacheContent = NamedTuple("CacheContent", [
("uid", str), ("etag", str), ("text", str), ("name", str), ("tag", str),
("start", int), ("end", int)])
class CollectionPartCache(CollectionBase):
def _clean_cache(self, folder: str, names: Iterable[str],
max_age: int = 0) -> None:
"""Delete all ``names`` in ``folder`` that are older than ``max_age``.
"""
age_limit: Optional[float] = None
if max_age is not None and max_age > 0:
age_limit = time.time() - max_age
modified = False
for name in names:
if not pathutils.is_safe_filesystem_path_component(name):
continue
if age_limit is not None:
try:
# Race: Another process might have deleted the file.
mtime = os.path.getmtime(os.path.join(folder, name))
except FileNotFoundError:
continue
if mtime > age_limit:
continue
logger.debug("Found expired item in cache: %r", name)
# Race: Another process might have deleted or locked the
# file.
try:
os.remove(os.path.join(folder, name))
except (FileNotFoundError, PermissionError):
continue
modified = True
if modified:
self._storage._sync_directory(folder)
@staticmethod
def _item_cache_hash(raw_text: bytes) -> str:
_hash = sha256()
_hash.update(storage.CACHE_VERSION)
_hash.update(raw_text)
return _hash.hexdigest()
def _item_cache_content(self, item: radicale_item.Item) -> CacheContent:
return CacheContent(item.uid, item.etag, item.serialize(), item.name,
item.component_name, *item.time_range)
def _store_item_cache(self, href: str, item: radicale_item.Item,
cache_hash: str = "") -> CacheContent:
if not cache_hash:
cache_hash = self._item_cache_hash(
item.serialize().encode(self._encoding))
cache_folder = os.path.join(self._filesystem_path, ".Radicale.cache",
"item")
content = self._item_cache_content(item)
self._storage._makedirs_synced(cache_folder)
# Race: Other processes might have created and locked the file.
# TODO: better fix for "mypy"
with contextlib.suppress(PermissionError), self._atomic_write( # type: ignore
os.path.join(cache_folder, href), "wb") as fo:
fb = cast(BinaryIO, fo)
pickle.dump((cache_hash, *content), fb)
return content
def _load_item_cache(self, href: str, cache_hash: str
) -> Optional[CacheContent]:
cache_folder = os.path.join(self._filesystem_path, ".Radicale.cache",
"item")
try:
with open(os.path.join(cache_folder, href), "rb") as f:
hash_, *remainder = pickle.load(f)
if hash_ and hash_ == cache_hash:
return CacheContent(*remainder)
except FileNotFoundError:
pass
except (pickle.UnpicklingError, ValueError) as e:
logger.warning("Failed to load item cache entry %r in %r: %s",
href, self.path, e, exc_info=True)
return None
def _clean_item_cache(self) -> None:
cache_folder = os.path.join(self._filesystem_path, ".Radicale.cache",
"item")
self._clean_cache(cache_folder, (
e.name for e in os.scandir(cache_folder) if not
os.path.isfile(os.path.join(self._filesystem_path, e.name))))
| 4,945
|
Python
|
.py
| 106
| 36.433962
| 86
| 0.611606
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,202
|
move.py
|
Kozea_Radicale/radicale/storage/multifilesystem/move.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2014 Jean-Marc Martins
# Copyright © 2012-2017 Guillaume Ayoub
# Copyright © 2017-2018 Unrud <unrud@outlook.com>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
import os
from radicale import item as radicale_item
from radicale import pathutils, storage
from radicale.storage import multifilesystem
from radicale.storage.multifilesystem.base import StorageBase
class StoragePartMove(StorageBase):
def move(self, item: radicale_item.Item,
to_collection: storage.BaseCollection, to_href: str) -> None:
if not pathutils.is_safe_filesystem_path_component(to_href):
raise pathutils.UnsafePathError(to_href)
assert isinstance(to_collection, multifilesystem.Collection)
assert isinstance(item.collection, multifilesystem.Collection)
assert item.href
os.replace(pathutils.path_to_filesystem(
item.collection._filesystem_path, item.href),
pathutils.path_to_filesystem(
to_collection._filesystem_path, to_href))
self._sync_directory(to_collection._filesystem_path)
if item.collection._filesystem_path != to_collection._filesystem_path:
self._sync_directory(item.collection._filesystem_path)
# Move the item cache entry
cache_folder = os.path.join(item.collection._filesystem_path,
".Radicale.cache", "item")
to_cache_folder = os.path.join(to_collection._filesystem_path,
".Radicale.cache", "item")
self._makedirs_synced(to_cache_folder)
try:
os.replace(os.path.join(cache_folder, item.href),
os.path.join(to_cache_folder, to_href))
except FileNotFoundError:
pass
else:
self._makedirs_synced(to_cache_folder)
if cache_folder != to_cache_folder:
self._makedirs_synced(cache_folder)
# Track the change
to_collection._update_history_etag(to_href, item)
item.collection._update_history_etag(item.href, None)
to_collection._clean_history()
if item.collection._filesystem_path != to_collection._filesystem_path:
item.collection._clean_history()
| 2,926
|
Python
|
.py
| 58
| 41.862069
| 78
| 0.683916
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,203
|
__init__.py
|
Kozea_Radicale/radicale/storage/multifilesystem/__init__.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2014 Jean-Marc Martins
# Copyright © 2012-2017 Guillaume Ayoub
# Copyright © 2017-2019 Unrud <unrud@outlook.com>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
"""
Storage backend that stores data in the file system.
Uses one folder per collection and one file per collection entry.
"""
import os
import time
from typing import ClassVar, Iterator, Optional, Type
from radicale import config
from radicale.storage.multifilesystem.base import CollectionBase, StorageBase
from radicale.storage.multifilesystem.cache import CollectionPartCache
from radicale.storage.multifilesystem.create_collection import \
StoragePartCreateCollection
from radicale.storage.multifilesystem.delete import CollectionPartDelete
from radicale.storage.multifilesystem.discover import StoragePartDiscover
from radicale.storage.multifilesystem.get import CollectionPartGet
from radicale.storage.multifilesystem.history import CollectionPartHistory
from radicale.storage.multifilesystem.lock import (CollectionPartLock,
StoragePartLock)
from radicale.storage.multifilesystem.meta import CollectionPartMeta
from radicale.storage.multifilesystem.move import StoragePartMove
from radicale.storage.multifilesystem.sync import CollectionPartSync
from radicale.storage.multifilesystem.upload import CollectionPartUpload
from radicale.storage.multifilesystem.verify import StoragePartVerify
class Collection(
CollectionPartDelete, CollectionPartMeta, CollectionPartSync,
CollectionPartUpload, CollectionPartGet, CollectionPartCache,
CollectionPartLock, CollectionPartHistory, CollectionBase):
_etag_cache: Optional[str]
def __init__(self, storage_: "Storage", path: str,
filesystem_path: Optional[str] = None) -> None:
super().__init__(storage_, path, filesystem_path)
self._etag_cache = None
@property
def path(self) -> str:
return self._path
@property
def last_modified(self) -> str:
def relevant_files_iter() -> Iterator[str]:
yield self._filesystem_path
if os.path.exists(self._props_path):
yield self._props_path
for href in self._list():
yield os.path.join(self._filesystem_path, href)
last = max(map(os.path.getmtime, relevant_files_iter()))
return time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(last))
@property
def etag(self) -> str:
# reuse cached value if the storage is read-only
if self._storage._lock.locked == "w" or self._etag_cache is None:
self._etag_cache = super().etag
return self._etag_cache
class Storage(
StoragePartCreateCollection, StoragePartLock, StoragePartMove,
StoragePartVerify, StoragePartDiscover, StorageBase):
_collection_class: ClassVar[Type[Collection]] = Collection
def __init__(self, configuration: config.Configuration) -> None:
super().__init__(configuration)
self._makedirs_synced(self._filesystem_folder)
| 3,721
|
Python
|
.py
| 75
| 44.093333
| 77
| 0.746623
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,204
|
verify.py
|
Kozea_Radicale/radicale/storage/multifilesystem/verify.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2014 Jean-Marc Martins
# Copyright © 2012-2017 Guillaume Ayoub
# Copyright © 2017-2021 Unrud <unrud@outlook.com>
# Copyright © 2024-2024 Peter Bieringer <pb@bieringer.de>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
from typing import Iterator, Optional, Set
from radicale import pathutils, storage, types
from radicale.log import logger
from radicale.storage.multifilesystem.base import StorageBase
from radicale.storage.multifilesystem.discover import StoragePartDiscover
class StoragePartVerify(StoragePartDiscover, StorageBase):
def verify(self) -> bool:
item_errors = collection_errors = 0
@types.contextmanager
def exception_cm(sane_path: str, href: Optional[str]
) -> Iterator[None]:
nonlocal item_errors, collection_errors
try:
yield
except Exception as e:
if href is not None:
item_errors += 1
name = "item %r in %r" % (href, sane_path)
else:
collection_errors += 1
name = "collection %r" % sane_path
logger.error("Invalid %s: %s", name, e, exc_info=True)
remaining_sane_paths = [""]
while remaining_sane_paths:
sane_path = remaining_sane_paths.pop(0)
path = pathutils.unstrip_path(sane_path, True)
logger.info("Verifying path %r", sane_path)
count = 0
is_collection = True
with exception_cm(sane_path, None):
saved_item_errors = item_errors
collection: Optional[storage.BaseCollection] = None
uids: Set[str] = set()
has_child_collections = False
for item in self.discover(path, "1", exception_cm):
if not collection:
assert isinstance(item, storage.BaseCollection)
collection = item
collection.get_meta()
if not collection.tag:
is_collection = False
logger.info("Skip !collection %r", sane_path)
continue
if isinstance(item, storage.BaseCollection):
has_child_collections = True
remaining_sane_paths.append(item.path)
elif item.uid in uids:
logger.error("Invalid item %r in %r: UID conflict %r",
item.href, sane_path, item.uid)
else:
uids.add(item.uid)
count += 1
logger.debug("Verified in %r item %r",
sane_path, item.href)
assert collection
if item_errors == saved_item_errors:
if is_collection:
collection.sync()
if has_child_collections and collection.tag:
logger.error("Invalid collection %r: %r must not have "
"child collections", sane_path,
collection.tag)
if is_collection:
logger.info("Verified collect %r (items: %d)", sane_path, count)
return item_errors == 0 and collection_errors == 0
| 4,072
|
Python
|
.py
| 83
| 34.807229
| 80
| 0.568376
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,205
|
base.py
|
Kozea_Radicale/radicale/storage/multifilesystem/base.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2014 Jean-Marc Martins
# Copyright © 2012-2017 Guillaume Ayoub
# Copyright © 2017-2022 Unrud <unrud@outlook.com>
# Copyright © 2024-2024 Peter Bieringer <pb@bieringer.de>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
import os
import sys
from tempfile import TemporaryDirectory
from typing import IO, AnyStr, ClassVar, Iterator, Optional, Type
from radicale import config, pathutils, storage, types
from radicale.storage import multifilesystem # noqa:F401
class CollectionBase(storage.BaseCollection):
_storage: "multifilesystem.Storage"
_path: str
_encoding: str
_filesystem_path: str
def __init__(self, storage_: "multifilesystem.Storage", path: str,
filesystem_path: Optional[str] = None) -> None:
super().__init__()
self._storage = storage_
folder = storage_._get_collection_root_folder()
# Path should already be sanitized
self._path = pathutils.strip_path(path)
self._encoding = storage_.configuration.get("encoding", "stock")
self._skip_broken_item = storage_.configuration.get("storage", "skip_broken_item")
if filesystem_path is None:
filesystem_path = pathutils.path_to_filesystem(folder, self.path)
self._filesystem_path = filesystem_path
# TODO: better fix for "mypy"
@types.contextmanager # type: ignore
def _atomic_write(self, path: str, mode: str = "w",
newline: Optional[str] = None) -> Iterator[IO[AnyStr]]:
# TODO: Overload with Literal when dropping support for Python < 3.8
parent_dir, name = os.path.split(path)
# Do not use mkstemp because it creates with permissions 0o600
with TemporaryDirectory(
prefix=".Radicale.tmp-", dir=parent_dir) as tmp_dir:
with open(os.path.join(tmp_dir, name), mode, newline=newline,
encoding=None if "b" in mode else self._encoding) as tmp:
yield tmp
tmp.flush()
self._storage._fsync(tmp)
os.replace(os.path.join(tmp_dir, name), path)
self._storage._sync_directory(parent_dir)
class StorageBase(storage.BaseStorage):
_collection_class: ClassVar[Type["multifilesystem.Collection"]]
_filesystem_folder: str
_filesystem_fsync: bool
def __init__(self, configuration: config.Configuration) -> None:
super().__init__(configuration)
self._filesystem_folder = configuration.get(
"storage", "filesystem_folder")
self._filesystem_fsync = configuration.get(
"storage", "_filesystem_fsync")
def _get_collection_root_folder(self) -> str:
return os.path.join(self._filesystem_folder, "collection-root")
def _fsync(self, f: IO[AnyStr]) -> None:
if self._filesystem_fsync:
try:
pathutils.fsync(f.fileno())
except OSError as e:
raise RuntimeError("Fsync'ing file %r failed: %s" %
(f.name, e)) from e
def _sync_directory(self, path: str) -> None:
"""Sync directory to disk.
This only works on POSIX and does nothing on other systems.
"""
if not self._filesystem_fsync:
return
if sys.platform != "win32":
try:
fd = os.open(path, 0)
try:
pathutils.fsync(fd)
finally:
os.close(fd)
except OSError as e:
raise RuntimeError("Fsync'ing directory %r failed: %s" %
(path, e)) from e
def _makedirs_synced(self, filesystem_path: str) -> None:
"""Recursively create a directory and its parents in a sync'ed way.
This method acts silently when the folder already exists.
"""
if os.path.isdir(filesystem_path):
return
parent_filesystem_path = os.path.dirname(filesystem_path)
# Prevent infinite loop
if filesystem_path != parent_filesystem_path:
# Create parent dirs recursively
self._makedirs_synced(parent_filesystem_path)
# Possible race!
os.makedirs(filesystem_path, exist_ok=True)
self._sync_directory(parent_filesystem_path)
| 4,961
|
Python
|
.py
| 106
| 37.811321
| 90
| 0.642931
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,206
|
create_collection.py
|
Kozea_Radicale/radicale/storage/multifilesystem/create_collection.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2014 Jean-Marc Martins
# Copyright © 2012-2017 Guillaume Ayoub
# Copyright © 2017-2018 Unrud <unrud@outlook.com>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
import os
from tempfile import TemporaryDirectory
from typing import Iterable, Optional, cast
import radicale.item as radicale_item
from radicale import pathutils
from radicale.storage import multifilesystem
from radicale.storage.multifilesystem.base import StorageBase
class StoragePartCreateCollection(StorageBase):
def create_collection(self, href: str,
items: Optional[Iterable[radicale_item.Item]] = None,
props=None) -> "multifilesystem.Collection":
folder = self._get_collection_root_folder()
# Path should already be sanitized
sane_path = pathutils.strip_path(href)
filesystem_path = pathutils.path_to_filesystem(folder, sane_path)
if not props:
self._makedirs_synced(filesystem_path)
return self._collection_class(
cast(multifilesystem.Storage, self),
pathutils.unstrip_path(sane_path, True))
parent_dir = os.path.dirname(filesystem_path)
self._makedirs_synced(parent_dir)
# Create a temporary directory with an unsafe name
with TemporaryDirectory(prefix=".Radicale.tmp-", dir=parent_dir
) as tmp_dir:
# The temporary directory itself can't be renamed
tmp_filesystem_path = os.path.join(tmp_dir, "collection")
os.makedirs(tmp_filesystem_path)
col = self._collection_class(
cast(multifilesystem.Storage, self),
pathutils.unstrip_path(sane_path, True),
filesystem_path=tmp_filesystem_path)
col.set_meta(props)
if items is not None:
if props.get("tag") == "VCALENDAR":
col._upload_all_nonatomic(items, suffix=".ics")
elif props.get("tag") == "VADDRESSBOOK":
col._upload_all_nonatomic(items, suffix=".vcf")
if os.path.lexists(filesystem_path):
pathutils.rename_exchange(tmp_filesystem_path, filesystem_path)
else:
os.rename(tmp_filesystem_path, filesystem_path)
self._sync_directory(parent_dir)
return self._collection_class(
cast(multifilesystem.Storage, self),
pathutils.unstrip_path(sane_path, True))
| 3,150
|
Python
|
.py
| 63
| 40.714286
| 79
| 0.669378
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,207
|
get.py
|
Kozea_Radicale/radicale/storage/multifilesystem/get.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2014 Jean-Marc Martins
# Copyright © 2012-2017 Guillaume Ayoub
# Copyright © 2017-2022 Unrud <unrud@outlook.com>
# Copyright © 2024-2024 Peter Bieringer <pb@bieringer.de>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
import os
import sys
import time
from typing import Iterable, Iterator, Optional, Tuple
import radicale.item as radicale_item
from radicale import pathutils
from radicale.log import logger
from radicale.storage import multifilesystem
from radicale.storage.multifilesystem.base import CollectionBase
from radicale.storage.multifilesystem.cache import CollectionPartCache
from radicale.storage.multifilesystem.lock import CollectionPartLock
class CollectionPartGet(CollectionPartCache, CollectionPartLock,
CollectionBase):
_item_cache_cleaned: bool
def __init__(self, storage_: "multifilesystem.Storage", path: str,
filesystem_path: Optional[str] = None) -> None:
super().__init__(storage_, path, filesystem_path)
self._item_cache_cleaned = False
def _list(self) -> Iterator[str]:
for entry in os.scandir(self._filesystem_path):
if not entry.is_file():
continue
href = entry.name
if not pathutils.is_safe_filesystem_path_component(href):
if not href.startswith(".Radicale"):
logger.debug("Skipping item %r in %r", href, self.path)
continue
yield href
def _get(self, href: str, verify_href: bool = True
) -> Optional[radicale_item.Item]:
if verify_href:
try:
if not pathutils.is_safe_filesystem_path_component(href):
raise pathutils.UnsafePathError(href)
path = pathutils.path_to_filesystem(self._filesystem_path,
href)
except ValueError as e:
logger.debug(
"Can't translate name %r safely to filesystem in %r: %s",
href, self.path, e, exc_info=True)
return None
else:
path = os.path.join(self._filesystem_path, href)
try:
with open(path, "rb") as f:
raw_text = f.read()
except (FileNotFoundError, IsADirectoryError):
return None
except PermissionError:
# Windows raises ``PermissionError`` when ``path`` is a directory
if (sys.platform == "win32" and
os.path.isdir(path) and os.access(path, os.R_OK)):
return None
raise
# The hash of the component in the file system. This is used to check,
# if the entry in the cache is still valid.
cache_hash = self._item_cache_hash(raw_text)
cache_content = self._load_item_cache(href, cache_hash)
if cache_content is None:
with self._acquire_cache_lock("item"):
# Lock the item cache to prevent multiple processes from
# generating the same data in parallel.
# This improves the performance for multiple requests.
if self._storage._lock.locked == "r":
# Check if another process created the file in the meantime
cache_content = self._load_item_cache(href, cache_hash)
if cache_content is None:
try:
vobject_items = radicale_item.read_components(
raw_text.decode(self._encoding))
radicale_item.check_and_sanitize_items(
vobject_items, tag=self.tag)
vobject_item, = vobject_items
temp_item = radicale_item.Item(
collection=self, vobject_item=vobject_item)
cache_content = self._store_item_cache(
href, temp_item, cache_hash)
except Exception as e:
if self._skip_broken_item:
logger.warning("Skip broken item %r in %r: %s", href, self.path, e)
return None
else:
raise RuntimeError("Failed to load item %r in %r: %s" %
(href, self.path, e)) from e
# Clean cache entries once after the data in the file
# system was edited externally.
if not self._item_cache_cleaned:
self._item_cache_cleaned = True
self._clean_item_cache()
last_modified = time.strftime(
"%a, %d %b %Y %H:%M:%S GMT",
time.gmtime(os.path.getmtime(path)))
# Don't keep reference to ``vobject_item``, because it requires a lot
# of memory.
return radicale_item.Item(
collection=self, href=href, last_modified=last_modified,
etag=cache_content.etag, text=cache_content.text,
uid=cache_content.uid, name=cache_content.name,
component_name=cache_content.tag,
time_range=(cache_content.start, cache_content.end))
def get_multi(self, hrefs: Iterable[str]
) -> Iterator[Tuple[str, Optional[radicale_item.Item]]]:
# It's faster to check for file name collisions here, because
# we only need to call os.listdir once.
files = None
for href in hrefs:
if files is None:
# List dir after hrefs returned one item, the iterator may be
# empty and the for-loop is never executed.
files = os.listdir(self._filesystem_path)
path = os.path.join(self._filesystem_path, href)
if (not pathutils.is_safe_filesystem_path_component(href) or
href not in files and os.path.lexists(path)):
logger.debug("Can't translate name safely to filesystem: %r",
href)
yield (href, None)
else:
yield (href, self._get(href, verify_href=False))
def get_all(self) -> Iterator[radicale_item.Item]:
for href in self._list():
# We don't need to check for collisions, because the file names
# are from os.listdir.
item = self._get(href, verify_href=False)
if item is not None:
yield item
| 7,175
|
Python
|
.py
| 143
| 36.881119
| 95
| 0.586207
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,208
|
test_auth.py
|
Kozea_Radicale/radicale/tests/test_auth.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2012-2016 Jean-Marc Martins
# Copyright © 2012-2017 Guillaume Ayoub
# Copyright © 2017-2022 Unrud <unrud@outlook.com>
# Copyright © 2024-2024 Peter Bieringer <pb@bieringer.de>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
"""
Radicale tests with simple requests and authentication.
"""
import os
import sys
from typing import Iterable, Tuple, Union
import pytest
from radicale import xmlutils
from radicale.tests import BaseTest
class TestBaseAuthRequests(BaseTest):
"""Tests basic requests with auth.
We should setup auth for each type before creating the Application object.
"""
def _test_htpasswd(self, htpasswd_encryption: str, htpasswd_content: str,
test_matrix: Union[str, Iterable[Tuple[str, str, bool]]]
= "ascii") -> None:
"""Test htpasswd authentication with user "tmp" and password "bepo" for
``test_matrix`` "ascii" or user "😀" and password "🔑" for
``test_matrix`` "unicode"."""
htpasswd_file_path = os.path.join(self.colpath, ".htpasswd")
encoding: str = self.configuration.get("encoding", "stock")
with open(htpasswd_file_path, "w", encoding=encoding) as f:
f.write(htpasswd_content)
self.configure({"auth": {"type": "htpasswd",
"htpasswd_filename": htpasswd_file_path,
"htpasswd_encryption": htpasswd_encryption}})
if test_matrix == "ascii":
test_matrix = (("tmp", "bepo", True), ("tmp", "tmp", False),
("tmp", "", False), ("unk", "unk", False),
("unk", "", False), ("", "", False))
elif test_matrix == "unicode":
test_matrix = (("😀", "🔑", True), ("😀", "🌹", False),
("�", "🔑", False), ("😀", "", False),
("", "🔑", False), ("", "", False))
elif isinstance(test_matrix, str):
raise ValueError("Unknown test matrix %r" % test_matrix)
for user, password, valid in test_matrix:
self.propfind("/", check=207 if valid else 401,
login="%s:%s" % (user, password))
def test_htpasswd_plain(self) -> None:
self._test_htpasswd("plain", "tmp:bepo")
def test_htpasswd_plain_password_split(self) -> None:
self._test_htpasswd("plain", "tmp:be:po", (
("tmp", "be:po", True), ("tmp", "bepo", False)))
def test_htpasswd_plain_unicode(self) -> None:
self._test_htpasswd("plain", "😀:🔑", "unicode")
def test_htpasswd_md5(self) -> None:
self._test_htpasswd("md5", "tmp:$apr1$BI7VKCZh$GKW4vq2hqDINMr8uv7lDY/")
def test_htpasswd_md5_unicode(self):
self._test_htpasswd(
"md5", "😀:$apr1$w4ev89r1$29xO8EvJmS2HEAadQ5qy11", "unicode")
def test_htpasswd_sha256(self) -> None:
self._test_htpasswd("sha256", "tmp:$5$i4Ni4TQq6L5FKss5$ilpTjkmnxkwZeV35GB9cYSsDXTALBn6KtWRJAzNlCL/")
def test_htpasswd_sha512(self) -> None:
self._test_htpasswd("sha512", "tmp:$6$3Qhl8r6FLagYdHYa$UCH9yXCed4A.J9FQsFPYAOXImzZUMfvLa0lwcWOxWYLOF5sE/lF99auQ4jKvHY2vijxmefl7G6kMqZ8JPdhIJ/")
def test_htpasswd_bcrypt(self) -> None:
self._test_htpasswd("bcrypt", "tmp:$2y$05$oD7hbiQFQlvCM7zoalo/T.MssV3V"
"NTRI3w5KDnj8NTUKJNWfVpvRq")
def test_htpasswd_bcrypt_unicode(self) -> None:
self._test_htpasswd("bcrypt", "😀:$2y$10$Oyz5aHV4MD9eQJbk6GPemOs4T6edK"
"6U9Sqlzr.W1mMVCS8wJUftnW", "unicode")
def test_htpasswd_multi(self) -> None:
self._test_htpasswd("plain", "ign:ign\ntmp:bepo")
@pytest.mark.skipif(sys.platform == "win32", reason="leading and trailing "
"whitespaces not allowed in file names")
def test_htpasswd_whitespace_user(self) -> None:
for user in (" tmp", "tmp ", " tmp "):
self._test_htpasswd("plain", "%s:bepo" % user, (
(user, "bepo", True), ("tmp", "bepo", False)))
def test_htpasswd_whitespace_password(self) -> None:
for password in (" bepo", "bepo ", " bepo "):
self._test_htpasswd("plain", "tmp:%s" % password, (
("tmp", password, True), ("tmp", "bepo", False)))
def test_htpasswd_comment(self) -> None:
self._test_htpasswd("plain", "#comment\n #comment\n \ntmp:bepo\n\n")
def test_htpasswd_lc_username(self) -> None:
self.configure({"auth": {"lc_username": "True"}})
self._test_htpasswd("plain", "tmp:bepo", (
("tmp", "bepo", True), ("TMP", "bepo", True), ("tmp1", "bepo", False)))
def test_htpasswd_strip_domain(self) -> None:
self.configure({"auth": {"strip_domain": "True"}})
self._test_htpasswd("plain", "tmp:bepo", (
("tmp", "bepo", True), ("tmp@domain.example", "bepo", True), ("tmp1", "bepo", False)))
def test_remote_user(self) -> None:
self.configure({"auth": {"type": "remote_user"}})
_, responses = self.propfind("/", """\
<?xml version="1.0" encoding="utf-8"?>
<propfind xmlns="DAV:">
<prop>
<current-user-principal />
</prop>
</propfind>""", REMOTE_USER="test")
assert responses is not None
response = responses["/"]
assert not isinstance(response, int)
status, prop = response["D:current-user-principal"]
assert status == 200
href_element = prop.find(xmlutils.make_clark("D:href"))
assert href_element is not None and href_element.text == "/test/"
def test_http_x_remote_user(self) -> None:
self.configure({"auth": {"type": "http_x_remote_user"}})
_, responses = self.propfind("/", """\
<?xml version="1.0" encoding="utf-8"?>
<propfind xmlns="DAV:">
<prop>
<current-user-principal />
</prop>
</propfind>""", HTTP_X_REMOTE_USER="test")
assert responses is not None
response = responses["/"]
assert not isinstance(response, int)
status, prop = response["D:current-user-principal"]
assert status == 200
href_element = prop.find(xmlutils.make_clark("D:href"))
assert href_element is not None and href_element.text == "/test/"
def test_custom(self) -> None:
"""Custom authentication."""
self.configure({"auth": {"type": "radicale.tests.custom.auth"}})
self.propfind("/tmp/", login="tmp:")
def test_none(self) -> None:
self.configure({"auth": {"type": "none"}})
self.propfind("/tmp/", login="tmp:")
def test_denyall(self) -> None:
self.configure({"auth": {"type": "denyall"}})
self.propfind("/tmp/", login="tmp:", check=401)
| 7,392
|
Python
|
.py
| 143
| 43.125874
| 151
| 0.609641
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,209
|
test_rights.py
|
Kozea_Radicale/radicale/tests/test_rights.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2017-2019 Unrud <unrud@outlook.com>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
"""
Radicale tests with simple requests and rights.
"""
import os
from radicale.tests import BaseTest
from radicale.tests.helpers import get_file_content
class TestBaseRightsRequests(BaseTest):
"""Tests basic requests with rights."""
def _test_rights(self, rights_type: str, user: str, path: str, mode: str,
expected_status: int, with_auth: bool = True) -> None:
assert mode in ("r", "w")
assert user in ("", "tmp")
htpasswd_file_path = os.path.join(self.colpath, ".htpasswd")
with open(htpasswd_file_path, "w") as f:
f.write("tmp:bepo\nother:bepo")
self.configure({
"rights": {"type": rights_type},
"auth": {"type": "htpasswd" if with_auth else "none",
"htpasswd_filename": htpasswd_file_path,
"htpasswd_encryption": "plain"}})
for u in ("tmp", "other"):
# Indirect creation of principal collection
self.propfind("/%s/" % u, login="%s:bepo" % u)
(self.propfind if mode == "r" else self.proppatch)(
path, check=expected_status, login="tmp:bepo" if user else None)
def test_owner_only(self) -> None:
self._test_rights("owner_only", "", "/", "r", 401)
self._test_rights("owner_only", "", "/", "w", 401)
self._test_rights("owner_only", "", "/tmp/", "r", 401)
self._test_rights("owner_only", "", "/tmp/", "w", 401)
self._test_rights("owner_only", "tmp", "/", "r", 207)
self._test_rights("owner_only", "tmp", "/", "w", 403)
self._test_rights("owner_only", "tmp", "/tmp/", "r", 207)
self._test_rights("owner_only", "tmp", "/tmp/", "w", 207)
self._test_rights("owner_only", "tmp", "/other/", "r", 403)
self._test_rights("owner_only", "tmp", "/other/", "w", 403)
def test_owner_only_without_auth(self) -> None:
self._test_rights("owner_only", "", "/", "r", 207, False)
self._test_rights("owner_only", "", "/", "w", 401, False)
self._test_rights("owner_only", "", "/tmp/", "r", 207, False)
self._test_rights("owner_only", "", "/tmp/", "w", 207, False)
def test_owner_write(self) -> None:
self._test_rights("owner_write", "", "/", "r", 401)
self._test_rights("owner_write", "", "/", "w", 401)
self._test_rights("owner_write", "", "/tmp/", "r", 401)
self._test_rights("owner_write", "", "/tmp/", "w", 401)
self._test_rights("owner_write", "tmp", "/", "r", 207)
self._test_rights("owner_write", "tmp", "/", "w", 403)
self._test_rights("owner_write", "tmp", "/tmp/", "r", 207)
self._test_rights("owner_write", "tmp", "/tmp/", "w", 207)
self._test_rights("owner_write", "tmp", "/other/", "r", 207)
self._test_rights("owner_write", "tmp", "/other/", "w", 403)
def test_owner_write_without_auth(self) -> None:
self._test_rights("owner_write", "", "/", "r", 207, False)
self._test_rights("owner_write", "", "/", "w", 401, False)
self._test_rights("owner_write", "", "/tmp/", "r", 207, False)
self._test_rights("owner_write", "", "/tmp/", "w", 207, False)
def test_authenticated(self) -> None:
self._test_rights("authenticated", "", "/", "r", 401)
self._test_rights("authenticated", "", "/", "w", 401)
self._test_rights("authenticated", "", "/tmp/", "r", 401)
self._test_rights("authenticated", "", "/tmp/", "w", 401)
self._test_rights("authenticated", "tmp", "/", "r", 207)
self._test_rights("authenticated", "tmp", "/", "w", 207)
self._test_rights("authenticated", "tmp", "/tmp/", "r", 207)
self._test_rights("authenticated", "tmp", "/tmp/", "w", 207)
self._test_rights("authenticated", "tmp", "/other/", "r", 207)
self._test_rights("authenticated", "tmp", "/other/", "w", 207)
def test_authenticated_without_auth(self) -> None:
self._test_rights("authenticated", "", "/", "r", 207, False)
self._test_rights("authenticated", "", "/", "w", 207, False)
self._test_rights("authenticated", "", "/tmp/", "r", 207, False)
self._test_rights("authenticated", "", "/tmp/", "w", 207, False)
def test_from_file(self) -> None:
rights_file_path = os.path.join(self.colpath, "rights")
with open(rights_file_path, "w") as f:
f.write("""\
[owner]
user: .+
collection: {user}(/.*)?
permissions: RrWw
[custom]
user: .*
collection: custom(/.*)?
permissions: Rr""")
self.configure({"rights": {"file": rights_file_path}})
self._test_rights("from_file", "", "/other/", "r", 401)
self._test_rights("from_file", "tmp", "/other/", "r", 403)
self._test_rights("from_file", "", "/custom/sub", "r", 404)
self._test_rights("from_file", "tmp", "/custom/sub", "r", 404)
self._test_rights("from_file", "", "/custom/sub", "w", 401)
self._test_rights("from_file", "tmp", "/custom/sub", "w", 403)
def test_from_file_limited_get(self):
rights_file_path = os.path.join(self.colpath, "rights")
with open(rights_file_path, "w") as f:
f.write("""\
[write-all]
user: tmp
collection: .*
permissions: RrWw
[limited-public]
user: .*
collection: public/[^/]*
permissions: i""")
self.configure({"rights": {"type": "from_file",
"file": rights_file_path}})
self.mkcalendar("/tmp/calendar", login="tmp:bepo")
self.mkcol("/public", login="tmp:bepo")
self.mkcalendar("/public/calendar", login="tmp:bepo")
self.get("/tmp/calendar", check=401)
self.get("/public/", check=401)
self.get("/public/calendar")
self.get("/public/calendar/1.ics", check=401)
def test_custom(self) -> None:
"""Custom rights management."""
self._test_rights("radicale.tests.custom.rights", "", "/", "r", 401)
self._test_rights(
"radicale.tests.custom.rights", "", "/tmp/", "r", 207)
def test_collections_and_items(self) -> None:
"""Test rights for creation of collections, calendars and items.
Collections are allowed at "/" and "/.../".
Calendars/Address books are allowed at "/.../.../".
Items are allowed at "/.../.../...".
"""
self.mkcalendar("/", check=401)
self.mkcalendar("/user/", check=401)
self.mkcol("/user/")
self.mkcol("/user/calendar/", check=401)
self.mkcalendar("/user/calendar/")
self.mkcol("/user/calendar/item", check=401)
self.mkcalendar("/user/calendar/item", check=401)
def test_put_collections_and_items(self) -> None:
"""Test rights for creation of calendars and items with PUT."""
self.put("/user/", "BEGIN:VCALENDAR\r\nEND:VCALENDAR", check=401)
self.mkcol("/user/")
self.put("/user/calendar/", "BEGIN:VCALENDAR\r\nEND:VCALENDAR")
event1 = get_file_content("event1.ics")
self.put("/user/calendar/event1.ics", event1)
| 7,780
|
Python
|
.py
| 153
| 43.385621
| 77
| 0.582808
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,210
|
test_web.py
|
Kozea_Radicale/radicale/tests/test_web.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2018-2019 Unrud <unrud@outlook.com>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
"""
Test web plugin.
"""
from radicale.tests import BaseTest
class TestBaseWebRequests(BaseTest):
"""Test web plugin."""
def test_internal(self) -> None:
_, headers, _ = self.request("GET", "/.web", check=302)
assert headers.get("Location") == "/.web/"
_, answer = self.get("/.web/")
assert answer
self.post("/.web", check=405)
def test_none(self) -> None:
self.configure({"web": {"type": "none"}})
_, answer = self.get("/.web")
assert answer
_, headers, _ = self.request("GET", "/.web/", check=302)
assert headers.get("Location") == "/.web"
self.post("/.web", check=405)
def test_custom(self) -> None:
"""Custom web plugin."""
self.configure({"web": {"type": "radicale.tests.custom.web"}})
_, answer = self.get("/.web")
assert answer == "custom"
_, answer = self.post("/.web", "body content")
assert answer == "echo:body content"
| 1,734
|
Python
|
.py
| 41
| 37.390244
| 70
| 0.653412
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,211
|
test_base.py
|
Kozea_Radicale/radicale/tests/test_base.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2012-2017 Guillaume Ayoub
# Copyright © 2017-2019 Unrud <unrud@outlook.com>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
"""
Radicale tests with simple requests.
"""
import os
import posixpath
from typing import Any, Callable, ClassVar, Iterable, List, Optional, Tuple
import defusedxml.ElementTree as DefusedET
import vobject
from radicale import storage, xmlutils
from radicale.tests import RESPONSES, BaseTest
from radicale.tests.helpers import get_file_content
class TestBaseRequests(BaseTest):
"""Tests with simple requests."""
# Allow skipping sync-token tests, when not fully supported by the backend
full_sync_token_support: ClassVar[bool] = True
def setup_method(self) -> None:
BaseTest.setup_method(self)
rights_file_path = os.path.join(self.colpath, "rights")
with open(rights_file_path, "w") as f:
f.write("""\
[permit delete collection]
user: .*
collection: test-permit-delete
permissions: RrWwD
[forbid delete collection]
user: .*
collection: test-forbid-delete
permissions: RrWwd
[permit overwrite collection]
user: .*
collection: test-permit-overwrite
permissions: RrWwO
[forbid overwrite collection]
user: .*
collection: test-forbid-overwrite
permissions: RrWwo
[allow all]
user: .*
collection: .*
permissions: RrWw""")
self.configure({"rights": {"file": rights_file_path,
"type": "from_file"}})
def test_root(self) -> None:
"""GET request at "/"."""
for path in ["", "/", "//"]:
_, headers, answer = self.request("GET", path, check=302)
assert headers.get("Location") == "/.web"
assert answer == "Redirected to /.web"
def test_root_script_name(self) -> None:
"""GET request at "/" with SCRIPT_NAME."""
for path in ["", "/", "//"]:
_, headers, _ = self.request("GET", path, check=302,
SCRIPT_NAME="/radicale")
assert headers.get("Location") == "/radicale/.web"
def test_root_broken_script_name(self) -> None:
"""GET request at "/" with SCRIPT_NAME ending with "/"."""
for script_name, prefix in [
("/", ""), ("//", ""), ("/radicale/", "/radicale"),
("radicale", None), ("radicale//", None)]:
_, headers, _ = self.request(
"GET", "/", check=500 if prefix is None else 302,
SCRIPT_NAME=script_name)
assert (prefix is None or
headers.get("Location") == prefix + "/.web")
def test_root_http_x_script_name(self) -> None:
"""GET request at "/" with HTTP_X_SCRIPT_NAME."""
for path in ["", "/", "//"]:
_, headers, _ = self.request("GET", path, check=302,
HTTP_X_SCRIPT_NAME="/radicale")
assert headers.get("Location") == "/radicale/.web"
def test_root_broken_http_x_script_name(self) -> None:
"""GET request at "/" with HTTP_X_SCRIPT_NAME ending with "/"."""
for script_name, prefix in [
("/", ""), ("//", ""), ("/radicale/", "/radicale"),
("radicale", None), ("radicale//", None)]:
_, headers, _ = self.request(
"GET", "/", check=400 if prefix is None else 302,
HTTP_X_SCRIPT_NAME=script_name)
assert (prefix is None or
headers.get("Location") == prefix + "/.web")
def test_sanitized_path(self) -> None:
"""GET request with unsanitized paths."""
for path, sane_path in [
("//.web", "/.web"), ("//.web/", "/.web/"),
("/.web//", "/.web/"), ("/.web/a//b", "/.web/a/b")]:
_, headers, _ = self.request("GET", path, check=301)
assert headers.get("Location") == sane_path
_, headers, _ = self.request("GET", path, check=301,
SCRIPT_NAME="/radicale")
assert headers.get("Location") == "/radicale%s" % sane_path
_, headers, _ = self.request("GET", path, check=301,
HTTP_X_SCRIPT_NAME="/radicale")
assert headers.get("Location") == "/radicale%s" % sane_path
def test_add_event(self) -> None:
"""Add an event."""
self.mkcalendar("/calendar.ics/")
event = get_file_content("event1.ics")
path = "/calendar.ics/event1.ics"
self.put(path, event)
_, headers, answer = self.request("GET", path, check=200)
assert "ETag" in headers
assert headers["Content-Type"] == "text/calendar; charset=utf-8"
assert "VEVENT" in answer
assert "Event" in answer
assert "UID:event" in answer
def test_add_event_without_uid(self) -> None:
"""Add an event without UID."""
self.mkcalendar("/calendar.ics/")
event = get_file_content("event1.ics").replace("UID:event1\n", "")
assert "\nUID:" not in event
path = "/calendar.ics/event.ics"
self.put(path, event, check=400)
def test_add_event_duplicate_uid(self) -> None:
"""Add an event with an existing UID."""
self.mkcalendar("/calendar.ics/")
event = get_file_content("event1.ics")
self.put("/calendar.ics/event1.ics", event)
status, answer = self.put(
"/calendar.ics/event1-duplicate.ics", event, check=None)
assert status in (403, 409)
xml = DefusedET.fromstring(answer)
assert xml.tag == xmlutils.make_clark("D:error")
assert xml.find(xmlutils.make_clark("C:no-uid-conflict")) is not None
def test_add_event_with_mixed_datetime_and_date(self) -> None:
"""Test event with DTSTART as DATE-TIME and EXDATE as DATE."""
self.mkcalendar("/calendar.ics/")
event = get_file_content("event_mixed_datetime_and_date.ics")
self.put("/calendar.ics/event.ics", event)
def test_add_todo(self) -> None:
"""Add a todo."""
self.mkcalendar("/calendar.ics/")
todo = get_file_content("todo1.ics")
path = "/calendar.ics/todo1.ics"
self.put(path, todo)
_, headers, answer = self.request("GET", path, check=200)
assert "ETag" in headers
assert headers["Content-Type"] == "text/calendar; charset=utf-8"
assert "VTODO" in answer
assert "Todo" in answer
assert "UID:todo" in answer
def test_add_contact(self) -> None:
"""Add a contact."""
self.create_addressbook("/contacts.vcf/")
contact = get_file_content("contact1.vcf")
path = "/contacts.vcf/contact.vcf"
self.put(path, contact)
_, headers, answer = self.request("GET", path, check=200)
assert "ETag" in headers
assert headers["Content-Type"] == "text/vcard; charset=utf-8"
assert "VCARD" in answer
assert "UID:contact1" in answer
_, answer = self.get(path)
assert "UID:contact1" in answer
def test_add_contact_photo_with_data_uri(self) -> None:
"""Test workaround for broken PHOTO data from InfCloud"""
self.create_addressbook("/contacts.vcf/")
contact = get_file_content("contact_photo_with_data_uri.vcf")
self.put("/contacts.vcf/contact.vcf", contact)
def test_add_contact_without_uid(self) -> None:
"""Add a contact without UID."""
self.create_addressbook("/contacts.vcf/")
contact = get_file_content("contact1.vcf").replace("UID:contact1\n",
"")
assert "\nUID" not in contact
path = "/contacts.vcf/contact.vcf"
self.put(path, contact, check=400)
def test_update_event(self) -> None:
"""Update an event."""
self.mkcalendar("/calendar.ics/")
event = get_file_content("event1.ics")
event_modified = get_file_content("event1_modified.ics")
path = "/calendar.ics/event1.ics"
self.put(path, event)
self.put(path, event_modified)
_, answer = self.get("/calendar.ics/")
assert answer.count("BEGIN:VEVENT") == 1
_, answer = self.get(path)
assert "DTSTAMP:20130902T150159Z" in answer
def test_update_event_uid_event(self) -> None:
"""Update an event with a different UID."""
self.mkcalendar("/calendar.ics/")
event1 = get_file_content("event1.ics")
event2 = get_file_content("event2.ics")
path = "/calendar.ics/event1.ics"
self.put(path, event1)
status, answer = self.put(path, event2, check=None)
assert status in (403, 409)
xml = DefusedET.fromstring(answer)
assert xml.tag == xmlutils.make_clark("D:error")
assert xml.find(xmlutils.make_clark("C:no-uid-conflict")) is not None
def test_put_whole_calendar(self) -> None:
"""Create and overwrite a whole calendar."""
self.put("/calendar.ics/", "BEGIN:VCALENDAR\r\nEND:VCALENDAR")
event1 = get_file_content("event1.ics")
self.put("/calendar.ics/test_event.ics", event1)
# Overwrite
events = get_file_content("event_multiple.ics")
self.put("/calendar.ics/", events)
self.get("/calendar.ics/test_event.ics", check=404)
_, answer = self.get("/calendar.ics/")
assert "\r\nUID:event\r\n" in answer and "\r\nUID:todo\r\n" in answer
assert "\r\nUID:event1\r\n" not in answer
def test_put_whole_calendar_without_uids(self) -> None:
"""Create a whole calendar without UID."""
event = get_file_content("event_multiple.ics")
event = event.replace("UID:event\n", "").replace("UID:todo\n", "")
assert "\nUID:" not in event
self.put("/calendar.ics/", event)
_, answer = self.get("/calendar.ics")
uids = []
for line in answer.split("\r\n"):
if line.startswith("UID:"):
uids.append(line[len("UID:"):])
assert len(uids) == 2
for i, uid1 in enumerate(uids):
assert uid1
for uid2 in uids[i + 1:]:
assert uid1 != uid2
def test_put_whole_calendar_case_sensitive_uids(self) -> None:
"""Create a whole calendar with case-sensitive UIDs."""
events = get_file_content("event_multiple_case_sensitive_uids.ics")
self.put("/calendar.ics/", events)
_, answer = self.get("/calendar.ics/")
assert "\r\nUID:event\r\n" in answer and "\r\nUID:EVENT\r\n" in answer
def test_put_whole_addressbook(self) -> None:
"""Create and overwrite a whole addressbook."""
contacts = get_file_content("contact_multiple.vcf")
self.put("/contacts.vcf/", contacts)
_, answer = self.get("/contacts.vcf/")
assert answer is not None
assert "\r\nUID:contact1\r\n" in answer
assert "\r\nUID:contact2\r\n" in answer
def test_put_whole_addressbook_without_uids(self) -> None:
"""Create a whole addressbook without UID."""
contacts = get_file_content("contact_multiple.vcf")
contacts = contacts.replace("UID:contact1\n", "").replace(
"UID:contact2\n", "")
assert "\nUID:" not in contacts
self.put("/contacts.vcf/", contacts)
_, answer = self.get("/contacts.vcf")
uids = []
for line in answer.split("\r\n"):
if line.startswith("UID:"):
uids.append(line[len("UID:"):])
assert len(uids) == 2
for i, uid1 in enumerate(uids):
assert uid1
for uid2 in uids[i + 1:]:
assert uid1 != uid2
def test_verify(self) -> None:
"""Verify the storage."""
contacts = get_file_content("contact_multiple.vcf")
self.put("/contacts.vcf/", contacts)
events = get_file_content("event_multiple.ics")
self.put("/calendar.ics/", events)
s = storage.load(self.configuration)
assert s.verify()
def test_delete(self) -> None:
"""Delete an event."""
self.mkcalendar("/calendar.ics/")
event = get_file_content("event1.ics")
path = "/calendar.ics/event1.ics"
self.put(path, event)
_, responses = self.delete(path)
assert responses[path] == 200
_, answer = self.get("/calendar.ics/")
assert "VEVENT" not in answer
def test_mkcalendar(self) -> None:
"""Make a calendar."""
self.mkcalendar("/calendar.ics/")
_, answer = self.get("/calendar.ics/")
assert "BEGIN:VCALENDAR" in answer
assert "END:VCALENDAR" in answer
def test_mkcalendar_overwrite(self) -> None:
"""Try to overwrite an existing calendar."""
self.mkcalendar("/calendar.ics/")
status, answer = self.mkcalendar("/calendar.ics/", check=None)
assert status in (403, 409)
xml = DefusedET.fromstring(answer)
assert xml.tag == xmlutils.make_clark("D:error")
assert xml.find(xmlutils.make_clark(
"D:resource-must-be-null")) is not None
def test_mkcalendar_intermediate(self) -> None:
"""Try make a calendar in a unmapped collection."""
self.mkcalendar("/unmapped/calendar.ics/", check=409)
def test_mkcol(self) -> None:
"""Make a collection."""
self.mkcol("/user/")
def test_mkcol_overwrite(self) -> None:
"""Try to overwrite an existing collection."""
self.mkcol("/user/")
self.mkcol("/user/", check=405)
def test_mkcol_intermediate(self) -> None:
"""Try make a collection in a unmapped collection."""
self.mkcol("/unmapped/user/", check=409)
def test_mkcol_make_calendar(self) -> None:
"""Make a calendar with additional props."""
mkcol_make_calendar = get_file_content("mkcol_make_calendar.xml")
self.mkcol("/calendar.ics/", mkcol_make_calendar)
_, answer = self.get("/calendar.ics/")
assert answer is not None
assert "BEGIN:VCALENDAR" in answer
assert "END:VCALENDAR" in answer
# Read additional properties
propfind = get_file_content("propfind_calendar_color.xml")
_, responses = self.propfind("/calendar.ics/", propfind)
response = responses["/calendar.ics/"]
assert not isinstance(response, int) and len(response) == 1
status, prop = response["ICAL:calendar-color"]
assert status == 200 and prop.text == "#BADA55"
def test_move(self) -> None:
"""Move a item."""
self.mkcalendar("/calendar.ics/")
event = get_file_content("event1.ics")
path1 = "/calendar.ics/event1.ics"
path2 = "/calendar.ics/event2.ics"
self.put(path1, event)
self.request("MOVE", path1, check=201,
HTTP_DESTINATION="http://127.0.0.1/"+path2)
self.get(path1, check=404)
self.get(path2)
def test_move_between_collections(self) -> None:
"""Move a item."""
self.mkcalendar("/calendar1.ics/")
self.mkcalendar("/calendar2.ics/")
event = get_file_content("event1.ics")
path1 = "/calendar1.ics/event1.ics"
path2 = "/calendar2.ics/event2.ics"
self.put(path1, event)
self.request("MOVE", path1, check=201,
HTTP_DESTINATION="http://127.0.0.1/"+path2)
self.get(path1, check=404)
self.get(path2)
def test_move_between_collections_duplicate_uid(self) -> None:
"""Move a item to a collection which already contains the UID."""
self.mkcalendar("/calendar1.ics/")
self.mkcalendar("/calendar2.ics/")
event = get_file_content("event1.ics")
path1 = "/calendar1.ics/event1.ics"
path2 = "/calendar2.ics/event2.ics"
self.put(path1, event)
self.put("/calendar2.ics/event1.ics", event)
status, _, answer = self.request(
"MOVE", path1, HTTP_DESTINATION="http://127.0.0.1/"+path2)
assert status in (403, 409)
xml = DefusedET.fromstring(answer)
assert xml.tag == xmlutils.make_clark("D:error")
assert xml.find(xmlutils.make_clark("C:no-uid-conflict")) is not None
def test_move_between_collections_overwrite(self) -> None:
"""Move a item to a collection which already contains the item."""
self.mkcalendar("/calendar1.ics/")
self.mkcalendar("/calendar2.ics/")
event = get_file_content("event1.ics")
path1 = "/calendar1.ics/event1.ics"
path2 = "/calendar2.ics/event1.ics"
self.put(path1, event)
self.put(path2, event)
self.request("MOVE", path1, check=412,
HTTP_DESTINATION="http://127.0.0.1/"+path2)
self.request("MOVE", path1, check=204, HTTP_OVERWRITE="T",
HTTP_DESTINATION="http://127.0.0.1/"+path2)
def test_move_between_collections_overwrite_uid_conflict(self) -> None:
"""Move an item to a collection which already contains the item with
a different UID."""
self.mkcalendar("/calendar1.ics/")
self.mkcalendar("/calendar2.ics/")
event1 = get_file_content("event1.ics")
event2 = get_file_content("event2.ics")
path1 = "/calendar1.ics/event1.ics"
path2 = "/calendar2.ics/event2.ics"
self.put(path1, event1)
self.put(path2, event2)
status, _, answer = self.request(
"MOVE", path1, HTTP_OVERWRITE="T",
HTTP_DESTINATION="http://127.0.0.1/"+path2)
assert status in (403, 409)
xml = DefusedET.fromstring(answer)
assert xml.tag == xmlutils.make_clark("D:error")
assert xml.find(xmlutils.make_clark("C:no-uid-conflict")) is not None
def test_head(self) -> None:
_, headers, answer = self.request("HEAD", "/", check=302)
assert int(headers.get("Content-Length", "0")) > 0 and not answer
def test_options(self) -> None:
_, headers, _ = self.request("OPTIONS", "/", check=200)
assert "DAV" in headers
def test_delete_collection(self) -> None:
"""Delete a collection."""
self.mkcalendar("/calendar.ics/")
event = get_file_content("event1.ics")
self.put("/calendar.ics/event1.ics", event)
_, responses = self.delete("/calendar.ics/")
assert responses["/calendar.ics/"] == 200
self.get("/calendar.ics/", check=404)
def test_delete_collection_global_forbid(self) -> None:
"""Delete a collection (expect forbidden)."""
self.configure({"rights": {"permit_delete_collection": False}})
self.mkcalendar("/calendar.ics/")
event = get_file_content("event1.ics")
self.put("/calendar.ics/event1.ics", event)
_, responses = self.delete("/calendar.ics/", check=401)
self.get("/calendar.ics/", check=200)
def test_delete_collection_global_forbid_explicit_permit(self) -> None:
"""Delete a collection with permitted path (expect permit)."""
self.configure({"rights": {"permit_delete_collection": False}})
self.mkcalendar("/test-permit-delete/")
event = get_file_content("event1.ics")
self.put("/test-permit-delete/event1.ics", event)
_, responses = self.delete("/test-permit-delete/", check=200)
self.get("/test-permit-delete/", check=404)
def test_delete_collection_global_permit_explicit_forbid(self) -> None:
"""Delete a collection with permitted path (expect forbid)."""
self.configure({"rights": {"permit_delete_collection": True}})
self.mkcalendar("/test-forbid-delete/")
event = get_file_content("event1.ics")
self.put("/test-forbid-delete/event1.ics", event)
_, responses = self.delete("/test-forbid-delete/", check=401)
self.get("/test-forbid-delete/", check=200)
def test_delete_root_collection(self) -> None:
"""Delete the root collection."""
self.mkcalendar("/calendar.ics/")
event = get_file_content("event1.ics")
self.put("/event1.ics", event)
self.put("/calendar.ics/event1.ics", event)
_, responses = self.delete("/")
assert len(responses) == 1 and responses["/"] == 200
self.get("/calendar.ics/", check=404)
self.get("/event1.ics", 404)
def test_overwrite_collection_global_forbid(self) -> None:
"""Overwrite a collection (expect forbid)."""
self.configure({"rights": {"permit_overwrite_collection": False}})
event = get_file_content("event1.ics")
self.put("/calender.ics/", event, check=401)
def test_overwrite_collection_global_forbid_explict_permit(self) -> None:
"""Overwrite a collection with permitted path (expect permit)."""
self.configure({"rights": {"permit_overwrite_collection": False}})
event = get_file_content("event1.ics")
self.put("/test-permit-overwrite/", event, check=201)
def test_overwrite_collection_global_permit(self) -> None:
"""Overwrite a collection (expect permit)."""
self.configure({"rights": {"permit_overwrite_collection": True}})
event = get_file_content("event1.ics")
self.put("/calender.ics/", event, check=201)
def test_overwrite_collection_global_permit_explict_forbid(self) -> None:
"""Overwrite a collection with forbidden path (expect forbid)."""
self.configure({"rights": {"permit_overwrite_collection": True}})
event = get_file_content("event1.ics")
self.put("/test-forbid-overwrite/", event, check=401)
def test_propfind(self) -> None:
calendar_path = "/calendar.ics/"
self.mkcalendar("/calendar.ics/")
event = get_file_content("event1.ics")
event_path = posixpath.join(calendar_path, "event.ics")
self.put(event_path, event)
_, responses = self.propfind("/", HTTP_DEPTH="1")
assert len(responses) == 2
assert "/" in responses and calendar_path in responses
_, responses = self.propfind(calendar_path, HTTP_DEPTH="1")
assert len(responses) == 2
assert calendar_path in responses and event_path in responses
def test_propfind_propname(self) -> None:
self.mkcalendar("/calendar.ics/")
event = get_file_content("event1.ics")
self.put("/calendar.ics/event.ics", event)
propfind = get_file_content("propname.xml")
_, responses = self.propfind("/calendar.ics/", propfind)
response = responses["/calendar.ics/"]
assert not isinstance(response, int)
status, prop = response["D:sync-token"]
assert status == 200 and not prop.text
_, responses = self.propfind("/calendar.ics/event.ics", propfind)
response = responses["/calendar.ics/event.ics"]
assert not isinstance(response, int)
status, prop = response["D:getetag"]
assert status == 200 and not prop.text
def test_propfind_allprop(self) -> None:
self.mkcalendar("/calendar.ics/")
event = get_file_content("event1.ics")
self.put("/calendar.ics/event.ics", event)
propfind = get_file_content("allprop.xml")
_, responses = self.propfind("/calendar.ics/", propfind)
response = responses["/calendar.ics/"]
assert not isinstance(response, int)
status, prop = response["D:sync-token"]
assert status == 200 and prop.text
_, responses = self.propfind("/calendar.ics/event.ics", propfind)
response = responses["/calendar.ics/event.ics"]
assert not isinstance(response, int)
status, prop = response["D:getetag"]
assert status == 200 and prop.text
def test_propfind_nonexistent(self) -> None:
"""Read a property that does not exist."""
self.mkcalendar("/calendar.ics/")
propfind = get_file_content("propfind_calendar_color.xml")
_, responses = self.propfind("/calendar.ics/", propfind)
response = responses["/calendar.ics/"]
assert not isinstance(response, int) and len(response) == 1
status, prop = response["ICAL:calendar-color"]
assert status == 404 and not prop.text
def test_proppatch(self) -> None:
"""Set/Remove a property and read it back."""
self.mkcalendar("/calendar.ics/")
proppatch = get_file_content("proppatch_set_calendar_color.xml")
_, responses = self.proppatch("/calendar.ics/", proppatch)
response = responses["/calendar.ics/"]
assert not isinstance(response, int) and len(response) == 1
status, prop = response["ICAL:calendar-color"]
assert status == 200 and not prop.text
# Read property back
propfind = get_file_content("propfind_calendar_color.xml")
_, responses = self.propfind("/calendar.ics/", propfind)
response = responses["/calendar.ics/"]
assert not isinstance(response, int) and len(response) == 1
status, prop = response["ICAL:calendar-color"]
assert status == 200 and prop.text == "#BADA55"
propfind = get_file_content("allprop.xml")
_, responses = self.propfind("/calendar.ics/", propfind)
response = responses["/calendar.ics/"]
assert not isinstance(response, int)
status, prop = response["ICAL:calendar-color"]
assert status == 200 and prop.text == "#BADA55"
# Remove property
proppatch = get_file_content("proppatch_remove_calendar_color.xml")
_, responses = self.proppatch("/calendar.ics/", proppatch)
response = responses["/calendar.ics/"]
assert not isinstance(response, int) and len(response) == 1
status, prop = response["ICAL:calendar-color"]
assert status == 200 and not prop.text
# Read property back
propfind = get_file_content("propfind_calendar_color.xml")
_, responses = self.propfind("/calendar.ics/", propfind)
response = responses["/calendar.ics/"]
assert not isinstance(response, int) and len(response) == 1
status, prop = response["ICAL:calendar-color"]
assert status == 404
def test_proppatch_multiple1(self) -> None:
"""Set/Remove a multiple properties and read them back."""
self.mkcalendar("/calendar.ics/")
propfind = get_file_content("propfind_multiple.xml")
proppatch = get_file_content("proppatch_set_multiple1.xml")
_, responses = self.proppatch("/calendar.ics/", proppatch)
response = responses["/calendar.ics/"]
assert not isinstance(response, int) and len(response) == 2
status, prop = response["ICAL:calendar-color"]
assert status == 200 and not prop.text
status, prop = response["C:calendar-description"]
assert status == 200 and not prop.text
# Read properties back
_, responses = self.propfind("/calendar.ics/", propfind)
response = responses["/calendar.ics/"]
assert not isinstance(response, int) and len(response) == 2
status, prop = response["ICAL:calendar-color"]
assert status == 200 and prop.text == "#BADA55"
status, prop = response["C:calendar-description"]
assert status == 200 and prop.text == "test"
# Remove properties
proppatch = get_file_content("proppatch_remove_multiple1.xml")
_, responses = self.proppatch("/calendar.ics/", proppatch)
response = responses["/calendar.ics/"]
assert not isinstance(response, int) and len(response) == 2
status, prop = response["ICAL:calendar-color"]
assert status == 200 and not prop.text
status, prop = response["C:calendar-description"]
assert status == 200 and not prop.text
# Read properties back
_, responses = self.propfind("/calendar.ics/", propfind)
response = responses["/calendar.ics/"]
assert not isinstance(response, int) and len(response) == 2
status, prop = response["ICAL:calendar-color"]
assert status == 404
status, prop = response["C:calendar-description"]
assert status == 404
def test_proppatch_multiple2(self) -> None:
"""Set/Remove a multiple properties and read them back."""
self.mkcalendar("/calendar.ics/")
propfind = get_file_content("propfind_multiple.xml")
proppatch = get_file_content("proppatch_set_multiple2.xml")
_, responses = self.proppatch("/calendar.ics/", proppatch)
response = responses["/calendar.ics/"]
assert not isinstance(response, int) and len(response) == 2
status, prop = response["ICAL:calendar-color"]
assert status == 200 and not prop.text
status, prop = response["C:calendar-description"]
assert status == 200 and not prop.text
# Read properties back
_, responses = self.propfind("/calendar.ics/", propfind)
response = responses["/calendar.ics/"]
assert not isinstance(response, int) and len(response) == 2
assert len(response) == 2
status, prop = response["ICAL:calendar-color"]
assert status == 200 and prop.text == "#BADA55"
status, prop = response["C:calendar-description"]
assert status == 200 and prop.text == "test"
# Remove properties
proppatch = get_file_content("proppatch_remove_multiple2.xml")
_, responses = self.proppatch("/calendar.ics/", proppatch)
response = responses["/calendar.ics/"]
assert not isinstance(response, int) and len(response) == 2
status, prop = response["ICAL:calendar-color"]
assert status == 200 and not prop.text
status, prop = response["C:calendar-description"]
assert status == 200 and not prop.text
# Read properties back
_, responses = self.propfind("/calendar.ics/", propfind)
response = responses["/calendar.ics/"]
assert not isinstance(response, int) and len(response) == 2
status, prop = response["ICAL:calendar-color"]
assert status == 404
status, prop = response["C:calendar-description"]
assert status == 404
def test_proppatch_set_and_remove(self) -> None:
"""Set and remove multiple properties in single request."""
self.mkcalendar("/calendar.ics/")
propfind = get_file_content("propfind_multiple.xml")
# Prepare
proppatch = get_file_content("proppatch_set_multiple1.xml")
self.proppatch("/calendar.ics/", proppatch)
# Remove and set properties in single request
proppatch = get_file_content("proppatch_set_and_remove.xml")
_, responses = self.proppatch("/calendar.ics/", proppatch)
response = responses["/calendar.ics/"]
assert not isinstance(response, int) and len(response) == 2
status, prop = response["ICAL:calendar-color"]
assert status == 200 and not prop.text
status, prop = response["C:calendar-description"]
assert status == 200 and not prop.text
# Read properties back
_, responses = self.propfind("/calendar.ics/", propfind)
response = responses["/calendar.ics/"]
assert not isinstance(response, int) and len(response) == 2
status, prop = response["ICAL:calendar-color"]
assert status == 404
status, prop = response["C:calendar-description"]
assert status == 200 and prop.text == "test2"
def test_put_whole_calendar_multiple_events_with_same_uid(self) -> None:
"""Add two events with the same UID."""
self.put("/calendar.ics/", get_file_content("event2.ics"))
_, responses = self.report("/calendar.ics/", """\
<?xml version="1.0" encoding="utf-8" ?>
<C:calendar-query xmlns:C="urn:ietf:params:xml:ns:caldav">
<D:prop xmlns:D="DAV:">
<D:getetag/>
</D:prop>
</C:calendar-query>""")
assert len(responses) == 1
response = responses["/calendar.ics/event2.ics"]
assert not isinstance(response, int)
status, prop = response["D:getetag"]
assert status == 200 and prop.text
_, answer = self.get("/calendar.ics/")
assert answer.count("BEGIN:VEVENT") == 2
def _test_filter(self, filters: Iterable[str], kind: str = "event",
test: Optional[str] = None, items: Iterable[int] = (1,)
) -> List[str]:
filter_template = "<C:filter>%s</C:filter>"
create_collection_fn: Callable[[str], Any]
if kind in ("event", "journal", "todo"):
create_collection_fn = self.mkcalendar
path = "/calendar.ics/"
filename_template = "%s%d.ics"
namespace = "urn:ietf:params:xml:ns:caldav"
report = "calendar-query"
elif kind == "contact":
create_collection_fn = self.create_addressbook
if test:
filter_template = '<C:filter test="%s">%%s</C:filter>' % test
path = "/contacts.vcf/"
filename_template = "%s%d.vcf"
namespace = "urn:ietf:params:xml:ns:carddav"
report = "addressbook-query"
else:
raise ValueError("Unsupported kind: %r" % kind)
status, _, = self.delete(path, check=None)
assert status in (200, 404)
create_collection_fn(path)
for i in items:
filename = filename_template % (kind, i)
event = get_file_content(filename)
self.put(posixpath.join(path, filename), event)
filters_text = "".join(filter_template % f for f in filters)
_, responses = self.report(path, """\
<?xml version="1.0" encoding="utf-8" ?>
<C:{1} xmlns:C="{0}">
<D:prop xmlns:D="DAV:">
<D:getetag/>
</D:prop>
{2}
</C:{1}>""".format(namespace, report, filters_text))
assert responses is not None
paths = []
for path, props in responses.items():
assert not isinstance(props, int) and len(props) == 1
status, prop = props["D:getetag"]
assert status == 200 and prop.text
paths.append(path)
return paths
def test_addressbook_empty_filter(self) -> None:
self._test_filter([""], kind="contact")
def test_addressbook_prop_filter(self) -> None:
assert "/contacts.vcf/contact1.vcf" in self._test_filter(["""\
<C:prop-filter name="NICKNAME">
<C:text-match collation="i;unicode-casemap" match-type="contains"
>es</C:text-match>
</C:prop-filter>"""], "contact")
assert "/contacts.vcf/contact1.vcf" in self._test_filter(["""\
<C:prop-filter name="NICKNAME">
<C:text-match collation="i;unicode-casemap">es</C:text-match>
</C:prop-filter>"""], "contact")
assert "/contacts.vcf/contact1.vcf" not in self._test_filter(["""\
<C:prop-filter name="NICKNAME">
<C:text-match collation="i;unicode-casemap" match-type="contains"
>a</C:text-match>
</C:prop-filter>"""], "contact")
assert "/contacts.vcf/contact1.vcf" in self._test_filter(["""\
<C:prop-filter name="NICKNAME">
<C:text-match collation="i;unicode-casemap" match-type="equals"
>test</C:text-match>
</C:prop-filter>"""], "contact")
assert "/contacts.vcf/contact1.vcf" not in self._test_filter(["""\
<C:prop-filter name="NICKNAME">
<C:text-match collation="i;unicode-casemap" match-type="equals"
>tes</C:text-match>
</C:prop-filter>"""], "contact")
assert "/contacts.vcf/contact1.vcf" not in self._test_filter(["""\
<C:prop-filter name="NICKNAME">
<C:text-match collation="i;unicode-casemap" match-type="equals"
>est</C:text-match>
</C:prop-filter>"""], "contact")
assert "/contacts.vcf/contact1.vcf" in self._test_filter(["""\
<C:prop-filter name="NICKNAME">
<C:text-match collation="i;unicode-casemap" match-type="starts-with"
>tes</C:text-match>
</C:prop-filter>"""], "contact")
assert "/contacts.vcf/contact1.vcf" not in self._test_filter(["""\
<C:prop-filter name="NICKNAME">
<C:text-match collation="i;unicode-casemap" match-type="starts-with"
>est</C:text-match>
</C:prop-filter>"""], "contact")
assert "/contacts.vcf/contact1.vcf" in self._test_filter(["""\
<C:prop-filter name="NICKNAME">
<C:text-match collation="i;unicode-casemap" match-type="ends-with"
>est</C:text-match>
</C:prop-filter>"""], "contact")
assert "/contacts.vcf/contact1.vcf" not in self._test_filter(["""\
<C:prop-filter name="NICKNAME">
<C:text-match collation="i;unicode-casemap" match-type="ends-with"
>tes</C:text-match>
</C:prop-filter>"""], "contact")
def test_addressbook_prop_filter_any(self) -> None:
assert "/contacts.vcf/contact1.vcf" in self._test_filter(["""\
<C:prop-filter name="NICKNAME">
<C:text-match collation="i;unicode-casemap">test</C:text-match>
</C:prop-filter>
<C:prop-filter name="EMAIL">
<C:text-match collation="i;unicode-casemap">test</C:text-match>
</C:prop-filter>"""], "contact", test="anyof")
assert "/contacts.vcf/contact1.vcf" not in self._test_filter(["""\
<C:prop-filter name="NICKNAME">
<C:text-match collation="i;unicode-casemap">a</C:text-match>
</C:prop-filter>
<C:prop-filter name="EMAIL">
<C:text-match collation="i;unicode-casemap">test</C:text-match>
</C:prop-filter>"""], "contact", test="anyof")
assert "/contacts.vcf/contact1.vcf" in self._test_filter(["""\
<C:prop-filter name="NICKNAME">
<C:text-match collation="i;unicode-casemap">test</C:text-match>
</C:prop-filter>
<C:prop-filter name="EMAIL">
<C:text-match collation="i;unicode-casemap">test</C:text-match>
</C:prop-filter>"""], "contact")
def test_addressbook_prop_filter_all(self) -> None:
assert "/contacts.vcf/contact1.vcf" in self._test_filter(["""\
<C:prop-filter name="NICKNAME">
<C:text-match collation="i;unicode-casemap">tes</C:text-match>
</C:prop-filter>
<C:prop-filter name="NICKNAME">
<C:text-match collation="i;unicode-casemap">est</C:text-match>
</C:prop-filter>"""], "contact", test="allof")
assert "/contacts.vcf/contact1.vcf" not in self._test_filter(["""\
<C:prop-filter name="NICKNAME">
<C:text-match collation="i;unicode-casemap">test</C:text-match>
</C:prop-filter>
<C:prop-filter name="EMAIL">
<C:text-match collation="i;unicode-casemap">test</C:text-match>
</C:prop-filter>"""], "contact", test="allof")
def test_calendar_empty_filter(self) -> None:
self._test_filter([""])
def test_calendar_tag_filter(self) -> None:
"""Report request with tag-based filter on calendar."""
assert "/calendar.ics/event1.ics" in self._test_filter(["""\
<C:comp-filter name="VCALENDAR"></C:comp-filter>"""])
def test_item_tag_filter(self) -> None:
"""Report request with tag-based filter on an item."""
assert "/calendar.ics/event1.ics" in self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT"></C:comp-filter>
</C:comp-filter>"""])
assert "/calendar.ics/event1.ics" not in self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VTODO"></C:comp-filter>
</C:comp-filter>"""])
def test_item_not_tag_filter(self) -> None:
"""Report request with tag-based is-not filter on an item."""
assert "/calendar.ics/event1.ics" not in self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT">
<C:is-not-defined />
</C:comp-filter>
</C:comp-filter>"""])
assert "/calendar.ics/event1.ics" in self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VTODO">
<C:is-not-defined />
</C:comp-filter>
</C:comp-filter>"""])
def test_item_prop_filter(self) -> None:
"""Report request with prop-based filter on an item."""
assert "/calendar.ics/event1.ics" in self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT">
<C:prop-filter name="SUMMARY"></C:prop-filter>
</C:comp-filter>
</C:comp-filter>"""])
assert "/calendar.ics/event1.ics" not in self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT">
<C:prop-filter name="UNKNOWN"></C:prop-filter>
</C:comp-filter>
</C:comp-filter>"""])
def test_item_not_prop_filter(self) -> None:
"""Report request with prop-based is-not filter on an item."""
assert "/calendar.ics/event1.ics" not in self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT">
<C:prop-filter name="SUMMARY">
<C:is-not-defined />
</C:prop-filter>
</C:comp-filter>
</C:comp-filter>"""])
assert "/calendar.ics/event1.ics" in self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT">
<C:prop-filter name="UNKNOWN">
<C:is-not-defined />
</C:prop-filter>
</C:comp-filter>
</C:comp-filter>"""])
def test_mutiple_filters(self) -> None:
"""Report request with multiple filters on an item."""
assert "/calendar.ics/event1.ics" not in self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT">
<C:prop-filter name="SUMMARY">
<C:is-not-defined />
</C:prop-filter>
</C:comp-filter>
</C:comp-filter>""", """
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT">
<C:prop-filter name="UNKNOWN">
<C:is-not-defined />
</C:prop-filter>
</C:comp-filter>
</C:comp-filter>"""])
assert "/calendar.ics/event1.ics" in self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT">
<C:prop-filter name="SUMMARY"></C:prop-filter>
</C:comp-filter>
</C:comp-filter>""", """
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT">
<C:prop-filter name="UNKNOWN">
<C:is-not-defined />
</C:prop-filter>
</C:comp-filter>
</C:comp-filter>"""])
assert "/calendar.ics/event1.ics" in self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT">
<C:prop-filter name="SUMMARY"></C:prop-filter>
<C:prop-filter name="UNKNOWN">
<C:is-not-defined />
</C:prop-filter>
</C:comp-filter>
</C:comp-filter>"""])
def test_text_match_filter(self) -> None:
"""Report request with text-match filter on calendar."""
assert "/calendar.ics/event1.ics" in self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT">
<C:prop-filter name="SUMMARY">
<C:text-match>event</C:text-match>
</C:prop-filter>
</C:comp-filter>
</C:comp-filter>"""])
assert "/calendar.ics/event1.ics" in self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT">
<C:prop-filter name="CATEGORIES">
<C:text-match>some_category1</C:text-match>
</C:prop-filter>
</C:comp-filter>
</C:comp-filter>"""])
assert "/calendar.ics/event1.ics" in self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT">
<C:prop-filter name="CATEGORIES">
<C:text-match collation="i;octet">some_category1</C:text-match>
</C:prop-filter>
</C:comp-filter>
</C:comp-filter>"""])
assert "/calendar.ics/event1.ics" not in self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT">
<C:prop-filter name="UNKNOWN">
<C:text-match>event</C:text-match>
</C:prop-filter>
</C:comp-filter>
</C:comp-filter>"""])
assert "/calendar.ics/event1.ics" not in self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT">
<C:prop-filter name="SUMMARY">
<C:text-match>unknown</C:text-match>
</C:prop-filter>
</C:comp-filter>
</C:comp-filter>"""])
assert "/calendar.ics/event1.ics" not in self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT">
<C:prop-filter name="SUMMARY">
<C:text-match negate-condition="yes">event</C:text-match>
</C:prop-filter>
</C:comp-filter>
</C:comp-filter>"""])
def test_param_filter(self) -> None:
"""Report request with param-filter on calendar."""
assert "/calendar.ics/event1.ics" in self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT">
<C:prop-filter name="ATTENDEE">
<C:param-filter name="PARTSTAT">
<C:text-match collation="i;ascii-casemap"
>ACCEPTED</C:text-match>
</C:param-filter>
</C:prop-filter>
</C:comp-filter>
</C:comp-filter>"""])
assert "/calendar.ics/event1.ics" not in self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT">
<C:prop-filter name="ATTENDEE">
<C:param-filter name="PARTSTAT">
<C:text-match collation="i;ascii-casemap"
>UNKNOWN</C:text-match>
</C:param-filter>
</C:prop-filter>
</C:comp-filter>
</C:comp-filter>"""])
assert "/calendar.ics/event1.ics" not in self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT">
<C:prop-filter name="ATTENDEE">
<C:param-filter name="PARTSTAT">
<C:is-not-defined />
</C:param-filter>
</C:prop-filter>
</C:comp-filter>
</C:comp-filter>"""])
assert "/calendar.ics/event1.ics" in self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT">
<C:prop-filter name="ATTENDEE">
<C:param-filter name="UNKNOWN">
<C:is-not-defined />
</C:param-filter>
</C:prop-filter>
</C:comp-filter>
</C:comp-filter>"""])
def test_time_range_filter_events(self) -> None:
"""Report request with time-range filter on events."""
answer = self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT">
<C:time-range start="20130801T000000Z" end="20131001T000000Z"/>
</C:comp-filter>
</C:comp-filter>"""], "event", items=range(1, 6))
assert "/calendar.ics/event1.ics" in answer
assert "/calendar.ics/event2.ics" in answer
assert "/calendar.ics/event3.ics" in answer
assert "/calendar.ics/event4.ics" in answer
assert "/calendar.ics/event5.ics" in answer
answer = self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VTODO">
<C:time-range start="20130801T000000Z" end="20131001T000000Z"/>
</C:comp-filter>
</C:comp-filter>"""], "event", items=range(1, 6))
assert "/calendar.ics/event1.ics" not in answer
answer = self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT">
<C:prop-filter name="ATTENDEE">
<C:param-filter name="PARTSTAT">
<C:is-not-defined />
</C:param-filter>
</C:prop-filter>
<C:time-range start="20130801T000000Z" end="20131001T000000Z"/>
</C:comp-filter>
</C:comp-filter>"""], items=range(1, 6))
assert "/calendar.ics/event1.ics" not in answer
assert "/calendar.ics/event2.ics" not in answer
assert "/calendar.ics/event3.ics" not in answer
assert "/calendar.ics/event4.ics" not in answer
assert "/calendar.ics/event5.ics" not in answer
answer = self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT">
<C:time-range start="20130902T000000Z" end="20131001T000000Z"/>
</C:comp-filter>
</C:comp-filter>"""], items=range(1, 6))
assert "/calendar.ics/event1.ics" not in answer
assert "/calendar.ics/event2.ics" in answer
assert "/calendar.ics/event3.ics" in answer
assert "/calendar.ics/event4.ics" in answer
assert "/calendar.ics/event5.ics" in answer
answer = self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT">
<C:time-range start="20130903T000000Z" end="20130908T000000Z"/>
</C:comp-filter>
</C:comp-filter>"""], items=range(1, 6))
assert "/calendar.ics/event1.ics" not in answer
assert "/calendar.ics/event2.ics" not in answer
assert "/calendar.ics/event3.ics" in answer
assert "/calendar.ics/event4.ics" in answer
assert "/calendar.ics/event5.ics" in answer
answer = self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT">
<C:time-range start="20130903T000000Z" end="20130904T000000Z"/>
</C:comp-filter>
</C:comp-filter>"""], items=range(1, 6))
assert "/calendar.ics/event1.ics" not in answer
assert "/calendar.ics/event2.ics" not in answer
assert "/calendar.ics/event3.ics" in answer
assert "/calendar.ics/event4.ics" not in answer
assert "/calendar.ics/event5.ics" not in answer
answer = self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT">
<C:time-range start="20130805T000000Z" end="20130810T000000Z"/>
</C:comp-filter>
</C:comp-filter>"""], items=range(1, 6))
assert "/calendar.ics/event1.ics" not in answer
assert "/calendar.ics/event2.ics" not in answer
assert "/calendar.ics/event3.ics" not in answer
assert "/calendar.ics/event4.ics" not in answer
assert "/calendar.ics/event5.ics" not in answer
# HACK: VObject doesn't match RECURRENCE-ID to recurrences, the
# overwritten recurrence is still used for filtering.
answer = self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT">
<C:time-range start="20170601T063000Z" end="20170601T070000Z"/>
</C:comp-filter>
</C:comp-filter>"""], items=(6, 7, 8, 9))
assert "/calendar.ics/event6.ics" in answer
assert "/calendar.ics/event7.ics" in answer
assert "/calendar.ics/event8.ics" in answer
assert "/calendar.ics/event9.ics" in answer
answer = self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT">
<C:time-range start="20170701T060000Z"/>
</C:comp-filter>
</C:comp-filter>"""], items=(6, 7, 8, 9))
assert "/calendar.ics/event6.ics" in answer
assert "/calendar.ics/event7.ics" in answer
assert "/calendar.ics/event8.ics" in answer
assert "/calendar.ics/event9.ics" not in answer
answer = self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT">
<C:time-range start="20170702T070000Z" end="20170704T060000Z"/>
</C:comp-filter>
</C:comp-filter>"""], items=(6, 7, 8, 9))
assert "/calendar.ics/event6.ics" not in answer
assert "/calendar.ics/event7.ics" not in answer
assert "/calendar.ics/event8.ics" not in answer
assert "/calendar.ics/event9.ics" not in answer
answer = self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT">
<C:time-range start="20170602T075959Z" end="20170602T080000Z"/>
</C:comp-filter>
</C:comp-filter>"""], items=(9,))
assert "/calendar.ics/event9.ics" in answer
answer = self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT">
<C:time-range start="20170602T080000Z" end="20170603T083000Z"/>
</C:comp-filter>
</C:comp-filter>"""], items=(9,))
assert "/calendar.ics/event9.ics" not in answer
def test_time_range_filter_events_rrule(self) -> None:
"""Report request with time-range filter on events with rrules."""
answer = self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT">
<C:time-range start="20130801T000000Z" end="20131001T000000Z"/>
</C:comp-filter>
</C:comp-filter>"""], "event", items=(1, 2))
assert "/calendar.ics/event1.ics" in answer
assert "/calendar.ics/event2.ics" in answer
answer = self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT">
<C:time-range start="20140801T000000Z" end="20141001T000000Z"/>
</C:comp-filter>
</C:comp-filter>"""], "event", items=(1, 2))
assert "/calendar.ics/event1.ics" not in answer
assert "/calendar.ics/event2.ics" in answer
answer = self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT">
<C:time-range start="20120801T000000Z" end="20121001T000000Z"/>
</C:comp-filter>
</C:comp-filter>"""], "event", items=(1, 2))
assert "/calendar.ics/event1.ics" not in answer
assert "/calendar.ics/event2.ics" not in answer
answer = self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT">
<C:time-range start="20130903T000000Z" end="20130907T000000Z"/>
</C:comp-filter>
</C:comp-filter>"""], "event", items=(1, 2))
assert "/calendar.ics/event1.ics" not in answer
assert "/calendar.ics/event2.ics" not in answer
def test_time_range_filter_todos(self) -> None:
"""Report request with time-range filter on todos."""
answer = self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VTODO">
<C:time-range start="20130801T000000Z" end="20131001T000000Z"/>
</C:comp-filter>
</C:comp-filter>"""], "todo", items=range(1, 9))
assert "/calendar.ics/todo1.ics" in answer
assert "/calendar.ics/todo2.ics" in answer
assert "/calendar.ics/todo3.ics" in answer
assert "/calendar.ics/todo4.ics" in answer
assert "/calendar.ics/todo5.ics" in answer
assert "/calendar.ics/todo6.ics" in answer
assert "/calendar.ics/todo7.ics" in answer
assert "/calendar.ics/todo8.ics" in answer
answer = self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VTODO">
<C:time-range start="20130901T160000Z" end="20130901T183000Z"/>
</C:comp-filter>
</C:comp-filter>"""], "todo", items=range(1, 9))
assert "/calendar.ics/todo1.ics" not in answer
assert "/calendar.ics/todo2.ics" in answer
assert "/calendar.ics/todo3.ics" in answer
assert "/calendar.ics/todo4.ics" not in answer
assert "/calendar.ics/todo5.ics" not in answer
assert "/calendar.ics/todo6.ics" not in answer
assert "/calendar.ics/todo7.ics" in answer
assert "/calendar.ics/todo8.ics" in answer
answer = self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VTODO">
<C:time-range start="20130903T160000Z" end="20130901T183000Z"/>
</C:comp-filter>
</C:comp-filter>"""], "todo", items=range(1, 9))
assert "/calendar.ics/todo2.ics" not in answer
answer = self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VTODO">
<C:time-range start="20130903T160000Z" end="20130901T173000Z"/>
</C:comp-filter>
</C:comp-filter>"""], "todo", items=range(1, 9))
assert "/calendar.ics/todo2.ics" not in answer
answer = self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VTODO">
<C:time-range start="20130903T160000Z" end="20130903T173000Z"/>
</C:comp-filter>
</C:comp-filter>"""], "todo", items=range(1, 9))
assert "/calendar.ics/todo3.ics" not in answer
answer = self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VTODO">
<C:time-range start="20130903T160000Z" end="20130803T203000Z"/>
</C:comp-filter>
</C:comp-filter>"""], "todo", items=range(1, 9))
assert "/calendar.ics/todo7.ics" in answer
def test_time_range_filter_todos_rrule(self) -> None:
"""Report request with time-range filter on todos with rrules."""
answer = self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VTODO">
<C:time-range start="20130801T000000Z" end="20131001T000000Z"/>
</C:comp-filter>
</C:comp-filter>"""], "todo", items=(1, 2, 9))
assert "/calendar.ics/todo1.ics" in answer
assert "/calendar.ics/todo2.ics" in answer
assert "/calendar.ics/todo9.ics" in answer
answer = self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VTODO">
<C:time-range start="20140801T000000Z" end="20141001T000000Z"/>
</C:comp-filter>
</C:comp-filter>"""], "todo", items=(1, 2, 9))
assert "/calendar.ics/todo1.ics" not in answer
assert "/calendar.ics/todo2.ics" in answer
assert "/calendar.ics/todo9.ics" in answer
answer = self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VTODO">
<C:time-range start="20140902T000000Z" end="20140903T000000Z"/>
</C:comp-filter>
</C:comp-filter>"""], "todo", items=(1, 2))
assert "/calendar.ics/todo1.ics" not in answer
assert "/calendar.ics/todo2.ics" in answer
answer = self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VTODO">
<C:time-range start="20140904T000000Z" end="20140914T000000Z"/>
</C:comp-filter>
</C:comp-filter>"""], "todo", items=(1, 2))
assert "/calendar.ics/todo1.ics" not in answer
assert "/calendar.ics/todo2.ics" not in answer
answer = self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VTODO">
<C:time-range start="20130902T000000Z" end="20130906T235959Z"/>
</C:comp-filter>
</C:comp-filter>"""], "todo", items=(9,))
assert "/calendar.ics/todo9.ics" not in answer
def test_time_range_filter_journals(self) -> None:
"""Report request with time-range filter on journals."""
answer = self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VJOURNAL">
<C:time-range start="19991229T000000Z" end="20000202T000000Z"/>
</C:comp-filter>
</C:comp-filter>"""], "journal", items=(1, 2, 3))
assert "/calendar.ics/journal1.ics" not in answer
assert "/calendar.ics/journal2.ics" in answer
assert "/calendar.ics/journal3.ics" in answer
answer = self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VJOURNAL">
<C:time-range start="19991229T000000Z" end="20000202T000000Z"/>
</C:comp-filter>
</C:comp-filter>"""], "journal", items=(1, 2, 3))
assert "/calendar.ics/journal1.ics" not in answer
assert "/calendar.ics/journal2.ics" in answer
assert "/calendar.ics/journal3.ics" in answer
answer = self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VJOURNAL">
<C:time-range start="19981229T000000Z" end="19991012T000000Z"/>
</C:comp-filter>
</C:comp-filter>"""], "journal", items=(1, 2, 3))
assert "/calendar.ics/journal1.ics" not in answer
assert "/calendar.ics/journal2.ics" not in answer
assert "/calendar.ics/journal3.ics" not in answer
answer = self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VJOURNAL">
<C:time-range start="20131229T000000Z" end="21520202T000000Z"/>
</C:comp-filter>
</C:comp-filter>"""], "journal", items=(1, 2, 3))
assert "/calendar.ics/journal1.ics" not in answer
assert "/calendar.ics/journal2.ics" in answer
assert "/calendar.ics/journal3.ics" not in answer
answer = self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VJOURNAL">
<C:time-range start="20000101T000000Z" end="20000202T000000Z"/>
</C:comp-filter>
</C:comp-filter>"""], "journal", items=(1, 2, 3))
assert "/calendar.ics/journal1.ics" not in answer
assert "/calendar.ics/journal2.ics" in answer
assert "/calendar.ics/journal3.ics" in answer
def test_time_range_filter_journals_rrule(self) -> None:
"""Report request with time-range filter on journals with rrules."""
answer = self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VJOURNAL">
<C:time-range start="19991229T000000Z" end="20000202T000000Z"/>
</C:comp-filter>
</C:comp-filter>"""], "journal", items=(1, 2))
assert "/calendar.ics/journal1.ics" not in answer
assert "/calendar.ics/journal2.ics" in answer
answer = self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VJOURNAL">
<C:time-range start="20051229T000000Z" end="20060202T000000Z"/>
</C:comp-filter>
</C:comp-filter>"""], "journal", items=(1, 2))
assert "/calendar.ics/journal1.ics" not in answer
assert "/calendar.ics/journal2.ics" in answer
answer = self._test_filter(["""\
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VJOURNAL">
<C:time-range start="20060102T000000Z" end="20060202T000000Z"/>
</C:comp-filter>
</C:comp-filter>"""], "journal", items=(1, 2))
assert "/calendar.ics/journal1.ics" not in answer
assert "/calendar.ics/journal2.ics" not in answer
def test_report_item(self) -> None:
"""Test report request on an item"""
calendar_path = "/calendar.ics/"
self.mkcalendar(calendar_path)
event = get_file_content("event1.ics")
event_path = posixpath.join(calendar_path, "event.ics")
self.put(event_path, event)
_, responses = self.report(event_path, """\
<?xml version="1.0" encoding="utf-8" ?>
<C:calendar-query xmlns:C="urn:ietf:params:xml:ns:caldav">
<D:prop xmlns:D="DAV:">
<D:getetag />
</D:prop>
</C:calendar-query>""")
assert len(responses) == 1
response = responses[event_path]
assert isinstance(response, dict)
status, prop = response["D:getetag"]
assert status == 200 and prop.text
def test_report_free_busy(self) -> None:
"""Test free busy report on a few items"""
calendar_path = "/calendar.ics/"
self.mkcalendar(calendar_path)
for i in (1, 2, 10):
filename = "event{}.ics".format(i)
event = get_file_content(filename)
self.put(posixpath.join(calendar_path, filename), event)
code, responses = self.report(calendar_path, """\
<?xml version="1.0" encoding="utf-8" ?>
<C:free-busy-query xmlns:C="urn:ietf:params:xml:ns:caldav">
<C:time-range start="20130901T140000Z" end="20130908T220000Z"/>
</C:free-busy-query>""", 200, is_xml=False)
for response in responses.values():
assert isinstance(response, vobject.base.Component)
assert len(responses) == 1
vcalendar = list(responses.values())[0]
assert isinstance(vcalendar, vobject.base.Component)
assert len(vcalendar.vfreebusy_list) == 3
types = {}
for vfb in vcalendar.vfreebusy_list:
fbtype_val = vfb.fbtype.value
if fbtype_val not in types:
types[fbtype_val] = 0
types[fbtype_val] += 1
assert types == {'BUSY': 2, 'FREE': 1}
# Test max_freebusy_occurrence limit
self.configure({"reporting": {"max_freebusy_occurrence": 1}})
code, responses = self.report(calendar_path, """\
<?xml version="1.0" encoding="utf-8" ?>
<C:free-busy-query xmlns:C="urn:ietf:params:xml:ns:caldav">
<C:time-range start="20130901T140000Z" end="20130908T220000Z"/>
</C:free-busy-query>""", 400, is_xml=False)
def _report_sync_token(
self, calendar_path: str, sync_token: Optional[str] = None
) -> Tuple[str, RESPONSES]:
sync_token_xml = (
"<sync-token><![CDATA[%s]]></sync-token>" % sync_token
if sync_token else "<sync-token />")
status, _, answer = self.request("REPORT", calendar_path, """\
<?xml version="1.0" encoding="utf-8" ?>
<sync-collection xmlns="DAV:">
<prop>
<getetag />
</prop>
%s
</sync-collection>""" % sync_token_xml)
xml = DefusedET.fromstring(answer)
if status in (403, 409):
assert xml.tag == xmlutils.make_clark("D:error")
assert sync_token and xml.find(
xmlutils.make_clark("D:valid-sync-token")) is not None
return "", {}
assert status == 207
assert xml.tag == xmlutils.make_clark("D:multistatus")
sync_token = xml.find(xmlutils.make_clark("D:sync-token")).text.strip()
assert sync_token
responses = self.parse_responses(answer)
for href, response in responses.items():
if not isinstance(response, int):
status, prop = response["D:getetag"]
assert status == 200 and prop.text and len(response) == 1
responses[href] = response = 200
assert response in (200, 404)
return sync_token, responses
def test_report_sync_collection_no_change(self) -> None:
"""Test sync-collection report without modifying the collection"""
calendar_path = "/calendar.ics/"
self.mkcalendar(calendar_path)
event = get_file_content("event1.ics")
event_path = posixpath.join(calendar_path, "event.ics")
self.put(event_path, event)
sync_token, responses = self._report_sync_token(calendar_path)
assert len(responses) == 1 and responses[event_path] == 200
new_sync_token, responses = self._report_sync_token(
calendar_path, sync_token)
if not self.full_sync_token_support and not new_sync_token:
return
assert sync_token == new_sync_token and len(responses) == 0
def test_report_sync_collection_add(self) -> None:
"""Test sync-collection report with an added item"""
calendar_path = "/calendar.ics/"
self.mkcalendar(calendar_path)
sync_token, responses = self._report_sync_token(calendar_path)
assert len(responses) == 0
event = get_file_content("event1.ics")
event_path = posixpath.join(calendar_path, "event.ics")
self.put(event_path, event)
sync_token, responses = self._report_sync_token(
calendar_path, sync_token)
if not self.full_sync_token_support and not sync_token:
return
assert len(responses) == 1 and responses[event_path] == 200
def test_report_sync_collection_delete(self) -> None:
"""Test sync-collection report with a deleted item"""
calendar_path = "/calendar.ics/"
self.mkcalendar(calendar_path)
event = get_file_content("event1.ics")
event_path = posixpath.join(calendar_path, "event.ics")
self.put(event_path, event)
sync_token, responses = self._report_sync_token(calendar_path)
assert len(responses) == 1 and responses[event_path] == 200
self.delete(event_path)
sync_token, responses = self._report_sync_token(
calendar_path, sync_token)
if not self.full_sync_token_support and not sync_token:
return
assert len(responses) == 1 and responses[event_path] == 404
def test_report_sync_collection_create_delete(self) -> None:
"""Test sync-collection report with a created and deleted item"""
calendar_path = "/calendar.ics/"
self.mkcalendar(calendar_path)
sync_token, responses = self._report_sync_token(calendar_path)
assert len(responses) == 0
event = get_file_content("event1.ics")
event_path = posixpath.join(calendar_path, "event.ics")
self.put(event_path, event)
self.delete(event_path)
sync_token, responses = self._report_sync_token(
calendar_path, sync_token)
if not self.full_sync_token_support and not sync_token:
return
assert len(responses) == 1 and responses[event_path] == 404
def test_report_sync_collection_modify_undo(self) -> None:
"""Test sync-collection report with a modified and changed back item"""
calendar_path = "/calendar.ics/"
self.mkcalendar(calendar_path)
event1 = get_file_content("event1.ics")
event2 = get_file_content("event1_modified.ics")
event_path = posixpath.join(calendar_path, "event.ics")
self.put(event_path, event1)
sync_token, responses = self._report_sync_token(calendar_path)
assert len(responses) == 1 and responses[event_path] == 200
self.put(event_path, event2)
self.put(event_path, event1)
sync_token, responses = self._report_sync_token(
calendar_path, sync_token)
if not self.full_sync_token_support and not sync_token:
return
assert len(responses) == 1 and responses[event_path] == 200
def test_report_sync_collection_move(self) -> None:
"""Test sync-collection report a moved item"""
calendar_path = "/calendar.ics/"
self.mkcalendar(calendar_path)
event = get_file_content("event1.ics")
event1_path = posixpath.join(calendar_path, "event1.ics")
event2_path = posixpath.join(calendar_path, "event2.ics")
self.put(event1_path, event)
sync_token, responses = self._report_sync_token(calendar_path)
assert len(responses) == 1 and responses[event1_path] == 200
self.request("MOVE", event1_path, check=201,
HTTP_DESTINATION="http://127.0.0.1/"+event2_path)
sync_token, responses = self._report_sync_token(
calendar_path, sync_token)
if not self.full_sync_token_support and not sync_token:
return
assert len(responses) == 2 and (responses[event1_path] == 404 and
responses[event2_path] == 200)
def test_report_sync_collection_move_undo(self) -> None:
"""Test sync-collection report with a moved and moved back item"""
calendar_path = "/calendar.ics/"
self.mkcalendar(calendar_path)
event = get_file_content("event1.ics")
event1_path = posixpath.join(calendar_path, "event1.ics")
event2_path = posixpath.join(calendar_path, "event2.ics")
self.put(event1_path, event)
sync_token, responses = self._report_sync_token(calendar_path)
assert len(responses) == 1 and responses[event1_path] == 200
self.request("MOVE", event1_path, check=201,
HTTP_DESTINATION="http://127.0.0.1/"+event2_path)
self.request("MOVE", event2_path, check=201,
HTTP_DESTINATION="http://127.0.0.1/"+event1_path)
sync_token, responses = self._report_sync_token(
calendar_path, sync_token)
if not self.full_sync_token_support and not sync_token:
return
assert len(responses) == 2 and (responses[event1_path] == 200 and
responses[event2_path] == 404)
def test_report_sync_collection_invalid_sync_token(self) -> None:
"""Test sync-collection report with an invalid sync token"""
calendar_path = "/calendar.ics/"
self.mkcalendar(calendar_path)
sync_token, _ = self._report_sync_token(
calendar_path, "http://radicale.org/ns/sync/INVALID")
assert not sync_token
def test_report_with_expand_property(self) -> None:
"""Test report with expand property"""
self.put("/calendar.ics/", get_file_content("event_daily_rrule.ics"))
req_body_without_expand = \
"""<?xml version="1.0" encoding="utf-8" ?>
<C:calendar-query xmlns:D="DAV:" xmlns:C="urn:ietf:params:xml:ns:caldav">
<D:prop>
<C:calendar-data>
</C:calendar-data>
</D:prop>
<C:filter>
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT">
<C:time-range start="20060103T000000Z" end="20060105T000000Z"/>
</C:comp-filter>
</C:comp-filter>
</C:filter>
</C:calendar-query>
"""
_, responses = self.report("/calendar.ics/", req_body_without_expand)
assert len(responses) == 1
response_without_expand = responses['/calendar.ics/event_daily_rrule.ics']
assert not isinstance(response_without_expand, int)
status, element = response_without_expand["C:calendar-data"]
assert status == 200 and element.text
assert "RRULE" in element.text
assert "BEGIN:VTIMEZONE" in element.text
assert "RECURRENCE-ID" not in element.text
uids: List[str] = []
for line in element.text.split("\n"):
if line.startswith("UID:"):
uid = line[len("UID:"):]
assert uid == "event_daily_rrule"
uids.append(uid)
assert len(uids) == 1
req_body_with_expand = \
"""<?xml version="1.0" encoding="utf-8" ?>
<C:calendar-query xmlns:D="DAV:" xmlns:C="urn:ietf:params:xml:ns:caldav">
<D:prop>
<C:calendar-data>
<C:expand start="20060103T000000Z" end="20060105T000000Z"/>
</C:calendar-data>
</D:prop>
<C:filter>
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT">
<C:time-range start="20060103T000000Z" end="20060105T000000Z"/>
</C:comp-filter>
</C:comp-filter>
</C:filter>
</C:calendar-query>
"""
_, responses = self.report("/calendar.ics/", req_body_with_expand)
assert len(responses) == 1
response_with_expand = responses['/calendar.ics/event_daily_rrule.ics']
assert not isinstance(response_with_expand, int)
status, element = response_with_expand["C:calendar-data"]
assert status == 200 and element.text
assert "RRULE" not in element.text
assert "BEGIN:VTIMEZONE" not in element.text
uids = []
recurrence_ids = []
for line in element.text.split("\n"):
if line.startswith("UID:"):
assert line == "UID:event_daily_rrule"
uids.append(line)
if line.startswith("RECURRENCE-ID:"):
assert line in ["RECURRENCE-ID:20060103T170000Z", "RECURRENCE-ID:20060104T170000Z"]
recurrence_ids.append(line)
if line.startswith("DTSTART:"):
assert line == "DTSTART:20060102T170000Z"
assert len(uids) == 2
assert len(set(recurrence_ids)) == 2
def test_report_with_expand_property_all_day_event(self) -> None:
"""Test report with expand property"""
self.put("/calendar.ics/", get_file_content("event_full_day_rrule.ics"))
req_body_without_expand = \
"""<?xml version="1.0" encoding="utf-8" ?>
<C:calendar-query xmlns:D="DAV:" xmlns:C="urn:ietf:params:xml:ns:caldav">
<D:prop>
<C:calendar-data>
</C:calendar-data>
</D:prop>
<C:filter>
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT">
<C:time-range start="20060103T000000Z" end="20060105T000000Z"/>
</C:comp-filter>
</C:comp-filter>
</C:filter>
</C:calendar-query>
"""
_, responses = self.report("/calendar.ics/", req_body_without_expand)
assert len(responses) == 1
response_without_expand = responses['/calendar.ics/event_full_day_rrule.ics']
assert not isinstance(response_without_expand, int)
status, element = response_without_expand["C:calendar-data"]
assert status == 200 and element.text
assert "RRULE" in element.text
assert "RECURRENCE-ID" not in element.text
uids: List[str] = []
for line in element.text.split("\n"):
if line.startswith("UID:"):
uid = line[len("UID:"):]
assert uid == "event_full_day_rrule"
uids.append(uid)
assert len(uids) == 1
req_body_with_expand = \
"""<?xml version="1.0" encoding="utf-8" ?>
<C:calendar-query xmlns:D="DAV:" xmlns:C="urn:ietf:params:xml:ns:caldav">
<D:prop>
<C:calendar-data>
<C:expand start="20060103T000000Z" end="20060105T000000Z"/>
</C:calendar-data>
</D:prop>
<C:filter>
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT">
<C:time-range start="20060103T000000Z" end="20060105T000000Z"/>
</C:comp-filter>
</C:comp-filter>
</C:filter>
</C:calendar-query>
"""
_, responses = self.report("/calendar.ics/", req_body_with_expand)
assert len(responses) == 1
response_with_expand = responses['/calendar.ics/event_full_day_rrule.ics']
assert not isinstance(response_with_expand, int)
status, element = response_with_expand["C:calendar-data"]
assert status == 200 and element.text
assert "RRULE" not in element.text
assert "BEGIN:VTIMEZONE" not in element.text
uids = []
recurrence_ids = []
for line in element.text.split("\n"):
if line.startswith("UID:"):
assert line == "UID:event_full_day_rrule"
uids.append(line)
if line.startswith("RECURRENCE-ID:"):
assert line in ["RECURRENCE-ID:20060103", "RECURRENCE-ID:20060104", "RECURRENCE-ID:20060105"]
recurrence_ids.append(line)
if line.startswith("DTSTART:"):
assert line == "DTSTART:20060102"
if line.startswith("DTEND:"):
assert line == "DTEND:20060103"
assert len(uids) == 3
assert len(set(recurrence_ids)) == 3
def test_propfind_sync_token(self) -> None:
"""Retrieve the sync-token with a propfind request"""
calendar_path = "/calendar.ics/"
self.mkcalendar(calendar_path)
propfind = get_file_content("allprop.xml")
_, responses = self.propfind(calendar_path, propfind)
response = responses[calendar_path]
assert not isinstance(response, int)
status, sync_token = response["D:sync-token"]
assert status == 200 and sync_token.text
event = get_file_content("event1.ics")
event_path = posixpath.join(calendar_path, "event.ics")
self.put(event_path, event)
_, responses = self.propfind(calendar_path, propfind)
response = responses[calendar_path]
assert not isinstance(response, int)
status, new_sync_token = response["D:sync-token"]
assert status == 200 and new_sync_token.text
assert sync_token.text != new_sync_token.text
def test_propfind_same_as_sync_collection_sync_token(self) -> None:
"""Compare sync-token property with sync-collection sync-token"""
calendar_path = "/calendar.ics/"
self.mkcalendar(calendar_path)
propfind = get_file_content("allprop.xml")
_, responses = self.propfind(calendar_path, propfind)
response = responses[calendar_path]
assert not isinstance(response, int)
status, sync_token = response["D:sync-token"]
assert status == 200 and sync_token.text
report_sync_token, _ = self._report_sync_token(calendar_path)
assert sync_token.text == report_sync_token
def test_calendar_getcontenttype(self) -> None:
"""Test report request on an item"""
self.mkcalendar("/test/")
for component in ("event", "todo", "journal"):
event = get_file_content("%s1.ics" % component)
status, _ = self.delete("/test/test.ics", check=None)
assert status in (200, 404)
self.put("/test/test.ics", event)
_, responses = self.report("/test/", """\
<?xml version="1.0" encoding="utf-8" ?>
<C:calendar-query xmlns:C="urn:ietf:params:xml:ns:caldav">
<D:prop xmlns:D="DAV:">
<D:getcontenttype />
</D:prop>
</C:calendar-query>""")
assert len(responses) == 1
response = responses["/test/test.ics"]
assert not isinstance(response, int) and len(response) == 1
status, prop = response["D:getcontenttype"]
assert status == 200 and prop.text == (
"text/calendar;charset=utf-8;component=V%s" %
component.upper())
def test_addressbook_getcontenttype(self) -> None:
"""Test report request on an item"""
self.create_addressbook("/test/")
contact = get_file_content("contact1.vcf")
self.put("/test/test.vcf", contact)
_, responses = self.report("/test/", """\
<?xml version="1.0" encoding="utf-8" ?>
<C:calendar-query xmlns:C="urn:ietf:params:xml:ns:caldav">
<D:prop xmlns:D="DAV:">
<D:getcontenttype />
</D:prop>
</C:calendar-query>""")
assert len(responses) == 1
response = responses["/test/test.vcf"]
assert not isinstance(response, int) and len(response) == 1
status, prop = response["D:getcontenttype"]
assert status == 200 and prop.text == "text/vcard;charset=utf-8"
def test_authorization(self) -> None:
_, responses = self.propfind("/", """\
<?xml version="1.0" encoding="utf-8"?>
<propfind xmlns="DAV:">
<prop>
<current-user-principal />
</prop>
</propfind>""", login="user:")
response = responses["/"]
assert not isinstance(response, int) and len(response) == 1
status, prop = response["D:current-user-principal"]
assert status == 200 and len(prop) == 1
element = prop.find(xmlutils.make_clark("D:href"))
assert element is not None and element.text == "/user/"
def test_authentication(self) -> None:
"""Test if server sends authentication request."""
self.configure({"auth": {"type": "htpasswd",
"htpasswd_filename": os.devnull,
"htpasswd_encryption": "plain"},
"rights": {"type": "owner_only"}})
status, headers, _ = self.request("MKCOL", "/user/")
assert status in (401, 403)
assert headers.get("WWW-Authenticate")
def test_principal_collection_creation(self) -> None:
"""Verify existence of the principal collection."""
self.propfind("/user/", login="user:")
def test_authentication_current_user_principal_hack(self) -> None:
"""Test if server sends authentication request when accessing
current-user-principal prop (workaround for DAVx5)."""
status, headers, _ = self.request("PROPFIND", "/", """\
<?xml version="1.0" encoding="utf-8"?>
<propfind xmlns="DAV:">
<prop>
<current-user-principal />
</prop>
</propfind>""")
assert status in (401, 403)
assert headers.get("WWW-Authenticate")
def test_existence_of_root_collections(self) -> None:
"""Verify that the root collection always exists."""
# Use PROPFIND because GET returns message
self.propfind("/")
# it should still exist after deletion
self.delete("/")
self.propfind("/")
def test_well_known(self) -> None:
for path in ["/.well-known/caldav", "/.well-known/carddav"]:
for path in [path, "/foo" + path]:
_, headers, _ = self.request("GET", path, check=301)
assert headers.get("Location") == "/"
def test_well_known_script_name(self) -> None:
for path in ["/.well-known/caldav", "/.well-known/carddav"]:
for path in [path, "/foo" + path]:
_, headers, _ = self.request(
"GET", path, check=301, SCRIPT_NAME="/radicale")
assert headers.get("Location") == "/radicale/"
def test_well_known_not_found(self) -> None:
for path in ["/.well-known", "/.well-known/", "/.well-known/foo"]:
for path in [path, "/foo" + path]:
self.get(path, check=404)
def test_custom_headers(self) -> None:
self.configure({"headers": {"test": "123"}})
# Test if header is set on success
_, headers, _ = self.request("OPTIONS", "/", check=200)
assert headers.get("test") == "123"
# Test if header is set on failure
_, headers, _ = self.request("GET", "/.well-known/foo", check=404)
assert headers.get("test") == "123"
def test_timezone_seconds(self) -> None:
"""Verify that timezones with minutes and seconds work."""
self.mkcalendar("/calendar.ics/")
event = get_file_content("event_timezone_seconds.ics")
self.put("/calendar.ics/event.ics", event)
| 85,907
|
Python
|
.py
| 1,823
| 38.528799
| 109
| 0.612781
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,212
|
__init__.py
|
Kozea_Radicale/radicale/tests/__init__.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2012-2017 Guillaume Ayoub
# Copyright © 2017-2018 Unrud <unrud@outlook.com>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
"""
Tests for Radicale.
"""
import base64
import logging
import shutil
import sys
import tempfile
import wsgiref.util
import xml.etree.ElementTree as ET
from io import BytesIO
from typing import Any, Dict, List, Optional, Tuple, Union
import defusedxml.ElementTree as DefusedET
import vobject
import radicale
from radicale import app, config, types, xmlutils
RESPONSES = Dict[str, Union[int, Dict[str, Tuple[int, ET.Element]], vobject.base.Component]]
# Enable debug output
radicale.log.logger.setLevel(logging.DEBUG)
class BaseTest:
"""Base class for tests."""
colpath: str
configuration: config.Configuration
application: app.Application
def setup_method(self) -> None:
self.configuration = config.load()
self.colpath = tempfile.mkdtemp()
self.configure({
"storage": {"filesystem_folder": self.colpath,
# Disable syncing to disk for better performance
"_filesystem_fsync": "False"},
# Set incorrect authentication delay to a short duration
"auth": {"delay": "0.001"}})
def configure(self, config_: types.CONFIG) -> None:
self.configuration.update(config_, "test", privileged=True)
self.application = app.Application(self.configuration)
def teardown_method(self) -> None:
shutil.rmtree(self.colpath)
def request(self, method: str, path: str, data: Optional[str] = None,
check: Optional[int] = None, **kwargs
) -> Tuple[int, Dict[str, str], str]:
"""Send a request."""
login = kwargs.pop("login", None)
if login is not None and not isinstance(login, str):
raise TypeError("login argument must be %r, not %r" %
(str, type(login)))
environ: Dict[str, Any] = {k.upper(): v for k, v in kwargs.items()}
for k, v in environ.items():
if not isinstance(v, str):
raise TypeError("type of %r is %r, expected %r" %
(k, type(v), str))
encoding: str = self.configuration.get("encoding", "request")
if login:
environ["HTTP_AUTHORIZATION"] = "Basic " + base64.b64encode(
login.encode(encoding)).decode()
environ["REQUEST_METHOD"] = method.upper()
environ["PATH_INFO"] = path
if data is not None:
data_bytes = data.encode(encoding)
environ["wsgi.input"] = BytesIO(data_bytes)
environ["CONTENT_LENGTH"] = str(len(data_bytes))
environ["wsgi.errors"] = sys.stderr
wsgiref.util.setup_testing_defaults(environ)
status = headers = None
def start_response(status_: str, headers_: List[Tuple[str, str]]
) -> None:
nonlocal status, headers
status = int(status_.split()[0])
headers = dict(headers_)
answers = list(self.application(environ, start_response))
assert status is not None and headers is not None
assert check is None or status == check, "%d != %d" % (status, check)
return status, headers, answers[0].decode() if answers else ""
@staticmethod
def parse_responses(text: str) -> RESPONSES:
xml = DefusedET.fromstring(text)
assert xml.tag == xmlutils.make_clark("D:multistatus")
path_responses: RESPONSES = {}
for response in xml.findall(xmlutils.make_clark("D:response")):
href = response.find(xmlutils.make_clark("D:href"))
assert href.text not in path_responses
prop_responses: Dict[str, Tuple[int, ET.Element]] = {}
for propstat in response.findall(
xmlutils.make_clark("D:propstat")):
status = propstat.find(xmlutils.make_clark("D:status"))
assert status.text.startswith("HTTP/1.1 ")
status_code = int(status.text.split(" ")[1])
for element in propstat.findall(
"./%s/*" % xmlutils.make_clark("D:prop")):
human_tag = xmlutils.make_human_tag(element.tag)
assert human_tag not in prop_responses
prop_responses[human_tag] = (status_code, element)
status = response.find(xmlutils.make_clark("D:status"))
if status is not None:
assert not prop_responses
assert status.text.startswith("HTTP/1.1 ")
status_code = int(status.text.split(" ")[1])
path_responses[href.text] = status_code
else:
path_responses[href.text] = prop_responses
return path_responses
@staticmethod
def parse_free_busy(text: str) -> RESPONSES:
path_responses: RESPONSES = {}
path_responses[""] = vobject.readOne(text)
return path_responses
def get(self, path: str, check: Optional[int] = 200, **kwargs
) -> Tuple[int, str]:
assert "data" not in kwargs
status, _, answer = self.request("GET", path, check=check, **kwargs)
return status, answer
def post(self, path: str, data: Optional[str] = None,
check: Optional[int] = 200, **kwargs) -> Tuple[int, str]:
status, _, answer = self.request("POST", path, data, check=check,
**kwargs)
return status, answer
def put(self, path: str, data: str, check: Optional[int] = 201,
**kwargs) -> Tuple[int, str]:
status, _, answer = self.request("PUT", path, data, check=check,
**kwargs)
return status, answer
def propfind(self, path: str, data: Optional[str] = None,
check: Optional[int] = 207, **kwargs
) -> Tuple[int, RESPONSES]:
status, _, answer = self.request("PROPFIND", path, data, check=check,
**kwargs)
if status < 200 or 300 <= status:
return status, {}
assert answer is not None
responses = self.parse_responses(answer)
if kwargs.get("HTTP_DEPTH", "0") == "0":
assert len(responses) == 1 and path in responses
return status, responses
def proppatch(self, path: str, data: Optional[str] = None,
check: Optional[int] = 207, **kwargs
) -> Tuple[int, RESPONSES]:
status, _, answer = self.request("PROPPATCH", path, data, check=check,
**kwargs)
if status < 200 or 300 <= status:
return status, {}
assert answer is not None
responses = self.parse_responses(answer)
assert len(responses) == 1 and path in responses
return status, responses
def report(self, path: str, data: str, check: Optional[int] = 207,
is_xml: Optional[bool] = True,
**kwargs) -> Tuple[int, RESPONSES]:
status, _, answer = self.request("REPORT", path, data, check=check,
**kwargs)
if status < 200 or 300 <= status:
return status, {}
assert answer is not None
if is_xml:
parsed = self.parse_responses(answer)
else:
parsed = self.parse_free_busy(answer)
return status, parsed
def delete(self, path: str, check: Optional[int] = 200, **kwargs
) -> Tuple[int, RESPONSES]:
assert "data" not in kwargs
status, _, answer = self.request("DELETE", path, check=check, **kwargs)
if status < 200 or 300 <= status:
return status, {}
assert answer is not None
responses = self.parse_responses(answer)
assert len(responses) == 1 and path in responses
return status, responses
def mkcalendar(self, path: str, data: Optional[str] = None,
check: Optional[int] = 201, **kwargs
) -> Tuple[int, str]:
status, _, answer = self.request("MKCALENDAR", path, data, check=check,
**kwargs)
return status, answer
def mkcol(self, path: str, data: Optional[str] = None,
check: Optional[int] = 201, **kwargs) -> int:
status, _, _ = self.request("MKCOL", path, data, check=check, **kwargs)
return status
def create_addressbook(self, path: str, check: Optional[int] = 201,
**kwargs) -> int:
assert "data" not in kwargs
return self.mkcol(path, """\
<?xml version="1.0" encoding="UTF-8" ?>
<create xmlns="DAV:" xmlns:CR="urn:ietf:params:xml:ns:carddav">
<set>
<prop>
<resourcetype>
<collection />
<CR:addressbook />
</resourcetype>
</prop>
</set>
</create>""", check=check, **kwargs)
| 9,688
|
Python
|
.py
| 208
| 35.971154
| 92
| 0.588677
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,213
|
test_storage.py
|
Kozea_Radicale/radicale/tests/test_storage.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2012-2017 Guillaume Ayoub
# Copyright © 2017-2019 Unrud <unrud@outlook.com>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
"""
Tests for storage backends.
"""
import os
import shutil
from typing import ClassVar, cast
import pytest
import radicale.tests.custom.storage_simple_sync
from radicale.tests import BaseTest
from radicale.tests.helpers import get_file_content
from radicale.tests.test_base import TestBaseRequests as _TestBaseRequests
class TestMultiFileSystem(BaseTest):
"""Tests for multifilesystem."""
def setup_method(self) -> None:
_TestBaseRequests.setup_method(cast(_TestBaseRequests, self))
self.configure({"storage": {"type": "multifilesystem"}})
def test_folder_creation(self) -> None:
"""Verify that the folder is created."""
folder = os.path.join(self.colpath, "subfolder")
self.configure({"storage": {"filesystem_folder": folder}})
assert os.path.isdir(folder)
def test_fsync(self) -> None:
"""Create a directory and file with syncing enabled."""
self.configure({"storage": {"_filesystem_fsync": "True"}})
self.mkcalendar("/calendar.ics/")
def test_hook(self) -> None:
"""Run hook."""
self.configure({"storage": {"hook": "mkdir %s" % os.path.join(
"collection-root", "created_by_hook")}})
self.mkcalendar("/calendar.ics/")
self.propfind("/created_by_hook/")
def test_hook_read_access(self) -> None:
"""Verify that hook is not run for read accesses."""
self.configure({"storage": {"hook": "mkdir %s" % os.path.join(
"collection-root", "created_by_hook")}})
self.propfind("/")
self.propfind("/created_by_hook/", check=404)
@pytest.mark.skipif(not shutil.which("flock"),
reason="flock command not found")
def test_hook_storage_locked(self) -> None:
"""Verify that the storage is locked when the hook runs."""
self.configure({"storage": {"hook": (
"flock -n .Radicale.lock || exit 0; exit 1")}})
self.mkcalendar("/calendar.ics/")
def test_hook_principal_collection_creation(self) -> None:
"""Verify that the hooks runs when a new user is created."""
self.configure({"storage": {"hook": "mkdir %s" % os.path.join(
"collection-root", "created_by_hook")}})
self.propfind("/", login="user:")
self.propfind("/created_by_hook/")
def test_hook_fail(self) -> None:
"""Verify that a request fails if the hook fails."""
self.configure({"storage": {"hook": "exit 1"}})
self.mkcalendar("/calendar.ics/", check=500)
def test_item_cache_rebuild(self) -> None:
"""Delete the item cache and verify that it is rebuild."""
self.mkcalendar("/calendar.ics/")
event = get_file_content("event1.ics")
path = "/calendar.ics/event1.ics"
self.put(path, event)
_, answer1 = self.get(path)
cache_folder = os.path.join(self.colpath, "collection-root",
"calendar.ics", ".Radicale.cache", "item")
assert os.path.exists(os.path.join(cache_folder, "event1.ics"))
shutil.rmtree(cache_folder)
_, answer2 = self.get(path)
assert answer1 == answer2
assert os.path.exists(os.path.join(cache_folder, "event1.ics"))
def test_put_whole_calendar_uids_used_as_file_names(self) -> None:
"""Test if UIDs are used as file names."""
_TestBaseRequests.test_put_whole_calendar(
cast(_TestBaseRequests, self))
for uid in ("todo", "event"):
_, answer = self.get("/calendar.ics/%s.ics" % uid)
assert "\r\nUID:%s\r\n" % uid in answer
def test_put_whole_calendar_random_uids_used_as_file_names(self) -> None:
"""Test if UIDs are used as file names."""
_TestBaseRequests.test_put_whole_calendar_without_uids(
cast(_TestBaseRequests, self))
_, answer = self.get("/calendar.ics")
assert answer is not None
uids = []
for line in answer.split("\r\n"):
if line.startswith("UID:"):
uids.append(line[len("UID:"):])
for uid in uids:
_, answer = self.get("/calendar.ics/%s.ics" % uid)
assert answer is not None
assert "\r\nUID:%s\r\n" % uid in answer
def test_put_whole_addressbook_uids_used_as_file_names(self) -> None:
"""Test if UIDs are used as file names."""
_TestBaseRequests.test_put_whole_addressbook(
cast(_TestBaseRequests, self))
for uid in ("contact1", "contact2"):
_, answer = self.get("/contacts.vcf/%s.vcf" % uid)
assert "\r\nUID:%s\r\n" % uid in answer
def test_put_whole_addressbook_random_uids_used_as_file_names(
self) -> None:
"""Test if UIDs are used as file names."""
_TestBaseRequests.test_put_whole_addressbook_without_uids(
cast(_TestBaseRequests, self))
_, answer = self.get("/contacts.vcf")
assert answer is not None
uids = []
for line in answer.split("\r\n"):
if line.startswith("UID:"):
uids.append(line[len("UID:"):])
for uid in uids:
_, answer = self.get("/contacts.vcf/%s.vcf" % uid)
assert answer is not None
assert "\r\nUID:%s\r\n" % uid in answer
class TestMultiFileSystemNoLock(BaseTest):
"""Tests for multifilesystem_nolock."""
def setup_method(self) -> None:
_TestBaseRequests.setup_method(cast(_TestBaseRequests, self))
self.configure({"storage": {"type": "multifilesystem_nolock"}})
test_add_event = _TestBaseRequests.test_add_event
test_item_cache_rebuild = TestMultiFileSystem.test_item_cache_rebuild
class TestCustomStorageSystem(BaseTest):
"""Test custom backend loading."""
def setup_method(self) -> None:
_TestBaseRequests.setup_method(cast(_TestBaseRequests, self))
self.configure({"storage": {
"type": "radicale.tests.custom.storage_simple_sync"}})
full_sync_token_support: ClassVar[bool] = False
test_add_event = _TestBaseRequests.test_add_event
_report_sync_token = _TestBaseRequests._report_sync_token
# include tests related to sync token
s: str = ""
for s in dir(_TestBaseRequests):
if s.startswith("test_") and "sync" in s.split("_"):
locals()[s] = getattr(_TestBaseRequests, s)
del s
class TestCustomStorageSystemCallable(BaseTest):
"""Test custom backend loading with ``callable``."""
def setup_method(self) -> None:
_TestBaseRequests.setup_method(cast(_TestBaseRequests, self))
self.configure({"storage": {
"type": radicale.tests.custom.storage_simple_sync.Storage}})
test_add_event = _TestBaseRequests.test_add_event
| 7,554
|
Python
|
.py
| 156
| 40.583333
| 78
| 0.641043
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,214
|
test_server.py
|
Kozea_Radicale/radicale/tests/test_server.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2018-2019 Unrud <unrud@outlook.com>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
"""
Test the internal server.
"""
import errno
import os
import socket
import ssl
import subprocess
import sys
import threading
import time
from configparser import RawConfigParser
from http.client import HTTPMessage
from typing import IO, Callable, Dict, Optional, Tuple, cast
from urllib import request
from urllib.error import HTTPError, URLError
import pytest
from radicale import config, server
from radicale.tests import BaseTest
from radicale.tests.helpers import configuration_to_dict, get_file_path
class DisabledRedirectHandler(request.HTTPRedirectHandler):
def redirect_request(
self, req: request.Request, fp: IO[bytes], code: int, msg: str,
headers: HTTPMessage, newurl: str) -> None:
return None
class TestBaseServerRequests(BaseTest):
"""Test the internal server."""
shutdown_socket: socket.socket
thread: threading.Thread
opener: request.OpenerDirector
def setup_method(self) -> None:
super().setup_method()
self.shutdown_socket, shutdown_socket_out = socket.socketpair()
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
# Find available port
sock.bind(("127.0.0.1", 0))
self.sockfamily = socket.AF_INET
self.sockname = sock.getsockname()
self.configure({"server": {"hosts": "%s:%d" % self.sockname},
# Enable debugging for new processes
"logging": {"level": "debug"}})
self.thread = threading.Thread(target=server.serve, args=(
self.configuration, shutdown_socket_out))
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
self.opener = request.build_opener(
request.HTTPSHandler(context=ssl_context),
DisabledRedirectHandler)
def teardown_method(self) -> None:
self.shutdown_socket.close()
try:
self.thread.join()
except RuntimeError: # Thread never started
pass
super().teardown_method()
def request(self, method: str, path: str, data: Optional[str] = None,
check: Optional[int] = None, **kwargs
) -> Tuple[int, Dict[str, str], str]:
"""Send a request."""
login = kwargs.pop("login", None)
if login is not None and not isinstance(login, str):
raise TypeError("login argument must be %r, not %r" %
(str, type(login)))
if login:
raise NotImplementedError
is_alive_fn: Optional[Callable[[], bool]] = kwargs.pop(
"is_alive_fn", None)
headers: Dict[str, str] = kwargs
for k, v in headers.items():
if not isinstance(v, str):
raise TypeError("type of %r is %r, expected %r" %
(k, type(v), str))
if is_alive_fn is None:
is_alive_fn = self.thread.is_alive
encoding: str = self.configuration.get("encoding", "request")
scheme = "https" if self.configuration.get("server", "ssl") else "http"
data_bytes = None
if data:
data_bytes = data.encode(encoding)
if self.sockfamily == socket.AF_INET6:
req_host = ("[%s]" % self.sockname[0])
else:
req_host = self.sockname[0]
req = request.Request(
"%s://%s:%d%s" % (scheme, req_host, self.sockname[1], path),
data=data_bytes, headers=headers, method=method)
while True:
assert is_alive_fn()
try:
with self.opener.open(req) as f:
return f.getcode(), dict(f.info()), f.read().decode()
except HTTPError as e:
assert check is None or e.code == check, "%d != %d" % (e.code,
check)
return e.code, dict(e.headers), e.read().decode()
except URLError as e:
if not isinstance(e.reason, ConnectionRefusedError):
raise
time.sleep(0.1)
def test_root(self) -> None:
self.thread.start()
self.get("/", check=302)
def test_ssl(self) -> None:
self.configure({"server": {"ssl": "True",
"certificate": get_file_path("cert.pem"),
"key": get_file_path("key.pem")}})
self.thread.start()
self.get("/", check=302)
def test_bind_fail(self) -> None:
for address_family, address in [(socket.AF_INET, "::1"),
(socket.AF_INET6, "127.0.0.1")]:
with socket.socket(address_family, socket.SOCK_STREAM) as sock:
if address_family == socket.AF_INET6:
# Only allow IPv6 connections to the IPv6 socket
sock.setsockopt(server.COMPAT_IPPROTO_IPV6,
socket.IPV6_V6ONLY, 1)
with pytest.raises(OSError) as exc_info:
sock.bind((address, 0))
# See ``radicale.server.serve``
assert (isinstance(exc_info.value, socket.gaierror) and
exc_info.value.errno in (
socket.EAI_NONAME, server.COMPAT_EAI_ADDRFAMILY,
server.COMPAT_EAI_NODATA) or
str(exc_info.value) == "address family mismatched" or
exc_info.value.errno in (
errno.EADDRNOTAVAIL, errno.EAFNOSUPPORT,
errno.EPROTONOSUPPORT))
def test_ipv6(self) -> None:
try:
with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as sock:
# Only allow IPv6 connections to the IPv6 socket
sock.setsockopt(
server.COMPAT_IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
# Find available port
sock.bind(("::1", 0))
self.sockfamily = socket.AF_INET6
self.sockname = sock.getsockname()[:2]
except OSError as e:
if e.errno in (errno.EADDRNOTAVAIL, errno.EAFNOSUPPORT,
errno.EPROTONOSUPPORT):
pytest.skip("IPv6 not supported")
raise
self.configure({"server": {"hosts": "[%s]:%d" % self.sockname}})
self.thread.start()
self.get("/", check=302)
def test_command_line_interface(self, with_bool_options=False) -> None:
self.configure({"headers": {"Test-Server": "test"}})
config_args = []
for section in self.configuration.sections():
if section.startswith("_"):
continue
for option in self.configuration.options(section):
if option.startswith("_"):
continue
long_name = "--%s-%s" % (section, option.replace("_", "-"))
if with_bool_options and config.DEFAULT_CONFIG_SCHEMA.get(
section, {}).get(option, {}).get("type") == bool:
if not cast(bool, self.configuration.get(section, option)):
long_name = "--no%s" % long_name[1:]
config_args.append(long_name)
else:
config_args.append(long_name)
raw_value = self.configuration.get_raw(section, option)
assert isinstance(raw_value, str)
config_args.append(raw_value)
config_args.append("--headers-Test-Header=test")
p = subprocess.Popen(
[sys.executable, "-m", "radicale"] + config_args,
env={**os.environ, "PYTHONPATH": os.pathsep.join(sys.path)})
try:
status, headers, _ = self.request(
"GET", "/", check=302, is_alive_fn=lambda: p.poll() is None)
for key in self.configuration.options("headers"):
assert headers.get(key) == self.configuration.get(
"headers", key)
finally:
p.terminate()
p.wait()
if sys.platform != "win32":
assert p.returncode == 0
def test_command_line_interface_with_bool_options(self) -> None:
self.test_command_line_interface(with_bool_options=True)
def test_wsgi_server(self) -> None:
config_path = os.path.join(self.colpath, "config")
parser = RawConfigParser()
parser.read_dict(configuration_to_dict(self.configuration))
with open(config_path, "w") as f:
parser.write(f)
env = os.environ.copy()
env["PYTHONPATH"] = os.pathsep.join(sys.path)
env["RADICALE_CONFIG"] = config_path
raw_server_hosts = self.configuration.get_raw("server", "hosts")
assert isinstance(raw_server_hosts, str)
p = subprocess.Popen([
sys.executable, "-m", "waitress", "--listen", raw_server_hosts,
"radicale:application"], env=env)
try:
self.get("/", is_alive_fn=lambda: p.poll() is None, check=302)
finally:
p.terminate()
p.wait()
| 9,963
|
Python
|
.py
| 217
| 34.110599
| 79
| 0.575159
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,215
|
test_config.py
|
Kozea_Radicale/radicale/tests/test_config.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2019 Unrud <unrud@outlook.com>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
import os
import shutil
import tempfile
from configparser import RawConfigParser
from typing import List, Tuple
import pytest
from radicale import config, types
from radicale.tests.helpers import configuration_to_dict
class TestConfig:
"""Test the configuration."""
colpath: str
def setup_method(self) -> None:
self.colpath = tempfile.mkdtemp()
def teardown_method(self) -> None:
shutil.rmtree(self.colpath)
def _write_config(self, config_dict: types.CONFIG, name: str) -> str:
parser = RawConfigParser()
parser.read_dict(config_dict)
config_path = os.path.join(self.colpath, name)
with open(config_path, "w") as f:
parser.write(f)
return config_path
def test_parse_compound_paths(self) -> None:
assert len(config.parse_compound_paths()) == 0
assert len(config.parse_compound_paths("")) == 0
assert len(config.parse_compound_paths(None, "")) == 0
assert len(config.parse_compound_paths("config", "")) == 0
assert len(config.parse_compound_paths("config", None)) == 1
assert len(config.parse_compound_paths(os.pathsep.join(["", ""]))) == 0
assert len(config.parse_compound_paths(os.pathsep.join([
"", "config", ""]))) == 1
paths = config.parse_compound_paths(os.pathsep.join([
"config1", "?config2", "config3"]))
assert len(paths) == 3
for i, (name, ignore_if_missing) in enumerate([
("config1", False), ("config2", True), ("config3", False)]):
assert os.path.isabs(paths[i][0])
assert os.path.basename(paths[i][0]) == name
assert paths[i][1] is ignore_if_missing
def test_load_empty(self) -> None:
config_path = self._write_config({}, "config")
config.load([(config_path, False)])
def test_load_full(self) -> None:
config_path = self._write_config(
configuration_to_dict(config.load()), "config")
config.load([(config_path, False)])
def test_load_missing(self) -> None:
config_path = os.path.join(self.colpath, "does_not_exist")
config.load([(config_path, True)])
with pytest.raises(Exception) as exc_info:
config.load([(config_path, False)])
e = exc_info.value
assert "Failed to load config file %r" % config_path in str(e)
def test_load_multiple(self) -> None:
config_path1 = self._write_config({
"server": {"hosts": "192.0.2.1:1111"}}, "config1")
config_path2 = self._write_config({
"server": {"max_connections": 1111}}, "config2")
configuration = config.load([(config_path1, False),
(config_path2, False)])
server_hosts: List[Tuple[str, int]] = configuration.get(
"server", "hosts")
assert len(server_hosts) == 1
assert server_hosts[0] == ("192.0.2.1", 1111)
assert configuration.get("server", "max_connections") == 1111
def test_copy(self) -> None:
configuration1 = config.load()
configuration1.update({"server": {"max_connections": "1111"}}, "test")
configuration2 = configuration1.copy()
configuration2.update({"server": {"max_connections": "1112"}}, "test")
assert configuration1.get("server", "max_connections") == 1111
assert configuration2.get("server", "max_connections") == 1112
def test_invalid_section(self) -> None:
configuration = config.load()
with pytest.raises(Exception) as exc_info:
configuration.update({"does_not_exist": {"x": "x"}}, "test")
e = exc_info.value
assert "Invalid section 'does_not_exist'" in str(e)
def test_invalid_option(self) -> None:
configuration = config.load()
with pytest.raises(Exception) as exc_info:
configuration.update({"server": {"x": "x"}}, "test")
e = exc_info.value
assert "Invalid option 'x'" in str(e)
assert "section 'server'" in str(e)
def test_invalid_option_plugin(self) -> None:
configuration = config.load()
with pytest.raises(Exception) as exc_info:
configuration.update({"auth": {"x": "x"}}, "test")
e = exc_info.value
assert "Invalid option 'x'" in str(e)
assert "section 'auth'" in str(e)
def test_invalid_value(self) -> None:
configuration = config.load()
with pytest.raises(Exception) as exc_info:
configuration.update({"server": {"max_connections": "x"}}, "test")
e = exc_info.value
assert "Invalid positive_int" in str(e)
assert "option 'max_connections" in str(e)
assert "section 'server" in str(e)
assert "'x'" in str(e)
def test_privileged(self) -> None:
configuration = config.load()
configuration.update({"server": {"_internal_server": "True"}},
"test", privileged=True)
with pytest.raises(Exception) as exc_info:
configuration.update(
{"server": {"_internal_server": "True"}}, "test")
e = exc_info.value
assert "Invalid option '_internal_server'" in str(e)
def test_plugin_schema(self) -> None:
plugin_schema: types.CONFIG_SCHEMA = {
"auth": {"new_option": {"value": "False", "type": bool}}}
configuration = config.load()
configuration.update({"auth": {"type": "new_plugin"}}, "test")
plugin_configuration = configuration.copy(plugin_schema)
assert plugin_configuration.get("auth", "new_option") is False
configuration.update({"auth": {"new_option": "True"}}, "test")
plugin_configuration = configuration.copy(plugin_schema)
assert plugin_configuration.get("auth", "new_option") is True
def test_plugin_schema_duplicate_option(self) -> None:
plugin_schema: types.CONFIG_SCHEMA = {
"auth": {"type": {"value": "False", "type": bool}}}
configuration = config.load()
with pytest.raises(Exception) as exc_info:
configuration.copy(plugin_schema)
e = exc_info.value
assert "option already exists in 'auth': 'type'" in str(e)
def test_plugin_schema_invalid(self) -> None:
plugin_schema: types.CONFIG_SCHEMA = {
"server": {"new_option": {"value": "False", "type": bool}}}
configuration = config.load()
with pytest.raises(Exception) as exc_info:
configuration.copy(plugin_schema)
e = exc_info.value
assert "not a plugin section: 'server" in str(e)
def test_plugin_schema_option_invalid(self) -> None:
plugin_schema: types.CONFIG_SCHEMA = {"auth": {}}
configuration = config.load()
configuration.update({"auth": {"type": "new_plugin",
"new_option": False}}, "test")
with pytest.raises(Exception) as exc_info:
configuration.copy(plugin_schema)
e = exc_info.value
assert "Invalid option 'new_option'" in str(e)
assert "section 'auth'" in str(e)
| 7,874
|
Python
|
.py
| 161
| 40.285714
| 79
| 0.621569
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,216
|
helpers.py
|
Kozea_Radicale/radicale/tests/helpers.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2008 Nicolas Kandel
# Copyright © 2008 Pascal Halter
# Copyright © 2008-2017 Guillaume Ayoub
# Copyright © 2017-2019 Unrud <unrud@outlook.com>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
"""
Radicale Helpers module.
This module offers helpers to use in tests.
"""
import os
from radicale import config, types
EXAMPLES_FOLDER: str = os.path.join(os.path.dirname(__file__), "static")
def get_file_path(file_name: str) -> str:
return os.path.join(EXAMPLES_FOLDER, file_name)
def get_file_content(file_name: str) -> str:
with open(get_file_path(file_name), encoding="utf-8") as f:
return f.read()
def configuration_to_dict(configuration: config.Configuration) -> types.CONFIG:
"""Convert configuration to a dict with raw values."""
return {section: {option: configuration.get_raw(section, option)
for option in configuration.options(section)
if not option.startswith("_")}
for section in configuration.sections()
if not section.startswith("_")}
| 1,711
|
Python
|
.py
| 37
| 42.324324
| 79
| 0.730398
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,217
|
rights.py
|
Kozea_Radicale/radicale/tests/custom/rights.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2017-2018 Unrud <unrud@outlook.com>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
"""
Custom rights management.
"""
from radicale import pathutils, rights
class Rights(rights.BaseRights):
def authorization(self, user: str, path: str) -> str:
sane_path = pathutils.strip_path(path)
if sane_path not in ("tmp", "other"):
return ""
return "RrWw"
| 1,050
|
Python
|
.py
| 25
| 39.16
| 70
| 0.740922
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,218
|
storage_simple_sync.py
|
Kozea_Radicale/radicale/tests/custom/storage_simple_sync.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2012-2017 Guillaume Ayoub
# Copyright © 2017-2018 Unrud <unrud@outlook.com>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
"""
Custom storage backend.
Copy of multifilesystem storage backend that uses the default ``sync``
implementation for testing.
"""
from radicale.storage import BaseCollection, multifilesystem
class Collection(multifilesystem.Collection):
sync = BaseCollection.sync
class Storage(multifilesystem.Storage):
_collection_class = Collection
| 1,138
|
Python
|
.py
| 26
| 42
| 70
| 0.793636
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,219
|
auth.py
|
Kozea_Radicale/radicale/tests/custom/auth.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2008 Nicolas Kandel
# Copyright © 2008 Pascal Halter
# Copyright © 2008-2017 Guillaume Ayoub
# Copyright © 2017-2018 Unrud <unrud@outlook.com>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
"""
Custom authentication.
Just check username for testing
"""
from radicale import auth
class Auth(auth.BaseAuth):
def login(self, login: str, password: str) -> str:
if login == "tmp":
return login
return ""
| 1,101
|
Python
|
.py
| 28
| 36.785714
| 70
| 0.752354
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,220
|
web.py
|
Kozea_Radicale/radicale/tests/custom/web.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2017-2018 Unrud <unrud@outlook.com>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
"""
Custom web plugin.
"""
from http import client
from radicale import httputils, types, web
class Web(web.BaseWeb):
def get(self, environ: types.WSGIEnviron, base_prefix: str, path: str,
user: str) -> types.WSGIResponse:
return client.OK, {"Content-Type": "text/plain"}, "custom"
def post(self, environ: types.WSGIEnviron, base_prefix: str, path: str,
user: str) -> types.WSGIResponse:
content = httputils.read_request_body(self.configuration, environ)
return client.OK, {"Content-Type": "text/plain"}, "echo:" + content
| 1,331
|
Python
|
.py
| 28
| 44.214286
| 75
| 0.733591
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,221
|
filter.py
|
Kozea_Radicale/radicale/item/filter.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2008 Nicolas Kandel
# Copyright © 2008 Pascal Halter
# Copyright © 2008-2015 Guillaume Ayoub
# Copyright © 2017-2018 Unrud <unrud@outlook.com>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
import math
import xml.etree.ElementTree as ET
from datetime import date, datetime, timedelta, timezone
from itertools import chain
from typing import (Callable, Iterable, Iterator, List, Optional, Sequence,
Tuple)
import vobject
from radicale import item, xmlutils
from radicale.log import logger
DAY: timedelta = timedelta(days=1)
SECOND: timedelta = timedelta(seconds=1)
DATETIME_MIN: datetime = datetime.min.replace(tzinfo=timezone.utc)
DATETIME_MAX: datetime = datetime.max.replace(tzinfo=timezone.utc)
TIMESTAMP_MIN: int = math.floor(DATETIME_MIN.timestamp())
TIMESTAMP_MAX: int = math.ceil(DATETIME_MAX.timestamp())
def date_to_datetime(d: date) -> datetime:
"""Transform any date to a UTC datetime.
If ``d`` is a datetime without timezone, return as UTC datetime. If ``d``
is already a datetime with timezone, return as is.
"""
if not isinstance(d, datetime):
d = datetime.combine(d, datetime.min.time())
if not d.tzinfo:
# NOTE: using vobject's UTC as it wasn't playing well with datetime's.
d = d.replace(tzinfo=vobject.icalendar.utc)
return d
def parse_time_range(time_filter: ET.Element) -> Tuple[datetime, datetime]:
start_text = time_filter.get("start")
end_text = time_filter.get("end")
if start_text:
start = datetime.strptime(
start_text, "%Y%m%dT%H%M%SZ").replace(
tzinfo=timezone.utc)
else:
start = DATETIME_MIN
if end_text:
end = datetime.strptime(
end_text, "%Y%m%dT%H%M%SZ").replace(
tzinfo=timezone.utc)
else:
end = DATETIME_MAX
return start, end
def time_range_timestamps(time_filter: ET.Element) -> Tuple[int, int]:
start, end = parse_time_range(time_filter)
return (math.floor(start.timestamp()), math.ceil(end.timestamp()))
def comp_match(item: "item.Item", filter_: ET.Element, level: int = 0) -> bool:
"""Check whether the ``item`` matches the comp ``filter_``.
If ``level`` is ``0``, the filter is applied on the
item's collection. Otherwise, it's applied on the item.
See rfc4791-9.7.1.
"""
# TODO: Filtering VALARM and VFREEBUSY is not implemented
# HACK: the filters are tested separately against all components
if level == 0:
tag = item.name
elif level == 1:
tag = item.component_name
else:
logger.warning(
"Filters with three levels of comp-filter are not supported")
return True
if not tag:
return False
name = filter_.get("name", "").upper()
if len(filter_) == 0:
# Point #1 of rfc4791-9.7.1
return name == tag
if len(filter_) == 1:
if filter_[0].tag == xmlutils.make_clark("C:is-not-defined"):
# Point #2 of rfc4791-9.7.1
return name != tag
if name != tag:
return False
if (level == 0 and name != "VCALENDAR" or
level == 1 and name not in ("VTODO", "VEVENT", "VJOURNAL")):
logger.warning("Filtering %s is not supported", name)
return True
# Point #3 and #4 of rfc4791-9.7.1
components = ([item.vobject_item] if level == 0
else list(getattr(item.vobject_item,
"%s_list" % tag.lower())))
for child in filter_:
if child.tag == xmlutils.make_clark("C:prop-filter"):
if not any(prop_match(comp, child, "C")
for comp in components):
return False
elif child.tag == xmlutils.make_clark("C:time-range"):
if not time_range_match(item.vobject_item, filter_[0], tag):
return False
elif child.tag == xmlutils.make_clark("C:comp-filter"):
if not comp_match(item, child, level=level + 1):
return False
else:
raise ValueError("Unexpected %r in comp-filter" % child.tag)
return True
def prop_match(vobject_item: vobject.base.Component,
filter_: ET.Element, ns: str) -> bool:
"""Check whether the ``item`` matches the prop ``filter_``.
See rfc4791-9.7.2 and rfc6352-10.5.1.
"""
name = filter_.get("name", "").lower()
if len(filter_) == 0:
# Point #1 of rfc4791-9.7.2
return name in vobject_item.contents
if len(filter_) == 1:
if filter_[0].tag == xmlutils.make_clark("%s:is-not-defined" % ns):
# Point #2 of rfc4791-9.7.2
return name not in vobject_item.contents
if name not in vobject_item.contents:
return False
# Point #3 and #4 of rfc4791-9.7.2
for child in filter_:
if ns == "C" and child.tag == xmlutils.make_clark("C:time-range"):
if not time_range_match(vobject_item, child, name):
return False
elif child.tag == xmlutils.make_clark("%s:text-match" % ns):
if not text_match(vobject_item, child, name, ns):
return False
elif child.tag == xmlutils.make_clark("%s:param-filter" % ns):
if not param_filter_match(vobject_item, child, name, ns):
return False
else:
raise ValueError("Unexpected %r in prop-filter" % child.tag)
return True
def time_range_match(vobject_item: vobject.base.Component,
filter_: ET.Element, child_name: str) -> bool:
"""Check whether the component/property ``child_name`` of
``vobject_item`` matches the time-range ``filter_``."""
if not filter_.get("start") and not filter_.get("end"):
return False
start, end = parse_time_range(filter_)
matched = False
def range_fn(range_start: datetime, range_end: datetime,
is_recurrence: bool) -> bool:
nonlocal matched
if start < range_end and range_start < end:
matched = True
return True
if end < range_start and not is_recurrence:
return True
return False
def infinity_fn(start: datetime) -> bool:
return False
visit_time_ranges(vobject_item, child_name, range_fn, infinity_fn)
return matched
def time_range_fill(vobject_item: vobject.base.Component,
filter_: ET.Element, child_name: str, n: int = 1
) -> List[Tuple[datetime, datetime]]:
"""Create a list of ``n`` occurances from the component/property ``child_name``
of ``vobject_item``."""
if not filter_.get("start") and not filter_.get("end"):
return []
start, end = parse_time_range(filter_)
ranges: List[Tuple[datetime, datetime]] = []
def range_fn(range_start: datetime, range_end: datetime,
is_recurrence: bool) -> bool:
nonlocal ranges
if start < range_end and range_start < end:
ranges.append((range_start, range_end))
if n > 0 and len(ranges) >= n:
return True
if end < range_start and not is_recurrence:
return True
return False
def infinity_fn(range_start: datetime) -> bool:
return False
visit_time_ranges(vobject_item, child_name, range_fn, infinity_fn)
return ranges
def visit_time_ranges(vobject_item: vobject.base.Component, child_name: str,
range_fn: Callable[[datetime, datetime, bool], bool],
infinity_fn: Callable[[datetime], bool]) -> None:
"""Visit all time ranges in the component/property ``child_name`` of
`vobject_item`` with visitors ``range_fn`` and ``infinity_fn``.
``range_fn`` gets called for every time_range with ``start`` and ``end``
datetimes and ``is_recurrence`` as arguments. If the function returns True,
the operation is cancelled.
``infinity_fn`` gets called when an infinite recurrence rule is detected
with ``start`` datetime as argument. If the function returns True, the
operation is cancelled.
See rfc4791-9.9.
"""
# HACK: According to rfc5545-3.8.4.4 a recurrence that is rescheduled
# with Recurrence ID affects the recurrence itself and all following
# recurrences too. This is not respected and client don't seem to bother
# either.
def getrruleset(child: vobject.base.Component, ignore: Sequence[date]
) -> Tuple[Iterable[date], bool]:
infinite = False
for rrule in child.contents.get("rrule", []):
if (";UNTIL=" not in rrule.value.upper() and
";COUNT=" not in rrule.value.upper()):
infinite = True
break
if infinite:
for dtstart in child.getrruleset(addRDate=True):
if dtstart in ignore:
continue
if infinity_fn(date_to_datetime(dtstart)):
return (), True
break
return filter(lambda dtstart: dtstart not in ignore,
child.getrruleset(addRDate=True)), False
def get_children(components: Iterable[vobject.base.Component]) -> Iterator[
Tuple[vobject.base.Component, bool, List[date]]]:
main = None
rec_main = None
recurrences = []
for comp in components:
if hasattr(comp, "recurrence_id") and comp.recurrence_id.value:
recurrences.append(comp.recurrence_id.value)
if comp.rruleset:
# Prevent possible infinite loop
raise ValueError("Overwritten recurrence with RRULESET")
rec_main = comp
yield comp, True, []
else:
if main is not None:
raise ValueError("Multiple main components")
main = comp
if main is None and len(recurrences) == 1:
main = rec_main
if main is None:
raise ValueError("Main component missing")
yield main, False, recurrences
# Comments give the lines in the tables of the specification
if child_name == "VEVENT":
for child, is_recurrence, recurrences in get_children(
vobject_item.vevent_list):
# TODO: check if there's a timezone
dtstart = child.dtstart.value
if child.rruleset:
dtstarts, infinity = getrruleset(child, recurrences)
if infinity:
return
else:
dtstarts = (dtstart,)
dtend = getattr(child, "dtend", None)
if dtend is not None:
dtend = dtend.value
original_duration = (dtend - dtstart).total_seconds()
dtend = date_to_datetime(dtend)
duration = getattr(child, "duration", None)
if duration is not None:
original_duration = duration = duration.value
for dtstart in dtstarts:
dtstart_is_datetime = isinstance(dtstart, datetime)
dtstart = date_to_datetime(dtstart)
if dtend is not None:
# Line 1
dtend = dtstart + timedelta(seconds=original_duration)
if range_fn(dtstart, dtend, is_recurrence):
return
elif duration is not None:
if original_duration is None:
original_duration = duration.seconds
if duration.seconds > 0:
# Line 2
if range_fn(dtstart, dtstart + duration,
is_recurrence):
return
else:
# Line 3
if range_fn(dtstart, dtstart + SECOND, is_recurrence):
return
elif dtstart_is_datetime:
# Line 4
if range_fn(dtstart, dtstart + SECOND, is_recurrence):
return
else:
# Line 5
if range_fn(dtstart, dtstart + DAY, is_recurrence):
return
elif child_name == "VTODO":
for child, is_recurrence, recurrences in get_children(
vobject_item.vtodo_list):
dtstart = getattr(child, "dtstart", None)
duration = getattr(child, "duration", None)
due = getattr(child, "due", None)
completed = getattr(child, "completed", None)
created = getattr(child, "created", None)
if dtstart is not None:
dtstart = date_to_datetime(dtstart.value)
if duration is not None:
duration = duration.value
if due is not None:
due = date_to_datetime(due.value)
if dtstart is not None:
original_duration = (due - dtstart).total_seconds()
if completed is not None:
completed = date_to_datetime(completed.value)
if created is not None:
created = date_to_datetime(created.value)
original_duration = (completed - created).total_seconds()
elif created is not None:
created = date_to_datetime(created.value)
if child.rruleset:
reference_dates, infinity = getrruleset(child, recurrences)
if infinity:
return
else:
if dtstart is not None:
reference_dates = (dtstart,)
elif due is not None:
reference_dates = (due,)
elif completed is not None:
reference_dates = (completed,)
elif created is not None:
reference_dates = (created,)
else:
# Line 8
if range_fn(DATETIME_MIN, DATETIME_MAX, is_recurrence):
return
reference_dates = ()
for reference_date in reference_dates:
reference_date = date_to_datetime(reference_date)
if dtstart is not None and duration is not None:
# Line 1
if range_fn(reference_date,
reference_date + duration + SECOND,
is_recurrence):
return
if range_fn(reference_date + duration - SECOND,
reference_date + duration + SECOND,
is_recurrence):
return
elif dtstart is not None and due is not None:
# Line 2
due = reference_date + timedelta(seconds=original_duration)
if (range_fn(reference_date, due, is_recurrence) or
range_fn(reference_date,
reference_date + SECOND, is_recurrence) or
range_fn(due - SECOND, due, is_recurrence) or
range_fn(due - SECOND, reference_date + SECOND,
is_recurrence)):
return
elif dtstart is not None:
if range_fn(reference_date, reference_date + SECOND,
is_recurrence):
return
elif due is not None:
# Line 4
if range_fn(reference_date - SECOND, reference_date,
is_recurrence):
return
elif completed is not None and created is not None:
# Line 5
completed = reference_date + timedelta(
seconds=original_duration)
if (range_fn(reference_date - SECOND,
reference_date + SECOND,
is_recurrence) or
range_fn(completed - SECOND, completed + SECOND,
is_recurrence) or
range_fn(reference_date - SECOND,
reference_date + SECOND, is_recurrence) or
range_fn(completed - SECOND, completed + SECOND,
is_recurrence)):
return
elif completed is not None:
# Line 6
if range_fn(reference_date - SECOND,
reference_date + SECOND, is_recurrence):
return
elif created is not None:
# Line 7
if range_fn(reference_date, DATETIME_MAX, is_recurrence):
return
elif child_name == "VJOURNAL":
for child, is_recurrence, recurrences in get_children(
vobject_item.vjournal_list):
dtstart = getattr(child, "dtstart", None)
if dtstart is not None:
dtstart = dtstart.value
if child.rruleset:
dtstarts, infinity = getrruleset(child, recurrences)
if infinity:
return
else:
dtstarts = (dtstart,)
for dtstart in dtstarts:
dtstart_is_datetime = isinstance(dtstart, datetime)
dtstart = date_to_datetime(dtstart)
if dtstart_is_datetime:
# Line 1
if range_fn(dtstart, dtstart + SECOND, is_recurrence):
return
else:
# Line 2
if range_fn(dtstart, dtstart + DAY, is_recurrence):
return
else:
# Match a property
child = getattr(vobject_item, child_name.lower())
if isinstance(child, date):
child_is_datetime = isinstance(child, datetime)
child = date_to_datetime(child)
if child_is_datetime:
range_fn(child, child + SECOND, False)
else:
range_fn(child, child + DAY, False)
def text_match(vobject_item: vobject.base.Component,
filter_: ET.Element, child_name: str, ns: str,
attrib_name: Optional[str] = None) -> bool:
"""Check whether the ``item`` matches the text-match ``filter_``.
See rfc4791-9.7.5.
"""
# TODO: collations are not supported, but the default ones needed
# for DAV servers are actually pretty useless. Texts are lowered to
# be case-insensitive, almost as the "i;ascii-casemap" value.
text = next(filter_.itertext()).lower()
match_type = "contains"
if ns == "CR":
match_type = filter_.get("match-type", match_type)
def match(value: str) -> bool:
value = value.lower()
if match_type == "equals":
return value == text
if match_type == "contains":
return text in value
if match_type == "starts-with":
return value.startswith(text)
if match_type == "ends-with":
return value.endswith(text)
raise ValueError("Unexpected text-match match-type: %r" % match_type)
children = getattr(vobject_item, "%s_list" % child_name, [])
if attrib_name is not None:
condition = any(
match(attrib) for child in children
for attrib in child.params.get(attrib_name, []))
else:
res = []
for child in children:
# Some filters such as CATEGORIES provide a list in child.value
if type(child.value) is list:
for value in child.value:
res.append(match(value))
else:
res.append(match(child.value))
condition = any(res)
if filter_.get("negate-condition") == "yes":
return not condition
return condition
def param_filter_match(vobject_item: vobject.base.Component,
filter_: ET.Element, parent_name: str, ns: str) -> bool:
"""Check whether the ``item`` matches the param-filter ``filter_``.
See rfc4791-9.7.3.
"""
name = filter_.get("name", "").upper()
children = getattr(vobject_item, "%s_list" % parent_name, [])
condition = any(name in child.params for child in children)
if len(filter_) > 0:
if filter_[0].tag == xmlutils.make_clark("%s:text-match" % ns):
return condition and text_match(
vobject_item, filter_[0], parent_name, ns, name)
if filter_[0].tag == xmlutils.make_clark("%s:is-not-defined" % ns):
return not condition
return condition
def simplify_prefilters(filters: Iterable[ET.Element], collection_tag: str
) -> Tuple[Optional[str], int, int, bool]:
"""Creates a simplified condition from ``filters``.
Returns a tuple (``tag``, ``start``, ``end``, ``simple``) where ``tag`` is
a string or None (match all) and ``start`` and ``end`` are POSIX
timestamps (as int). ``simple`` is a bool that indicates that ``filters``
and the simplified condition are identical.
"""
flat_filters = list(chain.from_iterable(filters))
simple = len(flat_filters) <= 1
for col_filter in flat_filters:
if collection_tag != "VCALENDAR":
simple = False
break
if (col_filter.tag != xmlutils.make_clark("C:comp-filter") or
col_filter.get("name", "").upper() != "VCALENDAR"):
simple = False
continue
simple &= len(col_filter) <= 1
for comp_filter in col_filter:
if comp_filter.tag != xmlutils.make_clark("C:comp-filter"):
simple = False
continue
tag = comp_filter.get("name", "").upper()
if comp_filter.find(
xmlutils.make_clark("C:is-not-defined")) is not None:
simple = False
continue
simple &= len(comp_filter) <= 1
for time_filter in comp_filter:
if tag not in ("VTODO", "VEVENT", "VJOURNAL"):
simple = False
break
if time_filter.tag != xmlutils.make_clark("C:time-range"):
simple = False
continue
start, end = time_range_timestamps(time_filter)
return tag, start, end, simple
return tag, TIMESTAMP_MIN, TIMESTAMP_MAX, simple
return None, TIMESTAMP_MIN, TIMESTAMP_MAX, simple
| 23,570
|
Python
|
.py
| 515
| 32.743689
| 83
| 0.557127
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,222
|
__init__.py
|
Kozea_Radicale/radicale/item/__init__.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2008 Nicolas Kandel
# Copyright © 2008 Pascal Halter
# Copyright © 2014 Jean-Marc Martins
# Copyright © 2008-2017 Guillaume Ayoub
# Copyright © 2017-2018 Unrud <unrud@outlook.com>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
"""
Module for address books and calendar entries (see ``Item``).
"""
import binascii
import contextlib
import math
import os
import re
from datetime import datetime, timedelta
from hashlib import sha256
from itertools import chain
from typing import (Any, Callable, List, MutableMapping, Optional, Sequence,
Tuple)
import vobject
from radicale import storage # noqa:F401
from radicale import pathutils
from radicale.item import filter as radicale_filter
from radicale.log import logger
def read_components(s: str) -> List[vobject.base.Component]:
"""Wrapper for vobject.readComponents"""
# Workaround for bug in InfCloud
# PHOTO is a data URI
s = re.sub(r"^(PHOTO(?:;[^:\r\n]*)?;ENCODING=b(?:;[^:\r\n]*)?:)"
r"data:[^;,\r\n]*;base64,", r"\1", s,
flags=re.MULTILINE | re.IGNORECASE)
# Workaround for bug with malformed ICS files containing control codes
# Filter out all control codes except those we expect to find:
# * 0x09 Horizontal Tab
# * 0x0A Line Feed
# * 0x0D Carriage Return
s = re.sub(r'[\x00-\x08\x0B\x0C\x0E-\x1F]', '', s)
return list(vobject.readComponents(s, allowQP=True))
def predict_tag_of_parent_collection(
vobject_items: Sequence[vobject.base.Component]) -> Optional[str]:
"""Returns the predicted tag or `None`"""
if len(vobject_items) != 1:
return None
if vobject_items[0].name == "VCALENDAR":
return "VCALENDAR"
if vobject_items[0].name in ("VCARD", "VLIST"):
return "VADDRESSBOOK"
return None
def predict_tag_of_whole_collection(
vobject_items: Sequence[vobject.base.Component],
fallback_tag: Optional[str] = None) -> Optional[str]:
"""Returns the predicted tag or `fallback_tag`"""
if vobject_items and vobject_items[0].name == "VCALENDAR":
return "VCALENDAR"
if vobject_items and vobject_items[0].name in ("VCARD", "VLIST"):
return "VADDRESSBOOK"
if not fallback_tag and not vobject_items:
# Maybe an empty address book
return "VADDRESSBOOK"
return fallback_tag
def check_and_sanitize_items(
vobject_items: List[vobject.base.Component],
is_collection: bool = False, tag: str = "") -> None:
"""Check vobject items for common errors and add missing UIDs.
Modifies the list `vobject_items`.
``is_collection`` indicates that vobject_item contains unrelated
components.
The ``tag`` of the collection.
"""
if tag and tag not in ("VCALENDAR", "VADDRESSBOOK", "VSUBSCRIBED"):
raise ValueError("Unsupported collection tag: %r" % tag)
if not is_collection and len(vobject_items) != 1:
raise ValueError("Item contains %d components" % len(vobject_items))
if tag == "VCALENDAR":
if len(vobject_items) > 1:
raise RuntimeError("VCALENDAR collection contains %d "
"components" % len(vobject_items))
vobject_item = vobject_items[0]
if vobject_item.name != "VCALENDAR":
raise ValueError("Item type %r not supported in %r "
"collection" % (vobject_item.name, tag))
component_uids = set()
for component in vobject_item.components():
if component.name in ("VTODO", "VEVENT", "VJOURNAL"):
component_uid = get_uid(component)
if component_uid:
component_uids.add(component_uid)
component_name = None
object_uid = None
object_uid_set = False
for component in vobject_item.components():
# https://tools.ietf.org/html/rfc4791#section-4.1
if component.name == "VTIMEZONE":
continue
if component_name is None or is_collection:
component_name = component.name
elif component_name != component.name:
raise ValueError("Multiple component types in object: %r, %r" %
(component_name, component.name))
if component_name not in ("VTODO", "VEVENT", "VJOURNAL"):
continue
component_uid = get_uid(component)
if not object_uid_set or is_collection:
object_uid_set = True
object_uid = component_uid
if not component_uid:
if not is_collection:
raise ValueError("%s component without UID in object" %
component_name)
component_uid = find_available_uid(
component_uids.__contains__)
component_uids.add(component_uid)
if hasattr(component, "uid"):
component.uid.value = component_uid
else:
component.add("UID").value = component_uid
elif not object_uid or not component_uid:
raise ValueError("Multiple %s components without UID in "
"object" % component_name)
elif object_uid != component_uid:
raise ValueError(
"Multiple %s components with different UIDs in object: "
"%r, %r" % (component_name, object_uid, component_uid))
# Workaround for bug in Lightning (Thunderbird)
# Rescheduling a single occurrence from a repeating event creates
# an event with DTEND and DURATION:PT0S
if (hasattr(component, "dtend") and
hasattr(component, "duration") and
component.duration.value == timedelta(0)):
logger.debug("Quirks: Removing zero duration from %s in "
"object %r", component_name, component_uid)
del component.duration
# Workaround for Evolution
# EXDATE has value DATE even if DTSTART/DTEND is DATE-TIME.
# The RFC is vaguely formulated on the issue.
# To resolve the issue convert EXDATE and RDATE to
# the same type as DTDSTART
if hasattr(component, "dtstart"):
ref_date = component.dtstart.value
ref_value_param = component.dtstart.params.get("VALUE")
for dates in chain(component.contents.get("exdate", []),
component.contents.get("rdate", [])):
if all(type(d) is type(ref_date) for d in dates.value):
continue
for i, date in enumerate(dates.value):
dates.value[i] = ref_date.replace(
date.year, date.month, date.day)
with contextlib.suppress(KeyError):
del dates.params["VALUE"]
if ref_value_param is not None:
dates.params["VALUE"] = ref_value_param
# vobject interprets recurrence rules on demand
try:
component.rruleset
except Exception as e:
raise ValueError("Invalid recurrence rules in %s in object %r"
% (component.name, component_uid)) from e
elif tag == "VADDRESSBOOK":
# https://tools.ietf.org/html/rfc6352#section-5.1
object_uids = set()
for vobject_item in vobject_items:
if vobject_item.name == "VCARD":
object_uid = get_uid(vobject_item)
if object_uid:
object_uids.add(object_uid)
for vobject_item in vobject_items:
if vobject_item.name == "VLIST":
# Custom format used by SOGo Connector to store lists of
# contacts
continue
if vobject_item.name != "VCARD":
raise ValueError("Item type %r not supported in %r "
"collection" % (vobject_item.name, tag))
object_uid = get_uid(vobject_item)
if not object_uid:
if not is_collection:
raise ValueError("%s object without UID" %
vobject_item.name)
object_uid = find_available_uid(object_uids.__contains__)
object_uids.add(object_uid)
if hasattr(vobject_item, "uid"):
vobject_item.uid.value = object_uid
else:
vobject_item.add("UID").value = object_uid
else:
for item in vobject_items:
raise ValueError("Item type %r not supported in %s collection" %
(item.name, repr(tag) if tag else "generic"))
def check_and_sanitize_props(props: MutableMapping[Any, Any]
) -> MutableMapping[str, str]:
"""Check collection properties for common errors.
Modifies the dict `props`.
"""
for k, v in list(props.items()): # Make copy to be able to delete items
if not isinstance(k, str):
raise ValueError("Key must be %r not %r: %r" % (
str.__name__, type(k).__name__, k))
if not isinstance(v, str):
if v is None:
del props[k]
continue
raise ValueError("Value of %r must be %r not %r: %r" % (
k, str.__name__, type(v).__name__, v))
if k == "tag":
if v not in ("", "VCALENDAR", "VADDRESSBOOK", "VSUBSCRIBED"):
raise ValueError("Unsupported collection tag: %r" % v)
return props
def find_available_uid(exists_fn: Callable[[str], bool], suffix: str = ""
) -> str:
"""Generate a pseudo-random UID"""
# Prevent infinite loop
for _ in range(1000):
r = binascii.hexlify(os.urandom(16)).decode("ascii")
name = "%s-%s-%s-%s-%s%s" % (
r[:8], r[8:12], r[12:16], r[16:20], r[20:], suffix)
if not exists_fn(name):
return name
# Something is wrong with the PRNG or `exists_fn`
raise RuntimeError("No available random UID found")
def get_etag(text: str) -> str:
"""Etag from collection or item.
Encoded as quoted-string (see RFC 2616).
"""
etag = sha256()
etag.update(text.encode())
return '"%s"' % etag.hexdigest()
def get_uid(vobject_component: vobject.base.Component) -> str:
"""UID value of an item if defined."""
return (vobject_component.uid.value or ""
if hasattr(vobject_component, "uid") else "")
def get_uid_from_object(vobject_item: vobject.base.Component) -> str:
"""UID value of an calendar/addressbook object."""
if vobject_item.name == "VCALENDAR":
if hasattr(vobject_item, "vevent"):
return get_uid(vobject_item.vevent)
if hasattr(vobject_item, "vjournal"):
return get_uid(vobject_item.vjournal)
if hasattr(vobject_item, "vtodo"):
return get_uid(vobject_item.vtodo)
elif vobject_item.name == "VCARD":
return get_uid(vobject_item)
return ""
def find_tag(vobject_item: vobject.base.Component) -> str:
"""Find component name from ``vobject_item``."""
if vobject_item.name == "VCALENDAR":
for component in vobject_item.components():
if component.name != "VTIMEZONE":
return component.name or ""
return ""
def find_time_range(vobject_item: vobject.base.Component, tag: str
) -> Tuple[int, int]:
"""Find enclosing time range from ``vobject item``.
``tag`` must be set to the return value of ``find_tag``.
Returns a tuple (``start``, ``end``) where ``start`` and ``end`` are
POSIX timestamps.
This is intended to be used for matching against simplified prefilters.
"""
if not tag:
return radicale_filter.TIMESTAMP_MIN, radicale_filter.TIMESTAMP_MAX
start = end = None
def range_fn(range_start: datetime, range_end: datetime,
is_recurrence: bool) -> bool:
nonlocal start, end
if start is None or range_start < start:
start = range_start
if end is None or end < range_end:
end = range_end
return False
def infinity_fn(range_start: datetime) -> bool:
nonlocal start, end
if start is None or range_start < start:
start = range_start
end = radicale_filter.DATETIME_MAX
return True
radicale_filter.visit_time_ranges(vobject_item, tag, range_fn, infinity_fn)
if start is None:
start = radicale_filter.DATETIME_MIN
if end is None:
end = radicale_filter.DATETIME_MAX
return math.floor(start.timestamp()), math.ceil(end.timestamp())
class Item:
"""Class for address book and calendar entries."""
collection: Optional["storage.BaseCollection"]
href: Optional[str]
last_modified: Optional[str]
_collection_path: str
_text: Optional[str]
_vobject_item: Optional[vobject.base.Component]
_etag: Optional[str]
_uid: Optional[str]
_name: Optional[str]
_component_name: Optional[str]
_time_range: Optional[Tuple[int, int]]
def __init__(self,
collection_path: Optional[str] = None,
collection: Optional["storage.BaseCollection"] = None,
vobject_item: Optional[vobject.base.Component] = None,
href: Optional[str] = None,
last_modified: Optional[str] = None,
text: Optional[str] = None,
etag: Optional[str] = None,
uid: Optional[str] = None,
name: Optional[str] = None,
component_name: Optional[str] = None,
time_range: Optional[Tuple[int, int]] = None):
"""Initialize an item.
``collection_path`` the path of the parent collection (optional if
``collection`` is set).
``collection`` the parent collection (optional).
``href`` the href of the item.
``last_modified`` the HTTP-datetime of when the item was modified.
``text`` the text representation of the item (optional if
``vobject_item`` is set).
``vobject_item`` the vobject item (optional if ``text`` is set).
``etag`` the etag of the item (optional). See ``get_etag``.
``uid`` the UID of the object (optional). See ``get_uid_from_object``.
``name`` the name of the item (optional). See ``vobject_item.name``.
``component_name`` the name of the primary component (optional).
See ``find_tag``.
``time_range`` the enclosing time range. See ``find_time_range``.
"""
if text is None and vobject_item is None:
raise ValueError(
"At least one of 'text' or 'vobject_item' must be set")
if collection_path is None:
if collection is None:
raise ValueError("At least one of 'collection_path' or "
"'collection' must be set")
collection_path = collection.path
assert collection_path == pathutils.strip_path(
pathutils.sanitize_path(collection_path))
self._collection_path = collection_path
self.collection = collection
self.href = href
self.last_modified = last_modified
self._text = text
self._vobject_item = vobject_item
self._etag = etag
self._uid = uid
self._name = name
self._component_name = component_name
self._time_range = time_range
def serialize(self) -> str:
if self._text is None:
try:
self._text = self.vobject_item.serialize()
except Exception as e:
raise RuntimeError("Failed to serialize item %r from %r: %s" %
(self.href, self._collection_path,
e)) from e
return self._text
@property
def vobject_item(self):
if self._vobject_item is None:
try:
self._vobject_item = vobject.readOne(self._text)
except Exception as e:
raise RuntimeError("Failed to parse item %r from %r: %s" %
(self.href, self._collection_path,
e)) from e
return self._vobject_item
@property
def etag(self) -> str:
"""Encoded as quoted-string (see RFC 2616)."""
if self._etag is None:
self._etag = get_etag(self.serialize())
return self._etag
@property
def uid(self) -> str:
if self._uid is None:
self._uid = get_uid_from_object(self.vobject_item)
return self._uid
@property
def name(self) -> str:
if self._name is None:
self._name = self.vobject_item.name or ""
return self._name
@property
def component_name(self) -> str:
if self._component_name is None:
self._component_name = find_tag(self.vobject_item)
return self._component_name
@property
def time_range(self) -> Tuple[int, int]:
if self._time_range is None:
self._time_range = find_time_range(
self.vobject_item, self.component_name)
return self._time_range
def prepare(self) -> None:
"""Fill cache with values."""
orig_vobject_item = self._vobject_item
self.serialize()
self.etag
self.uid
self.name
self.time_range
self.component_name
self._vobject_item = orig_vobject_item
| 18,557
|
Python
|
.py
| 411
| 34.155718
| 79
| 0.587363
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,223
|
ldap.py
|
Kozea_Radicale/radicale/auth/ldap.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright 2022 Peter Varkoly
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
"""
Authentication backend that checks credentials with a ldap server.
Following parameters are needed in the configuration:
ldap_uri The ldap url to the server like ldap://localhost
ldap_base The baseDN of the ldap server
ldap_reader_dn The DN of a ldap user with read access to get the user accounts
ldap_secret The password of the ldap_reader_dn
ldap_filter The search filter to find the user to authenticate by the username
ldap_load_groups If the groups of the authenticated users need to be loaded
Following parameters controls SSL connections:
ldap_use_ssl If the connection
ldap_ssl_verify_mode The certifikat verification mode. NONE, OPTIONAL, default is REQUIRED
ldap_ssl_ca_file
"""
import ssl
from radicale import auth, config
from radicale.log import logger
class Auth(auth.BaseAuth):
_ldap_uri: str
_ldap_base: str
_ldap_reader_dn: str
_ldap_secret: str
_ldap_filter: str
_ldap_load_groups: bool
_ldap_version: int = 3
_ldap_use_ssl: bool = False
_ldap_ssl_verify_mode: int = ssl.CERT_REQUIRED
_ldap_ssl_ca_file: str = ""
def __init__(self, configuration: config.Configuration) -> None:
super().__init__(configuration)
try:
import ldap3
self.ldap3 = ldap3
except ImportError:
try:
import ldap
self._ldap_version = 2
self.ldap = ldap
except ImportError as e:
raise RuntimeError("LDAP authentication requires the ldap3 module") from e
self._ldap_uri = configuration.get("auth", "ldap_uri")
self._ldap_base = configuration.get("auth", "ldap_base")
self._ldap_reader_dn = configuration.get("auth", "ldap_reader_dn")
self._ldap_load_groups = configuration.get("auth", "ldap_load_groups")
self._ldap_secret = configuration.get("auth", "ldap_secret")
self._ldap_filter = configuration.get("auth", "ldap_filter")
if self._ldap_version == 3:
self._ldap_use_ssl = configuration.get("auth", "ldap_use_ssl")
if self._ldap_use_ssl:
self._ldap_ssl_ca_file = configuration.get("auth", "ldap_ssl_ca_file")
tmp = configuration.get("auth", "ldap_ssl_verify_mode")
if tmp == "NONE":
self._ldap_ssl_verify_mode = ssl.CERT_NONE
elif tmp == "OPTIONAL":
self._ldap_ssl_verify_mode = ssl.CERT_OPTIONAL
def _login2(self, login: str, password: str) -> str:
try:
"""Bind as reader dn"""
logger.debug(f"_login2 {self._ldap_uri}, {self._ldap_reader_dn}")
conn = self.ldap.initialize(self._ldap_uri)
conn.protocol_version = 3
conn.set_option(self.ldap.OPT_REFERRALS, 0)
conn.simple_bind_s(self._ldap_reader_dn, self._ldap_secret)
"""Search for the dn of user to authenticate"""
res = conn.search_s(self._ldap_base, self.ldap.SCOPE_SUBTREE, filterstr=self._ldap_filter.format(login), attrlist=['memberOf'])
if len(res) == 0:
"""User could not be find"""
return ""
user_dn = res[0][0]
logger.debug("LDAP Auth user: %s", user_dn)
"""Close ldap connection"""
conn.unbind()
except Exception as e:
raise RuntimeError(f"Invalid ldap configuration:{e}")
try:
"""Bind as user to authenticate"""
conn = self.ldap.initialize(self._ldap_uri)
conn.protocol_version = 3
conn.set_option(self.ldap.OPT_REFERRALS, 0)
conn.simple_bind_s(user_dn, password)
tmp: list[str] = []
if self._ldap_load_groups:
tmp = []
for t in res[0][1]['memberOf']:
tmp.append(t.decode('utf-8').split(',')[0][3:])
self._ldap_groups = set(tmp)
logger.debug("LDAP Auth groups of user: %s", ",".join(self._ldap_groups))
conn.unbind()
return login
except self.ldap.INVALID_CREDENTIALS:
return ""
def _login3(self, login: str, password: str) -> str:
"""Connect the server"""
try:
logger.debug(f"_login3 {self._ldap_uri}, {self._ldap_reader_dn}")
if self._ldap_use_ssl:
tls = self.ldap3.Tls(validate=self._ldap_ssl_verify_mode)
if self._ldap_ssl_ca_file != "":
tls = self.ldap3.Tls(
validate=self._ldap_ssl_verify_mode,
ca_certs_file=self._ldap_ssl_ca_file
)
server = self.ldap3.Server(self._ldap_uri, use_ssl=True, tls=tls)
else:
server = self.ldap3.Server(self._ldap_uri)
conn = self.ldap3.Connection(server, self._ldap_reader_dn, password=self._ldap_secret)
except self.ldap3.core.exceptions.LDAPSocketOpenError:
raise RuntimeError("Unable to reach ldap server")
except Exception as e:
logger.debug(f"_login3 error 1 {e}")
pass
if not conn.bind():
logger.debug("_login3 can not bind")
raise RuntimeError("Unable to read from ldap server")
logger.debug(f"_login3 bind as {self._ldap_reader_dn}")
"""Search the user dn"""
conn.search(
search_base=self._ldap_base,
search_filter=self._ldap_filter.format(login),
search_scope=self.ldap3.SUBTREE,
attributes=['memberOf']
)
if len(conn.entries) == 0:
logger.debug(f"_login3 user '{login}' can not be find")
"""User could not be find"""
return ""
user_entry = conn.response[0]
conn.unbind()
user_dn = user_entry['dn']
logger.debug(f"_login3 found user_dn {user_dn}")
try:
"""Try to bind as the user itself"""
conn = self.ldap3.Connection(server, user_dn, password=password)
if not conn.bind():
logger.debug(f"_login3 user '{login}' can not be find")
return ""
if self._ldap_load_groups:
tmp = []
for g in user_entry['attributes']['memberOf']:
tmp.append(g.split(',')[0][3:])
self._ldap_groups = set(tmp)
conn.unbind()
logger.debug(f"_login3 {login} successfully authorized")
return login
except Exception as e:
logger.debug(f"_login3 error 2 {e}")
pass
return ""
def login(self, login: str, password: str) -> str:
"""Validate credentials.
In first step we make a connection to the ldap server with the ldap_reader_dn credential.
In next step the DN of the user to authenticate will be searched.
In the last step the authentication of the user will be proceeded.
"""
if self._ldap_version == 2:
return self._login2(login, password)
return self._login3(login, password)
| 7,905
|
Python
|
.py
| 172
| 35.593023
| 139
| 0.596943
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,224
|
htpasswd.py
|
Kozea_Radicale/radicale/auth/htpasswd.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2008 Nicolas Kandel
# Copyright © 2008 Pascal Halter
# Copyright © 2008-2017 Guillaume Ayoub
# Copyright © 2017-2019 Unrud <unrud@outlook.com>
# Copyright © 2024 Peter Bieringer <pb@bieringer.de>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
"""
Authentication backend that checks credentials with a htpasswd file.
Apache's htpasswd command (httpd.apache.org/docs/programs/htpasswd.html)
manages a file for storing user credentials. It can encrypt passwords using
different the methods BCRYPT/SHA256/SHA512 or MD5-APR1 (a version of MD5 modified for
Apache). MD5-APR1 provides medium security as of 2015. Only BCRYPT/SHA256/SHA512 can be
considered secure by current standards.
MD5-APR1-encrypted credentials can be written by all versions of htpasswd (it
is the default, in fact), whereas BCRYPT/SHA256/SHA512 requires htpasswd 2.4.x or newer.
The `is_authenticated(user, password)` function provided by this module
verifies the user-given credentials by parsing the htpasswd credential file
pointed to by the ``htpasswd_filename`` configuration value while assuming
the password encryption method specified via the ``htpasswd_encryption``
configuration value.
The following htpasswd password encryption methods are supported by Radicale
out-of-the-box:
- plain-text (created by htpasswd -p ...) -- INSECURE
- MD5-APR1 (htpasswd -m ...) -- htpasswd's default method, INSECURE
- SHA256 (htpasswd -2 ...)
- SHA512 (htpasswd -5 ...)
When bcrypt is installed:
- BCRYPT (htpasswd -B ...) -- Requires htpasswd 2.4.x
"""
import functools
import hmac
from typing import Any
from passlib.hash import apr_md5_crypt, sha256_crypt, sha512_crypt
from radicale import auth, config, logger
class Auth(auth.BaseAuth):
_filename: str
_encoding: str
def __init__(self, configuration: config.Configuration) -> None:
super().__init__(configuration)
self._filename = configuration.get("auth", "htpasswd_filename")
self._encoding = configuration.get("encoding", "stock")
encryption: str = configuration.get("auth", "htpasswd_encryption")
logger.info("auth htpasswd encryption is 'radicale.auth.htpasswd_encryption.%s'", encryption)
if encryption == "plain":
self._verify = self._plain
elif encryption == "md5":
self._verify = self._md5apr1
elif encryption == "sha256":
self._verify = self._sha256
elif encryption == "sha512":
self._verify = self._sha512
elif encryption == "bcrypt" or encryption == "autodetect":
try:
import bcrypt
except ImportError as e:
raise RuntimeError(
"The htpasswd encryption method 'bcrypt' or 'autodetect' requires "
"the bcrypt module.") from e
if encryption == "bcrypt":
self._verify = functools.partial(self._bcrypt, bcrypt)
else:
self._verify = self._autodetect
self._verify_bcrypt = functools.partial(self._bcrypt, bcrypt)
else:
raise RuntimeError("The htpasswd encryption method %r is not "
"supported." % encryption)
def _plain(self, hash_value: str, password: str) -> bool:
"""Check if ``hash_value`` and ``password`` match, plain method."""
return hmac.compare_digest(hash_value.encode(), password.encode())
def _bcrypt(self, bcrypt: Any, hash_value: str, password: str) -> bool:
return bcrypt.checkpw(password=password.encode('utf-8'), hashed_password=hash_value.encode())
def _md5apr1(self, hash_value: str, password: str) -> bool:
return apr_md5_crypt.verify(password, hash_value.strip())
def _sha256(self, hash_value: str, password: str) -> bool:
return sha256_crypt.verify(password, hash_value.strip())
def _sha512(self, hash_value: str, password: str) -> bool:
return sha512_crypt.verify(password, hash_value.strip())
def _autodetect(self, hash_value: str, password: str) -> bool:
if hash_value.startswith("$apr1$", 0, 6) and len(hash_value) == 37:
# MD5-APR1
return self._md5apr1(hash_value, password)
elif hash_value.startswith("$2y$", 0, 4) and len(hash_value) == 60:
# BCRYPT
return self._verify_bcrypt(hash_value, password)
elif hash_value.startswith("$5$", 0, 3) and len(hash_value) == 63:
# SHA-256
return self._sha256(hash_value, password)
elif hash_value.startswith("$6$", 0, 3) and len(hash_value) == 106:
# SHA-512
return self._sha512(hash_value, password)
else:
# assumed plaintext
return self._plain(hash_value, password)
def _login(self, login: str, password: str) -> str:
"""Validate credentials.
Iterate through htpasswd credential file until login matches, extract
hash (encrypted password) and check hash against password,
using the method specified in the Radicale config.
The content of the file is not cached because reading is generally a
very cheap operation, and it's useful to get live updates of the
htpasswd file.
"""
try:
with open(self._filename, encoding=self._encoding) as f:
for line in f:
line = line.rstrip("\n")
if line.lstrip() and not line.lstrip().startswith("#"):
try:
hash_login, hash_value = line.split(
":", maxsplit=1)
# Always compare both login and password to avoid
# timing attacks, see #591.
login_ok = hmac.compare_digest(
hash_login.encode(), login.encode())
password_ok = self._verify(hash_value, password)
if login_ok and password_ok:
return login
except ValueError as e:
raise RuntimeError("Invalid htpasswd file %r: %s" %
(self._filename, e)) from e
except OSError as e:
raise RuntimeError("Failed to load htpasswd file %r: %s" %
(self._filename, e)) from e
return ""
| 7,150
|
Python
|
.py
| 137
| 42.19708
| 101
| 0.634059
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,225
|
http_x_remote_user.py
|
Kozea_Radicale/radicale/auth/http_x_remote_user.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2008 Nicolas Kandel
# Copyright © 2008 Pascal Halter
# Copyright © 2008-2017 Guillaume Ayoub
# Copyright © 2017-2018 Unrud <unrud@outlook.com>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
"""
Authentication backend that takes the username from the
``HTTP_X_REMOTE_USER`` header.
It's intended for use with a reverse proxy. Be aware as this will be insecure
if the reverse proxy is not configured properly.
"""
from typing import Tuple, Union
from radicale import types
from radicale.auth import none
class Auth(none.Auth):
def get_external_login(self, environ: types.WSGIEnviron) -> Union[
Tuple[()], Tuple[str, str]]:
return environ.get("HTTP_X_REMOTE_USER", ""), ""
| 1,365
|
Python
|
.py
| 31
| 41.870968
| 77
| 0.762481
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,226
|
remote_user.py
|
Kozea_Radicale/radicale/auth/remote_user.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2008 Nicolas Kandel
# Copyright © 2008 Pascal Halter
# Copyright © 2008-2017 Guillaume Ayoub
# Copyright © 2017-2018 Unrud <unrud@outlook.com>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
"""
Authentication backend that takes the username from the ``REMOTE_USER``
WSGI environment variable.
It's intended for use with an external WSGI server.
"""
from typing import Tuple, Union
from radicale import types
from radicale.auth import none
class Auth(none.Auth):
def get_external_login(self, environ: types.WSGIEnviron
) -> Union[Tuple[()], Tuple[str, str]]:
return environ.get("REMOTE_USER", ""), ""
| 1,310
|
Python
|
.py
| 30
| 40.966667
| 71
| 0.753155
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,227
|
denyall.py
|
Kozea_Radicale/radicale/auth/denyall.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2024-2024 Peter Bieringer <pb@bieringer.de>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
"""
A dummy backend that denies any username and password.
Used as default for security reasons.
"""
from radicale import auth
class Auth(auth.BaseAuth):
def _login(self, login: str, password: str) -> str:
return ""
| 986
|
Python
|
.py
| 23
| 41.043478
| 70
| 0.766736
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,228
|
__init__.py
|
Kozea_Radicale/radicale/auth/__init__.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2008 Nicolas Kandel
# Copyright © 2008 Pascal Halter
# Copyright © 2008-2017 Guillaume Ayoub
# Copyright © 2017-2022 Unrud <unrud@outlook.com>
# Copyright © 2024-2024 Peter Bieringer <pb@bieringer.de>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
"""
Authentication module.
Authentication is based on usernames and passwords. If something more
advanced is needed an external WSGI server or reverse proxy can be used
(see ``remote_user`` or ``http_x_remote_user`` backend).
Take a look at the class ``BaseAuth`` if you want to implement your own.
"""
from typing import Sequence, Set, Tuple, Union
from radicale import config, types, utils
from radicale.log import logger
INTERNAL_TYPES: Sequence[str] = ("none", "remote_user", "http_x_remote_user",
"denyall",
"htpasswd",
"ldap")
def load(configuration: "config.Configuration") -> "BaseAuth":
"""Load the authentication module chosen in configuration."""
if configuration.get("auth", "type") == "none":
logger.warning("No user authentication is selected: '[auth] type=none' (insecure)")
if configuration.get("auth", "type") == "denyall":
logger.warning("All access is blocked by: '[auth] type=denyall'")
return utils.load_plugin(INTERNAL_TYPES, "auth", "Auth", BaseAuth,
configuration)
class BaseAuth:
_ldap_groups: Set[str] = set([])
_lc_username: bool
_strip_domain: bool
def __init__(self, configuration: "config.Configuration") -> None:
"""Initialize BaseAuth.
``configuration`` see ``radicale.config`` module.
The ``configuration`` must not change during the lifetime of
this object, it is kept as an internal reference.
"""
self.configuration = configuration
self._lc_username = configuration.get("auth", "lc_username")
self._strip_domain = configuration.get("auth", "strip_domain")
def get_external_login(self, environ: types.WSGIEnviron) -> Union[
Tuple[()], Tuple[str, str]]:
"""Optionally provide the login and password externally.
``environ`` a dict with the WSGI environment
If ``()`` is returned, Radicale handles HTTP authentication.
Otherwise, returns a tuple ``(login, password)``. For anonymous users
``login`` must be ``""``.
"""
return ()
def _login(self, login: str, password: str) -> str:
"""Check credentials and map login to internal user
``login`` the login name
``password`` the password
Returns the username or ``""`` for invalid credentials.
"""
raise NotImplementedError
def login(self, login: str, password: str) -> str:
if self._lc_username:
login = login.lower()
if self._strip_domain:
login = login.split('@')[0]
return self._login(login, password)
| 3,638
|
Python
|
.py
| 76
| 40.986842
| 91
| 0.66695
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,229
|
none.py
|
Kozea_Radicale/radicale/auth/none.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2008 Nicolas Kandel
# Copyright © 2008 Pascal Halter
# Copyright © 2008-2017 Guillaume Ayoub
# Copyright © 2017-2018 Unrud <unrud@outlook.com>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
"""
A dummy backend that accepts any username and password.
"""
from radicale import auth
class Auth(auth.BaseAuth):
def _login(self, login: str, password: str) -> str:
return login
| 1,053
|
Python
|
.py
| 25
| 40.24
| 70
| 0.768173
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,230
|
internal.py
|
Kozea_Radicale/radicale/web/internal.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2017-2018 Unrud <unrud@outlook.com>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
"""
The default web backend.
Features:
- Create and delete address books and calendars.
- Edit basic metadata of existing address books and calendars.
- Upload address books and calendars from files.
"""
from radicale import httputils, types, web
MIMETYPES = httputils.MIMETYPES # deprecated
FALLBACK_MIMETYPE = httputils.FALLBACK_MIMETYPE # deprecated
class Web(web.BaseWeb):
def get(self, environ: types.WSGIEnviron, base_prefix: str, path: str,
user: str) -> types.WSGIResponse:
return httputils.serve_resource("radicale.web", "internal_data",
base_prefix, path)
| 1,390
|
Python
|
.py
| 30
| 42.7
| 74
| 0.745374
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,231
|
__init__.py
|
Kozea_Radicale/radicale/web/__init__.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2017-2018 Unrud <unrud@outlook.com>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
"""
The web module for the website at ``/.web``.
Take a look at the class ``BaseWeb`` if you want to implement your own.
"""
from typing import Sequence
from radicale import config, httputils, types, utils
INTERNAL_TYPES: Sequence[str] = ("none", "internal")
def load(configuration: "config.Configuration") -> "BaseWeb":
"""Load the web module chosen in configuration."""
return utils.load_plugin(INTERNAL_TYPES, "web", "Web", BaseWeb,
configuration)
class BaseWeb:
configuration: "config.Configuration"
def __init__(self, configuration: "config.Configuration") -> None:
"""Initialize BaseWeb.
``configuration`` see ``radicale.config`` module.
The ``configuration`` must not change during the lifetime of
this object, it is kept as an internal reference.
"""
self.configuration = configuration
def get(self, environ: types.WSGIEnviron, base_prefix: str, path: str,
user: str) -> types.WSGIResponse:
"""GET request.
``base_prefix`` is sanitized and never ends with "/".
``path`` is sanitized and always starts with "/.web"
``user`` is empty for anonymous users.
"""
return httputils.METHOD_NOT_ALLOWED
def post(self, environ: types.WSGIEnviron, base_prefix: str, path: str,
user: str) -> types.WSGIResponse:
"""POST request.
``base_prefix`` is sanitized and never ends with "/".
``path`` is sanitized and always starts with "/.web"
``user`` is empty for anonymous users.
Use ``httputils.read*_request_body(self.configuration, environ)`` to
read the body.
"""
return httputils.METHOD_NOT_ALLOWED
| 2,500
|
Python
|
.py
| 53
| 41.207547
| 76
| 0.686623
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,232
|
none.py
|
Kozea_Radicale/radicale/web/none.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2017-2018 Unrud <unrud@outlook.com>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
"""
A dummy web backend that shows a simple message.
"""
from http import client
from radicale import httputils, pathutils, types, web
class Web(web.BaseWeb):
def get(self, environ: types.WSGIEnviron, base_prefix: str, path: str,
user: str) -> types.WSGIResponse:
assert path == "/.web" or path.startswith("/.web/")
assert pathutils.sanitize_path(path) == path
if path != "/.web":
return httputils.redirect(base_prefix + "/.web")
return client.OK, {"Content-Type": "text/plain"}, "Radicale works!"
| 1,308
|
Python
|
.py
| 28
| 43.321429
| 75
| 0.725844
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,233
|
post.py
|
Kozea_Radicale/radicale/app/post.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2008 Nicolas Kandel
# Copyright © 2008 Pascal Halter
# Copyright © 2008-2017 Guillaume Ayoub
# Copyright © 2017-2018 Unrud <unrud@outlook.com>
# Copyright © 2020 Tom Hacohen <tom@stosb.com>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
from radicale import httputils, types
from radicale.app.base import ApplicationBase
class ApplicationPartPost(ApplicationBase):
def do_POST(self, environ: types.WSGIEnviron, base_prefix: str,
path: str, user: str) -> types.WSGIResponse:
"""Manage POST request."""
if path == "/.web" or path.startswith("/.web/"):
return self._web.post(environ, base_prefix, path, user)
return httputils.METHOD_NOT_ALLOWED
| 1,366
|
Python
|
.py
| 28
| 45.464286
| 70
| 0.745673
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,234
|
report.py
|
Kozea_Radicale/radicale/app/report.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2008 Nicolas Kandel
# Copyright © 2008 Pascal Halter
# Copyright © 2008-2017 Guillaume Ayoub
# Copyright © 2017-2018 Unrud <unrud@outlook.com>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
import contextlib
import copy
import datetime
import posixpath
import socket
import xml.etree.ElementTree as ET
from http import client
from typing import (Any, Callable, Iterable, Iterator, List, Optional,
Sequence, Tuple, Union)
from urllib.parse import unquote, urlparse
import vobject
import vobject.base
from vobject.base import ContentLine
import radicale.item as radicale_item
from radicale import httputils, pathutils, storage, types, xmlutils
from radicale.app.base import Access, ApplicationBase
from radicale.item import filter as radicale_filter
from radicale.log import logger
def free_busy_report(base_prefix: str, path: str, xml_request: Optional[ET.Element],
collection: storage.BaseCollection, encoding: str,
unlock_storage_fn: Callable[[], None],
max_occurrence: int
) -> Tuple[int, Union[ET.Element, str]]:
# NOTE: this function returns both an Element and a string because
# free-busy reports are an edge-case on the return type according
# to the spec.
multistatus = ET.Element(xmlutils.make_clark("D:multistatus"))
if xml_request is None:
return client.MULTI_STATUS, multistatus
root = xml_request
if (root.tag == xmlutils.make_clark("C:free-busy-query") and
collection.tag != "VCALENDAR"):
logger.warning("Invalid REPORT method %r on %r requested",
xmlutils.make_human_tag(root.tag), path)
return client.FORBIDDEN, xmlutils.webdav_error("D:supported-report")
time_range_element = root.find(xmlutils.make_clark("C:time-range"))
assert isinstance(time_range_element, ET.Element)
# Build a single filter from the free busy query for retrieval
# TODO: filter for VFREEBUSY in additional to VEVENT but
# test_filter doesn't support that yet.
vevent_cf_element = ET.Element(xmlutils.make_clark("C:comp-filter"),
attrib={'name': 'VEVENT'})
vevent_cf_element.append(time_range_element)
vcalendar_cf_element = ET.Element(xmlutils.make_clark("C:comp-filter"),
attrib={'name': 'VCALENDAR'})
vcalendar_cf_element.append(vevent_cf_element)
filter_element = ET.Element(xmlutils.make_clark("C:filter"))
filter_element.append(vcalendar_cf_element)
filters = (filter_element,)
# First pull from storage
retrieved_items = list(collection.get_filtered(filters))
# !!! Don't access storage after this !!!
unlock_storage_fn()
cal = vobject.iCalendar()
collection_tag = collection.tag
while retrieved_items:
# Second filtering before evaluating occurrences.
# ``item.vobject_item`` might be accessed during filtering.
# Don't keep reference to ``item``, because VObject requires a lot of
# memory.
item, filter_matched = retrieved_items.pop(0)
if not filter_matched:
try:
if not test_filter(collection_tag, item, filter_element):
continue
except ValueError as e:
raise ValueError("Failed to free-busy filter item %r from %r: %s" %
(item.href, collection.path, e)) from e
except Exception as e:
raise RuntimeError("Failed to free-busy filter item %r from %r: %s" %
(item.href, collection.path, e)) from e
fbtype = None
if item.component_name == 'VEVENT':
transp = getattr(item.vobject_item.vevent, 'transp', None)
if transp and transp.value != 'OPAQUE':
continue
status = getattr(item.vobject_item.vevent, 'status', None)
if not status or status.value == 'CONFIRMED':
fbtype = 'BUSY'
elif status.value == 'CANCELLED':
fbtype = 'FREE'
elif status.value == 'TENTATIVE':
fbtype = 'BUSY-TENTATIVE'
else:
# Could do fbtype = status.value for x-name, I prefer this
fbtype = 'BUSY'
# TODO: coalesce overlapping periods
if max_occurrence > 0:
n_occurrences = max_occurrence+1
else:
n_occurrences = 0
occurrences = radicale_filter.time_range_fill(item.vobject_item,
time_range_element,
"VEVENT",
n=n_occurrences)
if len(occurrences) >= max_occurrence:
raise ValueError("FREEBUSY occurrences limit of {} hit"
.format(max_occurrence))
for occurrence in occurrences:
vfb = cal.add('vfreebusy')
vfb.add('dtstamp').value = item.vobject_item.vevent.dtstamp.value
vfb.add('dtstart').value, vfb.add('dtend').value = occurrence
if fbtype:
vfb.add('fbtype').value = fbtype
return (client.OK, cal.serialize())
def xml_report(base_prefix: str, path: str, xml_request: Optional[ET.Element],
collection: storage.BaseCollection, encoding: str,
unlock_storage_fn: Callable[[], None]
) -> Tuple[int, ET.Element]:
"""Read and answer REPORT requests that return XML.
Read rfc3253-3.6 for info.
"""
multistatus = ET.Element(xmlutils.make_clark("D:multistatus"))
if xml_request is None:
return client.MULTI_STATUS, multistatus
root = xml_request
if root.tag in (xmlutils.make_clark("D:principal-search-property-set"),
xmlutils.make_clark("D:principal-property-search"),
xmlutils.make_clark("D:expand-property")):
# We don't support searching for principals or indirect retrieving of
# properties, just return an empty result.
# InfCloud asks for expand-property reports (even if we don't announce
# support for them) and stops working if an error code is returned.
logger.warning("Unsupported REPORT method %r on %r requested",
xmlutils.make_human_tag(root.tag), path)
return client.MULTI_STATUS, multistatus
if (root.tag == xmlutils.make_clark("C:calendar-multiget") and
collection.tag != "VCALENDAR" or
root.tag == xmlutils.make_clark("CR:addressbook-multiget") and
collection.tag != "VADDRESSBOOK" or
root.tag == xmlutils.make_clark("D:sync-collection") and
collection.tag not in ("VADDRESSBOOK", "VCALENDAR")):
logger.warning("Invalid REPORT method %r on %r requested",
xmlutils.make_human_tag(root.tag), path)
return client.FORBIDDEN, xmlutils.webdav_error("D:supported-report")
props: Union[ET.Element, List] = root.find(xmlutils.make_clark("D:prop")) or []
hreferences: Iterable[str]
if root.tag in (
xmlutils.make_clark("C:calendar-multiget"),
xmlutils.make_clark("CR:addressbook-multiget")):
# Read rfc4791-7.9 for info
hreferences = set()
for href_element in root.findall(xmlutils.make_clark("D:href")):
temp_url_path = urlparse(href_element.text).path
assert isinstance(temp_url_path, str)
href_path = pathutils.sanitize_path(unquote(temp_url_path))
if (href_path + "/").startswith(base_prefix + "/"):
hreferences.add(href_path[len(base_prefix):])
else:
logger.warning("Skipping invalid path %r in REPORT request on "
"%r", href_path, path)
elif root.tag == xmlutils.make_clark("D:sync-collection"):
old_sync_token_element = root.find(
xmlutils.make_clark("D:sync-token"))
old_sync_token = ""
if old_sync_token_element is not None and old_sync_token_element.text:
old_sync_token = old_sync_token_element.text.strip()
logger.debug("Client provided sync token: %r", old_sync_token)
try:
sync_token, names = collection.sync(old_sync_token)
except ValueError as e:
# Invalid sync token
logger.warning("Client provided invalid sync token %r: %s",
old_sync_token, e, exc_info=True)
# client.CONFLICT doesn't work with some clients (e.g. InfCloud)
return (client.FORBIDDEN,
xmlutils.webdav_error("D:valid-sync-token"))
hreferences = (pathutils.unstrip_path(
posixpath.join(collection.path, n)) for n in names)
# Append current sync token to response
sync_token_element = ET.Element(xmlutils.make_clark("D:sync-token"))
sync_token_element.text = sync_token
multistatus.append(sync_token_element)
else:
hreferences = (path,)
filters = (
root.findall(xmlutils.make_clark("C:filter")) +
root.findall(xmlutils.make_clark("CR:filter")))
# Retrieve everything required for finishing the request.
retrieved_items = list(retrieve_items(
base_prefix, path, collection, hreferences, filters, multistatus))
collection_tag = collection.tag
# !!! Don't access storage after this !!!
unlock_storage_fn()
while retrieved_items:
# ``item.vobject_item`` might be accessed during filtering.
# Don't keep reference to ``item``, because VObject requires a lot of
# memory.
item, filters_matched = retrieved_items.pop(0)
if filters and not filters_matched:
try:
if not all(test_filter(collection_tag, item, filter_)
for filter_ in filters):
continue
except ValueError as e:
raise ValueError("Failed to filter item %r from %r: %s" %
(item.href, collection.path, e)) from e
except Exception as e:
raise RuntimeError("Failed to filter item %r from %r: %s" %
(item.href, collection.path, e)) from e
found_props = []
not_found_props = []
for prop in props:
element = ET.Element(prop.tag)
if prop.tag == xmlutils.make_clark("D:getetag"):
element.text = item.etag
found_props.append(element)
elif prop.tag == xmlutils.make_clark("D:getcontenttype"):
element.text = xmlutils.get_content_type(item, encoding)
found_props.append(element)
elif prop.tag in (
xmlutils.make_clark("C:calendar-data"),
xmlutils.make_clark("CR:address-data")):
element.text = item.serialize()
expand = prop.find(xmlutils.make_clark("C:expand"))
if expand is not None and item.component_name == 'VEVENT':
start = expand.get('start')
end = expand.get('end')
if (start is None) or (end is None):
return client.FORBIDDEN, \
xmlutils.webdav_error("C:expand")
start = datetime.datetime.strptime(
start, '%Y%m%dT%H%M%SZ'
).replace(tzinfo=datetime.timezone.utc)
end = datetime.datetime.strptime(
end, '%Y%m%dT%H%M%SZ'
).replace(tzinfo=datetime.timezone.utc)
expanded_element = _expand(
element, copy.copy(item), start, end)
found_props.append(expanded_element)
else:
found_props.append(element)
else:
not_found_props.append(element)
assert item.href
uri = pathutils.unstrip_path(
posixpath.join(collection.path, item.href))
multistatus.append(xml_item_response(
base_prefix, uri, found_props=found_props,
not_found_props=not_found_props, found_item=True))
return client.MULTI_STATUS, multistatus
def _expand(
element: ET.Element,
item: radicale_item.Item,
start: datetime.datetime,
end: datetime.datetime,
) -> ET.Element:
dt_format = '%Y%m%dT%H%M%SZ'
if type(item.vobject_item.vevent.dtstart.value) is datetime.date:
# If an event comes to us with a dt_start specified as a date
# then in the response we return the date, not datetime
dt_format = '%Y%m%d'
expanded_item, rruleset = _make_vobject_expanded_item(item, dt_format)
if rruleset:
recurrences = rruleset.between(start, end, inc=True)
expanded: vobject.base.Component = copy.copy(expanded_item.vobject_item)
is_expanded_filled: bool = False
for recurrence_dt in recurrences:
recurrence_utc = recurrence_dt.astimezone(datetime.timezone.utc)
vevent = copy.deepcopy(expanded.vevent)
vevent.recurrence_id = ContentLine(
name='RECURRENCE-ID',
value=recurrence_utc.strftime(dt_format), params={}
)
if is_expanded_filled is False:
expanded.vevent = vevent
is_expanded_filled = True
else:
expanded.add(vevent)
element.text = expanded.serialize()
else:
element.text = expanded_item.vobject_item.serialize()
return element
def _make_vobject_expanded_item(
item: radicale_item.Item,
dt_format: str,
) -> Tuple[radicale_item.Item, Optional[Any]]:
# https://www.rfc-editor.org/rfc/rfc4791#section-9.6.5
# The returned calendar components MUST NOT use recurrence
# properties (i.e., EXDATE, EXRULE, RDATE, and RRULE) and MUST NOT
# have reference to or include VTIMEZONE components. Date and local
# time with reference to time zone information MUST be converted
# into date with UTC time.
item = copy.copy(item)
vevent = item.vobject_item.vevent
if type(vevent.dtstart.value) is datetime.date:
start_utc = datetime.datetime.fromordinal(
vevent.dtstart.value.toordinal()
).replace(tzinfo=datetime.timezone.utc)
else:
start_utc = vevent.dtstart.value.astimezone(datetime.timezone.utc)
vevent.dtstart = ContentLine(name='DTSTART', value=start_utc, params=[])
dt_end = getattr(vevent, 'dtend', None)
if dt_end is not None:
if type(vevent.dtend.value) is datetime.date:
end_utc = datetime.datetime.fromordinal(
dt_end.value.toordinal()
).replace(tzinfo=datetime.timezone.utc)
else:
end_utc = dt_end.value.astimezone(datetime.timezone.utc)
vevent.dtend = ContentLine(name='DTEND', value=end_utc, params={})
rruleset = None
if hasattr(item.vobject_item.vevent, 'rrule'):
rruleset = vevent.getrruleset()
# There is something strange behaviour during serialization native datetime, so converting manually
vevent.dtstart.value = vevent.dtstart.value.strftime(dt_format)
if dt_end is not None:
vevent.dtend.value = vevent.dtend.value.strftime(dt_format)
timezones_to_remove = []
for component in item.vobject_item.components():
if component.name == 'VTIMEZONE':
timezones_to_remove.append(component)
for timezone in timezones_to_remove:
item.vobject_item.remove(timezone)
try:
delattr(item.vobject_item.vevent, 'rrule')
delattr(item.vobject_item.vevent, 'exdate')
delattr(item.vobject_item.vevent, 'exrule')
delattr(item.vobject_item.vevent, 'rdate')
except AttributeError:
pass
return item, rruleset
def xml_item_response(base_prefix: str, href: str,
found_props: Sequence[ET.Element] = (),
not_found_props: Sequence[ET.Element] = (),
found_item: bool = True) -> ET.Element:
response = ET.Element(xmlutils.make_clark("D:response"))
href_element = ET.Element(xmlutils.make_clark("D:href"))
href_element.text = xmlutils.make_href(base_prefix, href)
response.append(href_element)
if found_item:
for code, props in ((200, found_props), (404, not_found_props)):
if props:
propstat = ET.Element(xmlutils.make_clark("D:propstat"))
status = ET.Element(xmlutils.make_clark("D:status"))
status.text = xmlutils.make_response(code)
prop_element = ET.Element(xmlutils.make_clark("D:prop"))
for prop in props:
prop_element.append(prop)
propstat.append(prop_element)
propstat.append(status)
response.append(propstat)
else:
status = ET.Element(xmlutils.make_clark("D:status"))
status.text = xmlutils.make_response(404)
response.append(status)
return response
def retrieve_items(
base_prefix: str, path: str, collection: storage.BaseCollection,
hreferences: Iterable[str], filters: Sequence[ET.Element],
multistatus: ET.Element) -> Iterator[Tuple[radicale_item.Item, bool]]:
"""Retrieves all items that are referenced in ``hreferences`` from
``collection`` and adds 404 responses for missing and invalid items
to ``multistatus``."""
collection_requested = False
def get_names() -> Iterator[str]:
"""Extracts all names from references in ``hreferences`` and adds
404 responses for invalid references to ``multistatus``.
If the whole collections is referenced ``collection_requested``
gets set to ``True``."""
nonlocal collection_requested
for hreference in hreferences:
try:
name = pathutils.name_from_path(hreference, collection)
except ValueError as e:
logger.warning("Skipping invalid path %r in REPORT request on "
"%r: %s", hreference, path, e)
response = xml_item_response(base_prefix, hreference,
found_item=False)
multistatus.append(response)
continue
if name:
# Reference is an item
yield name
else:
# Reference is a collection
collection_requested = True
for name, item in collection.get_multi(get_names()):
if not item:
uri = pathutils.unstrip_path(posixpath.join(collection.path, name))
response = xml_item_response(base_prefix, uri, found_item=False)
multistatus.append(response)
else:
yield item, False
if collection_requested:
yield from collection.get_filtered(filters)
def test_filter(collection_tag: str, item: radicale_item.Item,
filter_: ET.Element) -> bool:
"""Match an item against a filter."""
if (collection_tag == "VCALENDAR" and
filter_.tag != xmlutils.make_clark("C:%s" % filter_)):
if len(filter_) == 0:
return True
if len(filter_) > 1:
raise ValueError("Filter with %d children" % len(filter_))
if filter_[0].tag != xmlutils.make_clark("C:comp-filter"):
raise ValueError("Unexpected %r in filter" % filter_[0].tag)
return radicale_filter.comp_match(item, filter_[0])
if (collection_tag == "VADDRESSBOOK" and
filter_.tag != xmlutils.make_clark("CR:%s" % filter_)):
for child in filter_:
if child.tag != xmlutils.make_clark("CR:prop-filter"):
raise ValueError("Unexpected %r in filter" % child.tag)
test = filter_.get("test", "anyof")
if test == "anyof":
return any(radicale_filter.prop_match(item.vobject_item, f, "CR")
for f in filter_)
if test == "allof":
return all(radicale_filter.prop_match(item.vobject_item, f, "CR")
for f in filter_)
raise ValueError("Unsupported filter test: %r" % test)
raise ValueError("Unsupported filter %r for %r" %
(filter_.tag, collection_tag))
class ApplicationPartReport(ApplicationBase):
def do_REPORT(self, environ: types.WSGIEnviron, base_prefix: str,
path: str, user: str) -> types.WSGIResponse:
"""Manage REPORT request."""
access = Access(self._rights, user, path)
if not access.check("r"):
return httputils.NOT_ALLOWED
try:
xml_content = self._read_xml_request_body(environ)
except RuntimeError as e:
logger.warning("Bad REPORT request on %r: %s", path, e,
exc_info=True)
return httputils.BAD_REQUEST
except socket.timeout:
logger.debug("Client timed out", exc_info=True)
return httputils.REQUEST_TIMEOUT
with contextlib.ExitStack() as lock_stack:
lock_stack.enter_context(self._storage.acquire_lock("r", user))
item = next(iter(self._storage.discover(path)), None)
if not item:
return httputils.NOT_FOUND
if not access.check("r", item):
return httputils.NOT_ALLOWED
if isinstance(item, storage.BaseCollection):
collection = item
else:
assert item.collection is not None
collection = item.collection
if xml_content is not None and \
xml_content.tag == xmlutils.make_clark("C:free-busy-query"):
max_occurrence = self.configuration.get("reporting", "max_freebusy_occurrence")
try:
status, body = free_busy_report(
base_prefix, path, xml_content, collection, self._encoding,
lock_stack.close, max_occurrence)
except ValueError as e:
logger.warning(
"Bad REPORT request on %r: %s", path, e, exc_info=True)
return httputils.BAD_REQUEST
headers = {"Content-Type": "text/calendar; charset=%s" % self._encoding}
return status, headers, str(body)
else:
try:
status, xml_answer = xml_report(
base_prefix, path, xml_content, collection, self._encoding,
lock_stack.close)
except ValueError as e:
logger.warning(
"Bad REPORT request on %r: %s", path, e, exc_info=True)
return httputils.BAD_REQUEST
headers = {"Content-Type": "text/xml; charset=%s" % self._encoding}
return status, headers, self._xml_response(xml_answer)
| 23,914
|
Python
|
.py
| 483
| 37.677019
| 103
| 0.604701
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,235
|
options.py
|
Kozea_Radicale/radicale/app/options.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2008 Nicolas Kandel
# Copyright © 2008 Pascal Halter
# Copyright © 2008-2017 Guillaume Ayoub
# Copyright © 2017-2018 Unrud <unrud@outlook.com>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
from http import client
from radicale import httputils, types
from radicale.app.base import ApplicationBase
class ApplicationPartOptions(ApplicationBase):
def do_OPTIONS(self, environ: types.WSGIEnviron, base_prefix: str,
path: str, user: str) -> types.WSGIResponse:
"""Manage OPTIONS request."""
headers = {
"Allow": ", ".join(
name[3:] for name in dir(self) if name.startswith("do_")),
"DAV": httputils.DAV_HEADERS}
return client.OK, headers, None
| 1,395
|
Python
|
.py
| 30
| 42.3
| 74
| 0.727876
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,236
|
mkcalendar.py
|
Kozea_Radicale/radicale/app/mkcalendar.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2008 Nicolas Kandel
# Copyright © 2008 Pascal Halter
# Copyright © 2008-2017 Guillaume Ayoub
# Copyright © 2017-2018 Unrud <unrud@outlook.com>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
import posixpath
import socket
from http import client
import radicale.item as radicale_item
from radicale import httputils, pathutils, storage, types, xmlutils
from radicale.app.base import ApplicationBase
from radicale.log import logger
class ApplicationPartMkcalendar(ApplicationBase):
def do_MKCALENDAR(self, environ: types.WSGIEnviron, base_prefix: str,
path: str, user: str) -> types.WSGIResponse:
"""Manage MKCALENDAR request."""
if "w" not in self._rights.authorization(user, path):
return httputils.NOT_ALLOWED
try:
xml_content = self._read_xml_request_body(environ)
except RuntimeError as e:
logger.warning(
"Bad MKCALENDAR request on %r: %s", path, e, exc_info=True)
return httputils.BAD_REQUEST
except socket.timeout:
logger.debug("Client timed out", exc_info=True)
return httputils.REQUEST_TIMEOUT
# Prepare before locking
props_with_remove = xmlutils.props_from_request(xml_content)
props_with_remove["tag"] = "VCALENDAR"
try:
props = radicale_item.check_and_sanitize_props(props_with_remove)
except ValueError as e:
logger.warning(
"Bad MKCALENDAR request on %r: %s", path, e, exc_info=True)
return httputils.BAD_REQUEST
# TODO: use this?
# timezone = props.get("C:calendar-timezone")
with self._storage.acquire_lock("w", user):
item = next(iter(self._storage.discover(path)), None)
if item:
return self._webdav_error_response(
client.CONFLICT, "D:resource-must-be-null")
parent_path = pathutils.unstrip_path(
posixpath.dirname(pathutils.strip_path(path)), True)
parent_item = next(iter(self._storage.discover(parent_path)), None)
if not parent_item:
return httputils.CONFLICT
if (not isinstance(parent_item, storage.BaseCollection) or
parent_item.tag):
return httputils.FORBIDDEN
try:
self._storage.create_collection(path, props=props)
except ValueError as e:
logger.warning(
"Bad MKCALENDAR request on %r: %s", path, e, exc_info=True)
return httputils.BAD_REQUEST
return client.CREATED, {}, None
| 3,321
|
Python
|
.py
| 71
| 37.901408
| 79
| 0.658439
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,237
|
delete.py
|
Kozea_Radicale/radicale/app/delete.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2008 Nicolas Kandel
# Copyright © 2008 Pascal Halter
# Copyright © 2008-2017 Guillaume Ayoub
# Copyright © 2017-2018 Unrud <unrud@outlook.com>
# Copyright © 2024-2024 Peter Bieringer <pb@bieringer.de>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
import xml.etree.ElementTree as ET
from http import client
from typing import Optional
from radicale import httputils, storage, types, xmlutils
from radicale.app.base import Access, ApplicationBase
from radicale.hook import HookNotificationItem, HookNotificationItemTypes
from radicale.log import logger
def xml_delete(base_prefix: str, path: str, collection: storage.BaseCollection,
item_href: Optional[str] = None) -> ET.Element:
"""Read and answer DELETE requests.
Read rfc4918-9.6 for info.
"""
collection.delete(item_href)
multistatus = ET.Element(xmlutils.make_clark("D:multistatus"))
response = ET.Element(xmlutils.make_clark("D:response"))
multistatus.append(response)
href_element = ET.Element(xmlutils.make_clark("D:href"))
href_element.text = xmlutils.make_href(base_prefix, path)
response.append(href_element)
status = ET.Element(xmlutils.make_clark("D:status"))
status.text = xmlutils.make_response(200)
response.append(status)
return multistatus
class ApplicationPartDelete(ApplicationBase):
def do_DELETE(self, environ: types.WSGIEnviron, base_prefix: str,
path: str, user: str) -> types.WSGIResponse:
"""Manage DELETE request."""
access = Access(self._rights, user, path)
if not access.check("w"):
return httputils.NOT_ALLOWED
with self._storage.acquire_lock("w", user):
item = next(iter(self._storage.discover(path)), None)
if not item:
return httputils.NOT_FOUND
if not access.check("w", item):
return httputils.NOT_ALLOWED
if_match = environ.get("HTTP_IF_MATCH", "*")
if if_match not in ("*", item.etag):
# ETag precondition not verified, do not delete item
return httputils.PRECONDITION_FAILED
hook_notification_item_list = []
if isinstance(item, storage.BaseCollection):
if self._permit_delete_collection:
if access.check("d", item):
logger.info("delete of collection is permitted by config/option [rights] permit_delete_collection but explicit forbidden by permission 'd': %s", path)
return httputils.NOT_ALLOWED
else:
if not access.check("D", item):
logger.info("delete of collection is prevented by config/option [rights] permit_delete_collection and not explicit allowed by permission 'D': %s", path)
return httputils.NOT_ALLOWED
for i in item.get_all():
hook_notification_item_list.append(
HookNotificationItem(
HookNotificationItemTypes.DELETE,
access.path,
i.uid
)
)
xml_answer = xml_delete(base_prefix, path, item)
else:
assert item.collection is not None
assert item.href is not None
hook_notification_item_list.append(
HookNotificationItem(
HookNotificationItemTypes.DELETE,
access.path,
item.uid
)
)
xml_answer = xml_delete(
base_prefix, path, item.collection, item.href)
for notification_item in hook_notification_item_list:
self._hook.notify(notification_item)
headers = {"Content-Type": "text/xml; charset=%s" % self._encoding}
return client.OK, headers, self._xml_response(xml_answer)
| 4,679
|
Python
|
.py
| 94
| 38.659574
| 176
| 0.631487
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,238
|
move.py
|
Kozea_Radicale/radicale/app/move.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2008 Nicolas Kandel
# Copyright © 2008 Pascal Halter
# Copyright © 2008-2017 Guillaume Ayoub
# Copyright © 2017-2018 Unrud <unrud@outlook.com>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
import posixpath
import re
from http import client
from urllib.parse import urlparse
from radicale import httputils, pathutils, storage, types
from radicale.app.base import Access, ApplicationBase
from radicale.log import logger
def get_server_netloc(environ: types.WSGIEnviron, force_port: bool = False):
if environ.get("HTTP_X_FORWARDED_HOST"):
host = environ["HTTP_X_FORWARDED_HOST"]
proto = environ.get("HTTP_X_FORWARDED_PROTO") or "http"
port = "443" if proto == "https" else "80"
port = environ["HTTP_X_FORWARDED_PORT"] or port
else:
host = environ.get("HTTP_HOST") or environ["SERVER_NAME"]
proto = environ["wsgi.url_scheme"]
port = environ["SERVER_PORT"]
if (not force_port and port == ("443" if proto == "https" else "80") or
re.search(r":\d+$", host)):
return host
return host + ":" + port
class ApplicationPartMove(ApplicationBase):
def do_MOVE(self, environ: types.WSGIEnviron, base_prefix: str,
path: str, user: str) -> types.WSGIResponse:
"""Manage MOVE request."""
raw_dest = environ.get("HTTP_DESTINATION", "")
to_url = urlparse(raw_dest)
to_netloc_with_port = to_url.netloc
if to_url.port is None:
to_netloc_with_port += (":443" if to_url.scheme == "https"
else ":80")
if to_netloc_with_port != get_server_netloc(environ, force_port=True):
logger.info("Unsupported destination address: %r", raw_dest)
# Remote destination server, not supported
return httputils.REMOTE_DESTINATION
access = Access(self._rights, user, path)
if not access.check("w"):
return httputils.NOT_ALLOWED
to_path = pathutils.sanitize_path(to_url.path)
if not (to_path + "/").startswith(base_prefix + "/"):
logger.warning("Destination %r from MOVE request on %r doesn't "
"start with base prefix", to_path, path)
return httputils.NOT_ALLOWED
to_path = to_path[len(base_prefix):]
to_access = Access(self._rights, user, to_path)
if not to_access.check("w"):
return httputils.NOT_ALLOWED
with self._storage.acquire_lock("w", user):
item = next(iter(self._storage.discover(path)), None)
if not item:
return httputils.NOT_FOUND
if (not access.check("w", item) or
not to_access.check("w", item)):
return httputils.NOT_ALLOWED
if isinstance(item, storage.BaseCollection):
# TODO: support moving collections
return httputils.METHOD_NOT_ALLOWED
to_item = next(iter(self._storage.discover(to_path)), None)
if isinstance(to_item, storage.BaseCollection):
return httputils.FORBIDDEN
to_parent_path = pathutils.unstrip_path(
posixpath.dirname(pathutils.strip_path(to_path)), True)
to_collection = next(iter(
self._storage.discover(to_parent_path)), None)
if not to_collection:
return httputils.CONFLICT
assert isinstance(to_collection, storage.BaseCollection)
assert item.collection is not None
collection_tag = item.collection.tag
if not collection_tag or collection_tag != to_collection.tag:
return httputils.FORBIDDEN
if to_item and environ.get("HTTP_OVERWRITE", "F") != "T":
return httputils.PRECONDITION_FAILED
if (to_item and item.uid != to_item.uid or
not to_item and
to_collection.path != item.collection.path and
to_collection.has_uid(item.uid)):
return self._webdav_error_response(
client.CONFLICT, "%s:no-uid-conflict" % (
"C" if collection_tag == "VCALENDAR" else "CR"))
to_href = posixpath.basename(pathutils.strip_path(to_path))
try:
self._storage.move(item, to_collection, to_href)
except ValueError as e:
logger.warning(
"Bad MOVE request on %r: %s", path, e, exc_info=True)
return httputils.BAD_REQUEST
return client.NO_CONTENT if to_item else client.CREATED, {}, None
| 5,302
|
Python
|
.py
| 106
| 39.660377
| 78
| 0.623384
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,239
|
__init__.py
|
Kozea_Radicale/radicale/app/__init__.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2008 Nicolas Kandel
# Copyright © 2008 Pascal Halter
# Copyright © 2008-2017 Guillaume Ayoub
# Copyright © 2017-2019 Unrud <unrud@outlook.com>
# Copyright © 2024-2024 Peter Bieringer <pb@bieringer.de>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
"""
Radicale WSGI application.
Can be used with an external WSGI server (see ``radicale.application()``) or
the built-in server (see ``radicale.server`` module).
"""
import base64
import datetime
import pprint
import random
import time
import zlib
from http import client
from typing import Iterable, List, Mapping, Tuple, Union
from radicale import config, httputils, log, pathutils, types
from radicale.app.base import ApplicationBase
from radicale.app.delete import ApplicationPartDelete
from radicale.app.get import ApplicationPartGet
from radicale.app.head import ApplicationPartHead
from radicale.app.mkcalendar import ApplicationPartMkcalendar
from radicale.app.mkcol import ApplicationPartMkcol
from radicale.app.move import ApplicationPartMove
from radicale.app.options import ApplicationPartOptions
from radicale.app.post import ApplicationPartPost
from radicale.app.propfind import ApplicationPartPropfind
from radicale.app.proppatch import ApplicationPartProppatch
from radicale.app.put import ApplicationPartPut
from radicale.app.report import ApplicationPartReport
from radicale.log import logger
# Combination of types.WSGIStartResponse and WSGI application return value
_IntermediateResponse = Tuple[str, List[Tuple[str, str]], Iterable[bytes]]
class Application(ApplicationPartDelete, ApplicationPartHead,
ApplicationPartGet, ApplicationPartMkcalendar,
ApplicationPartMkcol, ApplicationPartMove,
ApplicationPartOptions, ApplicationPartPropfind,
ApplicationPartProppatch, ApplicationPartPost,
ApplicationPartPut, ApplicationPartReport, ApplicationBase):
"""WSGI application."""
_mask_passwords: bool
_auth_delay: float
_internal_server: bool
_max_content_length: int
_auth_realm: str
_extra_headers: Mapping[str, str]
_permit_delete_collection: bool
_permit_overwrite_collection: bool
def __init__(self, configuration: config.Configuration) -> None:
"""Initialize Application.
``configuration`` see ``radicale.config`` module.
The ``configuration`` must not change during the lifetime of
this object, it is kept as an internal reference.
"""
super().__init__(configuration)
self._mask_passwords = configuration.get("logging", "mask_passwords")
self._bad_put_request_content = configuration.get("logging", "bad_put_request_content")
self._request_header_on_debug = configuration.get("logging", "request_header_on_debug")
self._response_content_on_debug = configuration.get("logging", "response_content_on_debug")
self._auth_delay = configuration.get("auth", "delay")
self._internal_server = configuration.get("server", "_internal_server")
self._max_content_length = configuration.get(
"server", "max_content_length")
self._auth_realm = configuration.get("auth", "realm")
self._permit_delete_collection = configuration.get("rights", "permit_delete_collection")
logger.info("permit delete of collection: %s", self._permit_delete_collection)
self._permit_overwrite_collection = configuration.get("rights", "permit_overwrite_collection")
logger.info("permit overwrite of collection: %s", self._permit_overwrite_collection)
self._extra_headers = dict()
for key in self.configuration.options("headers"):
self._extra_headers[key] = configuration.get("headers", key)
def _scrub_headers(self, environ: types.WSGIEnviron) -> types.WSGIEnviron:
"""Mask passwords and cookies."""
headers = dict(environ)
if (self._mask_passwords and
headers.get("HTTP_AUTHORIZATION", "").startswith("Basic")):
headers["HTTP_AUTHORIZATION"] = "Basic **masked**"
if headers.get("HTTP_COOKIE"):
headers["HTTP_COOKIE"] = "**masked**"
return headers
def __call__(self, environ: types.WSGIEnviron, start_response:
types.WSGIStartResponse) -> Iterable[bytes]:
with log.register_stream(environ["wsgi.errors"]):
try:
status_text, headers, answers = self._handle_request(environ)
except Exception as e:
logger.error("An exception occurred during %s request on %r: "
"%s", environ.get("REQUEST_METHOD", "unknown"),
environ.get("PATH_INFO", ""), e, exc_info=True)
# Make minimal response
status, raw_headers, raw_answer = (
httputils.INTERNAL_SERVER_ERROR)
assert isinstance(raw_answer, str)
answer = raw_answer.encode("ascii")
status_text = "%d %s" % (
status, client.responses.get(status, "Unknown"))
headers = [*raw_headers, ("Content-Length", str(len(answer)))]
answers = [answer]
start_response(status_text, headers)
if environ.get("REQUEST_METHOD") == "HEAD":
return []
return answers
def _handle_request(self, environ: types.WSGIEnviron
) -> _IntermediateResponse:
time_begin = datetime.datetime.now()
request_method = environ["REQUEST_METHOD"].upper()
unsafe_path = environ.get("PATH_INFO", "")
"""Manage a request."""
def response(status: int, headers: types.WSGIResponseHeaders,
answer: Union[None, str, bytes]) -> _IntermediateResponse:
"""Helper to create response from internal types.WSGIResponse"""
headers = dict(headers)
# Set content length
answers = []
if answer is not None:
if isinstance(answer, str):
if self._response_content_on_debug:
logger.debug("Response content:\n%s", answer)
else:
logger.debug("Response content: suppressed by config/option [logging] response_content_on_debug")
headers["Content-Type"] += "; charset=%s" % self._encoding
answer = answer.encode(self._encoding)
accept_encoding = [
encoding.strip() for encoding in
environ.get("HTTP_ACCEPT_ENCODING", "").split(",")
if encoding.strip()]
if "gzip" in accept_encoding:
zcomp = zlib.compressobj(wbits=16 + zlib.MAX_WBITS)
answer = zcomp.compress(answer) + zcomp.flush()
headers["Content-Encoding"] = "gzip"
headers["Content-Length"] = str(len(answer))
answers.append(answer)
# Add extra headers set in configuration
headers.update(self._extra_headers)
# Start response
time_end = datetime.datetime.now()
status_text = "%d %s" % (
status, client.responses.get(status, "Unknown"))
logger.info("%s response status for %r%s in %.3f seconds: %s",
request_method, unsafe_path, depthinfo,
(time_end - time_begin).total_seconds(), status_text)
# Return response content
return status_text, list(headers.items()), answers
remote_host = "unknown"
if environ.get("REMOTE_HOST"):
remote_host = repr(environ["REMOTE_HOST"])
elif environ.get("REMOTE_ADDR"):
remote_host = environ["REMOTE_ADDR"]
if environ.get("HTTP_X_FORWARDED_FOR"):
remote_host = "%s (forwarded for %r)" % (
remote_host, environ["HTTP_X_FORWARDED_FOR"])
remote_useragent = ""
if environ.get("HTTP_USER_AGENT"):
remote_useragent = " using %r" % environ["HTTP_USER_AGENT"]
depthinfo = ""
if environ.get("HTTP_DEPTH"):
depthinfo = " with depth %r" % environ["HTTP_DEPTH"]
logger.info("%s request for %r%s received from %s%s",
request_method, unsafe_path, depthinfo,
remote_host, remote_useragent)
if self._request_header_on_debug:
logger.debug("Request header:\n%s",
pprint.pformat(self._scrub_headers(environ)))
else:
logger.debug("Request header: suppressed by config/option [logging] request_header_on_debug")
# SCRIPT_NAME is already removed from PATH_INFO, according to the
# WSGI specification.
# Reverse proxies can overwrite SCRIPT_NAME with X-SCRIPT-NAME header
base_prefix_src = ("HTTP_X_SCRIPT_NAME" if "HTTP_X_SCRIPT_NAME" in
environ else "SCRIPT_NAME")
base_prefix = environ.get(base_prefix_src, "")
if base_prefix and base_prefix[0] != "/":
logger.error("Base prefix (from %s) must start with '/': %r",
base_prefix_src, base_prefix)
if base_prefix_src == "HTTP_X_SCRIPT_NAME":
return response(*httputils.BAD_REQUEST)
return response(*httputils.INTERNAL_SERVER_ERROR)
if base_prefix.endswith("/"):
logger.warning("Base prefix (from %s) must not end with '/': %r",
base_prefix_src, base_prefix)
base_prefix = base_prefix.rstrip("/")
logger.debug("Base prefix (from %s): %r", base_prefix_src, base_prefix)
# Sanitize request URI (a WSGI server indicates with an empty path,
# that the URL targets the application root without a trailing slash)
path = pathutils.sanitize_path(unsafe_path)
logger.debug("Sanitized path: %r", path)
# Get function corresponding to method
function = getattr(self, "do_%s" % request_method, None)
if not function:
return response(*httputils.METHOD_NOT_ALLOWED)
# Redirect all "…/.well-known/{caldav,carddav}" paths to "/".
# This shouldn't be necessary but some clients like TbSync require it.
# Status must be MOVED PERMANENTLY using FOUND causes problems
if (path.rstrip("/").endswith("/.well-known/caldav") or
path.rstrip("/").endswith("/.well-known/carddav")):
return response(*httputils.redirect(
base_prefix + "/", client.MOVED_PERMANENTLY))
# Return NOT FOUND for all other paths containing ".well-known"
if path.endswith("/.well-known") or "/.well-known/" in path:
return response(*httputils.NOT_FOUND)
# Ask authentication backend to check rights
login = password = ""
external_login = self._auth.get_external_login(environ)
authorization = environ.get("HTTP_AUTHORIZATION", "")
if external_login:
login, password = external_login
login, password = login or "", password or ""
elif authorization.startswith("Basic"):
authorization = authorization[len("Basic"):].strip()
login, password = httputils.decode_request(
self.configuration, environ, base64.b64decode(
authorization.encode("ascii"))).split(":", 1)
user = self._auth.login(login, password) or "" if login else ""
if self.configuration.get("auth", "type") == "ldap":
try:
logger.debug("Groups %r", ",".join(self._auth._ldap_groups))
self._rights._user_groups = self._auth._ldap_groups
except AttributeError:
pass
if user and login == user:
logger.info("Successful login: %r", user)
elif user:
logger.info("Successful login: %r -> %r", login, user)
elif login:
logger.warning("Failed login attempt from %s: %r",
remote_host, login)
# Random delay to avoid timing oracles and bruteforce attacks
if self._auth_delay > 0:
random_delay = self._auth_delay * (0.5 + random.random())
logger.debug("Sleeping %.3f seconds", random_delay)
time.sleep(random_delay)
if user and not pathutils.is_safe_path_component(user):
# Prevent usernames like "user/calendar.ics"
logger.info("Refused unsafe username: %r", user)
user = ""
# Create principal collection
if user:
principal_path = "/%s/" % user
with self._storage.acquire_lock("r", user):
principal = next(iter(self._storage.discover(
principal_path, depth="1")), None)
if not principal:
if "W" in self._rights.authorization(user, principal_path):
with self._storage.acquire_lock("w", user):
try:
new_coll = self._storage.create_collection(principal_path)
if new_coll:
jsn_coll = self.configuration.get("storage", "predefined_collections")
for (name_coll, props) in jsn_coll.items():
try:
self._storage.create_collection(principal_path + name_coll, props=props)
except ValueError as e:
logger.warning("Failed to create predefined collection %r: %s", name_coll, e)
except ValueError as e:
logger.warning("Failed to create principal "
"collection %r: %s", user, e)
user = ""
else:
logger.warning("Access to principal path %r denied by "
"rights backend", principal_path)
if self._internal_server:
# Verify content length
content_length = int(environ.get("CONTENT_LENGTH") or 0)
if content_length:
if (self._max_content_length > 0 and
content_length > self._max_content_length):
logger.info("Request body too large: %d", content_length)
return response(*httputils.REQUEST_ENTITY_TOO_LARGE)
if not login or user:
status, headers, answer = function(
environ, base_prefix, path, user)
if (status, headers, answer) == httputils.NOT_ALLOWED:
logger.info("Access to %r denied for %s", path,
repr(user) if user else "anonymous user")
else:
status, headers, answer = httputils.NOT_ALLOWED
if ((status, headers, answer) == httputils.NOT_ALLOWED and not user and
not external_login):
# Unknown or unauthorized user
logger.debug("Asking client for authentication")
status = client.UNAUTHORIZED
headers = dict(headers)
headers.update({
"WWW-Authenticate":
"Basic realm=\"%s\"" % self._auth_realm})
return response(status, headers, answer)
| 16,141
|
Python
|
.py
| 302
| 41.023179
| 121
| 0.60557
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,240
|
base.py
|
Kozea_Radicale/radicale/app/base.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2020 Unrud <unrud@outlook.com>
# Copyright © 2024-2024 Peter Bieringer <pb@bieringer.de>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
import io
import logging
import posixpath
import sys
import xml.etree.ElementTree as ET
from typing import Optional
from radicale import (auth, config, hook, httputils, pathutils, rights,
storage, types, web, xmlutils)
from radicale.log import logger
# HACK: https://github.com/tiran/defusedxml/issues/54
import defusedxml.ElementTree as DefusedET # isort:skip
sys.modules["xml.etree"].ElementTree = ET # type:ignore[attr-defined]
class ApplicationBase:
configuration: config.Configuration
_auth: auth.BaseAuth
_storage: storage.BaseStorage
_rights: rights.BaseRights
_web: web.BaseWeb
_encoding: str
_permit_delete_collection: bool
_permit_overwrite_collection: bool
_hook: hook.BaseHook
def __init__(self, configuration: config.Configuration) -> None:
self.configuration = configuration
self._auth = auth.load(configuration)
self._storage = storage.load(configuration)
self._rights = rights.load(configuration)
self._web = web.load(configuration)
self._encoding = configuration.get("encoding", "request")
self._log_bad_put_request_content = configuration.get("logging", "bad_put_request_content")
self._response_content_on_debug = configuration.get("logging", "response_content_on_debug")
self._request_content_on_debug = configuration.get("logging", "request_content_on_debug")
self._hook = hook.load(configuration)
def _read_xml_request_body(self, environ: types.WSGIEnviron
) -> Optional[ET.Element]:
content = httputils.decode_request(
self.configuration, environ,
httputils.read_raw_request_body(self.configuration, environ))
if not content:
return None
try:
xml_content = DefusedET.fromstring(content)
except ET.ParseError as e:
logger.debug("Request content (Invalid XML):\n%s", content)
raise RuntimeError("Failed to parse XML: %s" % e) from e
if logger.isEnabledFor(logging.DEBUG):
if self._request_content_on_debug:
logger.debug("Request content (XML):\n%s",
xmlutils.pretty_xml(xml_content))
else:
logger.debug("Request content (XML): suppressed by config/option [logging] request_content_on_debug")
return xml_content
def _xml_response(self, xml_content: ET.Element) -> bytes:
if logger.isEnabledFor(logging.DEBUG):
if self._response_content_on_debug:
logger.debug("Response content (XML):\n%s",
xmlutils.pretty_xml(xml_content))
else:
logger.debug("Response content (XML): suppressed by config/option [logging] response_content_on_debug")
f = io.BytesIO()
ET.ElementTree(xml_content).write(f, encoding=self._encoding,
xml_declaration=True)
return f.getvalue()
def _webdav_error_response(self, status: int, human_tag: str
) -> types.WSGIResponse:
"""Generate XML error response."""
headers = {"Content-Type": "text/xml; charset=%s" % self._encoding}
content = self._xml_response(xmlutils.webdav_error(human_tag))
return status, headers, content
class Access:
"""Helper class to check access rights of an item"""
user: str
path: str
parent_path: str
permissions: str
_rights: rights.BaseRights
_parent_permissions: Optional[str]
def __init__(self, rights: rights.BaseRights, user: str, path: str
) -> None:
self._rights = rights
self.user = user
self.path = path
self.parent_path = pathutils.unstrip_path(
posixpath.dirname(pathutils.strip_path(path)), True)
self.permissions = self._rights.authorization(self.user, self.path)
self._parent_permissions = None
@property
def parent_permissions(self) -> str:
if self.path == self.parent_path:
return self.permissions
if self._parent_permissions is None:
self._parent_permissions = self._rights.authorization(
self.user, self.parent_path)
return self._parent_permissions
def check(self, permission: str,
item: Optional[types.CollectionOrItem] = None) -> bool:
if permission not in "rwdDoO":
raise ValueError("Invalid permission argument: %r" % permission)
if not item:
permissions = permission + permission.upper()
parent_permissions = permission
elif isinstance(item, storage.BaseCollection):
if item.tag:
permissions = permission
else:
permissions = permission.upper()
parent_permissions = ""
else:
permissions = ""
parent_permissions = permission
return bool(rights.intersect(self.permissions, permissions) or (
self.path != self.parent_path and
rights.intersect(self.parent_permissions, parent_permissions)))
| 5,990
|
Python
|
.py
| 129
| 37.51938
| 119
| 0.655143
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,241
|
propfind.py
|
Kozea_Radicale/radicale/app/propfind.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2008 Nicolas Kandel
# Copyright © 2008 Pascal Halter
# Copyright © 2008-2017 Guillaume Ayoub
# Copyright © 2017-2018 Unrud <unrud@outlook.com>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
import collections
import itertools
import posixpath
import socket
import xml.etree.ElementTree as ET
from http import client
from typing import Dict, Iterable, Iterator, List, Optional, Sequence, Tuple
from radicale import httputils, pathutils, rights, storage, types, xmlutils
from radicale.app.base import Access, ApplicationBase
from radicale.log import logger
def xml_propfind(base_prefix: str, path: str,
xml_request: Optional[ET.Element],
allowed_items: Iterable[Tuple[types.CollectionOrItem, str]],
user: str, encoding: str) -> Optional[ET.Element]:
"""Read and answer PROPFIND requests.
Read rfc4918-9.1 for info.
The collections parameter is a list of collections that are to be included
in the output.
"""
# A client may choose not to submit a request body. An empty PROPFIND
# request body MUST be treated as if it were an 'allprop' request.
top_element = (xml_request[0] if xml_request is not None else
ET.Element(xmlutils.make_clark("D:allprop")))
props: List[str] = []
allprop = False
propname = False
if top_element.tag == xmlutils.make_clark("D:allprop"):
allprop = True
elif top_element.tag == xmlutils.make_clark("D:propname"):
propname = True
elif top_element.tag == xmlutils.make_clark("D:prop"):
props.extend(prop.tag for prop in top_element)
if xmlutils.make_clark("D:current-user-principal") in props and not user:
# Ask for authentication
# Returning the DAV:unauthenticated pseudo-principal as specified in
# RFC 5397 doesn't seem to work with DAVx5.
return None
# Writing answer
multistatus = ET.Element(xmlutils.make_clark("D:multistatus"))
for item, permission in allowed_items:
write = permission == "w"
multistatus.append(xml_propfind_response(
base_prefix, path, item, props, user, encoding, write=write,
allprop=allprop, propname=propname))
return multistatus
def xml_propfind_response(
base_prefix: str, path: str, item: types.CollectionOrItem,
props: Sequence[str], user: str, encoding: str, write: bool = False,
propname: bool = False, allprop: bool = False) -> ET.Element:
"""Build and return a PROPFIND response."""
if propname and allprop or (props and (propname or allprop)):
raise ValueError("Only use one of props, propname and allprops")
if isinstance(item, storage.BaseCollection):
is_collection = True
is_leaf = item.tag in ("VADDRESSBOOK", "VCALENDAR", "VSUBSCRIBED")
collection = item
# Some clients expect collections to end with `/`
uri = pathutils.unstrip_path(item.path, True)
else:
is_collection = is_leaf = False
assert item.collection is not None
assert item.href
collection = item.collection
uri = pathutils.unstrip_path(posixpath.join(
collection.path, item.href))
response = ET.Element(xmlutils.make_clark("D:response"))
href = ET.Element(xmlutils.make_clark("D:href"))
href.text = xmlutils.make_href(base_prefix, uri)
response.append(href)
if propname or allprop:
props = []
# Should list all properties that can be retrieved by the code below
props.append(xmlutils.make_clark("D:principal-collection-set"))
props.append(xmlutils.make_clark("D:current-user-principal"))
props.append(xmlutils.make_clark("D:current-user-privilege-set"))
props.append(xmlutils.make_clark("D:supported-report-set"))
props.append(xmlutils.make_clark("D:resourcetype"))
props.append(xmlutils.make_clark("D:owner"))
if is_collection and collection.is_principal:
props.append(xmlutils.make_clark("C:calendar-user-address-set"))
props.append(xmlutils.make_clark("D:principal-URL"))
props.append(xmlutils.make_clark("CR:addressbook-home-set"))
props.append(xmlutils.make_clark("C:calendar-home-set"))
if not is_collection or is_leaf:
props.append(xmlutils.make_clark("D:getetag"))
props.append(xmlutils.make_clark("D:getlastmodified"))
props.append(xmlutils.make_clark("D:getcontenttype"))
props.append(xmlutils.make_clark("D:getcontentlength"))
if is_collection:
if is_leaf:
props.append(xmlutils.make_clark("D:displayname"))
props.append(xmlutils.make_clark("D:sync-token"))
if collection.tag == "VCALENDAR":
props.append(xmlutils.make_clark("CS:getctag"))
props.append(
xmlutils.make_clark("C:supported-calendar-component-set"))
meta = collection.get_meta()
for tag in meta:
if tag == "tag":
continue
clark_tag = xmlutils.make_clark(tag)
if clark_tag not in props:
props.append(clark_tag)
responses: Dict[int, List[ET.Element]] = collections.defaultdict(list)
if propname:
for tag in props:
responses[200].append(ET.Element(tag))
props = []
for tag in props:
element = ET.Element(tag)
is404 = False
if tag == xmlutils.make_clark("D:getetag"):
if not is_collection or is_leaf:
element.text = item.etag
else:
is404 = True
elif tag == xmlutils.make_clark("D:getlastmodified"):
if not is_collection or is_leaf:
element.text = item.last_modified
else:
is404 = True
elif tag == xmlutils.make_clark("D:principal-collection-set"):
child_element = ET.Element(xmlutils.make_clark("D:href"))
child_element.text = xmlutils.make_href(base_prefix, "/")
element.append(child_element)
elif (tag in (xmlutils.make_clark("C:calendar-user-address-set"),
xmlutils.make_clark("D:principal-URL"),
xmlutils.make_clark("CR:addressbook-home-set"),
xmlutils.make_clark("C:calendar-home-set")) and
is_collection and collection.is_principal):
child_element = ET.Element(xmlutils.make_clark("D:href"))
child_element.text = xmlutils.make_href(base_prefix, path)
element.append(child_element)
elif tag == xmlutils.make_clark("C:supported-calendar-component-set"):
human_tag = xmlutils.make_human_tag(tag)
if is_collection and is_leaf:
components_text = collection.get_meta(human_tag)
if components_text:
components = components_text.split(",")
else:
components = ["VTODO", "VEVENT", "VJOURNAL"]
for component in components:
comp = ET.Element(xmlutils.make_clark("C:comp"))
comp.set("name", component)
element.append(comp)
else:
is404 = True
elif tag == xmlutils.make_clark("D:current-user-principal"):
if user:
child_element = ET.Element(xmlutils.make_clark("D:href"))
child_element.text = xmlutils.make_href(
base_prefix, "/%s/" % user)
element.append(child_element)
else:
element.append(ET.Element(
xmlutils.make_clark("D:unauthenticated")))
elif tag == xmlutils.make_clark("D:current-user-privilege-set"):
privileges = ["D:read"]
if write:
privileges.append("D:all")
privileges.append("D:write")
privileges.append("D:write-properties")
privileges.append("D:write-content")
for human_tag in privileges:
privilege = ET.Element(xmlutils.make_clark("D:privilege"))
privilege.append(ET.Element(
xmlutils.make_clark(human_tag)))
element.append(privilege)
elif tag == xmlutils.make_clark("D:supported-report-set"):
# These 3 reports are not implemented
reports = ["D:expand-property",
"D:principal-search-property-set",
"D:principal-property-search"]
if is_collection and is_leaf:
reports.append("D:sync-collection")
if collection.tag == "VADDRESSBOOK":
reports.append("CR:addressbook-multiget")
reports.append("CR:addressbook-query")
elif collection.tag == "VCALENDAR":
reports.append("C:calendar-multiget")
reports.append("C:calendar-query")
for human_tag in reports:
supported_report = ET.Element(
xmlutils.make_clark("D:supported-report"))
report_element = ET.Element(xmlutils.make_clark("D:report"))
report_element.append(
ET.Element(xmlutils.make_clark(human_tag)))
supported_report.append(report_element)
element.append(supported_report)
elif tag == xmlutils.make_clark("D:getcontentlength"):
if not is_collection or is_leaf:
element.text = str(len(item.serialize().encode(encoding)))
else:
is404 = True
elif tag == xmlutils.make_clark("D:owner"):
# return empty elment, if no owner available (rfc3744-5.1)
if collection.owner:
child_element = ET.Element(xmlutils.make_clark("D:href"))
child_element.text = xmlutils.make_href(
base_prefix, "/%s/" % collection.owner)
element.append(child_element)
elif is_collection:
if tag == xmlutils.make_clark("D:getcontenttype"):
if is_leaf:
element.text = xmlutils.MIMETYPES[
collection.tag]
else:
is404 = True
elif tag == xmlutils.make_clark("D:resourcetype"):
if collection.is_principal:
child_element = ET.Element(
xmlutils.make_clark("D:principal"))
element.append(child_element)
if is_leaf:
if collection.tag == "VADDRESSBOOK":
child_element = ET.Element(
xmlutils.make_clark("CR:addressbook"))
element.append(child_element)
elif collection.tag == "VCALENDAR":
child_element = ET.Element(
xmlutils.make_clark("C:calendar"))
element.append(child_element)
elif collection.tag == "VSUBSCRIBED":
child_element = ET.Element(
xmlutils.make_clark("CS:subscribed"))
element.append(child_element)
child_element = ET.Element(xmlutils.make_clark("D:collection"))
element.append(child_element)
elif tag == xmlutils.make_clark("RADICALE:displayname"):
# Only for internal use by the web interface
displayname = collection.get_meta("D:displayname")
if displayname is not None:
element.text = displayname
else:
is404 = True
elif tag == xmlutils.make_clark("RADICALE:getcontentcount"):
# Only for internal use by the web interface
if isinstance(item, storage.BaseCollection) and not collection.is_principal:
element.text = str(sum(1 for x in item.get_all()))
else:
is404 = True
elif tag == xmlutils.make_clark("D:displayname"):
displayname = collection.get_meta("D:displayname")
if not displayname and is_leaf:
displayname = collection.path
if displayname is not None:
element.text = displayname
else:
is404 = True
elif tag == xmlutils.make_clark("CS:getctag"):
if is_leaf:
element.text = collection.etag
else:
is404 = True
elif tag == xmlutils.make_clark("D:sync-token"):
if is_leaf:
element.text, _ = collection.sync()
else:
is404 = True
elif tag == xmlutils.make_clark("CS:source"):
if is_leaf:
child_element = ET.Element(xmlutils.make_clark("D:href"))
child_element.text = collection.get_meta('CS:source')
element.append(child_element)
else:
is404 = True
else:
human_tag = xmlutils.make_human_tag(tag)
tag_text = collection.get_meta(human_tag)
if tag_text is not None:
element.text = tag_text
else:
is404 = True
# Not for collections
elif tag == xmlutils.make_clark("D:getcontenttype"):
assert not isinstance(item, storage.BaseCollection)
element.text = xmlutils.get_content_type(item, encoding)
elif tag == xmlutils.make_clark("D:resourcetype"):
# resourcetype must be returned empty for non-collection elements
pass
else:
is404 = True
responses[404 if is404 else 200].append(element)
for status_code, children in responses.items():
if not children:
continue
propstat = ET.Element(xmlutils.make_clark("D:propstat"))
response.append(propstat)
prop = ET.Element(xmlutils.make_clark("D:prop"))
prop.extend(children)
propstat.append(prop)
status = ET.Element(xmlutils.make_clark("D:status"))
status.text = xmlutils.make_response(status_code)
propstat.append(status)
return response
class ApplicationPartPropfind(ApplicationBase):
def _collect_allowed_items(
self, items: Iterable[types.CollectionOrItem], user: str
) -> Iterator[Tuple[types.CollectionOrItem, str]]:
"""Get items from request that user is allowed to access."""
for item in items:
if isinstance(item, storage.BaseCollection):
path = pathutils.unstrip_path(item.path, True)
if item.tag:
permissions = rights.intersect(
self._rights.authorization(user, path), "rw")
target = "collection with tag %r" % item.path
else:
permissions = rights.intersect(
self._rights.authorization(user, path), "RW")
target = "collection %r" % item.path
else:
assert item.collection is not None
path = pathutils.unstrip_path(item.collection.path, True)
permissions = rights.intersect(
self._rights.authorization(user, path), "rw")
target = "item %r from %r" % (item.href, item.collection.path)
if rights.intersect(permissions, "Ww"):
permission = "w"
status = "write"
elif rights.intersect(permissions, "Rr"):
permission = "r"
status = "read"
else:
permission = ""
status = "NO"
logger.debug(
"%s has %s access to %s",
repr(user) if user else "anonymous user", status, target)
if permission:
yield item, permission
def do_PROPFIND(self, environ: types.WSGIEnviron, base_prefix: str,
path: str, user: str) -> types.WSGIResponse:
"""Manage PROPFIND request."""
access = Access(self._rights, user, path)
if not access.check("r"):
return httputils.NOT_ALLOWED
try:
xml_content = self._read_xml_request_body(environ)
except RuntimeError as e:
logger.warning(
"Bad PROPFIND request on %r: %s", path, e, exc_info=True)
return httputils.BAD_REQUEST
except socket.timeout:
logger.debug("Client timed out", exc_info=True)
return httputils.REQUEST_TIMEOUT
with self._storage.acquire_lock("r", user):
items_iter = iter(self._storage.discover(
path, environ.get("HTTP_DEPTH", "0"),
None, self._rights._user_groups))
# take root item for rights checking
item = next(items_iter, None)
if not item:
return httputils.NOT_FOUND
if not access.check("r", item):
return httputils.NOT_ALLOWED
# put item back
items_iter = itertools.chain([item], items_iter)
allowed_items = self._collect_allowed_items(items_iter, user)
headers = {"DAV": httputils.DAV_HEADERS,
"Content-Type": "text/xml; charset=%s" % self._encoding}
xml_answer = xml_propfind(base_prefix, path, xml_content,
allowed_items, user, self._encoding)
if xml_answer is None:
return httputils.NOT_ALLOWED
return client.MULTI_STATUS, headers, self._xml_response(xml_answer)
| 18,660
|
Python
|
.py
| 384
| 35.299479
| 92
| 0.580246
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,242
|
mkcol.py
|
Kozea_Radicale/radicale/app/mkcol.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2008 Nicolas Kandel
# Copyright © 2008 Pascal Halter
# Copyright © 2008-2017 Guillaume Ayoub
# Copyright © 2017-2018 Unrud <unrud@outlook.com>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
import posixpath
import socket
from http import client
import radicale.item as radicale_item
from radicale import httputils, pathutils, rights, storage, types, xmlutils
from radicale.app.base import ApplicationBase
from radicale.log import logger
class ApplicationPartMkcol(ApplicationBase):
def do_MKCOL(self, environ: types.WSGIEnviron, base_prefix: str,
path: str, user: str) -> types.WSGIResponse:
"""Manage MKCOL request."""
permissions = self._rights.authorization(user, path)
if not rights.intersect(permissions, "Ww"):
return httputils.NOT_ALLOWED
try:
xml_content = self._read_xml_request_body(environ)
except RuntimeError as e:
logger.warning(
"Bad MKCOL request on %r: %s", path, e, exc_info=True)
return httputils.BAD_REQUEST
except socket.timeout:
logger.debug("Client timed out", exc_info=True)
return httputils.REQUEST_TIMEOUT
# Prepare before locking
props_with_remove = xmlutils.props_from_request(xml_content)
try:
props = radicale_item.check_and_sanitize_props(props_with_remove)
except ValueError as e:
logger.warning(
"Bad MKCOL request on %r: %s", path, e, exc_info=True)
return httputils.BAD_REQUEST
collection_type = props.get("tag") or "UNKNOWN"
if props.get("tag") and "w" not in permissions:
logger.warning("MKCOL request %r (type:%s): %s", path, collection_type, "rejected because of missing rights 'w'")
return httputils.NOT_ALLOWED
if not props.get("tag") and "W" not in permissions:
logger.warning("MKCOL request %r (type:%s): %s", path, collection_type, "rejected because of missing rights 'W'")
return httputils.NOT_ALLOWED
with self._storage.acquire_lock("w", user):
item = next(iter(self._storage.discover(path)), None)
if item:
return httputils.METHOD_NOT_ALLOWED
parent_path = pathutils.unstrip_path(
posixpath.dirname(pathutils.strip_path(path)), True)
parent_item = next(iter(self._storage.discover(parent_path)), None)
if not parent_item:
return httputils.CONFLICT
if (not isinstance(parent_item, storage.BaseCollection) or
parent_item.tag):
return httputils.FORBIDDEN
try:
self._storage.create_collection(path, props=props)
except ValueError as e:
logger.warning(
"Bad MKCOL request on %r (type:%s): %s", path, collection_type, e, exc_info=True)
return httputils.BAD_REQUEST
logger.info("MKCOL request %r (type:%s): %s", path, collection_type, "successful")
return client.CREATED, {}, None
| 3,782
|
Python
|
.py
| 76
| 40.842105
| 125
| 0.658642
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,243
|
head.py
|
Kozea_Radicale/radicale/app/head.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2008 Nicolas Kandel
# Copyright © 2008 Pascal Halter
# Copyright © 2008-2017 Guillaume Ayoub
# Copyright © 2017-2018 Unrud <unrud@outlook.com>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
from radicale import types
from radicale.app.base import ApplicationBase
from radicale.app.get import ApplicationPartGet
class ApplicationPartHead(ApplicationPartGet, ApplicationBase):
def do_HEAD(self, environ: types.WSGIEnviron, base_prefix: str, path: str,
user: str) -> types.WSGIResponse:
"""Manage HEAD request."""
# Body is dropped in `Application.__call__` for HEAD requests
return self.do_GET(environ, base_prefix, path, user)
| 1,337
|
Python
|
.py
| 27
| 46.592593
| 78
| 0.761905
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,244
|
proppatch.py
|
Kozea_Radicale/radicale/app/proppatch.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2008 Nicolas Kandel
# Copyright © 2008 Pascal Halter
# Copyright © 2008-2017 Guillaume Ayoub
# Copyright © 2017-2018 Unrud <unrud@outlook.com>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
import socket
import xml.etree.ElementTree as ET
from http import client
from typing import Dict, Optional, cast
import defusedxml.ElementTree as DefusedET
import radicale.item as radicale_item
from radicale import httputils, storage, types, xmlutils
from radicale.app.base import Access, ApplicationBase
from radicale.hook import HookNotificationItem, HookNotificationItemTypes
from radicale.log import logger
def xml_proppatch(base_prefix: str, path: str,
xml_request: Optional[ET.Element],
collection: storage.BaseCollection) -> ET.Element:
"""Read and answer PROPPATCH requests.
Read rfc4918-9.2 for info.
"""
multistatus = ET.Element(xmlutils.make_clark("D:multistatus"))
response = ET.Element(xmlutils.make_clark("D:response"))
multistatus.append(response)
href = ET.Element(xmlutils.make_clark("D:href"))
href.text = xmlutils.make_href(base_prefix, path)
response.append(href)
# Create D:propstat element for props with status 200 OK
propstat = ET.Element(xmlutils.make_clark("D:propstat"))
status = ET.Element(xmlutils.make_clark("D:status"))
status.text = xmlutils.make_response(200)
props_ok = ET.Element(xmlutils.make_clark("D:prop"))
propstat.append(props_ok)
propstat.append(status)
response.append(propstat)
props_with_remove = xmlutils.props_from_request(xml_request)
all_props_with_remove = cast(Dict[str, Optional[str]],
dict(collection.get_meta()))
all_props_with_remove.update(props_with_remove)
all_props = radicale_item.check_and_sanitize_props(all_props_with_remove)
collection.set_meta(all_props)
for short_name in props_with_remove:
props_ok.append(ET.Element(xmlutils.make_clark(short_name)))
return multistatus
class ApplicationPartProppatch(ApplicationBase):
def do_PROPPATCH(self, environ: types.WSGIEnviron, base_prefix: str,
path: str, user: str) -> types.WSGIResponse:
"""Manage PROPPATCH request."""
access = Access(self._rights, user, path)
if not access.check("w"):
return httputils.NOT_ALLOWED
try:
xml_content = self._read_xml_request_body(environ)
except RuntimeError as e:
logger.warning(
"Bad PROPPATCH request on %r: %s", path, e, exc_info=True)
return httputils.BAD_REQUEST
except socket.timeout:
logger.debug("Client timed out", exc_info=True)
return httputils.REQUEST_TIMEOUT
with self._storage.acquire_lock("w", user):
item = next(iter(self._storage.discover(path)), None)
if not item:
return httputils.NOT_FOUND
if not access.check("w", item):
return httputils.NOT_ALLOWED
if not isinstance(item, storage.BaseCollection):
return httputils.FORBIDDEN
headers = {"DAV": httputils.DAV_HEADERS,
"Content-Type": "text/xml; charset=%s" % self._encoding}
try:
xml_answer = xml_proppatch(base_prefix, path, xml_content,
item)
if xml_content is not None:
hook_notification_item = HookNotificationItem(
HookNotificationItemTypes.CPATCH,
access.path,
DefusedET.tostring(
xml_content,
encoding=self._encoding
).decode(encoding=self._encoding)
)
self._hook.notify(hook_notification_item)
except ValueError as e:
logger.warning(
"Bad PROPPATCH request on %r: %s", path, e, exc_info=True)
return httputils.BAD_REQUEST
return client.MULTI_STATUS, headers, self._xml_response(xml_answer)
| 4,828
|
Python
|
.py
| 101
| 38.247525
| 79
| 0.654426
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,245
|
get.py
|
Kozea_Radicale/radicale/app/get.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2008 Nicolas Kandel
# Copyright © 2008 Pascal Halter
# Copyright © 2008-2017 Guillaume Ayoub
# Copyright © 2017-2018 Unrud <unrud@outlook.com>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
import posixpath
from http import client
from urllib.parse import quote
from radicale import httputils, pathutils, storage, types, xmlutils
from radicale.app.base import Access, ApplicationBase
from radicale.log import logger
def propose_filename(collection: storage.BaseCollection) -> str:
"""Propose a filename for a collection."""
if collection.tag == "VADDRESSBOOK":
fallback_title = "Address book"
suffix = ".vcf"
elif collection.tag == "VCALENDAR":
fallback_title = "Calendar"
suffix = ".ics"
else:
fallback_title = posixpath.basename(collection.path)
suffix = ""
title = collection.get_meta("D:displayname") or fallback_title
if title and not title.lower().endswith(suffix.lower()):
title += suffix
return title
class ApplicationPartGet(ApplicationBase):
def _content_disposition_attachment(self, filename: str) -> str:
value = "attachment"
try:
encoded_filename = quote(filename, encoding=self._encoding)
except UnicodeEncodeError:
logger.warning("Failed to encode filename: %r", filename,
exc_info=True)
encoded_filename = ""
if encoded_filename:
value += "; filename*=%s''%s" % (self._encoding, encoded_filename)
return value
def do_GET(self, environ: types.WSGIEnviron, base_prefix: str, path: str,
user: str) -> types.WSGIResponse:
"""Manage GET request."""
# Redirect to /.web if the root path is requested
if not pathutils.strip_path(path):
return httputils.redirect(base_prefix + "/.web")
if path == "/.web" or path.startswith("/.web/"):
# Redirect to sanitized path for all subpaths of /.web
unsafe_path = environ.get("PATH_INFO", "")
if unsafe_path != path:
location = base_prefix + path
logger.info("Redirecting to sanitized path: %r ==> %r",
base_prefix + unsafe_path, location)
return httputils.redirect(location, client.MOVED_PERMANENTLY)
# Dispatch /.web path to web module
return self._web.get(environ, base_prefix, path, user)
access = Access(self._rights, user, path)
if not access.check("r") and "i" not in access.permissions:
return httputils.NOT_ALLOWED
with self._storage.acquire_lock("r", user):
item = next(iter(self._storage.discover(path)), None)
if not item:
return httputils.NOT_FOUND
if access.check("r", item):
limited_access = False
elif "i" in access.permissions:
limited_access = True
else:
return httputils.NOT_ALLOWED
if isinstance(item, storage.BaseCollection):
if not item.tag:
return (httputils.NOT_ALLOWED if limited_access else
httputils.DIRECTORY_LISTING)
content_type = xmlutils.MIMETYPES[item.tag]
content_disposition = self._content_disposition_attachment(
propose_filename(item))
elif limited_access:
return httputils.NOT_ALLOWED
else:
content_type = xmlutils.OBJECT_MIMETYPES[item.name]
content_disposition = ""
assert item.last_modified
headers = {
"Content-Type": content_type,
"Last-Modified": item.last_modified,
"ETag": item.etag}
if content_disposition:
headers["Content-Disposition"] = content_disposition
answer = item.serialize()
return client.OK, headers, answer
| 4,673
|
Python
|
.py
| 101
| 36.376238
| 78
| 0.629605
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,246
|
put.py
|
Kozea_Radicale/radicale/app/put.py
|
# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2008 Nicolas Kandel
# Copyright © 2008 Pascal Halter
# Copyright © 2008-2017 Guillaume Ayoub
# Copyright © 2017-2018 Unrud <unrud@outlook.com>
# Copyright © 2024-2024 Peter Bieringer <pb@bieringer.de>
#
# This library 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 library 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 Radicale. If not, see <http://www.gnu.org/licenses/>.
import itertools
import posixpath
import socket
import sys
from http import client
from types import TracebackType
from typing import Iterator, List, Mapping, MutableMapping, Optional, Tuple
import vobject
import radicale.item as radicale_item
from radicale import httputils, pathutils, rights, storage, types, xmlutils
from radicale.app.base import Access, ApplicationBase
from radicale.hook import HookNotificationItem, HookNotificationItemTypes
from radicale.log import logger
MIMETYPE_TAGS: Mapping[str, str] = {value: key for key, value in
xmlutils.MIMETYPES.items()}
def prepare(vobject_items: List[vobject.base.Component], path: str,
content_type: str, permission: bool, parent_permission: bool,
tag: Optional[str] = None,
write_whole_collection: Optional[bool] = None) -> Tuple[
Iterator[radicale_item.Item], # items
Optional[str], # tag
Optional[bool], # write_whole_collection
Optional[MutableMapping[str, str]], # props
Optional[Tuple[type, BaseException, Optional[TracebackType]]]]:
if (write_whole_collection or permission and not parent_permission):
write_whole_collection = True
tag = radicale_item.predict_tag_of_whole_collection(
vobject_items, MIMETYPE_TAGS.get(content_type))
if not tag:
raise ValueError("Can't determine collection tag")
collection_path = pathutils.strip_path(path)
elif (write_whole_collection is not None and not write_whole_collection or
not permission and parent_permission):
write_whole_collection = False
if tag is None:
tag = radicale_item.predict_tag_of_parent_collection(vobject_items)
collection_path = posixpath.dirname(pathutils.strip_path(path))
props: Optional[MutableMapping[str, str]] = None
stored_exc_info = None
items = []
try:
if tag and write_whole_collection is not None:
radicale_item.check_and_sanitize_items(
vobject_items, is_collection=write_whole_collection, tag=tag)
if write_whole_collection and tag == "VCALENDAR":
vobject_components: List[vobject.base.Component] = []
vobject_item, = vobject_items
for content in ("vevent", "vtodo", "vjournal"):
vobject_components.extend(
getattr(vobject_item, "%s_list" % content, []))
vobject_components_by_uid = itertools.groupby(
sorted(vobject_components, key=radicale_item.get_uid),
radicale_item.get_uid)
for _, components in vobject_components_by_uid:
vobject_collection = vobject.iCalendar()
for component in components:
vobject_collection.add(component)
item = radicale_item.Item(collection_path=collection_path,
vobject_item=vobject_collection)
item.prepare()
items.append(item)
elif write_whole_collection and tag == "VADDRESSBOOK":
for vobject_item in vobject_items:
item = radicale_item.Item(collection_path=collection_path,
vobject_item=vobject_item)
item.prepare()
items.append(item)
elif not write_whole_collection:
vobject_item, = vobject_items
item = radicale_item.Item(collection_path=collection_path,
vobject_item=vobject_item)
item.prepare()
items.append(item)
if write_whole_collection:
props = {}
if tag:
props["tag"] = tag
if tag == "VCALENDAR" and vobject_items:
if hasattr(vobject_items[0], "x_wr_calname"):
calname = vobject_items[0].x_wr_calname.value
if calname:
props["D:displayname"] = calname
if hasattr(vobject_items[0], "x_wr_caldesc"):
caldesc = vobject_items[0].x_wr_caldesc.value
if caldesc:
props["C:calendar-description"] = caldesc
props = radicale_item.check_and_sanitize_props(props)
except Exception:
exc_info_or_none_tuple = sys.exc_info()
assert exc_info_or_none_tuple[0] is not None
stored_exc_info = exc_info_or_none_tuple
# Use iterator for items and delete references to free memory early
def items_iter() -> Iterator[radicale_item.Item]:
while items:
yield items.pop(0)
return items_iter(), tag, write_whole_collection, props, stored_exc_info
class ApplicationPartPut(ApplicationBase):
def do_PUT(self, environ: types.WSGIEnviron, base_prefix: str,
path: str, user: str) -> types.WSGIResponse:
"""Manage PUT request."""
access = Access(self._rights, user, path)
if not access.check("w"):
return httputils.NOT_ALLOWED
try:
content = httputils.read_request_body(self.configuration, environ)
except RuntimeError as e:
logger.warning("Bad PUT request on %r (read_request_body): %s", path, e, exc_info=True)
return httputils.BAD_REQUEST
except socket.timeout:
logger.debug("Client timed out", exc_info=True)
return httputils.REQUEST_TIMEOUT
# Prepare before locking
content_type = environ.get("CONTENT_TYPE", "").split(";",
maxsplit=1)[0]
try:
vobject_items = radicale_item.read_components(content or "")
except Exception as e:
logger.warning(
"Bad PUT request on %r (read_components): %s", path, e, exc_info=True)
if self._log_bad_put_request_content:
logger.warning("Bad PUT request content of %r:\n%s", path, content)
else:
logger.debug("Bad PUT request content: suppressed by config/option [logging] bad_put_request_content")
return httputils.BAD_REQUEST
(prepared_items, prepared_tag, prepared_write_whole_collection,
prepared_props, prepared_exc_info) = prepare(
vobject_items, path, content_type,
bool(rights.intersect(access.permissions, "Ww")),
bool(rights.intersect(access.parent_permissions, "w")))
with self._storage.acquire_lock("w", user):
item = next(iter(self._storage.discover(path)), None)
parent_item = next(iter(
self._storage.discover(access.parent_path)), None)
if not isinstance(parent_item, storage.BaseCollection):
return httputils.CONFLICT
write_whole_collection = (
isinstance(item, storage.BaseCollection) or
not parent_item.tag)
if write_whole_collection:
tag = prepared_tag
else:
tag = parent_item.tag
if write_whole_collection:
if ("w" if tag else "W") not in access.permissions:
return httputils.NOT_ALLOWED
if not self._permit_overwrite_collection:
if ("O") not in access.permissions:
logger.info("overwrite of collection is prevented by config/option [rights] permit_overwrite_collection and not explicit allowed by permssion 'O': %s", path)
return httputils.NOT_ALLOWED
else:
if ("o") in access.permissions:
logger.info("overwrite of collection is allowed by config/option [rights] permit_overwrite_collection but explicit forbidden by permission 'o': %s", path)
return httputils.NOT_ALLOWED
elif "w" not in access.parent_permissions:
return httputils.NOT_ALLOWED
etag = environ.get("HTTP_IF_MATCH", "")
if not item and etag:
# Etag asked but no item found: item has been removed
return httputils.PRECONDITION_FAILED
if item and etag and item.etag != etag:
# Etag asked but item not matching: item has changed
return httputils.PRECONDITION_FAILED
match = environ.get("HTTP_IF_NONE_MATCH", "") == "*"
if item and match:
# Creation asked but item found: item can't be replaced
return httputils.PRECONDITION_FAILED
if (tag != prepared_tag or
prepared_write_whole_collection != write_whole_collection):
(prepared_items, prepared_tag, prepared_write_whole_collection,
prepared_props, prepared_exc_info) = prepare(
vobject_items, path, content_type,
bool(rights.intersect(access.permissions, "Ww")),
bool(rights.intersect(access.parent_permissions, "w")),
tag, write_whole_collection)
props = prepared_props
if prepared_exc_info:
logger.warning(
"Bad PUT request on %r (prepare): %s", path, prepared_exc_info[1],
exc_info=prepared_exc_info)
return httputils.BAD_REQUEST
if write_whole_collection:
try:
etag = self._storage.create_collection(
path, prepared_items, props).etag
for item in prepared_items:
hook_notification_item = HookNotificationItem(
HookNotificationItemTypes.UPSERT,
access.path,
item.serialize()
)
self._hook.notify(hook_notification_item)
except ValueError as e:
logger.warning(
"Bad PUT request on %r (create_collection): %s", path, e, exc_info=True)
return httputils.BAD_REQUEST
else:
assert not isinstance(item, storage.BaseCollection)
prepared_item, = prepared_items
if (item and item.uid != prepared_item.uid or
not item and parent_item.has_uid(prepared_item.uid)):
return self._webdav_error_response(
client.CONFLICT, "%s:no-uid-conflict" % (
"C" if tag == "VCALENDAR" else "CR"))
href = posixpath.basename(pathutils.strip_path(path))
try:
etag = parent_item.upload(href, prepared_item).etag
hook_notification_item = HookNotificationItem(
HookNotificationItemTypes.UPSERT,
access.path,
prepared_item.serialize()
)
self._hook.notify(hook_notification_item)
except ValueError as e:
logger.warning(
"Bad PUT request on %r (upload): %s", path, e, exc_info=True)
return httputils.BAD_REQUEST
headers = {"ETag": etag}
return client.CREATED, headers, None
| 12,482
|
Python
|
.py
| 237
| 38.084388
| 181
| 0.584418
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,247
|
__init__.py
|
Kozea_Radicale/radicale/hook/__init__.py
|
import json
from enum import Enum
from typing import Sequence
from radicale import pathutils, utils
from radicale.log import logger
INTERNAL_TYPES: Sequence[str] = ("none", "rabbitmq")
def load(configuration):
"""Load the storage module chosen in configuration."""
try:
return utils.load_plugin(
INTERNAL_TYPES, "hook", "Hook", BaseHook, configuration)
except Exception as e:
logger.warning(e)
logger.warning("Hook \"%s\" failed to load, falling back to \"none\"." % configuration.get("hook", "type"))
configuration = configuration.copy()
configuration.update({"hook": {"type": "none"}}, "hook", privileged=True)
return utils.load_plugin(
INTERNAL_TYPES, "hook", "Hook", BaseHook, configuration)
class BaseHook:
def __init__(self, configuration):
"""Initialize BaseHook.
``configuration`` see ``radicale.config`` module.
The ``configuration`` must not change during the lifetime of
this object, it is kept as an internal reference.
"""
self.configuration = configuration
def notify(self, notification_item):
"""Upload a new or replace an existing item."""
raise NotImplementedError
class HookNotificationItemTypes(Enum):
CPATCH = "cpatch"
UPSERT = "upsert"
DELETE = "delete"
def _cleanup(path):
sane_path = pathutils.strip_path(path)
attributes = sane_path.split("/") if sane_path else []
if len(attributes) < 2:
return ""
return attributes[0] + "/" + attributes[1]
class HookNotificationItem:
def __init__(self, notification_item_type, path, content):
self.type = notification_item_type.value
self.point = _cleanup(path)
self.content = content
def to_json(self):
return json.dumps(
self,
default=lambda o: o.__dict__,
sort_keys=True,
indent=4
)
| 1,952
|
Python
|
.py
| 51
| 31.27451
| 115
| 0.648964
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,248
|
none.py
|
Kozea_Radicale/radicale/hook/none.py
|
from radicale import hook
class Hook(hook.BaseHook):
def notify(self, notification_item):
"""Notify nothing. Empty hook."""
| 138
|
Python
|
.py
| 4
| 30
| 41
| 0.712121
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,249
|
__init__.py
|
Kozea_Radicale/radicale/hook/rabbitmq/__init__.py
|
import pika
from pika.exceptions import ChannelWrongStateError, StreamLostError
from radicale import hook
from radicale.hook import HookNotificationItem
from radicale.log import logger
class Hook(hook.BaseHook):
def __init__(self, configuration):
super().__init__(configuration)
self._endpoint = configuration.get("hook", "rabbitmq_endpoint")
self._topic = configuration.get("hook", "rabbitmq_topic")
self._queue_type = configuration.get("hook", "rabbitmq_queue_type")
self._encoding = configuration.get("encoding", "stock")
self._make_connection_synced()
self._make_declare_queue_synced()
def _make_connection_synced(self):
parameters = pika.URLParameters(self._endpoint)
connection = pika.BlockingConnection(parameters)
self._channel = connection.channel()
def _make_declare_queue_synced(self):
self._channel.queue_declare(queue=self._topic, durable=True, arguments={"x-queue-type": self._queue_type})
def notify(self, notification_item):
if isinstance(notification_item, HookNotificationItem):
self._notify(notification_item, True)
def _notify(self, notification_item, recall):
try:
self._channel.basic_publish(
exchange='',
routing_key=self._topic,
body=notification_item.to_json().encode(
encoding=self._encoding
)
)
except Exception as e:
if (isinstance(e, ChannelWrongStateError) or
isinstance(e, StreamLostError)) and recall:
self._make_connection_synced()
self._notify(notification_item, False)
return
logger.error("An exception occurred during "
"publishing hook notification item: %s",
e, exc_info=True)
| 1,918
|
Python
|
.py
| 41
| 35.95122
| 114
| 0.632762
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,250
|
contact_multiple.vcf
|
Kozea_Radicale/radicale/tests/static/contact_multiple.vcf
|
BEGIN:VCARD
VERSION:3.0
UID:contact1
N:Contact1;;;;
FN:Contact1
END:VCARD
BEGIN:VCARD
VERSION:3.0
UID:contact2
N:Contact2;;;;
FN:Contact2
END:VCARD
| 148
|
Python
|
.tac
| 12
| 11.333333
| 14
| 0.838235
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,251
|
radicale.wsgi
|
Kozea_Radicale/radicale.wsgi
|
"""
Radicale WSGI file (mod_wsgi and uWSGI compliant).
"""
from radicale import application
| 94
|
Python
|
.wsgi
| 4
| 22
| 50
| 0.784091
|
Kozea/Radicale
| 3,268
| 426
| 211
|
GPL-3.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
11,252
|
setup.py
|
lmacken_pyrasite/setup.py
|
import sys
from setuptools import setup, find_packages
from distutils.command.build_py import build_py as _build_py
import platform
try:
# These imports are not used, but make
# tests pass smoothly on python2.7
import multiprocessing
import logging
except Exception:
pass
version = '2.0'
f = open('README.rst')
long_description = f.read().split('split here')[1]
f.close()
requirements = ['urwid']
if sys.version_info[0] == 3:
if sys.version_info[1] < 2:
requirements.append('argparse')
elif sys.version_info[0] == 2:
if sys.version_info[1] < 7:
requirements.append('argparse')
tests_require = ['nose']
class build_py(_build_py):
def run(self):
_build_py.run(self)
if platform.system() == 'Windows':
import os
try:
import winbuild
except:
self.announce("Could not find an microsoft compiler for supporting windows process injection", 2)
return
#can fail ?
dirs = [x for x in self.get_data_files() if x[0] == 'pyrasite'][0]
srcfile = os.path.join(dirs[1], 'win', 'inject_python.cpp')
out32exe = os.path.join(dirs[2], 'win', 'inject_python_32.exe')
out64exe = os.path.join(dirs[2], 'win', 'inject_python_64.exe')
try:
os.makedirs(os.path.dirname(out32exe))
except:
pass
try:
winbuild.compile(srcfile, out32exe, 'x86')
except:
self.announce("Could not find an x86 microsoft compiler for supporting injection to 32 bit python instances", 2)
try:
winbuild.compile(srcfile, out64exe, 'x64')
except:
self.announce("Could not find an x64 microsoft compiler for supporting injection to 64 bit python instances", 2)
setup(name='pyrasite',
version=version,
description="Inject code into a running Python process",
long_description=long_description,
keywords='debugging injection runtime',
author='Luke Macken',
author_email='lmacken@redhat.com',
url='http://pyrasite.com',
license='GPLv3',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
zip_safe=False,
install_requires=requirements,
tests_require=tests_require,
test_suite='nose.collector',
entry_points="""
[console_scripts]
pyrasite = pyrasite.main:main
pyrasite-memory-viewer = pyrasite.tools.memory_viewer:main
pyrasite-shell = pyrasite.tools.shell:shell
""",
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: GNU General Public License (GPL)',
'Topic :: System :: Monitoring',
'Topic :: Software Development :: Debuggers',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
],
cmdclass={'build_py': build_py}
)
| 3,025
|
Python
|
.py
| 84
| 29.440476
| 120
| 0.646096
|
lmacken/pyrasite
| 2,794
| 218
| 46
|
GPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,253
|
winbuild.py
|
lmacken_pyrasite/winbuild.py
|
from distutils import msvc9compiler
import subprocess
import os
def compile(filename, outputfilename, arch='x86', vcver=None):
if vcver == None:
if os.getenv('MSVCVER'):
vcver = float(os.getenv('MSVCVER'))
else:
vcver = msvc9compiler.get_build_version()
vcvars = msvc9compiler.find_vcvarsall(vcver)
if not vcvars: # My VS 2008 Standard Edition doesn't have vcvarsall.bat
vsbase = msvc9compiler.VS_BASE % vcver
productdir = msvc9compiler.Reg.get_value(r"%s\Setup\VC" % vsbase,
"productdir")
bat = 'vcvars%d.bat' % (arch == 'x86' and 32 or 64)
vcvars = os.path.join(productdir, 'bin', bat)
path = os.path.splitext(outputfilename)
objfilename = path[0] + '.obj'
p = subprocess.Popen('"%s" %s & cl %s /Fe%s /Fo%s' % (vcvars, arch, filename, outputfilename, objfilename),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
try:
stdout, stderr = p.communicate()
if p.wait() != 0:
raise Exception(stderr.decode("mbcs"))
os.remove(objfilename)
finally:
p.stdout.close()
p.stderr.close()
#try:
# compile('inject_python.cpp', 'inject_python_32.exe', 'x86', 10.0)
#except:
# pass
#try:
# compile('inject_python.cpp', 'inject_python_64.exe', 'amd64', 10.0)
#except:
# pass
| 1,435
|
Python
|
.py
| 37
| 30.675676
| 111
| 0.595272
|
lmacken/pyrasite
| 2,794
| 218
| 46
|
GPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,254
|
inspector.py
|
lmacken_pyrasite/pyrasite/inspector.py
|
# This file is part of pyrasite.
#
# pyrasite 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.
#
# pyrasite 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 pyrasite. If not, see <http://www.gnu.org/licenses/>.
#
# Copyright (C) 2011-2013 Red Hat, Inc., Luke Macken <lmacken@redhat.com>
import sys
import subprocess
encoding = sys.getdefaultencoding()
def inspect(pid, address):
"Return the value of an object in a given process at the specified address"
cmd = ' '.join([
'gdb --quiet -p %s -batch' % pid,
'-eval-command="print (PyObject *)%s"' % address,
])
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
for line in p.communicate()[0].decode(encoding).split('\n'):
if line.startswith('$1 = '):
return line[5:]
| 1,233
|
Python
|
.py
| 29
| 39.448276
| 79
| 0.719167
|
lmacken/pyrasite
| 2,794
| 218
| 46
|
GPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,255
|
reverse.py
|
lmacken_pyrasite/pyrasite/reverse.py
|
# This file is part of pyrasite.
#
# pyrasite 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.
#
# pyrasite 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 pyrasite. If not, see <http://www.gnu.org/licenses/>.
#
# Copyright (C) 2011-2013 Red Hat, Inc., Luke Macken <lmacken@redhat.com>
"""
:mod:`pyrasite.reverse` - Pyrasite Reverse Connection Payload
=============================================================
"""
import sys
import socket
import traceback
import threading
from code import InteractiveConsole
if sys.version_info[0] == 3:
from io import StringIO
else:
from StringIO import StringIO
import pyrasite
class ReverseConnection(threading.Thread, pyrasite.PyrasiteIPC):
"""A payload that connects to a given host:port and receives commands"""
host = 'localhost'
port = 9001
reliable = True
def __init__(self, host=None, port=None):
super(ReverseConnection, self).__init__()
self.sock = None
if host:
self.host = host
if port:
self.port = port
def on_connect(self):
"""Called when we successfuly connect to `self.host`"""
def on_command(self, cmd):
"""Called when the host sends us a command"""
def run(self):
running = True
while running:
try:
for res in socket.getaddrinfo(self.host, self.port,
socket.AF_UNSPEC, socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
try:
self.sock = socket.socket(af, socktype, proto)
try:
self.sock.connect(sa)
except socket.error:
self.sock.close()
self.sock = None
continue
except socket.error:
self.sock = None
continue
break
if not self.sock:
raise Exception('pyrasite cannot establish reverse ' +
'connection to %s:%d' % (self.host, self.port))
self.on_connect()
while running:
cmd = self.recv()
if cmd is None or cmd == "quit\n" or len(cmd) == 0:
running = False
else:
running = self.on_command(cmd)
except:
traceback.print_exc()
running = False
if not running:
self.close()
class ReversePythonConnection(ReverseConnection):
"""A reverse Python connection payload.
Executes Python commands and returns the output.
"""
def on_command(self, cmd):
buffer = StringIO()
sys.stdout = buffer
sys.stderr = buffer
output = ''
try:
exec(cmd)
output = buffer.getvalue()
except:
output = traceback.format_exc()
finally:
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
buffer.close()
self.send(output)
return True
class DistantInteractiveConsole(InteractiveConsole):
def __init__(self, ipc):
InteractiveConsole.__init__(self, globals())
self.ipc = ipc
self.set_buffer()
def set_buffer(self):
self.out_buffer = StringIO()
sys.stdout = sys.stderr = self.out_buffer
def unset_buffer(self):
sys.stdout, sys.stderr = sys.__stdout__, sys.__stderr__
value = self.out_buffer.getvalue()
self.out_buffer.close()
return value
def raw_input(self, prompt=""):
output = self.unset_buffer()
# payload format: 'prompt' ? '\n' 'output'
self.ipc.send('\n'.join((prompt, output)))
cmd = self.ipc.recv()
self.set_buffer()
return cmd
class ReversePythonShell(threading.Thread, pyrasite.PyrasiteIPC):
"""A reverse Python shell that behaves like Python interactive interpreter.
"""
host = 'localhost'
port = 9001
reliable = True
def __init__(self, host=None, port=None):
super(ReversePythonShell, self).__init__()
def run(self):
try:
for res in socket.getaddrinfo(self.host, self.port,
socket.AF_UNSPEC, socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
try:
self.sock = socket.socket(af, socktype, proto)
try:
self.sock.connect(sa)
except socket.error:
self.sock.close()
self.sock = None
continue
except socket.error:
self.sock = None
continue
break
if not self.sock:
raise Exception('pyrasite cannot establish reverse ' +
'connection to %s:%d' % (self.host, self.port))
DistantInteractiveConsole(self).interact()
except SystemExit:
pass
except:
traceback.print_exc(file=sys.__stderr__)
finally:
sys.stdout, sys.stderr = sys.__stdout__, sys.__stderr__
self.close()
| 5,832
|
Python
|
.py
| 156
| 26.307692
| 79
| 0.552305
|
lmacken/pyrasite
| 2,794
| 218
| 46
|
GPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,256
|
ipc.py
|
lmacken_pyrasite/pyrasite/ipc.py
|
# This file is part of pyrasite.
#
# pyrasite 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.
#
# pyrasite 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 pyrasite. If not, see <http://www.gnu.org/licenses/>.
#
# Copyright (C) 2011-2013 Red Hat, Inc., Luke Macken <lmacken@redhat.com>
"""
:mod:`pyrasite.ipc` - Pyrasite Inter-Python Communication
=========================================================
"""
import os
import stat
import socket
import struct
import tempfile
import traceback
import subprocess
import platform
from os.path import dirname, abspath, join
import pyrasite
class PyrasiteIPC(object):
"""Pyrasite Inter-Python Communication.
This object is used in communicating to or from another Python process.
It can perform a variety of tasks:
- Injection of the :class:`pyrasite.ReversePythonConnection` payload via
:meth:`PyrasiteIPC.connect()`, which causes the process to connect back
to a port that we are listening on. The connection with the process is
then available via `self.sock`.
- Python code can then be executed in the process using
:meth:`PyrasiteIPC.cmd`. Both stdout and stderr are returned.
- Low-level communication with the process, both reliably (via a length
header) or unreliably (raw data, ideal for use with netcat) with a
:class:`pyrasite.ReversePythonConnection` payload, via
:meth:`PyrasiteIPC.send(data)` and :meth:`PyrasiteIPC.recv(data)`.
The :class:`PyrasiteIPC` is subclassed by
:class:`pyrasite.tools.gui.Process` as well as
:class:`pyrasite.reverse.ReverseConnection`.
"""
# Allow subclasses to disable this and just send/receive raw data, as
# opposed to prepending a length header, to ensure reliability. The reason
# to enable 'unreliable' connections is so we can still use our reverse
# shell payloads with netcat.
reliable = True
def __init__(self, pid, reverse='ReversePythonConnection', timeout=5):
super(PyrasiteIPC, self).__init__()
self.pid = pid
self.sock = None
self.server_sock = None
self.hostname = None
self.port = None
self.reverse = reverse
self.timeout = float(timeout)
def __enter__(self):
self.connect()
return self
def __exit__(self, *args, **kwargs):
self.close()
@property
def title(self):
if not getattr(self, '_title', None):
if platform.system() == 'Windows':
p = subprocess.Popen('tasklist /v /fi "pid eq %d" /nh /fo csv' % self.pid,
stdout=subprocess.PIPE, shell=True)
tmp = p.communicate()[0].decode('utf-8').strip().split(',')
if tmp[-1] == '"N/A"':
self._title = tmp[0][1:-1]
else:
self._title = tmp[-1][1:-1]
else:
p = subprocess.Popen('ps --no-heading -o cmd= -p %d' % self.pid,
stdout=subprocess.PIPE, shell=True)
self._title = p.communicate()[0].decode('utf-8')
return self._title.strip()
def connect(self):
"""
Setup a communication socket with the process by injecting
a reverse subshell and having it connect back to us.
"""
self.listen()
self.inject()
self.wait()
def listen(self):
"""Listen on a random port"""
for res in socket.getaddrinfo('localhost', None, socket.AF_UNSPEC,
socket.SOCK_STREAM, 0, 0):
af, socktype, proto, canonname, sa = res
try:
self.server_sock = socket.socket(af, socktype, proto)
try:
self.server_sock.bind(sa)
self.server_sock.listen(1)
except socket.error:
self.server_sock.close()
self.server_sock = None
continue
except socket.error:
self.server_sock = None
continue
break
if not self.server_sock:
raise Exception('pyrasite was unable to setup a ' +
'local server socket')
else:
self.hostname, self.port = self.server_sock.getsockname()[0:2]
def create_payload(self):
"""Write out a reverse python connection payload with a custom port"""
(fd, filename) = tempfile.mkstemp()
tmp = os.fdopen(fd, 'w')
path = dirname(abspath(pyrasite.__file__))
payload = open(join(path, 'reverse.py'))
for line in payload.readlines():
if line.startswith('#'):
continue
line = line.replace('port = 9001', 'port = %d' % self.port)
if not self.reliable:
line = line.replace('reliable = True', 'reliable = False')
tmp.write(line)
tmp.write('%s().start()\n' % self.reverse)
tmp.close()
payload.close()
if platform.system() != 'Windows':
os.chmod(filename, stat.S_IREAD | stat.S_IRGRP | stat.S_IROTH)
return filename
def inject(self):
"""Inject the payload into the process."""
filename = self.create_payload()
pyrasite.inject(self.pid, filename)
os.unlink(filename)
def wait(self):
"""Wait for the injected payload to connect back to us"""
(clientsocket, address) = self.server_sock.accept()
self.sock = clientsocket
self.sock.settimeout(self.timeout)
self.address = address
def cmd(self, cmd):
"""
Send a python command to exec in the process and return the output
"""
self.send(cmd + '\n')
return self.recv()
def send(self, data):
"""Send arbitrary data to the process via self.sock"""
header = ''.encode('utf-8')
data = data.encode('utf-8')
if self.reliable:
header = struct.pack('<L', len(data))
self.sock.sendall(header + data)
def recv(self):
"""Receive a command from a given socket"""
if self.reliable:
header_data = self.recv_bytes(4)
if len(header_data) == 4:
msg_len = struct.unpack('<L', header_data)[0]
data = self.recv_bytes(msg_len).decode('utf-8')
if len(data) == msg_len:
return data
else:
return self.sock.recv(4096).decode('utf-8')
def recv_bytes(self, n):
"""Receive n bytes from a socket"""
data = ''.encode('utf-8')
while len(data) < n:
chunk = self.sock.recv(n - len(data))
if not chunk:
break
data += chunk
return data
def close(self):
try:
if self.sock:
self.sock.close()
if getattr(self, 'server_sock', None):
self.server_sock.close()
except:
traceback.print_exc()
def __repr__(self):
return "<%s %s>" % (self.__class__.__name__, self.pid)
| 7,601
|
Python
|
.py
| 187
| 31.15508
| 90
| 0.587781
|
lmacken/pyrasite
| 2,794
| 218
| 46
|
GPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,257
|
__init__.py
|
lmacken_pyrasite/pyrasite/__init__.py
|
__version__ = '2.0'
__all__ = ('inject', 'inspect', 'PyrasiteIPC',
'ReverseConnection', 'ReversePythonConnection')
__license__ = """\
pyrasite 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.
pyrasite 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 pyrasite. If not, see <http://www.gnu.org/licenses/>.\
"""
__copyright__ = "Copyright (C) 2011-2013 Red Hat, Inc."
from pyrasite.injector import inject
from pyrasite.inspector import inspect
from pyrasite.ipc import PyrasiteIPC
from pyrasite.reverse import ReverseConnection, ReversePythonConnection
| 992
|
Python
|
.py
| 20
| 47.9
| 71
| 0.783282
|
lmacken/pyrasite
| 2,794
| 218
| 46
|
GPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,258
|
injector.py
|
lmacken_pyrasite/pyrasite/injector.py
|
# This file is part of pyrasite.
#
# pyrasite 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.
#
# pyrasite 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 pyrasite. If not, see <http://www.gnu.org/licenses/>.
#
# Copyright (C) 2011-2013 Red Hat, Inc., Luke Macken <lmacken@redhat.com>
import os
import subprocess
import platform
def inject(pid, filename, verbose=False, gdb_prefix=''):
"""Executes a file in a running Python process."""
filename = os.path.abspath(filename)
gdb_cmds = [
'PyGILState_Ensure()',
'PyRun_SimpleString("'
'import sys; sys.path.insert(0, \\"%s\\"); '
'sys.path.insert(0, \\"%s\\"); '
'exec(open(\\"%s\\").read())")' %
(os.path.dirname(filename),
os.path.abspath(os.path.join(os.path.dirname(__file__), '..')),
filename),
'PyGILState_Release($1)',
]
p = subprocess.Popen('%sgdb -p %d -batch %s' % (gdb_prefix, pid,
' '.join(["-eval-command='call (void*) %s'" % cmd for cmd in gdb_cmds])),
shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
if verbose:
print(out)
print(err)
if platform.system() == 'Windows':
def inject_win(pid, filename, verbose=False, gdb_prefix=''):
if gdb_prefix == '':
gdb_prefix = os.path.join(os.path.dirname(__file__), 'win') + os.sep
filename = os.path.abspath(filename)
code = 'import sys; sys.path.insert(0, \\"%s\\"); sys.path.insert(0, \\"%s\\"); exec(open(\\"%s\\").read())' % (os.path.dirname(filename).replace('\\', '/'), os.path.abspath(os.path.join(os.path.dirname(__file__), '..')).replace('\\', '/'), filename.replace('\\', '/'))
p = subprocess.Popen('%sinject_python_32.exe %d \"%s\"' % (gdb_prefix, pid, code), shell = True, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
out, err = p.communicate()
if p.wait() == 25:
p = subprocess.Popen('%sinject_python_64.exe %d \"%s\"' % (gdb_prefix, pid, code), shell = True, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
out, err = p.communicate()
if verbose:
print(out)
print(err)
inject = inject_win
| 2,701
|
Python
|
.py
| 55
| 42.672727
| 277
| 0.618615
|
lmacken/pyrasite
| 2,794
| 218
| 46
|
GPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,259
|
main.py
|
lmacken_pyrasite/pyrasite/main.py
|
# This file is part of pyrasite.
#
# pyrasite 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.
#
# pyrasite 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 pyrasite. If not, see <http://www.gnu.org/licenses/>.
#
# Copyright (C) 2011-2013 Red Hat, Inc.
import os
import sys
import argparse
import subprocess
import pyrasite
def ptrace_check():
ptrace_scope = '/proc/sys/kernel/yama/ptrace_scope'
if os.path.exists(ptrace_scope):
f = open(ptrace_scope)
value = int(f.read().strip())
f.close()
if value == 1:
print("WARNING: ptrace is disabled. Injection will not work.")
print("You can enable it by running the following:")
print("echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope")
print("")
else:
getsebool = '/usr/sbin/getsebool'
if os.path.exists(getsebool):
p = subprocess.Popen([getsebool, 'deny_ptrace'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
if str(out) == 'deny_ptrace --> on\n':
print("WARNING: ptrace is disabled. Injection will not work.")
print("You can enable it by running the following:")
print("sudo setsebool -P deny_ptrace=off")
print("")
def get_payload_dir():
return os.path.join(os.path.dirname(pyrasite.__file__), 'payloads')
def list_payloads():
return sorted(fn for fn in os.listdir(get_payload_dir())
if fn.endswith('.py') and not fn.startswith('_'))
def expand_payload(payload):
"""If a standard payload with this name exists, return its full path.
Otherwise return the input value unchanged.
"""
if os.path.sep not in payload:
fn = os.path.join(get_payload_dir(), payload)
if os.path.isfile(fn):
return fn
return payload
def main():
ptrace_check()
parser = argparse.ArgumentParser(
description='pyrasite - inject code into a running python process',
epilog="For updates, visit https://github.com/lmacken/pyrasite")
parser.add_argument('pid', nargs='?',
help="The ID of the process to inject code into")
parser.add_argument('payload', nargs='?', default='',
help="The Python script to be executed inside the"
" running process. Can be one of the standard"
" payloads (see --list-payloads) or a filname.")
parser.add_argument('-l', '--list-payloads', help='List standard payloads',
default=False, action='store_const', const=True)
parser.add_argument('--gdb-prefix', dest='gdb_prefix',
help='GDB prefix (if specified during installation)',
default="")
parser.add_argument('--verbose', dest='verbose', help='Verbose mode',
default=False, action='store_const', const=True)
parser.add_argument('--output', dest='output_type', default='procstreams',
action='store',
help="Set where output is to be printed. 'procstreams'"
" prints output in stdout/stderr of running process"
" and 'localterm' prints output in local terminal.")
parser.add_argument('--ipc-timeout', dest='ipc_timeout', default=5,
action='store', type=int,
help="The number of seconds to wait for the injected"
" code to reply over IPC before giving up.")
if len(sys.argv) == 1:
parser.print_help()
sys.exit(1)
args = parser.parse_args()
if args.list_payloads:
print("Available payloads:")
for payload in list_payloads():
print(" %s" % payload)
sys.exit()
# Make sure the output type is valid (procstreams || localterm)
if args.output_type != 'procstreams' and args.output_type != 'localterm':
print("Error: --output arg must be 'procstreams' or 'localterm'")
sys.exit(5)
try:
pid = int(args.pid)
except ValueError:
print("Error: The first argument must be a pid")
sys.exit(2)
filename = expand_payload(args.payload)
if filename:
if not os.path.exists(filename):
print("Error: Invalid path or file doesn't exist")
sys.exit(3)
else:
print("Error: The second argument must be a filename or a payload name")
sys.exit(4)
if args.output_type == 'localterm':
# Create new IPC connection to the process.
ipc = pyrasite.PyrasiteIPC(pid, 'ReversePythonConnection',
timeout=args.ipc_timeout)
ipc.connect()
print("Pyrasite Shell %s" % pyrasite.__version__)
print("Connected to '%s'" % ipc.title)
# Read in the payload
fd = open(filename)
payload = fd.read()
fd.close
# Run the payload, print output, close ipc connection
print(ipc.cmd(payload))
ipc.close()
else:
pyrasite.inject(pid, filename, verbose=args.verbose,
gdb_prefix=args.gdb_prefix)
if __name__ == '__main__':
main()
| 5,770
|
Python
|
.py
| 129
| 34.976744
| 81
| 0.606589
|
lmacken/pyrasite
| 2,794
| 218
| 46
|
GPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,260
|
shell.py
|
lmacken_pyrasite/pyrasite/tools/shell.py
|
# This file is part of pyrasite.
#
# pyrasite 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.
#
# pyrasite 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 pyrasite. If not, see <http://www.gnu.org/licenses/>.
#
# Copyright (C) 2011-2013 Red Hat, Inc., Luke Macken <lmacken@redhat.com>
import os
import sys
import pyrasite
def shell():
"""Open a Python shell in a running process"""
usage = "Usage: pyrasite-shell <PID>"
if not len(sys.argv) == 2:
print(usage)
sys.exit(1)
try:
pid = int(sys.argv[1])
except ValueError:
print(usage)
sys.exit(1)
ipc = pyrasite.PyrasiteIPC(pid, 'ReversePythonShell',
timeout=os.getenv('PYRASITE_IPC_TIMEOUT') or 5)
ipc.connect()
print("Pyrasite Shell %s" % pyrasite.__version__)
print("Connected to '%s'" % ipc.title)
prompt, payload = ipc.recv().split('\n', 1)
print(payload)
try:
import readline
except ImportError:
pass
# py3k compat
try:
input_ = raw_input
except NameError:
input_ = input
try:
while True:
try:
input_line = input_(prompt)
except EOFError:
input_line = 'exit()'
print('')
except KeyboardInterrupt:
input_line = 'None'
print('')
ipc.send(input_line)
payload = ipc.recv()
if payload is None:
break
prompt, payload = payload.split('\n', 1)
if payload != '':
print(payload)
except:
print('')
raise
finally:
ipc.close()
if __name__ == '__main__':
shell()
| 2,186
|
Python
|
.py
| 70
| 24
| 78
| 0.601522
|
lmacken/pyrasite
| 2,794
| 218
| 46
|
GPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,261
|
memory_viewer.py
|
lmacken_pyrasite/pyrasite/tools/memory_viewer.py
|
# This file is part of pyrasite.
#
# pyrasite 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.
#
# pyrasite 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 pyrasite. If not, see <http://www.gnu.org/licenses/>.
#
# Copyright (C) 2011-2013 Red Hat, Inc.
# Authors: Luke Macken <lmacken@redhat.com>
"""
An interface for visualizing the output of of the dump-memory payload.
When selecting an object, we attach to the running process and obtain
the value of the object itself.
"""
__version__ = '1.0'
import os
import re
import sys
import urwid
import urwid.raw_display
from meliae import loader
from os.path import join, abspath, dirname
import pyrasite
class PyrasiteMemoryViewer(object):
palette = [
('body', 'black', 'light gray', 'standout'),
('header', 'white', 'dark red', 'bold'),
('button normal', 'light gray', 'dark blue', 'standout'),
('button select', 'white', 'dark green'),
('button disabled', 'dark gray', 'dark blue'),
('bigtext', 'white', 'black'),
('object_output', 'light gray', 'black'),
('exit', 'white', 'dark red'),
]
def __init__(self, pid, objects):
self.pid = pid
self.objects = objects
self.summary = objects.summarize()
def create_radio_button(self, g, name, obj, fn, disabled=False):
w = urwid.RadioButton(g, name, False, on_state_change=fn)
w.obj = obj
if disabled:
w = urwid.AttrWrap(w, 'button normal', 'button disabled')
else:
w = urwid.AttrWrap(w, 'button normal', 'button select')
return w
def create_disabled_radio_button(self, name):
w = urwid.Text(' ' + name)
w = urwid.AttrWrap(w, 'button disabled')
return w
def display_object(self, w, state):
if state:
value = pyrasite.inspect(self.pid, w.obj.max_address)
if not value:
value = 'Unable to inspect remote object. Make sure you have ' \
'the python-debuginfo package installed.'
self.object_output.set_text(value)
def get_object_buttons(self, group=[]):
buttons = []
for i, line in enumerate(str(self.summary).split('\n')):
if i in (0, 1):
rb = self.create_disabled_radio_button(line)
else:
obj = self.summary.summaries[i - 2]
rb = self.create_radio_button(group, line, obj,
self.display_object)
buttons.append(rb)
return buttons
def setup_view(self):
self.object_buttons = self.get_object_buttons()
# Title
self.bigtext = urwid.BigText('pyrasite ' + __version__, None)
self.bigtext.set_font(urwid.Thin6x6Font())
bt = urwid.Padding(self.bigtext, 'left', None)
bt = urwid.AttrWrap(bt, 'bigtext')
# Create the object output
self.object_output = urwid.Text("", wrap='any')
ca = urwid.AttrWrap(self.object_output, 'object_output')
# Select the first object
self.object_buttons[2].set_state(True)
# ListBox
obj_out = urwid.Pile([urwid.Divider(), ca])
objects = urwid.Pile(self.object_buttons)
l = [objects, obj_out]
w = urwid.ListBox(urwid.SimpleListWalker(l))
# Frame
w = urwid.AttrWrap(w, 'body')
w = urwid.Frame(header=bt, body=w)
# Exit message
exit = urwid.BigText(('exit', " Quit? "), urwid.Thin6x6Font())
exit = urwid.Overlay(exit, w, 'center', None, 'middle', None)
return w, exit
def unhandled_input(self, key):
if key in ('f8', 'q'):
self.loop.widget = self.exit_view
return True
if self.loop.widget != self.exit_view:
return
if key in ('y', 'Y'):
raise urwid.ExitMainLoop()
if key in ('n', 'N'):
self.loop.widget = self.view
return True
def main(self):
self.view, self.exit_view = self.setup_view()
self.loop = urwid.MainLoop(self.view, self.palette,
unhandled_input=self.unhandled_input)
self.loop.run()
def main():
if len(sys.argv) != 2:
print("[ pyrasite memory viewer ]\n")
print("Usage: %s <pid> <objects.json>" % sys.argv[0])
print("\n pid - the running process id")
print("")
sys.exit(1)
pid = int(sys.argv[1])
payload = abspath(join(dirname(__file__), '..',
'payloads', 'dump_memory.py'))
pyrasite.inject(pid, payload)
filename = '/tmp/pyrasite-%d-objects.json' % pid
# Work around bug caused by meliae dumping unicode strings:
# https://bugs.launchpad.net/meliae/+bug/876810
with open(filename) as sample_file, open(filename + '.tmp', 'w') as output_file:
pattern = re.compile(r"(?<!\\)\\u([dD][0-9a-fA-F]{3,3})")
for line in sample_file:
output_file.write(pattern.sub("#S\g<1>", line))
os.rename(filename + '.tmp', filename)
objects = loader.load(filename)
objects.compute_referrers()
PyrasiteMemoryViewer(pid=pid, objects=objects).main()
if '__main__' == __name__:
main()
| 5,767
|
Python
|
.py
| 140
| 33.414286
| 84
| 0.599785
|
lmacken/pyrasite
| 2,794
| 218
| 46
|
GPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,262
|
dump_modules.py
|
lmacken_pyrasite/pyrasite/payloads/dump_modules.py
|
import sys
for name in sorted(sys.modules):
print('%s: %s' % (name, sys.modules[name]))
| 93
|
Python
|
.py
| 3
| 28.333333
| 47
| 0.662921
|
lmacken/pyrasite
| 2,794
| 218
| 46
|
GPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,263
|
dump_stacks.py
|
lmacken_pyrasite/pyrasite/payloads/dump_stacks.py
|
import sys, traceback
for thread, frame in sys._current_frames().items():
print('Thread 0x%x' % thread)
traceback.print_stack(frame)
print()
| 154
|
Python
|
.py
| 5
| 27.2
| 51
| 0.702703
|
lmacken/pyrasite
| 2,794
| 218
| 46
|
GPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,264
|
dump_memory.py
|
lmacken_pyrasite/pyrasite/payloads/dump_memory.py
|
# "meliae" provides a way to dump python memory usage information to a JSON
# disk format, which can then be parsed into useful things like graph
# representations.
#
# https://launchpad.net/meliae
# http://jam-bazaar.blogspot.com/2009/11/memory-debugging-with-meliae.html
import os, meliae.scanner, platform
if platform.system() == 'Windows':
temp = os.getenv('TEMP', os.getenv('TMP', '/temp'))
path = os.path.join(temp, 'pyrasite-%d-objects.json' % os.getpid())
else:
path = '/tmp/pyrasite-%d-objects.json' % os.getpid()
meliae.scanner.dump_all_objects(path)
| 575
|
Python
|
.py
| 13
| 42.153846
| 75
| 0.732143
|
lmacken/pyrasite
| 2,794
| 218
| 46
|
GPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,265
|
reverse_shell.py
|
lmacken_pyrasite/pyrasite/payloads/reverse_shell.py
|
# This file is part of pyrasite.
#
# pyrasite 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.
#
# pyrasite 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 pyrasite. If not, see <http://www.gnu.org/licenses/>.
#
# Copyright (C) 2011-2013 Red Hat, Inc., Luke Macken <lmacken@redhat.com>
import pyrasite
class ReverseShell(pyrasite.ReverseConnection):
reliable = False # This payload is designed to be used with netcat
port = 9001
def on_connect(self):
uname = pyrasite.utils.run('uname -a')[1]
self.send("%sType 'quit' to exit\n%% " % uname)
def on_command(self, cmd):
p, out, err = pyrasite.utils.run(cmd)
if err:
out += err
self.send(out + '\n% ')
return True
ReverseShell().start()
| 1,213
|
Python
|
.py
| 30
| 36.7
| 73
| 0.71198
|
lmacken/pyrasite
| 2,794
| 218
| 46
|
GPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,266
|
reverse_python_shell.py
|
lmacken_pyrasite/pyrasite/payloads/reverse_python_shell.py
|
# This file is part of pyrasite.
#
# pyrasite 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.
#
# pyrasite 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 pyrasite. If not, see <http://www.gnu.org/licenses/>.
#
# Copyright (C) 2011-2013 Red Hat, Inc., Luke Macken <lmacken@redhat.com>
import sys
import pyrasite
class ReversePythonShell(pyrasite.ReversePythonConnection):
port = 9001
reliable = False
def on_connect(self):
self.send("Python %s\nType 'quit' to exit\n>>> " % sys.version)
ReversePythonShell().start()
| 988
|
Python
|
.py
| 24
| 39.166667
| 73
| 0.7625
|
lmacken/pyrasite
| 2,794
| 218
| 46
|
GPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,267
|
test_cli.py
|
lmacken_pyrasite/pyrasite/tests/test_cli.py
|
# This file is part of pyrasite.
#
# pyrasite 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.
#
# pyrasite 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 pyrasite. If not, see <http://www.gnu.org/licenses/>.
#
# Copyright (C) 2013 Red Hat, Inc., Luke Macken <lmacken@redhat.com>
import os
import sys
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
from pyrasite.main import main
class TestCLI(object):
def test_usage(self):
sys.argv = ['pyrasite']
try:
main()
except SystemExit:
exit_code = sys.exc_info()[1].code
assert exit_code == 1, exit_code
def test_list_payloads(self):
sys.argv = ['pyrasite', '-l']
stdout = sys.stdout
sys.stdout = StringIO()
try:
main()
except SystemExit:
pass
value = sys.stdout.getvalue()
sys.stdout = stdout
assert 'Available payloads:' in value, repr(value)
assert 'helloworld.py' in value, repr(value)
def test_invalid_pid(self):
sys.argv = ['pyrasite', 'foo', 'bar']
stdout = sys.stdout
sys.stdout = StringIO()
try:
main()
except SystemExit:
exit_code = sys.exc_info()[1].code
assert exit_code == 2, exit_code
value = sys.stdout.getvalue()
sys.stdout = stdout
assert 'Error: The first argument must be a pid' in value, repr(value)
def test_invalid_payload(self):
sys.argv = ['pyrasite', str(os.getpid()), 'foo']
stdout = sys.stdout
sys.stdout = StringIO()
try:
main()
except SystemExit:
exit_code = sys.exc_info()[1].code
assert exit_code == 3, exit_code
value = sys.stdout.getvalue()
sys.stdout = stdout
assert "Error: Invalid path or file doesn't exist" in value, repr(value)
def test_injection(self):
sys.argv = ['pyrasite', str(os.getpid()), 'helloworld.py']
stdout = sys.stdout
sys.stdout = StringIO()
main()
value = sys.stdout.getvalue()
sys.stdout = stdout
assert "Hello World!" in value, repr(value)
| 2,669
|
Python
|
.py
| 75
| 28.6
| 80
| 0.629787
|
lmacken/pyrasite
| 2,794
| 218
| 46
|
GPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,268
|
test_ipc.py
|
lmacken_pyrasite/pyrasite/tests/test_ipc.py
|
# This file is part of pyrasite.
#
# pyrasite 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.
#
# pyrasite 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 pyrasite. If not, see <http://www.gnu.org/licenses/>.
#
# Copyright (C) 2011-2013 Red Hat, Inc.
import os
import sys
from nose.plugins.skip import SkipTest
import pyrasite
from pyrasite.tests.utils import run_program, generate_program, stop_program
class TestIPCContextManager(object):
def setUp(self):
self.prog = generate_program()
self.p = run_program(self.prog)
def tearDown(self):
stop_program(self.p)
def test_context_manager(self):
# Check that we're on a version of python that
# supports context managers
info = sys.version_info
major, minor = info[0], info[1]
if major <= 2 and minor <= 5:
raise SkipTest("Context Managers not supported on Python<=2.5")
# Otherwise import a module which contains modern syntax.
# It really contains our test case, but we have pushed it out into
# another module so that python 2.4 never sees it.
import pyrasite.tests.context_manager_case
pyrasite.tests.context_manager_case.context_manager_business(self)
class TestIPC(object):
def setUp(self):
self.prog = generate_program()
self.p = run_program(self.prog)
self.ipc = pyrasite.PyrasiteIPC(self.p.pid)
def tearDown(self):
stop_program(self.p)
self.ipc.close()
def test_listen(self):
self.ipc.listen()
assert self.ipc.server_sock
assert self.ipc.hostname
assert self.ipc.port
assert self.ipc.server_sock.getsockname()[1] == self.ipc.port
def test_create_payload(self):
self.ipc.listen()
payload = self.ipc.create_payload()
assert os.path.exists(payload)
code = open(payload)
compile(code.read(), payload, 'exec')
code.close()
os.unlink(payload)
def test_connect(self):
self.ipc.connect()
assert self.ipc.sock
assert self.ipc.address
def test_cmd(self):
self.ipc.connect()
assert self.ipc.cmd('print("mu")') == 'mu\n'
def test_unreliable(self):
self.ipc.reliable = False
self.ipc.connect()
out = self.ipc.cmd('print("mu")')
assert out == 'mu\n', out
def test_repr(self):
assert repr(self.ipc)
def test_title(self):
assert self.ipc.title
| 2,941
|
Python
|
.py
| 77
| 31.896104
| 76
| 0.674402
|
lmacken/pyrasite
| 2,794
| 218
| 46
|
GPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,269
|
utils.py
|
lmacken_pyrasite/pyrasite/tests/utils.py
|
# This file is part of pyrasite.
#
# pyrasite 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.
#
# pyrasite 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 pyrasite. If not, see <http://www.gnu.org/licenses/>.
#
# Copyright (C) 2011-2013 Red Hat, Inc., Luke Macken <lmacken@redhat.com>
import os
import sys
import glob
import time
import textwrap
import tempfile
import subprocess
def generate_program(threads=1):
(fd, filename) = tempfile.mkstemp()
tmp = os.fdopen(fd, 'w')
script = textwrap.dedent("""
import os, time, threading
running = True
pidfile = '/tmp/pyrasite_%d' % os.getpid()
open(pidfile, 'w').close()
def cpu_bound():
i = 0
while running:
i += 1
""")
# CPU-bound threads
for t in range(threads):
script += "threading.Thread(target=cpu_bound).start()\n"
script += textwrap.dedent("""
while os.path.exists(pidfile):
time.sleep(0.1)
running = False
""")
tmp.write(script)
tmp.close()
return filename
def run_program(program, exe='/usr/bin/python'):
p = subprocess.Popen([exe, program],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
flag = '/tmp/pyrasite_%d' % p.pid
i = 0
while not os.path.exists(flag):
time.sleep(0.1)
i += 1
if i > 100:
raise Exception("Program never touched pid file!")
return p
def stop_program(p):
os.unlink('/tmp/pyrasite_%d' % p.pid)
def interpreters():
for exe in glob.glob('/usr/bin/python*.*'):
try:
int(exe.split('.')[-1])
except ValueError:
continue # skip python2.7-config, etc
yield exe
| 2,185
|
Python
|
.py
| 68
| 26.647059
| 73
| 0.646584
|
lmacken/pyrasite
| 2,794
| 218
| 46
|
GPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,270
|
test_code_injection.py
|
lmacken_pyrasite/pyrasite/tests/test_code_injection.py
|
# This file is part of pyrasite.
#
# pyrasite 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.
#
# pyrasite 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 pyrasite. If not, see <http://www.gnu.org/licenses/>.
#
# Copyright (C) 2011-2013 Red Hat, Inc., Luke Macken <lmacken@redhat.com>
import os
import sys
import subprocess
import pyrasite
from pyrasite.tests.utils import generate_program, run_program, stop_program, \
interpreters
class TestCodeInjection(object):
def assert_output_contains(self, stdout, stderr, text):
assert text in str(stdout), \
"Code injection failed: %s\n%s" % (stdout, stderr)
def test_injecting_into_all_interpreters(self):
program = generate_program()
try:
for exe in interpreters():
print("sys.executable = %s" % sys.executable)
print("injecting into %s" % exe)
p = run_program(program, exe=exe)
pyrasite.inject(p.pid,
'pyrasite/payloads/helloworld.py', verbose=True)
stop_program(p)
stdout, stderr = p.communicate()
self.assert_output_contains(stdout, stderr, 'Hello World!')
finally:
os.unlink(program)
def test_many_payloads_into_program_with_many_threads(self):
program = generate_program(threads=25)
num_payloads = 5
try:
for exe in interpreters():
p = run_program(program, exe=exe)
for i in range(num_payloads):
pyrasite.inject(p.pid,
'pyrasite/payloads/helloworld.py', verbose=True)
stop_program(p)
stdout, stderr = p.communicate()
count = 0
for line in stdout.decode('utf-8').split('\n'):
if line.strip() == 'Hello World!':
count += 1
assert count == num_payloads, "Read %d hello worlds" % count
finally:
os.unlink(program)
def test_pyrasite_script(self):
program = generate_program()
try:
for exe in interpreters():
print("sys.executable = %s" % sys.executable)
print("injecting into %s" % exe)
p = run_program(program, exe=exe)
subprocess.call([sys.executable, 'pyrasite/main.py',
str(p.pid), 'pyrasite/payloads/helloworld.py'],
env={'PYTHONPATH': os.getcwd()})
stop_program(p)
stdout, stderr = p.communicate()
self.assert_output_contains(stdout, stderr, 'Hello World!')
finally:
os.unlink(program)
| 3,213
|
Python
|
.py
| 73
| 33.054795
| 79
| 0.59361
|
lmacken/pyrasite
| 2,794
| 218
| 46
|
GPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,271
|
context_manager_case.py
|
lmacken_pyrasite/pyrasite/tests/context_manager_case.py
|
""" This is kept in a separate file so that python2.4 never picks it up. """
import pyrasite
def context_manager_business(case):
# Check that the context manager injects ipc correctly.
with pyrasite.PyrasiteIPC(case.p.pid) as ipc:
assert ipc.cmd('print("mu")') == 'mu\n'
# Check that the context manager closes the ipc correctly.
try:
ipc.cmd('print("mu")')
assert False, "The connection was not closed."
except IOError as e:
assert "Bad file descriptor" in str(e)
| 521
|
Python
|
.py
| 12
| 37.75
| 76
| 0.679208
|
lmacken/pyrasite
| 2,794
| 218
| 46
|
GPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,272
|
inject_python.cpp
|
lmacken_pyrasite/pyrasite/win/inject_python.cpp
|
#include <stdio.h>
#include <Windows.h>
//TODO
// support both ansi and unicode in the code (path for injection might have non english letters), how does python handle unicode in PyRun_SimpleString ?
// i checked on windows 7 64bit running 32bit python 2.7, check on other windows versions, and other python versions
// try maybe to write a code to auto figure out in which modules the Python functions are, maybe with EnumProcessModules
// do i need to statically compile the runtime libraries here ? (compile with VS2008 which is python 2.7 runtime maybe?)
// check the 64bit process injection especially in the context of ASLR
// in python 64 bit building, does disttools choose the 64 bit compiler?
// if python extension restore previous privilieges after running ?
// set only the privilieges needed for what i want to do..
// itanium support?
// Can be compiled in visual studio command prompt with: cl.exe inject_python.cpp
#pragma comment(lib, "kernel32.lib")
#pragma comment(lib, "user32.lib")
#pragma comment(lib, "advapi32.lib")
int RaisePrivileges()
{
int retCode = 0;
HANDLE hToken;
TOKEN_PRIVILEGES tp;
TOKEN_PRIVILEGES oldtp;
DWORD dwSize = sizeof(TOKEN_PRIVILEGES);
LUID luid;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
{
retCode = 1;
goto error1;
}
if (!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &luid))
{
retCode = 2;
goto error2;
}
ZeroMemory(&tp, sizeof(tp));
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if (!AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), &oldtp, &dwSize))
{
retCode = 3;
goto error2;
}
error2:
CloseHandle(hToken);
error1:
return retCode;
}
typedef struct
{
HMODULE (__stdcall *pGetModuleHandle)(LPCSTR);
FARPROC (__stdcall *pGetProcAddress)(HMODULE, LPCSTR);
char ModuleName[9];
char PyGILState_Ensure[18];
char PyRun_SimpleString[19];
char PyGILState_Release[19];
char *Code;
} REMOTEDATA;
static DWORD WINAPI ExecutePythonCode(REMOTEDATA *data)
{
DWORD retCode = 0;
HMODULE hModule = data->pGetModuleHandle(data->ModuleName);
if (hModule != NULL)
{
int (__cdecl *a)() = reinterpret_cast<int (__cdecl *)()>(data->pGetProcAddress(hModule, data->PyGILState_Ensure));
if (a != NULL)
{
int ret = a();
void (__cdecl *b)(char *) = reinterpret_cast<void (__cdecl *)(char *)>(data->pGetProcAddress(hModule, data->PyRun_SimpleString));
if (b != NULL)
{
b(data->Code);
} else {
retCode = 3;
}
void (__cdecl *c)(int) = reinterpret_cast<void (__cdecl *)(int)>(data->pGetProcAddress(hModule, data->PyGILState_Release));
if (c != NULL)
{
c(ret);
} else {
retCode = 4;
}
} else {
retCode = 2;
}
} else {
retCode = 1;
}
return retCode;
}
static void AfterExecutePythonCode()
{
}
int InjectPythonCode(HANDLE hProcess, const char *code, char *moduleName)
{
int retCode = 0;
REMOTEDATA data;
int cbCodeSize = (PBYTE)AfterExecutePythonCode - (PBYTE)ExecutePythonCode;
void* remoteCodeString = VirtualAllocEx(hProcess, NULL, strlen(code) + 1, MEM_COMMIT, PAGE_READWRITE);
if (remoteCodeString == NULL)
{
retCode = 1;
goto error1;
}
void* remoteCode = VirtualAllocEx(hProcess, NULL, cbCodeSize, MEM_COMMIT, PAGE_EXECUTE);
if (remoteCode == NULL)
{
retCode = 2;
goto error2;
}
void* remoteData = VirtualAllocEx(hProcess, NULL, sizeof(data), MEM_COMMIT, PAGE_READWRITE);
if (remoteData == NULL)
{
retCode = 3;
goto error3;
}
if (!WriteProcessMemory(hProcess, remoteCodeString, (void*)code, strlen(code) + 1, NULL))
{
retCode = 4;
goto error3;
}
data.pGetModuleHandle = GetModuleHandle;
data.pGetProcAddress = GetProcAddress;
strcpy_s(data.ModuleName, moduleName);
strcpy_s(data.PyGILState_Ensure, "PyGILState_Ensure");
strcpy_s(data.PyRun_SimpleString, "PyRun_SimpleString");
strcpy_s(data.PyGILState_Release, "PyGILState_Release");
data.Code = (char *)remoteCodeString;
if (!WriteProcessMemory(hProcess, remoteData, (void*)&data, sizeof(data), NULL))
{
retCode = 5;
goto error3;
}
if (!WriteProcessMemory(hProcess, remoteCode, (void*)ExecutePythonCode, cbCodeSize, NULL))
{
retCode = 6;
goto error3;
}
HANDLE hRemoteThread = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)remoteCode, remoteData, 0, NULL);
if (!hRemoteThread)
{
retCode = 7;
goto error3;
}
if (WaitForSingleObject(hRemoteThread, INFINITE) == WAIT_FAILED)
{
retCode = 8;
goto error4;
}
DWORD exitCode;
if (!GetExitCodeThread(hRemoteThread, &exitCode))
{
retCode = 9;
goto error4;
}
if (exitCode != 0)
{
retCode = 10;
goto error4;
}
error4:
CloseHandle(hRemoteThread);
error3:
VirtualFreeEx(hProcess, remoteData, sizeof(data), MEM_RELEASE);
error2:
VirtualFreeEx(hProcess, remoteCode, cbCodeSize, MEM_RELEASE);
error1:
VirtualFreeEx(hProcess, remoteCodeString, strlen(code) + 1, MEM_RELEASE);
return retCode;
}
int InjectPythonCodeToPID(DWORD pid, const char *code)
{
char versions[][9] = { "Python36", "Python35", "Python34", "Python33", "Python32", "Python31", "Python30", "Python27", "Python26", "Python25", "Python24" };
unsigned int numVersions = 11;
unsigned int i;
int retCode = 0;
int ret;
BOOL is32Bit;
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pid);
if (!hProcess)
{
retCode = 1;
goto error1;
}
//TODO this requires windows xp an above, later check if the function exists first...
if (!IsWow64Process(hProcess, &is32Bit))
{
retCode = 2;
goto error2;
}
#ifdef _WIN64
if (is32Bit)
{
retCode = 5;
goto error2;
}
#else
BOOL amI32Bit;
IsWow64Process(GetCurrentProcess(), &amI32Bit);
if (amI32Bit && !is32Bit)
{
retCode = 5;
goto error2;
}
#endif
for (i = 0; i < numVersions; ++i)
{
ret = InjectPythonCode(hProcess, code, versions[i]);
if (ret == 0)
{
break;
}
if (ret != 10)
{
retCode = 3;
goto error2;
}
}
if (ret != 0)
{
retCode = 4;
goto error2;
}
error2:
CloseHandle(hProcess);
error1:
return retCode;
}
int main(int argc, char *argv[])
{
if (argc != 3)
{
fprintf(stderr, "Usage: %s <pid> <code>\n", argv[0]);
return 1;
}
DWORD pid = atoi(argv[1]);
char* code = argv[2];
int ret;
ret = RaisePrivileges();
if (ret)
{
fprintf(stderr, "Could not raise privileges, return value %d, error code %d\n", ret, GetLastError());
return 10 + ret;
}
ret = InjectPythonCodeToPID(pid, code);
if (ret)
{
fprintf(stderr, "Could not inject code, return value %d, error code %d\n", ret, GetLastError());
return 20 + ret;
}
return 0;
}
| 6,614
|
Python
|
.py
| 252
| 23.873016
| 157
| 0.715411
|
lmacken/pyrasite
| 2,794
| 218
| 46
|
GPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,273
|
conf.py
|
lmacken_pyrasite/docs/conf.py
|
# -*- coding: utf-8 -*-
#
# Pyrasite documentation build configuration file, created by
# sphinx-quickstart on Mon Feb 13 02:40:02 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.autosummary']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'pyrasite'
copyright = u'2011-2013, Red Hat, Inc., Luke Macken'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '2.0'
# The full version, including alpha/beta/rc tags.
release = '2.0beta'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'Pyrasitedoc'
# -- Options for LaTeX output --------------------------------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'Pyrasite.tex', u'Pyrasite Documentation',
u'Luke Macken', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'pyrasite', u'Pyrasite Documentation',
[u'Luke Macken'], 1)
]
| 7,131
|
Python
|
.py
| 159
| 43.389937
| 82
| 0.730074
|
lmacken/pyrasite
| 2,794
| 218
| 46
|
GPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,274
|
reverse_python_shell.py
|
lmacken_pyrasite/pyrasite/payloads/reverse_python_shell.py
|
# This file is part of pyrasite.
#
# pyrasite 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.
#
# pyrasite 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 pyrasite. If not, see <http://www.gnu.org/licenses/>.
#
# Copyright (C) 2011-2013 Red Hat, Inc., Luke Macken <lmacken@redhat.com>
import sys
import pyrasite
class ReversePythonShell(pyrasite.ReversePythonConnection):
port = 9001
reliable = False
def on_connect(self):
self.send("Python %s\nType 'quit' to exit\n>>> " % sys.version)
ReversePythonShell().start()
| 988
|
Python
|
.pyt
| 24
| 39.166667
| 73
| 0.7625
|
lmacken/pyrasite
| 2,794
| 218
| 46
|
GPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,275
|
inject_python.cpp
|
lmacken_pyrasite/pyrasite/win/inject_python.cpp
|
#include <stdio.h>
#include <Windows.h>
//TODO
// support both ansi and unicode in the code (path for injection might have non english letters), how does python handle unicode in PyRun_SimpleString ?
// i checked on windows 7 64bit running 32bit python 2.7, check on other windows versions, and other python versions
// try maybe to write a code to auto figure out in which modules the Python functions are, maybe with EnumProcessModules
// do i need to statically compile the runtime libraries here ? (compile with VS2008 which is python 2.7 runtime maybe?)
// check the 64bit process injection especially in the context of ASLR
// in python 64 bit building, does disttools choose the 64 bit compiler?
// if python extension restore previous privilieges after running ?
// set only the privilieges needed for what i want to do..
// itanium support?
// Can be compiled in visual studio command prompt with: cl.exe inject_python.cpp
#pragma comment(lib, "kernel32.lib")
#pragma comment(lib, "user32.lib")
#pragma comment(lib, "advapi32.lib")
int RaisePrivileges()
{
int retCode = 0;
HANDLE hToken;
TOKEN_PRIVILEGES tp;
TOKEN_PRIVILEGES oldtp;
DWORD dwSize = sizeof(TOKEN_PRIVILEGES);
LUID luid;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
{
retCode = 1;
goto error1;
}
if (!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &luid))
{
retCode = 2;
goto error2;
}
ZeroMemory(&tp, sizeof(tp));
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if (!AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), &oldtp, &dwSize))
{
retCode = 3;
goto error2;
}
error2:
CloseHandle(hToken);
error1:
return retCode;
}
typedef struct
{
HMODULE (__stdcall *pGetModuleHandle)(LPCSTR);
FARPROC (__stdcall *pGetProcAddress)(HMODULE, LPCSTR);
char ModuleName[9];
char PyGILState_Ensure[18];
char PyRun_SimpleString[19];
char PyGILState_Release[19];
char *Code;
} REMOTEDATA;
static DWORD WINAPI ExecutePythonCode(REMOTEDATA *data)
{
DWORD retCode = 0;
HMODULE hModule = data->pGetModuleHandle(data->ModuleName);
if (hModule != NULL)
{
int (__cdecl *a)() = reinterpret_cast<int (__cdecl *)()>(data->pGetProcAddress(hModule, data->PyGILState_Ensure));
if (a != NULL)
{
int ret = a();
void (__cdecl *b)(char *) = reinterpret_cast<void (__cdecl *)(char *)>(data->pGetProcAddress(hModule, data->PyRun_SimpleString));
if (b != NULL)
{
b(data->Code);
} else {
retCode = 3;
}
void (__cdecl *c)(int) = reinterpret_cast<void (__cdecl *)(int)>(data->pGetProcAddress(hModule, data->PyGILState_Release));
if (c != NULL)
{
c(ret);
} else {
retCode = 4;
}
} else {
retCode = 2;
}
} else {
retCode = 1;
}
return retCode;
}
static void AfterExecutePythonCode()
{
}
int InjectPythonCode(HANDLE hProcess, const char *code, char *moduleName)
{
int retCode = 0;
REMOTEDATA data;
int cbCodeSize = (PBYTE)AfterExecutePythonCode - (PBYTE)ExecutePythonCode;
void* remoteCodeString = VirtualAllocEx(hProcess, NULL, strlen(code) + 1, MEM_COMMIT, PAGE_READWRITE);
if (remoteCodeString == NULL)
{
retCode = 1;
goto error1;
}
void* remoteCode = VirtualAllocEx(hProcess, NULL, cbCodeSize, MEM_COMMIT, PAGE_EXECUTE);
if (remoteCode == NULL)
{
retCode = 2;
goto error2;
}
void* remoteData = VirtualAllocEx(hProcess, NULL, sizeof(data), MEM_COMMIT, PAGE_READWRITE);
if (remoteData == NULL)
{
retCode = 3;
goto error3;
}
if (!WriteProcessMemory(hProcess, remoteCodeString, (void*)code, strlen(code) + 1, NULL))
{
retCode = 4;
goto error3;
}
data.pGetModuleHandle = GetModuleHandle;
data.pGetProcAddress = GetProcAddress;
strcpy_s(data.ModuleName, moduleName);
strcpy_s(data.PyGILState_Ensure, "PyGILState_Ensure");
strcpy_s(data.PyRun_SimpleString, "PyRun_SimpleString");
strcpy_s(data.PyGILState_Release, "PyGILState_Release");
data.Code = (char *)remoteCodeString;
if (!WriteProcessMemory(hProcess, remoteData, (void*)&data, sizeof(data), NULL))
{
retCode = 5;
goto error3;
}
if (!WriteProcessMemory(hProcess, remoteCode, (void*)ExecutePythonCode, cbCodeSize, NULL))
{
retCode = 6;
goto error3;
}
HANDLE hRemoteThread = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)remoteCode, remoteData, 0, NULL);
if (!hRemoteThread)
{
retCode = 7;
goto error3;
}
if (WaitForSingleObject(hRemoteThread, INFINITE) == WAIT_FAILED)
{
retCode = 8;
goto error4;
}
DWORD exitCode;
if (!GetExitCodeThread(hRemoteThread, &exitCode))
{
retCode = 9;
goto error4;
}
if (exitCode != 0)
{
retCode = 10;
goto error4;
}
error4:
CloseHandle(hRemoteThread);
error3:
VirtualFreeEx(hProcess, remoteData, sizeof(data), MEM_RELEASE);
error2:
VirtualFreeEx(hProcess, remoteCode, cbCodeSize, MEM_RELEASE);
error1:
VirtualFreeEx(hProcess, remoteCodeString, strlen(code) + 1, MEM_RELEASE);
return retCode;
}
int InjectPythonCodeToPID(DWORD pid, const char *code)
{
char versions[][9] = { "Python36", "Python35", "Python34", "Python33", "Python32", "Python31", "Python30", "Python27", "Python26", "Python25", "Python24" };
unsigned int numVersions = 11;
unsigned int i;
int retCode = 0;
int ret;
BOOL is32Bit;
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pid);
if (!hProcess)
{
retCode = 1;
goto error1;
}
//TODO this requires windows xp an above, later check if the function exists first...
if (!IsWow64Process(hProcess, &is32Bit))
{
retCode = 2;
goto error2;
}
#ifdef _WIN64
if (is32Bit)
{
retCode = 5;
goto error2;
}
#else
BOOL amI32Bit;
IsWow64Process(GetCurrentProcess(), &amI32Bit);
if (amI32Bit && !is32Bit)
{
retCode = 5;
goto error2;
}
#endif
for (i = 0; i < numVersions; ++i)
{
ret = InjectPythonCode(hProcess, code, versions[i]);
if (ret == 0)
{
break;
}
if (ret != 10)
{
retCode = 3;
goto error2;
}
}
if (ret != 0)
{
retCode = 4;
goto error2;
}
error2:
CloseHandle(hProcess);
error1:
return retCode;
}
int main(int argc, char *argv[])
{
if (argc != 3)
{
fprintf(stderr, "Usage: %s <pid> <code>\n", argv[0]);
return 1;
}
DWORD pid = atoi(argv[1]);
char* code = argv[2];
int ret;
ret = RaisePrivileges();
if (ret)
{
fprintf(stderr, "Could not raise privileges, return value %d, error code %d\n", ret, GetLastError());
return 10 + ret;
}
ret = InjectPythonCodeToPID(pid, code);
if (ret)
{
fprintf(stderr, "Could not inject code, return value %d, error code %d\n", ret, GetLastError());
return 20 + ret;
}
return 0;
}
| 6,614
|
Python
|
.pyt
| 252
| 23.873016
| 157
| 0.715411
|
lmacken/pyrasite
| 2,794
| 218
| 46
|
GPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,276
|
dump_stacks.py
|
lmacken_pyrasite/pyrasite/payloads/dump_stacks.py
|
import sys, traceback
for thread, frame in sys._current_frames().items():
print('Thread 0x%x' % thread)
traceback.print_stack(frame)
print()
| 154
|
Python
|
.tac
| 5
| 27.2
| 51
| 0.702703
|
lmacken/pyrasite
| 2,794
| 218
| 46
|
GPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,277
|
setup.py
|
Kozea_pygal/setup.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of pygal
#
# A python svg graph plotting library
# Copyright © 2012-2016 Kozea
#
# This library is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This library 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 Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with pygal. If not, see <http://www.gnu.org/licenses/>.
import os
from setuptools import find_packages, setup
ROOT = os.path.dirname(__file__)
tests_requirements = [
"cairosvg",
"coveralls",
"lxml",
"pyquery",
"pytest",
"pytest-cov",
"ruff>=0.5.6",
]
moulinrouge_requirements = [
"flask",
"pygal_maps_ch",
"pygal_maps_fr",
"pygal_maps_world",
]
about = {}
with open(os.path.join(
os.path.dirname(__file__), "pygal", "__about__.py")) as f:
exec(f.read(), about)
setup(
name=about['__title__'],
version=about['__version__'],
description=about['__summary__'],
long_description=open('README').read(),
long_description_content_type="text/x-rst",
url=about['__uri__'],
author=about['__author__'],
author_email=about['__email__'],
license=about['__license__'],
platforms="Any",
python_requires=">=3.8",
packages=find_packages(),
provides=['pygal'],
scripts=["pygal_gen.py"],
keywords=[
"svg", "chart", "graph", "diagram", "plot", "histogram", "kiviat"],
setup_requires=['pytest-runner'],
install_requires=['importlib-metadata'], # TODO: remove this (see #545, #546)
package_data={'pygal': ['css/*', 'graph/maps/*.svg']},
extras_require={
'lxml': ['lxml'],
'docs': ['sphinx', 'sphinx_rtd_theme', 'pygal_sphinx_directives'],
'png': ['cairosvg'],
'test': tests_requirements,
'moulinrouge': moulinrouge_requirements,
},
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Console",
"Intended Audience :: End Users/Desktop",
"License :: OSI Approved :: "
"GNU Lesser General Public License v3 or later (LGPLv3+)",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3",
"Topic :: Multimedia :: Graphics :: Presentation"])
| 2,641
|
Python
|
.py
| 77
| 29.948052
| 82
| 0.647381
|
Kozea/pygal
| 2,634
| 411
| 197
|
LGPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,278
|
perf.py
|
Kozea_pygal/perf.py
|
# -*- coding: utf-8 -*-
# This file is part of pygal
#
# A python svg graph plotting library
# Copyright © 2012-2016 Kozea
#
# This library is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This library 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 Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with pygal. If not, see <http://www.gnu.org/licenses/>.
import sys
import timeit
from random import sample
from pygal import CHARTS, CHARTS_BY_NAME
from pygal.etree import etree
from pygal.test import adapt
sizes = (1, 5, 10, 50, 100, 500, 1000)
rands = list(zip(
sample(range(1000), 1000),
sample(range(1000), 1000)))
def perf(chart_name, length, series):
chart = CHARTS_BY_NAME.get(chart_name)()
for i in range(series):
chart.add('s %d' % i, adapt(chart, rands[:length]))
return chart
if '--bench' in sys.argv:
bench = True
def prt(s):
pass
def cht(s):
sys.stdout.write(s)
else:
bench = False
def prt(s):
sys.stdout.write(s)
sys.stdout.flush()
def cht(s):
pass
if '--profile' in sys.argv:
import cProfile
c = perf('Line', 500, 500)
cProfile.run("c.render()")
sys.exit(0)
if '--mem' in sys.argv:
_TWO_20 = float(2 ** 20)
import linecache
import os
import psutil
pid = os.getpid()
process = psutil.Process(pid)
import gc
gc.set_debug(
gc.DEBUG_UNCOLLECTABLE | gc.DEBUG_INSTANCES | gc.DEBUG_OBJECTS)
def print_mem():
mem = process.get_memory_info()[0] / _TWO_20
f = sys._getframe(1)
line = linecache.getline(
f.f_code.co_filename, f.f_lineno - 1).replace('\n', '')
print('%s:%d \t| %.6f \t| %s' % (
f.f_code.co_name, f.f_lineno, mem, line))
c = perf('Line', 100, 500)
print_mem()
a = c.render()
print_mem()
import objgraph
objgraph.show_refs([c], filename='sample-graph.png')
gc.collect()
print_mem()
print(gc.garbage)
print_mem()
del a
print_mem()
del c
print_mem()
sys.exit(0)
charts = CHARTS if '--all' in sys.argv else 'Line',
for impl in ['lxml', 'etree']:
if impl == 'lxml':
etree.to_lxml()
else:
etree.to_etree()
for chart in charts:
prt('%s\n' % chart)
prt('s\\l\t1\t10\t100')
v = sys.version.split(' ')[0]
if hasattr(sys, 'subversion'):
v += ' ' + sys.subversion[0]
v += ' ' + impl
if len(charts) > 1:
v += ' ' + chart
cht('bench.add("%s", ' % v)
diag = []
for series in sizes:
prt('\n%d\t' % series)
for length in sizes:
times = []
if series == length or not bench:
time = timeit.timeit(
"c.render()",
setup="from __main__ import perf; "
"c = perf('%s', %d, %d)" % (
chart, length, series),
number=10)
if series == length:
diag.append(1000 * time)
prt('%d\t' % (1000 * time))
cht(repr(diag))
cht(')\n')
prt('\n')
| 3,640
|
Python
|
.py
| 117
| 24.119658
| 79
| 0.571184
|
Kozea/pygal
| 2,634
| 411
| 197
|
LGPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,279
|
pygal_gen.py
|
Kozea_pygal/pygal_gen.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of pygal
#
# A python svg graph plotting library
# Copyright © 2012-2016 Kozea
#
# This library is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This library 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 Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with pygal. If not, see <http://www.gnu.org/licenses/>.
import argparse
import pygal
parser = argparse.ArgumentParser(
description='Generate pygal chart in command line',
prog='pygal_gen')
parser.add_argument('-t', '--type', dest='type', default='Line',
choices=map(lambda x: x.__name__, pygal.CHARTS),
help='Kind of chart to generate')
parser.add_argument('-o', '--output', dest='filename', default='pygal_out.svg',
help='Filename to write the svg to')
parser.add_argument('-s', '--serie', dest='series', nargs='+', action='append',
help='Add a serie in the form (title val1 val2...)')
parser.add_argument('--version', action='version',
version='pygal %s' % pygal.__version__)
for key in pygal.config.CONFIG_ITEMS:
opt_name = key.name
val = key.value
opts = {}
if key.type == list:
opts['type'] = key.subtype
opts['nargs'] = '+'
else:
opts['type'] = key.type
if opts['type'] == bool:
del opts['type']
opts['action'] = 'store_true' if not val else 'store_false'
if val:
opt_name = 'no-' + opt_name
if key.name == 'interpolate':
opts['choices'] = list(pygal.interpolate.INTERPOLATIONS.keys())
parser.add_argument(
'--%s' % opt_name, dest=key.name, default=val, **opts)
config = parser.parse_args()
chart = getattr(pygal, config.type)(**vars(config))
for serie in config.series:
chart.add(serie[0], map(float, serie[1:]))
chart.render_to_file(config.filename)
| 2,329
|
Python
|
.py
| 56
| 36.446429
| 79
| 0.66077
|
Kozea/pygal
| 2,634
| 411
| 197
|
LGPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,280
|
svg.py
|
Kozea_pygal/pygal/svg.py
|
# -*- coding: utf-8 -*-
# This file is part of pygal
#
# A python svg graph plotting library
# Copyright © 2012-2016 Kozea
#
# This library is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This library 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 Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with pygal. If not, see <http://www.gnu.org/licenses/>.
"""Svg helper"""
from __future__ import division
import io
import json
import os
from datetime import date, datetime
from math import pi
from numbers import Number
from urllib.parse import quote_plus
from pygal import __version__
from pygal.etree import etree
from pygal.util import (
coord_abs_project,
coord_diff,
coord_dual,
coord_format,
coord_project,
minify_css,
template,
)
nearly_2pi = 2 * pi - .00001
class Svg(object):
"""Svg related methods"""
ns = 'http://www.w3.org/2000/svg'
xlink_ns = 'http://www.w3.org/1999/xlink'
def __init__(self, graph):
"""Create the svg helper with the chart instance"""
self.graph = graph
if not graph.no_prefix:
self.id = '#chart-%s ' % graph.uuid
else:
self.id = ''
self.processing_instructions = []
if etree.lxml:
attrs = {'nsmap': {None: self.ns, 'xlink': self.xlink_ns}}
else:
attrs = {'xmlns': self.ns}
if hasattr(etree, 'register_namespace'):
etree.register_namespace('xlink', self.xlink_ns)
else:
etree._namespace_map[self.xlink_ns] = 'xlink'
self.root = etree.Element('svg', **attrs)
self.root.attrib['id'] = self.id.lstrip('#').rstrip()
if graph.classes:
self.root.attrib['class'] = ' '.join(graph.classes)
self.root.append(
etree.Comment(
'Generated with pygal %s (%s) ©Kozea 2012-2016 on %s' % (
__version__, 'lxml' if etree.lxml else 'etree',
date.today().isoformat()
)
)
)
self.root.append(etree.Comment('http://pygal.org'))
self.root.append(etree.Comment('http://github.com/Kozea/pygal'))
self.defs = self.node(tag='defs')
self.title = self.node(tag='title')
self.title.text = graph.title or 'Pygal'
for def_ in self.graph.defs:
self.defs.append(etree.fromstring(def_))
def add_styles(self):
"""Add the css to the svg"""
colors = self.graph.style.get_colors(self.id, self.graph._order)
strokes = self.get_strokes()
all_css = []
auto_css = ['file://base.css']
if self.graph.style._google_fonts:
auto_css.append(
'//fonts.googleapis.com/css?family=%s' %
quote_plus('|'.join(self.graph.style._google_fonts))
)
for css in auto_css + list(self.graph.css):
css_text = None
if css.startswith('inline:'):
css_text = css[len('inline:'):]
elif css.startswith('file://'):
css = css[len('file://'):]
if not os.path.exists(css):
css = os.path.join(os.path.dirname(__file__), 'css', css)
with io.open(css, encoding='utf-8') as f:
css_text = template(
f.read(),
style=self.graph.style,
colors=colors,
strokes=strokes,
id=self.id
)
if css_text is not None:
if not self.graph.pretty_print:
css_text = minify_css(css_text)
all_css.append(css_text)
else:
if css.startswith('//') and self.graph.force_uri_protocol:
css = '%s:%s' % (self.graph.force_uri_protocol, css)
self.processing_instructions.append(
etree.PI('xml-stylesheet', 'href="%s"' % css)
)
self.node(
self.defs, 'style', type='text/css'
).text = '\n'.join(all_css)
def add_scripts(self):
"""Add the js to the svg"""
common_script = self.node(self.defs, 'script', type='text/javascript')
def get_js_dict():
return dict(
(k, getattr(self.graph.state, k))
for k in dir(self.graph.config)
if not k.startswith('_') and hasattr(self.graph.state, k)
and not hasattr(getattr(self.graph.state, k), '__call__')
)
def json_default(o):
if isinstance(o, (datetime, date)):
return o.isoformat()
if hasattr(o, 'to_dict'):
return o.to_dict()
return json.JSONEncoder().default(o)
dct = get_js_dict()
# Config adds
dct['legends'] = [
l.get('title') if isinstance(l, dict) else l
for l in self.graph._legends + self.graph._secondary_legends
]
common_js = 'window.pygal = window.pygal || {};'
common_js += 'window.pygal.config = window.pygal.config || {};'
if self.graph.no_prefix:
common_js += 'window.pygal.config = '
else:
common_js += 'window.pygal.config[%r] = ' % self.graph.uuid
common_script.text = common_js + json.dumps(dct, default=json_default)
for js in self.graph.js:
if js.startswith('file://'):
script = self.node(self.defs, 'script', type='text/javascript')
with io.open(js[len('file://'):], encoding='utf-8') as f:
script.text = f.read()
else:
if js.startswith('//') and self.graph.force_uri_protocol:
js = '%s:%s' % (self.graph.force_uri_protocol, js)
self.node(self.defs, 'script', type='text/javascript', href=js)
def node(self, parent=None, tag='g', attrib=None, **extras):
"""Make a new svg node"""
if parent is None:
parent = self.root
attrib = attrib or {}
attrib.update(extras)
def in_attrib_and_number(key):
return key in attrib and isinstance(attrib[key], Number)
for pos, dim in (('x', 'width'), ('y', 'height')):
if in_attrib_and_number(dim) and attrib[dim] < 0:
attrib[dim] = -attrib[dim]
if in_attrib_and_number(pos):
attrib[pos] = attrib[pos] - attrib[dim]
for key, value in dict(attrib).items():
if value is None:
del attrib[key]
attrib[key] = str(value)
if key.endswith('_'):
attrib[key.rstrip('_')] = attrib[key]
del attrib[key]
elif key == 'href':
attrib[etree.QName('http://www.w3.org/1999/xlink',
key)] = attrib[key]
del attrib[key]
return etree.SubElement(parent, tag, attrib)
def transposable_node(self, parent=None, tag='g', attrib=None, **extras):
"""Make a new svg node which can be transposed if horizontal"""
if self.graph.horizontal:
for key1, key2 in (('x', 'y'), ('width', 'height'), ('cx', 'cy')):
attr1 = extras.get(key1, None)
attr2 = extras.get(key2, None)
if attr2:
extras[key1] = attr2
elif attr1:
del extras[key1]
if attr1:
extras[key2] = attr1
elif attr2:
del extras[key2]
return self.node(parent, tag, attrib, **extras)
def serie(self, serie):
"""Make serie node"""
return dict(
plot=self.node(
self.graph.nodes['plot'],
class_='series serie-%d color-%d' % (serie.index, serie.index)
),
overlay=self.node(
self.graph.nodes['overlay'],
class_='series serie-%d color-%d' % (serie.index, serie.index)
),
text_overlay=self.node(
self.graph.nodes['text_overlay'],
class_='series serie-%d color-%d' % (serie.index, serie.index)
)
)
def line(self, node, coords, close=False, **kwargs):
"""Draw a svg line"""
line_len = len(coords)
if len([c for c in coords if c[1] is not None]) < 2:
return
root = 'M%s L%s Z' if close else 'M%s L%s'
origin_index = 0
while origin_index < line_len and None in coords[origin_index]:
origin_index += 1
if origin_index == line_len:
return
if self.graph.horizontal:
coord_format = lambda xy: '%f %f' % (xy[1], xy[0])
else:
coord_format = lambda xy: '%f %f' % xy
origin = coord_format(coords[origin_index])
line = ' '.join([
coord_format(c) for c in coords[origin_index + 1:] if None not in c
])
return self.node(node, 'path', d=root % (origin, line), **kwargs)
def slice(
self, serie_node, node, radius, small_radius, angle, start_angle,
center, val, i, metadata
):
"""Draw a pie slice"""
if angle == 2 * pi:
angle = nearly_2pi
if angle > 0:
to = [
coord_abs_project(center, radius, start_angle),
coord_abs_project(center, radius, start_angle + angle),
coord_abs_project(center, small_radius, start_angle + angle),
coord_abs_project(center, small_radius, start_angle)
]
rv = self.node(
node,
'path',
d='M%s A%s 0 %d 1 %s L%s A%s 0 %d 0 %s z' % (
to[0], coord_dual(radius), int(angle > pi), to[1], to[2],
coord_dual(small_radius), int(angle > pi), to[3]
),
class_='slice reactive tooltip-trigger'
)
else:
rv = None
x, y = coord_diff(
center,
coord_project((radius + small_radius) / 2, start_angle + angle / 2)
)
self.graph._tooltip_data(
node, val, x, y, "centered", self.graph._x_labels
and self.graph._x_labels[i][0]
)
if angle >= 0.3: # 0.3 radians is about 17 degrees
self.graph._static_value(serie_node, val, x, y, metadata)
return rv
def gauge_background(
self, serie_node, start_angle, center, radius, small_radius,
end_angle, half_pie, max_value
):
if end_angle == 2 * pi:
end_angle = nearly_2pi
to_shade = [
coord_abs_project(center, radius, start_angle),
coord_abs_project(center, radius, end_angle),
coord_abs_project(center, small_radius, end_angle),
coord_abs_project(center, small_radius, start_angle)
]
self.node(
serie_node['plot'],
'path',
d='M%s A%s 0 1 1 %s L%s A%s 0 1 0 %s z' % (
to_shade[0], coord_dual(radius), to_shade[1], to_shade[2],
coord_dual(small_radius), to_shade[3]
),
class_='gauge-background reactive'
)
if half_pie:
begin_end = [
coord_diff(
center,
coord_project(
radius - (radius - small_radius) / 2, start_angle
)
),
coord_diff(
center,
coord_project(
radius - (radius - small_radius) / 2, end_angle
)
)
]
pos = 0
for i in begin_end:
self.node(
serie_node['plot'],
'text',
class_='y-{} bound reactive'.format(pos),
x=i[0],
y=i[1] + 10,
attrib={
'text-anchor': 'middle'
}
).text = '{}'.format(0 if pos == 0 else max_value)
pos += 1
else:
middle_radius = .5 * (radius + small_radius)
# Correct text vertical alignment
middle_radius -= .1 * (radius - small_radius)
to_labels = [
coord_abs_project(center, middle_radius, 0),
coord_abs_project(center, middle_radius, nearly_2pi)
]
self.node(
self.defs,
'path',
id='valuePath-%s%s' % center,
d='M%s A%s 0 1 1 %s' %
(to_labels[0], coord_dual(middle_radius), to_labels[1])
)
text_ = self.node(serie_node['text_overlay'], 'text')
self.node(
text_,
'textPath',
class_='max-value reactive',
attrib={
'href': '#valuePath-%s%s' % center,
'startOffset': '99%',
'text-anchor': 'end'
}
).text = max_value
def solid_gauge(
self, serie_node, node, radius, small_radius, angle, start_angle,
center, val, i, metadata, half_pie, end_angle, max_value
):
"""Draw a solid gauge slice and background slice"""
if angle == 2 * pi:
angle = nearly_2pi
if angle > 0:
to = [
coord_abs_project(center, radius, start_angle),
coord_abs_project(center, radius, start_angle + angle),
coord_abs_project(center, small_radius, start_angle + angle),
coord_abs_project(center, small_radius, start_angle)
]
self.node(
node,
'path',
d='M%s A%s 0 %d 1 %s L%s A%s 0 %d 0 %s z' % (
to[0], coord_dual(radius), int(angle > pi), to[1], to[2],
coord_dual(small_radius), int(angle > pi), to[3]
),
class_='slice reactive tooltip-trigger'
)
else:
return
x, y = coord_diff(
center,
coord_project((radius + small_radius) / 2, start_angle + angle / 2)
)
self.graph._static_value(serie_node, val, x, y, metadata, 'middle')
self.graph._tooltip_data(
node, val, x, y, "centered", self.graph._x_labels
and self.graph._x_labels[i][0]
)
def confidence_interval(self, node, x, low, high, width=7):
if self.graph.horizontal:
fmt = lambda xy: '%f %f' % (xy[1], xy[0])
else:
fmt = coord_format
shr = lambda xy: (xy[0] + width, xy[1])
shl = lambda xy: (xy[0] - width, xy[1])
top = (x, high)
bottom = (x, low)
ci = self.node(node, class_="ci")
self.node(
ci,
'path',
d="M%s L%s M%s L%s M%s L%s L%s M%s L%s" % tuple(
map(
fmt, (
top, shr(top), top, shl(top), top, bottom, shr(bottom),
bottom, shl(bottom)
)
)
),
class_='nofill reactive'
)
def pre_render(self):
"""Last things to do before rendering"""
self.add_styles()
self.add_scripts()
self.root.set(
'viewBox', '0 0 %d %d' % (self.graph.width, self.graph.height)
)
if self.graph.explicit_size:
self.root.set('width', str(self.graph.width))
self.root.set('height', str(self.graph.height))
def draw_no_data(self):
"""Write the no data text to the svg"""
no_data = self.node(
self.graph.nodes['text_overlay'],
'text',
x=self.graph.view.width / 2,
y=self.graph.view.height / 2,
class_='no_data'
)
no_data.text = self.graph.no_data_text
def render(self, is_unicode=False, pretty_print=False):
"""Last thing to do before rendering"""
for f in self.graph.xml_filters:
self.root = f(self.root)
args = {'encoding': 'utf-8'}
svg = b''
if etree.lxml:
args['pretty_print'] = pretty_print
if not self.graph.disable_xml_declaration:
svg = b"<?xml version='1.0' encoding='utf-8'?>\n"
if not self.graph.disable_xml_declaration:
svg += b'\n'.join([
etree.tostring(pi, **args)
for pi in self.processing_instructions
])
svg += etree.tostring(self.root, **args)
if self.graph.disable_xml_declaration or is_unicode:
svg = svg.decode('utf-8')
return svg
def get_strokes(self):
"""Return a css snippet containing all stroke style options"""
def stroke_dict_to_css(stroke, i=None):
"""Return a css style for the given option"""
css = [
'%s.series%s {\n' %
(self.id, '.serie-%d' % i if i is not None else '')
]
for key in ('width', 'linejoin', 'linecap', 'dasharray',
'dashoffset'):
if stroke.get(key):
css.append(' stroke-%s: %s;\n' % (key, stroke[key]))
css.append('}')
return '\n'.join(css)
css = []
if self.graph.stroke_style is not None:
css.append(stroke_dict_to_css(self.graph.stroke_style))
for serie in self.graph.series:
if serie.stroke_style is not None:
css.append(stroke_dict_to_css(serie.stroke_style, serie.index))
for secondary_serie in self.graph.secondary_series:
if secondary_serie.stroke_style is not None:
css.append(
stroke_dict_to_css(
secondary_serie.stroke_style, secondary_serie.index
)
)
return '\n'.join(css)
| 18,702
|
Python
|
.py
| 467
| 27.513919
| 79
| 0.503412
|
Kozea/pygal
| 2,634
| 411
| 197
|
LGPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,281
|
state.py
|
Kozea_pygal/pygal/state.py
|
# -*- coding: utf-8 -*-
# This file is part of pygal
#
# A python svg graph plotting library
# Copyright © 2012-2016 Kozea
#
# This library is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This library 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 Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with pygal. If not, see <http://www.gnu.org/licenses/>.
"""Class holding state during render"""
from pygal.util import merge
class State(object):
"""
Class containing config values
overriden by chart values
overriden by keyword args
"""
def __init__(self, graph, **kwargs):
"""Create the transient state"""
merge(self.__dict__, graph.config.__class__.__dict__)
merge(self.__dict__, graph.config.__dict__)
merge(self.__dict__, graph.__dict__)
merge(self.__dict__, kwargs)
| 1,256
|
Python
|
.py
| 32
| 36.125
| 79
| 0.712295
|
Kozea/pygal
| 2,634
| 411
| 197
|
LGPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,282
|
__about__.py
|
Kozea_pygal/pygal/__about__.py
|
__title__ = "pygal"
__version__ = "3.0.5"
__summary__ = "A Python svg graph plotting library"
__uri__ = "https://www.pygal.org/"
__author__ = "Florian Mounier / Kozea"
__email__ = "community@kozea.fr"
__license__ = "GNU LGPL v3+"
__copyright__ = "Copyright 2020 %s" % __author__
__all__ = [
'__title__', '__version__', '__summary__', '__uri__', '__author__',
'__email__', '__license__', '__copyright__'
]
| 416
|
Python
|
.py
| 12
| 32.75
| 71
| 0.546135
|
Kozea/pygal
| 2,634
| 411
| 197
|
LGPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,283
|
colors.py
|
Kozea_pygal/pygal/colors.py
|
# -*- coding: utf-8 -*-
# This file is part of pygal
#
# A python svg graph plotting library
# Copyright © 2012-2016 Kozea
#
# This library is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This library 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 Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with pygal. If not, see <http://www.gnu.org/licenses/>.
"""
This package is an utility package oriented on color alteration.
This is used by the :py:mod:`pygal.style` package to generate
parametric styles.
"""
from __future__ import division
def normalize_float(f):
"""Round float errors"""
if abs(f - round(f)) < .0000000000001:
return round(f)
return f
def rgb_to_hsl(r, g, b):
"""Convert a color in r, g, b to a color in h, s, l"""
r = r or 0
g = g or 0
b = b or 0
r /= 255
g /= 255
b /= 255
max_ = max((r, g, b))
min_ = min((r, g, b))
d = max_ - min_
if not d:
h = 0
elif r is max_:
h = 60 * (g - b) / d
elif g is max_:
h = 60 * (b - r) / d + 120
else:
h = 60 * (r - g) / d + 240
l = .5 * (max_ + min_)
if not d:
s = 0
elif l < 0.5:
s = .5 * d / l
else:
s = .5 * d / (1 - l)
return tuple(map(normalize_float, (h % 360, s * 100, l * 100)))
def hsl_to_rgb(h, s, l):
"""Convert a color in h, s, l to a color in r, g, b"""
h /= 360
s /= 100
l /= 100
m2 = l * (s + 1) if l <= .5 else l + s - l * s
m1 = 2 * l - m2
def h_to_rgb(h):
h = h % 1
if 6 * h < 1:
return m1 + 6 * h * (m2 - m1)
if 2 * h < 1:
return m2
if 3 * h < 2:
return m1 + 6 * (2 / 3 - h) * (m2 - m1)
return m1
r, g, b = map(
lambda x: round(x * 255), map(h_to_rgb, (h + 1 / 3, h, h - 1 / 3))
)
return r, g, b
def parse_color(color):
"""Take any css color definition and give back a tuple containing the
r, g, b, a values along with a type which can be: #rgb, #rgba, #rrggbb,
#rrggbbaa, rgb, rgba
"""
r = g = b = a = type = None
if color.startswith('#'):
color = color[1:]
if len(color) == 3:
type = '#rgb'
color = color + 'f'
if len(color) == 4:
type = type or '#rgba'
color = ''.join([c * 2 for c in color])
if len(color) == 6:
type = type or '#rrggbb'
color = color + 'ff'
assert len(color) == 8
type = type or '#rrggbbaa'
r, g, b, a = [
int(''.join(c), 16) for c in zip(color[::2], color[1::2])
]
a /= 255
elif color.startswith('rgb('):
type = 'rgb'
color = color[4:-1]
r, g, b, a = [int(c) for c in color.split(',')] + [1]
elif color.startswith('rgba('):
type = 'rgba'
color = color[5:-1]
r, g, b, a = [int(c) for c in color.split(',')[:-1]
] + [float(color.split(',')[-1])]
return r, g, b, a, type
def unparse_color(r, g, b, a, type):
"""
Take the r, g, b, a color values and give back
a type css color string. This is the inverse function of parse_color
"""
if type == '#rgb':
# Don't lose precision on rgb shortcut
if r % 17 == 0 and g % 17 == 0 and b % 17 == 0:
return '#%x%x%x' % (int(r / 17), int(g / 17), int(b / 17))
type = '#rrggbb'
if type == '#rgba':
if r % 17 == 0 and g % 17 == 0 and b % 17 == 0:
return '#%x%x%x%x' % (
int(r / 17), int(g / 17), int(b / 17), int(a * 15)
)
type = '#rrggbbaa'
if type == '#rrggbb':
return '#%02x%02x%02x' % (r, g, b)
if type == '#rrggbbaa':
return '#%02x%02x%02x%02x' % (r, g, b, int(a * 255))
if type == 'rgb':
return 'rgb(%d, %d, %d)' % (r, g, b)
if type == 'rgba':
return 'rgba(%d, %d, %d, %g)' % (r, g, b, a)
def is_foreground_light(color):
"""
Determine if the background color need a light or dark foreground color
"""
return rgb_to_hsl(*parse_color(color)[:3])[2] < 17.9
_clamp = lambda x: max(0, min(100, x))
def _adjust(hsl, attribute, percent):
"""Internal adjust function"""
hsl = list(hsl)
if attribute > 0:
hsl[attribute] = _clamp(hsl[attribute] + percent)
else:
hsl[attribute] += percent
return hsl
def adjust(color, attribute, percent):
"""Adjust an attribute of color by a percent"""
r, g, b, a, type = parse_color(color)
r, g, b = hsl_to_rgb(*_adjust(rgb_to_hsl(r, g, b), attribute, percent))
return unparse_color(r, g, b, a, type)
def rotate(color, percent):
"""Rotate a color by changing its hue value by percent"""
return adjust(color, 0, percent)
def saturate(color, percent):
"""Saturate a color by increasing its saturation by percent"""
return adjust(color, 1, percent)
def desaturate(color, percent):
"""Desaturate a color by decreasing its saturation by percent"""
return adjust(color, 1, -percent)
def lighten(color, percent):
"""Lighten a color by increasing its lightness by percent"""
return adjust(color, 2, percent)
def darken(color, percent):
"""Darken a color by decreasing its lightness by percent"""
return adjust(color, 2, -percent)
| 5,749
|
Python
|
.py
| 167
| 28.329341
| 79
| 0.554413
|
Kozea/pygal
| 2,634
| 411
| 197
|
LGPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,284
|
_compat.py
|
Kozea_pygal/pygal/_compat.py
|
# -*- coding: utf-8 -*-
# This file is part of pygal
#
# A python svg graph plotting library
# Copyright © 2012-2016 Kozea
#
# This library is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This library 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 Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with pygal. If not, see <http://www.gnu.org/licenses/>.
"""Various hacks for former transparent python 2 / python 3 support"""
import datetime
from collections.abc import Iterable
def is_list_like(value):
"""Return whether value is an iterable but not a mapping / string"""
return isinstance(value, Iterable) and not isinstance(value, (str, dict))
def timestamp(x):
"""Get a timestamp from a date"""
if x.tzinfo is None:
# Naive dates to utc
x = x.replace(tzinfo=datetime.timezone.utc)
return x.timestamp()
| 1,266
|
Python
|
.py
| 30
| 39.8
| 79
| 0.74878
|
Kozea/pygal
| 2,634
| 411
| 197
|
LGPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,285
|
util.py
|
Kozea_pygal/pygal/util.py
|
# -*- coding: utf-8 -*-
# This file is part of pygal
#
# A python svg graph plotting library
# Copyright © 2012-2016 Kozea
#
# This library is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This library 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 Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with pygal. If not, see <http://www.gnu.org/licenses/>.
"""Various utility functions"""
from __future__ import division
import re
from decimal import Decimal
from math import ceil, cos, floor, log10, pi, sin
def float_format(number):
"""Format a float to a precision of 3, without zeroes or dots"""
return ("%.3f" % number).rstrip('0').rstrip('.')
def majorize(values):
"""Filter sequence to return only major considered numbers"""
sorted_values = sorted(values)
if len(values) <= 3 or (
abs(2 * sorted_values[1] - sorted_values[0] - sorted_values[2]) >
abs(1.5 * (sorted_values[1] - sorted_values[0]))):
return []
values_step = sorted_values[1] - sorted_values[0]
full_range = sorted_values[-1] - sorted_values[0]
step = 10**int(log10(full_range))
if step == values_step:
step *= 10
step_factor = 10**(int(log10(step)) + 1)
if round(step * step_factor) % (round(values_step * step_factor) or 1):
# TODO: Find lower common multiple instead
step *= values_step
if full_range <= 2 * step:
step *= .5
elif full_range >= 5 * step:
step *= 5
major_values = [
value for value in values if value / step == round(value / step)
]
return [value for value in sorted_values if value in major_values]
def round_to_int(number, precision):
"""Round a number to a precision"""
precision = int(precision)
rounded = (int(number) + precision / 2) // precision * precision
return rounded
def round_to_float(number, precision):
"""Round a float to a precision"""
rounded = Decimal(str(floor((number + precision / 2) // precision))
) * Decimal(str(precision))
return float(rounded)
def round_to_scale(number, precision):
"""Round a number or a float to a precision"""
if precision < 1:
return round_to_float(number, precision)
return round_to_int(number, precision)
def cut(list_, index=0):
"""Cut a list by index or arg"""
if isinstance(index, int):
cut_ = lambda x: x[index]
else:
cut_ = lambda x: getattr(x, index)
return list(map(cut_, list_))
def rad(degrees):
"""Convert degrees in radiants"""
return pi * degrees / 180
def deg(radiants):
"""Convert radiants in degrees"""
return 180 * radiants / pi
def _swap_curly(string):
"""Swap single and double curly brackets"""
return (
string.replace('{{ ', '{{').replace('{{', '\x00').replace('{', '{{')
.replace('\x00', '{').replace(' }}', '}}').replace('}}', '\x00')
.replace('}', '}}').replace('\x00', '}')
)
def template(string, **kwargs):
"""Format a string using double braces"""
return _swap_curly(string).format(**kwargs)
swap = lambda tuple_: tuple(reversed(tuple_))
ident = lambda x: x
def compute_logarithmic_scale(min_, max_, min_scale, max_scale):
"""Compute an optimal scale for logarithmic"""
if max_ <= 0 or min_ <= 0:
return []
min_order = int(floor(log10(min_)))
max_order = int(ceil(log10(max_)))
positions = []
amplitude = max_order - min_order
if amplitude <= 1:
return []
detail = 10.
while amplitude * detail < min_scale * 5:
detail *= 2
while amplitude * detail > max_scale * 3:
detail /= 2
for order in range(min_order, max_order + 1):
for i in range(int(detail)):
tick = (10 * i / detail or 1) * 10**order
tick = round_to_scale(tick, tick)
if min_ <= tick <= max_ and tick not in positions:
positions.append(tick)
return positions
def compute_scale(min_, max_, logarithmic, order_min, min_scale, max_scale):
"""Compute an optimal scale between min and max"""
if min_ == 0 and max_ == 0:
return [0]
if max_ - min_ == 0:
return [min_]
if logarithmic:
log_scale = compute_logarithmic_scale(min_, max_, min_scale, max_scale)
if log_scale:
return log_scale
# else we fallback to normal scalling
order = round(log10(max(abs(min_), abs(max_)))) - 1
if order_min is not None and order < order_min:
order = order_min
else:
while ((max_ - min_) / (10**order) < min_scale
and (order_min is None or order > order_min)):
order -= 1
step = float(10**order)
while (max_ - min_) / step > max_scale:
step *= 2.
positions = []
position = round_to_scale(min_, step)
while position < (max_ + step):
rounded = round_to_scale(position, step)
if min_ <= rounded <= max_:
if rounded not in positions:
positions.append(rounded)
position += step
if len(positions) < 2:
return [min_, max_]
return positions
def text_len(length, fs):
"""Approximation of text width"""
return length * 0.6 * fs
def reverse_text_len(width, fs):
"""Approximation of text length"""
return int(width / (0.6 * fs))
def get_text_box(text, fs):
"""Approximation of text bounds"""
return (fs, text_len(len(text), fs))
def get_texts_box(texts, fs):
"""Approximation of multiple texts bounds"""
max_len = max(map(len, texts))
return (fs, text_len(max_len, fs))
def decorate(svg, node, metadata):
"""Add metedata next to a node"""
if not metadata:
return node
xlink = metadata.get('xlink')
if xlink:
if not isinstance(xlink, dict):
xlink = {'href': xlink, 'target': '_blank'}
node = svg.node(node, 'a', **xlink)
svg.node(
node, 'desc', class_='xlink'
).text = str(xlink.get('href'))
if 'tooltip' in metadata:
svg.node(node, 'title').text = str(metadata['tooltip'])
if 'color' in metadata:
color = metadata.pop('color')
node.attrib['style'] = 'fill: %s; stroke: %s' % (color, color)
if 'style' in metadata:
node.attrib['style'] = metadata.pop('style')
if 'label' in metadata and metadata['label']:
svg.node(
node, 'desc', class_='label'
).text = str(metadata['label'])
return node
def alter(node, metadata):
"""Override nodes attributes from metadata node mapping"""
if node is not None and metadata and 'node' in metadata:
node.attrib.update(
dict((k, str(v)) for k, v in metadata['node'].items())
)
def truncate(string, index):
"""Truncate a string at index and add ..."""
if len(string) > index and index > 0:
string = string[:index - 1] + '…'
return string
# # Stolen partly from brownie http://packages.python.org/Brownie/
class cached_property(object):
"""Memoize a property"""
def __init__(self, getter, doc=None):
"""Initialize the decorator"""
self.getter = getter
self.__module__ = getter.__module__
self.__name__ = getter.__name__
self.__doc__ = doc or getter.__doc__
def __get__(self, obj, type_=None):
"""
Get descriptor calling the property function and replacing it with
its value or on state if we are in the transient state.
"""
if obj is None:
return self
value = self.getter(obj)
if hasattr(obj, 'state'):
setattr(obj.state, self.__name__, value)
else:
obj.__dict__[self.__name__] = self.getter(obj)
return value
css_comments = re.compile(r'/\*.*?\*/', re.MULTILINE | re.DOTALL)
def minify_css(css):
"""Little css minifier"""
# Inspired by slimmer by Peter Bengtsson
remove_next_comment = 1
for css_comment in css_comments.findall(css):
if css_comment[-3:] == r'\*/':
remove_next_comment = 0
continue
if remove_next_comment:
css = css.replace(css_comment, '')
else:
remove_next_comment = 1
# >= 2 whitespace becomes one whitespace
css = re.sub(r'\s\s+', ' ', css)
# no whitespace before end of line
css = re.sub(r'\s+\n', '', css)
# Remove space before and after certain chars
for char in ('{', '}', ':', ';', ','):
css = re.sub(char + r'\s', char, css)
css = re.sub(r'\s' + char, char, css)
css = re.sub(r'}\s(#|\w)', r'}\1', css)
# no need for the ; before end of attributes
css = re.sub(r';}', r'}', css)
css = re.sub(r'}//-->', r'}\n//-->', css)
return css.strip()
def compose(f, g):
"""Chain functions"""
fun = lambda *args, **kwargs: f(g(*args, **kwargs))
fun.__name__ = "%s o %s" % (f.__name__, g.__name__)
return fun
def safe_enumerate(iterable):
"""Enumerate which does not yield None values"""
for i, v in enumerate(iterable):
if v is not None:
yield i, v
def split_title(title, width, title_fs):
"""Split a string for a specified width and font size"""
titles = []
if not title:
return titles
size = reverse_text_len(width, title_fs * 1.1)
title_lines = title.split("\n")
for title_line in title_lines:
while len(title_line) > size:
title_part = title_line[:size]
i = title_part.rfind(' ')
if i == -1:
i = len(title_part)
titles.append(title_part[:i])
title_line = title_line[i:].strip()
titles.append(title_line)
return titles
def filter_kwargs(fun, kwargs):
if not hasattr(fun, '__code__'):
return {}
args = fun.__code__.co_varnames[1:]
return dict((k, v) for k, v in kwargs.items() if k in args)
def coord_project(rho, alpha):
return rho * sin(-alpha), rho * cos(-alpha)
def coord_diff(x, y):
return (x[0] - y[0], x[1] - y[1])
def coord_format(x):
return '%f %f' % x
def coord_dual(r):
return coord_format((r, r))
def coord_abs_project(center, rho, theta):
return coord_format(coord_diff(center, coord_project(rho, theta)))
def mergextend(list1, list2):
if list1 is None or Ellipsis not in list1:
return list1
index = list1.index(Ellipsis)
return list(list1[:index]) + list(list2) + list(list1[index + 1:])
def merge(dict1, dict2):
from pygal.config import CONFIG_ITEMS, Key
_list_items = [item.name for item in CONFIG_ITEMS if item.type == list]
for key, val in dict2.items():
if isinstance(val, Key):
val = val.value
if key in _list_items:
dict1[key] = mergextend(val, dict1.get(key, ()))
else:
dict1[key] = val
| 11,273
|
Python
|
.py
| 297
| 31.518519
| 79
| 0.603543
|
Kozea/pygal
| 2,634
| 411
| 197
|
LGPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,286
|
interpolate.py
|
Kozea_pygal/pygal/interpolate.py
|
# -*- coding: utf-8 -*-
# This file is part of pygal
#
# A python svg graph plotting library
# Copyright © 2012-2016 Kozea
#
# This library is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This library 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 Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with pygal. If not, see <http://www.gnu.org/licenses/>.
"""
Interpolation functions
These functions takes two lists of points x and y and
returns an iterator over the interpolation between all these points
with `precision` interpolated points between each of them
"""
from __future__ import division
from math import sin
def quadratic_interpolate(x, y, precision=250, **kwargs):
"""
Interpolate x, y using a quadratic algorithm
https://en.wikipedia.org/wiki/Spline_(mathematics)
"""
n = len(x) - 1
delta_x = [x2 - x1 for x1, x2 in zip(x, x[1:])]
delta_y = [y2 - y1 for y1, y2 in zip(y, y[1:])]
slope = [delta_y[i] / delta_x[i] if delta_x[i] else 1 for i in range(n)]
# Quadratic spline: a + bx + cx²
a = y
b = [0] * (n + 1)
c = [0] * (n + 1)
for i in range(1, n):
b[i] = 2 * slope[i - 1] - b[i - 1]
c = [(slope[i] - b[i]) / delta_x[i] if delta_x[i] else 0 for i in range(n)]
for i in range(n + 1):
yield x[i], a[i]
if i == n or delta_x[i] == 0:
continue
for s in range(1, precision):
X = s * delta_x[i] / precision
X2 = X * X
yield x[i] + X, a[i] + b[i] * X + c[i] * X2
def cubic_interpolate(x, y, precision=250, **kwargs):
"""
Interpolate x, y using a cubic algorithm
https://en.wikipedia.org/wiki/Spline_interpolation
"""
n = len(x) - 1
# Spline equation is a + bx + cx² + dx³
# ie: Spline part i equation is a[i] + b[i]x + c[i]x² + d[i]x³
a = y
b = [0] * (n + 1)
c = [0] * (n + 1)
d = [0] * (n + 1)
m = [0] * (n + 1)
z = [0] * (n + 1)
h = [x2 - x1 for x1, x2 in zip(x, x[1:])]
k = [a2 - a1 for a1, a2 in zip(a, a[1:])]
g = [k[i] / h[i] if h[i] else 1 for i in range(n)]
for i in range(1, n):
j = i - 1
l = 1 / (2 * (x[i + 1] - x[j]) - h[j] * m[j]) if x[i + 1] - x[j] else 0
m[i] = h[i] * l
z[i] = (3 * (g[i] - g[j]) - h[j] * z[j]) * l
for j in reversed(range(n)):
if h[j] == 0:
continue
c[j] = z[j] - (m[j] * c[j + 1])
b[j] = g[j] - (h[j] * (c[j + 1] + 2 * c[j])) / 3
d[j] = (c[j + 1] - c[j]) / (3 * h[j])
for i in range(n + 1):
yield x[i], a[i]
if i == n or h[i] == 0:
continue
for s in range(1, precision):
X = s * h[i] / precision
X2 = X * X
X3 = X2 * X
yield x[i] + X, a[i] + b[i] * X + c[i] * X2 + d[i] * X3
def hermite_interpolate(
x, y, precision=250, type='cardinal', c=None, b=None, t=None
):
"""
Interpolate x, y using the hermite method.
See https://en.wikipedia.org/wiki/Cubic_Hermite_spline
This interpolation is configurable and contain 4 subtypes:
* Catmull Rom
* Finite Difference
* Cardinal
* Kochanek Bartels
The cardinal subtype is customizable with a parameter:
* c: tension (0, 1)
This last type is also customizable using 3 parameters:
* c: continuity (-1, 1)
* b: bias (-1, 1)
* t: tension (-1, 1)
"""
n = len(x) - 1
m = [1] * (n + 1)
w = [1] * (n + 1)
delta_x = [x2 - x1 for x1, x2 in zip(x, x[1:])]
if type == 'catmull_rom':
type = 'cardinal'
c = 0
if type == 'finite_difference':
for i in range(1, n):
m[i] = w[i] = .5 * ((y[i + 1] - y[i]) / (x[i + 1] - x[i]) +
(y[i] - y[i - 1]) / (x[i] - x[i - 1])
) if x[i + 1] - x[i] and x[i] - x[i - 1] else 0
elif type == 'kochanek_bartels':
c = c or 0
b = b or 0
t = t or 0
for i in range(1, n):
m[i] = .5 * ((1 - t) * (1 + b) * (1 + c) * (y[i] - y[i - 1]) +
(1 - t) * (1 - b) * (1 - c) * (y[i + 1] - y[i]))
w[i] = .5 * ((1 - t) * (1 + b) * (1 - c) * (y[i] - y[i - 1]) +
(1 - t) * (1 - b) * (1 + c) * (y[i + 1] - y[i]))
if type == 'cardinal':
c = c or 0
for i in range(1, n):
m[i] = w[i] = (1 - c) * (y[i + 1] - y[i - 1]) / (
x[i + 1] - x[i - 1]
) if x[i + 1] - x[i - 1] else 0
def p(i, x_):
t = (x_ - x[i]) / delta_x[i]
t2 = t * t
t3 = t2 * t
h00 = 2 * t3 - 3 * t2 + 1
h10 = t3 - 2 * t2 + t
h01 = -2 * t3 + 3 * t2
h11 = t3 - t2
return (
h00 * y[i] + h10 * m[i] * delta_x[i] + h01 * y[i + 1] +
h11 * w[i + 1] * delta_x[i]
)
for i in range(n + 1):
yield x[i], y[i]
if i == n or delta_x[i] == 0:
continue
for s in range(1, precision):
X = x[i] + s * delta_x[i] / precision
yield X, p(i, X)
def lagrange_interpolate(x, y, precision=250, **kwargs):
"""
Interpolate x, y using Lagrange polynomials
https://en.wikipedia.org/wiki/Lagrange_polynomial
"""
n = len(x) - 1
delta_x = [x2 - x1 for x1, x2 in zip(x, x[1:])]
for i in range(n + 1):
yield x[i], y[i]
if i == n or delta_x[i] == 0:
continue
for s in range(1, precision):
X = x[i] + s * delta_x[i] / precision
s = 0
for k in range(n + 1):
p = 1
for m in range(n + 1):
if m == k:
continue
if x[k] - x[m]:
p *= (X - x[m]) / (x[k] - x[m])
s += y[k] * p
yield X, s
def trigonometric_interpolate(x, y, precision=250, **kwargs):
"""
Interpolate x, y using trigonometric
As per http://en.wikipedia.org/wiki/Trigonometric_interpolation
"""
n = len(x) - 1
delta_x = [x2 - x1 for x1, x2 in zip(x, x[1:])]
for i in range(n + 1):
yield x[i], y[i]
if i == n or delta_x[i] == 0:
continue
for s in range(1, precision):
X = x[i] + s * delta_x[i] / precision
s = 0
for k in range(n + 1):
p = 1
for m in range(n + 1):
if m == k:
continue
if sin(0.5 * (x[k] - x[m])):
p *= sin(0.5 * (X - x[m])) / sin(0.5 * (x[k] - x[m]))
s += y[k] * p
yield X, s
INTERPOLATIONS = {
'quadratic': quadratic_interpolate,
'cubic': cubic_interpolate,
'hermite': hermite_interpolate,
'lagrange': lagrange_interpolate,
'trigonometric': trigonometric_interpolate
}
if __name__ == '__main__':
from pygal import XY
points = [(.1, 7), (.3, -4), (.6, 10), (.9, 8), (1.4, 3), (1.7, 1)]
xy = XY(show_dots=False)
xy.add('normal', points)
xy.add('quadratic', quadratic_interpolate(*zip(*points)))
xy.add('cubic', cubic_interpolate(*zip(*points)))
xy.add('lagrange', lagrange_interpolate(*zip(*points)))
xy.add('trigonometric', trigonometric_interpolate(*zip(*points)))
xy.add(
'hermite catmul_rom',
hermite_interpolate(*zip(*points), type='catmul_rom')
)
xy.add(
'hermite finite_difference',
hermite_interpolate(*zip(*points), type='finite_difference')
)
xy.add(
'hermite cardinal -.5',
hermite_interpolate(*zip(*points), type='cardinal', c=-.5)
)
xy.add(
'hermite cardinal .5',
hermite_interpolate(*zip(*points), type='cardinal', c=.5)
)
xy.add(
'hermite kochanek_bartels .5 .75 -.25',
hermite_interpolate(
*zip(*points), type='kochanek_bartels', c=.5, b=.75, t=-.25
)
)
xy.add(
'hermite kochanek_bartels .25 -.75 .5',
hermite_interpolate(
*zip(*points), type='kochanek_bartels', c=.25, b=-.75, t=.5
)
)
xy.render_in_browser()
| 8,614
|
Python
|
.py
| 242
| 27.586777
| 79
| 0.489556
|
Kozea/pygal
| 2,634
| 411
| 197
|
LGPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,287
|
serie.py
|
Kozea_pygal/pygal/serie.py
|
# -*- coding: utf-8 -*-
# This file is part of pygal
#
# A python svg graph plotting library
# Copyright © 2012-2016 Kozea
#
# This library is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This library 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 Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with pygal. If not, see <http://www.gnu.org/licenses/>.
"""Serie property holder"""
from pygal.util import cached_property
class Serie(object):
"""Serie class containing title, values and the graph serie index"""
def __init__(self, index, values, config, metadata=None):
"""Create the serie with its options"""
self.index = index
self.values = values
self.config = config
self.__dict__.update(config.__dict__)
self.metadata = metadata or {}
@cached_property
def safe_values(self):
"""Property containing all values that are not None"""
return list(filter(lambda x: x is not None, self.values))
| 1,396
|
Python
|
.py
| 33
| 38.727273
| 79
| 0.71944
|
Kozea/pygal
| 2,634
| 411
| 197
|
LGPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,288
|
config.py
|
Kozea_pygal/pygal/config.py
|
# -*- coding: utf-8 -*-
# This file is part of pygal
#
# A python svg graph plotting library
# Copyright © 2012-2016 Kozea
#
# This library is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This library 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 Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with pygal. If not, see <http://www.gnu.org/licenses/>.
"""Config module holding all options and their default values."""
from copy import deepcopy
from pygal import formatters
from pygal.interpolate import INTERPOLATIONS
from pygal.style import DefaultStyle, Style
CONFIG_ITEMS = []
callable = type(lambda: 1)
class Key(object):
"""
Represents a config parameter.
A config parameter has a name, a default value, a type,
a category, a documentation, an optional longer documentatation
and an optional subtype for list style option.
Most of these informations are used in cabaret to auto generate
forms representing these options.
"""
_categories = []
def __init__(
self, default_value, type_, category, doc, subdoc="", subtype=None
):
"""Create a configuration key"""
self.value = default_value
self.type = type_
self.doc = doc
self.category = category
self.subdoc = subdoc
self.subtype = subtype
self.name = "Unbound"
if category not in self._categories:
self._categories.append(category)
CONFIG_ITEMS.append(self)
def __repr__(self):
"""
Make a documentation repr.
This is a hack to generate doc from inner doc
"""
return """
Type: %s%s
Default: %r
%s%s
""" % (
self.type.__name__, (' of %s' % self.subtype.__name__)
if self.subtype else '', self.value, self.doc,
(' %s' % self.subdoc) if self.subdoc else ''
)
@property
def is_boolean(self):
"""Return `True` if this parameter is a boolean"""
return self.type == bool
@property
def is_numeric(self):
"""Return `True` if this parameter is numeric (int or float)"""
return self.type in (int, float)
@property
def is_string(self):
"""Return `True` if this parameter is a string"""
return self.type == str
@property
def is_dict(self):
"""Return `True` if this parameter is a mapping"""
return self.type == dict
@property
def is_list(self):
"""Return `True` if this parameter is a list"""
return self.type == list
def coerce(self, value):
"""Cast a string into this key type"""
if self.type == Style:
return value
elif self.type == list:
return self.type(
map(self.subtype, map(lambda x: x.strip(), value.split(',')))
)
elif self.type == dict:
rv = {}
for pair in value.split(','):
key, val = pair.split(':')
key = key.strip()
val = val.strip()
try:
rv[key] = self.subtype(val)
except Exception:
rv[key] = val
return rv
return self.type(value)
class MetaConfig(type):
"""Config metaclass. Used to get the key name and set it on the value."""
def __new__(mcs, classname, bases, classdict):
"""Get the name of the key and set it on the key"""
for k, v in classdict.items():
if isinstance(v, Key):
v.name = k
return type.__new__(mcs, classname, bases, classdict)
class BaseConfig(MetaConfig('ConfigBase', (object, ), {})):
"""
This class holds the common method for configs.
A config object can be instanciated with keyword arguments and
updated on call with keyword arguments.
"""
def __init__(self, **kwargs):
"""Can be instanciated with config kwargs"""
for k in dir(self):
v = getattr(self, k)
if (k not in self.__dict__ and not k.startswith('_')
and not hasattr(v, '__call__')):
if isinstance(v, Key):
if v.is_list and v.value is not None:
v = list(v.value)
else:
v = v.value
setattr(self, k, v)
self._update(kwargs)
def __call__(self, **kwargs):
"""Can be updated with kwargs"""
self._update(kwargs)
def _update(self, kwargs):
"""Update the config with the given dictionary"""
from pygal.util import merge
dir_self_set = set(dir(self))
merge(
self.__dict__,
dict([(k, v) for (k, v) in kwargs.items()
if not k.startswith('_') and k in dir_self_set])
)
def to_dict(self):
"""Export a JSON serializable dictionary of the config"""
config = {}
for attr in dir(self):
if not attr.startswith('__'):
value = getattr(self, attr)
if hasattr(value, 'to_dict'):
config[attr] = value.to_dict()
elif not hasattr(value, '__call__'):
config[attr] = value
return config
def copy(self):
"""Copy this config object into another"""
return deepcopy(self)
class CommonConfig(BaseConfig):
"""Class holding options used in both chart and serie configuration"""
stroke = Key(
True, bool, "Look", "Line dots (set it to false to get a scatter plot)"
)
show_dots = Key(True, bool, "Look", "Set to false to remove dots")
show_only_major_dots = Key(
False, bool, "Look",
"Set to true to show only major dots according to their majored label"
)
dots_size = Key(2.5, float, "Look", "Radius of the dots")
fill = Key(False, bool, "Look", "Fill areas under lines")
stroke_style = Key(
None, dict, "Look", "Stroke style of serie element.",
"This is a dict which can contain a "
"'width', 'linejoin', 'linecap', 'dasharray' "
"and 'dashoffset'"
)
rounded_bars = Key(
None, int, "Look",
"Set this to the desired radius in px (for Bar-like charts)"
)
inner_radius = Key(
0, float, "Look", "Piechart inner radius (donut), must be <.9"
)
allow_interruptions = Key(
False, bool, "Look", "Break lines on None values"
)
formatter = Key(
None, callable, "Value",
"A function to convert raw value to strings for this chart or serie",
"Default to value_formatter in most charts, it depends on dual charts."
"(Can be overriden by value with the formatter metadata.)"
)
class Config(CommonConfig):
"""Class holding config values"""
style = Key(
DefaultStyle, Style, "Style", "Style holding values injected in css"
)
css = Key(
('file://style.css', 'file://graph.css'), list, "Style",
"List of css file",
"It can be any uri from file:///tmp/style.css to //domain/style.css",
str
)
classes = Key(('pygal-chart', ), list, "Style",
"Classes of the root svg node", str)
defs = Key([], list, "Misc", "Extraneous defs to be inserted in svg",
"Useful for adding gradients / patterns…", str)
# Look #
title = Key(
None, str, "Look", "Graph title.", "Leave it to None to disable title."
)
x_title = Key(
None, str, "Look", "Graph X-Axis title.",
"Leave it to None to disable X-Axis title."
)
y_title = Key(
None, str, "Look", "Graph Y-Axis title.",
"Leave it to None to disable Y-Axis title."
)
width = Key(800, int, "Look", "Graph width")
height = Key(600, int, "Look", "Graph height")
show_x_guides = Key(
False, bool, "Look", "Set to true to always show x guide lines"
)
show_y_guides = Key(
True, bool, "Look", "Set to false to hide y guide lines"
)
show_legend = Key(True, bool, "Look", "Set to false to remove legend")
legend_at_bottom = Key(
False, bool, "Look", "Set to true to position legend at bottom"
)
legend_at_bottom_columns = Key(
None, int, "Look", "Set to true to position legend at bottom"
)
legend_box_size = Key(12, int, "Look", "Size of legend boxes")
rounded_bars = Key(
None, int, "Look", "Set this to the desired radius in px"
)
stack_from_top = Key(
False, bool, "Look", "Stack from top to zero, this makes the stacked "
"data match the legend order"
)
spacing = Key(10, int, "Look", "Space between titles/legend/axes")
margin = Key(20, int, "Look", "Margin around chart")
margin_top = Key(None, int, "Look", "Margin around top of chart")
margin_right = Key(None, int, "Look", "Margin around right of chart")
margin_bottom = Key(None, int, "Look", "Margin around bottom of chart")
margin_left = Key(None, int, "Look", "Margin around left of chart")
tooltip_border_radius = Key(0, int, "Look", "Tooltip border radius")
tooltip_fancy_mode = Key(
True, bool, "Look", "Fancy tooltips",
"Print legend, x label in tooltip and use serie color for value."
)
inner_radius = Key(
0, float, "Look", "Piechart inner radius (donut), must be <.9"
)
half_pie = Key(False, bool, "Look", "Create a half-pie chart")
x_labels = Key(
None, list, "Label", "X labels, must have same len than data.",
"Leave it to None to disable x labels display.", str
)
x_labels_major = Key(
None,
list,
"Label",
"X labels that will be marked major.",
subtype=str
)
x_labels_major_every = Key(
None, int, "Label", "Mark every n-th x label as major."
)
x_labels_major_count = Key(
None, int, "Label", "Mark n evenly distributed labels as major."
)
show_x_labels = Key(True, bool, "Label", "Set to false to hide x-labels")
show_minor_x_labels = Key(
True, bool, "Label", "Set to false to hide x-labels not marked major"
)
y_labels = Key(
None, list, "Label", "You can specify explicit y labels",
"Must be a list of numbers", float
)
y_labels_major = Key(
None,
list,
"Label",
"Y labels that will be marked major. Default: auto",
subtype=str
)
y_labels_major_every = Key(
None, int, "Label", "Mark every n-th y label as major."
)
y_labels_major_count = Key(
None, int, "Label", "Mark n evenly distributed y labels as major."
)
show_minor_y_labels = Key(
True, bool, "Label", "Set to false to hide y-labels not marked major"
)
show_y_labels = Key(True, bool, "Label", "Set to false to hide y-labels")
x_label_rotation = Key(
0, int, "Label", "Specify x labels rotation angles", "in degrees"
)
y_label_rotation = Key(
0, int, "Label", "Specify y labels rotation angles", "in degrees"
)
missing_value_fill_truncation = Key(
"x", str, "Look",
"Filled series with missing x and/or y values at the end of a series "
"are closed at the first value with a missing "
"'x' (default), 'y' or 'either'"
)
# Value #
x_value_formatter = Key(
formatters.default, callable, "Value",
"A function to convert abscissa numeric value to strings "
"(used in XY and Date charts)"
)
value_formatter = Key(
formatters.default, callable, "Value",
"A function to convert ordinate numeric value to strings"
)
logarithmic = Key(
False, bool, "Value", "Display values in logarithmic scale"
)
interpolate = Key(
None, str, "Value", "Interpolation",
"May be %s" % ' or '.join(INTERPOLATIONS)
)
interpolation_precision = Key(
250, int, "Value", "Number of interpolated points between two values"
)
interpolation_parameters = Key(
{}, dict, "Value", "Various parameters for parametric interpolations",
"ie: For hermite interpolation, you can set the cardinal tension with"
"{'type': 'cardinal', 'c': .5}", int
)
box_mode = Key(
'extremes', str, "Value", "Sets the mode to be used. "
"(Currently only supported on box plot)", "May be %s" %
' or '.join(["1.5IQR", "extremes", "tukey", "stdev", "pstdev"])
)
order_min = Key(
None, int, "Value", "Minimum order of scale, defaults to None"
)
min_scale = Key(
4, int, "Value", "Minimum number of scale graduation for auto scaling"
)
max_scale = Key(
16, int, "Value", "Maximum number of scale graduation for auto scaling"
)
range = Key(
None, list, "Value", "Explicitly specify min and max of values",
"(ie: (0, 100))", int
)
secondary_range = Key(
None, list, "Value",
"Explicitly specify min and max of secondary values", "(ie: (0, 100))",
int
)
xrange = Key(
None, list, "Value", "Explicitly specify min and max of x values "
"(used in XY and Date charts)", "(ie: (0, 100))", int
)
include_x_axis = Key(False, bool, "Value", "Always include x axis")
zero = Key(
0, int, "Value", "Set the ordinate zero value",
"Useful for filling to another base than abscissa"
)
# Text #
no_data_text = Key(
"No data", str, "Text", "Text to display when no data is given"
)
print_values = Key(False, bool, "Text", "Display values as text over plot")
dynamic_print_values = Key(
False, bool, "Text", "Show values only on hover"
)
print_values_position = Key(
'center', str, "Text", "Customize position of `print_values`. "
"(For bars: `top`, `center` or `bottom`)"
)
print_zeroes = Key(True, bool, "Text", "Display zero values as well")
print_labels = Key(False, bool, "Text", "Display value labels")
truncate_legend = Key(
None, int, "Text", "Legend string length truncation threshold",
"None = auto, Negative for none"
)
truncate_label = Key(
None, int, "Text", "Label string length truncation threshold",
"None = auto, Negative for none"
)
# Misc #
js = Key(('//kozea.github.io/pygal.js/2.0.x/pygal-tooltips.min.js', ),
list, "Misc", "List of js file",
"It can be any uri from file:///tmp/ext.js to //domain/ext.js",
str)
disable_xml_declaration = Key(
False, bool, "Misc",
"Don't write xml declaration and return str instead of string",
"useful for writing output directly in html"
)
force_uri_protocol = Key(
'https', str, "Misc", "Default uri protocol",
"Default protocol for external files. "
"Can be set to None to use a // uri"
)
explicit_size = Key(
False, bool, "Misc", "Write width and height attributes"
)
pretty_print = Key(False, bool, "Misc", "Pretty print the svg")
strict = Key(
False, bool, "Misc", "If True don't try to adapt / filter wrong values"
)
no_prefix = Key(False, bool, "Misc", "Don't prefix css")
inverse_y_axis = Key(False, bool, "Misc", "Inverse Y axis direction")
class SerieConfig(CommonConfig):
"""Class holding serie config values"""
title = Key(
None, str, "Look", "Serie title.", "Leave it to None to disable title."
)
secondary = Key(
False, bool, "Misc", "Set it to put the serie in a second axis"
)
| 16,149
|
Python
|
.py
| 420
| 30.742857
| 79
| 0.594451
|
Kozea/pygal
| 2,634
| 411
| 197
|
LGPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,289
|
style.py
|
Kozea_pygal/pygal/style.py
|
# -*- coding: utf-8 -*-
# This file is part of pygal
#
# A python svg graph plotting library
# Copyright © 2012-2016 Kozea
#
# This library is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This library 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 Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with pygal. If not, see <http://www.gnu.org/licenses/>.
"""Charts styling classes"""
from __future__ import division
from itertools import chain
from pygal import colors
from pygal.colors import darken, is_foreground_light, lighten
class Style(object):
"""Styling class containing colors for the css generation"""
plot_background = 'rgba(255, 255, 255, 1)'
background = 'rgba(249, 249, 249, 1)'
value_background = 'rgba(229, 229, 229, 1)'
foreground = 'rgba(0, 0, 0, .87)'
foreground_strong = 'rgba(0, 0, 0, 1)'
foreground_subtle = 'rgba(0, 0, 0, .54)'
# Monospaced font is highly encouraged
font_family = ('Consolas, "Liberation Mono", Menlo, Courier, monospace')
label_font_family = None
major_label_font_family = None
value_font_family = None
value_label_font_family = None
tooltip_font_family = None
title_font_family = None
legend_font_family = None
no_data_font_family = None
label_font_size = 10
major_label_font_size = 10
value_font_size = 16
value_label_font_size = 10
tooltip_font_size = 14
title_font_size = 16
legend_font_size = 14
no_data_font_size = 64
# Guide line dash array style
guide_stroke_dasharray = '4,4'
major_guide_stroke_dasharray = '6,6'
guide_stroke_color = 'black'
major_guide_stroke_color = 'black'
opacity = '.7'
opacity_hover = '.8'
stroke_opacity = '.8'
stroke_width = '1'
stroke_opacity_hover = '.9'
stroke_width_hover = '4'
dot_opacity = '1'
transition = '150ms'
colors = (
'#F44336', # 0
'#3F51B5', # 4
'#009688', # 8
'#FFC107', # 13
'#FF5722', # 15
'#9C27B0', # 2
'#03A9F4', # 6
'#8BC34A', # 10
'#FF9800', # 14
'#E91E63', # 1
'#2196F3', # 5
'#4CAF50', # 9
'#FFEB3B', # 12
'#673AB7', # 3
'#00BCD4', # 7
'#CDDC39', # 11b
'#9E9E9E', # 17
'#607D8B', # 18
)
value_colors = ()
ci_colors = ()
def __init__(self, **kwargs):
"""Create the style"""
self.__dict__.update(kwargs)
self._google_fonts = set()
if self.font_family.startswith('googlefont:'):
self.font_family = self.font_family.replace('googlefont:', '')
self._google_fonts.add(self.font_family.split(',')[0].strip())
for name in dir(self):
if name.endswith('_font_family'):
fn = getattr(self, name)
if fn is None:
setattr(self, name, self.font_family)
elif fn.startswith('googlefont:'):
setattr(self, name, fn.replace('googlefont:', ''))
self._google_fonts.add(
getattr(self, name).split(',')[0].strip()
)
def get_colors(self, prefix, len_):
"""Get the css color list"""
def color(tupl):
"""Make a color css"""
return ((
'%s.color-{0}, %s.color-{0} a:visited {{\n'
' stroke: {1};\n'
' fill: {1};\n'
'}}\n'
) % (prefix, prefix)).format(*tupl)
def value_color(tupl):
"""Make a value color css"""
return ((
'%s .text-overlay .color-{0} text {{\n'
' fill: {1};\n'
'}}\n'
) % (prefix, )).format(*tupl)
def ci_color(tupl):
"""Make a value color css"""
if not tupl[1]:
return ''
return (('%s .color-{0} .ci {{\n'
' stroke: {1};\n'
'}}\n') % (prefix, )).format(*tupl)
if len(self.colors) < len_:
missing = len_ - len(self.colors)
cycles = 1 + missing // len(self.colors)
colors = []
for i in range(0, cycles + 1):
for color_ in self.colors:
colors.append(darken(color_, 33 * i / cycles))
if len(colors) >= len_:
break
else:
continue
break
else:
colors = self.colors[:len_]
# Auto compute foreground value color when color is missing
value_colors = []
for i in range(len_):
if i < len(self.value_colors) and self.value_colors[i] is not None:
value_colors.append(self.value_colors[i])
else:
value_colors.append(
'white' if is_foreground_light(colors[i]) else 'black'
)
return '\n'.join(
chain(
map(color, enumerate(colors)),
map(value_color, enumerate(value_colors)),
map(ci_color, enumerate(self.ci_colors))
)
)
def to_dict(self):
"""Convert instance to a serializable mapping."""
config = {}
for attr in dir(self):
if not attr.startswith('_'):
value = getattr(self, attr)
if not hasattr(value, '__call__'):
config[attr] = value
return config
DefaultStyle = Style
class DarkStyle(Style):
"""A dark style (old default)"""
background = 'black'
plot_background = '#111'
foreground = '#999'
foreground_strong = '#eee'
foreground_subtle = '#555'
opacity = '.8'
opacity_hover = '.4'
transition = '250ms'
colors = (
'#ff5995', '#b6e354', '#feed6c', '#8cedff', '#9e6ffe', '#899ca1',
'#f8f8f2', '#bf4646', '#516083', '#f92672', '#82b414', '#fd971f',
'#56c2d6', '#808384', '#8c54fe', '#465457'
)
class LightStyle(Style):
"""A light style"""
background = 'white'
plot_background = 'rgba(0, 0, 255, 0.1)'
foreground = 'rgba(0, 0, 0, 0.7)'
foreground_strong = 'rgba(0, 0, 0, 0.9)'
foreground_subtle = 'rgba(0, 0, 0, 0.5)'
colors = (
'#242424', '#9f6767', '#92ac68', '#d0d293', '#9aacc3', '#bb77a4',
'#77bbb5', '#777777'
)
class NeonStyle(DarkStyle):
"""Similar to DarkStyle but with more opacity and effects"""
opacity = '.1'
opacity_hover = '.75'
transition = '1s ease-out'
class CleanStyle(Style):
"""A rather clean style"""
background = 'transparent'
plot_background = 'rgba(240, 240, 240, 0.7)'
foreground = 'rgba(0, 0, 0, 0.9)'
foreground_strong = 'rgba(0, 0, 0, 0.9)'
foreground_subtle = 'rgba(0, 0, 0, 0.5)'
colors = (
'rgb(12,55,149)', 'rgb(117,38,65)', 'rgb(228,127,0)', 'rgb(159,170,0)',
'rgb(149,12,12)'
)
class DarkSolarizedStyle(Style):
"""Dark solarized popular theme"""
background = '#073642'
plot_background = '#002b36'
foreground = '#839496'
foreground_strong = '#fdf6e3'
foreground_subtle = '#657b83'
opacity = '.66'
opacity_hover = '.9'
transition = '500ms ease-in'
colors = (
'#b58900', '#cb4b16', '#dc322f', '#d33682', '#6c71c4', '#268bd2',
'#2aa198', '#859900'
)
class LightSolarizedStyle(DarkSolarizedStyle):
"""Light solarized popular theme"""
background = '#fdf6e3'
plot_background = '#eee8d5'
foreground = '#657b83'
foreground_strong = '#073642'
foreground_subtle = '#073642'
class RedBlueStyle(Style):
"""A red and blue theme"""
background = lighten('#e6e7e9', 7)
plot_background = lighten('#e6e7e9', 10)
foreground = 'rgba(0, 0, 0, 0.9)'
foreground_strong = 'rgba(0, 0, 0, 0.9)'
foreground_subtle = 'rgba(0, 0, 0, 0.5)'
opacity = '.6'
opacity_hover = '.9'
colors = (
'#d94e4c', '#e5884f', '#39929a', lighten('#d94e4c', 10),
darken('#39929a', 15), lighten('#e5884f', 17), darken('#d94e4c', 10),
'#234547'
)
class LightColorizedStyle(Style):
"""A light colorized style"""
background = '#f8f8f8'
plot_background = lighten('#f8f8f8', 3)
foreground = '#333'
foreground_strong = '#666'
foreground_subtle = 'rgba(0, 0 , 0, 0.5)'
opacity = '.5'
opacity_hover = '.9'
transition = '250ms ease-in'
colors = (
'#fe9592', '#534f4c', '#3ac2c0', '#a2a7a1', darken('#fe9592', 15),
lighten('#534f4c', 15), lighten('#3ac2c0', 15), lighten('#a2a7a1', 15),
lighten('#fe9592', 15), darken('#3ac2c0', 10)
)
class DarkColorizedStyle(Style):
"""A dark colorized style"""
background = darken('#3a2d3f', 5)
plot_background = lighten('#3a2d3f', 2)
foreground = 'rgba(255, 255, 255, 0.9)'
foreground_strong = 'rgba(255, 255, 255, 0.9)'
foreground_subtle = 'rgba(255, 255 , 255, 0.5)'
opacity = '.2'
opacity_hover = '.7'
transition = '250ms ease-in'
colors = (
'#c900fe', '#01b8fe', '#59f500', '#ff00e4', '#f9fa00',
darken('#c900fe', 20), darken('#01b8fe', 15), darken('#59f500', 20),
darken('#ff00e4', 15), lighten('#f9fa00', 20)
)
class TurquoiseStyle(Style):
"""A turquoise style"""
background = darken('#1b8088', 15)
plot_background = darken('#1b8088', 17)
foreground = 'rgba(255, 255, 255, 0.9)'
foreground_strong = 'rgba(255, 255, 255, 0.9)'
foreground_subtle = 'rgba(255, 255 , 255, 0.5)'
opacity = '.5'
opacity_hover = '.9'
transition = '250ms ease-in'
colors = (
'#93d2d9', '#ef940f', '#8C6243', '#fff', darken('#93d2d9', 20),
lighten('#ef940f', 15), lighten('#8c6243', 15), '#1b8088'
)
class LightGreenStyle(Style):
"""A light green style"""
background = lighten('#f3f3f3', 3)
plot_background = '#fff'
foreground = '#333333'
foreground_strong = '#666'
foreground_subtle = '#222222'
opacity = '.5'
opacity_hover = '.9'
transition = '250ms ease-in'
colors = (
'#7dcf30', '#247fab', lighten('#7dcf30', 10), '#ccc',
darken('#7dcf30', 15), '#ddd', lighten('#247fab', 10),
darken('#247fab', 15)
)
class DarkGreenStyle(Style):
"""A dark green style"""
background = darken('#251e01', 3)
plot_background = darken('#251e01', 1)
foreground = 'rgba(255, 255, 255, 0.9)'
foreground_strong = 'rgba(255, 255, 255, 0.9)'
foreground_subtle = 'rgba(255, 255, 255, 0.6)'
opacity = '.6'
opacity_hover = '.9'
transition = '250ms ease-in'
colors = (
'#adde09', '#6e8c06', '#4a5e04', '#fcd202', '#C1E34D',
lighten('#fcd202', 25)
)
class DarkGreenBlueStyle(Style):
"""A dark green and blue style"""
background = '#000'
plot_background = lighten('#000', 8)
foreground = 'rgba(255, 255, 255, 0.9)'
foreground_strong = 'rgba(255, 255, 255, 0.9)'
foreground_subtle = 'rgba(255, 255, 255, 0.6)'
opacity = '.55'
opacity_hover = '.9'
transition = '250ms ease-in'
colors = (
lighten('#34B8F7', 15), '#7dcf30', '#247fab', darken('#7dcf30', 10),
lighten('#247fab', 10), lighten('#7dcf30', 10), darken('#247fab', 10),
'#fff'
)
class BlueStyle(Style):
"""A blue style"""
background = darken('#f8f8f8', 3)
plot_background = '#f8f8f8'
foreground = 'rgba(0, 0, 0, 0.9)'
foreground_strong = 'rgba(0, 0, 0, 0.9)'
foreground_subtle = 'rgba(0, 0, 0, 0.6)'
opacity = '.5'
opacity_hover = '.9'
transition = '250ms ease-in'
colors = (
'#00b2f0', '#43d9be', '#0662ab', darken('#00b2f0', 20),
lighten('#43d9be', 20), lighten('#7dcf30', 10), darken('#0662ab', 15),
'#ffd541', '#7dcf30', lighten('#00b2f0', 15), darken('#ffd541', 20)
)
class SolidColorStyle(Style):
"""A light style with strong colors"""
background = '#FFFFFF'
plot_background = '#FFFFFF'
foreground = '#000000'
foreground_strong = '#000000'
foreground_subtle = '#828282'
opacity = '.8'
opacity_hover = '.9'
transition = '400ms ease-in'
colors = (
'#FF9900', '#DC3912', '#4674D1', '#109618', '#990099', '#0099C6',
'#DD4477', '#74B217', '#B82E2E', '#316395', '#994499'
)
styles = {
'default': DefaultStyle,
'dark': DarkStyle,
'light': LightStyle,
'neon': NeonStyle,
'clean': CleanStyle,
'light_red_blue': RedBlueStyle,
'dark_solarized': DarkSolarizedStyle,
'light_solarized': LightSolarizedStyle,
'dark_colorized': DarkColorizedStyle,
'light_colorized': LightColorizedStyle,
'turquoise': TurquoiseStyle,
'green': LightGreenStyle,
'dark_green': DarkGreenStyle,
'dark_green_blue': DarkGreenBlueStyle,
'blue': BlueStyle,
'solid_color': SolidColorStyle
}
class ParametricStyleBase(Style):
"""Parametric Style base class for all the parametric operations"""
_op = None
def __init__(self, color, step=10, max_=None, base_style=None, **kwargs):
"""
Initialization of the parametric style.
This takes several parameters:
* a `step` which correspond on how many colors will be needed
* a `max_` which defines the maximum amplitude of the color effect
* a `base_style` which will be taken as default for everything
except colors
* any keyword arguments setting other style parameters
"""
if self._op is None:
raise RuntimeError('ParametricStyle is not instanciable')
defaults = {}
if base_style is not None:
if isinstance(base_style, type):
base_style = base_style()
defaults.update(base_style.to_dict())
defaults.update(kwargs)
super(ParametricStyleBase, self).__init__(**defaults)
if max_ is None:
violency = {
'darken': 50,
'lighten': 50,
'saturate': 100,
'desaturate': 100,
'rotate': 360
}
max_ = violency[self._op]
def modifier(index):
percent = max_ * index / (step - 1)
return getattr(colors, self._op)(color, percent)
self.colors = list(map(modifier, range(0, max(2, step))))
class LightenStyle(ParametricStyleBase):
"""Create a style by lightening the given color"""
_op = 'lighten'
class DarkenStyle(ParametricStyleBase):
"""Create a style by darkening the given color"""
_op = 'darken'
class SaturateStyle(ParametricStyleBase):
"""Create a style by saturating the given color"""
_op = 'saturate'
class DesaturateStyle(ParametricStyleBase):
"""Create a style by desaturating the given color"""
_op = 'desaturate'
class RotateStyle(ParametricStyleBase):
"""Create a style by rotating the given color"""
_op = 'rotate'
parametric_styles = {
'lighten': LightenStyle,
'darken': DarkenStyle,
'saturate': SaturateStyle,
'desaturate': DesaturateStyle,
'rotate': RotateStyle
}
| 15,595
|
Python
|
.py
| 434
| 28.490783
| 79
| 0.573411
|
Kozea/pygal
| 2,634
| 411
| 197
|
LGPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,290
|
etree.py
|
Kozea_pygal/pygal/etree.py
|
# -*- coding: utf-8 -*-
# This file is part of pygal
#
# A python svg graph plotting library
# Copyright © 2012-2016 Kozea
#
# This library is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This library 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 Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with pygal. If not, see <http://www.gnu.org/licenses/>.
"""
Wrapper for seamless lxml.etree / xml.etree usage
depending on whether lxml is installed or not.
"""
import os
class Etree(object):
"""Etree wrapper using lxml.etree or standard xml.etree"""
def __init__(self):
"""Create the wrapper"""
from xml.etree import ElementTree as _py_etree
self._py_etree = _py_etree
try:
from lxml import etree as _lxml_etree
self._lxml_etree = _lxml_etree
except ImportError:
self._lxml_etree = None
if os.getenv('NO_LXML', None):
self._etree = self._py_etree
else:
self._etree = self._lxml_etree or self._py_etree
self.lxml = self._etree is self._lxml_etree
def __getattribute__(self, attr):
"""Retrieve attr from current active etree implementation"""
if (attr not in object.__getattribute__(self, '__dict__')
and attr not in Etree.__dict__):
return object.__getattribute__(self._etree, attr)
return object.__getattribute__(self, attr)
def to_lxml(self):
"""Force lxml.etree to be used"""
self._etree = self._lxml_etree
self.lxml = True
def to_etree(self):
"""Force xml.etree to be used"""
self._etree = self._py_etree
self.lxml = False
etree = Etree()
| 2,114
|
Python
|
.py
| 54
| 33.444444
| 79
| 0.661463
|
Kozea/pygal
| 2,634
| 411
| 197
|
LGPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,291
|
formatters.py
|
Kozea_pygal/pygal/formatters.py
|
# -*- coding: utf-8 -*-
# This file is part of pygal
#
# A python svg graph plotting library
# Copyright © 2012-2016 Kozea
#
# This library is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This library 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 Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with pygal. If not, see <http://www.gnu.org/licenses/>.
"""
Formatters to use with `value_formatter` and `x_value_formatter` configs
"""
from __future__ import division
from datetime import date, datetime, time
from math import floor, log
from pygal.util import float_format
class Formatter(object):
pass
class HumanReadable(Formatter):
"""Format a number to engineer scale"""
ORDERS = "yzafpnµm kMGTPEZY"
def __init__(self, none_char='∅'):
self.none_char = none_char
def __call__(self, val):
if val is None:
return self.none_char
order = val and int(floor(log(abs(val)) / log(1000)))
orders = self.ORDERS.split(" ")[int(order > 0)]
if order == 0 or order > len(orders):
return float_format(val / (1000**int(order)))
return (
float_format(val / (1000**int(order))) +
orders[int(order) - int(order > 0)]
)
class Significant(Formatter):
"""Show precision significant digit of float"""
def __init__(self, precision=10):
self.format = '%%.%dg' % precision
def __call__(self, val):
if val is None:
return ''
return self.format % val
class Integer(Formatter):
"""Cast number to integer"""
def __call__(self, val):
if val is None:
return ''
return '%d' % val
class Raw(Formatter):
"""Cast everything to string"""
def __call__(self, val):
if val is None:
return ''
return str(val)
class IsoDateTime(Formatter):
"""Iso format datetimes"""
def __call__(self, val):
if val is None:
return ''
return val.isoformat()
class Default(Significant, IsoDateTime, Raw):
"""Try to guess best format from type"""
def __call__(self, val):
if val is None:
return ''
if isinstance(val, (int, float)):
return Significant.__call__(self, val)
if isinstance(val, (date, time, datetime)):
return IsoDateTime.__call__(self, val)
return Raw.__call__(self, val)
# Formatters with default options
human_readable = HumanReadable()
significant = Significant()
integer = Integer()
raw = Raw()
# Default config formatter
default = Default()
| 3,007
|
Python
|
.py
| 86
| 29.453488
| 79
| 0.649013
|
Kozea/pygal
| 2,634
| 411
| 197
|
LGPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,292
|
__init__.py
|
Kozea_pygal/pygal/__init__.py
|
# -*- coding: utf-8 -*-
# This file is part of pygal
#
# A python svg graph plotting library
# Copyright © 2012-2016 Kozea
#
# This library is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This library 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 Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with pygal. If not, see <http://www.gnu.org/licenses/>.
"""
Main pygal package.
This package holds all available charts in pygal, the Config class
and the maps extensions namespace module.
"""
from .__about__ import * # noqa: F401,F403 isort: skip
import sys
import traceback
import warnings
from importlib_metadata import entry_points
from pygal import maps
from pygal.config import Config
from pygal.graph.bar import Bar
from pygal.graph.box import Box
from pygal.graph.dot import Dot
from pygal.graph.funnel import Funnel
from pygal.graph.gauge import Gauge
from pygal.graph.graph import Graph
from pygal.graph.histogram import Histogram
from pygal.graph.horizontalbar import HorizontalBar
from pygal.graph.horizontalline import HorizontalLine
from pygal.graph.horizontalstackedbar import HorizontalStackedBar
from pygal.graph.horizontalstackedline import HorizontalStackedLine
from pygal.graph.line import Line
from pygal.graph.pie import Pie
from pygal.graph.pyramid import Pyramid, VerticalPyramid
from pygal.graph.radar import Radar
from pygal.graph.solidgauge import SolidGauge
from pygal.graph.stackedbar import StackedBar
from pygal.graph.stackedline import StackedLine
from pygal.graph.time import DateLine, DateTimeLine, TimeDeltaLine, TimeLine
from pygal.graph.treemap import Treemap
from pygal.graph.xy import XY
CHARTS_BY_NAME = dict([
(k, v) for k, v in locals().items()
if isinstance(v, type) and issubclass(v, Graph) and v != Graph
])
from pygal.graph.map import BaseMap
for entry in entry_points(group="pygal.maps"):
try:
module = entry.load()
except Exception:
warnings.warn(
'Unable to load %s pygal plugin \n\n%s' %
(entry, traceback.format_exc()), Warning
)
continue
setattr(maps, entry.name, module)
for k, v in module.__dict__.items():
if isinstance(v, type) and issubclass(v, BaseMap) and v != BaseMap:
CHARTS_BY_NAME[entry.name.capitalize() + k + 'Map'] = v
CHARTS_NAMES = list(CHARTS_BY_NAME.keys())
CHARTS = list(CHARTS_BY_NAME.values())
class PluginImportFixer(object):
"""
Allow external map plugins to be imported from pygal.maps package.
It is a ``sys.meta_path`` loader.
"""
def find_module(self, fullname, path=None):
"""
Tell if the module to load can be loaded by
the load_module function, ie: if it is a ``pygal.maps.*``
module.
"""
if fullname.startswith('pygal.maps.') and hasattr(
maps, fullname.split('.')[2]):
return self
return None
def load_module(self, name):
"""
Load the ``pygal.maps.name`` module from the previously
loaded plugin
"""
if name not in sys.modules:
sys.modules[name] = getattr(maps, name.split('.')[2])
return sys.modules[name]
sys.meta_path += [PluginImportFixer()]
| 3,632
|
Python
|
.py
| 95
| 34.242105
| 79
| 0.729906
|
Kozea/pygal
| 2,634
| 411
| 197
|
LGPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,293
|
table.py
|
Kozea_pygal/pygal/table.py
|
# -*- coding: utf-8 -*-
# This file is part of pygal
#
# A python svg graph plotting library
# Copyright © 2012-2016 Kozea
#
# This library is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This library 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 Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with pygal. If not, see <http://www.gnu.org/licenses/>.
"""
HTML Table maker.
This class is used to render an html table from a chart data.
"""
import uuid
from lxml.html import builder, tostring
from pygal.util import template
class HTML(object):
"""Lower case adapter of lxml builder"""
def __getattribute__(self, attr):
"""Get the uppercase builder attribute"""
return getattr(builder, attr.upper())
class Table(object):
"""Table generator class"""
_dual = None
def __init__(self, chart):
"""Init the table"""
self.chart = chart
def render(self, total=False, transpose=False, style=False):
"""Render the HTMTL table of the chart.
`total` can be specified to include data sums
`transpose` make labels becomes columns
`style` include scoped style for the table
"""
self.chart.setup()
ln = self.chart._len
html = HTML()
attrs = {}
if style:
attrs['id'] = 'table-%s' % uuid.uuid4()
table = []
_ = lambda x: x if x is not None else ''
if self.chart.x_labels:
labels = [None] + list(self.chart.x_labels)
if len(labels) < ln:
labels += [None] * (ln + 1 - len(labels))
if len(labels) > ln + 1:
labels = labels[:ln + 1]
table.append(labels)
if total:
if len(table):
table[0].append('Total')
else:
table.append([None] * (ln + 1) + ['Total'])
acc = [0] * (ln + 1)
for i, serie in enumerate(self.chart.all_series):
row = [serie.title]
if total:
sum_ = 0
for j, value in enumerate(serie.values):
if total:
v = value or 0
acc[j] += v
sum_ += v
row.append(self.chart._format(serie, j))
if total:
acc[-1] += sum_
row.append(self.chart._serie_format(serie, sum_))
table.append(row)
width = ln + 1
if total:
width += 1
table.append(['Total'])
for val in acc:
table[-1].append(self.chart._serie_format(serie, val))
# Align values
len_ = max([len(r) for r in table] or [0])
for i, row in enumerate(table[:]):
len_ = len(row)
if len_ < width:
table[i] = row + [None] * (width - len_)
if not transpose:
table = list(zip(*table))
thead = []
tbody = []
tfoot = []
if not transpose or self.chart.x_labels:
# There's always series title but not always x_labels
thead = [table[0]]
tbody = table[1:]
else:
tbody = table
if total:
tfoot = [tbody[-1]]
tbody = tbody[:-1]
parts = []
if thead:
parts.append(
html.thead(
*[html.tr(*[html.th(_(col)) for col in r]) for r in thead]
)
)
if tbody:
parts.append(
html.tbody(
*[html.tr(*[html.td(_(col)) for col in r]) for r in tbody]
)
)
if tfoot:
parts.append(
html.tfoot(
*[html.tr(*[html.th(_(col)) for col in r]) for r in tfoot]
)
)
table = tostring(html.table(*parts, **attrs))
if style:
if style is True:
css = '''
#{{ id }} {
border-collapse: collapse;
border-spacing: 0;
empty-cells: show;
border: 1px solid #cbcbcb;
}
#{{ id }} td, #{{ id }} th {
border-left: 1px solid #cbcbcb;
border-width: 0 0 0 1px;
margin: 0;
padding: 0.5em 1em;
}
#{{ id }} td:first-child, #{{ id }} th:first-child {
border-left-width: 0;
}
#{{ id }} thead, #{{ id }} tfoot {
color: #000;
text-align: left;
vertical-align: bottom;
}
#{{ id }} thead {
background: #e0e0e0;
}
#{{ id }} tfoot {
background: #ededed;
}
#{{ id }} tr:nth-child(2n-1) td {
background-color: #f2f2f2;
}
'''
else:
css = style
table = tostring(
html.style(template(css, **attrs), scoped='scoped')
) + table
table = table.decode('utf-8')
self.chart.teardown()
return table
| 5,732
|
Python
|
.py
| 164
| 23.140244
| 79
| 0.482036
|
Kozea/pygal
| 2,634
| 411
| 197
|
LGPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,294
|
view.py
|
Kozea_pygal/pygal/view.py
|
# -*- coding: utf-8 -*-
# This file is part of pygal
#
# A python svg graph plotting library
# Copyright © 2012-2016 Kozea
#
# This library is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This library 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 Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with pygal. If not, see <http://www.gnu.org/licenses/>.
"""Projection and bounding helpers"""
from __future__ import division
from math import cos, log10, pi, sin
class Margin(object):
"""Class reprensenting a margin (top, right, left, bottom)"""
def __init__(self, top, right, bottom, left):
"""Create the margin object from the top, right, left, bottom margin"""
self.top = top
self.right = right
self.bottom = bottom
self.left = left
@property
def x(self):
"""Helper for total x margin"""
return self.left + self.right
@property
def y(self):
"""Helper for total y margin"""
return self.top + self.bottom
class Box(object):
"""Chart boundings"""
margin = .02
def __init__(self, xmin=0, ymin=0, xmax=1, ymax=1):
"""
Create the chart bounds with min max horizontal
and vertical values
"""
self._xmin = xmin
self._ymin = ymin
self._xmax = xmax
self._ymax = ymax
def set_polar_box(self, rmin=0, rmax=1, tmin=0, tmax=2 * pi):
"""Helper for polar charts"""
self._rmin = rmin
self._rmax = rmax
self._tmin = tmin
self._tmax = tmax
self.xmin = self.ymin = rmin - rmax
self.xmax = self.ymax = rmax - rmin
@property
def xmin(self):
"""X minimum getter"""
return self._xmin
@xmin.setter
def xmin(self, value):
"""X minimum setter"""
if value is not None:
self._xmin = value
@property
def ymin(self):
"""Y minimum getter"""
return self._ymin
@ymin.setter
def ymin(self, value):
"""Y minimum setter"""
if value is not None:
self._ymin = value
@property
def xmax(self):
"""X maximum getter"""
return self._xmax
@xmax.setter
def xmax(self, value):
"""X maximum setter"""
if value is not None:
self._xmax = value
@property
def ymax(self):
"""Y maximum getter"""
return self._ymax
@ymax.setter
def ymax(self, value):
"""Y maximum setter"""
if value or self.ymin:
self._ymax = value
@property
def width(self):
"""Helper for box width"""
return self.xmax - self.xmin
@property
def height(self):
"""Helper for box height"""
return self.ymax - self.ymin
def swap(self):
"""Return the box (for horizontal graphs)"""
self.xmin, self.ymin = self.ymin, self.xmin
self.xmax, self.ymax = self.ymax, self.xmax
def fix(self, with_margin=True):
"""Correct box when no values and take margin in account"""
if not self.width:
self.xmax = self.xmin + 1
if not self.height:
self.ymin /= 2
self.ymax += self.ymin
xmargin = self.margin * self.width
self.xmin -= xmargin
self.xmax += xmargin
if with_margin:
ymargin = self.margin * self.height
self.ymin -= ymargin
self.ymax += ymargin
class View(object):
"""Projection base class"""
def __init__(self, width, height, box):
"""Create the view with a width an height and a box bounds"""
self.width = width
self.height = height
self.box = box
self.box.fix()
def x(self, x):
"""Project x"""
if x is None:
return None
return self.width * (x - self.box.xmin) / self.box.width
def y(self, y):
"""Project y"""
if y is None:
return None
return (
self.height - self.height * (y - self.box.ymin) / self.box.height
)
def __call__(self, xy):
"""Project x and y"""
x, y = xy
return (self.x(x), self.y(y))
class ReverseView(View):
"""Same as view but reversed vertically"""
def y(self, y):
"""Project reversed y"""
if y is None:
return None
return (self.height * (y - self.box.ymin) / self.box.height)
class HorizontalView(View):
"""Same as view but transposed"""
def __init__(self, width, height, box):
"""Create the view with a width an height and a box bounds"""
self._force_vertical = None
self.width = width
self.height = height
self.box = box
self.box.fix()
self.box.swap()
def x(self, x):
"""Project x as y"""
if x is None:
return None
if self._force_vertical:
return super(HorizontalView, self).x(x)
return super(HorizontalView, self).y(x)
def y(self, y):
"""Project y as x"""
if y is None:
return None
if self._force_vertical:
return super(HorizontalView, self).y(y)
return super(HorizontalView, self).x(y)
class PolarView(View):
"""Polar projection for pie like graphs"""
def __call__(self, rhotheta):
"""Project rho and theta"""
if None in rhotheta:
return None, None
rho, theta = rhotheta
return super(PolarView,
self).__call__((rho * cos(theta), rho * sin(theta)))
class PolarLogView(View):
"""Logarithmic polar projection"""
def __init__(self, width, height, box):
"""Create the view with a width an height and a box bounds"""
super(PolarLogView, self).__init__(width, height, box)
if not hasattr(box, '_rmin') or not hasattr(box, '_rmax'):
raise Exception(
'Box must be set with set_polar_box for polar charts'
)
self.log10_rmax = log10(self.box._rmax)
self.log10_rmin = log10(self.box._rmin)
if self.log10_rmin == self.log10_rmax:
self.log10_rmax = self.log10_rmin + 1
def __call__(self, rhotheta):
"""Project rho and theta"""
if None in rhotheta:
return None, None
rho, theta = rhotheta
# Center case
if rho == 0:
return super(PolarLogView, self).__call__((0, 0))
rho = (self.box._rmax - self.box._rmin) * (
log10(rho) - self.log10_rmin
) / (self.log10_rmax - self.log10_rmin)
return super(PolarLogView,
self).__call__((rho * cos(theta), rho * sin(theta)))
class PolarThetaView(View):
"""Logarithmic polar projection"""
def __init__(self, width, height, box, aperture=pi / 3):
"""Create the view with a width an height and a box bounds"""
super(PolarThetaView, self).__init__(width, height, box)
self.aperture = aperture
if not hasattr(box, '_tmin') or not hasattr(box, '_tmax'):
raise Exception(
'Box must be set with set_polar_box for polar charts'
)
def __call__(self, rhotheta):
"""Project rho and theta"""
if None in rhotheta:
return None, None
rho, theta = rhotheta
start = 3 * pi / 2 + self.aperture / 2
theta = start + (2 * pi - self.aperture) * (theta - self.box._tmin) / (
self.box._tmax - self.box._tmin
)
return super(PolarThetaView,
self).__call__((rho * cos(theta), rho * sin(theta)))
class PolarThetaLogView(View):
"""Logarithmic polar projection"""
def __init__(self, width, height, box, aperture=pi / 3):
"""Create the view with a width an height and a box bounds"""
super(PolarThetaLogView, self).__init__(width, height, box)
self.aperture = aperture
if not hasattr(box, '_tmin') or not hasattr(box, '_tmax'):
raise Exception(
'Box must be set with set_polar_box for polar charts'
)
self.log10_tmax = log10(self.box._tmax) if self.box._tmax > 0 else 0
self.log10_tmin = log10(self.box._tmin) if self.box._tmin > 0 else 0
if self.log10_tmin == self.log10_tmax:
self.log10_tmax = self.log10_tmin + 1
def __call__(self, rhotheta):
"""Project rho and theta"""
if None in rhotheta:
return None, None
rho, theta = rhotheta
# Center case
if theta == 0:
return super(PolarThetaLogView, self).__call__((0, 0))
theta = self.box._tmin + (self.box._tmax - self.box._tmin) * (
log10(theta) - self.log10_tmin
) / (self.log10_tmax - self.log10_tmin)
start = 3 * pi / 2 + self.aperture / 2
theta = start + (2 * pi - self.aperture) * (theta - self.box._tmin) / (
self.box._tmax - self.box._tmin
)
return super(PolarThetaLogView,
self).__call__((rho * cos(theta), rho * sin(theta)))
class LogView(View):
"""Y Logarithmic projection"""
# Do not want to call the parent here
def __init__(self, width, height, box):
"""Create the view with a width an height and a box bounds"""
self.width = width
self.height = height
self.box = box
self.log10_ymax = log10(self.box.ymax) if self.box.ymax > 0 else 0
self.log10_ymin = log10(self.box.ymin) if self.box.ymin > 0 else 0
if self.log10_ymin == self.log10_ymax:
self.log10_ymax = self.log10_ymin + 1
self.box.fix(False)
def y(self, y):
"""Project y"""
if y is None or y <= 0 or self.log10_ymax - self.log10_ymin == 0:
return 0
return (
self.height - self.height * (log10(y) - self.log10_ymin) /
(self.log10_ymax - self.log10_ymin)
)
class XLogView(View):
"""X logarithmic projection"""
# Do not want to call the parent here
def __init__(self, width, height, box):
"""Create the view with a width an height and a box bounds"""
self.width = width
self.height = height
self.box = box
self.log10_xmax = log10(self.box.xmax) if self.box.xmax > 0 else 0
self.log10_xmin = log10(self.box.xmin) if self.box.xmin > 0 else 0
self.box.fix(False)
def x(self, x):
"""Project x"""
if x is None or x <= 0 or self.log10_xmax - self.log10_xmin == 0:
return None
return (
self.width * (log10(x) - self.log10_xmin) /
(self.log10_xmax - self.log10_xmin)
)
class XYLogView(XLogView, LogView):
"""X and Y logarithmic projection"""
def __init__(self, width, height, box):
"""Create the view with a width an height and a box bounds"""
self.width = width
self.height = height
self.box = box
self.log10_ymax = log10(self.box.ymax) if self.box.ymax > 0 else 0
self.log10_ymin = log10(self.box.ymin) if self.box.ymin > 0 else 0
self.log10_xmax = log10(self.box.xmax) if self.box.xmax > 0 else 0
self.log10_xmin = log10(self.box.xmin) if self.box.xmin > 0 else 0
self.box.fix(False)
class HorizontalLogView(XLogView):
"""Transposed Logarithmic projection"""
# Do not want to call the parent here
def __init__(self, width, height, box):
"""Create the view with a width an height and a box bounds"""
self._force_vertical = None
self.width = width
self.height = height
self.box = box
self.log10_xmax = log10(self.box.ymax) if self.box.ymax > 0 else 0
self.log10_xmin = log10(self.box.ymin) if self.box.ymin > 0 else 0
if self.log10_xmin == self.log10_xmax:
self.log10_xmax = self.log10_xmin + 1
self.box.fix(False)
self.box.swap()
def x(self, x):
"""Project x as y"""
if x is None:
return None
if self._force_vertical:
return super(HorizontalLogView, self).x(x)
return super(XLogView, self).y(x)
def y(self, y):
"""Project y as x"""
if y is None:
return None
if self._force_vertical:
return super(XLogView, self).y(y)
return super(HorizontalLogView, self).x(y)
| 12,833
|
Python
|
.py
| 342
| 29.128655
| 79
| 0.579965
|
Kozea/pygal
| 2,634
| 411
| 197
|
LGPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,295
|
adapters.py
|
Kozea_pygal/pygal/adapters.py
|
# -*- coding: utf-8 -*-
# This file is part of pygal
#
# A python svg graph plotting library
# Copyright © 2012-2016 Kozea
#
# This library is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This library 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 Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with pygal. If not, see <http://www.gnu.org/licenses/>.
"""Value adapters to use when a chart doesn't accept all value types"""
from decimal import Decimal
def positive(x):
"""Return zero if value is negative"""
if x is None:
return
if isinstance(x, str):
return x
if x < 0:
return 0
return x
def not_zero(x):
"""Return None if value is zero"""
if x == 0:
return
return x
def none_to_zero(x):
"""Return 0 if value is None"""
if x is None:
return 0
return x
def decimal_to_float(x):
"""Cast Decimal values to float"""
if isinstance(x, Decimal):
return float(x)
return x
| 1,398
|
Python
|
.py
| 44
| 28.227273
| 79
| 0.700594
|
Kozea/pygal
| 2,634
| 411
| 197
|
LGPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,296
|
stats.py
|
Kozea_pygal/pygal/stats.py
|
from math import log, pi, sqrt
def erfinv(x, a=.147):
"""Approximation of the inverse error function
https://en.wikipedia.org/wiki/Error_function
#Approximation_with_elementary_functions
"""
lnx = log(1 - x * x)
part1 = (2 / (a * pi) + lnx / 2)
part2 = lnx / a
sgn = 1 if x > 0 else -1
return sgn * sqrt(sqrt(part1 * part1 - part2) - part1)
def norm_ppf(x):
if not 0 < x < 1:
raise ValueError("Can't compute the percentage point for value %d" % x)
return sqrt(2) * erfinv(2 * x - 1)
def ppf(x, n):
try:
from scipy import stats
except ImportError:
stats = None
if stats:
if n < 30:
return stats.t.ppf(x, n)
return stats.norm.ppf(x)
else:
if n < 30:
# TODO: implement power series:
# http://eprints.maths.ox.ac.uk/184/1/tdist.pdf
raise ImportError(
'You must have scipy installed to use t-student '
'when sample_size is below 30'
)
return norm_ppf(x)
# According to http://sphweb.bumc.bu.edu/otlt/MPH-Modules/BS/
# BS704_Confidence_Intervals/BS704_Confidence_Intervals_print.html
def confidence_interval_continuous(
point_estimate, stddev, sample_size, confidence=.95, **kwargs
):
"""Continuous confidence interval from sample size and standard error"""
alpha = ppf((confidence + 1) / 2, sample_size - 1)
margin = stddev / sqrt(sample_size)
return (point_estimate - alpha * margin, point_estimate + alpha * margin)
def confidence_interval_dichotomous(
point_estimate,
sample_size,
confidence=.95,
bias=False,
percentage=True,
**kwargs
):
"""Dichotomous confidence interval from sample size and maybe a bias"""
alpha = ppf((confidence + 1) / 2, sample_size - 1)
p = point_estimate
if percentage:
p /= 100
margin = sqrt(p * (1 - p) / sample_size)
if bias:
margin += .5 / sample_size
if percentage:
margin *= 100
return (point_estimate - alpha * margin, point_estimate + alpha * margin)
def confidence_interval_manual(point_estimate, low, high):
return (low, high)
| 2,218
|
Python
|
.py
| 63
| 28.52381
| 79
| 0.621432
|
Kozea/pygal
| 2,634
| 411
| 197
|
LGPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,297
|
conftest.py
|
Kozea_pygal/pygal/test/conftest.py
|
# -*- coding: utf-8 -*-
# This file is part of pygal
#
# A python svg graph plotting library
# Copyright © 2012-2016 Kozea
#
# This library is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This library 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 Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with pygal. If not, see <http://www.gnu.org/licenses/>.
"""pytest fixtures"""
import sys
import pytest
import pygal
from pygal.etree import etree
from . import get_data
@pytest.fixture
def etreefx(request):
"""Fixture allowing to test with builtin etree and lxml"""
if request.param == 'etree':
etree.to_etree()
if request.param == 'lxml':
etree.to_lxml()
def pytest_generate_tests(metafunc):
"""Generate the tests for etree and lxml"""
if etree._lxml_etree:
metafunc.fixturenames.append('etreefx')
metafunc.parametrize('etreefx', ['lxml', 'etree'], indirect=True)
if not hasattr(sys, 'pypy_version_info'):
etree.to_lxml()
if hasattr(sys, 'pypy_version_info'):
etree.to_etree()
if "Chart" in metafunc.fixturenames:
metafunc.parametrize("Chart", pygal.CHARTS)
if "datas" in metafunc.fixturenames:
metafunc.parametrize(
"datas", [[("Serie %d" % i, get_data(i)) for i in range(s)]
for s in (5, 1, 0)]
)
| 1,770
|
Python
|
.py
| 47
| 33.404255
| 79
| 0.69743
|
Kozea/pygal
| 2,634
| 411
| 197
|
LGPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,298
|
test_bar.py
|
Kozea_pygal/pygal/test/test_bar.py
|
# -*- coding: utf-8 -*-
# This file is part of pygal
#
# A python svg graph plotting library
# Copyright © 2012-2016 Kozea
#
# This library is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This library 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 Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with pygal. If not, see <http://www.gnu.org/licenses/>.
"""Bar chart related tests"""
from pygal import Bar
def test_simple_bar():
"""Simple bar test"""
bar = Bar()
rng = [-3, -32, -39]
bar.add('test1', rng)
bar.add('test2', map(abs, rng))
bar.x_labels = map(str, rng)
bar.title = "Bar test"
q = bar.render_pyquery()
assert len(q(".axis.x")) == 1
assert len(q(".axis.y")) == 1
assert len(q(".legend")) == 2
assert len(q(".plot .series rect")) == 2 * 3
| 1,220
|
Python
|
.py
| 33
| 34.424242
| 79
| 0.695101
|
Kozea/pygal
| 2,634
| 411
| 197
|
LGPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|
11,299
|
test_date.py
|
Kozea_pygal/pygal/test/test_date.py
|
# -*- coding: utf-8 -*-
# This file is part of pygal
#
# A python svg graph plotting library
# Copyright © 2012-2016 Kozea
#
# This library is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This library 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 Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with pygal. If not, see <http://www.gnu.org/licenses/>.
"""Date related charts tests"""
from datetime import date, datetime, time, timedelta, timezone
from pygal import DateLine, DateTimeLine, TimeDeltaLine, TimeLine
from pygal._compat import timestamp
from pygal.test.utils import texts
def test_date():
"""Test a simple dateline"""
date_chart = DateLine(truncate_label=1000)
date_chart.add(
'dates', [(date(2013, 1, 2), 300), (date(2013, 1, 12), 412),
(date(2013, 2, 2), 823), (date(2013, 2, 22), 672)]
)
q = date_chart.render_pyquery()
dates = list(map(lambda t: t.split(' ')[0], q(".axis.x text").map(texts)))
assert dates == ['2013-01-12', '2013-01-24', '2013-02-04', '2013-02-16']
def test_time():
"""Test a simple timeline"""
time_chart = TimeLine(truncate_label=1000)
time_chart.add(
'times', [(time(1, 12, 29), 2), (time(21, 2, 29), 10),
(time(12, 30, 59), 7)]
)
q = time_chart.render_pyquery()
dates = list(map(lambda t: t.split(' ')[0], q(".axis.x text").map(texts)))
assert dates == [
'02:46:40', '05:33:20', '08:20:00', '11:06:40', '13:53:20', '16:40:00',
'19:26:40'
]
def test_datetime():
"""Test a simple datetimeline"""
datetime_chart = DateTimeLine(truncate_label=1000)
datetime_chart.add(
'datetimes',
[(datetime(2013, 1, 2, 1, 12, 29), 300),
(datetime(2013, 1, 12, 21, 2, 29), 412),
(datetime(2013, 2, 2, 12, 30, 59), 823), (datetime(2013, 2, 22), 672)]
)
q = datetime_chart.render_pyquery()
dates = list(map(lambda t: t.split(' ')[0], q(".axis.x text").map(texts)))
assert dates == [
'2013-01-12T14:13:20', '2013-01-24T04:00:00', '2013-02-04T17:46:40',
'2013-02-16T07:33:20'
]
def test_timedelta():
"""Test a simple timedeltaline"""
timedelta_chart = TimeDeltaLine(truncate_label=1000)
timedelta_chart.add(
'timedeltas', [
(timedelta(seconds=1), 10),
(timedelta(weeks=1), 50),
(timedelta(hours=3, seconds=30), 3),
(timedelta(microseconds=12112), .3),
]
)
q = timedelta_chart.render_pyquery()
assert list(t for t in q(".axis.x text").map(texts) if t != '0:00:00') == [
'1 day, 3:46:40', '2 days, 7:33:20', '3 days, 11:20:00',
'4 days, 15:06:40', '5 days, 18:53:20', '6 days, 22:40:00'
]
def test_date_xrange():
"""Test dateline with xrange"""
datey = DateLine(truncate_label=1000)
datey.add(
'dates', [(date(2013, 1, 2), 300), (date(2013, 1, 12), 412),
(date(2013, 2, 2), 823), (date(2013, 2, 22), 672)]
)
datey.xrange = (date(2013, 1, 1), date(2013, 3, 1))
q = datey.render_pyquery()
dates = list(map(lambda t: t.split(' ')[0], q(".axis.x text").map(texts)))
assert dates == [
'2013-01-01', '2013-01-12', '2013-01-24', '2013-02-04', '2013-02-16',
'2013-02-27'
]
def test_date_labels():
"""Test dateline with xrange"""
datey = DateLine(truncate_label=1000)
datey.add(
'dates', [(date(2013, 1, 2), 300), (date(2013, 1, 12), 412),
(date(2013, 2, 2), 823), (date(2013, 2, 22), 672)]
)
datey.x_labels = [date(2013, 1, 1), date(2013, 2, 1), date(2013, 3, 1)]
q = datey.render_pyquery()
dates = list(map(lambda t: t.split(' ')[0], q(".axis.x text").map(texts)))
assert dates == ['2013-01-01', '2013-02-01', '2013-03-01']
def test_utc_timestamping():
t = datetime(2017, 7, 14, 2, 40).replace(tzinfo=timezone.utc)
assert timestamp(t) == 1500000000
for d in (
datetime.now(),
datetime.utcnow(),
datetime(1999, 12, 31, 23, 59, 59),
datetime(2000, 1, 1, 0, 0, 0),
):
assert datetime.utcfromtimestamp(timestamp(d)) - d < timedelta(microseconds=10)
| 4,607
|
Python
|
.py
| 112
| 35.357143
| 87
| 0.604922
|
Kozea/pygal
| 2,634
| 411
| 197
|
LGPL-3.0
|
9/5/2024, 5:11:10 PM (Europe/Amsterdam)
|