epicyon/follow.py

1451 lines
54 KiB
Python
Raw Normal View History

2020-04-03 11:38:44 +00:00
__filename__ = "follow.py"
__author__ = "Bob Mottram"
__license__ = "AGPL3+"
2021-01-26 10:07:42 +00:00
__version__ = "1.2.0"
2020-04-03 11:38:44 +00:00
__maintainer__ = "Bob Mottram"
2021-09-10 16:14:50 +00:00
__email__ = "bob@libreserver.org"
2020-04-03 11:38:44 +00:00
__status__ = "Production"
2021-06-15 15:08:12 +00:00
__module_group__ = "ActivityPub"
2020-04-03 11:38:44 +00:00
2019-06-29 18:23:13 +00:00
from pprint import pprint
import os
2021-12-26 15:54:46 +00:00
from utils import has_object_string_object
2021-12-26 17:12:07 +00:00
from utils import has_object_stringType
2021-12-26 18:17:37 +00:00
from utils import remove_domain_port
2021-12-26 12:19:00 +00:00
from utils import has_users_path
2021-12-26 12:45:03 +00:00
from utils import get_full_domain
2021-12-27 13:58:17 +00:00
from utils import get_followers_list
2021-12-28 14:41:10 +00:00
from utils import valid_nickname
2021-12-27 18:28:26 +00:00
from utils import domain_permitted
2021-12-27 19:05:25 +00:00
from utils import get_domain_from_actor
2021-12-27 22:19:18 +00:00
from utils import get_nickname_from_actor
2021-12-27 17:42:35 +00:00
from utils import get_status_number
2021-12-27 17:08:19 +00:00
from utils import follow_person
2021-12-29 21:55:09 +00:00
from posts import send_signed_json
from posts import get_person_box
2021-12-26 15:13:34 +00:00
from utils import load_json
2021-12-26 14:47:21 +00:00
from utils import save_json
2021-12-26 18:46:43 +00:00
from utils import is_account_dir
2021-12-26 12:24:40 +00:00
from utils import get_user_paths
2021-12-26 12:02:29 +00:00
from utils import acct_dir
2021-12-26 17:53:07 +00:00
from utils import has_group_type
2021-12-26 10:19:59 +00:00
from utils import local_actor_url
2021-12-29 21:55:09 +00:00
from acceptreject import create_accept
from acceptreject import create_reject
from webfinger import webfinger_handle
2021-12-28 21:36:27 +00:00
from auth import create_basic_auth_header
2021-12-29 21:55:09 +00:00
from session import get_json
from session import post_json
2019-06-29 18:23:13 +00:00
2020-04-03 11:38:44 +00:00
2021-12-28 20:32:11 +00:00
def create_initial_last_seen(base_dir: str, http_prefix: str) -> None:
2021-06-07 08:59:43 +00:00
"""Creates initial lastseen files for all follows.
The lastseen files are used to generate the Zzz icons on
follows/following lists on the profile screen.
2020-12-13 22:01:10 +00:00
"""
2021-12-25 16:17:53 +00:00
for subdir, dirs, files in os.walk(base_dir + '/accounts'):
2020-12-13 22:01:10 +00:00
for acct in dirs:
2021-12-26 18:46:43 +00:00
if not is_account_dir(acct):
2020-12-13 22:01:10 +00:00
continue
2021-12-25 16:17:53 +00:00
accountDir = os.path.join(base_dir + '/accounts', acct)
2020-12-13 22:01:10 +00:00
followingFilename = accountDir + '/following.txt'
if not os.path.isfile(followingFilename):
continue
lastSeenDir = accountDir + '/lastseen'
if not os.path.isdir(lastSeenDir):
os.mkdir(lastSeenDir)
2021-11-26 14:35:26 +00:00
followingHandles = []
try:
with open(followingFilename, 'r') as fp:
followingHandles = fp.readlines()
except OSError:
2021-12-28 20:32:11 +00:00
print('EX: create_initial_last_seen ' + followingFilename)
2021-11-26 14:35:26 +00:00
for handle in followingHandles:
if '#' in handle:
continue
if '@' not in handle:
continue
handle = handle.replace('\n', '')
nickname = handle.split('@')[0]
domain = handle.split('@')[1]
if nickname.startswith('!'):
nickname = nickname[1:]
2021-12-26 10:19:59 +00:00
actor = local_actor_url(http_prefix, nickname, domain)
2021-11-26 14:35:26 +00:00
lastSeenFilename = \
lastSeenDir + '/' + actor.replace('/', '#') + '.txt'
if not os.path.isfile(lastSeenFilename):
try:
with open(lastSeenFilename, 'w+') as fp:
fp.write(str(100))
2021-11-26 14:35:26 +00:00
except OSError:
2021-12-28 20:32:11 +00:00
print('EX: create_initial_last_seen 2 ' +
2021-11-26 14:35:26 +00:00
lastSeenFilename)
2020-12-13 22:01:10 +00:00
break
2021-12-29 21:55:09 +00:00
def _pre_approved_follower(base_dir: str,
nickname: str, domain: str,
approveHandle: str) -> bool:
2019-12-31 09:23:41 +00:00
"""Is the given handle an already manually approved follower?
"""
2020-04-03 11:38:44 +00:00
handle = nickname + '@' + domain
2021-12-25 16:17:53 +00:00
accountDir = base_dir + '/accounts/' + handle
2020-04-03 11:38:44 +00:00
approvedFilename = accountDir + '/approved.txt'
2019-12-31 09:23:41 +00:00
if os.path.isfile(approvedFilename):
if approveHandle in open(approvedFilename).read():
return True
return False
2020-04-03 11:38:44 +00:00
2021-12-29 21:55:09 +00:00
def _remove_from_follow_base(base_dir: str,
nickname: str, domain: str,
acceptOrDenyHandle: str, followFile: str,
debug: bool) -> None:
"""Removes a handle/actor from follow requests or rejects file
2019-09-18 17:04:19 +00:00
"""
2020-04-03 11:38:44 +00:00
handle = nickname + '@' + domain
2021-12-25 16:17:53 +00:00
accountsDir = base_dir + '/accounts/' + handle
2020-04-03 11:38:44 +00:00
approveFollowsFilename = accountsDir + '/' + followFile + '.txt'
2019-09-18 17:04:19 +00:00
if not os.path.isfile(approveFollowsFilename):
if debug:
2020-04-03 11:38:44 +00:00
print('WARN: Approve follow requests file ' +
approveFollowsFilename + ' not found')
2019-09-18 17:04:19 +00:00
return
acceptDenyActor = None
2019-10-06 09:48:37 +00:00
if acceptOrDenyHandle not in open(approveFollowsFilename).read():
# is this stored in the file as an actor rather than a handle?
acceptDenyNickname = acceptOrDenyHandle.split('@')[0]
acceptDenyDomain = acceptOrDenyHandle.split('@')[1]
# for each possible users path construct an actor and
# check if it exists in teh file
2021-12-26 12:24:40 +00:00
usersPaths = get_user_paths()
actorFound = False
for usersName in usersPaths:
acceptDenyActor = \
'://' + acceptDenyDomain + usersName + acceptDenyNickname
if acceptDenyActor in open(approveFollowsFilename).read():
actorFound = True
break
if not actorFound:
return
2021-11-26 14:35:26 +00:00
try:
with open(approveFollowsFilename + '.new', 'w+') as approvefilenew:
with open(approveFollowsFilename, 'r') as approvefile:
if not acceptDenyActor:
for approveHandle in approvefile:
if not approveHandle.startswith(acceptOrDenyHandle):
approvefilenew.write(approveHandle)
else:
for approveHandle in approvefile:
if acceptDenyActor not in approveHandle:
approvefilenew.write(approveHandle)
2021-12-25 15:28:52 +00:00
except OSError as ex:
2021-12-29 21:55:09 +00:00
print('EX: _remove_from_follow_base ' +
2021-12-25 15:28:52 +00:00
approveFollowsFilename + ' ' + str(ex))
2021-06-22 12:27:10 +00:00
2020-04-03 11:38:44 +00:00
os.rename(approveFollowsFilename + '.new', approveFollowsFilename)
2019-09-18 17:04:19 +00:00
2021-12-29 21:55:09 +00:00
def remove_from_follow_requests(base_dir: str,
nickname: str, domain: str,
denyHandle: str, debug: bool) -> None:
2019-10-06 09:48:37 +00:00
"""Removes a handle from follow requests
"""
2021-12-29 21:55:09 +00:00
_remove_from_follow_base(base_dir, nickname, domain,
denyHandle, 'followrequests', debug)
2019-10-06 09:48:37 +00:00
2020-04-03 11:38:44 +00:00
2021-12-29 21:55:09 +00:00
def _remove_from_follow_rejects(base_dir: str,
nickname: str, domain: str,
acceptHandle: str, debug: bool) -> None:
2019-10-06 09:48:37 +00:00
"""Removes a handle from follow rejects
"""
2021-12-29 21:55:09 +00:00
_remove_from_follow_base(base_dir, nickname, domain,
acceptHandle, 'followrejects', debug)
2020-04-03 11:38:44 +00:00
2019-10-06 09:48:37 +00:00
2021-12-28 20:32:11 +00:00
def is_following_actor(base_dir: str,
nickname: str, domain: str, actor: str) -> bool:
2020-07-14 09:09:33 +00:00
"""Is the given nickname following the given actor?
The actor can also be a handle: nickname@domain
2019-07-29 19:46:30 +00:00
"""
2021-12-26 18:17:37 +00:00
domain = remove_domain_port(domain)
2020-04-03 11:38:44 +00:00
handle = nickname + '@' + domain
2021-12-25 16:17:53 +00:00
if not os.path.isdir(base_dir + '/accounts/' + handle):
2019-07-29 19:46:30 +00:00
return False
2021-12-25 16:17:53 +00:00
followingFile = base_dir + '/accounts/' + handle + '/following.txt'
2019-08-31 12:25:42 +00:00
if not os.path.isfile(followingFile):
2019-07-29 19:46:30 +00:00
return False
2020-07-14 20:55:47 +00:00
if actor.lower() in open(followingFile).read().lower():
2019-07-29 19:46:30 +00:00
return True
2021-12-27 22:19:18 +00:00
followingNickname = get_nickname_from_actor(actor)
2019-09-02 09:43:43 +00:00
if not followingNickname:
2020-04-03 11:38:44 +00:00
print('WARN: unable to find nickname in ' + actor)
2019-09-02 09:43:43 +00:00
return False
2021-12-27 19:05:25 +00:00
followingDomain, followingPort = get_domain_from_actor(actor)
2020-12-16 10:30:54 +00:00
followingHandle = \
2021-12-26 12:45:03 +00:00
get_full_domain(followingNickname + '@' + followingDomain,
followingPort)
2020-07-14 20:55:47 +00:00
if followingHandle.lower() in open(followingFile).read().lower():
2019-07-29 19:46:30 +00:00
return True
return False
2020-04-03 11:38:44 +00:00
2021-12-29 21:55:09 +00:00
def get_mutuals_of_person(base_dir: str,
nickname: str, domain: str) -> []:
2020-01-13 16:06:31 +00:00
"""Returns the mutuals of a person
i.e. accounts which they follow and which also follow back
"""
2020-04-03 11:38:44 +00:00
followers = \
2021-12-27 13:58:17 +00:00
get_followers_list(base_dir, nickname, domain, 'followers.txt')
2020-04-03 11:38:44 +00:00
following = \
2021-12-27 13:58:17 +00:00
get_followers_list(base_dir, nickname, domain, 'following.txt')
2020-04-03 11:38:44 +00:00
mutuals = []
2020-01-13 16:06:31 +00:00
for handle in following:
if handle in followers:
mutuals.append(handle)
return mutuals
2020-04-03 11:38:44 +00:00
2021-12-29 21:55:09 +00:00
def add_follower_of_person(base_dir: str, nickname: str, domain: str,
followerNickname: str, followerDomain: str,
federation_list: [], debug: bool,
group_account: bool) -> bool:
"""Adds a follower of the given person
"""
2021-12-27 17:08:19 +00:00
return follow_person(base_dir, nickname, domain,
followerNickname, followerDomain,
federation_list, debug, group_account,
'followers.txt')
2020-04-03 11:38:44 +00:00
2019-06-29 18:23:13 +00:00
2021-12-29 21:55:09 +00:00
def get_follower_domains(base_dir: str, nickname: str, domain: str) -> []:
"""Returns a list of domains for followers
"""
2021-12-26 18:17:37 +00:00
domain = remove_domain_port(domain)
2021-12-26 12:02:29 +00:00
followersFile = acct_dir(base_dir, nickname, domain) + '/followers.txt'
if not os.path.isfile(followersFile):
return []
lines = []
2021-11-26 14:35:26 +00:00
try:
with open(followersFile, 'r') as fpFollowers:
lines = fpFollowers.readlines()
except OSError:
2021-12-29 21:55:09 +00:00
print('EX: get_follower_domains ' + followersFile)
domainsList = []
for handle in lines:
2021-11-08 18:35:14 +00:00
handle = handle.replace('\n', '')
2021-12-27 19:05:25 +00:00
followerDomain, _ = get_domain_from_actor(handle)
if not followerDomain:
continue
if followerDomain not in domainsList:
domainsList.append(followerDomain)
return domainsList
2021-12-29 21:55:09 +00:00
def is_follower_of_person(base_dir: str, nickname: str, domain: str,
followerNickname: str, followerDomain: str) -> bool:
2019-08-31 15:17:07 +00:00
"""is the given nickname a follower of followerNickname?
"""
2021-09-13 13:41:29 +00:00
if not followerDomain:
print('No followerDomain')
return False
if not followerNickname:
print('No followerNickname for ' + followerDomain)
return False
2021-12-26 18:17:37 +00:00
domain = remove_domain_port(domain)
2021-12-26 12:02:29 +00:00
followersFile = acct_dir(base_dir, nickname, domain) + '/followers.txt'
2019-08-31 15:17:07 +00:00
if not os.path.isfile(followersFile):
return False
2020-04-03 11:38:44 +00:00
handle = followerNickname + '@' + followerDomain
alreadyFollowing = False
followersStr = ''
2021-11-26 14:35:26 +00:00
try:
with open(followersFile, 'r') as fpFollowers:
followersStr = fpFollowers.read()
except OSError:
2021-12-29 21:55:09 +00:00
print('EX: is_follower_of_person ' + followersFile)
if handle in followersStr:
alreadyFollowing = True
2021-07-03 17:51:58 +00:00
else:
2021-12-26 12:24:40 +00:00
paths = get_user_paths()
2021-07-03 17:51:58 +00:00
for userPath in paths:
url = '://' + followerDomain + userPath + followerNickname
if url in followersStr:
alreadyFollowing = True
break
2020-10-24 11:11:14 +00:00
return alreadyFollowing
2019-08-31 15:17:07 +00:00
2020-04-03 11:38:44 +00:00
2021-12-28 20:32:11 +00:00
def unfollow_account(base_dir: str, nickname: str, domain: str,
followNickname: str, followDomain: str,
debug: bool, group_account: bool,
followFile: str = 'following.txt') -> bool:
2019-06-29 18:23:13 +00:00
"""Removes a person to the follow list
"""
2021-12-26 18:17:37 +00:00
domain = remove_domain_port(domain)
2020-04-03 11:38:44 +00:00
handle = nickname + '@' + domain
handleToUnfollow = followNickname + '@' + followDomain
2021-12-26 00:07:44 +00:00
if group_account:
2021-07-30 16:06:34 +00:00
handleToUnfollow = '!' + handleToUnfollow
2021-12-25 16:17:53 +00:00
if not os.path.isdir(base_dir + '/accounts'):
os.mkdir(base_dir + '/accounts')
if not os.path.isdir(base_dir + '/accounts/' + handle):
os.mkdir(base_dir + '/accounts/' + handle)
2020-04-03 11:38:44 +00:00
2021-12-25 16:17:53 +00:00
filename = base_dir + '/accounts/' + handle + '/' + followFile
2019-07-17 10:34:00 +00:00
if not os.path.isfile(filename):
2019-07-17 11:54:13 +00:00
if debug:
2020-04-03 11:38:44 +00:00
print('DEBUG: follow file ' + filename + ' was not found')
2019-07-17 10:34:00 +00:00
return False
2020-08-20 12:11:07 +00:00
handleToUnfollowLower = handleToUnfollow.lower()
if handleToUnfollowLower not in open(filename).read().lower():
2019-07-17 11:54:13 +00:00
if debug:
2020-04-03 11:38:44 +00:00
print('DEBUG: handle to unfollow ' + handleToUnfollow +
' is not in ' + filename)
2019-07-17 10:34:00 +00:00
return
2021-11-26 14:35:26 +00:00
lines = []
try:
with open(filename, 'r') as f:
lines = f.readlines()
except OSError:
2021-12-28 20:32:11 +00:00
print('EX: unfollow_account ' + filename)
2021-11-26 14:35:26 +00:00
if lines:
2021-11-25 21:18:53 +00:00
try:
with open(filename, 'w+') as f:
for line in lines:
checkHandle = line.strip("\n").strip("\r").lower()
if checkHandle != handleToUnfollowLower and \
checkHandle != '!' + handleToUnfollowLower:
f.write(line)
2021-12-25 15:28:52 +00:00
except OSError as ex:
print('EX: unable to write ' + filename + ' ' + str(ex))
# write to an unfollowed file so that if a follow accept
# later arrives then it can be ignored
2021-12-25 16:17:53 +00:00
unfollowedFilename = base_dir + '/accounts/' + handle + '/unfollowed.txt'
if os.path.isfile(unfollowedFilename):
2020-07-14 21:48:39 +00:00
if handleToUnfollowLower not in \
open(unfollowedFilename).read().lower():
2021-11-26 14:35:26 +00:00
try:
with open(unfollowedFilename, 'a+') as f:
f.write(handleToUnfollow + '\n')
except OSError:
print('EX: unable to append ' + unfollowedFilename)
else:
2021-11-25 21:18:53 +00:00
try:
with open(unfollowedFilename, 'w+') as f:
f.write(handleToUnfollow + '\n')
except OSError:
2021-11-25 22:22:54 +00:00
print('EX: unable to write ' + unfollowedFilename)
2019-10-30 21:44:16 +00:00
return True
2019-06-29 18:23:13 +00:00
2020-04-03 11:38:44 +00:00
2021-12-29 21:55:09 +00:00
def unfollower_of_account(base_dir: str, nickname: str, domain: str,
followerNickname: str, followerDomain: str,
debug: bool, group_account: bool) -> bool:
"""Remove a follower of a person
"""
2021-12-28 20:32:11 +00:00
return unfollow_account(base_dir, nickname, domain,
followerNickname, followerDomain,
debug, group_account, 'followers.txt')
2019-06-29 18:23:13 +00:00
2020-04-03 11:38:44 +00:00
2021-12-29 21:55:09 +00:00
def clear_follows(base_dir: str, nickname: str, domain: str,
followFile: str = 'following.txt') -> None:
2019-06-29 18:23:13 +00:00
"""Removes all follows
"""
2020-09-15 09:16:03 +00:00
handle = nickname + '@' + domain
2021-12-25 16:17:53 +00:00
if not os.path.isdir(base_dir + '/accounts'):
os.mkdir(base_dir + '/accounts')
if not os.path.isdir(base_dir + '/accounts/' + handle):
os.mkdir(base_dir + '/accounts/' + handle)
filename = base_dir + '/accounts/' + handle + '/' + followFile
2019-06-29 18:23:13 +00:00
if os.path.isfile(filename):
try:
os.remove(filename)
2021-11-25 18:42:38 +00:00
except OSError:
2021-12-29 21:55:09 +00:00
print('EX: clear_follows unable to delete ' + filename)
2019-06-29 18:23:13 +00:00
2020-04-03 11:38:44 +00:00
2021-12-29 21:55:09 +00:00
def clear_followers(base_dir: str, nickname: str, domain: str) -> None:
"""Removes all followers
"""
2021-12-29 21:55:09 +00:00
clear_follows(base_dir, nickname, domain, 'followers.txt')
2020-04-03 11:38:44 +00:00
2019-06-29 20:21:37 +00:00
2021-12-29 21:55:09 +00:00
def _get_no_of_follows(base_dir: str, nickname: str, domain: str,
authenticated: bool,
followFile='following.txt') -> int:
"""Returns the number of follows or followers
"""
# only show number of followers to authenticated
# account holders
2020-04-03 11:38:44 +00:00
# if not authenticated:
# return 9999
2020-09-15 09:16:03 +00:00
handle = nickname + '@' + domain
2021-12-25 16:17:53 +00:00
filename = base_dir + '/accounts/' + handle + '/' + followFile
2019-06-29 20:21:37 +00:00
if not os.path.isfile(filename):
return 0
2020-04-03 11:38:44 +00:00
ctr = 0
2021-11-26 14:35:26 +00:00
lines = []
try:
with open(filename, 'r') as f:
lines = f.readlines()
except OSError:
2021-12-29 21:55:09 +00:00
print('EX: _get_no_of_follows ' + filename)
2021-11-26 14:35:26 +00:00
if lines:
2019-06-29 20:21:37 +00:00
for line in lines:
if '#' in line:
continue
if '@' in line and \
'.' in line and \
not line.startswith('http'):
ctr += 1
elif ((line.startswith('http') or
2021-07-01 17:59:24 +00:00
line.startswith('hyper')) and
2021-12-26 12:19:00 +00:00
has_users_path(line)):
ctr += 1
2019-06-29 20:21:37 +00:00
return ctr
2020-04-03 11:38:44 +00:00
2021-12-29 21:55:09 +00:00
def get_no_of_followers(base_dir: str,
nickname: str, domain: str,
authenticated: bool) -> int:
"""Returns the number of followers of the given person
"""
2021-12-29 21:55:09 +00:00
return _get_no_of_follows(base_dir, nickname, domain,
authenticated, 'followers.txt')
2020-04-03 11:38:44 +00:00
2019-06-29 20:21:37 +00:00
2021-12-28 20:32:11 +00:00
def get_following_feed(base_dir: str, domain: str, port: int, path: str,
http_prefix: str, authorized: bool,
follows_per_page=12,
followFile='following') -> {}:
2020-10-24 09:28:21 +00:00
"""Returns the following and followers feeds from GET requests.
This accesses the following.txt or followers.txt and builds a collection.
"""
2021-03-24 13:15:43 +00:00
# Show a small number of follows to non-authorized viewers
if not authorized:
2021-12-28 16:00:24 +00:00
follows_per_page = 6
2020-04-03 11:38:44 +00:00
if '/' + followFile not in path:
2019-06-29 20:21:37 +00:00
return None
# handle page numbers
2020-04-03 11:38:44 +00:00
headerOnly = True
pageNumber = None
2019-06-29 20:21:37 +00:00
if '?page=' in path:
2020-04-03 11:38:44 +00:00
pageNumber = path.split('?page=')[1]
2021-03-24 13:15:43 +00:00
if pageNumber == 'true' or not authorized:
2020-04-03 11:38:44 +00:00
pageNumber = 1
2019-06-29 20:21:37 +00:00
else:
try:
2020-04-03 11:38:44 +00:00
pageNumber = int(pageNumber)
except BaseException:
2021-12-28 20:32:11 +00:00
print('EX: get_following_feed unable to convert to int ' +
2021-10-29 18:48:15 +00:00
str(pageNumber))
2019-06-29 20:21:37 +00:00
pass
2020-04-03 11:38:44 +00:00
path = path.split('?page=')[0]
headerOnly = False
2020-03-22 21:16:02 +00:00
2020-04-03 11:38:44 +00:00
if not path.endswith('/' + followFile):
2019-06-29 20:21:37 +00:00
return None
2020-04-03 11:38:44 +00:00
nickname = None
2019-06-29 20:21:37 +00:00
if path.startswith('/users/'):
2020-04-03 11:38:44 +00:00
nickname = path.replace('/users/', '', 1).replace('/' + followFile, '')
2019-06-29 20:21:37 +00:00
if path.startswith('/@'):
2020-04-03 11:38:44 +00:00
nickname = path.replace('/@', '', 1).replace('/' + followFile, '')
2019-07-03 09:40:27 +00:00
if not nickname:
2019-06-29 20:21:37 +00:00
return None
2021-12-28 14:41:10 +00:00
if not valid_nickname(domain, nickname):
2019-06-29 20:21:37 +00:00
return None
2021-12-26 12:45:03 +00:00
domain = get_full_domain(domain, port)
2019-06-30 19:01:43 +00:00
2019-06-29 20:21:37 +00:00
if headerOnly:
2020-04-03 11:38:44 +00:00
firstStr = \
2021-12-26 10:19:59 +00:00
local_actor_url(http_prefix, nickname, domain) + \
2021-08-14 11:13:39 +00:00
'/' + followFile + '?page=1'
2020-04-03 11:38:44 +00:00
idStr = \
2021-12-26 10:19:59 +00:00
local_actor_url(http_prefix, nickname, domain) + '/' + followFile
2020-04-03 11:38:44 +00:00
totalStr = \
2021-12-29 21:55:09 +00:00
_get_no_of_follows(base_dir, nickname, domain, authorized)
2020-04-03 11:38:44 +00:00
following = {
2019-06-29 20:21:37 +00:00
'@context': 'https://www.w3.org/ns/activitystreams',
2020-04-03 11:38:44 +00:00
'first': firstStr,
'id': idStr,
'totalItems': totalStr,
2020-03-22 20:36:19 +00:00
'type': 'OrderedCollection'
}
2019-06-29 20:21:37 +00:00
return following
if not pageNumber:
2020-04-03 11:38:44 +00:00
pageNumber = 1
nextPageNumber = int(pageNumber + 1)
idStr = \
2021-12-26 10:19:59 +00:00
local_actor_url(http_prefix, nickname, domain) + \
2021-08-14 11:13:39 +00:00
'/' + followFile + '?page=' + str(pageNumber)
2020-04-03 11:38:44 +00:00
partOfStr = \
2021-12-26 10:19:59 +00:00
local_actor_url(http_prefix, nickname, domain) + '/' + followFile
2020-04-03 11:38:44 +00:00
following = {
2019-06-29 20:21:37 +00:00
'@context': 'https://www.w3.org/ns/activitystreams',
2020-04-03 11:38:44 +00:00
'id': idStr,
2019-06-29 20:21:37 +00:00
'orderedItems': [],
2020-04-03 11:38:44 +00:00
'partOf': partOfStr,
2019-06-29 20:21:37 +00:00
'totalItems': 0,
2020-03-22 20:36:19 +00:00
'type': 'OrderedCollectionPage'
}
2019-06-29 20:21:37 +00:00
2020-04-03 11:38:44 +00:00
handleDomain = domain
2021-12-26 18:17:37 +00:00
handleDomain = remove_domain_port(handleDomain)
2020-09-15 09:16:03 +00:00
handle = nickname + '@' + handleDomain
2021-12-25 16:17:53 +00:00
filename = base_dir + '/accounts/' + handle + '/' + followFile + '.txt'
2019-06-29 20:21:37 +00:00
if not os.path.isfile(filename):
return following
2020-04-03 11:38:44 +00:00
currPage = 1
pageCtr = 0
totalCtr = 0
2021-11-26 14:35:26 +00:00
lines = []
try:
with open(filename, 'r') as f:
lines = f.readlines()
except OSError:
2021-12-28 20:32:11 +00:00
print('EX: get_following_feed ' + filename)
2021-11-26 14:35:26 +00:00
for line in lines:
if '#' not in line:
if '@' in line and not line.startswith('http'):
# nickname@domain
pageCtr += 1
totalCtr += 1
if currPage == pageNumber:
line2 = \
line.lower().replace('\n', '').replace('\r', '')
nick = line2.split('@')[0]
dom = line2.split('@')[1]
if not nick.startswith('!'):
# person actor
2021-12-26 10:19:59 +00:00
url = local_actor_url(http_prefix, nick, dom)
2021-11-26 14:35:26 +00:00
else:
# group actor
2021-12-25 17:09:22 +00:00
url = http_prefix + '://' + dom + '/c/' + nick
2021-11-26 14:35:26 +00:00
following['orderedItems'].append(url)
elif ((line.startswith('http') or
line.startswith('hyper')) and
2021-12-26 12:19:00 +00:00
has_users_path(line)):
2021-11-26 14:35:26 +00:00
# https://domain/users/nickname
pageCtr += 1
totalCtr += 1
if currPage == pageNumber:
appendStr = \
line.lower().replace('\n', '').replace('\r', '')
following['orderedItems'].append(appendStr)
2021-12-28 16:00:24 +00:00
if pageCtr >= follows_per_page:
2021-11-26 14:35:26 +00:00
pageCtr = 0
currPage += 1
2020-04-03 11:38:44 +00:00
following['totalItems'] = totalCtr
2021-12-28 16:00:24 +00:00
lastPage = int(totalCtr / follows_per_page)
2020-04-03 11:38:44 +00:00
if lastPage < 1:
lastPage = 1
if nextPageNumber > lastPage:
following['next'] = \
2021-12-26 10:19:59 +00:00
local_actor_url(http_prefix, nickname, domain) + \
2021-08-14 11:13:39 +00:00
'/' + followFile + '?page=' + str(lastPage)
2019-06-29 20:21:37 +00:00
return following
2019-07-02 18:17:04 +00:00
2020-04-03 11:38:44 +00:00
2021-12-29 21:55:09 +00:00
def follow_approval_required(base_dir: str, nicknameToFollow: str,
domainToFollow: str, debug: bool,
followRequestHandle: str) -> bool:
2019-07-19 20:03:50 +00:00
""" Returns the policy for follower approvals
"""
2020-01-02 22:42:06 +00:00
# has this handle already been manually approved?
2021-12-29 21:55:09 +00:00
if _pre_approved_follower(base_dir, nicknameToFollow, domainToFollow,
followRequestHandle):
2019-12-31 09:23:41 +00:00
return False
2020-04-03 11:38:44 +00:00
manuallyApproveFollows = False
2021-12-26 18:17:37 +00:00
domainToFollow = remove_domain_port(domainToFollow)
2021-12-25 16:17:53 +00:00
actorFilename = base_dir + '/accounts/' + \
2020-04-03 11:38:44 +00:00
nicknameToFollow + '@' + domainToFollow + '.json'
2019-07-19 20:03:50 +00:00
if os.path.isfile(actorFilename):
2021-12-26 15:13:34 +00:00
actor = load_json(actorFilename)
2019-09-30 22:39:02 +00:00
if actor:
2019-07-19 20:03:50 +00:00
if actor.get('manuallyApprovesFollowers'):
2020-04-03 11:38:44 +00:00
manuallyApproveFollows = actor['manuallyApprovesFollowers']
2019-07-19 20:03:50 +00:00
else:
if debug:
2020-04-03 11:38:44 +00:00
print(nicknameToFollow + '@' + domainToFollow +
' automatically approves followers')
2019-07-19 20:03:50 +00:00
else:
if debug:
2020-04-03 11:38:44 +00:00
print('DEBUG: Actor file not found: ' + actorFilename)
2019-07-19 20:03:50 +00:00
return manuallyApproveFollows
2020-04-03 11:38:44 +00:00
2021-12-29 21:55:09 +00:00
def no_of_follow_requests(base_dir: str,
nicknameToFollow: str, domainToFollow: str,
nickname: str, domain: str, fromPort: int,
followType: str) -> int:
"""Returns the current number of follow requests
"""
2021-12-25 16:17:53 +00:00
accountsDir = base_dir + '/accounts/' + \
2020-04-03 11:38:44 +00:00
nicknameToFollow + '@' + domainToFollow
approveFollowsFilename = accountsDir + '/followrequests.txt'
if not os.path.isfile(approveFollowsFilename):
return 0
2020-04-03 11:38:44 +00:00
ctr = 0
2021-11-26 14:35:26 +00:00
lines = []
try:
with open(approveFollowsFilename, 'r') as f:
lines = f.readlines()
except OSError:
2021-12-29 21:55:09 +00:00
print('EX: no_of_follow_requests ' + approveFollowsFilename)
2021-11-26 14:35:26 +00:00
if lines:
2020-06-03 20:21:44 +00:00
if followType == "onion":
for fileLine in lines:
if '.onion' in fileLine:
ctr += 1
elif followType == "i2p":
for fileLine in lines:
if '.i2p' in fileLine:
ctr += 1
else:
return len(lines)
return ctr
2020-04-03 11:38:44 +00:00
2021-12-29 21:55:09 +00:00
def store_follow_request(base_dir: str,
nicknameToFollow: str, domainToFollow: str, port: int,
nickname: str, domain: str, fromPort: int,
followJson: {},
debug: bool, personUrl: str,
group_account: bool) -> bool:
"""Stores the follow request for later use
"""
2021-12-25 16:17:53 +00:00
accountsDir = base_dir + '/accounts/' + \
2020-04-03 11:38:44 +00:00
nicknameToFollow + '@' + domainToFollow
2019-08-07 11:49:38 +00:00
if not os.path.isdir(accountsDir):
return False
2021-12-26 12:45:03 +00:00
domain_full = get_full_domain(domain, fromPort)
approveHandle = get_full_domain(nickname + '@' + domain, fromPort)
2021-12-26 00:07:44 +00:00
if group_account:
approveHandle = '!' + approveHandle
2020-04-03 11:38:44 +00:00
followersFilename = accountsDir + '/followers.txt'
2019-08-26 22:38:09 +00:00
if os.path.isfile(followersFilename):
alreadyFollowing = False
followersStr = ''
2021-11-26 14:35:26 +00:00
try:
with open(followersFilename, 'r') as fpFollowers:
followersStr = fpFollowers.read()
except OSError:
2021-12-29 21:55:09 +00:00
print('EX: store_follow_request ' + followersFilename)
if approveHandle in followersStr:
alreadyFollowing = True
2021-07-30 19:20:49 +00:00
else:
2021-12-26 12:24:40 +00:00
usersPaths = get_user_paths()
2021-07-30 19:20:49 +00:00
for possibleUsersPath in usersPaths:
2021-12-26 10:00:46 +00:00
url = '://' + domain_full + possibleUsersPath + nickname
2021-07-30 19:20:49 +00:00
if url in followersStr:
alreadyFollowing = True
break
if alreadyFollowing:
2019-08-26 22:38:09 +00:00
if debug:
2020-04-03 11:38:44 +00:00
print('DEBUG: ' +
nicknameToFollow + '@' + domainToFollow +
' already following ' + approveHandle)
2019-08-26 22:38:09 +00:00
return True
# should this follow be denied?
2020-04-03 11:38:44 +00:00
denyFollowsFilename = accountsDir + '/followrejects.txt'
if os.path.isfile(denyFollowsFilename):
2019-09-18 19:05:08 +00:00
if approveHandle in open(denyFollowsFilename).read():
2021-12-29 21:55:09 +00:00
remove_from_follow_requests(base_dir, nicknameToFollow,
domainToFollow, approveHandle, debug)
2020-04-03 11:38:44 +00:00
print(approveHandle + ' was already denied as a follower of ' +
nicknameToFollow)
return True
# add to a file which contains a list of requests
2020-04-03 11:38:44 +00:00
approveFollowsFilename = accountsDir + '/followrequests.txt'
# store either nick@domain or the full person/actor url
approveHandleStored = approveHandle
if '/users/' not in personUrl:
approveHandleStored = personUrl
2021-12-26 00:07:44 +00:00
if group_account:
approveHandle = '!' + approveHandle
if os.path.isfile(approveFollowsFilename):
if approveHandle not in open(approveFollowsFilename).read():
2021-11-26 14:35:26 +00:00
try:
with open(approveFollowsFilename, 'a+') as fp:
fp.write(approveHandleStored + '\n')
except OSError:
2021-12-29 21:55:09 +00:00
print('EX: store_follow_request 2 ' + approveFollowsFilename)
else:
if debug:
print('DEBUG: ' + approveHandleStored +
2020-04-03 11:38:44 +00:00
' is already awaiting approval')
else:
2021-11-25 21:18:53 +00:00
try:
with open(approveFollowsFilename, 'w+') as fp:
fp.write(approveHandleStored + '\n')
except OSError:
2021-12-29 21:55:09 +00:00
print('EX: store_follow_request 3 ' + approveFollowsFilename)
# store the follow request in its own directory
# We don't rely upon the inbox because items in there could expire
2020-04-03 11:38:44 +00:00
requestsDir = accountsDir + '/requests'
if not os.path.isdir(requestsDir):
os.mkdir(requestsDir)
2020-04-03 11:38:44 +00:00
followActivityfilename = requestsDir + '/' + approveHandle + '.follow'
2021-12-26 14:47:21 +00:00
return save_json(followJson, followActivityfilename)
2020-04-03 11:38:44 +00:00
2021-12-29 21:55:09 +00:00
def followed_account_accepts(session, base_dir: str, http_prefix: str,
nicknameToFollow: str, domainToFollow: str,
port: int,
nickname: str, domain: str, fromPort: int,
personUrl: str, federation_list: [],
followJson: {}, send_threads: [], postLog: [],
cached_webfingers: {}, person_cache: {},
debug: bool, project_version: str,
removeFollowActivity: bool,
signing_priv_key_pem: str):
2019-07-20 08:33:18 +00:00
"""The person receiving a follow request accepts the new follower
and sends back an Accept activity
"""
2020-04-03 11:38:44 +00:00
acceptHandle = nickname + '@' + domain
2019-10-06 09:57:49 +00:00
2019-07-05 18:57:19 +00:00
# send accept back
2019-07-06 13:49:25 +00:00
if debug:
2020-04-03 11:38:44 +00:00
print('DEBUG: sending Accept activity for ' +
'follow request which arrived at ' +
nicknameToFollow + '@' + domainToFollow +
' back to ' + acceptHandle)
2021-12-29 21:55:09 +00:00
acceptJson = create_accept(base_dir, federation_list,
nicknameToFollow, domainToFollow, port,
personUrl, '', http_prefix,
followJson)
2019-07-06 15:17:21 +00:00
if debug:
pprint(acceptJson)
2020-04-03 11:38:44 +00:00
print('DEBUG: sending follow Accept from ' +
nicknameToFollow + '@' + domainToFollow +
' port ' + str(port) + ' to ' +
acceptHandle + ' port ' + str(fromPort))
2021-12-25 20:39:35 +00:00
client_to_server = False
2019-12-16 10:19:21 +00:00
if removeFollowActivity:
# remove the follow request json
2020-04-03 11:38:44 +00:00
followActivityfilename = \
2021-12-26 12:02:29 +00:00
acct_dir(base_dir, nicknameToFollow, domainToFollow) + \
2021-07-13 21:59:53 +00:00
'/requests/' + \
2020-04-03 11:38:44 +00:00
nickname + '@' + domain + '.follow'
if os.path.isfile(followActivityfilename):
try:
os.remove(followActivityfilename)
2021-11-25 18:42:38 +00:00
except OSError:
2021-12-29 21:55:09 +00:00
print('EX: followed_account_accepts unable to delete ' +
2021-10-29 18:48:15 +00:00
followActivityfilename)
2019-12-16 10:19:21 +00:00
2021-12-26 00:07:44 +00:00
group_account = False
if followJson:
if followJson.get('actor'):
2021-12-26 17:53:07 +00:00
if has_group_type(base_dir, followJson['actor'], person_cache):
2021-12-26 00:07:44 +00:00
group_account = True
2021-12-29 21:55:09 +00:00
return send_signed_json(acceptJson, session, base_dir,
nicknameToFollow, domainToFollow, port,
nickname, domain, fromPort, '',
http_prefix, True, client_to_server,
federation_list,
send_threads, postLog, cached_webfingers,
person_cache, debug, project_version, None,
group_account, signing_priv_key_pem,
7856837)
def followed_account_rejects(session, base_dir: str, http_prefix: str,
nicknameToFollow: str, domainToFollow: str,
port: int,
nickname: str, domain: str, fromPort: int,
federation_list: [],
send_threads: [], postLog: [],
cached_webfingers: {}, person_cache: {},
debug: bool, project_version: str,
signing_priv_key_pem: str):
"""The person receiving a follow request rejects the new follower
and sends back a Reject activity
"""
# send reject back
if debug:
2020-04-03 11:38:44 +00:00
print('DEBUG: sending Reject activity for ' +
'follow request which arrived at ' +
nicknameToFollow + '@' + domainToFollow +
' back to ' + nickname + '@' + domain)
2019-12-16 10:01:57 +00:00
# get the json for the original follow request
2020-04-03 11:38:44 +00:00
followActivityfilename = \
2021-12-26 12:02:29 +00:00
acct_dir(base_dir, nicknameToFollow, domainToFollow) + '/requests/' + \
2020-04-03 11:38:44 +00:00
nickname + '@' + domain + '.follow'
2021-12-26 15:13:34 +00:00
followJson = load_json(followActivityfilename)
2019-12-16 10:01:57 +00:00
if not followJson:
2020-04-03 11:38:44 +00:00
print('No follow request json was found for ' +
2019-12-16 10:19:21 +00:00
followActivityfilename)
2019-12-16 10:01:57 +00:00
return None
# actor who made the follow request
2020-04-03 11:38:44 +00:00
personUrl = followJson['actor']
2019-12-16 10:01:57 +00:00
# create the reject activity
2020-04-03 11:38:44 +00:00
rejectJson = \
2021-12-29 21:55:09 +00:00
create_reject(base_dir, federation_list,
nicknameToFollow, domainToFollow, port,
personUrl, '', http_prefix, followJson)
if debug:
pprint(rejectJson)
2020-04-03 11:38:44 +00:00
print('DEBUG: sending follow Reject from ' +
nicknameToFollow + '@' + domainToFollow +
' port ' + str(port) + ' to ' +
nickname + '@' + domain + ' port ' + str(fromPort))
2021-12-25 20:39:35 +00:00
client_to_server = False
2021-12-26 12:45:03 +00:00
denyHandle = get_full_domain(nickname + '@' + domain, fromPort)
2021-12-26 00:07:44 +00:00
group_account = False
2021-12-26 17:53:07 +00:00
if has_group_type(base_dir, personUrl, person_cache):
2021-12-26 00:07:44 +00:00
group_account = True
# remove from the follow requests file
2021-12-29 21:55:09 +00:00
remove_from_follow_requests(base_dir, nicknameToFollow, domainToFollow,
denyHandle, debug)
# remove the follow request json
try:
2019-12-16 10:19:21 +00:00
os.remove(followActivityfilename)
2021-11-25 18:42:38 +00:00
except OSError:
2021-12-29 21:55:09 +00:00
print('EX: followed_account_rejects unable to delete ' +
2021-10-29 18:48:15 +00:00
followActivityfilename)
# send the reject activity
2021-12-29 21:55:09 +00:00
return send_signed_json(rejectJson, session, base_dir,
nicknameToFollow, domainToFollow, port,
nickname, domain, fromPort, '',
http_prefix, True, client_to_server,
federation_list,
send_threads, postLog, cached_webfingers,
person_cache, debug, project_version, None,
group_account, signing_priv_key_pem,
6393063)
2020-04-03 11:38:44 +00:00
2021-12-28 20:32:11 +00:00
def send_follow_request(session, base_dir: str,
nickname: str, domain: str, port: int,
http_prefix: str,
followNickname: str, followDomain: str,
followedActor: str,
followPort: int, followHttpPrefix: str,
client_to_server: bool, federation_list: [],
send_threads: [], postLog: [], cached_webfingers: {},
person_cache: {}, debug: bool,
project_version: str, signing_priv_key_pem: str) -> {}:
2019-07-02 20:54:22 +00:00
"""Gets the json object for sending a follow request
2020-03-22 21:16:02 +00:00
"""
2021-12-25 23:03:28 +00:00
if not signing_priv_key_pem:
2021-09-20 16:14:24 +00:00
print('WARN: follow request without signing key')
2021-12-27 18:28:26 +00:00
if not domain_permitted(followDomain, federation_list):
print('You are not permitted to follow the domain ' + followDomain)
2019-07-02 18:38:51 +00:00
return None
2020-03-22 21:16:02 +00:00
2021-12-26 12:45:03 +00:00
fullDomain = get_full_domain(domain, port)
2021-12-26 10:19:59 +00:00
followActor = local_actor_url(http_prefix, nickname, fullDomain)
2019-07-02 18:38:51 +00:00
2021-12-26 12:45:03 +00:00
requestDomain = get_full_domain(followDomain, followPort)
2019-07-06 10:33:57 +00:00
2021-12-27 17:42:35 +00:00
statusNumber, published = get_status_number()
2020-03-22 21:16:02 +00:00
2021-12-26 00:07:44 +00:00
group_account = False
2019-10-21 14:12:22 +00:00
if followNickname:
followedId = followedActor
2020-04-03 11:38:44 +00:00
followHandle = followNickname + '@' + requestDomain
2021-12-26 17:53:07 +00:00
group_account = has_group_type(base_dir, followedActor, person_cache)
2021-12-26 00:07:44 +00:00
if group_account:
2021-07-30 19:20:49 +00:00
followHandle = '!' + followHandle
2021-08-02 20:57:44 +00:00
print('Follow request being sent to group account')
2019-10-21 14:12:22 +00:00
else:
if debug:
2021-12-28 20:32:11 +00:00
print('DEBUG: send_follow_request - assuming single user instance')
2020-04-03 11:38:44 +00:00
followedId = followHttpPrefix + '://' + requestDomain
singleUserNickname = 'dev'
followHandle = singleUserNickname + '@' + requestDomain
2019-07-06 19:24:52 +00:00
2021-10-17 17:45:49 +00:00
# remove follow handle from unfollowed.txt
2021-12-25 16:17:53 +00:00
unfollowedFilename = \
2021-12-26 12:02:29 +00:00
acct_dir(base_dir, nickname, domain) + '/unfollowed.txt'
2021-10-17 17:45:49 +00:00
if os.path.isfile(unfollowedFilename):
if followHandle in open(unfollowedFilename).read():
unfollowedFile = None
2021-11-26 14:35:26 +00:00
try:
with open(unfollowedFilename, 'r') as fp:
unfollowedFile = fp.read()
except OSError:
2021-12-28 20:32:11 +00:00
print('EX: send_follow_request ' + unfollowedFilename)
2021-11-26 14:35:26 +00:00
if unfollowedFile:
2021-10-17 17:45:49 +00:00
unfollowedFile = \
unfollowedFile.replace(followHandle + '\n', '')
2021-11-25 21:18:53 +00:00
try:
with open(unfollowedFilename, 'w+') as fp:
fp.write(unfollowedFile)
except OSError:
2021-11-25 22:22:54 +00:00
print('EX: unable to write ' + unfollowedFilename)
2021-10-17 17:45:49 +00:00
2020-04-03 11:38:44 +00:00
newFollowJson = {
2019-08-16 21:52:11 +00:00
'@context': 'https://www.w3.org/ns/activitystreams',
2020-04-03 11:38:44 +00:00
'id': followActor + '/statuses/' + str(statusNumber),
2019-07-02 18:38:51 +00:00
'type': 'Follow',
2019-07-06 10:33:57 +00:00
'actor': followActor,
2019-08-16 21:52:11 +00:00
'object': followedId
2019-07-02 18:38:51 +00:00
}
2021-12-26 00:07:44 +00:00
if group_account:
2021-08-02 21:09:22 +00:00
newFollowJson['to'] = followedId
2021-08-02 20:57:44 +00:00
print('Follow request: ' + str(newFollowJson))
2019-07-02 19:05:59 +00:00
2021-12-29 21:55:09 +00:00
if follow_approval_required(base_dir, nickname, domain, debug,
followHandle):
2020-02-19 12:51:14 +00:00
# Remove any follow requests rejected for the account being followed.
# It's assumed that if you are following someone then you are
# ok with them following back. If this isn't the case then a rejected
# follow request will block them again.
2021-12-29 21:55:09 +00:00
_remove_from_follow_rejects(base_dir,
nickname, domain,
followHandle, debug)
send_signed_json(newFollowJson, session, base_dir, nickname, domain, port,
followNickname, followDomain, followPort,
'https://www.w3.org/ns/activitystreams#Public',
http_prefix, True, client_to_server,
federation_list,
send_threads, postLog, cached_webfingers, person_cache,
debug, project_version, None, group_account,
signing_priv_key_pem, 8234389)
2019-07-05 20:32:21 +00:00
return newFollowJson
2020-04-03 11:38:44 +00:00
2021-12-28 20:32:11 +00:00
def send_follow_requestViaServer(base_dir: str, session,
fromNickname: str, password: str,
fromDomain: str, fromPort: int,
followNickname: str, followDomain: str,
followPort: int,
http_prefix: str,
cached_webfingers: {}, person_cache: {},
debug: bool, project_version: str,
signing_priv_key_pem: str) -> {}:
2019-07-16 21:38:06 +00:00
"""Creates a follow request via c2s
"""
if not session:
2021-12-28 20:32:11 +00:00
print('WARN: No session for send_follow_requestViaServer')
2019-07-16 21:38:06 +00:00
return 6
2021-12-26 12:45:03 +00:00
fromDomainFull = get_full_domain(fromDomain, fromPort)
2019-07-18 11:35:48 +00:00
2021-12-26 12:45:03 +00:00
followDomainFull = get_full_domain(followDomain, followPort)
2019-07-16 21:38:06 +00:00
2021-12-26 10:19:59 +00:00
followActor = local_actor_url(http_prefix, fromNickname, fromDomainFull)
2021-08-14 12:00:32 +00:00
followedId = \
2021-12-25 17:09:22 +00:00
http_prefix + '://' + followDomainFull + '/@' + followNickname
2019-07-16 21:38:06 +00:00
2021-12-27 17:42:35 +00:00
statusNumber, published = get_status_number()
2020-04-03 11:38:44 +00:00
newFollowJson = {
2019-08-16 21:52:11 +00:00
'@context': 'https://www.w3.org/ns/activitystreams',
2020-04-03 11:38:44 +00:00
'id': followActor + '/statuses/' + str(statusNumber),
2019-07-16 21:38:06 +00:00
'type': 'Follow',
'actor': followActor,
2019-08-16 21:52:11 +00:00
'object': followedId
2019-07-16 21:38:06 +00:00
}
2021-12-25 17:09:22 +00:00
handle = http_prefix + '://' + fromDomainFull + '/@' + fromNickname
2019-07-16 21:38:06 +00:00
# lookup the inbox for the To handle
2020-04-03 11:38:44 +00:00
wfRequest = \
2021-12-29 21:55:09 +00:00
webfinger_handle(session, handle, http_prefix, cached_webfingers,
fromDomain, project_version, debug, False,
signing_priv_key_pem)
2019-07-16 21:38:06 +00:00
if not wfRequest:
if debug:
2021-03-18 10:01:01 +00:00
print('DEBUG: follow request webfinger failed for ' + handle)
2019-07-16 21:38:06 +00:00
return 1
2020-06-23 10:41:12 +00:00
if not isinstance(wfRequest, dict):
2021-03-18 10:01:01 +00:00
print('WARN: follow request Webfinger for ' + handle +
' did not return a dict. ' + str(wfRequest))
2020-06-23 10:41:12 +00:00
return 1
2019-07-16 21:38:06 +00:00
2020-04-03 11:38:44 +00:00
postToBox = 'outbox'
2019-07-16 21:38:06 +00:00
# get the actor inbox for the To handle
2021-09-15 14:05:08 +00:00
originDomain = fromDomain
2020-04-03 11:38:44 +00:00
(inboxUrl, pubKeyId, pubKey,
2020-09-27 19:27:24 +00:00
fromPersonId, sharedInbox, avatarUrl,
2021-12-29 21:55:09 +00:00
displayName, _) = get_person_box(signing_priv_key_pem, originDomain,
base_dir, session, wfRequest,
person_cache,
project_version, http_prefix,
fromNickname,
fromDomain, postToBox, 52025)
2020-03-22 21:16:02 +00:00
2019-07-16 21:38:06 +00:00
if not inboxUrl:
if debug:
2021-03-18 10:01:01 +00:00
print('DEBUG: follow request no ' + postToBox +
' was found for ' + handle)
2019-07-16 21:38:06 +00:00
return 3
if not fromPersonId:
if debug:
2021-03-18 10:01:01 +00:00
print('DEBUG: follow request no actor was found for ' + handle)
2019-07-16 21:38:06 +00:00
return 4
2020-03-22 21:16:02 +00:00
2021-12-28 21:36:27 +00:00
authHeader = create_basic_auth_header(fromNickname, password)
2020-03-22 21:16:02 +00:00
2020-04-03 11:38:44 +00:00
headers = {
'host': fromDomain,
'Content-type': 'application/json',
2020-03-22 20:36:19 +00:00
'Authorization': authHeader
}
2020-04-03 11:38:44 +00:00
postResult = \
2021-12-29 21:55:09 +00:00
post_json(http_prefix, fromDomainFull,
session, newFollowJson, [], inboxUrl, headers, 3, True)
2020-04-03 11:38:44 +00:00
if not postResult:
if debug:
2021-03-18 10:01:01 +00:00
print('DEBUG: POST follow request failed for c2s to ' + inboxUrl)
2020-04-03 11:38:44 +00:00
return 5
2019-07-16 21:38:06 +00:00
if debug:
2021-03-18 10:01:01 +00:00
print('DEBUG: c2s POST follow request success')
2019-07-16 21:38:06 +00:00
return newFollowJson
2020-04-03 11:38:44 +00:00
2021-12-29 21:55:09 +00:00
def send_unfollow_request_via_server(base_dir: str, session,
fromNickname: str, password: str,
fromDomain: str, fromPort: int,
followNickname: str, followDomain: str,
followPort: int,
http_prefix: str,
cached_webfingers: {}, person_cache: {},
debug: bool, project_version: str,
signing_priv_key_pem: str) -> {}:
2019-07-17 10:34:00 +00:00
"""Creates a unfollow request via c2s
"""
if not session:
2021-12-29 21:55:09 +00:00
print('WARN: No session for send_unfollow_request_via_server')
2019-07-17 10:34:00 +00:00
return 6
2021-12-26 12:45:03 +00:00
fromDomainFull = get_full_domain(fromDomain, fromPort)
followDomainFull = get_full_domain(followDomain, followPort)
2019-07-17 10:34:00 +00:00
2021-12-26 10:19:59 +00:00
followActor = local_actor_url(http_prefix, fromNickname, fromDomainFull)
2021-08-14 12:00:32 +00:00
followedId = \
2021-12-25 17:09:22 +00:00
http_prefix + '://' + followDomainFull + '/@' + followNickname
2021-12-27 17:42:35 +00:00
statusNumber, published = get_status_number()
2019-07-17 10:34:00 +00:00
2020-04-03 11:38:44 +00:00
unfollowJson = {
2019-08-16 21:52:11 +00:00
'@context': 'https://www.w3.org/ns/activitystreams',
2020-04-03 11:38:44 +00:00
'id': followActor + '/statuses/' + str(statusNumber) + '/undo',
2019-07-17 10:34:00 +00:00
'type': 'Undo',
'actor': followActor,
'object': {
2020-04-03 11:38:44 +00:00
'id': followActor + '/statuses/' + str(statusNumber),
2019-07-17 10:34:00 +00:00
'type': 'Follow',
'actor': followActor,
2019-08-16 21:52:11 +00:00
'object': followedId
2019-07-17 10:34:00 +00:00
}
}
2021-12-25 17:09:22 +00:00
handle = http_prefix + '://' + fromDomainFull + '/@' + fromNickname
2019-07-17 10:34:00 +00:00
# lookup the inbox for the To handle
2020-04-03 11:38:44 +00:00
wfRequest = \
2021-12-29 21:55:09 +00:00
webfinger_handle(session, handle, http_prefix, cached_webfingers,
fromDomain, project_version, debug, False,
signing_priv_key_pem)
2019-07-17 10:34:00 +00:00
if not wfRequest:
if debug:
2021-03-18 10:01:01 +00:00
print('DEBUG: unfollow webfinger failed for ' + handle)
2019-07-17 10:34:00 +00:00
return 1
2020-06-23 10:41:12 +00:00
if not isinstance(wfRequest, dict):
2021-03-18 10:01:01 +00:00
print('WARN: unfollow webfinger for ' + handle +
' did not return a dict. ' + str(wfRequest))
2020-06-23 10:41:12 +00:00
return 1
2019-07-17 10:34:00 +00:00
2020-04-03 11:38:44 +00:00
postToBox = 'outbox'
2019-07-17 10:34:00 +00:00
# get the actor inbox for the To handle
2021-09-15 14:05:08 +00:00
originDomain = fromDomain
(inboxUrl, pubKeyId, pubKey, fromPersonId, sharedInbox, avatarUrl,
2021-12-29 21:55:09 +00:00
displayName, _) = get_person_box(signing_priv_key_pem,
originDomain,
base_dir, session,
wfRequest, person_cache,
project_version, http_prefix,
fromNickname,
fromDomain, postToBox,
76536)
2020-03-22 21:16:02 +00:00
2019-07-17 10:34:00 +00:00
if not inboxUrl:
if debug:
2021-03-18 10:01:01 +00:00
print('DEBUG: unfollow no ' + postToBox +
' was found for ' + handle)
2019-07-17 10:34:00 +00:00
return 3
if not fromPersonId:
if debug:
2021-03-18 10:01:01 +00:00
print('DEBUG: unfollow no actor was found for ' + handle)
2019-07-17 10:34:00 +00:00
return 4
2020-03-22 21:16:02 +00:00
2021-12-28 21:36:27 +00:00
authHeader = create_basic_auth_header(fromNickname, password)
2020-03-22 21:16:02 +00:00
2020-04-03 11:38:44 +00:00
headers = {
'host': fromDomain,
'Content-type': 'application/json',
2020-03-22 20:36:19 +00:00
'Authorization': authHeader
}
2020-04-03 11:38:44 +00:00
postResult = \
2021-12-29 21:55:09 +00:00
post_json(http_prefix, fromDomainFull,
session, unfollowJson, [], inboxUrl, headers, 3, True)
2020-04-03 11:38:44 +00:00
if not postResult:
if debug:
2021-03-18 10:01:01 +00:00
print('DEBUG: POST unfollow failed for c2s to ' + inboxUrl)
2020-04-03 11:38:44 +00:00
return 5
2019-07-17 10:34:00 +00:00
if debug:
print('DEBUG: c2s POST unfollow success')
return unfollowJson
2020-04-03 11:38:44 +00:00
2021-12-29 21:55:09 +00:00
def get_following_via_server(base_dir: str, session,
nickname: str, password: str,
domain: str, port: int,
http_prefix: str, pageNumber: int,
cached_webfingers: {}, person_cache: {},
debug: bool, project_version: str,
signing_priv_key_pem: str) -> {}:
2021-03-24 12:43:24 +00:00
"""Gets a page from the following collection as json
"""
if not session:
2021-12-29 21:55:09 +00:00
print('WARN: No session for get_following_via_server')
2021-03-24 12:43:24 +00:00
return 6
2021-12-26 12:45:03 +00:00
domain_full = get_full_domain(domain, port)
2021-12-26 10:19:59 +00:00
followActor = local_actor_url(http_prefix, nickname, domain_full)
2021-03-24 12:43:24 +00:00
2021-12-28 21:36:27 +00:00
authHeader = create_basic_auth_header(nickname, password)
2021-03-24 12:43:24 +00:00
headers = {
'host': domain,
'Content-type': 'application/json',
'Authorization': authHeader
}
if pageNumber < 1:
pageNumber = 1
url = followActor + '/following?page=' + str(pageNumber)
followingJson = \
2021-12-29 21:55:09 +00:00
get_json(signing_priv_key_pem, session, url, headers, {}, debug,
__version__, http_prefix, domain, 10, True)
2021-03-24 12:43:24 +00:00
if not followingJson:
if debug:
print('DEBUG: GET following list failed for c2s to ' + url)
return 5
if debug:
print('DEBUG: c2s GET following list request success')
return followingJson
2021-12-29 21:55:09 +00:00
def get_followers_via_server(base_dir: str, session,
nickname: str, password: str,
domain: str, port: int,
http_prefix: str, pageNumber: int,
cached_webfingers: {}, person_cache: {},
debug: bool, project_version: str,
signing_priv_key_pem: str) -> {}:
2021-03-24 13:52:20 +00:00
"""Gets a page from the followers collection as json
"""
if not session:
2021-12-29 21:55:09 +00:00
print('WARN: No session for get_followers_via_server')
2021-03-24 13:52:20 +00:00
return 6
2021-12-26 12:45:03 +00:00
domain_full = get_full_domain(domain, port)
2021-12-26 10:19:59 +00:00
followActor = local_actor_url(http_prefix, nickname, domain_full)
2021-03-24 13:52:20 +00:00
2021-12-28 21:36:27 +00:00
authHeader = create_basic_auth_header(nickname, password)
2021-03-24 13:52:20 +00:00
headers = {
'host': domain,
'Content-type': 'application/json',
'Authorization': authHeader
}
if pageNumber < 1:
pageNumber = 1
url = followActor + '/followers?page=' + str(pageNumber)
followersJson = \
2021-12-29 21:55:09 +00:00
get_json(signing_priv_key_pem, session, url, headers, {}, debug,
__version__, http_prefix, domain, 10, True)
2021-03-24 13:52:20 +00:00
if not followersJson:
if debug:
print('DEBUG: GET followers list failed for c2s to ' + url)
return 5
if debug:
print('DEBUG: c2s GET followers list request success')
return followersJson
2021-12-29 21:55:09 +00:00
def get_follow_requests_via_server(base_dir: str, session,
nickname: str, password: str,
domain: str, port: int,
http_prefix: str, pageNumber: int,
cached_webfingers: {}, person_cache: {},
debug: bool, project_version: str,
signing_priv_key_pem: str) -> {}:
"""Gets a page from the follow requests collection as json
"""
if not session:
2021-12-29 21:55:09 +00:00
print('WARN: No session for get_follow_requests_via_server')
return 6
2021-12-26 12:45:03 +00:00
domain_full = get_full_domain(domain, port)
2021-12-26 10:19:59 +00:00
followActor = local_actor_url(http_prefix, nickname, domain_full)
2021-12-28 21:36:27 +00:00
authHeader = create_basic_auth_header(nickname, password)
headers = {
'host': domain,
'Content-type': 'application/json',
'Authorization': authHeader
}
if pageNumber < 1:
pageNumber = 1
url = followActor + '/followrequests?page=' + str(pageNumber)
followersJson = \
2021-12-29 21:55:09 +00:00
get_json(signing_priv_key_pem, session, url, headers, {}, debug,
__version__, http_prefix, domain, 10, True)
if not followersJson:
if debug:
print('DEBUG: GET follow requests list failed for c2s to ' + url)
return 5
if debug:
print('DEBUG: c2s GET follow requests list request success')
return followersJson
2021-12-29 21:55:09 +00:00
def approve_follow_request_via_server(base_dir: str, session,
nickname: str, password: str,
domain: str, port: int,
http_prefix: str, approveHandle: int,
cached_webfingers: {}, person_cache: {},
debug: bool, project_version: str,
signing_priv_key_pem: str) -> str:
"""Approves a follow request
This is not exactly via c2s though. It simulates pressing the Approve
button on the web interface
"""
if not session:
2021-12-29 21:55:09 +00:00
print('WARN: No session for approve_follow_request_via_server')
return 6
2021-12-26 12:45:03 +00:00
domain_full = get_full_domain(domain, port)
2021-12-26 10:19:59 +00:00
actor = local_actor_url(http_prefix, nickname, domain_full)
2021-12-28 21:36:27 +00:00
authHeader = create_basic_auth_header(nickname, password)
headers = {
'host': domain,
'Content-type': 'text/html; charset=utf-8',
'Authorization': authHeader
}
url = actor + '/followapprove=' + approveHandle
approveHtml = \
2021-12-29 21:55:09 +00:00
get_json(signing_priv_key_pem, session, url, headers, {}, debug,
__version__, http_prefix, domain, 10, True)
if not approveHtml:
if debug:
print('DEBUG: GET approve follow request failed for c2s to ' + url)
return 5
if debug:
print('DEBUG: c2s GET approve follow request request success')
return approveHtml
2021-12-29 21:55:09 +00:00
def deny_follow_request_via_server(base_dir: str, session,
nickname: str, password: str,
domain: str, port: int,
http_prefix: str, denyHandle: int,
cached_webfingers: {}, person_cache: {},
debug: bool, project_version: str,
signing_priv_key_pem: str) -> str:
"""Denies a follow request
This is not exactly via c2s though. It simulates pressing the Deny
button on the web interface
"""
if not session:
2021-12-29 21:55:09 +00:00
print('WARN: No session for deny_follow_request_via_server')
return 6
2021-12-26 12:45:03 +00:00
domain_full = get_full_domain(domain, port)
2021-12-26 10:19:59 +00:00
actor = local_actor_url(http_prefix, nickname, domain_full)
2021-12-28 21:36:27 +00:00
authHeader = create_basic_auth_header(nickname, password)
headers = {
'host': domain,
'Content-type': 'text/html; charset=utf-8',
'Authorization': authHeader
}
url = actor + '/followdeny=' + denyHandle
denyHtml = \
2021-12-29 21:55:09 +00:00
get_json(signing_priv_key_pem, session, url, headers, {}, debug,
__version__, http_prefix, domain, 10, True)
if not denyHtml:
if debug:
print('DEBUG: GET deny follow request failed for c2s to ' + url)
return 5
if debug:
print('DEBUG: c2s GET deny follow request request success')
return denyHtml
2021-12-29 21:55:09 +00:00
def get_followers_of_actor(base_dir: str, actor: str, debug: bool) -> {}:
"""In a shared inbox if we receive a post we know who it's from
2019-07-08 17:15:55 +00:00
and if it's addressed to followers then we need to get a list of those.
This returns a list of account handles which follow the given actor
"""
2019-07-11 12:29:31 +00:00
if debug:
2020-04-03 11:38:44 +00:00
print('DEBUG: getting followers of ' + actor)
recipientsDict = {}
2019-07-08 17:15:55 +00:00
if ':' not in actor:
2019-07-08 22:12:24 +00:00
return recipientsDict
2021-12-27 22:19:18 +00:00
nickname = get_nickname_from_actor(actor)
if not nickname:
2019-07-11 12:29:31 +00:00
if debug:
2020-04-03 11:38:44 +00:00
print('DEBUG: no nickname found in ' + actor)
2019-07-08 22:12:24 +00:00
return recipientsDict
2021-12-27 19:05:25 +00:00
domain, port = get_domain_from_actor(actor)
if not domain:
2019-07-11 12:29:31 +00:00
if debug:
2020-04-03 11:38:44 +00:00
print('DEBUG: no domain found in ' + actor)
2019-07-08 22:12:24 +00:00
return recipientsDict
2020-04-03 11:38:44 +00:00
actorHandle = nickname + '@' + domain
2019-07-11 12:29:31 +00:00
if debug:
2020-04-03 11:38:44 +00:00
print('DEBUG: searching for handle ' + actorHandle)
# for each of the accounts
2021-12-25 16:17:53 +00:00
for subdir, dirs, files in os.walk(base_dir + '/accounts'):
for account in dirs:
if '@' in account and not account.startswith('inbox@'):
2020-04-03 11:38:44 +00:00
followingFilename = \
os.path.join(subdir, account) + '/following.txt'
2019-07-11 12:29:31 +00:00
if debug:
2020-04-03 11:38:44 +00:00
print('DEBUG: examining follows of ' + account)
2019-07-11 12:29:31 +00:00
print(followingFilename)
if os.path.isfile(followingFilename):
# does this account follow the given actor?
2019-07-11 12:29:31 +00:00
if debug:
2020-04-03 11:38:44 +00:00
print('DEBUG: checking if ' + actorHandle +
' in ' + followingFilename)
2019-07-08 17:15:55 +00:00
if actorHandle in open(followingFilename).read():
2019-07-11 12:29:31 +00:00
if debug:
2020-04-03 11:38:44 +00:00
print('DEBUG: ' + account +
' follows ' + actorHandle)
2020-09-27 18:35:35 +00:00
recipientsDict[account] = None
2020-12-13 22:13:45 +00:00
break
2019-07-08 22:12:24 +00:00
return recipientsDict
2019-07-17 10:34:00 +00:00
2020-04-03 11:38:44 +00:00
2021-12-29 21:55:09 +00:00
def outbox_undo_follow(base_dir: str, message_json: {}, debug: bool) -> None:
2019-07-17 10:34:00 +00:00
"""When an unfollow request is received by the outbox from c2s
This removes the followed handle from the following.txt file
of the relevant account
"""
2021-12-25 23:51:19 +00:00
if not message_json.get('type'):
2019-07-17 10:34:00 +00:00
return
2021-12-25 23:51:19 +00:00
if not message_json['type'] == 'Undo':
2019-07-17 10:34:00 +00:00
return
2021-12-26 17:12:07 +00:00
if not has_object_stringType(message_json, debug):
2019-07-17 10:34:00 +00:00
return
2021-12-25 23:51:19 +00:00
if not message_json['object']['type'] == 'Follow':
if not message_json['object']['type'] == 'Join':
return
2021-12-26 15:54:46 +00:00
if not has_object_string_object(message_json, debug):
2019-07-17 10:34:00 +00:00
return
2021-12-25 23:51:19 +00:00
if not message_json['object'].get('actor'):
2019-07-17 10:34:00 +00:00
return
if debug:
print('DEBUG: undo follow arrived in outbox')
2021-12-27 22:19:18 +00:00
nicknameFollower = get_nickname_from_actor(message_json['object']['actor'])
2019-09-02 09:43:43 +00:00
if not nicknameFollower:
2020-04-03 11:38:44 +00:00
print('WARN: unable to find nickname in ' +
2021-12-25 23:51:19 +00:00
message_json['object']['actor'])
2019-09-02 09:43:43 +00:00
return
2020-04-03 11:38:44 +00:00
domainFollower, portFollower = \
2021-12-27 19:05:25 +00:00
get_domain_from_actor(message_json['object']['actor'])
2021-12-26 12:45:03 +00:00
domainFollowerFull = get_full_domain(domainFollower, portFollower)
2020-03-22 21:16:02 +00:00
2021-12-27 22:19:18 +00:00
nicknameFollowing = \
get_nickname_from_actor(message_json['object']['object'])
2019-09-02 09:43:43 +00:00
if not nicknameFollowing:
2020-04-03 11:38:44 +00:00
print('WARN: unable to find nickname in ' +
2021-12-25 23:51:19 +00:00
message_json['object']['object'])
2019-09-02 09:43:43 +00:00
return
2020-04-03 11:38:44 +00:00
domainFollowing, portFollowing = \
2021-12-27 19:05:25 +00:00
get_domain_from_actor(message_json['object']['object'])
2021-12-26 12:45:03 +00:00
domainFollowingFull = get_full_domain(domainFollowing, portFollowing)
2019-07-17 10:34:00 +00:00
2021-12-26 00:07:44 +00:00
group_account = \
2021-12-26 17:53:07 +00:00
has_group_type(base_dir, message_json['object']['object'], None)
2021-12-28 20:32:11 +00:00
if unfollow_account(base_dir, nicknameFollower, domainFollowerFull,
nicknameFollowing, domainFollowingFull,
debug, group_account):
2019-07-17 10:34:00 +00:00
if debug:
2020-04-03 11:38:44 +00:00
print('DEBUG: ' + nicknameFollower + ' unfollowed ' +
nicknameFollowing + '@' + domainFollowingFull)
2019-07-17 10:34:00 +00:00
else:
if debug:
2020-04-03 11:38:44 +00:00
print('WARN: ' + nicknameFollower + ' could not unfollow ' +
nicknameFollowing + '@' + domainFollowingFull)
2020-11-09 15:40:24 +00:00
2021-12-28 20:32:11 +00:00
def follower_approval_active(base_dir: str,
nickname: str, domain: str) -> bool:
2020-11-09 15:40:24 +00:00
"""Returns true if the given account requires follower approval
"""
manuallyApprovesFollowers = False
2021-12-26 12:02:29 +00:00
actorFilename = acct_dir(base_dir, nickname, domain) + '.json'
2020-11-09 15:40:24 +00:00
if os.path.isfile(actorFilename):
2021-12-26 15:13:34 +00:00
actor_json = load_json(actorFilename)
2021-12-26 10:29:52 +00:00
if actor_json:
if actor_json.get('manuallyApprovesFollowers'):
2020-11-09 15:40:24 +00:00
manuallyApprovesFollowers = \
2021-12-26 10:29:52 +00:00
actor_json['manuallyApprovesFollowers']
2020-11-09 15:40:24 +00:00
return manuallyApprovesFollowers