2016-12-28 14:46:42 +01:00
|
|
|
from typing import Any, Dict, List
|
|
|
|
|
2021-04-16 00:57:30 +02:00
|
|
|
from django.utils.translation import gettext as _
|
2020-06-11 00:54:34 +02:00
|
|
|
|
2016-12-28 14:46:42 +01:00
|
|
|
from zerver.lib.request import JsonableError
|
|
|
|
from zerver.lib.upload import delete_message_image
|
|
|
|
from zerver.models import Attachment, UserProfile
|
|
|
|
|
2020-06-11 00:54:34 +02:00
|
|
|
|
2017-11-05 11:15:10 +01:00
|
|
|
def user_attachments(user_profile: UserProfile) -> List[Dict[str, Any]]:
|
2021-02-12 08:20:45 +01:00
|
|
|
attachments = Attachment.objects.filter(owner=user_profile).prefetch_related("messages")
|
2016-12-28 14:46:42 +01:00
|
|
|
return [a.to_dict() for a in attachments]
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
|
|
def access_attachment_by_id(
|
|
|
|
user_profile: UserProfile, attachment_id: int, needs_owner: bool = False
|
|
|
|
) -> Attachment:
|
2016-12-28 14:46:42 +01:00
|
|
|
query = Attachment.objects.filter(id=attachment_id)
|
|
|
|
if needs_owner:
|
|
|
|
query = query.filter(owner=user_profile)
|
|
|
|
|
|
|
|
attachment = query.first()
|
|
|
|
if attachment is None:
|
|
|
|
raise JsonableError(_("Invalid attachment"))
|
|
|
|
return attachment
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
2017-11-05 11:15:10 +01:00
|
|
|
def remove_attachment(user_profile: UserProfile, attachment: Attachment) -> None:
|
2017-09-19 23:13:52 +02:00
|
|
|
try:
|
|
|
|
delete_message_image(attachment.path_id)
|
|
|
|
except Exception:
|
2021-02-12 08:19:30 +01:00
|
|
|
raise JsonableError(
|
|
|
|
_("An error occurred while deleting the attachment. Please try again later.")
|
|
|
|
)
|
2016-12-28 14:46:42 +01:00
|
|
|
attachment.delete()
|