epicyon/like.py

557 lines
20 KiB
Python
Raw Normal View History

2019-07-02 11:13:45 +00:00
__filename__ = "like.py"
__author__ = "Bob Mottram"
__license__ = "AGPL3+"
__version__ = "0.0.1"
__maintainer__ = "Bob Mottram"
__email__ = "bob@freedombone.net"
__status__ = "Production"
import json
import commentjson
2019-07-11 12:29:31 +00:00
from pprint import pprint
2019-07-02 11:13:45 +00:00
from utils import urlPermitted
2019-07-10 09:47:07 +00:00
from utils import getNicknameFromActor
from utils import getDomainFromActor
2019-07-11 12:29:31 +00:00
from utils import locatePost
from posts import sendSignedJson
2019-07-17 19:31:52 +00:00
from session import postJson
from webfinger import webfingerHandle
from auth import createBasicAuthHeader
from posts import getPersonBox
2019-07-11 12:29:31 +00:00
2019-08-01 12:49:16 +00:00
def undoLikesCollectionEntry(postFilename: str,objectUrl: str,actor: str,debug: bool) -> None:
2019-07-11 22:22:27 +00:00
"""Undoes a like for a particular actor
2019-08-01 12:49:16 +00:00
"""
2019-07-11 22:22:27 +00:00
with open(postFilename, 'r') as fp:
2019-07-14 16:57:06 +00:00
postJsonObject=commentjson.load(fp)
if not postJsonObject.get('type'):
return
if postJsonObject['type']!='Create':
2019-07-12 10:06:36 +00:00
return
2019-07-14 16:57:06 +00:00
if not postJsonObject.get('object'):
2019-07-11 22:22:27 +00:00
if debug:
2019-07-14 16:57:06 +00:00
pprint(postJsonObject)
2019-07-11 22:22:27 +00:00
print('DEBUG: post '+objectUrl+' has no object')
return
if not isinstance(postJsonObject['object'], dict):
return
2019-07-14 16:57:06 +00:00
if not postJsonObject['object'].get('likes'):
2019-07-11 22:22:27 +00:00
return
2019-07-14 16:57:06 +00:00
if not postJsonObject['object']['likes'].get('items'):
2019-07-11 22:22:27 +00:00
return
totalItems=0
2019-07-14 16:57:06 +00:00
if postJsonObject['object']['likes'].get('totalItems'):
totalItems=postJsonObject['object']['likes']['totalItems']
2019-07-11 22:22:27 +00:00
itemFound=False
2019-07-14 16:57:06 +00:00
for likeItem in postJsonObject['object']['likes']['items']:
2019-07-11 22:22:27 +00:00
if likeItem.get('actor'):
if likeItem['actor']==actor:
if debug:
print('DEBUG: like was removed for '+actor)
2019-07-14 16:57:06 +00:00
postJsonObject['object']['likes']['items'].remove(likeItem)
2019-07-11 22:22:27 +00:00
itemFound=True
break
if itemFound:
if totalItems==1:
if debug:
print('DEBUG: likes was removed from post')
2019-08-01 12:18:22 +00:00
del postJsonObject['object']['likes']
2019-07-11 22:22:27 +00:00
else:
2019-07-14 16:57:06 +00:00
postJsonObject['object']['likes']['totalItems']=len(postJsonObject['likes']['items'])
2019-07-11 22:22:27 +00:00
with open(postFilename, 'w') as fp:
2019-07-14 16:57:06 +00:00
commentjson.dump(postJsonObject, fp, indent=4, sort_keys=True)
2019-07-11 22:22:27 +00:00
2019-08-01 09:05:09 +00:00
def likedByPerson(postJsonObject: {}, nickname: str,domain: str) -> bool:
"""Returns True if the given post is liked by the given person
2019-08-01 09:05:09 +00:00
"""
if not postJsonObject.get('object'):
return False
if not isinstance(postJsonObject['object'], dict):
return False
if not postJsonObject['object'].get('likes'):
return False
actorMatch=domain+'/users/'+nickname
for item in postJsonObject['object']['likes']['items']:
if item['actor'].endswith(actorMatch):
return True
return False
2019-07-11 12:29:31 +00:00
def updateLikesCollection(postFilename: str,objectUrl: str, actor: str,debug: bool) -> None:
"""Updates the likes collection within a post
"""
with open(postFilename, 'r') as fp:
2019-07-14 16:57:06 +00:00
postJsonObject=commentjson.load(fp)
if not postJsonObject.get('object'):
2019-07-11 12:29:31 +00:00
if debug:
2019-07-14 16:57:06 +00:00
pprint(postJsonObject)
2019-07-11 12:29:31 +00:00
print('DEBUG: post '+objectUrl+' has no object')
return
if not objectUrl.endswith('/likes'):
objectUrl=objectUrl+'/likes'
2019-07-14 16:57:06 +00:00
if not postJsonObject['object'].get('likes'):
2019-07-11 12:29:31 +00:00
if debug:
print('DEBUG: Adding initial likes to '+objectUrl)
likesJson = {
'id': objectUrl,
'type': 'Collection',
"totalItems": 1,
'items': [{
'type': 'Like',
'actor': actor
}]
}
2019-07-14 16:57:06 +00:00
postJsonObject['object']['likes']=likesJson
2019-07-11 12:29:31 +00:00
else:
2019-07-14 16:57:06 +00:00
if postJsonObject['object']['likes'].get('items'):
for likeItem in postJsonObject['likes']['items']:
2019-07-11 12:29:31 +00:00
if likeItem.get('actor'):
if likeItem['actor']==actor:
return
newLike={
'type': 'Like',
'actor': actor
}
2019-07-14 16:57:06 +00:00
postJsonObject['object']['likes']['items'].append(newLike)
postJsonObject['object']['likes']['totalItems']=len(postJsonObject['likes']['items'])
2019-07-11 12:29:31 +00:00
else:
if debug:
print('DEBUG: likes section of post has no items list')
if debug:
print('DEBUG: saving post with likes added')
2019-07-18 12:01:53 +00:00
pprint(postJsonObject)
2019-07-11 12:29:31 +00:00
with open(postFilename, 'w') as fp:
2019-07-14 16:57:06 +00:00
commentjson.dump(postJsonObject, fp, indent=4, sort_keys=True)
2019-07-02 11:13:45 +00:00
2019-07-10 09:47:07 +00:00
def like(session,baseDir: str,federationList: [],nickname: str,domain: str,port: int, \
2019-07-11 12:29:31 +00:00
ccList: [],httpPrefix: str,objectUrl: str,clientToServer: bool, \
sendThreads: [],postLog: [],personCache: {},cachedWebfingers: {}, \
2019-08-14 20:12:27 +00:00
debug: bool,projectVersion: str) -> {}:
2019-07-02 11:13:45 +00:00
"""Creates a like
2019-07-12 09:10:09 +00:00
actor is the person doing the liking
'to' might be a specific person (actor) whose post was liked
object is typically the url of the message which was liked
2019-07-02 11:13:45 +00:00
"""
2019-07-09 14:20:23 +00:00
if not urlPermitted(objectUrl,federationList,"inbox:write"):
2019-07-02 11:13:45 +00:00
return None
2019-07-11 12:29:31 +00:00
fullDomain=domain
2019-07-02 11:13:45 +00:00
if port!=80 and port!=443:
2019-07-11 12:29:31 +00:00
if ':' not in domain:
fullDomain=domain+':'+str(port)
2019-07-02 11:13:45 +00:00
2019-08-07 11:02:15 +00:00
likeTo=[]
if '/statuses/' in objectUrl:
likeTo=[objectUrl.split('/statuses/')[0]]
2019-07-10 09:47:07 +00:00
newLikeJson = {
2019-07-02 11:13:45 +00:00
'type': 'Like',
2019-07-11 12:29:31 +00:00
'actor': httpPrefix+'://'+fullDomain+'/users/'+nickname,
2019-07-02 11:13:45 +00:00
'object': objectUrl,
2019-08-07 11:02:15 +00:00
'to': likeTo,
'cc': [httpPrefix+'://'+fullDomain+'/users/'+nickname+'/followers']
2019-07-02 11:13:45 +00:00
}
2019-07-11 12:29:31 +00:00
if ccList:
if len(ccList)>0:
newLikeJson['cc']=ccList
2019-07-10 09:47:07 +00:00
# Extract the domain and nickname from a statuses link
likedPostNickname=None
likedPostDomain=None
likedPostPort=None
if '/users/' in objectUrl:
likedPostNickname=getNicknameFromActor(objectUrl)
likedPostDomain,likedPostPort=getDomainFromActor(objectUrl)
if likedPostNickname:
2019-07-11 12:29:31 +00:00
postFilename=locatePost(baseDir,nickname,domain,objectUrl)
if not postFilename:
2019-08-16 15:04:40 +00:00
print('DEBUG: like baseDir: '+baseDir)
print('DEBUG: like nickname: '+nickname)
print('DEBUG: like domain: '+domain)
print('DEBUG: like objectUrl: '+objectUrl)
2019-07-11 12:29:31 +00:00
return None
updateLikesCollection(postFilename,objectUrl,newLikeJson['actor'],debug)
sendSignedJson(newLikeJson,session,baseDir, \
2019-07-10 09:47:07 +00:00
nickname,domain,port, \
likedPostNickname,likedPostDomain,likedPostPort, \
'https://www.w3.org/ns/activitystreams#Public', \
httpPrefix,True,clientToServer,federationList, \
2019-08-14 20:12:27 +00:00
sendThreads,postLog,cachedWebfingers,personCache, \
debug,projectVersion)
2019-07-10 09:47:07 +00:00
return newLikeJson
def likePost(session,baseDir: str,federationList: [], \
2019-07-11 12:29:31 +00:00
nickname: str,domain: str,port: int,httpPrefix: str, \
likeNickname: str,likeDomain: str,likePort: int, \
ccList: [], \
likeStatusNumber: int,clientToServer: bool, \
sendThreads: [],postLog: [], \
personCache: {},cachedWebfingers: {}, \
2019-08-14 20:12:27 +00:00
debug: bool,projectVersion: str) -> {}:
2019-07-02 14:02:58 +00:00
"""Likes a given status post
"""
likeDomain=likeDomain
if likePort!=80 and likePort!=443:
2019-08-16 15:04:40 +00:00
if ':' not in likeDomain:
likeDomain=likeDomain+':'+str(likePort)
2019-07-02 14:02:58 +00:00
2019-07-10 09:47:07 +00:00
objectUrl = \
httpPrefix + '://'+likeDomain+'/users/'+likeNickname+ \
'/statuses/'+str(likeStatusNumber)
2019-07-02 14:02:58 +00:00
2019-07-11 12:29:31 +00:00
if likePort!=80 and likePort!=443:
ccUrl=httpPrefix+'://'+likeDomain+':'+str(likePort)+'/users/'+likeNickname
else:
ccUrl=httpPrefix+'://'+likeDomain+'/users/'+likeNickname
2019-07-10 09:47:07 +00:00
return like(session,baseDir,federationList,nickname,domain,port, \
2019-07-11 12:29:31 +00:00
ccList,httpPrefix,objectUrl,clientToServer, \
2019-08-14 20:12:27 +00:00
sendThreads,postLog,personCache,cachedWebfingers, \
debug,projectVersion)
2019-07-10 12:40:31 +00:00
2019-07-12 09:10:09 +00:00
def undolike(session,baseDir: str,federationList: [],nickname: str,domain: str,port: int, \
ccList: [],httpPrefix: str,objectUrl: str,clientToServer: bool, \
sendThreads: [],postLog: [],personCache: {},cachedWebfingers: {}, \
2019-08-14 20:12:27 +00:00
debug: bool,projectVersion: str) -> {}:
2019-07-12 09:10:09 +00:00
"""Removes a like
actor is the person doing the liking
'to' might be a specific person (actor) whose post was liked
object is typically the url of the message which was liked
"""
if not urlPermitted(objectUrl,federationList,"inbox:write"):
return None
fullDomain=domain
if port!=80 and port!=443:
if ':' not in domain:
fullDomain=domain+':'+str(port)
2019-08-07 11:02:15 +00:00
likeTo=[]
if '/statuses/' in objectUrl:
likeTo=[objectUrl.split('/statuses/')[0]]
2019-07-12 09:10:09 +00:00
newUndoLikeJson = {
'type': 'Undo',
'actor': httpPrefix+'://'+fullDomain+'/users/'+nickname,
'object': {
'type': 'Like',
'actor': httpPrefix+'://'+fullDomain+'/users/'+nickname,
'object': objectUrl,
2019-08-07 11:02:15 +00:00
'to': likeTo,
'cc': [httpPrefix+'://'+fullDomain+'/users/'+nickname+'/followers']
2019-07-12 09:10:09 +00:00
},
2019-08-07 11:02:15 +00:00
'cc': [httpPrefix+'://'+fullDomain+'/users/'+nickname+'/followers'],
'to': likeTo
2019-07-12 09:10:09 +00:00
}
if ccList:
if len(ccList)>0:
newUndoLikeJson['cc']=ccList
newUndoLikeJson['object']['cc']=ccList
# Extract the domain and nickname from a statuses link
likedPostNickname=None
likedPostDomain=None
likedPostPort=None
if '/users/' in objectUrl:
likedPostNickname=getNicknameFromActor(objectUrl)
likedPostDomain,likedPostPort=getDomainFromActor(objectUrl)
if likedPostNickname:
postFilename=locatePost(baseDir,nickname,domain,objectUrl)
if not postFilename:
return None
undoLikesCollectionEntry(postFilename,objectUrl,newLikeJson['actor'],debug)
2019-07-12 09:41:57 +00:00
sendSignedJson(newUndoLikeJson,session,baseDir, \
2019-07-12 09:10:09 +00:00
nickname,domain,port, \
likedPostNickname,likedPostDomain,likedPostPort, \
'https://www.w3.org/ns/activitystreams#Public', \
httpPrefix,True,clientToServer,federationList, \
2019-08-14 20:12:27 +00:00
sendThreads,postLog,cachedWebfingers,personCache, \
debug,projectVersion)
2019-07-12 09:10:09 +00:00
else:
return None
2019-07-12 09:41:57 +00:00
return newUndoLikeJson
2019-07-12 09:10:09 +00:00
def undoLikePost(session,baseDir: str,federationList: [], \
nickname: str,domain: str,port: int,httpPrefix: str, \
likeNickname: str,likeDomain: str,likePort: int, \
ccList: [], \
likeStatusNumber: int,clientToServer: bool, \
sendThreads: [],postLog: [], \
personCache: {},cachedWebfingers: {}, \
debug: bool) -> {}:
"""Removes a liked post
"""
likeDomain=likeDomain
if likePort!=80 and likePort!=443:
likeDomain=likeDomain+':'+str(likePort)
objectUrl = \
httpPrefix + '://'+likeDomain+'/users/'+likeNickname+ \
'/statuses/'+str(likeStatusNumber)
if likePort!=80 and likePort!=443:
ccUrl=httpPrefix+'://'+likeDomain+':'+str(likePort)+'/users/'+likeNickname
else:
ccUrl=httpPrefix+'://'+likeDomain+'/users/'+likeNickname
return undoLike(session,baseDir,federationList,nickname,domain,port, \
ccList,httpPrefix,objectUrl,clientToServer, \
sendThreads,postLog,personCache,cachedWebfingers,debug)
2019-07-17 18:33:41 +00:00
def sendLikeViaServer(session,fromNickname: str,password: str,
fromDomain: str,fromPort: int, \
httpPrefix: str,likeUrl: str, \
cachedWebfingers: {},personCache: {}, \
2019-08-14 20:12:27 +00:00
debug: bool,projectVersion: str) -> {}:
2019-07-17 18:33:41 +00:00
"""Creates a like via c2s
"""
if not session:
print('WARN: No session for sendLikeViaServer')
return 6
fromDomainFull=fromDomain
if fromPort!=80 and fromPort!=443:
fromDomainFull=fromDomain+':'+str(fromPort)
2019-08-07 11:02:15 +00:00
toUrl = ['https://www.w3.org/ns/activitystreams#Public']
2019-07-17 18:33:41 +00:00
ccUrl = httpPrefix + '://'+fromDomainFull+'/users/'+fromNickname+'/followers'
2019-08-07 11:02:15 +00:00
if '/statuses/' in likeUrl:
toUrl=[likeUrl.split('/statuses/')[0]]
2019-07-17 18:33:41 +00:00
newLikeJson = {
'type': 'Like',
2019-07-17 19:04:00 +00:00
'actor': httpPrefix+'://'+fromDomainFull+'/users/'+fromNickname,
2019-07-17 18:33:41 +00:00
'object': likeUrl,
2019-08-07 11:02:15 +00:00
'to': toUrl,
2019-07-17 18:33:41 +00:00
'cc': [ccUrl]
}
handle=httpPrefix+'://'+fromDomainFull+'/@'+fromNickname
# lookup the inbox for the To handle
2019-08-14 20:12:27 +00:00
wfRequest = webfingerHandle(session,handle,httpPrefix,cachedWebfingers, \
fromDomain,projectVersion)
2019-07-17 18:33:41 +00:00
if not wfRequest:
if debug:
print('DEBUG: announce webfinger failed for '+handle)
return 1
postToBox='outbox'
# get the actor inbox for the To handle
2019-07-22 14:21:49 +00:00
inboxUrl,pubKeyId,pubKey,fromPersonId,sharedInbox,capabilityAcquisition,avatarUrl,preferredName = \
2019-08-14 20:12:27 +00:00
getPersonBox(session,wfRequest,personCache, \
projectVersion,httpPrefix,fromDomain,postToBox)
2019-07-17 18:33:41 +00:00
if not inboxUrl:
if debug:
print('DEBUG: No '+postToBox+' was found for '+handle)
return 3
if not fromPersonId:
if debug:
print('DEBUG: No actor was found for '+handle)
return 4
authHeader=createBasicAuthHeader(fromNickname,password)
headers = {'host': fromDomain, \
'Content-type': 'application/json', \
'Authorization': authHeader}
postResult = \
postJson(session,newLikeJson,[],inboxUrl,headers,"inbox:write")
#if not postResult:
# if debug:
# print('DEBUG: POST announce failed for c2s to '+inboxUrl)
# return 5
if debug:
print('DEBUG: c2s POST like success')
return newLikeJson
2019-07-17 19:04:00 +00:00
def sendUndoLikeViaServer(session,fromNickname: str,password: str,
fromDomain: str,fromPort: int, \
httpPrefix: str,likeUrl: str, \
cachedWebfingers: {},personCache: {}, \
2019-08-14 20:12:27 +00:00
debug: bool,projectVersion: str) -> {}:
2019-07-17 19:04:00 +00:00
"""Undo a like via c2s
"""
if not session:
print('WARN: No session for sendUndoLikeViaServer')
return 6
fromDomainFull=fromDomain
if fromPort!=80 and fromPort!=443:
fromDomainFull=fromDomain+':'+str(fromPort)
2019-08-07 11:02:15 +00:00
toUrl = ['https://www.w3.org/ns/activitystreams#Public']
2019-07-17 19:04:00 +00:00
ccUrl = httpPrefix + '://'+fromDomainFull+'/users/'+fromNickname+'/followers'
2019-08-07 11:02:15 +00:00
if '/statuses/' in likeUrl:
toUrl=[likeUrl.split('/statuses/')[0]]
2019-07-17 19:04:00 +00:00
newUndoLikeJson = {
'type': 'Undo',
'actor': httpPrefix+'://'+fromDomainFull+'/users/'+fromNickname,
'object': {
'type': 'Like',
'actor': httpPrefix+'://'+fromDomainFull+'/users/'+fromNickname,
'object': likeUrl,
2019-08-07 11:02:15 +00:00
'to': toUrl,
2019-07-17 19:04:00 +00:00
'cc': [ccUrl]
}
}
handle=httpPrefix+'://'+fromDomainFull+'/@'+fromNickname
# lookup the inbox for the To handle
2019-08-14 20:12:27 +00:00
wfRequest = webfingerHandle(session,handle,httpPrefix,cachedWebfingers, \
fromDomain,projectVersion)
2019-07-17 19:04:00 +00:00
if not wfRequest:
if debug:
print('DEBUG: announce webfinger failed for '+handle)
return 1
postToBox='outbox'
# get the actor inbox for the To handle
2019-07-22 14:21:49 +00:00
inboxUrl,pubKeyId,pubKey,fromPersonId,sharedInbox,capabilityAcquisition,avatarUrl,preferredName = \
2019-08-14 20:12:27 +00:00
getPersonBox(session,wfRequest,personCache, \
projectVersion,httpPrefix,fromDomain,postToBox)
2019-07-17 19:04:00 +00:00
if not inboxUrl:
if debug:
print('DEBUG: No '+postToBox+' was found for '+handle)
return 3
if not fromPersonId:
if debug:
print('DEBUG: No actor was found for '+handle)
return 4
authHeader=createBasicAuthHeader(fromNickname,password)
headers = {'host': fromDomain, \
'Content-type': 'application/json', \
'Authorization': authHeader}
postResult = \
postJson(session,newUndoLikeJson,[],inboxUrl,headers,"inbox:write")
#if not postResult:
# if debug:
# print('DEBUG: POST announce failed for c2s to '+inboxUrl)
# return 5
if debug:
print('DEBUG: c2s POST undo like success')
return newUndoLikeJson
2019-07-17 19:31:52 +00:00
def outboxLike(baseDir: str,httpPrefix: str, \
nickname: str,domain: str,port: int, \
messageJson: {},debug: bool) -> None:
""" When a like request is received by the outbox from c2s
"""
if not messageJson.get('type'):
if debug:
print('DEBUG: like - no type')
return
if not messageJson['type']=='Like':
if debug:
print('DEBUG: not a like')
return
if not messageJson.get('object'):
if debug:
print('DEBUG: no object in like')
return
if not isinstance(messageJson['object'], str):
if debug:
print('DEBUG: like object is not string')
return
if debug:
print('DEBUG: c2s like request arrived in outbox')
messageId=messageJson['object'].replace('/activity','')
if '/statuses/' not in messageId:
if debug:
print('DEBUG: c2s like object is not a status')
return
if '/users/' not in messageId:
if debug:
print('DEBUG: c2s like object has no nickname')
return
if ':' in domain:
domain=domain.split(':')[0]
2019-07-17 19:47:36 +00:00
postFilename=locatePost(baseDir,nickname,domain,messageId)
2019-07-17 19:31:52 +00:00
if not postFilename:
if debug:
print('DEBUG: c2s like post not found in inbox or outbox')
print(messageId)
return True
updateLikesCollection(postFilename,messageId,messageJson['actor'],debug)
if debug:
print('DEBUG: post liked via c2s - '+postFilename)
2019-07-17 19:55:24 +00:00
def outboxUndoLike(baseDir: str,httpPrefix: str, \
nickname: str,domain: str,port: int, \
messageJson: {},debug: bool) -> None:
""" When an undo like request is received by the outbox from c2s
"""
if not messageJson.get('type'):
return
if not messageJson['type']=='Undo':
return
if not messageJson.get('object'):
return
2019-08-01 12:49:16 +00:00
if not isinstance(messageJson['object'], dict):
2019-07-17 19:55:24 +00:00
if debug:
print('DEBUG: undo like object is not dict')
2019-08-01 12:49:16 +00:00
return
2019-07-17 19:55:24 +00:00
if not messageJson['object'].get('type'):
if debug:
print('DEBUG: undo like - no type')
return
if not messageJson['object']['type']=='Like':
if debug:
print('DEBUG: not a undo like')
return
if not messageJson['object'].get('object'):
if debug:
print('DEBUG: no object in undo like')
return
if not isinstance(messageJson['object']['object'], str):
if debug:
print('DEBUG: undo like object is not string')
return
if debug:
print('DEBUG: c2s undo like request arrived in outbox')
messageId=messageJson['object']['object'].replace('/activity','')
if '/statuses/' not in messageId:
if debug:
print('DEBUG: c2s undo like object is not a status')
return
if '/users/' not in messageId:
if debug:
print('DEBUG: c2s undo like object has no nickname')
return
if ':' in domain:
domain=domain.split(':')[0]
postFilename=locatePost(baseDir,nickname,domain,messageId)
if not postFilename:
if debug:
print('DEBUG: c2s undo like post not found in inbox or outbox')
print(messageId)
return True
undoLikesCollectionEntry(postFilename,messageId,messageJson['actor'],debug)
if debug:
print('DEBUG: post undo liked via c2s - '+postFilename)