epicyon/follow.py

301 lines
12 KiB
Python
Raw Normal View History

2019-06-29 18:23:13 +00:00
__filename__ = "follow.py"
__author__ = "Bob Mottram"
__license__ = "AGPL3+"
__version__ = "0.0.1"
__maintainer__ = "Bob Mottram"
__email__ = "bob@freedombone.net"
__status__ = "Production"
import json
from pprint import pprint
import os
import sys
2019-07-03 09:40:27 +00:00
from person import validNickname
2019-07-02 10:39:55 +00:00
from utils import domainPermitted
2019-07-05 18:57:19 +00:00
from posts import sendSignedJson
2019-06-29 18:23:13 +00:00
def getFollowersOfPerson(baseDir: str,nickname: str,domain: str,followFile='following.txt') -> []:
"""Returns a list containing the followers of the given person
Used by the shared inbox to know who to send incoming mail to
"""
followers=[]
handle=nickname.lower()+'@'+domain.lower()
if not os.path.isdir(baseDir+'/accounts/'+handle):
return followers
for subdir, dirs, files in os.walk(baseDir+'/accounts'):
for account in dirs:
filename = os.path.join(subdir, account)+'/'+followFile
if account == handle or account.startswith('sharedinbox@'):
continue
if not os.path.isfile(filename):
continue
with open(filename, 'r') as followingfile:
for followingHandle in followingfile:
if followingHandle.replace('\n','')==handle:
if account not in followers:
followers.append(account)
break
return followers
2019-07-03 09:40:27 +00:00
def followPerson(baseDir: str,nickname: str, domain: str, \
followNickname: str, followDomain: str, \
2019-07-02 19:05:59 +00:00
federationList: [], followFile='following.txt') -> bool:
2019-06-29 18:23:13 +00:00
"""Adds a person to the follow list
"""
2019-07-02 10:39:55 +00:00
if not domainPermitted(followDomain.lower().replace('\n',''), federationList):
return False
2019-07-03 09:40:27 +00:00
handle=nickname.lower()+'@'+domain.lower()
handleToFollow=followNickname.lower()+'@'+followDomain.lower()
2019-07-02 17:20:15 +00:00
if not os.path.isdir(baseDir+'/accounts'):
os.mkdir(baseDir+'/accounts')
2019-06-29 18:23:13 +00:00
if not os.path.isdir(baseDir+'/accounts/'+handle):
os.mkdir(baseDir+'/accounts/'+handle)
filename=baseDir+'/accounts/'+handle+'/'+followFile
if os.path.isfile(filename):
if handleToFollow in open(filename).read():
return True
2019-06-29 18:23:13 +00:00
with open(filename, "a") as followfile:
followfile.write(handleToFollow+'\n')
return True
2019-06-29 18:23:13 +00:00
with open(filename, "w") as followfile:
followfile.write(handleToFollow+'\n')
return True
2019-06-29 18:23:13 +00:00
2019-07-03 09:40:27 +00:00
def followerOfPerson(baseDir: str,nickname: str, domain: str, \
followerNickname: str, followerDomain: str, \
2019-07-02 19:05:59 +00:00
federationList: []) -> bool:
"""Adds a follower of the given person
"""
2019-07-03 09:40:27 +00:00
return followPerson(baseDir,nickname, domain, \
followerNickname, followerDomain, \
2019-07-02 19:05:59 +00:00
federationList, 'followers.txt')
2019-06-29 18:23:13 +00:00
2019-07-03 09:40:27 +00:00
def unfollowPerson(baseDir: str,nickname: str, domain: str, \
followNickname: str, followDomain: str, \
2019-07-02 19:05:59 +00:00
followFile='following.txt') -> None:
2019-06-29 18:23:13 +00:00
"""Removes a person to the follow list
"""
2019-07-03 09:40:27 +00:00
handle=nickname.lower()+'@'+domain.lower()
handleToUnfollow=followNickname.lower()+'@'+followDomain.lower()
2019-07-02 17:20:15 +00:00
if not os.path.isdir(baseDir+'/accounts'):
os.mkdir(baseDir+'/accounts')
2019-06-29 18:23:13 +00:00
if not os.path.isdir(baseDir+'/accounts/'+handle):
os.mkdir(baseDir+'/accounts/'+handle)
filename=baseDir+'/accounts/'+handle+'/'+followFile
if os.path.isfile(filename):
if handleToUnfollow not in open(filename).read():
return
with open(filename, "r") as f:
lines = f.readlines()
with open(filename, "w") as f:
for line in lines:
if line.strip("\n") != handleToUnfollow:
f.write(line)
2019-07-03 09:40:27 +00:00
def unfollowerOfPerson(baseDir: str,nickname: str,domain: str, \
followerNickname: str,followerDomain: str) -> None:
"""Remove a follower of a person
"""
2019-07-03 09:40:27 +00:00
unfollowPerson(baseDir,nickname,domain,followerNickname,followerDomain,'followers.txt')
2019-06-29 18:23:13 +00:00
2019-07-03 09:40:27 +00:00
def clearFollows(baseDir: str,nickname: str,domain: str,followFile='following.txt') -> None:
2019-06-29 18:23:13 +00:00
"""Removes all follows
"""
2019-07-03 09:40:27 +00:00
handle=nickname.lower()+'@'+domain.lower()
2019-07-02 17:20:15 +00:00
if not os.path.isdir(baseDir+'/accounts'):
os.mkdir(baseDir+'/accounts')
2019-06-29 18:23:13 +00:00
if not os.path.isdir(baseDir+'/accounts/'+handle):
os.mkdir(baseDir+'/accounts/'+handle)
filename=baseDir+'/accounts/'+handle+'/'+followFile
if os.path.isfile(filename):
os.remove(filename)
2019-07-03 09:40:27 +00:00
def clearFollowers(baseDir: str,nickname: str,domain: str) -> None:
"""Removes all followers
"""
2019-07-03 09:40:27 +00:00
clearFollows(baseDir,nickname, domain,'followers.txt')
2019-06-29 20:21:37 +00:00
2019-07-03 09:40:27 +00:00
def getNoOfFollows(baseDir: str,nickname: str,domain: str,followFile='following.txt') -> int:
"""Returns the number of follows or followers
"""
2019-07-03 09:40:27 +00:00
handle=nickname.lower()+'@'+domain.lower()
2019-06-29 20:21:37 +00:00
filename=baseDir+'/accounts/'+handle+'/'+followFile
if not os.path.isfile(filename):
return 0
ctr = 0
with open(filename, "r") as f:
lines = f.readlines()
for line in lines:
if '#' not in line:
if '@' in line and '.' in line and not line.startswith('http'):
ctr += 1
elif line.startswith('http') and '/users/' in line:
ctr += 1
return ctr
2019-07-03 09:40:27 +00:00
def getNoOfFollowers(baseDir: str,nickname: str,domain: str) -> int:
"""Returns the number of followers of the given person
"""
2019-07-03 09:40:27 +00:00
return getNoOfFollows(baseDir,nickname,domain,'followers.txt')
2019-06-29 20:21:37 +00:00
2019-07-03 19:00:03 +00:00
def getFollowingFeed(baseDir: str,domain: str,port: int,path: str,httpPrefix: str, \
2019-07-02 19:05:59 +00:00
followsPerPage=12,followFile='following') -> {}:
"""Returns the following and followers feeds from GET requests
"""
2019-06-29 20:21:37 +00:00
if '/'+followFile not in path:
return None
# handle page numbers
headerOnly=True
pageNumber=None
if '?page=' in path:
pageNumber=path.split('?page=')[1]
if pageNumber=='true':
pageNumber=1
else:
try:
pageNumber=int(pageNumber)
except:
pass
path=path.split('?page=')[0]
headerOnly=False
if not path.endswith('/'+followFile):
return None
2019-07-03 09:40:27 +00:00
nickname=None
2019-06-29 20:21:37 +00:00
if path.startswith('/users/'):
2019-07-03 09:40:27 +00:00
nickname=path.replace('/users/','',1).replace('/'+followFile,'')
2019-06-29 20:21:37 +00:00
if path.startswith('/@'):
2019-07-03 09:40:27 +00:00
nickname=path.replace('/@','',1).replace('/'+followFile,'')
if not nickname:
2019-06-29 20:21:37 +00:00
return None
2019-07-03 09:40:27 +00:00
if not validNickname(nickname):
2019-06-29 20:21:37 +00:00
return None
2019-06-30 19:01:43 +00:00
if port!=80 and port!=443:
domain=domain+':'+str(port)
2019-06-29 20:21:37 +00:00
if headerOnly:
following = {
'@context': 'https://www.w3.org/ns/activitystreams',
2019-07-03 19:00:03 +00:00
'first': httpPrefix+'://'+domain+'/users/'+nickname+'/'+followFile+'?page=1',
'id': httpPrefix+'://'+domain+'/users/'+nickname+'/'+followFile,
2019-07-03 09:40:27 +00:00
'totalItems': getNoOfFollows(nickname,domain),
2019-06-29 20:21:37 +00:00
'type': 'OrderedCollection'}
return following
if not pageNumber:
pageNumber=1
nextPageNumber=int(pageNumber+1)
following = {
'@context': 'https://www.w3.org/ns/activitystreams',
2019-07-03 19:00:03 +00:00
'id': httpPrefix+'://'+domain+'/users/'+nickname+'/'+followFile+'?page='+str(pageNumber),
2019-06-29 20:21:37 +00:00
'orderedItems': [],
2019-07-03 19:00:03 +00:00
'partOf': httpPrefix+'://'+domain+'/users/'+nickname+'/'+followFile,
2019-06-29 20:21:37 +00:00
'totalItems': 0,
'type': 'OrderedCollectionPage'}
2019-07-03 09:40:27 +00:00
handle=nickname.lower()+'@'+domain.lower()
2019-06-29 20:21:37 +00:00
filename=baseDir+'/accounts/'+handle+'/'+followFile+'.txt'
if not os.path.isfile(filename):
return following
currPage=1
pageCtr=0
totalCtr=0
with open(filename, "r") as f:
lines = f.readlines()
for line in lines:
if '#' not in line:
if '@' in line and '.' in line and not line.startswith('http'):
pageCtr += 1
totalCtr += 1
if currPage==pageNumber:
2019-07-03 19:00:03 +00:00
url = httpPrefix + '://' + line.lower().replace('\n','').split('@')[1] + \
2019-06-29 20:21:37 +00:00
'/users/' + line.lower().replace('\n','').split('@')[0]
following['orderedItems'].append(url)
2019-07-03 19:00:03 +00:00
elif (line.startswith('http') or line.startswith('dat')) and '/users/' in line:
2019-06-29 20:21:37 +00:00
pageCtr += 1
totalCtr += 1
if currPage==pageNumber:
following['orderedItems'].append(line.lower().replace('\n',''))
if pageCtr>=followsPerPage:
pageCtr=0
currPage += 1
following['totalItems']=totalCtr
lastPage=int(totalCtr/followsPerPage)
if lastPage<1:
lastPage=1
if nextPageNumber>lastPage:
2019-07-03 19:00:03 +00:00
following['next']=httpPrefix+'://'+domain+'/users/'+nickname+'/'+followFile+'?page='+str(lastPage)
2019-06-29 20:21:37 +00:00
return following
2019-07-02 18:17:04 +00:00
2019-07-05 18:57:19 +00:00
def receiveFollowRequest(session,baseDir: str,httpPrefix: str,port: int,sendThreads: [],postLog: [],cachedWebfingers: {},personCache: {},messageJson: {},federationList: []) -> bool:
2019-07-02 18:38:51 +00:00
"""Receives a follow request within the POST section of HTTPServer
"""
2019-07-05 18:57:19 +00:00
if not messageJson.get('actor'):
return False
2019-07-02 18:17:04 +00:00
if not messageJson['type'].startswith('Follow'):
return False
if '/users/' not in messageJson['actor']:
return False
2019-07-03 19:00:03 +00:00
domain=messageJson['actor'].split('/users/')[0].replace('https://','').replace('http://','').replace('dat://','')
2019-07-02 18:17:04 +00:00
if not domainPermitted(domain,federationList):
return False
2019-07-03 09:40:27 +00:00
nickname=messageJson['actor'].split('/users/')[1].replace('@','')
handle=nickname.lower()+'@'+domain.lower()
2019-07-02 18:17:04 +00:00
if not os.path.isdir(baseDir+'/accounts/'+handle):
return False
if '/users/' not in messageJson['object']:
return False
2019-07-03 19:00:03 +00:00
domainToFollow=messageJson['object'].split('/users/')[0].replace('https://','').replace('http://','').replace('dat://','')
2019-07-02 18:17:04 +00:00
if not domainPermitted(domainToFollow,federationList):
return False
2019-07-03 09:40:27 +00:00
nicknameToFollow=messageJson['object'].split('/users/')[1].replace('@','')
handleToFollow=nicknameToFollow.lower()+'@'+domainToFollow.lower()
2019-07-02 18:17:04 +00:00
if domainToFollow==domain:
if not os.path.isdir(baseDir+'/accounts/'+handleToFollow):
return False
2019-07-05 18:57:19 +00:00
if not followerOfPerson(baseDir,nickname,domain,nicknameToFollow,domainToFollow,federationList):
return False
# send accept back
personUrl=messageJson['actor']
acceptJson=createAccept(baseDir,federationList,nickname,domain,port, \
personUrl,'',httpPrefix,messageJson['object'])
sendSignedJson(acceptJson,session,baseDir,nickname,domain,port, \
nicknameToFollow,domainToFollow,toPort, '', \
httpPrefix,saveToFile,clientToServer,federationList, \
sendThreads,postLog,cachedWebfingers,personCache)
2019-07-02 18:38:51 +00:00
2019-07-03 19:00:03 +00:00
def sendFollowRequest(baseDir: str,nickname: str,domain: str,port: int,httpPrefix: str, \
followNickname: str,followDomain: str,followPort: bool,followHttpPrefix: str, \
2019-07-02 20:54:22 +00:00
federationList: []) -> {}:
"""Gets the json object for sending a follow request
2019-07-02 19:05:59 +00:00
"""
2019-07-02 18:38:51 +00:00
if not domainPermitted(followDomain,federationList):
return None
if port!=80 and port!=443:
domain=domain+':'+str(port)
if followPort!=80 and followPort!=443:
followDomain=followDomain+':'+str(followPort)
2019-07-05 20:32:21 +00:00
newFollowJson = {
2019-07-02 18:38:51 +00:00
'type': 'Follow',
2019-07-03 19:00:03 +00:00
'actor': httpPrefix+'://'+domain+'/users/'+nickname,
'object': followHttpPrefix+'://'+followDomain+'/users/'+followNickname,
2019-07-02 18:38:51 +00:00
'to': [toUrl],
'cc': []
}
2019-07-02 19:05:59 +00:00
2019-07-02 18:38:51 +00:00
if ccUrl:
if len(ccUrl)>0:
2019-07-05 20:32:21 +00:00
newFollowJson['cc']=ccUrl
sendSignedJson(newFollowJson,session,baseDir,nickname,domain,port, \
nicknameToFollow,domainToFollow,toPort, '', \
httpPrefix,saveToFile,clientToServer,federationList, \
sendThreads,postLog,cachedWebfingers,personCache)
return newFollowJson