bookwyrm/bookwyrm/utils/tar.py

51 lines
1.6 KiB
Python
Raw Normal View History

2023-10-22 05:52:29 +00:00
"""manage tar files for user exports"""
import io
2024-03-28 12:09:21 +00:00
import os
2023-10-22 05:52:29 +00:00
import tarfile
2023-10-23 09:43:49 +00:00
from typing import Any, Optional
from uuid import uuid4
from django.core.files import File
class BookwyrmTarFile(tarfile.TarFile):
2023-10-22 05:52:29 +00:00
"""Create tar files for user exports"""
2023-10-22 06:49:26 +00:00
def write_bytes(self, data: bytes) -> None:
2023-10-22 05:52:29 +00:00
"""Add a file containing bytes to the archive"""
buffer = io.BytesIO(data)
info = tarfile.TarInfo("archive.json")
info.size = len(data)
self.addfile(info, fileobj=buffer)
2023-10-23 09:43:49 +00:00
def add_image(
2024-03-28 12:21:30 +00:00
self, image: Any, filename: Optional[str] = None, directory: str = ""
2023-10-23 09:43:49 +00:00
) -> None:
"""
Add an image to the tar archive
:param str filename: overrides the file name set by image
:param str directory: the directory in the archive to put the image
"""
2024-03-28 12:09:21 +00:00
if filename is None:
2024-03-28 12:21:30 +00:00
dst_filename = image.name
else:
2024-03-28 12:21:30 +00:00
dst_filename = filename + os.path.splitext(image.name)[1]
dst_path = os.path.join(directory, dst_filename)
2024-03-28 12:21:30 +00:00
info = tarfile.TarInfo(name=dst_path)
info.size = image.size
self.addfile(info, fileobj=image)
2023-10-22 06:49:26 +00:00
def read(self, filename: str) -> Any:
2023-10-22 05:52:29 +00:00
"""read data from the tar"""
2023-10-23 09:43:49 +00:00
if reader := self.extractfile(filename):
return reader.read()
2023-10-23 10:30:17 +00:00
return None
2023-10-22 06:49:26 +00:00
def write_image_to_file(self, filename: str, file_field: Any) -> None:
2023-10-22 05:52:29 +00:00
"""add an image to the tar"""
2024-03-28 12:09:21 +00:00
extension = os.path.splitext(filename)[1]
2023-10-23 09:43:49 +00:00
if buf := self.extractfile(filename):
2024-03-28 12:09:21 +00:00
filename = str(uuid4()) + extension
2023-10-23 09:43:49 +00:00
file_field.save(filename, File(buf))