ids.translate_* noop refactoring: from_proto => from_, to_proto => to

pull/968/head
Ryan Barrett 2024-04-20 21:03:06 -07:00
rodzic 7c34689c9f
commit 0c37d94191
Nie znaleziono w bazie danych klucza dla tego podpisu
ID klucza GPG: 6BE31FDF4776E9D4
5 zmienionych plików z 69 dodań i 70 usunięć

94
ids.py
Wyświetl plik

@ -53,30 +53,30 @@ def web_ap_base_domain(user_domain):
return f'https://{subdomain}{SUPERDOMAIN}/'
def translate_user_id(*, id, from_proto, to_proto):
def translate_user_id(*, id, from_, to):
"""Translate a user id from one protocol to another.
TODO: unify with :func:`translate_object_id`.
Args:
id (str)
from_proto (protocol.Protocol)
to_proto (protocol.Protocol)
from_ (protocol.Protocol)
to (protocol.Protocol)
Returns:
str: the corresponding id in ``to_proto``
str: the corresponding id in ``to``
"""
assert id and from_proto and to_proto, (id, from_proto, to_proto)
assert from_proto.owns_id(id) is not False or from_proto.LABEL == 'ui', \
(id, from_proto.LABEL, to_proto.LABEL)
assert id and from_ and to, (id, from_, to)
assert from_.owns_id(id) is not False or from_.LABEL == 'ui', \
(id, from_.LABEL, to.LABEL)
parsed = urlparse(id)
if from_proto.LABEL == 'web' and parsed.path.strip('/') == '':
if from_.LABEL == 'web' and parsed.path.strip('/') == '':
# home page; replace with domain
id = parsed.netloc
# bsky.app profile URL to DID
if to_proto.LABEL == 'atproto':
if to.LABEL == 'atproto':
if match := BSKY_APP_URL_RE.match(id):
repo = match.group('id')
if repo.startswith('did:'):
@ -89,25 +89,25 @@ def translate_user_id(*, id, from_proto, to_proto):
logger.warning(e)
return None
if from_proto == to_proto:
if from_ == to:
return id
# follow use_instead
user = from_proto.get_by_id(id)
user = from_.get_by_id(id)
if user:
id = user.key.id()
if from_proto.LABEL in COPIES_PROTOCOLS or to_proto.LABEL in COPIES_PROTOCOLS:
if from_.LABEL in COPIES_PROTOCOLS or to.LABEL in COPIES_PROTOCOLS:
if user:
if copy := user.get_copy(to_proto):
if copy := user.get_copy(to):
return copy
if orig := models.get_original(id):
if isinstance(orig, to_proto):
if isinstance(orig, to):
return orig.key.id()
match from_proto.LABEL, to_proto.LABEL:
match from_.LABEL, to.LABEL:
case _, 'atproto' | 'nostr':
logger.warning(f"Can't translate user id {id} to {to_proto.LABEL} , haven't copied it there yet!")
logger.warning(f"Can't translate user id {id} to {to.LABEL} , haven't copied it there yet!")
return None
case 'web', 'activitypub':
@ -117,45 +117,45 @@ def translate_user_id(*, id, from_proto, to_proto):
return id
case _, 'activitypub' | 'web':
return subdomain_wrap(from_proto, f'/{to_proto.ABBREV}/{id}')
return subdomain_wrap(from_, f'/{to.ABBREV}/{id}')
# only for unit tests
case _, 'fake' | 'other' | 'eefake':
return f'{to_proto.LABEL}:u:{id}'
return f'{to.LABEL}:u:{id}'
case 'fake' | 'other', _:
return id
assert False, (id, from_proto.LABEL, to_proto.LABEL)
assert False, (id, from_.LABEL, to.LABEL)
def translate_handle(*, handle, from_proto, to_proto, enhanced):
def translate_handle(*, handle, from_, to, enhanced):
"""Translates a user handle from one protocol to another.
Args:
handle (str)
from_proto (protocol.Protocol)
to_proto (protocol.Protocol)
from_ (protocol.Protocol)
to (protocol.Protocol)
enhanced (bool): whether to convert to an "enhanced" handle based on the
user's domain
Returns:
str: the corresponding handle in ``to_proto``
str: the corresponding handle in ``to``
"""
assert handle and from_proto and to_proto, (handle, from_proto, to_proto)
assert from_proto.owns_handle(handle) is not False or from_proto.LABEL == 'ui'
assert handle and from_ and to, (handle, from_, to)
assert from_.owns_handle(handle) is not False or from_.LABEL == 'ui'
if from_proto == to_proto:
if from_ == to:
return handle
match from_proto.LABEL, to_proto.LABEL:
match from_.LABEL, to.LABEL:
case _, 'activitypub':
domain = handle if enhanced else f'{from_proto.ABBREV}{SUPERDOMAIN}'
domain = handle if enhanced else f'{from_.ABBREV}{SUPERDOMAIN}'
return f'@{handle}@{domain}'
case _, 'atproto' | 'nostr':
handle = handle.lstrip('@').replace('@', '.')
return (handle if enhanced
else f'{handle}.{from_proto.ABBREV}{SUPERDOMAIN}')
else f'{handle}.{from_.ABBREV}{SUPERDOMAIN}')
case 'activitypub', 'web':
user, instance = handle.lstrip('@').split('@')
@ -168,29 +168,29 @@ def translate_handle(*, handle, from_proto, to_proto, enhanced):
# only for unit tests
case _, 'fake' | 'other' | 'eefake':
return f'{to_proto.LABEL}:handle:{handle}'
return f'{to.LABEL}:handle:{handle}'
assert False, (handle, from_proto.LABEL, to_proto.LABEL)
assert False, (handle, from_.LABEL, to.LABEL)
def translate_object_id(*, id, from_proto, to_proto):
def translate_object_id(*, id, from_, to):
"""Translates a user handle from one protocol to another.
TODO: unify with :func:`translate_user_id`.
Args:
id (str)
from_proto (protocol.Protocol)
to_proto (protocol.Protocol)
from_ (protocol.Protocol)
to (protocol.Protocol)
Returns:
str: the corresponding id in ``to_proto``
str: the corresponding id in ``to``
"""
assert id and from_proto and to_proto, (id, from_proto, to_proto)
assert from_proto.owns_id(id) is not False or from_proto.LABEL == 'ui'
assert id and from_ and to, (id, from_, to)
assert from_.owns_id(id) is not False or from_.LABEL == 'ui'
# bsky.app profile URL to DID
if to_proto.LABEL == 'atproto':
if to.LABEL == 'atproto':
if match := BSKY_APP_URL_RE.match(id):
repo = match.group('id')
handle = None
@ -205,29 +205,29 @@ def translate_object_id(*, id, from_proto, to_proto):
return web_url_to_at_uri(id, handle=handle, did=repo)
if from_proto == to_proto:
if from_ == to:
return id
if from_proto.LABEL in COPIES_PROTOCOLS or to_proto.LABEL in COPIES_PROTOCOLS:
if obj := from_proto.load(id, remote=False):
if copy := obj.get_copy(to_proto):
if from_.LABEL in COPIES_PROTOCOLS or to.LABEL in COPIES_PROTOCOLS:
if obj := from_.load(id, remote=False):
if copy := obj.get_copy(to):
return copy
if orig := models.get_original(id):
return orig.key.id()
match from_proto.LABEL, to_proto.LABEL:
match from_.LABEL, to.LABEL:
case _, 'atproto' | 'nostr':
logger.warning(f"Can't translate object id {id} to {to_proto.LABEL} , haven't copied it there yet!")
logger.warning(f"Can't translate object id {id} to {to.LABEL} , haven't copied it there yet!")
return id
case 'web', 'activitypub':
return urljoin(web_ap_base_domain(util.domain_from_link(id)), f'/r/{id}')
case _, 'activitypub' | 'web':
return subdomain_wrap(from_proto, f'/convert/{to_proto.ABBREV}/{id}')
return subdomain_wrap(from_, f'/convert/{to.ABBREV}/{id}')
# only for unit tests
case _, 'fake' | 'other' | 'eefake':
return f'{to_proto.LABEL}:o:{from_proto.ABBREV}:{id}'
return f'{to.LABEL}:o:{from_.ABBREV}:{id}'
assert False, (id, from_proto.LABEL, to_proto.LABEL)
assert False, (id, from_.LABEL, to.LABEL)

Wyświetl plik

@ -395,8 +395,8 @@ class User(StringIdModel, metaclass=ProtocolUserMeta):
if not handle:
return None
return ids.translate_handle(handle=handle, from_proto=self.__class__,
to_proto=to_proto, enhanced=False)
return ids.translate_handle(handle=handle, from_=self.__class__,
to=to_proto, enhanced=False)
def id_as(self, to_proto):
"""Returns this user's id in a different protocol.
@ -410,8 +410,8 @@ class User(StringIdModel, metaclass=ProtocolUserMeta):
if isinstance(to_proto, str):
to_proto = PROTOCOLS[to_proto]
return ids.translate_user_id(id=self.key.id(), from_proto=self.__class__,
to_proto=to_proto)
return ids.translate_user_id(id=self.key.id(), from_=self.__class__,
to=to_proto)
def handle_or_id(self):
"""Returns handle if we know it, otherwise id."""
@ -1077,7 +1077,7 @@ class Object(StringIdModel):
if not proto:
return val
translated = translate_fn(id=orig, from_proto=proto, to_proto=proto)
translated = translate_fn(id=orig, from_=proto, to=proto)
if translated and translated != orig:
logger.info(f'Normalized {proto.LABEL} id {orig} to {translated}')
replaced = True

Wyświetl plik

@ -598,7 +598,7 @@ class Protocol:
# TODO: what if from_cls is None? relax translate_object_id,
# make it a noop if we don't know enough about from/to?
if from_cls and from_cls != to_cls:
elem[field]['id'] = fn(id=id, from_proto=from_cls, to_proto=to_cls)
elem[field]['id'] = fn(id=id, from_=from_cls, to=to_cls)
if elem[field].keys() == {'id'}:
elem[field] = elem[field]['id']

Wyświetl plik

@ -61,7 +61,7 @@ class IdsTest(TestCase):
]:
with self.subTest(from_=from_.LABEL, to=to.LABEL):
self.assertEqual(expected, translate_user_id(
id=id, from_proto=from_, to_proto=to))
id=id, from_=from_, to=to))
def test_translate_user_id_no_copy_did_stored(self):
for proto, id in [
@ -70,8 +70,7 @@ class IdsTest(TestCase):
(Fake, 'fake:user'),
]:
with self.subTest(proto=proto.LABEL):
self.assertIsNone(translate_user_id(
id=id, from_proto=proto, to_proto=ATProto))
self.assertIsNone(translate_user_id(id=id, from_=proto, to=ATProto))
def test_translate_user_id_use_instead(self):
did = Target(uri='did:plc:123', protocol='atproto')
@ -85,18 +84,18 @@ class IdsTest(TestCase):
]:
with self.subTest(proto=proto.LABEL):
self.assertEqual(expected, translate_user_id(
id='www.user.com', from_proto=Web, to_proto=proto))
id='www.user.com', from_=Web, to=proto))
self.assertEqual(expected, translate_user_id(
id='https://www.user.com/', from_proto=Web, to_proto=proto))
id='https://www.user.com/', from_=Web, to=proto))
@patch('ids._FED_SUBDOMAIN_SITES', new={'on-fed.com'})
def test_translate_user_id_web_ap_subdomain_fed(self):
for base_url in ['https://web.brid.gy/', 'https://fed.brid.gy/']:
with app.test_request_context('/', base_url=base_url):
self.assertEqual('https://web.brid.gy/on-web.com', translate_user_id(
id='on-web.com', from_proto=Web, to_proto=ActivityPub))
id='on-web.com', from_=Web, to=ActivityPub))
self.assertEqual('https://fed.brid.gy/on-fed.com', translate_user_id(
id='on-fed.com', from_proto=Web, to_proto=ActivityPub))
id='on-fed.com', from_=Web, to=ActivityPub))
def test_translate_handle(self):
for from_, handle, to, expected in [
@ -123,7 +122,7 @@ class IdsTest(TestCase):
]:
with self.subTest(from_=from_.LABEL, to=to.LABEL):
self.assertEqual(expected, translate_handle(
handle=handle, from_proto=from_, to_proto=to, enhanced=False))
handle=handle, from_=from_, to=to, enhanced=False))
def test_translate_handle_enhanced(self):
for from_, handle, to, expected in [
@ -136,7 +135,7 @@ class IdsTest(TestCase):
]:
with self.subTest(from_=from_.LABEL, to=to.LABEL):
self.assertEqual(expected, translate_handle(
handle=handle, from_proto=from_, to_proto=to, enhanced=True))
handle=handle, from_=from_, to=to, enhanced=True))
def test_translate_object_id(self):
self.store_object(id='http://po.st',
@ -184,16 +183,16 @@ class IdsTest(TestCase):
]:
with self.subTest(from_=from_.LABEL, to=to.LABEL):
self.assertEqual(expected, translate_object_id(
id=id, from_proto=from_, to_proto=to))
id=id, from_=from_, to=to))
@patch('ids._FED_SUBDOMAIN_SITES', new={'on-fed.com'})
def test_translate_object_id_web_ap_subdomain_fed(self):
for base_url in ['https://web.brid.gy/', 'https://fed.brid.gy/']:
with app.test_request_context('/', base_url=base_url):
got = translate_object_id(id='http://on-fed.com/post', from_proto=Web,
to_proto=ActivityPub)
got = translate_object_id(id='http://on-fed.com/post', from_=Web,
to=ActivityPub)
self.assertEqual('https://fed.brid.gy/r/http://on-fed.com/post', got)
got = translate_object_id(id='http://on-web.com/post', from_proto=Web,
to_proto=ActivityPub)
got = translate_object_id(id='http://on-web.com/post', from_=Web,
to=ActivityPub)
self.assertEqual('https://web.brid.gy/r/http://on-web.com/post', got)

6
web.py
Wyświetl plik

@ -172,8 +172,8 @@ class Web(User, Protocol):
if isinstance(to_proto, str):
to_proto = PROTOCOLS[to_proto]
converted = translate_user_id(id=self.key.id(), from_proto=self,
to_proto=to_proto)
converted = translate_user_id(id=self.key.id(), from_=self,
to=to_proto)
if to_proto.LABEL == 'activitypub':
other = 'web' if self.ap_subdomain == 'fed' else 'fed'
@ -397,7 +397,7 @@ class Web(User, Protocol):
return False
source_id = translate_object_id(
id=obj.key.id(), from_proto=PROTOCOLS[obj.source_protocol], to_proto=Web)
id=obj.key.id(), from_=PROTOCOLS[obj.source_protocol], to=Web)
source_url = quote(source_id, safe=':/%+')
logger.info(f'Sending webmention from {source_url} to {url}')