create_collection.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 CollectionCreateCollectionMixin:
  22. @classmethod
  23. def create_collection(cls, href, items=None, props=None):
  24. folder = cls._get_collection_root_folder()
  25. # Path should already be sanitized
  26. sane_path = pathutils.strip_path(href)
  27. filesystem_path = pathutils.path_to_filesystem(folder, sane_path)
  28. if not props:
  29. cls._makedirs_synced(filesystem_path)
  30. return cls(pathutils.unstrip_path(sane_path, True))
  31. parent_dir = os.path.dirname(filesystem_path)
  32. cls._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. self = cls(pathutils.unstrip_path(sane_path, True),
  40. filesystem_path=tmp_filesystem_path)
  41. self.set_meta(props)
  42. if items is not None:
  43. if props.get("tag") == "VCALENDAR":
  44. self._upload_all_nonatomic(items, suffix=".ics")
  45. elif props.get("tag") == "VADDRESSBOOK":
  46. self._upload_all_nonatomic(items, suffix=".vcf")
  47. # This operation is not atomic on the filesystem level but it's
  48. # very unlikely that one rename operations succeeds while the
  49. # other fails or that only one gets written to disk.
  50. if os.path.exists(filesystem_path):
  51. os.rename(filesystem_path, os.path.join(tmp_dir, "delete"))
  52. os.rename(tmp_filesystem_path, filesystem_path)
  53. cls._sync_directory(parent_dir)
  54. return cls(pathutils.unstrip_path(sane_path, True))