"""Bluesky source class.
* https://bsky.app/
* https://atproto.com/lexicons/app-bsky-actor
* https://github.com/bluesky-social/atproto/tree/main/lexicons/app/bsky
"""
import copy
from datetime import datetime, timezone
import html
import json
import logging
from pathlib import Path
import re
import string
import urllib.parse
from urllib.parse import urlparse, urlunparse
from arroba.did import resolve_handle
from bs4 import BeautifulSoup
from io import BytesIO
from lexrpc import Client
from lexrpc.base import AT_URI_RE, Base, LANG_RE, ValidationError
from multiformats import CID
from oauth_dropins import bluesky as oauth_bluesky
from pymediainfo import MediaInfo
import requests
from requests_oauth2client import OAuth2AccessTokenAuth, TokenSerializer
from webutil import util
from . import as1
from .as2 import CONTENT_TYPE, QUOTE_RE_SUFFIX
from .source import (
creation_result,
FRIENDS,
HTML_ENTITY_RE,
html_to_text,
INCLUDE_LINK,
INCLUDE_IF_TRUNCATED,
OMIT_LINK,
Source,
whitespace_to_html,
)
logger = logging.getLogger(__name__)
# via https://atproto.com/specs/handle
HANDLE_RE = re.compile(
r'([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+'
r'[a-zA-Z]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?'
)
DID_WEB_PATTERN = re.compile('did:web:' + HANDLE_RE.pattern)
MAX_MEDIA_SIZE_BYTES = 5_000_000
# app.bsky.embed.gallery requires aspectRatio, unlike app.bsky.embed.images
DEFAULT_ASPECT_RATIO = {'width': 1, 'height': 1}
MAX_FOLLOWS = 10000
# Maps AT Protocol NSID collections to frontend web URL templates. {id} is the
# repo's handle, if known, otherwise its DID. Used in at_uri_to_web_url.
#
# eg for mapping a URI like:
# at://did:plc:z72i7hd/app.bsky.feed.generator/mutuals
# to a frontend URL like:
# https://bsky.app/profile/did:plc:z72i7hdynmk6r22z27h6tvur/feed/mutuals
COLLECTION_TO_WEB_URL = {
'app.bsky.actor.profile': 'https://bsky.app/profile/{id}',
'app.bsky.feed.generator': 'https://bsky.app/profile/{id}/feed/{rkey}',
'app.bsky.feed.post': 'https://bsky.app/profile/{id}/post/{rkey}',
'app.bsky.graph.list': 'https://bsky.app/profile/{id}/lists/{rkey}',
'so.sprk.actor.profile': 'https://sprk.so/profile/{id}',
'so.sprk.feed.post': 'https://sprk.so/post/{did}/{rkey}',
'social.grain.actor.profile': 'https://grain.social/profile/{id}',
'social.grain.gallery': 'https://grain.social/profile/{id}/gallery/{rkey}',
}
# Maps path elements in bsky.app URLs to AT Protocol NSID collections.
# Used in web_url_to_at_uri.
BSKY_APP_TYPE_TO_COLLECTION = {
'feed': 'app.bsky.feed.generator',
'post': 'app.bsky.feed.post',
'lists': 'app.bsky.graph.list',
}
# maps AS1 RSVP verbs to community.lexicon.calendar.rsvp status tokens.
# the lexicon has no "maybe," so we map it to interested.
RSVP_VERB_TO_STATUS = {
'rsvp-yes': 'going',
'rsvp-no': 'notgoing',
'rsvp-maybe': 'interested',
'rsvp-interested': 'interested',
}
RSVP_STATUS_TO_VERB = {
'going': 'rsvp-yes',
'notgoing': 'rsvp-no',
'interested': 'rsvp-interested',
}
# maps AS1 objectType/verb to possible output Bluesky lexicon types.
# used in from_as1.
#
# Order here is meaningful, starting with most preferred type to convert to.
POST_TYPES = as1.POST_TYPES | set(['bookmark'])
FROM_AS1_TYPES = {
type: (
'app.bsky.actor.profile',
'site.standard.publication',
'so.sprk.actor.profile',
'social.grain.actor.profile',
'app.bsky.actor.defs#profileView',
'app.bsky.actor.defs#profileViewBasic',
'app.bsky.actor.defs#profileViewDetailed',
) for type in as1.ACTOR_TYPES
} | {
type: (
'app.bsky.feed.post',
'so.sprk.feed.post',
'so.sprk.feed.reply',
'social.grain.comment',
'social.grain.gallery',
'app.bsky.feed.defs#feedViewPost',
'app.bsky.feed.defs#postView',
) for type in POST_TYPES
} | {
'link': (
'app.bsky.actor.link',
),
'article': (
'site.standard.document',
'app.bsky.feed.post',
'app.bsky.feed.defs#feedViewPost',
'app.bsky.feed.defs#postView',
),
'block': (
'app.bsky.graph.block',
'app.bsky.graph.listblock',
'so.sprk.graph.block',
),
'event': (
'community.lexicon.calendar.event',
),
'flag': (
'com.atproto.moderation.createReport#input',
),
'follow': (
'app.bsky.graph.follow',
'so.sprk.graph.follow',
),
'like': (
'app.bsky.feed.like',
'so.sprk.feed.like',
'social.grain.favorite',
),
'place': (
'community.lexicon.location.geo',
'community.lexicon.location.address',
),
'question': (
'community.blacksky.assembly.conversation',
),
'vote': (
'community.blacksky.assembly.vote',
),
'share': (
'app.bsky.feed.repost',
'so.sprk.feed.repost',
'app.bsky.feed.defs#feedViewPost',
'app.bsky.feed.defs#reasonRepost',
),
} | {
verb: ('community.lexicon.calendar.rsvp',) for verb in RSVP_VERB_TO_STATUS
}
ATP_PROFILE_TYPES = (
'app.bsky.actor.profile',
'so.sprk.actor.profile',
'social.grain.actor.profile',
)
ATP_POST_TYPES = (
'app.bsky.feed.post',
'so.sprk.feed.post',
'so.sprk.feed.reply',
'social.grain.comment',
'social.grain.gallery',
)
AUTHORITY_CHARS = 'a-zA-Z0-9-.:'
RKEY_CHARS = f'{AUTHORITY_CHARS}~_'
BSKY_APP_URL_RE = re.compile(fr"""
https://(staging\.)?bsky\.app
/profile/(?P<id>[{AUTHORITY_CHARS}]+)
(/(?P<type>{"|".join(BSKY_APP_TYPE_TO_COLLECTION)})
/(?P<tid>[{RKEY_CHARS}]+))?
""", re.VERBOSE)
SPARK_URL_RE = re.compile(fr"""
https://sprk\.so
(/profile/(?P<id>[{AUTHORITY_CHARS}]+)
|/post/(?P<did>[{AUTHORITY_CHARS}]+)/(?P<rkey>[{RKEY_CHARS}]+))
""", re.VERBOSE)
DEFAULT_PDS_DOMAIN = 'bsky.social'
DEFAULT_PDS = f'https://{DEFAULT_PDS_DOMAIN}/'
DEFAULT_APPVIEW = 'https://api.bsky.app'
# URL format for thumbnails generated by Bluesky's video CDN. not officially
# documented.
# https://github.com/bluesky-social/atproto/blob/328a4a86a999357eeae12a6da897bf686b4da88e/packages/bsky/src/views/util.ts#L97
# https://github.com/bluesky-social/atproto/blob/328a4a86a999357eeae12a6da897bf686b4da88e/packages/bsky/src/config.ts#L163
VIDEO_THUMBNAIL_URL = 'https://video.bsky.app/watch/{did}/{cid}/thumbnail.jpg'
# label on profiles set to only show them to logged in users
# https://bsky.app/profile/safety.bsky.app/post/3khhw7s3rtx2s
# https://docs.bsky.app/docs/advanced-guides/resolving-identities#for-backend-services
# https://github.com/bluesky-social/atproto/blob/main/packages/api/docs/labels.md#label-behaviors
NO_UNAUTHENTICATED_LABEL = '!no-unauthenticated'
# label on profiles that indicate automated/bot accounts
# https://docs.bsky.app/docs/advanced-guides/moderation#global-label-values
BOT_LABEL = 'bot'
# Bluesky => AS1 labels
#
# https://docs.bsky.app/docs/advanced-guides/moderation#global-label-values
# https://public.api.bsky.app/xrpc/app.bsky.labeler.getServices?dids=did%3Aplc%3Aar7c4by46qjdydhdevvrndac&detailed=true
# https://github.com/bluesky-social/atproto/blob/f2f8de63b333448d87c364578e023ddbb63b8b25/lexicons/com/atproto/label/defs.json#L139-L154
# https://github.com/bluesky-social/social-app/blob/3627a249ffb32e4c0f84597f8f9adf228ee90a8f/src/lib/moderation/useGlobalLabelStrings.ts
# https://github.com/bluesky-social/social-app/blob/3627a249ffb32e4c0f84597f8f9adf228ee90a8f/bskyembed/src/labels.ts
SENSITIVE_LABELS = {
'porn': 'Adult content',
'sexual': 'Sexually suggestive',
'nudity': 'Non-sexual nudity',
'graphic-media': 'Explicit or potentially disturbing media',
# deprecated
'nsfl': 'Explicit or potentially disturbing media',
'gore': 'Explicit or potentially disturbing media',
}
# AS1 => Bluesky keyword map
#
# Used for checking the as1 summary for keywords that might suggest a specific bluesky label level.
# We are checking labels in increasing order of severity, so the most severe one will be used even if lesser ones are present. (Python preserves the order of dict items)
AS1_TO_BLUESKY_LABEL_MAP = {
'nudity': ['nudity'],
'sexual': ['suggestive', 'sexual'],
'porn': ['porn', 'nsfw']
}
SENSITIVE_LABEL_DEFAULT = 'graphic-media'
# from_as1 output types that get community.lexicon.meta.links (proxy links)
META_LINK_TYPES = (
'app.bsky.actor.profile',
'app.bsky.feed.post',
'community.lexicon.calendar.event',
'site.standard.document',
'so.sprk.actor.profile',
'so.sprk.feed.post',
'so.sprk.feed.reply',
'so.sprk.graph.block',
'so.sprk.graph.follow',
'social.grain.actor.profile',
'social.grain.comment',
'social.grain.gallery',
)
# TODO: bring back validate? or remove?
LEXRPC = Base(truncate=True, validate=False)
# for from_as1(validate=True)
LEXRPC_VALIDATE = Base(truncate=True, validate=True)
ELLIPSIS = ' […]'
[docs]
def url_to_did_web(url):
"""Converts a URL to a ``did:web``.
In AT Proto, only hostname-based web DIDs are supported.
Paths are not supported, and will be discarded.
https://atproto.com/specs/did
Examples:
* ``https://foo.com`` => ``did:web:foo.com``
* ``https://foo.com:3000`` => ``did:web:foo.com``
* ``https://foo.bar.com/baz/baj`` => ``did:web:foo.bar.com``
* ``https://foo.com.`` => ``did:web:foo.com``
Args:
url (str)
Returns:
str:
"""
parsed = urlparse(url)
if not parsed.hostname:
raise ValueError(f'Invalid URL: {url}')
if parsed.port:
logger.warning(f"URL {url} contained a port, which will not be included in the DID.")
if parsed.path and parsed.path != "/":
logger.warning(f"URL {url} contained a path, which will not be included in the DID.")
# strip trailing dot from fully qualified domain names, it's not allowed in DIDs
return f'did:web:{parsed.hostname.removesuffix(".")}'
[docs]
def did_web_to_url(did):
"""Converts a did:web to a URL.
In AT Proto, only hostname-based web DIDs are supported.
Paths are not supported, and will throw an invalid error.
Examples:
* ``did:web:foo.com`` => ``https://foo.com``
* ``did:web:foo.com%3A3000`` => INVALID
* ``did:web:bar.com:baz:baj`` => INVALID
https://atproto.com/specs/did
Args:
did (str)
Returns:
str:
"""
if not did or not DID_WEB_PATTERN.fullmatch(did):
raise ValueError(f'Invalid did:web: {did}')
host = did.removeprefix('did:web:')
host = urllib.parse.unquote(host)
return f'https://{host}/'
[docs]
def at_uri_to_web_url(uri, handle=None):
"""Converts an ``at://`` URI to a frontend web URL, eg on ``https://bsky.app``.
https://atproto.com/specs/at-uri-scheme
Args:
uri (str): ``at://`` URI
handle: (str): optional user handle. If not provided, defaults to the DID in
uri.
Returns:
str: web URL, or None if the collection isn't in
:const:`COLLECTION_TO_WEB_URL`
Raises:
ValueError: if uri is not a string or doesn't start with ``at://``
"""
if not uri:
return None
if not uri.startswith('at://'):
raise ValueError(f'Expected at:// URI, got {uri}')
parsed = urlparse(uri)
did = parsed.netloc
collection, rkey = (parsed.path.strip('/').split('/') if parsed.path
else ('app.bsky.actor.profile', 'self'))
if template := COLLECTION_TO_WEB_URL.get(collection):
return template.format(id=(handle or did).lstrip('@'), did=did, rkey=rkey)
[docs]
def web_url_to_at_uri(url, handle=None, did=None):
"""Converts a ``https://bsky.app`` or ``https://sprk.so`` URL to an ``at://`` URI.
https://atproto.com/specs/at-uri-scheme
Currently supports profile, post, and feed URLs with DIDs and handles, eg:
* ``https://bsky.app/profile/did:plc:123abc``
* ``https://bsky.app/profile/alice.example/post/456def``
* ``https://bsky.app/profile/bsky.app/feed/mutuals``
* ``https://sprk.so/profile/alice.example``
* ``https://sprk.so/post/did:plc:123abc/456def``
If both ``handle`` and ``did`` are provided, and ``handle`` matches the URL,
the handle in the resulting URI will be replaced with ``did``.
Args:
url (str): ``bsky.app`` or ``sprk.so`` URL
handle (str): Bluesky handle, or None
did (str): Valid DID, or None
Returns:
str: ``at://`` URI, or None
Raises:
ValueError: if ``url`` can't be parsed as a ``bsky.app`` or ``sprk.so``
profile or post URL
"""
if not url:
return None
if match := SPARK_URL_RE.fullmatch(url):
if not (id := match.group('id')):
return f'at://{match.group("did")}/so.sprk.feed.post/{match.group("rkey")}'
if did and handle and id == handle:
id = did
return f'at://{id}/so.sprk.actor.profile/self'
match = BSKY_APP_URL_RE.fullmatch(url)
if not match:
raise ValueError(f"{url} doesn't look like a bsky.app or sprk.so profile or post URL")
id = match.group('id')
assert id
# If a did and handle have been provided explicitly,
# replace the existing handle with the did.
if did and handle and id == handle:
id = did
rkey = match.group('tid')
type = match.group('type')
if type:
collection = BSKY_APP_TYPE_TO_COLLECTION[type]
assert rkey
else:
collection = 'app.bsky.actor.profile'
rkey = 'self'
return f'at://{id}/{collection}/{rkey}'
[docs]
def from_as1_to_strong_ref(obj, client=None, value=False, raise_=False,
validate=True):
"""Converts an AS1 object to an ATProto ``com.atproto.repo.strongRef``.
Uses AS1 ``id`` or ``url`, which should be an ``at://`` URI.
Args:
obj (dict): AS1 object or activity
client (lexrpc.Client): optional; if provided, this will be used to make API
calls to PDSes to fetch and populate the ``cid`` field and resolve handle
to DID.
value (bool): whether to include the record's ``value`` field in the
returned object
raise_ (bool): whether to raise ``ValueError`` if ``client`` is provided and
we can't fetch the object's record and populate ``cid``
validate (bool): if False, and ``obj``'s id isn't an ``at://`` URI or
Bluesky URL, returns a strong ref with that id as ``uri`` and no ``cid``,
which is invalid
Returns:
dict: ATProto ``com.atproto.repo.strongRef`` record
Raises:
ValueError:
"""
if not client:
assert not raise_
id = (obj.get('id') or as1.get_url(obj)) if isinstance(obj, dict) else obj
if match := AT_URI_RE.fullmatch(id):
at_uri = id
else:
at_uri = Bluesky.post_id(id) or ''
match = AT_URI_RE.fullmatch(at_uri)
if not match and id and validate is False:
return {'uri': id}
if not match or not client:
if not match and raise_:
raise ValueError(f"Couldn't parse {id} as ATProto URI or Bluesky URL")
return {
'uri': at_uri,
'cid': '',
}
repo = match['repo']
if not repo.startswith('did:'):
handle = repo
repo = client.com.atproto.identity.resolveHandle(handle=handle)['did']
# only replace first instance of handle in case it's also in collection or rkey
at_uri = at_uri.replace(handle, repo, 1)
try:
record = client.com.atproto.repo.getRecord(
repo=repo, collection=match['collection'], rkey=match['rkey'])
except requests.RequestException as e:
logger.info(e)
record = {}
if not record and raise_:
raise ValueError(f"Couldn't load {at_uri}")
if not value:
record.pop('value', None)
return record
[docs]
def from_as1_datetime(val):
"""Converts an AS1 RFC 3339 datetime string to ATProto ISO 8601.
Bluesky requires full date and time with time zone, recommends UTC with
Z suffix, fractional seconds.
https://atproto.com/specs/lexicon#datetime
Returns now (ie the current time) if the input datetime can't be parsed.
Args:
val (str): RFC 3339 datetime
Returns:
str: ATProto compatible ISO 8601 datetime
"""
dt = util.now()
if val:
try:
if stripped := val.strip():
dt = util.parse_iso8601(stripped)
except (AttributeError, TypeError, ValueError):
logging.debug(f"Couldn't parse {val} as ISO 8601; defaulting to current time")
if dt.tzinfo:
dt = util.as_utc(dt)
# else it's naive, assume it's UTC
assert dt.utcoffset() is None, dt.utcoffset()
return dt.isoformat(sep='T', timespec='milliseconds') + 'Z'
[docs]
def from_as1(obj, out_type=None, blobs=None, aspects=None, client=None,
original_fields_prefix=None, as_embed=False, raise_=False,
dynamic_sensitive_labels=False, multiple=False, domain=None,
validate=None):
"""Converts an AS1 object to a Bluesky object.
Converts to ``record`` types by default, eg ``app.bsky.actor.profile`` or
``app.bsky.feed.post``. Use ``out_type`` to convert to a different type, eg
``app.bsky.actor.defs#profileViewBasic`` or ``app.bsky.feed.defs#feedViewPost``.
The ``objectType`` field is required.
If a string value in an output Bluesky object is longer than its
``maxGraphemes`` or ``maxLength`` in its lexicon, it's truncated with an ``…``
ellipsis character at the end in order to fit.
Some at-uri and strongRef fields within returned records will be left blank, eg
``app.bsky.actor.profile``, ``social.grain.gallery.item``,
``community.blacksky.assembly.statement``, ``community.blacksky.assembly.vote``.
They point to other returned records, but those records don't yet have rkeys.
Callers should fill in those fields once they've generated and assigned rkeys.
TODO: drop ``aspects`` in favor of ``width``/``height`` fields in ``image``
objects themselves
Args:
obj (dict): AS1 object or activity
out_type (str): desired output lexicon ``$type``
blobs (dict): optional mapping from str URL to ``$type: blob`` dict (with
``ref``, ``mimeType``, and ``size``) to use in the returned object. If not
provided, or if this doesn't have an ``image`` or similar URL in the input
object, its output blob will be omitted.
aspects (dict): optional mapping from str URL to int (width, height) tuple.
Used to provide aspect ratio in image/video embeds.
client (Bluesky or lexrpc.Client): optional; if provided, this will be used
to make API calls to PDSes to fetch and populate CIDs for records
referenced by replies, likes, reposts, etc.
original_fields_prefix (str): optional; if provided, stores original object URLs,
post text, and actor profiles (ie before truncation) in custom fields with this
prefix in output records. For example, if this is `foo`, an actor's complete
``summary`` field will be stored in the custom ``fooOriginalDescription``
field, and their (first) `url` will be stored in ``fooOriginalUrl``.
as_embed (bool): whether to render the post as an external embed (ie link
preview) instead of a native post. This happens automatically if
``objectType`` is ``article``
raise_ (bool): whether to raise ``ValueError`` if ``client`` is provided and
we can't fetch an object's record
dynamic_sensitive_labels (bool): if enabled we attempt to determine the bluesky
label based on ``summary``
multiple (bool): if True, always return a list of output records,
including eg ``so.sprk.*``, ``social.grain.*``, and
``community.lexicon.payments.webMonetization``. Default False.
domain (str): optional. A DNS domain for the actor. Only used with
``out_type='site.standard.publication'``, and required then.
validate (bool or None): if True, validates output records against their
lexicons and raises :class:`lexrpc.ValidationError` if they're invalid.
If None, the default, doesn't validate output records, but still requires
valid strong refs. If False, allows generating invalid records. Currently
only allows replies to non-Bluesky objects, with their ids in the reply
refs' ``uri`` and no ``cid``.
Returns:
dict or list: ``app.bsky.*`` object, or list of objects if ``multiple`` is True
Raises:
ValueError: if the object can't be converted, eg if the ``objectType`` or
``verb`` fields are missing or unsupported
"""
if isinstance(client, Bluesky):
client = client.client
activity = obj
inner_obj = as1.get_object(activity)
verb = activity.get('verb') or 'post'
if inner_obj and verb == 'post':
obj = inner_obj
type = as1.object_type(obj)
if not type:
raise ValueError(f"Missing objectType or verb")
obj = copy.deepcopy(obj)
actor = as1.get_object(activity, 'actor')
if blobs is None:
blobs = {}
if aspects is None:
aspects = {}
# validate out_type
if out_type and out_type not in FROM_AS1_TYPES.get(type, []):
raise ValueError(f"{type} {verb} doesn't support out_type {out_type}")
# summary can be HTML; convert to plain text
summary = obj.get('summary') or ''
summary_is_html = (bool(BeautifulSoup(summary, 'html.parser').find())
or HTML_ENTITY_RE.search(summary))
if summary_is_html:
summary = html_to_text(summary, ignore_links=True)
ret = None
rets = []
# for nested from_as1 calls, if necessary
kwargs = {'original_fields_prefix': original_fields_prefix}
# TODO: once we're on Python 3.10, switch this to a match statement!
if type in as1.ACTOR_TYPES:
rets = _from_as1_actor(
obj, out_type=out_type, multiple=multiple, summary=summary,
blobs=blobs, client=client, raise_=raise_, domain=domain,
original_fields_prefix=original_fields_prefix)
elif type == 'link':
# profile link. destination is in value, like in actors' urls field.
# default createdAt to a constant, not now, so that unchanged links convert
# to identical records
# https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/actor/link.json
ret = as1.trim_nulls({
'$type': 'app.bsky.actor.link',
'url': obj.get('value'),
'title': obj.get('displayName'),
'createdAt': from_as1_datetime(obj.get('published') or util.EPOCH_ISO),
})
elif verb in ('post', 'update') and type in POST_TYPES:
rets = _from_as1_post(
obj, multiple=multiple, actor=actor, summary=summary,
out_type=out_type, blobs=blobs, aspects=aspects, client=client,
original_fields_prefix=original_fields_prefix, as_embed=as_embed,
raise_=raise_, dynamic_sensitive_labels=dynamic_sensitive_labels,
validate=validate)
elif type in ('like', 'share') and out_type not in (
'app.bsky.feed.defs#reasonRepost', 'app.bsky.feed.defs#feedViewPost'):
# Spark likes and reposts have the same schemas (not lexicons) as Bluesky's. use
# them if the subject is a Spark record
subject = from_as1_to_strong_ref(inner_obj, client=client, raise_=raise_,
validate=validate)
match = AT_URI_RE.fullmatch(subject.get('uri', ''))
collection = match['collection'] if match else ''
created_at = from_as1_datetime(obj.get('published'))
if out_type == 'social.grain.favorite' or (
type == 'like' and not out_type and collection.startswith('social.grain.')):
# https://tangled.org/grain.social/grain/blob/main/lexicons/social/grain/favorite/favorite.json
# Grain favorites' subjects are at-URIs, not strongRefs
ret = {
'$type': 'social.grain.favorite',
'subject': subject.get('uri'),
'createdAt': created_at,
}
else:
nsid = 'so.sprk' if collection.startswith('so.sprk.') else 'app.bsky'
ret = {
'$type': out_type or f'{nsid}.feed.{"like" if type == "like" else "repost"}',
'subject': subject,
'createdAt': created_at,
}
elif type == 'share':
if out_type == 'app.bsky.feed.defs#reasonRepost':
ret = {
'$type': 'app.bsky.feed.defs#reasonRepost',
'by': from_as1(actor, out_type='app.bsky.actor.defs#profileViewBasic', **kwargs),
'indexedAt': from_as1_datetime(None),
}
elif out_type == 'app.bsky.feed.defs#feedViewPost':
ret = {
'$type': 'app.bsky.feed.defs#feedViewPost',
'post': from_as1(inner_obj, out_type='app.bsky.feed.defs#postView', **kwargs),
'reason': from_as1(obj, out_type='app.bsky.feed.defs#reasonRepost', **kwargs),
}
elif type in RSVP_VERB_TO_STATUS:
# https://github.com/lexicon-community/lexicon/blob/main/community/lexicon/calendar/rsvp.json
ret = {
'$type': 'community.lexicon.calendar.rsvp',
'subject': from_as1_to_strong_ref(inner_obj, client=client, raise_=raise_,
validate=validate),
'status': f'community.lexicon.calendar.rsvp#{RSVP_VERB_TO_STATUS[type]}',
}
elif type in ('follow', 'block'):
if not inner_obj:
raise ValueError('follow activity requires actor and object')
obj_id = inner_obj.get('id')
lexicon = out_type or f'app.bsky.graph.{type}'
if match := AT_URI_RE.fullmatch(obj_id):
if match.group('collection') == 'app.bsky.graph.list':
lexicon = 'app.bsky.graph.listblock'
ret = {
'$type': lexicon,
'subject': obj_id, # DID or list at:// URI
'createdAt': from_as1_datetime(obj.get('published')),
}
if multiple and not out_type and lexicon != 'app.bsky.graph.listblock':
# so.sprk follows and blocks have the same schemas as app.bsky's
rets = [ret, {**ret, '$type': f'so.sprk.graph.{type}'}]
elif type == 'flag':
# use the first object that we can get an ATProto DID or URI/CID for
post_ref = repo_ref = None
for inner in as1.get_objects(activity):
if inner.get('id', '').startswith('did:'):
repo_ref = {
'$type': 'com.atproto.admin.defs#repoRef',
'did': inner['id'],
}
elif not post_ref or not post_ref.get('cid'):
post_ref = {
'$type': 'com.atproto.repo.strongRef',
**from_as1_to_strong_ref(inner, client=client, raise_=raise_),
}
if not (post_ref and post_ref.get('cid')) and not repo_ref:
raise ValueError('flag activity requires at:// or did: object')
ret = {
'$type': 'com.atproto.moderation.createReport#input',
'subject': post_ref or repo_ref,
# https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/moderation/defs.json#
'reasonType': 'com.atproto.moderation.defs#reasonOther',
# https://github.com/bluesky-social/atproto/blob/651d4c2a3447525c68d3bf1b8492bdafb0a88c66/lexicons/com/atproto/moderation/createReport.json#L21
'reason': (obj.get('content') or summary)[:2000],
}
elif type == 'place':
# https://activitystrea.ms/specs/json/schema/activity-schema.html#place
# https://github.com/lexicon-community/lexicon/tree/main/community/lexicon/location
address = obj.get('address')
if isinstance(address, str) and address.strip():
address = {'streetAddress': address.strip()}
lat = obj.get('latitude')
lon = obj.get('longitude')
if lat and lon and out_type != 'community.lexicon.location.address':
ret = {
'$type': 'community.lexicon.location.geo',
'name': obj.get('displayName'),
'latitude': str(lat),
'longitude': str(lon),
}
elif (isinstance(address, dict) and address
and out_type != 'community.lexicon.location.geo'):
ret = {
'$type': 'community.lexicon.location.address',
'name': obj.get('displayName'),
'street': address.get('streetAddress'),
'locality': address.get('locality'),
'region': address.get('region'),
'postalCode': address.get('postalCode'),
# country is required, minLength 2
'country': address.get('country') or '--',
}
else:
raise ValueError(f"place needs latitude and longitude or address to convert to {out_type or 'community.lexicon.location.*'}")
ret = as1.trim_nulls(ret)
elif type == 'event':
ret = _from_as1_event(obj, summary=summary, blobs=blobs, aspects=aspects)
if multiple:
rets = [ret, _from_as1_event_to_post(
obj, actor=actor, blobs=blobs, aspects=aspects, client=client,
original_fields_prefix=original_fields_prefix, raise_=raise_,
dynamic_sensitive_labels=dynamic_sensitive_labels, validate=validate)]
elif type == 'question':
# https://activitystrea.ms/specs/json/schema/activity-schema.html#question
# https://github.com/blacksky-algorithms/assembly.blacksky.community
content = obj.get('content') or ''
if as1.is_html(obj, 'content'):
content = html_to_text(content)
created_at = from_as1_datetime(obj.get('published'))
ret = as1.trim_nulls({
'$type': 'community.blacksky.assembly.conversation',
'topic': content or obj.get('displayName') or '',
'description': summary,
'createdAt': created_at,
}, ignore=('topic',))
# TODO: we don't know the conversation's rkey or CID yet, so the caller has to
# fill in the statements' conversation strongRef after creating it
if multiple:
rets = [ret] + [{
'$type': 'community.blacksky.assembly.statement',
'conversation': from_as1_to_strong_ref(obj, client=client,
validate=validate),
'text': option.get('displayName') or option.get('content') or '',
'createdAt': created_at,
} for option in as1.get_objects(obj, 'options')]
elif type == 'vote':
# a vote in a poll. right now we only handle community.blacksky.assembly.vote
# https://github.com/blacksky-algorithms/assembly.blacksky.community/blob/edge/lexicons/community/blacksky/assembly/vote.json
parent = AT_URI_RE.fullmatch(as1.get_object(obj, 'inReplyTo').get('id') or '')
if not parent or parent['collection'] != 'community.blacksky.assembly.conversation':
raise ValueError("Can only convert votes on community.blacksky.assembly.conversation polls")
# we can't find the statement for this option ourselves, so the caller
# has to fill in the subject strongRef
ret = {
'$type': 'community.blacksky.assembly.vote',
'subject': {'uri': '', 'cid': ''},
'value': -1, # agree (surprisingly yes -1! not a bug)
'createdAt': from_as1_datetime(obj.get('published')),
}
elif type == 'collection':
ret = {
'$type': 'app.bsky.graph.list',
'purpose': 'app.bsky.graph.defs#curatelist',
'name': obj.get('displayName') or obj.get('id'),
'description': summary,
'avatar': blobs.get(util.get_url(obj, 'image')),
'createdAt': from_as1_datetime(obj.get('published')),
}
elif verb == 'add':
ret = {
'$type': 'app.bsky.graph.listitem',
'subject': inner_obj.get('id'),
'list': activity.get('target'),
'createdAt': from_as1_datetime(obj.get('published')),
}
else:
raise ValueError(f'AS1 object has unknown objectType {type} verb {verb}')
# FEP-fffd proxy links
if links := as1.get_rel_links(obj):
for record in rets or [ret]:
if record.get('$type') in META_LINK_TYPES:
record['community.lexicon.meta.links'] = {
'$type': 'community.lexicon.meta.links',
'links': [as1.trim_nulls({
'href': link['value'],
'rel': link['rel'],
'mediaType': link.get('mimeType'),
}) for link in links],
}
# validate against lexicon schema, truncate for character limits, etc
truncated = []
for record in (rets or [ret]):
if nsid := record.get('$type'):
method = nsid.removesuffix('#input')
if method == nsid:
type = 'record'
else:
nsid = method
type = 'input'
record = (LEXRPC_VALIDATE if validate else LEXRPC).validate(nsid, type, record)
truncated.append(record)
return truncated if multiple else truncated[0]
def _from_as1_actor(obj, *, out_type, multiple, summary, blobs, client,
raise_, original_fields_prefix, domain):
"""Converts an AS1 actor to Bluesky and related profile records.
Helper for :func:`from_as1`. See it for args, except:
Args:
obj (dict): AS1 actor object, *not* activity
summary (str): ``obj``'s ``summary``, converted to plain text
Returns:
list of dict: output records, before validation and truncation. The first
one is the primary record.
"""
type = as1.object_type(obj)
rets = []
# avatar and banner. banner is featured image, if available
avatar = util.get_url(obj, 'image')
banner = None
for img in as1.get_objects(obj, 'image'):
url = util.get_url(img)
if as1.object_type(img) == 'featured' and url:
banner = url
break
# extract pinned post from featured collection.
# note that we skip pinned post ids that aren't at:// URIs!
pinned_post = None
if featured := as1.get_object(obj, 'featured'):
if first := (as1.get_id(featured, 'orderedItems')
or as1.get_id(featured, 'items')):
if first.startswith('at://'):
pinned_post = from_as1_to_strong_ref(first, client=client, raise_=raise_)
url = as1.get_url(obj)
id = obj.get('id')
if not url and id:
parsed = util.parse_tag_uri(id)
if parsed:
# This is only really formatted as a URL to keep url_to_did_web below happy
url = f'https://{parsed[0]}'
ret = {
'displayName': obj.get('displayName'),
'description': summary,
'pronouns': obj.get('pronouns'),
'avatar': blobs.get(avatar),
'banner': blobs.get(banner),
'pinnedPost': pinned_post,
'website': url,
}
if original_fields_prefix:
ret.update({
f'{original_fields_prefix}OriginalDescription': obj.get('summary') or '',
f'{original_fields_prefix}OriginalUrl': url or id,
})
if not out_type or out_type in ATP_PROFILE_TYPES:
# TODO: Spark pinnedPost. needs to be a so.sprk.feed.post
if out_type == 'so.sprk.actor.profile':
ret['pinnedPost'] = ret['pronouns'] = None
ret = as1.trim_nulls({**ret, '$type': out_type or 'app.bsky.actor.profile'})
elif out_type == 'site.standard.publication':
if not domain:
raise ValueError("No domain, can't convert to site.standard.publication")
ret = as1.trim_nulls({
'$type': 'site.standard.publication',
'url': f'https://{domain}',
'name': obj.get('displayName') or '',
'description': summary,
'icon': blobs.get(avatar),
}, ignore=('name',))
else:
did_web = ''
if id and id.startswith('did:web:'):
did_web = id
else:
try:
did_web = url_to_did_web(url)
except ValueError as e:
logger.info(f"Couldn't generate did:web: {e}")
# handles must be hostnames
# https://atproto.com/specs/handle
username = obj.get('username')
parsed = urlparse(url)
domain = parsed.netloc
did_web_bare = did_web.removeprefix('did:web:')
handle = (username if username and HANDLE_RE.fullmatch(username)
else did_web_bare if ':' not in did_web_bare
else domain if domain
else '')
ret.update({
'$type': out_type,
# TODO: more specific than domain, many users will be on shared domains
'did': id if id and id.startswith('did:') else did_web,
'handle': handle,
'avatar': avatar,
'banner': banner,
# these collections aren't not in AS1, they're borrowed from ActivityPub:
# https://www.w3.org/TR/activitypub/#followers
'followersCount': obj.get('followers', {}).get('totalItems'),
'followsCount': obj.get('following', {}).get('totalItems'),
})
# WARNING: this includes a few fields that aren't in #profileViewBasic, eg
# description, followersCount, followsCount
# https://atproto.com/specs/lexicon#authority-and-control
ret = as1.trim_nulls(ret, ignore=('did', 'handle'))
# add bot label for automated account objectTypes
if type in as1.BOT_TYPES:
bsky_type = ret.get('$type')
if bsky_type in ATP_PROFILE_TYPES:
ret['labels'] = {
'$type': 'com.atproto.label.defs#selfLabels',
'values': [{'val': BOT_LABEL}],
}
elif bsky_type.startswith('app.bsky.actor.defs#'):
ret['labels'] = [{'val': BOT_LABEL}]
if ret['$type'] == 'app.bsky.actor.profile':
rets = [ret]
# Spark, same as Bluesky's except for pinnedPost and pronouns
# https://github.com/sprksocial/server/blob/main/lexicons/so/sprk/actor/profile.json
if multiple:
rets.append(as1.trim_nulls({
**ret,
'$type': 'so.sprk.actor.profile',
'pinnedPost': None,
'pronouns': None,
}))
# Grain, also similar to Bluesky's, but even more minimal
# https://tangled.org/grain.social/grain/blob/main/lexicons/social/grain/actor/profile.json
rets.append({**ret, '$type': 'social.grain.actor.profile'})
# profile links. we don't know the link records' rkeys or CIDs yet, so the
# caller has to fill in the profile's links strongRefs
# https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/actor/link.json
links = util.get_list(obj, 'urls') or util.get_list(obj, 'url')
max_links = LEXRPC.defs['app.bsky.actor.profile']['record']['properties']['links']['maxLength']
for link in links[:max_links]:
if not isinstance(link, dict):
link = {'value': link}
# FEP-fffd proxy links are about the account's identity elsewhere, not
# links the user chose to show, and their URLs, eg AP actor ids, often
# aren't human-browsable
if link.get('rel') in as1.PROXY_LINK_RELS:
continue
url = link.get('value')
if not util.is_web(url):
continue
# skip invalid links, eg URLs with spaces, so that they don't make the
# whole profile commit fail
try:
record = from_as1({**link, 'objectType': 'link'},
out_type='app.bsky.actor.link', validate=True)
except ValidationError as e:
logger.info(f'Skipping invalid profile link {url} : {e}')
continue
ret.setdefault('links', []).append({'uri': '', 'cid': ''})
rets.append(record)
# Web Monetization
# https://github.com/lexicon-community/lexicon/tree/main/community/lexicon/payments
if wallet := obj.get('monetization'):
if wallet.startswith('$'):
wallet = wallet.replace('$', 'https://', 1)
rets.append({
'$type': 'community.lexicon.payments.webMonetization',
'address': wallet,
})
# Grain profiles only have displayName, description, avatar, createdAt
for profile in rets or [ret]:
if profile['$type'] == 'social.grain.actor.profile':
for field in 'banner', 'labels', 'pinnedPost', 'pronouns', 'website':
profile.pop(field, None)
return rets or [ret]
def _from_as1_post(obj, *, out_type, multiple, actor, summary, blobs, aspects,
client, original_fields_prefix, as_embed, raise_,
dynamic_sensitive_labels, validate):
"""Converts an AS1 post, eg note or article, to Bluesky and related records.
Helper for :func:`from_as1`. Args are the same as there, except:
Args:
obj (dict): AS1 object, *not* activity
summary (str): ``obj``'s ``summary``, converted to plain text
Returns:
list of dict: output records, before validation and truncation. The first
one is the primary record.
"""
type = as1.object_type(obj)
# for nested from_as1 calls, if necessary
kwargs = {'original_fields_prefix': original_fields_prefix}
# images => embeds
images_embed = images_record_embed = None
spark_images = []
if images := as1.get_objects(obj, 'image'):
images_embed_items = []
use_gallery = len(images) > 4
if use_gallery:
images_embed = {
'$type': 'app.bsky.embed.gallery#view',
'items': images_embed_items,
}
else:
images_embed = {
'$type': 'app.bsky.embed.images#view',
'images': images_embed_items,
}
for img in images:
url = img.get('url') or img.get('id')
alt = img.get('displayName') or ''
view_item = {
'$type': ('app.bsky.embed.gallery#viewImage' if use_gallery
else 'app.bsky.embed.images#viewImage'),
('thumbnail' if use_gallery else 'thumb'): url,
'fullsize': url,
'alt': alt,
}
if use_gallery:
view_item['aspectRatio'] = DEFAULT_ASPECT_RATIO
images_embed_items.append(view_item)
if blob := blobs.get(url):
if not images_record_embed:
images_record_items = []
if use_gallery:
images_record_embed = {
'$type': 'app.bsky.embed.gallery',
'items': images_record_items,
}
else:
images_record_embed = {
'$type': 'app.bsky.embed.images',
'images': images_record_items,
}
image_record = {
'$type': ('app.bsky.embed.gallery#image' if use_gallery
else 'app.bsky.embed.images#image'),
'image': blob,
'alt': alt,
}
spark_image = {
'image': blob,
'alt': alt,
}
if aspect := aspects.get(url) or as1.aspect_ratio(img):
image_record['aspectRatio'] = spark_image['aspectRatio'] = {
'width': aspect[0],
'height': aspect[1]
}
elif use_gallery:
image_record['aspectRatio'] = DEFAULT_ASPECT_RATIO
images_record_items.append(image_record)
spark_images.append(spark_image)
# first video => embed
attachments = util.get_list(obj, 'attachments')
has_audio_attachment = any(as1.object_type(att) == 'audio' for att in attachments)
video = video_embed = video_record_embed = None
video_missing_blob = False
for att in attachments:
url = util.get_url(att, 'stream')
blob = blobs.get(url)
if url and blob and as1.object_type(att) == 'video':
video = url
alt = att.get('displayName') or ''
video_embed = {
'$type': 'app.bsky.embed.video#view',
'cid': blob_cid(blob),
'playlist': '?',
'alt': alt,
}
video_record_embed = {
'$type': 'app.bsky.embed.video',
'video': blob,
'alt': alt,
}
stream = as1.get_object(att, 'stream')
if aspect := aspects.get(url) or as1.aspect_ratio(stream):
video_record_embed['aspectRatio'] = {
'width': aspect[0],
'height': aspect[1]
}
break
elif as1.object_type(att) == 'video':
video_missing_blob = True
# by default, original post link goes into an external embed. Bluesky can't
# do either images or video along with an external embed in the same post
# though, https://github.com/bluesky-social/atproto/discussions/2575 , so if
# the post has those, put the original post link at the end of the text
# instead, after truncating.
original_post_embed_name = original_post_text_suffix = None
include_link = None
url = as1.get_url(obj) or obj.get('id')
if url:
snippet = f'Original post on {util.domain_from_link(url)}'
original_post_embed_name = snippet
original_post_text_suffix = f'[{snippet}]'
if has_audio_attachment:
original_post_embed_name = '[Audio] ' + original_post_embed_name
original_post_text_suffix = '[Audio] ' + original_post_text_suffix
elif video_missing_blob:
original_post_embed_name = '[Video] ' + original_post_embed_name
original_post_text_suffix = '[Video] ' + original_post_text_suffix
original_post_text_suffix = '\n\n' + original_post_text_suffix
if images or video:
include_link = INCLUDE_LINK if has_audio_attachment or video_missing_blob else INCLUDE_IF_TRUNCATED
else:
include_link = OMIT_LINK # link will be in the external embed, not text
# convert text from HTML and truncate
orig_content = obj.get('content', '')
as1.convert_html_content_to_text(obj)
as1.expand_tags(obj)
tags = util.get_list(obj, 'tags')
# handle summary. for articles, use instead of content. for notes, assume
# it's a fediverse-style content warnings, add above content.
# https://github.com/snarfed/bridgy-fed/issues/1001
full_text = content = obj.get('content') or ''
index_offset = 0
preview_record = None
if type == 'article' or as_embed:
if (preview := obj.get('preview')) and as1.object_type(preview) == 'note':
# link preview: https://fediverse.codeberg.page/fep/fep/8967/
# we'll take text and facets from this below
preview_record = from_as1(preview, **kwargs)
else:
full_text = summary
tags = [] # tags are presumably in content, not summary
elif summary:
prefix = f'[{summary}]\n\n'
full_text = prefix + full_text
index_offset = len(prefix)
# attachments to embed(s), including quoted posts
record_embed = record_record_embed = external_embed = external_record_embed = None
# convert Bluesky post link at end of content to a quote
attachment_urls = [att['url'] for att in attachments if 'url' in att]
text_end = len(full_text)
for tag in tags:
# check that the link is at the end and the text is the url
if (as1.object_type(tag) != 'link' or tag.get('url') != tag.get('displayName') or
tag.get('startIndex', 0) + tag.get('length', 0) + index_offset != text_end):
continue
# check the link is to a bluesky post and not already in attachments
if ((tag['url'].startswith('at://')
or ((match := BSKY_APP_URL_RE.fullmatch(tag['url']))
and match.group('type') == 'post'))
and not tag['url'] in attachment_urls):
start_index = tag['startIndex'] + index_offset
# check link is on its own line
if start_index > 0 and full_text[start_index - 1] != '\n':
continue
# create attachment
attachments.append({
'objectType' : 'note',
'url' : tag['url']
})
# remove link
full_text = full_text[:start_index - 1]
for att in attachments:
att_id = att.get('id') or ''
att_url = as1.get_url(att) or ''
if not (as1.object_type(att) in ('article', 'link', 'note')
and (att_url or att_id)):
continue
if (att_id.startswith('at://') or att_id.startswith(Bluesky.BASE_URL) or
att_url.startswith('at://') or att_url.startswith(Bluesky.BASE_URL)):
# quoted Bluesky post
embed = from_as1(att, **kwargs).get('post') or {}
embed['value'] = embed.pop('record', None)
record_embed = {
'$type': f'app.bsky.embed.record#view',
'record': {
**embed,
'$type': f'app.bsky.embed.record#viewRecord',
# override these so that trim_nulls below will remove them
'likeCount': None,
'replyCount': None,
'repostCount': None,
},
}
record_record_embed = {
'$type': f'app.bsky.embed.record',
'record': from_as1_to_strong_ref(att, client=client, raise_=raise_),
}
full_text = QUOTE_RE_SUFFIX.sub('', full_text)
else:
# external link
external_record_embed = to_external_embed(att, blobs=blobs)
external_embed = {
'$type': f'app.bsky.embed.external#view',
'external': {
**external_record_embed['external'],
'$type': f'app.bsky.embed.external#viewExternal',
'thumb': util.get_first(att, 'image'),
},
}
# language(s)
# (we steal contentMap from AS2, it's not officially part of AS1)
langs = [lang for lang, lang_content in obj.get('contentMap', {}).items()
if LANG_RE.fullmatch(lang) and lang_content == orig_content]
# truncate text. if we're including a suffix, ie original post link, link
# that with a facet
is_dm = as1.is_dm(obj, actor=actor)
text = Bluesky('unused').truncate(
full_text, original_post_text_suffix, include_link=include_link,
punctuation=('', ''), type='dm' if is_dm else type, weights=False,
lang=langs[0] if langs else None)
truncated = text != full_text
facets, standalone_tags = _from_as1_facets(
tags, obj=obj, full_text=full_text, text=text, truncated=truncated,
index_offset=index_offset, url=url,
original_post_text_suffix=original_post_text_suffix, client=client)
# if we truncated this post's text, override external embed with link to
# original post. (if there are images, we added a link in the text instead,
# and this won't get used.)
if (truncated or has_audio_attachment or video_missing_blob) and url:
external_record_embed = {
'$type': f'app.bsky.embed.external',
'external': {
'$type': f'app.bsky.embed.external#external',
'uri': url,
'title': original_post_embed_name,
'description': '',
},
}
external_embed = {
'$type': f'app.bsky.embed.external#view',
'external': {
**external_record_embed['external'],
'$type': f'app.bsky.embed.external#viewExternal',
'thumb': (images[0].get('url') or images[0].get('id')) if images else None,
},
}
# populate embeds
media_embed = video_embed or images_embed or external_embed
if record_embed and media_embed:
embed = {
'$type': 'app.bsky.embed.recordWithMedia#view',
'record': record_embed,
'media': media_embed,
}
else:
embed = record_embed or media_embed
media_record_embed = video_record_embed or images_record_embed or external_record_embed
if is_dm:
# chat.bsky.convo.defs#messageInput only allows record embeds
record_embed = record_record_embed
embed = record_embed
elif record_record_embed and media_record_embed:
record_embed = {
'$type': 'app.bsky.embed.recordWithMedia',
'record': record_record_embed,
'media' : media_record_embed
}
else:
record_embed = record_record_embed or media_record_embed
# in reply to
reply = None
parent_record = {}
in_reply_to = Bluesky.base_object(obj, bluesky_only=validate is not False)
if in_reply_to and not is_dm:
parent_ref = from_as1_to_strong_ref(in_reply_to, client=client, value=True,
raise_=raise_, validate=validate)
parent_record = parent_ref.pop('value', {})
root_ref = parent_record.get('reply', {}).get('root') or parent_ref
reply = {
'$type': 'app.bsky.feed.post#replyRef',
'root': root_ref,
'parent': parent_ref,
}
# convert AS1 sensitive to "nudity" label
# https://github.com/snarfed/atproto/blob/f2f8de63b333448d87c364578e023ddbb63b8b25/lexicons/com/atproto/label/defs.json#L139-L154
# https://swicg.github.io/miscellany/#sensitive
# https://docs.joinmastodon.org/user/posting/#cw
labels = None
if obj.get('sensitive'):
label = SENSITIVE_LABEL_DEFAULT
if dynamic_sensitive_labels and summary:
summary_lower = summary.lower()
for bluesky_label, keywords in AS1_TO_BLUESKY_LABEL_MAP.items():
if any(s in summary_lower for s in keywords):
label = bluesky_label
labels = {
'$type' : 'com.atproto.label.defs#selfLabels',
'values' : [{'val' : label}],
}
ret = {
'$type': 'chat.bsky.convo.defs#messageInput' if is_dm else 'app.bsky.feed.post',
'text': text,
'createdAt': from_as1_datetime(obj.get('published')),
'embed': record_embed,
'facets': facets,
'reply': reply,
'langs': langs,
'labels': labels,
'tags': sorted(standalone_tags),
}
if preview_record and preview_record['text']:
ret.update({
'text': preview_record['text'],
'facets': preview_record.get('facets'),
'langs': preview_record.get('langs'),
'tags': preview_record.get('tags'),
})
if as_embed or (type == 'article' and url):
ret['embed'] = to_external_embed(obj, description=content or summary,
blobs=blobs)
if images_record_embed:
imgs = images_record_embed.get('images') or images_record_embed.get('items')
ret['embed']['external']['thumb'] = imgs[0]['image']
if original_fields_prefix:
ret.update({
f'{original_fields_prefix}OriginalText': orig_content,
f'{original_fields_prefix}OriginalUrl': url,
})
ret = as1.trim_nulls(ret, ignore=('alt', 'createdAt', 'cid', 'description',
'text', 'title', 'uri'))
spark_facets = [{
**facet,
'$type': 'so.sprk.richtext.facet',
'features': [{
**feat,
'$type': feat['$type'].replace('app.bsky.', 'so.sprk.'),
} for feat in facet['features']],
} for facet in ret.get('facets', [])]
# Spark reply instead, if the parent is a Spark record
spark_parent = (reply
and (parent := AT_URI_RE.fullmatch(reply['parent'].get('uri', '')))
and parent['collection'].startswith('so.sprk.'))
if out_type == 'so.sprk.feed.reply' or (spark_parent and not out_type):
if not reply:
raise ValueError("Not a reply, can't convert to so.sprk.feed.reply")
ret = _from_as1_to_spark_reply(ret, reply=reply, facets=spark_facets,
images=spark_images)
# Grain comment instead, if the parent is a Grain record
parent_uri = reply['parent'].get('uri', '') if reply else ''
grain_parent = ((parsed := AT_URI_RE.fullmatch(parent_uri))
and parsed['collection'].startswith('social.grain.'))
if out_type == 'social.grain.comment' or (grain_parent and not out_type):
if not reply:
raise ValueError("Not a reply, can't convert to social.grain.comment")
ret = _from_as1_to_grain_comment(ret, parent=parent_record)
# also Spark post, if possible
rets = []
if multiple or out_type == 'so.sprk.feed.post':
if (ret['$type'] == 'app.bsky.feed.post' and not reply
and type != 'article' and not as_embed
and (spark := _from_as1_to_spark_post(
ret, images_as1=images, images=spark_images, attachments=attachments,
video_record_embed=video_record_embed, facets=spark_facets))):
if multiple:
rets = [ret, spark]
else:
ret = spark
elif out_type == 'so.sprk.feed.post':
raise ValueError('Spark posts need just images or a single video, all with blobs, and no replies, quotes, links, or DMs')
# also Grain gallery, photos, and gallery items, if possible
if multiple or out_type == 'social.grain.gallery':
if (ret['$type'] == 'app.bsky.feed.post' and not reply
and type != 'article' and not as_embed
and (grain := _from_as1_to_grain_gallery(
ret, obj=obj, blobs=blobs, aspects=aspects))):
if multiple:
rets = (rets or [ret]) + grain
else:
ret = grain[0]
elif out_type == 'social.grain.gallery':
raise ValueError('Grain galleries need just images, all with blobs, and no replies, quotes, links, video, or DMs')
# also site.standard.document for articles
if out_type == 'site.standard.document' and not url:
raise ValueError("No url or id, can't convert to site.standard.document")
if (type == 'article' and url
and (multiple or out_type == 'site.standard.document')):
doc = _from_as1_to_standard_document(obj, url=url, summary=summary,
content=content,
images_record_embed=images_record_embed)
if multiple:
rets = [ret, doc]
else:
ret = doc
if out_type in ('app.bsky.feed.defs#feedViewPost',
'app.bsky.feed.defs#postView'):
# author
author = as1.get_object(obj, 'author')
author.setdefault('objectType', 'person')
author = from_as1(author, out_type='app.bsky.actor.defs#profileViewBasic',
**kwargs)
ret = as1.trim_nulls({
'$type': 'app.bsky.feed.defs#postView',
'uri': obj.get('id') or url or '',
'cid': '',
'record': ret,
'author': author,
'embed': embed,
'replyCount': 0,
'repostCount': 0,
'likeCount': 0,
'indexedAt': from_as1_datetime(None),
}, ignore=('author', 'createdAt', 'cid', 'description', 'indexedAt',
'record', 'text', 'title', 'uri'))
if out_type == 'app.bsky.feed.defs#feedViewPost':
ret = {
'$type': out_type,
'post': ret,
}
return rets or [ret]
def _from_as1_facets(tags, *, obj, full_text, text, truncated, index_offset, url,
original_post_text_suffix, client):
"""Converts AS1 tags to Bluesky facets and standalone hashtags.
Args:
tags (sequence of dict): AS1 tags
obj (dict): AS1 object
full_text (str): post text, before truncation
text (str): post text, after truncation
truncated (bool): whether ``text`` was truncated
index_offset (int): offset of ``obj``'s ``content`` in ``full_text``, eg
after a content warning prefix
url (str): original post URL, if any
original_post_text_suffix (str): original post link appended to
``text``, if any
client: see :func:`from_as1`
Returns:
(list of dict, set of str) tuple: ``app.bsky.richtext.facet`` objects, and
hashtags that aren't in the (truncated) text
"""
if truncated:
text_byte_end = len(text.split(ELLIPSIS, maxsplit=1)[0].encode())
else:
text_byte_end = len(text.encode())
facets = []
standalone_tags = set()
if (truncated and original_post_text_suffix
and text.endswith(original_post_text_suffix)):
facets.append({
'$type': 'app.bsky.richtext.facet',
'features': [{
'$type': 'app.bsky.richtext.facet#link',
'uri': url,
}],
'index': {
'byteStart': len(text.removesuffix(original_post_text_suffix).encode()),
'byteEnd': len(text.encode()),
}
})
# convert tags to facets
hashtag_facets = set() # contains string displayNames, lower cased
for tag in tags:
name = tag.get('displayName', '').strip().lstrip('@#')
tag_type = util.get_first(tag, 'objectType')
if name and not tag_type:
tag_type = 'hashtag'
tag_url = tag.get('url') or ''
if not name and not tag_url:
continue
facet = {
'$type': 'app.bsky.richtext.facet',
}
try:
start = int(tag['startIndex']) + index_offset
if start and as1.is_html(obj, 'content'):
raise NotImplementedError('HTML content is not supported with index tags')
end = start + int(tag['length'])
facet['index'] = {
# convert indices from Unicode chars to UTF-8 encoded bytes
# https://github.com/snarfed/atproto/blob/5b0c2d7dd533711c17202cd61c0e101ef3a81971/lexicons/app/bsky/richtext/facet.json#L34
'byteStart': len(full_text[:start].encode()),
'byteEnd': len(full_text[:end].encode()),
}
except (KeyError, ValueError, IndexError, TypeError):
pass
if tag_type == 'hashtag':
max_graphemes = LEXRPC.defs['app.bsky.feed.post']['record']['properties']['tags']['items']['maxGraphemes']
if len(name) >= max_graphemes:
logger.warning(f'Hashtag "{name}" longer than maxGraphemes {max_graphemes}')
continue
facet['features'] = [{
'$type': 'app.bsky.richtext.facet#tag',
'tag': name,
}]
elif tag_type == 'mention':
# extract and resolve DID
if tag_url.startswith('did:'):
user = tag_url
elif match := AT_URI_RE.fullmatch(tag_url):
user = match.group('repo')
elif match := BSKY_APP_URL_RE.fullmatch(tag_url):
user = match.group('id')
else:
user = name.lstrip('@')
did = None
if user.startswith('did:'):
did = user
elif client and HANDLE_RE.fullmatch(user):
try:
did = client.com.atproto.identity.resolveHandle(handle=user)['did']
except BaseException as e:
code, _ = util.interpret_http_exception(e)
if not code:
raise
if did:
facet['features'] = [{
'$type': 'app.bsky.richtext.facet#mention',
'did': did,
}]
if not facet.get('features') and tag_url:
if util.DOMAIN_RE.fullmatch(tag_url):
tag_url = f'https://{tag_url}/'
if util.is_url(tag_url):
facet['features'] = [{
'$type': 'app.bsky.richtext.facet#link',
'uri': tag_url,
}]
# skip or trim this facet if it's off the end of content that got truncated
index = facet.get('index')
if not index or index.get('byteStart', 0) >= text_byte_end:
max_length = LEXRPC.defs['app.bsky.feed.post']['record']['properties']['tags']['maxLength']
if tag_type == 'hashtag' and name.lower() not in hashtag_facets:
if len(standalone_tags) >= max_length:
logger.warning(f'More than {max_length} standalone hashtags, omitting "{name}"')
else:
standalone_tags.add(name)
continue
if index.get('byteEnd', 0) > text_byte_end:
index['byteEnd'] = text_byte_end
if facet.get('features') and facet not in facets:
facets.append(facet)
if tag_type == 'hashtag':
hashtag_facets.add(name.lower())
standalone_tags.discard(name.lower())
return facets, standalone_tags
def _from_as1_to_spark_post(post, *, images_as1, images, attachments,
video_record_embed, facets):
"""Generates a Spark ``so.sprk.feed.post`` for a post with images or video.
Spark posts only have either images or a single video, so only generates one
if that's all this post has, ie no quote, link, or other media.
Args:
post (dict): ``app.bsky.feed.post`` record, not a reply
images_as1 (sequence of dict): AS1 image objects
images (list of dict): ``so.sprk.media.image`` objects
attachments (sequence of dict): AS1 attachment objects
video_record_embed (dict): ``app.bsky.embed.video``, or None
facets (list of dict): ``so.sprk.richtext.facet`` objects
Returns:
dict: ``so.sprk.feed.post`` record, or None if this post's media can't be
represented in one
"""
# https://github.com/sprksocial/server/blob/main/lexicons/so/sprk/feed/post.json
media = None
max_images = LEXRPC.defs['so.sprk.media.images']['properties']['images']['maxLength']
# TODO: handle too many images, and images without blobs, consistently. right
# now we include all images with blobs in Bluesky posts, even if that's more
# than app.bsky.embed.gallery's maxLength, but skip Spark posts entirely.
#
# as2.to_as1 etc duplicate images into attachments, so ignore those
image_urls = [img.get('url') or img.get('id') for img in images_as1]
other_atts = [att for att in attachments if util.get_url(att) not in image_urls]
if video_record_embed and len(other_atts) == 1 and not images_as1:
media = {**video_record_embed, '$type': 'so.sprk.media.video'}
elif (images and not other_atts
and len(images_as1) == len(images) <= max_images):
media = {
'$type': 'so.sprk.media.images',
'images': images,
}
if media:
return as1.trim_nulls({
**post,
'$type': 'so.sprk.feed.post',
'text': None,
'facets': None,
'embed': None,
'caption': {
'text': post['text'],
'facets': facets,
},
'media': media,
}, ignore=('alt', 'createdAt'))
def _from_as1_to_spark_reply(post, *, reply, facets, images):
"""Converts a Bluesky reply to a Spark ``so.sprk.feed.reply``.
Spark replies only support text and one image, so this drops anything else.
Args:
post (dict): ``app.bsky.feed.post`` or compatible record
(eg ``chat.bsky.convo.defs#messageInput``)
reply (dict): ``app.bsky.feed.post#replyRef``
facets (list of dict): ``so.sprk.richtext.facet`` objects
images (list of dict): ``so.sprk.media.image`` objects
Returns:
dict: ``so.sprk.feed.reply`` record
"""
# https://github.com/sprksocial/server/blob/main/lexicons/so/sprk/feed/reply.json
# log anything we're dropping
if tags := post.get('tags'):
logger.info(f"so.sprk.feed.reply doesn't support tags {tags} ; dropping")
if len(images) > 1:
logger.info(f"so.sprk.feed.reply doesn't support multiple images; dropping")
embed_type = post.get('embed', {}).get('$type')
if embed_type not in (None, 'app.bsky.embed.images', 'app.bsky.embed.gallery'):
logger.info(f"so.sprk.feed.reply doesn't support {embed_type} ; dropping")
ret = as1.trim_nulls({
**post,
'$type': 'so.sprk.feed.reply',
'reply': {**reply, '$type': 'so.sprk.feed.reply#replyRef'},
'facets': facets,
'embed': None,
'tags': None,
'media': None
}, ignore=('alt', 'createdAt', 'cid', 'text', 'uri'))
if images:
ret['media'] = {**images[0], '$type': 'so.sprk.media.image'}
return ret
def _from_as1_to_grain_gallery(post, *, obj, blobs, aspects):
"""Generates Grain records for a post with images.
Grain galleries only have images, so only generates them if that's all this
post has, ie no quote, link, video, or other media.
Doesn't populate the ``social.grain.gallery.item`` records' ``gallery`` and
``item`` at-URIs, since we don't know the other records' rkeys yet. The caller
should populate them. Importantly, each item's ``position`` is the index of its
``social.grain.photo`` in the returned photos.
Args:
post (dict): ``app.bsky.feed.post`` record, not a reply
obj (dict): AS1 object
blobs (dict): see :func:`from_as1`
aspects (dict): see :func:`from_as1`
Returns:
list of dict: ``social.grain.gallery`` record, then
``social.grain.photo`` records, then ``social.grain.gallery.item``
records, or None if this post's media can't be represented in them
"""
# https://tangled.org/grain.social/grain/tree/main/lexicons/social/grain
#
# as2.to_as1 etc duplicate images into attachments, so ignore those
images = as1.get_objects(obj, 'image')
image_urls = [img.get('url') or img.get('id') for img in images]
other_atts = [att for att in util.get_list(obj, 'attachments')
if util.get_url(att) not in image_urls]
if not images or other_atts or not all(blobs.get(url) for url in image_urls):
return None
created_at = post['createdAt']
gallery = as1.trim_nulls({
**post,
'$type': 'social.grain.gallery',
'title': obj.get('displayName') or '',
'description': post['text'],
'text': None,
'embed': None,
'langs': None,
'tags': None,
}, ignore=('createdAt', 'title'))
photos = []
for img, url in zip(images, image_urls):
aspect = aspects.get(url) or as1.aspect_ratio(img)
photos.append({
'$type': 'social.grain.photo',
'photo': blobs[url],
'alt': img.get('displayName') or '',
'aspectRatio': ({'width': aspect[0], 'height': aspect[1]} if aspect
else DEFAULT_ASPECT_RATIO),
'createdAt': created_at,
})
items = [{
'$type': 'social.grain.gallery.item',
'position': i,
'createdAt': created_at,
} for i in range(len(photos))]
return [gallery] + photos + items
def _from_as1_to_grain_comment(post, *, parent):
"""Converts a Bluesky reply to a Grain ``social.grain.comment``.
Grain comments only support text and facets, so this drops anything else.
Args:
post (dict): ``app.bsky.feed.post`` reply record. Its parent should be a
``social.grain.gallery`` or ``social.grain.comment``.
parent (dict): parent record, if available
Returns:
dict: ``social.grain.comment`` record
Raises:
ValueError: if the parent isn't a Grain gallery or comment, or it's a
comment and we don't have its record, so we don't know its gallery
"""
# https://tangled.org/grain.social/grain/blob/main/lexicons/social/grain/comment/comment.json
parent_uri = post['reply']['parent']['uri']
collection = AT_URI_RE.fullmatch(parent_uri)['collection']
if collection == 'social.grain.gallery':
subject = parent_uri
reply_to = None
elif collection == 'social.grain.comment':
subject = parent.get('subject')
if not subject:
raise ValueError(f"Couldn't determine gallery for Grain comment {parent_uri}")
reply_to = parent_uri
else:
raise ValueError(f"Can't reply to {collection} with social.grain.comment")
# log anything we're dropping
for field in 'embed', 'tags', 'langs', 'labels':
if val := post.get(field):
logger.info(f"social.grain.comment doesn't support {field} {val} ; dropping")
return as1.trim_nulls({
**post,
'$type': 'social.grain.comment',
'subject': subject,
'replyTo': reply_to,
'reply': None,
'embed': None,
'tags': None,
'langs': None,
'labels': None,
}, ignore=('createdAt', 'text'))
def _from_as1_to_standard_document(obj, *, url, summary, content,
images_record_embed):
"""Generates a ``site.standard.document`` for an AS1 article.
Args:
obj (dict): AS1 article object
url (str): article URL
summary (str): article summary, converted to plain text
content (str): article content, converted to plain text
images_record_embed (dict): ``app.bsky.embed.images`` or
``app.bsky.embed.gallery``, or None
Returns:
dict: ``site.standard.document`` record
"""
url_parts = urlparse(url)
doc = as1.trim_nulls({
'$type': 'site.standard.document',
'site': urlunparse(url_parts[:2] + ('',) * 4),
'path': urlunparse(('', '') + url_parts[2:]),
'title': obj.get('displayName') or '',
'description': summary,
'textContent': content,
'tags': util.uniquify(
tag['displayName'].removeprefix('#')
for tag in util.get_list(obj, 'tags') if tag.get('displayName')),
'publishedAt': from_as1_datetime(obj.get('published')),
}, ignore=('title',))
if updated := obj.get('updated'):
doc['updatedAt'] = from_as1_datetime(updated)
if images_record_embed:
imgs = images_record_embed.get('images') or images_record_embed.get('items')
doc['coverImage'] = imgs[0]['image'] # blob
return doc
def _from_as1_event(obj, *, summary, blobs, aspects):
"""Converts an AS1 event to a ``community.lexicon.calendar.event`` record.
Helper for :func:`from_as1`.
Args:
obj (dict): AS1 event object
summary (str): ``obj``'s ``summary``, converted to plain text
blobs (dict): see :func:`from_as1`
aspects (dict): see :func:`from_as1`
Returns:
dict: ``community.lexicon.calendar.event`` record
"""
# https://activitystrea.ms/specs/json/schema/activity-schema.html#event
# https://github.com/lexicon-community/lexicon/tree/main/community/lexicon/calendar
content = obj.get('content') or ''
if as1.is_html(obj, 'content'):
content = html_to_text(content)
ret = {
'$type': 'community.lexicon.calendar.event',
'name': obj.get('displayName') or '',
'description': content or summary,
'createdAt': from_as1_datetime(obj.get('published')),
'uris': [{'uri': url} for url in as1.object_urls(obj)],
}
for as1_field, bsky_field in ('startTime', 'startsAt'), ('endTime', 'endsAt'):
if val := obj.get(as1_field):
ret[bsky_field] = from_as1_datetime(val)
locs = as1.get_objects(obj, 'location')
for loc in locs:
# emit every location type we can, since apps differ in which they show
converted = []
for loc_type in ('community.lexicon.location.address',
'community.lexicon.location.geo'):
try:
converted.append(
from_as1({**loc, 'objectType': 'place'}, out_type=loc_type))
except ValueError:
pass
if not converted and (loc_url := as1.get_url(loc)):
converted = [{
'$type': 'community.lexicon.calendar.event#uri',
'name': loc.get('displayName'),
'uri': loc_url,
}]
if converted:
ret.setdefault('locations', []).extend(converted)
else:
logger.info(f"Dropping location without coordinates, address, or URL: {loc}")
# isOnline is Mobilizon's, passed through by as2.to_as1
online = obj.get('isOnline')
if mode := ('hybrid' if online and locs
else 'virtual' if online
else 'inperson' if locs
else None):
ret['mode'] = f'community.lexicon.calendar.event#{mode}'
# media isn't in the lexicon yet, but Smoke Signal, atmo.rsvp, etc use it
# https://discourse.atmosphere.community/t/kicking-off-a-dedicated-space-for-discussion-for-calendar-events-rsvp/684/5
for img in as1.get_objects(obj, 'image'):
url = util.get_url(img)
if blob := blobs.get(url):
media = {
'role': 'header' if as1.object_type(img) == 'featured' else 'thumbnail',
'content': blob,
'alt': img.get('displayName'),
}
if aspect := aspects.get(url) or as1.aspect_ratio(img):
media['aspect_ratio'] = {'width': aspect[0], 'height': aspect[1]}
ret.setdefault('media', []).append(media)
return as1.trim_nulls(ret, ignore=('name',))
def _from_as1_event_to_post(obj, **kwargs):
"""Generates an ``app.bsky.feed.post`` for an AS1 event.
The post's text has the event's name, time, and location(s). If the event has
a URL, the post has a link preview card to it with the event's description and
image.
Helper for :func:`from_as1`. See it for args.
Args:
obj (dict): AS1 event object
kwargs: passed through to :func:`_from_as1_post`
Returns:
dict: ``app.bsky.feed.post`` record, before validation and truncation
"""
lines = [f"[Event] {obj.get('displayName') or ''}\n"]
times = []
for field in 'startTime', 'endTime':
try:
if not (val := obj.get(field)):
break
times.append(util.parse_iso8601(val))
except (AttributeError, TypeError, ValueError):
break
if times:
start = times[0]
when = start.strftime('%Y-%m-%d %H:%M')
if len(times) == 2:
end = times[1]
if start.tzinfo and end.tzinfo:
end = end.astimezone(start.tzinfo)
when += ' – ' + end.strftime(
'%H:%M' if end.date() == start.date() else '%Y-%m-%d %H:%M')
# fixed offset time zones render as eg UTC+02:00
if tz := start.strftime('%Z'):
when += f' {tz}'
lines.append(f'📅 {when}')
for loc in as1.get_objects(obj, 'location'):
parts = [loc.get('displayName')]
address = loc.get('address') or {}
if isinstance(address, str):
parts.append(address)
else:
parts.extend([address.get(field) for field in
('streetAddress', 'locality', 'region', 'postalCode', 'country')])
parts = util.uniquify(util.trim_nulls(parts))
if where := ', '.join(parts) or as1.get_url(loc):
lines.append(f'📍 {where}')
header = '\n'.join(lines)
content = obj.get('content') or ''
if as1.is_html(obj, 'content'):
content = html_to_text(content)
# with a URL, use article mode: header is the post text (via summary), content
# goes in the link card. without one, use note mode, all text in content, and
# no summary, since notes render it as a content warning
if url := as1.get_url(obj):
summary = header
as_embed = True
else:
summary = ''
content = '\n\n'.join(filter(None, (header, content)))
as_embed = False
[post] = _from_as1_post({
**obj,
'objectType': 'note',
'content': content,
'content_is_html': False,
}, out_type=None, multiple=False, as_embed=as_embed, summary=summary, **kwargs)
return post
[docs]
def to_external_embed(obj, description=None, blobs=None):
"""Converts an AS1 object to a Bluesky ``app.bsky.embed.external#external``.
Args:
obj (dict): AS1 object
description (str): if provided, overrides ``summary`` and ``content`` in ``obj``
Returns:
dict: Bluesky ``app.bsky.embed.external#external`` record
"""
url = as1.get_url(obj) or obj.get('id')
assert url
ret = {
'$type': f'app.bsky.embed.external',
'external': {
'$type': f'app.bsky.embed.external#external',
'uri': url,
'title': obj.get('displayName') or '', # required
'description': (description
or html_to_text(obj.get('summary') or obj.get('content'),
ignore_links=True)
or ''),
}
}
if blobs:
for img in as1.get_objects(obj, 'image'):
if img_url := img.get('url') or img.get('id'):
if blob := blobs.get(img_url):
ret['external']['thumb'] = blob
break
return ret
[docs]
def to_as1(obj, type=None, uri=None, repo_did=None, repo_handle=None,
pds=DEFAULT_PDS, client=None):
"""Converts a Bluesky object to an AS1 object.
Note that some returned AS1 objects will be incomplete! Notably polls, ie
``question``s converted from ``community.blacksky.assembly.conversation``,
won't have poll options (in ``anyOf`` or ``oneOf``) or votes, since those
stored as separate ATProto records. Callers will need to populate those
themselves.
Args:
obj (dict): ``app.bsky.*`` object
type (str): optional ``$type`` to parse with, only used if ``obj['$type']``
is unset
uri (str): optional ``at://`` URI of this object. Used to populate the
``id`` and ``url`` fields for some object types, eg posts.
repo_did (str): optional DID of the repo this object is from. Required to
generate image URLs.
repo_handle (str): optional handle of the user whose repo this object is from
pds (str): base URL of the PDS that currently serves this object's repo.
Required to generate image URLs. Defaults to ``https://bsky.social/``.
client (Bluesky or lexrpc.Client): optional; if provided, this will be used
to make API calls to PDSes to fetch secondary records needed for conversion,
eg ``community.lexicon.payments.webMonetization`` for profiles
Returns:
dict: AS1 object, or None if the record doesn't correspond to an AS1 object,
eg "not found" records
Raises:
ValueError: if the ``$type`` field is missing or unsupported
"""
if not obj:
return {}
type = obj.get('$type') or type
if not type:
raise ValueError('Bluesky object missing $type field')
uri_repo = uri_bsky_url = None
if uri:
uri_bsky_url = at_uri_to_web_url(uri)
if not uri.startswith('at://'):
raise ValueError('Expected at:// uri, got {uri}')
if parsed := AT_URI_RE.fullmatch(uri):
uri_repo = parsed.group(1)
# for nested to_as1 calls, if necessary
kwargs = {'repo_did': repo_did, 'repo_handle': repo_handle, 'pds': pds}
# TODO: once we're on Python 3.10, switch this to a match statement!
if type in ATP_PROFILE_TYPES + (
'app.bsky.actor.defs#profileView',
'app.bsky.actor.defs#profileViewBasic',
'app.bsky.actor.defs#profileViewDetailed',
'app.bsky.feed.generator',
):
ret = _to_as1_actor(obj, type=type, uri=uri, repo_did=repo_did,
repo_handle=repo_handle, pds=pds, client=client)
elif type in ('app.bsky.feed.post',
'chat.bsky.convo.defs#messageInput',
'chat.bsky.convo.defs#messageView',
'so.sprk.feed.post',
'so.sprk.feed.reply',
'social.grain.comment',
):
ret = _to_as1_post(obj, type=type, uri=uri, repo_did=repo_did,
repo_handle=repo_handle, pds=pds)
elif type in ('app.bsky.feed.defs#postView', 'app.bsky.embed.record#viewRecord'):
ret = to_as1(obj.get('record') or obj.get('value'), **kwargs)
author = obj.get('author') or {}
uri = obj.get('uri')
kwargs['repo_did'] = obj.get('author', {}).get('did') or repo_did
ret.update({
'id': uri,
'url': (at_uri_to_web_url(uri, handle=author.get('handle'))
if uri.startswith('at://') else None),
'author': to_as1(author, type='app.bsky.actor.defs#profileViewBasic', **kwargs),
})
# convert embeds to attachments
for embed in util.get_list(obj, 'embeds') + util.get_list(obj, 'embed'):
embed_type = embed.get('$type')
if embed_type in ('app.bsky.embed.images#view', 'app.bsky.embed.gallery#view'):
ret.setdefault('image', []).extend(to_as1(embed, **kwargs))
elif embed_type in ('app.bsky.embed.external#view',
'app.bsky.embed.record#view',
'app.bsky.embed.video#view',
):
ret['attachments'] = [to_as1(embed, **kwargs)]
elif embed_type == 'app.bsky.embed.recordWithMedia#view':
ret['attachments'] = [to_as1(embed.get('record', {}).get('record'), **kwargs)]
media = embed.get('media')
media_type = media.get('$type')
if media_type in ('app.bsky.embed.external#view', 'app.bsky.embed.video#view'):
ret.setdefault('attachments', []).append(to_as1(media, **kwargs))
elif media_type in ('app.bsky.embed.images#view', 'app.bsky.embed.gallery#view'):
ret.setdefault('image', []).extend(to_as1(media, **kwargs))
else:
assert False, f'Unknown embed media type: {media_type}'
elif type in ('app.bsky.embed.images',
'app.bsky.embed.gallery',
'so.sprk.media.image',
'so.sprk.media.images',
):
ret = []
if repo_did and pds:
imgs = ([obj] if type == 'so.sprk.media.image'
else obj.get('images') or obj.get('items') or [])
for img in imgs:
if image := img.get('image'):
url = blob_to_url(blob=image, repo_did=repo_did, pds=pds)
as1_img = {'url': url}
if alt := img.get('alt'):
as1_img['displayName'] = alt
if aspect := img.get('aspectRatio'):
as1_img.update(**aspect) # only has width and height
if list(as1_img.keys()) == ['url']:
as1_img = url
ret.append(as1_img)
elif type in ('app.bsky.embed.video', 'so.sprk.media.video'):
ret = {}
if repo_did and pds:
if vid := obj['video']:
url = blob_to_url(blob=vid, repo_did=repo_did, pds=pds)
ret = {
'objectType': 'video',
'stream': {
'url': url,
'mimeType': vid.get('mimeType'),
},
'displayName': obj.get('alt'),
}
# only Bluesky's video CDN generates thumbnails
if type == 'app.bsky.embed.video':
ret['image'] = VIDEO_THUMBNAIL_URL.format(
did=urllib.parse.quote(repo_did), cid=blob_cid(vid))
elif type in ('app.bsky.embed.images#view', 'app.bsky.embed.gallery#view'):
ret = []
for img in obj.get('images') or obj.get('items') or []:
as1_img = {
'url': img.get('fullsize'),
'displayName': img.get('alt'),
}
if aspect := img.get('aspectRatio'):
as1_img.update(**aspect) # only has width and height
ret.append(as1_img)
elif type == 'app.bsky.embed.video#view':
ret = {}
if repo_did and pds:
ret = {
'objectType': 'video',
'stream': {'url': blob_to_url(blob=obj, repo_did=repo_did, pds=pds)},
'image': (obj.get('thumbnail')
or VIDEO_THUMBNAIL_URL.format(did=urllib.parse.quote(repo_did),
cid=obj.get('cid'))),
'displayName': obj.get('alt'),
}
elif type in ('app.bsky.embed.external', 'app.bsky.embed.external#view'):
ret = to_as1(obj.get('external'), type='app.bsky.embed.external#viewExternal',
**kwargs)
elif type in ('app.bsky.embed.external#external',
'app.bsky.embed.external#viewExternal'):
ret = {
'objectType': 'link',
'url': obj.get('uri'),
'displayName': obj.get('title'),
'summary': obj.get('description'),
}
thumb = obj.get('thumb')
if type == 'app.bsky.embed.external#external':
if repo_did and pds:
ret['image'] = blob_to_url(blob=thumb, repo_did=repo_did, pds=pds)
else:
ret['image'] = thumb
elif type == 'app.bsky.embed.record':
at_uri = to_as1(obj.get('record'), type='com.atproto.repo.strongRef', **kwargs)
if not at_uri or not isinstance(at_uri, str):
return None
ret = {
'objectType': 'note',
'id': at_uri,
'url': at_uri_to_web_url(at_uri),
}
elif type == 'app.bsky.embed.recordWithMedia':
ret = to_as1(obj.get('record'), type='app.bsky.embed.record', **kwargs)
# TODO: move media handling here from app.bsky.feed.post embed block above
elif type == 'app.bsky.embed.record#view':
return to_as1(obj.get('record'), type='app.bsky.embed.record', **kwargs)
elif type in ('app.bsky.embed.record#viewNotFound',
'app.bsky.embed.record#viewBlocked',
'app.bsky.feed.defs#notFoundPost',
):
return None
elif type == 'app.bsky.feed.defs#feedViewPost':
ret = to_as1(obj['post'], type='app.bsky.feed.defs#postView', **kwargs)
reason = obj.get('reason')
if reason and reason.get('$type') == 'app.bsky.feed.defs#reasonRepost':
post = obj.get('post', {})
uri = post.get('viewer', {}).get('repost')
kwargs['repo_did'] = post.get('author', {}).get('did') or repo_did
ret = {
'objectType': 'activity',
'verb': 'share',
'id': uri,
'url': at_uri_to_web_url(uri),
'object': ret,
'actor': to_as1(reason.get('by'),
type='app.bsky.actor.defs#profileViewBasic', **kwargs),
}
elif type in ('app.bsky.graph.follow',
'app.bsky.graph.block',
'app.bsky.graph.listblock',
'so.sprk.graph.follow',
'so.sprk.graph.block'):
ret = {
'objectType': 'activity',
'verb': 'follow' if type.endswith('.graph.follow') else 'block',
'id': uri,
'url': at_uri_to_web_url(uri),
'object': obj.get('subject'),
'actor': repo_did,
}
elif type == 'com.atproto.moderation.createReport#input':
content = obj['reasonType'].removeprefix('com.atproto.moderation.defs#reason')
if reason := obj.get('reason'):
content += f': {reason}'
ret = {
'objectType': 'activity',
'verb': 'flag',
'actor': repo_did,
'object': to_as1(obj['subject']),
'content': content,
}
elif type in ('app.bsky.feed.like', 'app.bsky.feed.repost',
'so.sprk.feed.like', 'so.sprk.feed.repost',
'social.grain.favorite'):
is_repost = type.endswith('.repost')
# Grain favorites' subjects are at-URIs, not strongRefs
subject = obj.get('subject')
if isinstance(subject, dict):
subject = subject.get('uri')
ret = {
'objectType': 'activity',
'verb': 'share' if is_repost else 'like',
'id': uri,
'object': subject,
'actor': repo_did,
'published': obj.get('createdAt'),
}
# non-at:// subjects are from "invalid" likes/reposts of non-Bluesky posts
if subject and subject.startswith('at://') and uri_repo:
if web_url := at_uri_to_web_url(subject):
# synthetic fragment
verb = 'reposted' if is_repost else 'liked'
ret['url'] = f'{web_url}#{verb}_by_{uri_repo}'
elif type == 'community.lexicon.calendar.rsvp':
# https://github.com/lexicon-community/lexicon/blob/main/community/lexicon/calendar/rsvp.json
status = obj['status'].removeprefix('community.lexicon.calendar.rsvp#')
ret = {
'objectType': 'activity',
'verb': RSVP_STATUS_TO_VERB.get(status, 'rsvp-yes'),
'id': uri,
'object': obj['subject']['uri'],
'actor': repo_did,
}
elif type == 'community.blacksky.assembly.vote':
# converts to an FEP-9967 poll vote, which only supports agree (-1)
# https://github.com/blacksky-algorithms/assembly.blacksky.community/blob/edge/lexicons/community/blacksky/assembly/vote.json
# https://codeberg.org/fediverse/fep/src/branch/main/fep/9967/fep-9967.md#vote-object
if obj.get('value') != -1:
logger.info(f"Can't convert non-agree vote {obj.get('value')} to AS1")
return None
statement_uri = obj.get('subject', {}).get('uri') or ''
parsed = AT_URI_RE.fullmatch(statement_uri)
if not client or not parsed:
logger.info(f"Can't convert vote without fetching its statement {statement_uri}")
return None
try:
record = client.com.atproto.repo.getRecord(**parsed.groupdict())
except requests.RequestException as e:
logger.info(f"Couldn't fetch vote's statement {statement_uri}: {e}")
return None
if not (statement := record.get('value')):
logger.info(f"Couldn't fetch vote's statement {statement_uri}")
return None
ret = {
'objectType': 'vote',
'id': uri,
'author': repo_did,
'inReplyTo': statement.get('conversation', {}).get('uri'),
'displayName': statement.get('text'),
'published': obj.get('createdAt'),
}
elif type == 'app.bsky.feed.defs#threadViewPost':
post = obj.get('post', {})
kwargs['repo_did'] = post.get('author', {}).get('did') or repo_did
return to_as1(post, type='app.bsky.feed.defs#postView', **kwargs)
elif type in ('app.bsky.feed.defs#generatorView',
'app.bsky.graph.defs#listView'):
uri = obj.get('uri')
ret = {
'objectType': 'service',
'id': uri,
'url': at_uri_to_web_url(uri),
'displayName': (obj.get('displayName') # generator
or obj.get('name')), # list
'summary': obj.get('description'),
'image': obj.get('avatar'),
'author': to_as1(obj.get('creator'), type='app.bsky.actor.defs#profileView',
**kwargs),
}
elif type == 'app.bsky.feed.defs#blockedPost':
uri = obj.get('uri') or uri
ret = {
'objectType': 'note',
'id': uri,
'url': at_uri_to_web_url(uri),
'blocked': True,
'author': obj.get('blockedAuthor', {}).get('did'),
}
elif type == 'com.atproto.repo.strongRef':
return obj['uri']
elif type == 'com.atproto.admin.defs#repoRef':
return obj['did']
elif type == 'app.bsky.graph.list':
ret = {
'objectType': 'collection',
'id': uri,
'url': uri_bsky_url,
'displayName': obj.get('name'),
'summary': obj.get('description'),
'published': obj.get('createdAt'),
}
if repo_did and pds:
ret['image'] = blob_to_url(blob=obj.get('avatar'), repo_did=repo_did, pds=pds)
elif type == 'app.bsky.graph.listitem':
ret = {
'objectType': 'activity',
'verb': 'add',
'id': uri,
'actor': repo_did,
'object': obj.get('subject'),
'target': obj.get('list'),
'published': obj.get('createdAt'),
}
elif type in ('app.bsky.actor.link', 'app.bsky.actor.defs#profileLinkView'):
# profile link. destination goes in value, not url, so that this object can
# go directly into an actor's urls field
# https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/actor/link.json
repo = repo_did or uri_repo
icon = None
if type == 'app.bsky.actor.link' and repo and pds:
icon = blob_to_url(blob=obj.get('icon'), repo_did=repo, pds=pds)
elif type == 'app.bsky.actor.defs#profileLinkView':
icon = obj.get('icon')
ret = {
'objectType': 'link',
'id': uri,
'author': repo,
'value': obj.get('url'),
'displayName': obj.get('title'),
'image': icon,
'published': obj.get('createdAt'),
}
elif type == 'community.lexicon.payments.webMonetization':
# not a real AS1 object, just a stub so that we minimally support these records
# https://github.com/lexicon-community/lexicon/tree/main/community/lexicon/payments
ret = {
'monetization': obj.get('address'),
}
elif type in ('community.lexicon.location.address',
'community.lexicon.location.fsq',
'community.lexicon.location.geo',
'community.lexicon.location.hthree'):
# https://github.com/lexicon-community/lexicon/tree/main/community/lexicon/location
# https://activitystrea.ms/specs/json/schema/activity-schema.html#place
ret = {
'objectType': 'place',
'displayName': obj.get('name'),
'address': {
'streetAddress': obj.get('street'),
'locality': obj.get('locality'),
'region': obj.get('region'),
'postalCode': obj.get('postalCode'),
'country': obj.get('country'),
},
}
for field in 'latitude', 'longitude':
if util.is_float(val := obj.get(field)):
ret[field] = float(val)
elif type == 'community.lexicon.calendar.event':
# https://github.com/lexicon-community/lexicon/tree/main/community/lexicon/calendar
# https://activitystrea.ms/specs/json/schema/activity-schema.html#event
urls = [{'displayName': u.get('name'), 'value': u.get('uri')}
for u in obj.get('uris', [])]
ret = {
'objectType': 'event',
'id': uri,
'author': repo_did,
'url': urls[0]['value'] if urls else None,
'urls': urls if len(urls) > 1 else None,
'displayName': obj.get('name'),
'content': obj.get('description'),
'published': obj.get('createdAt'),
'startTime': obj.get('startsAt'),
'endTime': obj.get('endsAt'),
}
locs = []
for loc in obj.get('locations', []):
if loc.get('$type') == 'community.lexicon.calendar.event#uri':
locs.append({
'objectType': 'place',
'displayName': loc.get('name'),
'url': loc.get('uri'),
})
else:
locs.append(to_as1(loc))
ret['location'] = locs[0] if len(locs) == 1 else locs
# media isn't in the lexicon yet, but Smoke Signal, atmo.rsvp, etc use it
# https://discourse.atmosphere.community/t/kicking-off-a-dedicated-space-for-discussion-for-calendar-events-rsvp/684/5
if repo_did and pds:
ret['image'] = []
for media in obj.get('media', []):
if content := media.get('content'):
ret['image'].append({
'objectType': 'featured' if media.get('role') == 'header' else None,
'url': blob_to_url(blob=content, repo_did=repo_did, pds=pds),
'displayName': media.get('alt'),
**media.get('aspect_ratio', {}),
})
elif type == 'community.blacksky.assembly.conversation':
# https://github.com/blacksky-algorithms/assembly.blacksky.community
ret = {
'objectType': 'question',
'id': uri,
'author': repo_did,
'content': obj.get('topic'),
'summary': obj.get('description'),
'published': obj.get('createdAt'),
}
elif type == 'community.blacksky.assembly.statement':
ret = {
'objectType': 'note',
'id': uri,
'author': repo_did,
'displayName': obj.get('text'),
'inReplyTo': obj.get('conversation', {}).get('uri'),
'published': obj.get('createdAt'),
}
elif type == 'site.standard.document':
ret = {
'objectType': 'article',
'id': uri,
'author': repo_did,
'displayName': obj.get('title'),
'summary': obj.get('description'),
'content': obj.get('textContent'),
'published': obj.get('publishedAt'),
'updated': obj.get('updatedAt'),
'tags': [{'objectType': 'hashtag', 'displayName': tag}
for tag in obj.get('tags', [])],
}
site = obj.get('site')
if site and (parsed := AT_URI_RE.fullmatch(site)):
# site is a site.standard.publication record. fetch it to get its URL
site = None
if client and parsed.lastgroup == 'rkey':
if record := client.com.atproto.repo.getRecord(**parsed.groupdict()):
site = record.get('value', {}).get('url')
if site:
if path := obj.get('path'):
# not urljoin because site may or may not have a trailing /
ret['url'] = site.rstrip('/') + '/' + path.lstrip('/')
else:
ret['url'] = site
if client and (post_uri := obj.get('bskyPostRef', {}).get('uri')):
if (parsed := AT_URI_RE.fullmatch(post_uri)) and parsed.lastgroup == 'rkey':
# note that bskyPostRef is a strongRef, with cid, but we don't pass that cid
# to getRecord, since if the post record has been updated, the repo may no
# longer have the version with this cid. (plus, we probably *want* the
# updated version anyway.)
if record := client.com.atproto.repo.getRecord(**parsed.groupdict()):
ret['preview'] = to_as1(record['value'], uri=post_uri,
repo_did=parsed['repo'], pds=pds)
elif type == 'site.standard.publication':
ret = {
# should this be organization or service or group instead?
'objectType': 'person',
'url': obj.get('url'),
'displayName': obj.get('name'),
'summary': obj.get('description'),
}
else:
raise ValueError(f'Bluesky object has unknown $type: {type}')
# FEP-fffd proxy links from community.lexicon.meta.links and wafrn's fediverseId
# https://tangled.org/essentialrandom.bsky.social/lexicon-community-lexicons/blob/add-proxy-links/community/lexicon/meta/README.md
# https://github.com/snarfed/bridgy-fed/issues/800#issuecomment-6694473048
proxy_links = []
seen_urls = []
meta_links = obj.get('community.lexicon.meta.links')
if isinstance(meta_links, dict):
for link in meta_links.get('links', []):
if ((url := link.get('href')) and url not in seen_urls
and link.get('rel') in as1.PROXY_LINK_RELS):
proxy_links.append({
'value': url,
'rel': link['rel'],
'mimeType': link.get('mediaType'),
})
seen_urls.append(url)
if (fediverse_id := obj.get('fediverseId')) and fediverse_id not in seen_urls:
proxy_links.append({
'value': fediverse_id,
'rel': 'alternate',
'mimeType': CONTENT_TYPE,
})
if proxy_links and isinstance(ret, dict):
ret['urls'] = (util.get_list(ret, 'urls') or util.get_list(ret, 'url')) + proxy_links
ret = as1.trim_nulls(ret)
# ugly hack
if isinstance(ret, dict) and ret.get('author') == {'objectType': 'person'}:
del ret['author']
return ret
def _to_as1_actor(obj, *, type, uri, repo_did, repo_handle, pds, client):
"""Converts a Bluesky or related profile, profile view, or feed generator to AS1.
Helper for :func:`to_as1`. See it for args, except:
Args:
type (str): ``obj``'s ``$type``
Returns:
dict: AS1 actor or service
"""
images = [{'url': obj.get('avatar')}]
banner = obj.get('banner')
if banner:
images.append({'url': obj.get('banner'), 'objectType': 'featured'})
handle = obj.get('handle')
did = obj.get('did')
if type in ATP_PROFILE_TYPES:
if not handle:
handle = repo_handle
if not did:
did = repo_did
# urls: bsky.app profile, did:web domain, bsky.app feed generator, links in bio
urls = []
if handle:
profile_type = type if type in ATP_PROFILE_TYPES else 'app.bsky.actor.profile'
urls.append(COLLECTION_TO_WEB_URL[profile_type].format(id=handle))
if did and did.startswith('did:web:'):
urls.append(did_web_to_url(did))
if website := obj.get('website'):
urls.append(website)
# profile links. profile views include them inline, profile records have
# strongRefs to app.bsky.actor.link records that we have to fetch
owner = did
if not owner and (parsed := AT_URI_RE.fullmatch(uri or '')):
owner = parsed['repo']
links = []
for link in obj.get('links', []):
link_uri = link.get('uri') or ''
link_as1 = None
if type == 'app.bsky.actor.defs#profileViewDetailed':
link_as1 = to_as1(link, type='app.bsky.actor.defs#profileLinkView',
uri=link_uri, pds=pds)
elif (client and (parsed := AT_URI_RE.fullmatch(link_uri))
and parsed['repo'] == owner
and parsed['collection'] == 'app.bsky.actor.link'):
try:
record = client.com.atproto.repo.getRecord(**parsed.groupdict())
link_as1 = to_as1(record.get('value'), uri=link_uri, pds=pds)
except (requests.RequestException, NotImplementedError, ValueError) as e:
logger.info(f"Couldn't fetch profile link {link_uri} : {e}")
if link_as1 and (url := link_as1.get('value')):
links.append(link_as1)
urls.append(url)
desc = html.escape(obj.get('description') or '')
summary = whitespace_to_html(util.linkify(desc, pretty=True), escape=False)
urls.extend(util.extract_links(summary))
if type == 'app.bsky.feed.generator':
if uri_web_url := at_uri_to_web_url(uri):
urls.insert(0, uri_web_url)
ret = {
'objectType': 'service',
'id': uri,
'author': repo_did,
'generator': did,
}
else:
ret = {
'objectType': 'person',
'id': uri or did,
'username': obj.get('handle') or repo_handle,
}
ret.update({
'displayName': obj.get('displayName'),
# TODO: for app.bsky.feed.generator, use descriptionFacets
'summary': summary,
'pronouns': obj.get('pronouns'),
'image': images,
'published': obj.get('createdAt'),
})
# urls
if urls:
urls = util.dedupe_urls(urls)
ret['url'] = urls[0]
if len(urls) > 1 or links:
ret['urls'] = as1.merge_urls(urls, links)
# avatar and banner are blobs in app.bsky.actor.profile; convert to URLs
repo_did = repo_did or did
if type in ATP_PROFILE_TYPES + ('app.bsky.feed.generator',):
if repo_did and pds:
for img in ret['image']:
img['url'] = blob_to_url(blob=img['url'], repo_did=repo_did, pds=pds)
else:
ret['image'] = []
# convert public view opt-out to unlisted AS1 audience targeting
# https://docs.bsky.app/docs/advanced-guides/resolving-identities#for-backend-services
# https://activitystrea.ms/specs/json/targeting/1.0/
labels = (obj.get('labels', {}).get('values', [])
if type in ATP_PROFILE_TYPES
else obj.get('labels', []))
for label in labels:
if label.get('val') == NO_UNAUTHENTICATED_LABEL and not label.get('neg'):
ret['to'] = [{
'objectType': 'group',
'alias': '@unlisted',
}]
if label.get('val') == BOT_LABEL and not label.get('neg'):
ret['objectType'] = 'service'
# follow/follower counts. convert to followers/following collections, not in AS1,
# borrowed from ActivityPub: https://www.w3.org/TR/activitypub/#followers
if followers := obj.get('followersCount'):
ret['followers'] = {'totalItems': followers}
if follows := obj.get('followsCount'):
ret['following'] = {'totalItems': follows}
# convert pinnedPost to featured ActivityStreams collection
# https://docs.joinmastodon.org/spec/activitypub/#featured
if pinned_post := obj.get('pinnedPost'):
# sometimes this is a str. not sure why, that's invalid based on the schema,
# pinnedPost has always been an object, but we still see it occasionally, eg
# https://console.cloud.google.com/errors/detail/CKevsI3gyqrAdw?project=bridgy-federated
if isinstance(pinned_post, dict):
ret['featured'] = {
'totalItems': 1,
'items': [pinned_post['uri']],
}
# Web Monetization wallet address, if any
# https://github.com/lexicon-community/lexicon/tree/main/community/lexicon/payments
if client and repo_did:
if wallet := client.com.atproto.repo.getRecord(
repo=repo_did, collection='community.lexicon.payments.webMonetization',
rkey='self'):
ret['monetization'] = wallet['value']['address']
return ret
def _to_as1_post(obj, *, type, uri, repo_did, repo_handle, pds):
"""Converts a Bluesky/Spark/Grain post/reply, or chat message, to AS1.
Helper for :func:`to_as1`. See it for args, except:
Args:
type (str): ``obj``'s ``$type``
Returns:
dict: AS1 note or comment
"""
# for nested to_as1 calls, if necessary
kwargs = {'repo_did': repo_did, 'repo_handle': repo_handle, 'pds': pds}
# Spark posts and replies are the same as Bluesky posts except embed is
# media, and in posts, text and facets are in caption
text_obj = (obj.get('caption') or {}) if type == 'so.sprk.feed.post' else obj
text = text_obj.get('text', '')
text_encoded = text.encode()
# convert facets to tags
tags = []
for facet in text_obj.get('facets', []):
tag = {}
for feat in facet.get('features', []):
feat_type = (feat.get('$type') or '').replace('so.sprk.', 'app.bsky.')
if feat_type == 'app.bsky.richtext.facet#link':
tag.update({
'objectType': 'article',
'url': feat.get('uri'),
})
elif feat_type == 'app.bsky.richtext.facet#mention':
tag.update({
'objectType': 'mention',
'url': Bluesky.user_url(feat.get('did')),
})
elif feat_type == 'app.bsky.richtext.facet#tag':
name = feat.get('tag')
tag.update({
'objectType': 'hashtag',
'displayName': name,
'url': f'https://bsky.app/search?q=%23{urllib.parse.quote(name)}',
})
index = facet.get('index', {})
# convert indices from UTF-8 encoded bytes to Unicode chars (code points)
# https://github.com/snarfed/atproto/blob/5b0c2d7dd533711c17202cd61c0e101ef3a81971/lexicons/app/bsky/richtext/facet.json#L34
byte_start = index.get('byteStart')
byte_end = index.get('byteEnd')
try:
if byte_start is not None:
tag['startIndex'] = len(text_encoded[:byte_start].decode())
if byte_end is not None:
name = text_encoded[byte_start:byte_end].decode()
tag.setdefault('displayName', name)
tag['length'] = len(name)
except UnicodeDecodeError as e:
logger.warning(f"Couldn't apply facet {facet} to unicode text: {text}")
tags.append(tag)
# escape HTML characters: <, >, &. shuffle over facet indices to match.
while match := re.search(r'<|>', text):
# escape char
entity = f'&{html.entities.codepoint2name[ord(match.group(0))]};'
pos = match.start(0)
text = text[:pos] + entity + text[pos + 1:]
# no need to update text_encoded, we're done with it by here
# shuffle indices
added = len(entity) - 1
for tag in tags:
start = tag.get('startIndex', 0)
end = start + tag.get('length', 0) # exclusive
if end <= pos:
continue
elif start <= pos:
tag['length'] += added
else: # start > pos
tag['startIndex'] += added
# extra tags not in post text
tags.extend({
'objectType': 'hashtag',
'displayName': name,
'url': f'https://bsky.app/search?q=%23{urllib.parse.quote(name)}',
} for name in obj.get('tags', []))
if type == 'social.grain.comment':
in_reply_to = obj.get('replyTo') or obj.get('subject')
else:
in_reply_to = obj.get('reply', {}).get('parent', {}).get('uri')
try:
in_reply_to_url = at_uri_to_web_url(in_reply_to)
except ValueError: # not an at:// URI
in_reply_to_url = in_reply_to
# convert self labels to AS1 sensitive and content warning in summary
# https://github.com/snarfed/atproto/blob/f2f8de63b333448d87c364578e023ddbb63b8b25/lexicons/com/atproto/label/defs.json#L139-L154
# https://swicg.github.io/miscellany/#sensitive
content_warnings = []
sensitive = None
for label in obj.get('labels', {}).get('values', []):
label_text = SENSITIVE_LABELS.get(label.get('val'))
if label_text and not label.get('neg'):
sensitive = True
content_warnings.append(label_text)
ret = {
'objectType': 'comment' if in_reply_to else 'note',
'id': uri,
'url': at_uri_to_web_url(uri),
'content': text,
# originally I used <br> as the separator here, which is supposed to work
# because AS2 summary supports HTML:
# https://www.w3.org/TR/activitystreams-vocabulary/#dfn-summary
# ...but Mastodon doesn't support it :(
# https://github.com/snarfed/bridgy-fed/issues/2509
# https://github.com/mastodon/mastodon/issues/34079#issuecomment-2703397374
'summary': '; '.join(content_warnings),
'inReplyTo': [{
'id': in_reply_to,
'url': in_reply_to_url,
}],
'published': obj.get('createdAt', ''),
'tags': tags,
'author': repo_did,
# we steal this from AS2, it's not officially part of AS1
'contentMap': {lang: text for lang in obj.get('langs', [])},
'sensitive': sensitive,
}
if type == 'chat.bsky.convo.defs#messageView':
author = obj['sender']['did']
if not ret['id']:
ret['id'] = f'at://{author}/chat.bsky.convo.defs.messageView/{obj["id"]}'
ret.update({
'author': author,
'published': obj.get('sentAt'),
'to': ['?'], # show that it's a DM even though we don't know the recipient
})
# embeds
embed = obj.get('media' if type.startswith('so.sprk.') else 'embed') or {}
embed_type = embed.get('$type')
if embed_type in ('app.bsky.embed.images',
'app.bsky.embed.gallery',
'so.sprk.media.image',
'so.sprk.media.images',
):
ret['image'] = to_as1(embed, **kwargs)
elif embed_type in ('app.bsky.embed.external',
'app.bsky.embed.record',
'app.bsky.embed.video',
'so.sprk.media.video',
):
ret['attachments'] = [to_as1(embed, **kwargs)]
elif embed_type == 'app.bsky.embed.recordWithMedia':
ret['attachments'] = [to_as1(embed, **kwargs)]
# TODO: stop reaching inside and do this in the to_as1 call instead?
# need to make it return both the quote post attachment and the image.
media = embed.get('media')
media_type = media.get('$type')
if media_type in ('app.bsky.embed.external', 'app.bsky.embed.video'):
ret['attachments'].append(to_as1(media, **kwargs))
elif media_type in ('app.bsky.embed.images', 'app.bsky.embed.gallery'):
ret['image'] = to_as1(media, **kwargs)
else:
assert False, f'Unknown embed media type: {media_type}'
return ret
[docs]
def blob_to_url(*, blob, repo_did, pds=DEFAULT_PDS):
"""Generates a URL for a blob.
Supports both new and old style blobs:
https://atproto.com/specs/data-model#blob-type
Supports ``ref`` values as raw bytes, base-32 encoded strings, and
DAG-JSON mappings with inner ``$link`` values.
The resulting URL is a ``com.atproto.sync.getBlob`` XRPC call to the PDS.
For blobs on the official ``bsky.social`` PDS, we could consider using their CDN
instead: ``https://av-cdn.bsky.app/img/avatar/plain/[DID]/[CID]@jpeg``
They also run a resizing image proxy on ``cdn.bsky.social`` with URLs like
``https://cdn.bsky.social/imgproxy/[SIG]/rs:fit:2000:2000:1:0/plain/[CID]@jpeg``,
not sure how to generate signatures for it yet.
Args:
blob (dict): https://atproto.com/specs/data-model#blob-type
repo_did (str): DID of the repo that owns this blob
pds (str): base URL of the PDS that serves this repo. Defaults to
:const:`DEFAULT_PDS`
Returns:
str: URL for this blob, or None if ``blob`` is empty or has no CID
"""
if not blob:
return None
assert repo_did and pds
if cid := blob_cid(blob):
path = f'/xrpc/com.atproto.sync.getBlob?did={repo_did}&cid={cid}'
return urllib.parse.urljoin(pds, path)
[docs]
def blob_cid(blob):
"""Returns a blob's base32-encoded CID.
Supports both new and old style blobs:
https://atproto.com/specs/data-model#blob-type
Supports ``ref`` values as raw bytes, base-32 encoded strings, and
DAG-JSON mappings with inner ``$link`` values.
Args:
blob (dict): https://atproto.com/specs/data-model#blob-type
Returns:
str: this blob's CID, base32-encoded
"""
assert blob
if ref := blob.get('ref'):
return (ref if isinstance(ref, str)
else CID.decode(ref).encode('base32') if isinstance(ref, bytes)
else ref.encode('base32') if isinstance(ref, CID)
else ref.get('$link'))
else:
return blob.get('cid')
[docs]
class Bluesky(Source):
"""Bluesky source class. See file docstring and :class:`Source` class for
details.
Attributes:
handle (str)
did (str)
client (lexrpc.Client)
"""
DOMAIN = 'bsky.app'
BASE_URL = 'https://bsky.app'
NAME = 'Bluesky'
TRUNCATE_TEXT_LENGTH = None # different for post text vs profile description
POST_ID_RE = AT_URI_RE
TYPE_LABELS = {
'post': 'post',
'comment': 'reply',
'repost': 'repost',
'like': 'like',
'follow': 'follow',
}
_client = None
_app_password = None
def __init__(self, handle, pds_url=None, did=None, access_token=None,
refresh_token=None, app_password=None, auth=None,
session_callback=None, **requests_kwargs):
"""Constructor.
Args:
handle (str): username, eg ``snarfed.bsky.social`` or ``snarfed.org``
pds_url (str): base URL for the user's PDS, eg ``https://my.pds/``
did (str): did:plc or did:web, optional
access_token (str): optional
refresh_token (str): optional
app_password (str): optional
auth (requests.auth.AuthBase): optional, used to authenticate XRPC requests
session_callback (callable, dict => None): passed to :class:`lexrpc.Client`
constructor, called when a new session is created or refreshed
requests_kwargs (dict): passed to :func:`requests.get`/:func:`requests.post`
"""
assert not ((access_token or refresh_token) and auth)
self.handle = handle
self.did = did
self._pds_url = pds_url
self._access_token = access_token
self._refresh_token = refresh_token
self._app_password = app_password
self._auth = auth
self._session_callback = session_callback
self._requests_kwargs = requests_kwargs
[docs]
@classmethod
def from_auth(cls, auth_entity, client_metadata=None, **kwargs):
"""Creates a :class:`Bluesky` from a :class:`oauth_dropins.bluesky.BlueskyAuth`.
TODO: unify with :meth:`oauth_dropins.bluesky.BlueskyAuth.oauth_api`?
Args:
auth_entity (oauth_dropins.bluesky.BlueskyAuth)
client_metadata (dict): Bluesky OAuth client metadata. Required for OAuth
users (those with :attr:`~oauth_dropins.bluesky.BlueskyAuth.dpop_token`
set). See :func:`oauth_dropins.bluesky.bluesky_auth_kwargs`.
kwargs: passed to :class:`Bluesky`
Returns:
Bluesky:
"""
pds_url = auth_entity.pds_url or oauth_bluesky.pds_for_did(auth_entity.key.id())
if auth_entity.dpop_token:
oauth_client = oauth_bluesky.oauth_client_for_pds(client_metadata, pds_url)
token = TokenSerializer().loads(auth_entity.dpop_token)
kwargs.setdefault('auth', OAuth2AccessTokenAuth(client=oauth_client,
token=token))
else:
kwargs.setdefault('app_password', auth_entity.password)
if auth_entity.session:
kwargs.setdefault('access_token', auth_entity.session.get('accessJwt'))
kwargs.setdefault('refresh_token', auth_entity.session.get('refreshJwt'))
return cls(
handle=auth_entity.user_display_name(),
did=auth_entity.key.id(),
pds_url=pds_url,
session_callback=oauth_bluesky.make_session_callback(auth_entity),
**kwargs,
)
@property
def client(self):
if not self._client:
# initialize
if not self._pds_url:
if self.handle and not self.did:
self.did = resolve_handle(self.handle, get_fn=util.session.get)
if self.did:
self._pds_url = oauth_bluesky.pds_for_did(self.did)
headers = {'User-Agent': util.user_agent}
self._client = Client(self._pds_url, access_token=self._access_token,
refresh_token=self._refresh_token, auth=self._auth,
headers=headers, session_callback=self._session_callback,
validate=True, requests_session=util.session,
**self._requests_kwargs)
self._appview = Client(DEFAULT_APPVIEW, headers=headers, validate=True,
requests_session=util.session, **self._requests_kwargs)
if not self._client.session and self._app_password:
# log in
resp = self._client.com.atproto.server.createSession({
'identifier': self.did or self.handle,
'password': self._app_password,
})
self.handle = resp['handle']
self.did = resp['did']
return self._client
@property
def appview(self):
self.client # generate _appview
return self._appview
[docs]
@classmethod
def user_url(cls, handle):
"""Returns the profile URL for a given handle.
Args:
handle (str)
Returns:
str: profile URL
"""
return f'{cls.BASE_URL}/profile/{handle.lstrip("@")}'
[docs]
@classmethod
def to_as1_actor(cls, user, **kwargs):
"""Converts a user to an actor.
Args:
user (dict): an ``app.bsky.actor.profile`` record
kwargs: passed through to :func:`to_as1`
Returns:
dict: ActivityStreams actor
"""
return to_as1(user, **kwargs)
[docs]
@classmethod
def post_url(cls, handle, tid):
"""Returns the post URL for a given handle and tid.
Args:
handle (str)
tid (str)
Returns:
str: profile URL
"""
return f'{cls.user_url(handle)}/post/{tid}'
[docs]
@classmethod
def post_id(cls, url):
"""Returns the `at://` URI for the given URL if it's for a post.
Also see ``arroba.util.parse_at_uri``.
Returns:
str or None
"""
if not url:
return None
if not AT_URI_RE.fullmatch(url):
try:
url = web_url_to_at_uri(url)
except ValueError:
return None
if (len(url.removeprefix('at://').split('/')) == 3
# only return at:// URIs for posts, not profiles
and not any(url.endswith(f'/{type}/self') for type in ATP_PROFILE_TYPES)):
return url
[docs]
def get_activities_response(self, user_id=None, group_id=None, app_id=None,
activity_id=None, fetch_replies=False,
fetch_likes=False, fetch_shares=False,
include_shares=True, fetch_mentions=False,
search_query=None, start_index=None, count=None,
cache=None, **kwargs):
"""Fetches posts and converts them to AS1 activities.
See :meth:`Source.get_activities_response` for more information.
Bluesky-specific details:
Args:
activity_id (str): an ``at://`` URI
"""
assert not start_index
params = {}
if count is not None:
params['limit'] = count
posts = None
handle = self.handle
if activity_id:
if not activity_id.startswith('at://'):
raise ValueError(f'Expected activity_id to be at:// URI; got {activity_id}')
resp = self.client.app.bsky.feed.getPostThread({}, uri=activity_id, depth=1)
posts = [resp.get('thread', {})]
elif group_id in (None, FRIENDS):
resp = self.client.app.bsky.feed.getTimeline({}, **params)
posts = resp.get('feed', [])
else: # eg group_id SELF
actor = user_id or self.did or self.handle
if not actor:
raise ValueError('user_id is required')
resp = self.client.app.bsky.feed.getAuthorFeed({}, actor=actor, **params)
posts = resp.get('feed', [])
if cache is None:
# for convenience, throwaway object just for this method
cache = {}
activities = []
for post in posts:
reason = post.get('reason')
is_repost = reason and reason.get('$type') == 'app.bsky.feed.defs#reasonRepost'
if is_repost and not include_shares:
continue
activity = self.postprocess_activity(self._post_to_activity(post))
if not activity:
continue
activities.append(activity)
obj = activity['object']
id = obj.get('id')
tags = obj.setdefault('tags', [])
if is_repost:
# If it's a repost we're not interested in responses to it.
continue
bs_post = post.get('post')
if bs_post and id:
# Likes
like_count = bs_post.get('likeCount')
if fetch_likes and like_count and like_count != cache.get('ABL ' + id):
likers = self.client.app.bsky.feed.getLikes({}, uri=bs_post.get('uri'))
tags.extend(self._make_like(bs_post, l.get('actor')) for l in likers.get('likes'))
cache['ABL ' + id] = like_count
# Reposts
repost_count = bs_post.get('repostCount')
if fetch_shares and repost_count and repost_count != cache.get('ABRP ' + id):
reposters = self.client.app.bsky.feed.getRepostedBy({}, uri=bs_post.get('uri'))
tags.extend(self._make_share(bs_post, r) for r in reposters.get('repostedBy'))
cache['ABRP ' + id] = repost_count
# Replies
reply_count = bs_post.get('replyCount')
if fetch_replies and reply_count and reply_count != cache.get('ABR ' + id):
replies = []
for r in self._get_replies(bs_post.get('uri')):
try:
reply = to_as1(r)
except ValueError as e:
logger.warning(f'skipping a reply: {e}')
continue
if reply:
replies.append(reply)
for r in replies:
r['id'] = self.tag_uri(r['id'])
obj['replies'] = {
'items': replies,
}
cache['ABR ' + id] = reply_count
resp = self.make_activities_base_response(as1.trim_nulls(activities))
return resp
[docs]
def get_actor(self, user_id=None):
"""Fetches and returns a user.
Args:
user_id (str): either handle or DID; defaults to current user
Returns:
dict: ActivityStreams actor
"""
did = handle = None
if user_id:
if user_id.startswith('did:'):
did = user_id
else:
handle = user_id
else:
did = self.did
handle = self.handle
profile = self.client.app.bsky.actor.getProfile({}, actor=did or handle)
return to_as1(profile, type='app.bsky.actor.defs#profileViewDetailed',
repo_did=did, repo_handle=handle)
def _post_to_activity(self, post):
"""Converts a post to an activity.
Returns ``{}`` if ``post`` has an unknown or unsupported type.
Args:
post: Bluesky post app.bluesky.feed.defs#feedViewPost
Returns: AS1 activity
"""
try:
obj = to_as1(post, type='app.bsky.feed.defs#feedViewPost')
except ValueError as e:
logger.warning(e)
return {}
if util.get_first(obj, 'objectType') == 'activity':
return obj
return {
'id': obj.get('id'),
'verb': 'post',
'actor': obj.get('author'),
'object': obj,
'objectType': 'activity',
}
def _make_like(self, post, actor):
return self._make_like_or_share(post, actor, 'like')
def _make_share(self, post, actor):
return self._make_like_or_share(post, actor, 'share')
def _make_like_or_share(self, post, actor, verb):
"""Generates and returns a ActivityStreams like object.
Args:
post: dict, Bluesky app.bsky.feed.defs#feedViewPost
actor: dict, Bluesky app.bsky.actor.defs#profileView
verb: string, 'like' or 'share'
Returns: dict, AS1 like activity
"""
assert verb in ('like', 'share')
label = 'liked' if verb == 'like' else 'reposted'
url = at_uri_to_web_url(post.get('uri'), post.get('author').get('handle'))
actor_id = actor.get('did')
author = to_as1(actor, 'app.bsky.actor.defs#profileView')
author['id'] = self.tag_uri(author['id'])
suffix = f'{label}_by_{actor_id}'
return {
'id': self.tag_uri(f'{post.get("uri")}_{suffix}'),
'url': f'{url}#{suffix}',
'objectType': 'activity',
'verb': verb,
'object': {'url': url},
'author': author,
}
def _get_replies(self, uri):
"""
Gets the replies to a specific post and returns them
in ascending order of creation. Does not include the original post.
Args:
uri: string, post uri
Returns: list, Bluesky app.bsky.feed.defs#threadViewPost
"""
ret = []
resp = self.client.app.bsky.feed.getPostThread({}, uri=uri)
thread = resp.get('thread')
if thread:
ret = self._recurse_replies(thread)
return sorted(ret, key = lambda thread:
thread.get('post', {}).get('record', {}).get('createdAt') or '')
# TODO this ought to take a depth limit. hellthread, anyone?
def _recurse_replies(self, thread):
"""
Recurses through a Bluesky app.bsky.feed.defs#threadViewPost
and returns its replies as a list.
Args:
thread: dict, Bluesky app.bsky.feed.defs#threadViewPost
Returns: list, Bluesky app.bsky.feed.defs#threadViewPost
"""
ret = []
for r in thread.get('replies', []):
ret += [r]
ret += self._recurse_replies(r)
return ret
[docs]
def get_followers(self, user_id=None):
"""Returns the current user's followers.
Limited to the first 10k followers.
Args:
user_id (str): the DID to fetch followers for. If unset, defaults to
``self.user_id``.
Returns:
sequence of dict: ActivityStreams 1 actors
"""
return self._get_follows_or_followers('app.bsky.graph.getFollowers',
user_id=user_id)
[docs]
def get_follows(self, user_id=None):
"""Returns the current user's follows.
Limited to the first 10k follows.
Args:
user_id (str): the DID to fetch follows for. If unset, defaults to
``self.user_id``.
Returns:
sequence of dict: ActivityStreams 1 actors
"""
return self._get_follows_or_followers('app.bsky.graph.getFollows', user_id=user_id)
def _get_follows_or_followers(self, method, user_id=None):
"""Returns the current user's follows.
This will often be limited, eg to the first 10k followers,
depending on the silo.
Args:
method (str): either ``app.bsky.graph.getFollows`
or ``app.bsky.graph.getFollowers``
user_id (str): the user to fetch follows for. If unset, defaults to
``self.user_id``.
Returns:
sequence of dict: ActivityStreams 1 actors
"""
assert method in ('app.bsky.graph.getFollows', 'app.bsky.graph.getFollowers'), \
method
follows = []
cursor = None
while True:
max = LEXRPC.defs[method]['parameters']['properties']['limit']['maximum']
resp = self.appview.call(method, {}, actor=(user_id or self.did),
cursor=cursor, limit=max)
follows.extend(self.to_as1_actor(f, type='app.bsky.actor.defs#profileView')
for f in (resp.get('follows') or resp.get('followers') or []))
cursor = resp.get('cursor')
if not cursor or len(follows) >= MAX_FOLLOWS:
return follows[:MAX_FOLLOWS]
[docs]
def create(self, obj, include_link=OMIT_LINK, ignore_formatting=False,
validate=None, blobs=None, **kwargs):
"""Creates a post, reply, repost, or like.
Args:
obj (dict): ActivityStreams object
include_link (str)
ignore_formatting (bool)
validate (bool or None): passed through to :func:`from_as1`. If False,
allows creating invalid records, eg replies to non-Bluesky posts, and
passes ``validate: false`` to ``createRecord``.
blobs (dict): optional mapping from str image or video URL in ``obj`` to
``$type: blob`` dict for blobs that have already been uploaded to the
user's PDS. These URLs aren't fetched or uploaded again.
Returns:
CreationResult: whose content will be a dict with ``id``, ``url``, and
``type`` keys (all optional) for the newly created object (or None)
"""
return self._create(obj, preview=False, include_link=include_link,
ignore_formatting=ignore_formatting, validate=validate,
blobs=blobs)
[docs]
def preview_create(self, obj, include_link=OMIT_LINK,
ignore_formatting=False):
"""Preview creating a post, reply, repost, or like.
Args:
obj: ActivityStreams object
include_link (str)
ignore_formatting (bool)
Returns:
CreationResult: content will be a str HTML snippet or None
"""
return self._create(obj, preview=True, include_link=include_link,
ignore_formatting=ignore_formatting)
[docs]
def update(self, obj, include_link=OMIT_LINK, ignore_formatting=False,
validate=None, **kwargs):
"""Updates an existing post, reply, like, repost, follow, or block.
``obj['id']`` must be the at:// URI of the existing record to update.
Args:
obj (dict): ActivityStreams object
include_link (str)
ignore_formatting (bool)
validate (bool): see :meth:`create`
kwargs: passed through to :meth:`_create`, eg ``blobs``. See :meth:`create`
Returns:
CreationResult: whose content will be a dict with ``id`` and ``url``
keys (all optional) for the updated object (or None)
"""
return self._create(obj, preview=False, update=True, include_link=include_link,
ignore_formatting=ignore_formatting, validate=validate,
**kwargs)
[docs]
def preview_update(self, obj, include_link=OMIT_LINK,
ignore_formatting=False):
"""Preview updating an existing post, reply, like, repost, follow, or block.
Args:
obj: ActivityStreams object
include_link (str)
ignore_formatting (bool)
Returns:
CreationResult: content will be a str HTML snippet or None
"""
return self._create(obj, preview=True, update=True, include_link=include_link,
ignore_formatting=ignore_formatting)
[docs]
def write_record(self, record, rkey=None, validate=True):
"""Creates a new repo record, or updates an existing one in place.
Args:
record (dict): ATProto record to write
rkey (str): optional, the rkey of an existing record to update in place.
If not provided, a new record is created instead.
validate (bool): if False, tells the PDS not to validate the record
against its lexicon
Returns:
dict: ``com.atproto.repo.createRecord`` or ``putRecord`` output, with
``uri`` and ``cid`` keys
"""
input = {
'repo': self.did,
'collection': record['$type'],
'record': record,
}
if not validate:
input['validate'] = False
if rkey:
return self.client.com.atproto.repo.putRecord({**input, 'rkey': rkey})
else:
return self.client.com.atproto.repo.createRecord(input)
def _create(self, obj, preview=None, update=False, include_link=OMIT_LINK,
ignore_formatting=False, validate=None, blobs=None):
assert preview in (False, True)
assert self.did
type = util.get_first(obj, 'objectType')
verb = obj.get('verb')
try:
base_obj = self.base_object(obj, bluesky_only=validate is not False)
except ValueError as e:
e_str = str(e)
return creation_result(abort=True, error_plain=e_str,
error_html=util.linkify(e_str, pretty=True))
base_id = base_obj.get('id')
base_url = base_obj.get('url')
non_bluesky_base = (validate is False and base_obj
and not (base_id or '').startswith(('at://', 'did:')))
if non_bluesky_base:
base_id = base_url = base_id or base_url
is_reply = type == 'comment' or obj.get('inReplyTo')
rkey = None
if update and (id := obj.get('id')):
if not ((uri_match := AT_URI_RE.fullmatch(id))
and (rkey := uri_match['rkey'])):
msg = f'Expected full at:// URI in id, got {id}'
return creation_result(abort=True, error_plain=msg)
elif uri_match['repo'] != self.did:
msg = f"Logged in user {self.did} can't update {uri_match['repo']}",
return creation_result(abort=True, error_plain=msg)
atts = obj.get('attachments', [])
images = util.dedupe_urls(util.get_list(obj, 'image') +
[a for a in atts if as1.object_type(a) == 'image'])
# images in other attachments, eg link previews, are uploaded for external
# embed thumbs. kept out of images so that they don't become image embeds
att_images = [img for att in atts
if as1.object_type(att) in ('article', 'link', 'note')
for img in as1.get_objects(att, 'image')]
videos = [a for a in atts if as1.object_type(a) == 'video']
has_media = (images or videos) and (type in ('note', 'article') or is_reply)
# prefer displayName over content for articles
#
# TODO: handle activities as well as objects? ie pull out ['object'] here if
# necessary?
prefer_content = type == 'note' or (base_url and is_reply)
preview_description = ''
content = self._content_for_create(
obj, ignore_formatting=ignore_formatting, prefer_name=not prefer_content)
if not content:
if type == 'activity':
content = verb
elif has_media:
content = ''
else:
return creation_result(
abort=False, # keep looking for things to publish,
error_plain='No content text found.',
error_html='No content text found.')
# truncate and ellipsize content if necessary
url = obj.get('url')
post_label = f"{self.NAME} {self.TYPE_LABELS['post']}"
if type == 'activity' and verb == 'like':
if not base_url:
return creation_result(
abort=True,
error_plain=f"Could not find a {post_label} to {self.TYPE_LABELS['like']}.",
error_html=f"Could not find a {post_label} to <a href=\"http://indiewebcamp.com/like\">{self.TYPE_LABELS['like']}</a>. Check that your post has the right <a href=\"http://indiewebcamp.com/like\">u-like-of link</a>.")
if preview:
verb_label = 'update' if update else self.TYPE_LABELS['like']
preview_description += f"<span class=\"verb\">{verb_label}</span> <a href=\"{base_url}\">this {self.TYPE_LABELS['post']}</a>."
return creation_result(description=preview_description)
result_url = (base_url if non_bluesky_base
else at_uri_to_web_url(base_id) + '/liked-by')
elif type == 'activity' and verb == 'share':
if not base_url:
return creation_result(
abort=True,
error_plain=f"Could not find a {post_label} to {self.TYPE_LABELS['repost']}.",
error_html=f"Could not find a {post_label} to <a href=\"http://indiewebcamp.com/repost\">{self.TYPE_LABELS['repost']}</a>. Check that your post has the right <a href=\"http://indiewebcamp.com/repost\">repost-of</a> link.")
if preview:
verb_label = 'update' if update else self.TYPE_LABELS['repost']
preview_description += f"<span class=\"verb\">{verb_label}</span> <a href=\"{base_url}\">this {self.TYPE_LABELS['post']}</a>."
return creation_result(description=preview_description)
result_url = (base_url if non_bluesky_base
else at_uri_to_web_url(base_id) + '/reposted-by')
elif type == 'activity' and verb == 'follow':
if not base_id:
return creation_result(
abort=True,
error_plain=f"Could not find a user to follow.",
error_html=f"Could not find a user to <a href=\"http://indiewebcamp.com/follow\">follow</a>. Check that your post has the right <a href=\"http://indiewebcamp.com/follow\">u-follow-of link</a>.")
if preview:
verb_label = 'update' if update else 'follow'
preview_description += f"<span class=\"verb\">{verb_label}</span> <a href=\"{base_url}\">this user</a>."
return creation_result(description=preview_description)
result_url = base_url if non_bluesky_base else base_url + '/followers'
elif type == 'activity' and verb == 'block':
if not base_id:
return creation_result(
abort=True,
error_plain=f"Could not find a user to block.",
error_html=f"Could not find a user to <a href=\"http://indiewebcamp.com/block\">block</a>. Check that your post has the right <a href=\"http://indiewebcamp.com/block\">u-block-of link</a>.")
if preview:
verb_label = 'update' if update else 'block'
preview_description += f"<span class=\"verb\">{verb_label}</span> <a href=\"{base_url}\">this user</a>."
return creation_result(description=preview_description)
result_url = base_url
elif (type in as1.POST_TYPES or is_reply or
(type == 'activity' and verb == 'post')): # probably a bookmark
# TODO: add bookmarked URL and facet
# tricky because we only want to do that if it's not truncated away
content = self.truncate(content, url, include_link=include_link, type='note')
# TODO linkify mentions and hashtags
preview_content = util.linkify(content, pretty=True, skip_bare_cc_tlds=True)
data = {'status': content}
if update:
preview_description += '<span class="verb">update</span>:'
elif is_reply and base_url:
preview_description += f"<span class=\"verb\">{self.TYPE_LABELS['comment']}</span> to <a href=\"{base_url}\">this {self.TYPE_LABELS['post']}</a>:"
data['in_reply_to_id'] = base_id
else:
preview_description += f"<span class=\"verb\">{self.TYPE_LABELS['post']}</span>:"
max_images = LEXRPC.defs['app.bsky.embed.images']['properties']['images']['maxLength']
if len(images) > max_images:
images = images[:max_images]
logger.warning(f'Found {len(images)} images! Only using the first {max_images}: {images!r}')
if preview:
media_previews = [
f"<img src=\"{util.get_url(img)}\" alt=\"{util.parse_html(img.get('displayName') or '').get_text(' ', strip=True)}\" />"
for img in images
]
if media_previews:
preview_content += '<br /><br />' + ' '.join(media_previews)
return creation_result(content=preview_content,
description=preview_description)
else:
blobs, aspects = self.upload_media(images, existing=blobs)
# external embed thumbs are best effort. if a thumbnail image can't be
# fetched or is too big, post without it instead of failing
max_thumb = LEXRPC.defs['app.bsky.embed.external#external']['properties']['thumb']['maxSize']
try:
blobs, _ = self.upload_media(att_images, existing=blobs, max_size=max_thumb)
except (requests.RequestException, ValueError) as e:
logger.warning(f'Skipping attachment image for embed thumb: {e}')
post_atp = from_as1(obj, blobs=blobs, aspects=aspects, client=self,
validate=validate)
post_atp['text'] = content
# facet for link to original post, if any
if url:
url_index = content.rfind(url)
if url_index != -1:
byte_start = len(content[:url_index].encode())
post_atp.setdefault('facets', []).append({
'$type': 'app.bsky.richtext.facet',
'features': [{
'$type': 'app.bsky.richtext.facet#link',
'uri': url,
}],
'index': {
'byteStart': byte_start,
'byteEnd': byte_start + len(url.encode()),
},
})
result = self.write_record(post_atp, rkey=rkey,
validate=validate is not False)
return creation_result({
'id': result['uri'],
'url': at_uri_to_web_url(result['uri'], handle=self.handle),
})
else:
return creation_result(
abort=False,
error_plain=f'Cannot publish type={type}, verb={verb} to Bluesky',
error_html=f'Cannot publish type={type}, verb={verb} to Bluesky')
result = self.write_record(from_as1(obj, client=self, validate=validate),
rkey=rkey, validate=validate is not False)
return creation_result({
'id': result['uri'],
'url': result_url,
})
[docs]
def delete(self, at_uri):
"""Deletes a record.
Args:
at_uri (str): at:// URI of record delete
Returns:
CreationResult: content is dict with ``url`` and ``id`` fields
"""
match = AT_URI_RE.fullmatch(at_uri)
if not match:
raise ValueError(f'Expected at:// URI, got {at_uri}')
self.client.com.atproto.repo.deleteRecord({
'repo': match['repo'],
'collection': match['collection'],
'rkey': match['rkey'],
})
return creation_result({
'id': at_uri,
'url': at_uri_to_web_url(at_uri),
})
[docs]
def preview_delete(self, at_uri):
"""Previews deleting a record.
Args:
at_uri (str): at:// URI of record delete
Returns:
CreationResult:
"""
url = at_uri_to_web_url(at_uri)
return creation_result(description=f'<span class="verb">delete</span> <a href="{url}">this</a>.')
[docs]
@classmethod
def base_object(cls, obj, bluesky_only=True):
"""Wraps :meth:`Source.base_object` and infers ``id`` and/or ``url``.
TODO: unify with :meth:`Source.base_object`, probably with a ``new
normalize_url`` or similar function that determines if a URL is on this source.
maybe with :class:`util.UrlCanonicalizer`?
Args:
obj (dict): AS1 object or activity
bluesky_only (bool): if False, and none of the base objects are on
Bluesky/ATProto, returns the first non-Bluesky base object instead of
raising ``ValueError``
Raises:
ValueError: if no ATProto base object is found and ``bluesky_only`` is True
"""
for field in ('inReplyTo', 'object', 'target'):
if not (bases := as1.get_objects(obj, field)):
continue
non_bluesky = []
for base in bases:
if as1.object_type(base) == 'bookmark':
# awkward. TODO: clean up. see test_create_bookmark in test_bluesky.py
return {}
if not (ids := util.get_list(base, 'id') + util.get_list(base, 'url')):
continue
base = copy.deepcopy(base)
for id in ids:
if id.startswith(('https://bsky.app/', 'https://sprk.so/')):
base.setdefault('id', web_url_to_at_uri(id))
base.setdefault('url', id)
return base
elif id.startswith('at://'):
base.setdefault('id', id)
base.setdefault('url', at_uri_to_web_url(id))
return base
elif id.startswith('did:'):
base.setdefault('id', id)
base.setdefault('url', Bluesky.user_url(id))
return base
non_bluesky.append(base)
if non_bluesky and not bluesky_only:
return non_bluesky[0]
raise ValueError(f"{field} {non_bluesky} doesn't look like Bluesky/ATProto")
return {}
[docs]
def truncate(self, *args, type=None, **kwargs):
"""Thin wrapper around :meth:`Source.truncate` that sets default kwargs."""
if type == 'dm':
length = LEXRPC.defs['chat.bsky.convo.defs#messageInput']['properties']['text']['maxGraphemes']
elif type in as1.ACTOR_TYPES:
length = LEXRPC.defs['app.bsky.actor.profile']['record']['properties']['description']['maxGraphemes']
elif type in POST_TYPES:
length = LEXRPC.defs['app.bsky.feed.post']['record']['properties']['text']['maxGraphemes']
else:
assert False, f'unexpected type {type}'
kwargs = {
'include_link': INCLUDE_LINK,
'target_length': length,
'link_length': None,
'ellipsis': ' […]',
**kwargs,
}
return super().truncate(*args, **kwargs)