Terminando integración

This commit is contained in:
Jesús Pavón Abián
2026-02-01 10:42:05 +01:00
parent ec8d6ecada
commit f7f12a1c7b
13 changed files with 975 additions and 1903 deletions

View File

@@ -1,297 +1,64 @@
# -*- coding: utf-8 -*-
from __future__ import annotations
"""
Compose functions for Bluesky content display in TWBlue.
These functions format API data into user-readable strings for display in
list controls. They follow the TWBlue compose function pattern:
compose_function(item, db, relative_times, show_screen_names, session)
Returns a list of strings for display columns.
"""
import logging
from typing import TYPE_CHECKING, Any
from datetime import datetime
import arrow
import languageHandler
if TYPE_CHECKING:
from sessions.blueski.session import Session as BlueskiSession
from atproto.xrpc_client import models # For type hinting ATProto models
logger = logging.getLogger(__name__)
# For SUPPORTED_LANG_CHOICES in composeDialog.py
SUPPORTED_LANG_CHOICES_COMPOSE = {
_("English"): "en", _("Spanish"): "es", _("French"): "fr", _("German"): "de",
_("Japanese"): "ja", _("Portuguese"): "pt", _("Russian"): "ru", _("Chinese"): "zh",
}
class BlueskiCompose:
MAX_CHARS = 300
MAX_MEDIA_ATTACHMENTS = 4
MAX_LANGUAGES = 3
MAX_IMAGE_SIZE_BYTES = 1_000_000
def __init__(self, session: BlueskiSession) -> None:
self.session = session
self.supported_media_types: list[str] = ["image/jpeg", "image/png"]
self.max_image_size_bytes: int = self.MAX_IMAGE_SIZE_BYTES
def get_panel_configuration(self) -> dict[str, Any]:
"""Returns configuration for the compose panel specific to Blueski."""
return {
"max_chars": self.MAX_CHARS,
"max_media_attachments": self.MAX_MEDIA_ATTACHMENTS,
"supports_content_warning": True,
"supports_scheduled_posts": False,
"supported_media_types": self.supported_media_types,
"max_media_size_bytes": self.max_image_size_bytes,
"supports_alternative_text": True,
"sensitive_reasons_options": self.session.get_sensitive_reason_options(),
"supports_language_selection": True,
"max_languages": self.MAX_LANGUAGES,
"supports_quoting": True,
"supports_polls": False,
}
async def get_quote_text(self, message_id: str, url: str) -> str | None:
return ""
async def get_reply_text(self, message_id: str, author_handle: str) -> str | None:
if not author_handle.startswith("@"):
return f"@{author_handle} "
return f"{author_handle} "
def get_text_formatting_rules(self) -> dict[str, Any]:
return {
"markdown_enabled": False,
"custom_emojis_enabled": False,
"max_length": self.MAX_CHARS,
"line_break_char": "\n",
"link_format": "Full URL (e.g., https://example.com)",
"mention_format": "@handle.bsky.social",
"tag_format": "#tag (becomes a facet link)",
}
def is_media_type_supported(self, mime_type: str) -> bool:
return mime_type.lower() in self.supported_media_types
def get_max_schedule_date(self) -> str | None:
return None
def get_poll_configuration(self) -> dict[str, Any] | None:
return None
def compose_post_for_display(self, post_data: dict[str, Any], session_settings: dict[str, Any] | None = None) -> str:
"""
Composes a string representation of a Bluesky post for display in UI timelines.
"""
if not post_data or not isinstance(post_data, dict):
return _("Invalid post data.")
author_info = post_data.get("author", {})
record = post_data.get("record", {})
embed_data = post_data.get("embed")
viewer_state = post_data.get("viewer", {})
display_name = author_info.get("displayName", "") or author_info.get("handle", _("Unknown User"))
handle = author_info.get("handle", _("unknown.handle"))
post_text = getattr(record, 'text', '') if not isinstance(record, dict) else record.get('text', '')
reason = post_data.get("reason")
if reason:
rtype = getattr(reason, "$type", "") if not isinstance(reason, dict) else reason.get("$type", "")
if not rtype and not isinstance(reason, dict):
rtype = getattr(reason, "py_type", "")
if rtype and "reasonRepost" in rtype:
by = getattr(reason, "by", None) if not isinstance(reason, dict) else reason.get("by")
by_handle = getattr(by, "handle", "") if by and not isinstance(by, dict) else (by.get("handle", "") if by else "")
reason_line = _("Reposted by @{handle}").format(handle=by_handle) if by_handle else _("Reposted")
post_text = f"{reason_line}\n{post_text}" if post_text else reason_line
created_at_str = getattr(record, 'createdAt', '') if not isinstance(record, dict) else record.get('createdAt', '')
timestamp_str = ""
if created_at_str:
try:
ts = arrow.get(created_at_str)
timestamp_str = ts.format(_("dddd, MMMM D, YYYY H:m"), locale=languageHandler.curLang[:2])
except Exception as e:
logger.debug(f"Could not parse timestamp {created_at_str}: {e}")
timestamp_str = created_at_str
header = f"{display_name} (@{handle}) - {timestamp_str}"
labels = post_data.get("labels", [])
spoiler_text = None
is_sensitive_post = False
if labels:
for label_obj in labels:
label_val = getattr(label_obj, 'val', '') if not isinstance(label_obj, dict) else label_obj.get('val', '')
if label_val == "!warn":
is_sensitive_post = True
elif label_val in ["porn", "sexual", "nudity", "gore", "graphic-media", "corpse", "self-harm", "hate", "spam", "impersonation"]:
is_sensitive_post = True
if not spoiler_text: spoiler_text = _("Sensitive Content: {label}").format(label=label_val)
elif label_val.startswith("warn:") and len(label_val) > 5:
spoiler_text = label_val.split("warn:", 1)[-1].strip()
is_sensitive_post = True
post_text_display = post_text
if spoiler_text:
post_text_display = f"CW: {spoiler_text}\n\n{post_text}"
elif is_sensitive_post and not spoiler_text:
post_text_display = f"CW: {_('Sensitive Content')}\n\n{post_text}"
embed_display = ""
if embed_data:
embed_type = getattr(embed_data, '$type', '')
if not embed_type and isinstance(embed_data, dict): embed_type = embed_data.get('$type', '')
if embed_type in ['app.bsky.embed.images#view', 'app.bsky.embed.images']:
images = getattr(embed_data, 'images', []) if hasattr(embed_data, 'images') else embed_data.get('images', [])
if images:
img_count = len(images)
alt_texts_present = any(getattr(img, 'alt', '') for img in images if hasattr(img, 'alt')) or \
any(img_dict.get('alt', '') for img_dict in images if isinstance(img_dict, dict))
embed_display += f"\n[{img_count} Image"
if img_count > 1: embed_display += "s"
if alt_texts_present: embed_display += _(" (Alt text available)")
embed_display += "]"
elif embed_type in ['app.bsky.embed.record#view', 'app.bsky.embed.record', 'app.bsky.embed.recordWithMedia#view', 'app.bsky.embed.recordWithMedia']:
record_embed_data = getattr(embed_data, 'record', None) if hasattr(embed_data, 'record') else embed_data.get('record', None)
if record_embed_data and isinstance(record_embed_data, dict):
record_embed_data = record_embed_data.get("record") or record_embed_data
record_embed_type = getattr(record_embed_data, '$type', '')
if not record_embed_type and isinstance(record_embed_data, dict): record_embed_type = record_embed_data.get('$type', '')
if record_embed_type == 'app.bsky.embed.record#viewNotFound':
embed_display += f"\n[{_('Quoted post not found or unavailable')}]"
elif record_embed_type == 'app.bsky.embed.record#viewBlocked':
embed_display += f"\n[{_('Content from the quoted account is blocked')}]"
elif record_embed_data and (isinstance(record_embed_data, dict) or hasattr(record_embed_data, 'author')):
quote_author_info = getattr(record_embed_data, 'author', record_embed_data.get('author'))
quote_value = getattr(record_embed_data, 'value', record_embed_data.get('value'))
if quote_author_info and quote_value:
quote_author_handle = getattr(quote_author_info, 'handle', 'unknown')
quote_text_content = getattr(quote_value, 'text', '') if not isinstance(quote_value, dict) else quote_value.get('text', '')
quote_text_snippet = (quote_text_content[:75] + "...") if quote_text_content else _("post content")
embed_display += f"\n[ {_('Quote by')} @{quote_author_handle}: \"{quote_text_snippet}\" ]"
else:
embed_display += f"\n[{_('Quoted Post')}]"
elif embed_type in ['app.bsky.embed.external#view', 'app.bsky.embed.external']:
external_data = getattr(embed_data, 'external', None) if hasattr(embed_data, 'external') else embed_data.get('external', None)
if external_data:
ext_uri = getattr(external_data, 'uri', _('External Link'))
ext_title = getattr(external_data, 'title', '') or ext_uri
embed_display += f"\n[{_('Link')}: {ext_title}]"
reply_context_str = ""
actual_record = post_data.get("record", {})
reply_ref = getattr(actual_record, 'reply', None) if not isinstance(actual_record, dict) else actual_record.get('reply')
if reply_ref:
reply_context_str = f"[{_('In reply to a post')}] "
counts_str_parts = []
reply_count = post_data.get("replyCount", 0)
repost_count = post_data.get("repostCount", 0)
like_count = post_data.get("likeCount", 0)
if reply_count > 0: counts_str_parts.append(f"{_('Replies')}: {reply_count}")
if repost_count > 0: counts_str_parts.append(f"{_('Reposts')}: {repost_count}")
if like_count > 0: counts_str_parts.append(f"{_('Likes')}: {like_count}")
viewer_liked_uri = viewer_state.get("like") if isinstance(viewer_state, dict) else getattr(viewer_state, 'like', None)
viewer_reposted_uri = viewer_state.get("repost") if isinstance(viewer_state, dict) else getattr(viewer_state, 'repost', None)
if viewer_liked_uri: counts_str_parts.append(f"({_('Liked by you')})")
if viewer_reposted_uri: counts_str_parts.append(f"({_('Reposted by you')})")
counts_line = ""
if counts_str_parts:
counts_line = "\n" + " | ".join(counts_str_parts)
full_display = f"{header}\n{reply_context_str}{post_text_display}{embed_display}{counts_line}"
return full_display.strip()
def compose_notification_for_display(self, notif_data: dict[str, Any]) -> str:
"""
Composes a string representation of a Bluesky notification for display.
Args:
notif_data: A dictionary representing the notification,
typically from BlueskiSession._handle_*_notification methods
which create an approve.notifications.Notification object and then
convert it to dict or pass relevant parts.
Expected keys: 'title', 'body', 'author_name', 'timestamp_dt', 'kind'.
The 'title' usually already contains the core action.
Returns:
A formatted string for display.
"""
if not notif_data or not isinstance(notif_data, dict):
return _("Invalid notification data.")
title = notif_data.get('title', _("Notification"))
body = notif_data.get('body', '')
author_name = notif_data.get('author_name') # Author of the action (e.g. who liked)
timestamp_dt = notif_data.get('timestamp_dt') # datetime object
timestamp_str = ""
if timestamp_dt and isinstance(timestamp_dt, datetime):
try:
timestamp_str = timestamp_dt.strftime("%I:%M %p - %b %d, %Y")
except Exception as e:
logger.debug(f"Could not format notification timestamp {timestamp_dt}: {e}")
timestamp_str = str(timestamp_dt)
display_parts = []
if timestamp_str:
display_parts.append(f"[{timestamp_str}]")
# Title already contains good info like "UserX liked your post"
display_parts.append(title)
if body: # Body might be text of a reply/mention/quote
# Truncate body if too long for a list display
body_snippet = (body[:100] + "...") if len(body) > 103 else body
display_parts.append(f"\"{body_snippet}\"")
return " ".join(display_parts).strip()
log = logging.getLogger("sessions.blueski.compose")
def compose_post(post, db, settings, relative_times, show_screen_names=False, safe=True):
"""
Compose a Bluesky post into a list of strings [User, Text, Date, Source].
post: dict or ATProto model object.
Compose a Bluesky post into a list of strings for display.
Args:
post: dict or ATProto model object (FeedViewPost or PostView)
db: Session database dict
settings: Session settings
relative_times: If True, use relative time formatting
show_screen_names: If True, show only @handle instead of display name
safe: If True, handle exceptions gracefully
Returns:
List of strings: [User, Text, Date, Source]
"""
# Extract data using getattr for models or .get for dicts
def g(obj, key, default=None):
"""Helper to get attribute from dict or object."""
if isinstance(obj, dict):
return obj.get(key, default)
return getattr(obj, key, default)
# Resolve Post View or Feed View structure
# Feed items often have .post field. Direct post objects don't.
actual_post = g(post, "post", post)
# Feed items have .post field, direct post objects don't
actual_post = g(post, "post", post)
record = g(actual_post, "record", {})
author = g(actual_post, "author", {})
# Author
handle = g(author, "handle", "")
display_name = g(author, "displayName") or g(author, "display_name") or handle or "Unknown"
if show_screen_names:
user_str = f"@{handle}"
else:
# "Display Name (@handle)"
if handle and display_name != handle:
user_str = f"{display_name} (@{handle})"
else:
user_str = f"@{handle}"
# Text
text = g(record, "text", "")
# Repost reason (so users know why they see an unfamiliar post)
# Repost reason
reason = g(post, "reason", None)
if reason:
rtype = g(reason, "$type") or g(reason, "py_type")
@@ -300,113 +67,196 @@ def compose_post(post, db, settings, relative_times, show_screen_names=False, sa
by_handle = g(by, "handle", "")
reason_line = _("Reposted by @{handle}").format(handle=by_handle) if by_handle else _("Reposted")
text = f"{reason_line}\n{text}" if text else reason_line
# Labels / Content Warning
labels = g(actual_post, "labels", [])
cw_text = ""
is_sensitive = False
for label in labels:
val = g(label, "val", "")
if val in ["!warn", "porn", "sexual", "nudity", "gore", "graphic-media", "corpse", "self-harm", "hate", "spam", "impersonation"]:
is_sensitive = True
if not cw_text: cw_text = _("Sensitive Content")
if not cw_text:
cw_text = _("Sensitive Content")
elif val.startswith("warn:"):
is_sensitive = True
cw_text = val.split("warn:", 1)[-1].strip()
if cw_text:
text = f"CW: {cw_text}\n\n{text}"
# Embeds (Images, Quotes)
# Embeds (Images, Quotes, Links)
embed = g(actual_post, "embed", None)
if embed:
etype = g(embed, "$type") or g(embed, "py_type")
# Images
if etype and ("images" in etype):
images = g(embed, "images", [])
if images:
text += f"\n[{len(images)} {_('Images')}]"
# Handle Record (Quote) or RecordWithMedia (Quote + Media)
# Quote posts
quote_rec = None
if etype and ("recordWithMedia" in etype):
# Extract the nested record
rec_embed = g(embed, "record", {})
if rec_embed:
quote_rec = g(rec_embed, "record", None) or rec_embed
# Also check for media in the wrapper
media = g(embed, "media", {})
mtype = g(media, "$type") or g(media, "py_type")
if mtype and "images" in mtype:
images = g(media, "images", [])
if images: text += f"\n[{len(images)} {_('Images')}]"
elif etype and ("record" in etype):
# Direct quote
quote_rec = g(embed, "record", {})
if isinstance(quote_rec, dict):
quote_rec = quote_rec.get("record") or quote_rec
if quote_rec:
# It is likely a ViewRecord
# Check type (ViewRecord, ViewNotFound, ViewBlocked, etc)
qtype = g(quote_rec, "$type") or g(quote_rec, "py_type")
if qtype and "viewNotFound" in qtype:
text += f"\n[{_('Quoted post not found')}]"
elif qtype and "viewBlocked" in qtype:
text += f"\n[{_('Quoted post blocked')}]"
elif qtype and "generatorView" in qtype:
# Feed generator
gen = g(quote_rec, "displayName", "Feed")
text += f"\n[{_('Quoting Feed')}: {gen}]"
else:
# Assume ViewRecord
q_author = g(quote_rec, "author", {})
q_handle = g(q_author, "handle", "unknown")
q_val = g(quote_rec, "value", {})
q_text = g(q_val, "text", "")
rec_embed = g(embed, "record", {})
if rec_embed:
quote_rec = g(rec_embed, "record", None) or rec_embed
# Media in wrapper
media = g(embed, "media", {})
mtype = g(media, "$type") or g(media, "py_type")
if mtype and "images" in mtype:
images = g(media, "images", [])
if images:
text += f"\n[{len(images)} {_('Images')}]"
if q_text:
text += f"\n[{_('Quoting')} @{q_handle}: {q_text}]"
else:
text += f"\n[{_('Quoting')} @{q_handle}]"
elif etype and ("record" in etype):
quote_rec = g(embed, "record", {})
if isinstance(quote_rec, dict):
quote_rec = quote_rec.get("record") or quote_rec
if quote_rec:
qtype = g(quote_rec, "$type") or g(quote_rec, "py_type")
if qtype and "viewNotFound" in qtype:
text += f"\n[{_('Quoted post not found')}]"
elif qtype and "viewBlocked" in qtype:
text += f"\n[{_('Quoted post blocked')}]"
elif qtype and "generatorView" in qtype:
gen = g(quote_rec, "displayName", "Feed")
text += f"\n[{_('Quoting Feed')}: {gen}]"
else:
q_author = g(quote_rec, "author", {})
q_handle = g(q_author, "handle", "unknown")
q_val = g(quote_rec, "value", {})
q_text = g(q_val, "text", "")
if q_text:
text += f"\n[{_('Quoting')} @{q_handle}: {q_text}]"
else:
text += f"\n[{_('Quoting')} @{q_handle}]"
elif etype and ("external" in etype):
ext = g(embed, "external", {})
uri = g(ext, "uri", "")
title = g(ext, "title", "")
text += f"\n[{_('Link')}: {title}]"
# Date
indexed_at = g(actual_post, "indexed_at", "")
indexed_at = g(actual_post, "indexed_at", "") or g(actual_post, "indexedAt", "")
ts_str = ""
if indexed_at:
try:
# Try arrow parsing
import arrow
ts = arrow.get(indexed_at)
if relative_times:
ts_str = ts.humanize(locale=languageHandler.curLang[:2])
else:
ts_str = ts.format(_("dddd, MMMM D, YYYY H:m"), locale=languageHandler.curLang[:2])
ts = arrow.get(indexed_at)
if relative_times:
ts_str = ts.humanize(locale=languageHandler.curLang[:2])
else:
ts_str = ts.format(_("dddd, MMMM D, YYYY H:m"), locale=languageHandler.curLang[:2])
except Exception:
ts_str = str(indexed_at)[:16].replace("T", " ")
ts_str = str(indexed_at)[:16].replace("T", " ")
# Source (not always available in Bsky view, often just client)
# We'll leave it empty or mock it if needed
# Source / Client
source = "Bluesky"
# Viewer state (liked, reposted, etc.)
viewer_indicators = []
viewer = g(actual_post, "viewer") or g(post, "viewer")
if viewer:
if g(viewer, "like"):
viewer_indicators.append("") # Liked
if g(viewer, "repost"):
viewer_indicators.append("🔁") # Reposted
# Add viewer indicators to the source column or create a prefix for text
if viewer_indicators:
indicator_str = " ".join(viewer_indicators)
# Add to beginning of text for visibility
text = f"{indicator_str} {text}"
return [user_str, text, ts_str, source]
def compose_notification(notification, db, settings, relative_times, show_screen_names=False, safe=True):
"""
Compose a Bluesky notification into a list of strings for display.
Args:
notification: ATProto notification object
db: Session database dict
settings: Session settings
relative_times: If True, use relative time formatting
show_screen_names: If True, show only @handle
safe: If True, handle exceptions gracefully
Returns:
List of strings: [User, Action/Text, Date]
"""
def g(obj, key, default=None):
if isinstance(obj, dict):
return obj.get(key, default)
return getattr(obj, key, default)
# Author of the notification (who performed the action)
author = g(notification, "author", {})
handle = g(author, "handle", "unknown")
display_name = g(author, "displayName") or g(author, "display_name") or handle
if show_screen_names:
user_str = f"@{handle}"
else:
user_str = f"{display_name} (@{handle})"
# Notification reason/type
reason = g(notification, "reason", "unknown")
# Map reason to user-readable text
reason_text_map = {
"like": _("liked your post"),
"repost": _("reposted your post"),
"follow": _("followed you"),
"mention": _("mentioned you"),
"reply": _("replied to you"),
"quote": _("quoted your post"),
"starterpack-joined": _("joined your starter pack"),
}
action_text = reason_text_map.get(reason, reason)
# For mentions/replies/quotes, include snippet of the text
record = g(notification, "record", {})
post_text = g(record, "text", "")
if post_text and reason in ["mention", "reply", "quote"]:
snippet = post_text[:100] + "..." if len(post_text) > 100 else post_text
action_text = f"{action_text}: {snippet}"
# Date
indexed_at = g(notification, "indexedAt", "") or g(notification, "indexed_at", "")
ts_str = ""
if indexed_at:
try:
ts = arrow.get(indexed_at)
if relative_times:
ts_str = ts.humanize(locale=languageHandler.curLang[:2])
else:
ts_str = ts.format(_("dddd, MMMM D, YYYY H:m"), locale=languageHandler.curLang[:2])
except Exception:
ts_str = str(indexed_at)[:16].replace("T", " ")
return [user_str, action_text, ts_str]
def compose_user(user, db, settings, relative_times, show_screen_names=False, safe=True):
"""
Compose a Bluesky user for list display.
Returns: [User summary string]
Compose a Bluesky user profile for list display.
Args:
user: User profile dict or ATProto model
db: Session database dict
settings: Session settings
relative_times: If True, use relative time formatting
show_screen_names: If True, show only @handle
safe: If True, handle exceptions gracefully
Returns:
List of strings: [User summary]
"""
# Extract data using getattr for models or .get for dicts
def g(obj, key, default=None):
if isinstance(obj, dict):
return obj.get(key, default)
@@ -422,7 +272,6 @@ def compose_user(user, db, settings, relative_times, show_screen_names=False, sa
ts = ""
if created_at:
try:
import arrow
original_date = arrow.get(created_at)
if relative_times:
ts = original_date.humanize(locale=languageHandler.curLang[:2])
@@ -442,10 +291,21 @@ def compose_user(user, db, settings, relative_times, show_screen_names=False, sa
return [" ".join(parts).strip()]
def compose_convo(convo, db, settings, relative_times, show_screen_names=False, safe=True):
"""
Compose a Bluesky chat conversation for list display.
Returns: [Participants, Last Message, Date]
Args:
convo: Conversation dict or ATProto model
db: Session database dict
settings: Session settings
relative_times: If True, use relative time formatting
show_screen_names: If True, show only @handle
safe: If True, handle exceptions gracefully
Returns:
List of strings: [Participants, Last Message, Date]
"""
def g(obj, key, default=None):
if isinstance(obj, dict):
@@ -454,6 +314,8 @@ def compose_convo(convo, db, settings, relative_times, show_screen_names=False,
members = g(convo, "members", [])
self_did = db.get("user_id") if isinstance(db, dict) else None
# Get other participants (exclude self)
others = []
for m in members:
did = g(m, "did", None)
@@ -461,35 +323,36 @@ def compose_convo(convo, db, settings, relative_times, show_screen_names=False,
continue
label = g(m, "displayName") or g(m, "display_name") or g(m, "handle", "unknown")
others.append(label)
if not others:
others = [g(m, "displayName") or g(m, "display_name") or g(m, "handle", "unknown") for m in members]
participants = ", ".join(others)
# Last message
last_msg_obj = g(convo, "lastMessage") or g(convo, "last_message")
last_text = ""
last_sender = ""
if last_msg_obj:
last_text = g(last_msg_obj, "text", "")
sender = g(last_msg_obj, "sender", None)
if sender:
last_sender = g(sender, "displayName") or g(sender, "display_name") or g(sender, "handle", "")
# Date (using lastMessage.sentAt)
# Date
date_str = ""
sent_at = None
if last_msg_obj:
sent_at = g(last_msg_obj, "sentAt") or g(last_msg_obj, "sent_at")
if sent_at:
try:
import arrow
ts = arrow.get(sent_at)
if relative_times:
date_str = ts.humanize(locale=languageHandler.curLang[:2])
else:
date_str = ts.format(_("dddd, MMMM D, YYYY H:m"), locale=languageHandler.curLang[:2])
except:
date_str = str(sent_at)[:16]
if sent_at:
try:
ts = arrow.get(sent_at)
if relative_times:
date_str = ts.humanize(locale=languageHandler.curLang[:2])
else:
date_str = ts.format(_("dddd, MMMM D, YYYY H:m"), locale=languageHandler.curLang[:2])
except Exception:
date_str = str(sent_at)[:16]
if last_sender and last_text:
last_text = _("Last message from {user}: {text}").format(user=last_sender, text=last_text)
@@ -498,10 +361,21 @@ def compose_convo(convo, db, settings, relative_times, show_screen_names=False,
return [participants, last_text, date_str]
def compose_chat_message(msg, db, settings, relative_times, show_screen_names=False, safe=True):
"""
Compose an individual chat message for display in a thread.
Returns: [Sender, Text, Date]
Compose an individual chat message for display.
Args:
msg: Chat message dict or ATProto model
db: Session database dict
settings: Session settings
relative_times: If True, use relative time formatting
show_screen_names: If True, show only @handle
safe: If True, handle exceptions gracefully
Returns:
List of strings: [Sender, Text, Date]
"""
def g(obj, key, default=None):
if isinstance(obj, dict):
@@ -510,20 +384,20 @@ def compose_chat_message(msg, db, settings, relative_times, show_screen_names=Fa
sender = g(msg, "sender", {})
handle = g(sender, "displayName") or g(sender, "display_name") or g(sender, "handle", "unknown")
text = g(msg, "text", "")
# Date
sent_at = g(msg, "sentAt") or g(msg, "sent_at")
date_str = ""
if sent_at:
try:
import arrow
ts = arrow.get(sent_at)
if relative_times:
date_str = ts.humanize(locale=languageHandler.curLang[:2])
else:
date_str = ts.format(_("dddd, MMMM D, YYYY H:m"), locale=languageHandler.curLang[:2])
except:
except Exception:
date_str = str(sent_at)[:16]
return [handle, text, date_str]

View File

@@ -6,6 +6,8 @@ from typing import Any
import wx
from pubsub import pub
from sessions import base
from sessions import session_exceptions as Exceptions
import output
@@ -36,6 +38,9 @@ class Session(base.baseSession):
self.type = "blueski"
self.char_limit = 300
self.api = None
self.poller = None
# Subscribe to pub/sub events from the poller
pub.subscribe(self.on_notification, "blueski.notification_received")
def _ensure_settings_namespace(self) -> None:
"""Migrate legacy atprotosocial settings to blueski namespace."""
@@ -648,19 +653,119 @@ class Session(base.baseSession):
def list_convos(self, limit: int = 50, cursor: str | None = None) -> dict[str, Any]:
api = self._ensure_client()
res = api.chat.bsky.convo.list_convos({"limit": limit, "cursor": cursor})
# Chat API requires using the chat proxy
dm_client = api.with_bsky_chat_proxy()
res = dm_client.chat.bsky.convo.list_convos({"limit": limit, "cursor": cursor})
return {"items": res.convos, "cursor": res.cursor}
def get_convo_messages(self, convo_id: str, limit: int = 50, cursor: str | None = None) -> dict[str, Any]:
api = self._ensure_client()
res = api.chat.bsky.convo.get_messages({"convoId": convo_id, "limit": limit, "cursor": cursor})
dm_client = api.with_bsky_chat_proxy()
res = dm_client.chat.bsky.convo.get_messages({"convoId": convo_id, "limit": limit, "cursor": cursor})
return {"items": res.messages, "cursor": res.cursor}
def send_chat_message(self, convo_id: str, text: str) -> Any:
api = self._ensure_client()
return api.chat.bsky.convo.send_message({
dm_client = api.with_bsky_chat_proxy()
return dm_client.chat.bsky.convo.send_message({
"convoId": convo_id,
"message": {
"text": text
}
})
# Streaming/Polling methods
def start_streaming(self):
"""Start the background poller for notifications."""
if not self.logged:
log.debug("Cannot start Bluesky poller: not logged in.")
return
if self.poller is not None and self.poller.is_alive():
log.debug("Bluesky poller already running for %s", self.get_name())
return
try:
from sessions.blueski.streaming import BlueskyPoller
poll_interval = 60
try:
poll_interval = self.settings["general"].get("update_period", 60)
except Exception:
pass
self.poller = BlueskyPoller(
session=self,
session_name=self.get_name(),
poll_interval=poll_interval
)
self.poller.start()
log.info("Started Bluesky poller for session %s", self.get_name())
except Exception:
log.exception("Failed to start Bluesky poller")
def stop_streaming(self):
"""Stop the background poller."""
if self.poller is not None:
self.poller.stop()
self.poller = None
log.info("Stopped Bluesky poller for session %s", self.get_name())
def on_notification(self, notification, session_name):
"""Handle notification received from the poller via pub/sub."""
# Discard if notification is for a different session
if self.get_name() != session_name:
return
# Add notification to the notifications buffer
try:
num = self.order_buffer("notifications", [notification])
if num > 0:
pub.sendMessage(
"blueski.new_item",
session_name=self.get_name(),
item=notification,
_buffers=["notifications"]
)
except Exception:
log.exception("Error processing Bluesky notification")
def order_buffer(self, buffer_name, items):
"""Add items to the specified buffer's database.
Returns the number of new items added.
"""
if buffer_name not in self.db:
self.db[buffer_name] = []
# Get existing URIs to avoid duplicates
existing_uris = set()
for item in self.db[buffer_name]:
uri = None
if isinstance(item, dict):
uri = item.get("uri")
else:
uri = getattr(item, "uri", None)
if uri:
existing_uris.add(uri)
# Add new items
new_count = 0
for item in items:
uri = None
if isinstance(item, dict):
uri = item.get("uri")
else:
uri = getattr(item, "uri", None)
if uri and uri in existing_uris:
continue
if uri:
existing_uris.add(uri)
# Insert at beginning (newest first)
self.db[buffer_name].insert(0, item)
new_count += 1
return new_count

View File

@@ -1,209 +1,196 @@
from __future__ import annotations
# -*- coding: utf-8 -*-
"""
Bluesky polling-based update system for TWBlue.
Since Bluesky's Firehose requires complex CAR/CBOR decoding and filtering
of millions of events, we use a polling approach instead of true streaming.
This matches the existing start_stream() pattern used by buffers.
Events are published via pub/sub to maintain consistency with Mastodon's
streaming implementation.
"""
import asyncio
import logging
from typing import TYPE_CHECKING, Any, Callable, Coroutine
import threading
import time
from pubsub import pub
if TYPE_CHECKING:
fromapprove.sessions.blueski.session import Session as BlueskiSession
logger = logging.getLogger(__name__)
# Blueski (Bluesky) uses a Firehose model for streaming.
# This typically involves connecting to a WebSocket endpoint and receiving events.
# The atproto SDK provides tools for this.
log = logging.getLogger("sessions.blueski.streaming")
class BlueskiStreaming:
def __init__(self, session: BlueskiSession, stream_type: str, params: dict[str, Any] | None = None) -> None:
class BlueskyPoller:
"""
Polling-based update system for Bluesky.
Periodically checks for new notifications and publishes them via pub/sub.
This provides a similar interface to Mastodon's StreamListener but uses
polling instead of WebSocket streaming.
"""
def __init__(self, session, session_name, poll_interval=60):
"""
Initialize the poller.
Args:
session: The Bluesky session instance
session_name: Unique identifier for this session (for pub/sub routing)
poll_interval: Seconds between API polls (default 60, min 30)
"""
self.session = session
self.stream_type = stream_type # e.g., 'user', 'public', 'hashtag' - will need mapping to Firehose concepts
self.params = params or {}
self._handler: Callable[[dict[str, Any]], Coroutine[Any, Any, None]] | None = None
self._connection_task: asyncio.Task[None] | None = None
self._should_stop = False
# self._client = None # This would be an instance of atproto.firehose.FirehoseSubscribeReposClient or similar
self.session_name = session_name
self.poll_interval = max(30, poll_interval) # Minimum 30 seconds to respect rate limits
# TODO: Map stream_type and params to ATProto Firehose subscription needs.
# For example, 'user' might mean subscribing to mentions, replies, follows for the logged-in user.
# This would likely involve filtering the general repo firehose for relevant events,
# or using a more specific subscription if available for user-level events.
self._stop_event = threading.Event()
self._thread = None
self._last_notification_cursor = None
self._last_seen_notification_uri = None
async def _connect(self) -> None:
"""Internal method to connect to the Blueski Firehose."""
# from atproto import AsyncClient
# from atproto.firehose import FirehoseSubscribeReposClient, parse_subscribe_repos_message
# from atproto.xrpc_client.models import get_or_create, ids, models
logger.info(f"Blueski streaming: Connecting to Firehose for user {self.session.user_id}, stream type {self.stream_type}")
self._should_stop = False
try:
# TODO: Replace with actual atproto SDK usage
# client = self.session.util.get_client() # Get authenticated client from session utils
# if not client or not client.me: # Check if client is authenticated
# logger.error("Blueski client not authenticated. Cannot start Firehose.")
# return
# self._firehose_client = FirehoseSubscribeReposClient(params=None, base_uri=self.session.api_base_url) # Adjust base_uri if needed
# async def on_message_handler(message: models.ComAtprotoSyncSubscribeRepos.Message) -> None:
# if self._should_stop:
# await self._firehose_client.stop() # Ensure client stops if flag is set
# return
# # This is a simplified example. Real implementation needs to:
# # 1. Determine the type of message (commit, handle, info, migrate, tombstone)
# # 2. For commits, unpack operations to find posts, likes, reposts, follows, etc.
# # 3. Filter these events to be relevant to the user (e.g., mentions, replies to user, new posts from followed users)
# # 4. Format the data into a structure that self._handle_event expects.
# # This filtering can be complex.
# # Example: if it's a commit and contains a new post that mentions the user
# # if isinstance(message, models.ComAtprotoSyncSubscribeRepos.Commit):
# # # This part is highly complex due to CAR CIBOR decoding
# # # Operations need to be extracted from the commit block
# # # For each op, check if it's a create, and if the record is a post
# # # Then, check if the post's text or facets mention the current user.
# # # This is a placeholder for that logic.
# # logger.debug(f"Firehose commit from {message.repo} at {message.time}")
# # # Example of processing ops (pseudo-code, actual decoding is more involved):
# # # ops = message.ops
# # # for op in ops:
# # # if op.action == 'create' and op.path.endswith('/app.bsky.feed.post/...'):
# # # record_data = ... # decode op.cid from message.blocks
# # # if self.session.util.is_mention_of_me(record_data):
# # # event_data = self.session.util.format_post_event(record_data)
# # # await self._handle_event("mention", event_data)
# # For now, we'll just log that a message was received
# logger.debug(f"Blueski Firehose message received: {message.__class__.__name__}")
# await self._firehose_client.start(on_message_handler)
# Placeholder loop to simulate receiving events
while not self._should_stop:
await asyncio.sleep(1)
# In a real implementation, this loop wouldn't exist; it'd be driven by the SDK's event handler.
# To simulate an event:
# if self._handler:
# mock_event = {"type": "placeholder_event", "data": {"text": "Hello from mock stream"}}
# await self._handler(mock_event) # Call the registered handler
logger.info(f"Blueski streaming: Placeholder loop for {self.session.user_id} stopped.")
except asyncio.CancelledError:
logger.info(f"Blueski streaming task for user {self.session.user_id} was cancelled.")
except Exception as e:
logger.error(f"Blueski streaming error for user {self.session.user_id}: {e}", exc_info=True)
# Optional: implement retry logic here or in the start_streaming method
if not self._should_stop:
await asyncio.sleep(30) # Wait before trying to reconnect (if auto-reconnect is desired)
if not self._should_stop: # Check again before restarting
self._connection_task = asyncio.create_task(self._connect())
finally:
# if self._firehose_client:
# await self._firehose_client.stop()
logger.info(f"Blueski streaming connection closed for user {self.session.user_id}.")
async def _handle_event(self, event_type: str, data: dict[str, Any]) -> None:
"""
Internal method to process an event from the stream and pass it to the session's handler.
"""
if self._handler:
try:
# The data should be transformed into a common format expected by session.handle_streaming_event
# This is where Blueski-specific event data is mapped to Approve's internal event structure.
# For example, an Blueski 'mention' event needs to be structured similarly to
# how a Mastodon 'mention' event would be.
await self.session.handle_streaming_event(event_type, data)
except Exception as e:
logger.error(f"Error handling Blueski streaming event type {event_type}: {e}", exc_info=True)
else:
logger.warning(f"Blueski streaming: No handler registered for session {self.session.user_id}, event: {event_type}")
def start_streaming(self, handler: Callable[[dict[str, Any]], Coroutine[Any, Any, None]]) -> None:
"""Starts the streaming connection."""
if self._connection_task and not self._connection_task.done():
logger.warning(f"Blueski streaming already active for user {self.session.user_id}.")
def start(self):
"""Start the polling thread."""
if self._thread is not None and self._thread.is_alive():
log.warning(f"Bluesky poller for {self.session_name} is already running.")
return
self._handler = handler # This handler is what session.py's handle_streaming_event calls
self._should_stop = False
logger.info(f"Blueski streaming: Starting for user {self.session.user_id}, type: {self.stream_type}")
self._connection_task = asyncio.create_task(self._connect())
self._stop_event.clear()
self._thread = threading.Thread(
target=self._poll_loop,
name=f"BlueskyPoller-{self.session_name}",
daemon=True
)
self._thread.start()
log.info(f"Bluesky poller started for {self.session_name} (interval: {self.poll_interval}s)")
def stop(self):
"""Stop the polling thread."""
if self._thread is None:
return
async def stop_streaming(self) -> None:
"""Stops the streaming connection."""
logger.info(f"Blueski streaming: Stopping for user {self.session.user_id}")
self._should_stop = True
# if self._firehose_client: # Assuming the SDK has a stop method
# await self._firehose_client.stop()
self._stop_event.set()
self._thread.join(timeout=5)
self._thread = None
log.info(f"Bluesky poller stopped for {self.session_name}")
if self._connection_task:
if not self._connection_task.done():
self._connection_task.cancel()
def is_alive(self):
"""Check if the polling thread is running."""
return self._thread is not None and self._thread.is_alive()
def _poll_loop(self):
"""Main polling loop running in background thread."""
log.debug(f"Polling loop started for {self.session_name}")
# Initial delay to let the app fully initialize
time.sleep(5)
while not self._stop_event.is_set():
try:
await self._connection_task
except asyncio.CancelledError:
logger.info(f"Blueski streaming task successfully cancelled for {self.session.user_id}.")
self._connection_task = None
self._handler = None
logger.info(f"Blueski streaming stopped for user {self.session.user_id}.")
self._check_notifications()
except Exception as e:
log.exception(f"Error in Bluesky polling loop for {self.session_name}: {e}")
def is_alive(self) -> bool:
"""Checks if the streaming connection is currently active."""
# return self._connection_task is not None and not self._connection_task.done() and self._firehose_client and self._firehose_client.is_connected
return self._connection_task is not None and not self._connection_task.done() # Simplified check
# Wait for next poll interval, checking stop event periodically
for _ in range(self.poll_interval):
if self._stop_event.is_set():
break
time.sleep(1)
def get_stream_type(self) -> str:
return self.stream_type
log.debug(f"Polling loop ended for {self.session_name}")
def get_params(self) -> dict[str, Any]:
return self.params
def _check_notifications(self):
"""Check for new notifications and publish events."""
if not self.session.logged:
return
# TODO: Add methods specific to Blueski streaming if necessary,
# e.g., methods to modify subscription details on the fly if the API supports it.
# For Bluesky Firehose, this might not be applicable as you usually connect and filter client-side.
# However, if there were different Firehose endpoints (e.g., one for public posts, one for user-specific events),
# this class might manage multiple connections or re-establish with new parameters.
try:
api = self.session._ensure_client()
if not api:
return
# Example of how events might be processed (highly simplified):
# This would be called by the on_message_handler in _connect
# async def _process_firehose_message(self, message: models.ComAtprotoSyncSubscribeRepos.Message):
# if isinstance(message, models.ComAtprotoSyncSubscribeRepos.Commit):
# # Decode CAR file in message.blocks to get ops
# # For each op (create, update, delete of a record):
# # record = get_record_from_blocks(message.blocks, op.cid)
# # if op.path.startswith("app.bsky.feed.post"): # It's a post
# # # Check if it's a new post, a reply, a quote, etc.
# # # Check for mentions of the current user
# # # Example:
# # if self.session.util.is_mention_of_me(record):
# # formatted_event = self.session.util.format_post_as_notification(record, "mention")
# # await self._handle_event("mention", formatted_event)
# # elif op.path.startswith("app.bsky.graph.follow"):
# # # Check if it's a follow of the current user
# # if record.subject == self.session.util.get_my_did(): # Assuming get_my_did() exists
# # formatted_event = self.session.util.format_follow_as_notification(record)
# # await self._handle_event("follow", formatted_event)
# # # Handle likes (app.bsky.feed.like), reposts (app.bsky.feed.repost), etc.
# pass
# elif isinstance(message, models.ComAtprotoSyncSubscribeRepos.Handle):
# # Handle DID to handle mapping updates if necessary
# logger.debug(f"Handle update: {message.handle} now points to {message.did} at {message.time}")
# elif isinstance(message, models.ComAtprotoSyncSubscribeRepos.Migrate):
# logger.info(f"Repo migration: {message.did} migrating from {message.migrateTo} at {message.time}")
# elif isinstance(message, models.ComAtprotoSyncSubscribeRepos.Tombstone):
# logger.info(f"Repo tombstone: {message.did} at {message.time}")
# elif isinstance(message, models.ComAtprotoSyncSubscribeRepos.Info):
# logger.info(f"Firehose info: {message.name} - {message.message}")
# else:
# logger.debug(f"Unknown Firehose message type: {message.__class__.__name__}")
# Fetch recent notifications
res = api.app.bsky.notification.list_notifications({"limit": 20})
notifications = getattr(res, "notifications", [])
if not notifications:
return
# Track which notifications are new
new_notifications = []
newest_uri = None
for notif in notifications:
uri = getattr(notif, "uri", None)
if not uri:
continue
# First time running - just record the newest and don't flood
if self._last_seen_notification_uri is None:
newest_uri = uri
break
# Check if we've seen this notification before
if uri == self._last_seen_notification_uri:
break
new_notifications.append(notif)
if newest_uri is None:
newest_uri = uri
# Update last seen
if newest_uri:
self._last_seen_notification_uri = newest_uri
# Publish new notifications (in reverse order so oldest first)
for notif in reversed(new_notifications):
self._publish_notification(notif)
except Exception as e:
log.debug(f"Error checking notifications for {self.session_name}: {e}")
def _publish_notification(self, notification):
"""Publish a notification event via pub/sub."""
try:
reason = getattr(notification, "reason", "unknown")
log.debug(f"Publishing Bluesky notification: {reason} for {self.session_name}")
pub.sendMessage(
"blueski.notification_received",
notification=notification,
session_name=self.session_name
)
# Also publish specific events for certain notification types
if reason == "mention":
pub.sendMessage(
"blueski.mention_received",
notification=notification,
session_name=self.session_name
)
elif reason == "reply":
pub.sendMessage(
"blueski.reply_received",
notification=notification,
session_name=self.session_name
)
elif reason == "follow":
pub.sendMessage(
"blueski.follow_received",
notification=notification,
session_name=self.session_name
)
except Exception as e:
log.exception(f"Error publishing notification event: {e}")
def create_poller(session, session_name, poll_interval=60):
"""
Factory function to create a BlueskyPoller instance.
Args:
session: The Bluesky session instance
session_name: Unique identifier for this session
poll_interval: Seconds between polls (default 60)
Returns:
BlueskyPoller instance
"""
return BlueskyPoller(session, session_name, poll_interval)

View File

@@ -1,123 +0,0 @@
from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Any
fromapprove.translation import translate as _
if TYPE_CHECKING:
fromapprove.sessions.blueski.session import Session as BlueskiSession
logger = logging.getLogger(__name__)
class BlueskiTemplates:
def __init__(self, session: BlueskiSession) -> None:
self.session = session
def get_template_data(self, template_name: str, context: dict[str, Any] | None = None) -> dict[str, Any]:
"""
Returns data required for rendering a specific template for Blueski.
This method would populate template variables based on the template name and context.
"""
base_data = {
"session_kind": self.session.kind,
"session_label": self.session.label,
"user_id": self.session.user_id,
# Add any other common data needed by Blueski templates
}
if context:
base_data.update(context)
# TODO: Implement specific data fetching for different Blueski templates
# Example:
# if template_name == "profile_summary.html":
# # profile_info = await self.session.util.get_my_profile_info() # Assuming such a method exists
# # base_data["profile"] = profile_info
# base_data["profile"] = {"display_name": "User", "handle": "user.bsky.social"} # Placeholder
# elif template_name == "post_details.html":
# # post_id = context.get("post_id")
# # post_details = await self.session.util.get_post_by_id(post_id)
# # base_data["post"] = post_details
# base_data["post"] = {"text": "A sample post", "author_handle": "author.bsky.social"} # Placeholder
return base_data
def get_message_card_template(self) -> str:
"""Returns the path to the message card template for Blueski."""
# This template would define how a single Blueski post (or other message type)
# is rendered in a list (e.g., in a timeline or search results).
# return "sessions/blueski/cards/message.html" # Example path
return "sessions/generic/cards/message_generic.html" # Placeholder, use generic if no specific yet
def get_notification_template_map(self) -> dict[str, str]:
"""
Returns a map of Blueski notification types to their respective template paths.
"""
# TODO: Define templates for different Blueski notification types
# (e.g., mention, reply, new follower, like, repost).
# The keys should match the notification types used internally by Approve
# when processing Blueski events.
# Example:
# return {
# "mention": "sessions/blueski/notifications/mention.html",
# "reply": "sessions/blueski/notifications/reply.html",
# "follow": "sessions/blueski/notifications/follow.html",
# "like": "sessions/blueski/notifications/like.html", # Bluesky uses 'like'
# "repost": "sessions/blueski/notifications/repost.html", # Bluesky uses 'repost'
# # ... other notification types
# }
# Using generic templates as placeholders:
return {
"mention": "sessions/generic/notifications/mention.html",
"reply": "sessions/generic/notifications/reply.html",
"follow": "sessions/generic/notifications/follow.html",
"like": "sessions/generic/notifications/favourite.html", # Map to favourite if generic expects that
"repost": "sessions/generic/notifications/reblog.html", # Map to reblog if generic expects that
}
def get_settings_template(self) -> str | None:
"""Returns the path to the settings template for Blueski, if any."""
# This template would be used to render Blueski-specific settings in the UI.
# return "sessions/blueski/settings.html"
return "sessions/generic/settings_auth_password.html" # If using simple handle/password auth
def get_user_action_templates(self) -> dict[str, str] | None:
"""
Returns a map of user action identifiers to their template paths for Blueski.
User actions are typically buttons or forms displayed on a user's profile.
"""
# TODO: Define templates for Blueski user actions
# Example:
# return {
# "view_profile_on_bsky": "sessions/blueski/actions/view_profile_button.html",
# "send_direct_message": "sessions/blueski/actions/send_dm_form.html", # If DMs are supported
# }
return None # Placeholder
def get_user_list_action_templates(self) -> dict[str, str] | None:
"""
Returns a map of user list action identifiers to their template paths for Blueski.
These actions might appear on lists of users (e.g., followers, following).
"""
# TODO: Define templates for Blueski user list actions
# Example:
# return {
# "follow_all_visible": "sessions/blueski/list_actions/follow_all_button.html",
# }
return None # Placeholder
# Add any other template-related helper methods specific to Blueski.
# For example, methods to get templates for specific types of content (images, polls)
# if they need special rendering.
def get_template_for_message_type(self, message_type: str) -> str | None:
"""
Returns a specific template path for a given message type (e.g., post, reply, quote).
This can be useful if different types of messages need distinct rendering beyond the standard card.
"""
# TODO: Define specific templates if Blueski messages have varied structures
# that require different display logic.
# if message_type == "quote_post":
# return "sessions/blueski/cards/quote_post.html"
return None # Default to standard message card if not specified

File diff suppressed because it is too large Load Diff