import base64 from dataclasses import dataclass from ows_text_campaigns.artist.types import PhoneNumberStr from ows_text_campaigns.assets.types import BinaryAsset @dataclass(kw_only=True) class ArtistVCard: version = "3.0" def __init__( self, name: str, phone: PhoneNumberStr, photo: BinaryAsset | None = None ) -> None: self.name = name self.phone = phone self.photo = photo def render(self) -> str: vcard = [ "BEGIN:VCARD", f"VERSION:{self.version}", f"FN:{self.name}", f"TEL;TYPE=CELL:{self.phone}", ] if self.photo is not None: encoded = base64.b64encode(self.photo.data).decode("utf-8") vcard.append( f"PHOTO;ENCODING=b;TYPE={self._photo_type(self.photo)}:{encoded}" ) vcard.append("END:VCARD") return "\n".join(vcard) def as_binary(self, filename: str = "vcard.vcf") -> BinaryAsset: data = self.render().encode() return BinaryAsset( data=data, content_type="text/vcard", extension="vcf", file_size=len(data), filename=filename, ) @staticmethod def _photo_type(photo: BinaryAsset) -> str: """Determine the photo type based on the asset's content type.""" if photo.content_type == "image/png": return "PNG" elif photo.content_type in ["image/jpg", "image/jpeg"]: return "JPEG" elif photo.content_type == "image/gif": return "GIF" else: return "BINARY"