delete.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. # This file is part of Radicale - CalDAV and CardDAV server
  2. # Copyright © 2014 Jean-Marc Martins
  3. # Copyright © 2012-2017 Guillaume Ayoub
  4. # Copyright © 2017-2018 Unrud <unrud@outlook.com>
  5. # Copyright © 2024-2024 Peter Bieringer <pb@bieringer.de>
  6. #
  7. # This library is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This library is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  19. import os
  20. from tempfile import TemporaryDirectory
  21. from typing import Optional
  22. from radicale import pathutils, storage
  23. from radicale.storage.multifilesystem.base import CollectionBase
  24. from radicale.storage.multifilesystem.history import CollectionPartHistory
  25. class CollectionPartDelete(CollectionPartHistory, CollectionBase):
  26. def delete(self, href: Optional[str] = None) -> None:
  27. if href is None:
  28. # Delete the collection
  29. parent_dir = os.path.dirname(self._filesystem_path)
  30. try:
  31. os.rmdir(self._filesystem_path)
  32. except OSError:
  33. with TemporaryDirectory(prefix=".Radicale.tmp-", dir=parent_dir
  34. ) as tmp:
  35. os.rename(self._filesystem_path, os.path.join(
  36. tmp, os.path.basename(self._filesystem_path)))
  37. self._storage._sync_directory(parent_dir)
  38. else:
  39. self._storage._sync_directory(parent_dir)
  40. else:
  41. # Delete an item
  42. if not pathutils.is_safe_filesystem_path_component(href):
  43. raise pathutils.UnsafePathError(href)
  44. path = pathutils.path_to_filesystem(self._filesystem_path, href)
  45. if not os.path.isfile(path):
  46. raise storage.ComponentNotFoundError(href)
  47. os.remove(path)
  48. self._storage._sync_directory(os.path.dirname(path))
  49. # Track the change
  50. self._update_history_etag(href, None)
  51. self._clean_history()
  52. # Remove item from cache
  53. cache_folder = self._storage._get_collection_cache_subfolder(os.path.dirname(path), ".Radicale.cache", "item")
  54. cache_file = os.path.join(cache_folder, os.path.basename(path))
  55. if os.path.isfile(cache_file):
  56. os.remove(cache_file)
  57. self._storage._sync_directory(cache_folder)