delete.py 2.3 KB

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