create_collection.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 radicale import pathutils
  21. class StorageCreateCollectionMixin:
  22. def create_collection(self, href, items=None, props=None):
  23. folder = self._get_collection_root_folder()
  24. # Path should already be sanitized
  25. sane_path = pathutils.strip_path(href)
  26. filesystem_path = pathutils.path_to_filesystem(folder, sane_path)
  27. if not props:
  28. self._makedirs_synced(filesystem_path)
  29. return self._collection_class(
  30. self, pathutils.unstrip_path(sane_path, True))
  31. parent_dir = os.path.dirname(filesystem_path)
  32. self._makedirs_synced(parent_dir)
  33. # Create a temporary directory with an unsafe name
  34. with TemporaryDirectory(
  35. prefix=".Radicale.tmp-", dir=parent_dir) as tmp_dir:
  36. # The temporary directory itself can't be renamed
  37. tmp_filesystem_path = os.path.join(tmp_dir, "collection")
  38. os.makedirs(tmp_filesystem_path)
  39. col = self._collection_class(
  40. self, pathutils.unstrip_path(sane_path, True),
  41. filesystem_path=tmp_filesystem_path)
  42. col.set_meta(props)
  43. if items is not None:
  44. if props.get("tag") == "VCALENDAR":
  45. col._upload_all_nonatomic(items, suffix=".ics")
  46. elif props.get("tag") == "VADDRESSBOOK":
  47. col._upload_all_nonatomic(items, suffix=".vcf")
  48. if os.path.lexists(filesystem_path):
  49. pathutils.rename_exchange(tmp_filesystem_path, filesystem_path)
  50. else:
  51. os.rename(tmp_filesystem_path, filesystem_path)
  52. self._sync_directory(parent_dir)
  53. return self._collection_class(
  54. self, pathutils.unstrip_path(sane_path, True))