bridgy-fed/follow.py

247 wiersze
9.0 KiB
Python
Czysty Zwykły widok Historia

"""Remote follow handler.
* https://github.com/snarfed/bridgy-fed/issues/60
* https://socialhub.activitypub.rocks/t/what-is-the-current-spec-for-remote-follow/2020
* https://www.rfc-editor.org/rfc/rfc7033
"""
import logging
2024-05-08 00:01:01 +00:00
from flask import redirect, request, session
from granary import as1
from oauth_dropins import indieauth
from oauth_dropins.webutil import util
noop, lint fixes from flake8 remaining: $ flake8 --extend-ignore=E501 *.py tests/*.py "pyflakes" failed during execution due to "'FlakesChecker' object has no attribute 'NAMEDEXPR'" Run flake8 with greater verbosity to see more details activitypub.py:15:1: F401 'oauth_dropins.webutil.util.json_loads' imported but unused activitypub.py:36:1: F401 'web' imported but unused activitypub.py:48:1: E302 expected 2 blank lines, found 1 activitypub.py:51:9: F811 redefinition of unused 'web' from line 36 app.py:6:1: F401 'flask_app.app' imported but unused app.py:9:1: F401 'activitypub' imported but unused app.py:9:1: F401 'convert' imported but unused app.py:9:1: F401 'follow' imported but unused app.py:9:1: F401 'pages' imported but unused app.py:9:1: F401 'redirect' imported but unused app.py:9:1: F401 'superfeedr' imported but unused app.py:9:1: F401 'ui' imported but unused app.py:9:1: F401 'webfinger' imported but unused app.py:9:1: F401 'web' imported but unused app.py:9:1: F401 'xrpc_actor' imported but unused app.py:9:1: F401 'xrpc_feed' imported but unused app.py:9:1: F401 'xrpc_graph' imported but unused app.py:9:19: E401 multiple imports on one line models.py:19:1: F401 'oauth_dropins.webutil.util.json_loads' imported but unused models.py:364:31: E114 indentation is not a multiple of four (comment) models.py:364:31: E116 unexpected indentation (comment) protocol.py:17:1: F401 'oauth_dropins.webutil.util.json_loads' imported but unused redirect.py:26:1: F401 'oauth_dropins.webutil.util.json_loads' imported but unused web.py:18:1: F401 'oauth_dropins.webutil.util.json_loads' imported but unused webfinger.py:13:1: F401 'oauth_dropins.webutil.util.json_loads' imported but unused webfinger.py:110:13: E122 continuation line missing indentation or outdented webfinger.py:111:13: E122 continuation line missing indentation or outdented webfinger.py:131:13: E122 continuation line missing indentation or outdented webfinger.py:132:13: E122 continuation line missing indentation or outdented webfinger.py:133:13: E122 continuation line missing indentation or outdented webfinger.py:134:13: E122 continuation line missing indentation or outdented tests/__init__.py:2:1: F401 'oauth_dropins.webutil.tests' imported but unused tests/test_follow.py:11:1: F401 'oauth_dropins.webutil.util.json_dumps' imported but unused tests/test_follow.py:14:1: F401 '.testutil.Fake' imported but unused tests/test_models.py:156:15: E122 continuation line missing indentation or outdented tests/test_models.py:157:15: E122 continuation line missing indentation or outdented tests/test_models.py:158:11: E122 continuation line missing indentation or outdented tests/test_web.py:12:1: F401 'oauth_dropins.webutil.util.json_dumps' imported but unused tests/test_web.py:17:1: F401 '.testutil' imported but unused tests/test_web.py:1513:13: E128 continuation line under-indented for visual indent tests/test_web.py:1514:9: E124 closing bracket does not match visual indentation tests/testutil.py:106:1: E402 module level import not at top of file tests/testutil.py:107:1: E402 module level import not at top of file tests/testutil.py:108:1: E402 module level import not at top of file tests/testutil.py:109:1: E402 module level import not at top of file tests/testutil.py:110:1: E402 module level import not at top of file tests/testutil.py:301:24: E203 whitespace before ':' tests/testutil.py:301:25: E701 multiple statements on one line (colon) tests/testutil.py:301:25: E231 missing whitespace after ':'
2023-06-20 18:22:54 +00:00
from oauth_dropins.webutil.flask_util import error, flash
from activitypub import ActivityPub
from flask_app import app
import common
from models import Follower, Object, PROTOCOLS
from protocol import Protocol
from web import Web
import webfinger
logger = logging.getLogger(__name__)
@app.post('/remote-follow')
def remote_follow():
"""Discovers and redirects to a remote follow page for a given user."""
logger.info(f'Got: {request.values}')
cls = PROTOCOLS.get(request.values['protocol'])
if not cls:
error(f'Unknown protocol {request.values["protocol"]}')
domain = request.values['domain']
user = cls.get_by_id(domain)
if not user:
error(f'No web user found for domain {domain}')
addr = request.values['address']
resp = webfinger.fetch(addr)
if resp is None:
return redirect(user.user_page_path())
for link in resp.get('links', []):
if link.get('rel') == webfinger.SUBSCRIBE_LINK_REL:
template = link.get('template')
if template and '{uri}' in template:
return redirect(template.replace('{uri}', user.handle_as(ActivityPub)))
flash(f"Couldn't find remote follow link for {addr}")
return redirect(user.user_page_path())
class FollowStart(indieauth.Start):
"""Starts the IndieAuth flow to add a follower to an existing user."""
def dispatch_request(self):
logger.info(f'Got: {request.values}')
address = request.form['address']
me = request.form['me']
session_me = session.get('indieauthed-me')
if session_me:
logger.info(f'found indieauthed-me: {session_me} in session cookie')
if session_me == me:
logger.info(' skipping IndieAuth')
return FollowCallback('-').finish(indieauth.IndieAuth(id=me), address)
try:
return redirect(self.redirect_url(state=address))
except Exception as e:
if util.is_connection_failure(e) or util.interpret_http_exception(e)[0]:
flash(f"Couldn't fetch your web site: {e}")
domain = util.domain_from_link(me)
return redirect(f'/web/{domain}/following?address={address}')
raise
class FollowCallback(indieauth.Callback):
"""IndieAuth callback to add a follower to an existing user."""
def finish(self, auth_entity, state=None):
if not auth_entity:
return
me = auth_entity.key.id()
logger.info(f'Storing indieauthed-me: {me} in session cookie')
session['indieauthed-me'] = me
domain = util.domain_from_link(me)
# Web is hard-coded here since this is IndieAuth
user = Web.get_by_id(domain)
if not user:
error(f'No web user for domain {domain}')
if not state:
error('Missing state')
addr = state
if util.is_web(addr):
as2_url = addr
else: # it's an @-@ handle
# if ActivityPub.owns_handle(addr) is False:
# flash(f"{addr} isn't a native fediverse account")
# return redirect(user.user_page_path('following'))
as2_url = webfinger.fetch_actor_url(addr)
if util.domain_or_parent_in(util.domain_from_link(as2_url), common.DOMAINS):
proto = Protocol.for_id(as2_url)
flash(f"{addr} is a bridged account. Try following them on {proto.PHRASE}!")
return redirect(user.user_page_path('following'))
elif ActivityPub.owns_id(as2_url) is False:
flash(f"{addr} isn't a native fediverse account")
return redirect(user.user_page_path('following'))
# TODO(#512): follower will always be Web here, but we should generalize
# followee support in UI and here across protocols
followee = ActivityPub.load(as2_url)
if not followee:
flash(f"Couldn't load {as2_url} as AS2")
return redirect(user.user_page_path('following'))
followee_id = followee.as1.get('id')
timestamp = util.now().replace(microsecond=0, tzinfo=None).isoformat()
follow_id = f'{user.web_url()}#follow-{timestamp}-{addr}'
follow_as1 = {
'objectType': 'activity',
'verb': 'follow',
'id': follow_id,
'actor': user.key.id(),
'object': followee_id,
}
followee_user = ActivityPub.get_or_create(followee_id, obj=followee)
follow_obj = Object(id=follow_id, our_as1=follow_as1, source_protocol='ui',
labels=['user'])
resp = Web.receive(follow_obj, authed_as=domain, internal=True)
logger.info(f'Web.receive returned {resp}')
follow_obj = follow_obj.key.get()
follow_obj.source_protocol = 'ui'
follow_obj.put()
url = as1.get_url(followee.as1) or followee_id
link = common.pretty_link(url, text=addr)
flash(f'Followed {link}.')
return redirect(user.user_page_path('following'))
class UnfollowStart(indieauth.Start):
"""Starts the IndieAuth flow to remove a follower from an existing user."""
def dispatch_request(self):
logger.info(f'Got: {request.values}')
key = request.form['key']
me = request.form['me']
session_me = session.get('indieauthed-me')
if session_me:
logger.info(f'has IndieAuth session for {session_me}')
if session_me == me:
return UnfollowCallback('-').finish(indieauth.IndieAuth(id=me), key)
try:
return redirect(self.redirect_url(state=key))
except Exception as e:
if util.is_connection_failure(e) or util.interpret_http_exception(e)[0]:
flash(f"Couldn't fetch your web site: {e}")
domain = util.domain_from_link(me)
return redirect(f'/web/{domain}/following')
raise
class UnfollowCallback(indieauth.Callback):
"""IndieAuth callback to remove a follower."""
def finish(self, auth_entity, state=None):
if not auth_entity:
return
me = auth_entity.key.id()
# store login in a session cookie
session['indieauthed-me'] = me
domain = util.domain_from_link(me)
# Web is hard-coded here since this is IndieAuth
user = Web.get_by_id(domain)
if not user:
error(f'No web user for domain {domain}')
if util.is_int(state):
state = int(state)
follower = Follower.get_by_id(state)
if not follower:
error(f'Bad state {state}')
followee_id = follower.to.id()
followee = follower.to.get()
if not followee.obj or not followee.obj.as1:
# fetch to get full followee so we can find its target to deliver to
followee.obj = ActivityPub.load(followee_id)
if not followee.obj:
error("Couldn't load {followee_id} as AS2")
followee.put()
# TODO(#529): generalize
timestamp = util.now().replace(microsecond=0, tzinfo=None).isoformat()
unfollow_id = f'{user.web_url()}#unfollow-{timestamp}-{followee_id}'
unfollow_as1 = {
'objectType': 'activity',
'verb': 'stop-following',
'id': unfollow_id,
'actor': user.key.id(),
'object': followee.key.id(),
}
# don't include the followee User who's being unfollowed in the users
# property, since we don't want to notify or show them. (standard social
# network etiquette.)
follow_obj = Object(id=unfollow_id, users=[user.key], labels=['user'],
source_protocol='ui', our_as1=unfollow_as1)
resp = Web.receive(follow_obj, authed_as=domain, internal=True)
follower.status = 'inactive'
follower.put()
follow_obj = follow_obj.key.get()
follow_obj.source_protocol = 'ui'
follow_obj.put()
link = common.pretty_link(as1.get_url(followee.obj.as1) or followee_id)
flash(f'Unfollowed {link}.')
return redirect(user.user_page_path('following'))
app.add_url_rule('/follow/start',
view_func=FollowStart.as_view('follow_start', '/follow/callback'),
methods=['POST'])
app.add_url_rule('/follow/callback',
view_func=FollowCallback.as_view('follow_callback', 'unused'),
methods=['GET'])
app.add_url_rule('/unfollow/start',
view_func=UnfollowStart.as_view('unfollow_start', '/unfollow/callback'),
methods=['POST'])
app.add_url_rule('/unfollow/callback',
view_func=UnfollowCallback.as_view('unfollow_callback', 'unused'),
methods=['GET'])