|
| 1 | +import os |
| 2 | +from urllib.parse import urlparse |
| 3 | +import tempfile |
| 4 | + |
| 5 | +import requests |
| 6 | +from mastodon import Mastodon |
| 7 | + |
| 8 | +from abstractions import Post, PostResult, SocialPoster |
| 9 | + |
| 10 | +MASTODON_CHARACTER_LIMIT = 500 |
| 11 | +TRUNCATION_SUFFIX = "..." |
| 12 | + |
| 13 | + |
| 14 | +class PosterMastodon(SocialPoster): |
| 15 | + def __init__(self): |
| 16 | + raw_token = os.environ.get("MASTODON_TOKEN") |
| 17 | + self.token = raw_token.strip() if raw_token else None |
| 18 | + self.api_base_url = "https://mastodon.social" |
| 19 | + self._session = None |
| 20 | + self._is_available = bool(self.token) |
| 21 | + self._auth_error = None |
| 22 | + |
| 23 | + @property |
| 24 | + def platform_name(self) -> str: |
| 25 | + return "Mastodon" |
| 26 | + |
| 27 | + def authenticate(self) -> bool: |
| 28 | + try: |
| 29 | + self._session = Mastodon( |
| 30 | + access_token=self.token, |
| 31 | + api_base_url=self.api_base_url, |
| 32 | + ) |
| 33 | + self._session.account_verify_credentials() |
| 34 | + self._auth_error = None |
| 35 | + return True |
| 36 | + except Exception as exc: |
| 37 | + self._session = None |
| 38 | + self._auth_error = f"{type(exc).__name__}: {exc}" |
| 39 | + return False |
| 40 | + |
| 41 | + def publish(self, post: Post) -> PostResult: |
| 42 | + if not self._is_available: |
| 43 | + return PostResult( |
| 44 | + success=False, |
| 45 | + error_message="Mastodon credentials not available.", |
| 46 | + ) |
| 47 | + |
| 48 | + if not post.image_url: |
| 49 | + return PostResult( |
| 50 | + success=False, |
| 51 | + error_message="Mastodon posts require an image URL.", |
| 52 | + ) |
| 53 | + |
| 54 | + if not self._session and not self.authenticate(): |
| 55 | + return PostResult( |
| 56 | + success=False, |
| 57 | + error_message=( |
| 58 | + "Mastodon authentication failed." |
| 59 | + if not self._auth_error |
| 60 | + else f"Mastodon authentication failed: {self._auth_error}" |
| 61 | + ), |
| 62 | + ) |
| 63 | + |
| 64 | + image_path = None |
| 65 | + try: |
| 66 | + image_path = self._download_image(post.image_url) |
| 67 | + media = self._session.media_post( |
| 68 | + image_path, |
| 69 | + description=post.alt_text or "Photo of an adoptable pet", |
| 70 | + ) |
| 71 | + status = self._session.status_post( |
| 72 | + self._format_caption(post), |
| 73 | + media_ids=[media["id"]], |
| 74 | + ) |
| 75 | + return PostResult( |
| 76 | + success=True, |
| 77 | + post_id=str(status["id"]), |
| 78 | + post_url=status.get("url"), |
| 79 | + ) |
| 80 | + except Exception as exc: |
| 81 | + return PostResult(success=False, error_message=str(exc)) |
| 82 | + finally: |
| 83 | + self._session = None |
| 84 | + if image_path and os.path.exists(image_path): |
| 85 | + os.unlink(image_path) |
| 86 | + |
| 87 | + def _format_caption(self, post: Post) -> str: |
| 88 | + tags = " ".join(f"#{tag}" for tag in post.tags if tag) |
| 89 | + tag_suffix = f"\n\n{tags}" if tags else "" |
| 90 | + available_text_length = MASTODON_CHARACTER_LIMIT - len(tag_suffix) |
| 91 | + |
| 92 | + if available_text_length <= len(TRUNCATION_SUFFIX): |
| 93 | + return (tag_suffix[-MASTODON_CHARACTER_LIMIT:]).strip() |
| 94 | + |
| 95 | + caption_text = post.text.strip() |
| 96 | + if len(caption_text) > available_text_length: |
| 97 | + caption_text = caption_text[: available_text_length - len(TRUNCATION_SUFFIX)].rstrip() |
| 98 | + caption_text = f"{caption_text}{TRUNCATION_SUFFIX}" |
| 99 | + |
| 100 | + return f"{caption_text}{tag_suffix}" |
| 101 | + |
| 102 | + def _download_image(self, image_url: str) -> str: |
| 103 | + parsed_url = urlparse(image_url) |
| 104 | + ext = os.path.splitext(parsed_url.path)[1] or ".jpg" |
| 105 | + with tempfile.NamedTemporaryFile(delete=False, suffix=ext) as tmp: |
| 106 | + response = requests.get(image_url, stream=True, timeout=20) |
| 107 | + response.raise_for_status() |
| 108 | + for chunk in response.iter_content(chunk_size=1024 * 128): |
| 109 | + if chunk: |
| 110 | + tmp.write(chunk) |
| 111 | + return tmp.name |
0 commit comments