flake8 style

main
Bob Mottram 2020-04-01 10:44:33 +00:00
parent 33a397b9fb
commit abe216a2b3
1 changed files with 233 additions and 279 deletions

512
like.py
View File

@ -1,14 +1,12 @@
__filename__="like.py" __filename__ = "like.py"
__author__="Bob Mottram" __author__ = "Bob Mottram"
__license__="AGPL3+" __license__ = "AGPL3+"
__version__="1.1.0" __version__ = "1.1.0"
__maintainer__="Bob Mottram" __maintainer__ = "Bob Mottram"
__email__="bob@freedombone.net" __email__ = "bob@freedombone.net"
__status__="Production" __status__ = "Production"
import os import os
import json
import time
from pprint import pprint from pprint import pprint
from utils import removePostFromCache from utils import removePostFromCache
from utils import urlPermitted from utils import urlPermitted
@ -24,25 +22,27 @@ from webfinger import webfingerHandle
from auth import createBasicAuthHeader from auth import createBasicAuthHeader
from posts import getPersonBox from posts import getPersonBox
def undoLikesCollectionEntry(recentPostsCache: {}, \
baseDir: str,postFilename: str,objectUrl: str, \ def undoLikesCollectionEntry(recentPostsCache: {},
actor: str,domain: str,debug: bool) -> None: baseDir: str, postFilename: str, objectUrl: str,
actor: str, domain: str, debug: bool) -> None:
"""Undoes a like for a particular actor """Undoes a like for a particular actor
""" """
postJsonObject=loadJson(postFilename) postJsonObject = loadJson(postFilename)
if postJsonObject: if postJsonObject:
# remove any cached version of this post so that the like icon is changed # remove any cached version of this post so that the
nickname=getNicknameFromActor(actor) # like icon is changed
cachedPostFilename= \ nickname = getNicknameFromActor(actor)
getCachedPostFilename(baseDir,nickname,domain,postJsonObject) cachedPostFilename = getCachedPostFilename(baseDir, nickname,
domain, postJsonObject)
if cachedPostFilename: if cachedPostFilename:
if os.path.isfile(cachedPostFilename): if os.path.isfile(cachedPostFilename):
os.remove(cachedPostFilename) os.remove(cachedPostFilename)
removePostFromCache(postJsonObject,recentPostsCache) removePostFromCache(postJsonObject, recentPostsCache)
if not postJsonObject.get('type'): if not postJsonObject.get('type'):
return return
if postJsonObject['type']!='Create': if postJsonObject['type'] != 'Create':
return return
if not postJsonObject.get('object'): if not postJsonObject.get('object'):
if debug: if debug:
@ -57,39 +57,42 @@ def undoLikesCollectionEntry(recentPostsCache: {}, \
return return
if not postJsonObject['object']['likes'].get('items'): if not postJsonObject['object']['likes'].get('items'):
return return
totalItems=0 totalItems = 0
if postJsonObject['object']['likes'].get('totalItems'): if postJsonObject['object']['likes'].get('totalItems'):
totalItems=postJsonObject['object']['likes']['totalItems'] totalItems = postJsonObject['object']['likes']['totalItems']
itemFound=False itemFound = False
for likeItem in postJsonObject['object']['likes']['items']: for likeItem in postJsonObject['object']['likes']['items']:
if likeItem.get('actor'): if likeItem.get('actor'):
if likeItem['actor']==actor: if likeItem['actor'] == actor:
if debug: if debug:
print('DEBUG: like was removed for '+actor) print('DEBUG: like was removed for '+actor)
postJsonObject['object']['likes']['items'].remove(likeItem) postJsonObject['object']['likes']['items'].remove(likeItem)
itemFound=True itemFound = True
break break
if itemFound: if itemFound:
if totalItems==1: if totalItems == 1:
if debug: if debug:
print('DEBUG: likes was removed from post') print('DEBUG: likes was removed from post')
del postJsonObject['object']['likes'] del postJsonObject['object']['likes']
else: else:
postJsonObject['object']['likes']['totalItems']= \ itlen = len(postJsonObject['object']['likes']['items'])
len(postJsonObject['object']['likes']['items']) postJsonObject['object']['likes']['totalItems'] = itlen
saveJson(postJsonObject,postFilename)
def likedByPerson(postJsonObject: {}, nickname: str,domain: str) -> bool: saveJson(postJsonObject, postFilename)
def likedByPerson(postJsonObject: {}, nickname: str, domain: str) -> bool:
"""Returns True if the given post is liked by the given person """Returns True if the given post is liked by the given person
""" """
if noOfLikes(postJsonObject)==0: if noOfLikes(postJsonObject) == 0:
return False return False
actorMatch=domain+'/users/'+nickname actorMatch = domain+'/users/'+nickname
for item in postJsonObject['object']['likes']['items']: for item in postJsonObject['object']['likes']['items']:
if item['actor'].endswith(actorMatch): if item['actor'].endswith(actorMatch):
return True return True
return False return False
def noOfLikes(postJsonObject: {}) -> int: def noOfLikes(postJsonObject: {}) -> int:
"""Returns the number of likes ona given post """Returns the number of likes ona given post
""" """
@ -102,26 +105,28 @@ def noOfLikes(postJsonObject: {}) -> int:
if not isinstance(postJsonObject['object']['likes'], dict): if not isinstance(postJsonObject['object']['likes'], dict):
return 0 return 0
if not postJsonObject['object']['likes'].get('items'): if not postJsonObject['object']['likes'].get('items'):
postJsonObject['object']['likes']['items']=[] postJsonObject['object']['likes']['items'] = []
postJsonObject['object']['likes']['totalItems']=0 postJsonObject['object']['likes']['totalItems'] = 0
return len(postJsonObject['object']['likes']['items']) return len(postJsonObject['object']['likes']['items'])
def updateLikesCollection(recentPostsCache: {}, \
baseDir: str,postFilename: str, \ def updateLikesCollection(recentPostsCache: {},
objectUrl: str, \ baseDir: str, postFilename: str,
actor: str,domain: str,debug: bool) -> None: objectUrl: str,
actor: str, domain: str, debug: bool) -> None:
"""Updates the likes collection within a post """Updates the likes collection within a post
""" """
postJsonObject=loadJson(postFilename) postJsonObject = loadJson(postFilename)
if postJsonObject: if postJsonObject:
# remove any cached version of this post so that the like icon is changed # remove any cached version of this post so that the
nickname=getNicknameFromActor(actor) # like icon is changed
cachedPostFilename= \ nickname = getNicknameFromActor(actor)
getCachedPostFilename(baseDir,nickname,domain,postJsonObject) cachedPostFilename = getCachedPostFilename(baseDir, nickname,
domain, postJsonObject)
if cachedPostFilename: if cachedPostFilename:
if os.path.isfile(cachedPostFilename): if os.path.isfile(cachedPostFilename):
os.remove(cachedPostFilename) os.remove(cachedPostFilename)
removePostFromCache(postJsonObject,recentPostsCache) removePostFromCache(postJsonObject, recentPostsCache)
if not postJsonObject.get('object'): if not postJsonObject.get('object'):
if debug: if debug:
@ -131,11 +136,11 @@ def updateLikesCollection(recentPostsCache: {}, \
if not isinstance(postJsonObject['object'], dict): if not isinstance(postJsonObject['object'], dict):
return return
if not objectUrl.endswith('/likes'): if not objectUrl.endswith('/likes'):
objectUrl=objectUrl+'/likes' objectUrl = objectUrl+'/likes'
if not postJsonObject['object'].get('likes'): if not postJsonObject['object'].get('likes'):
if debug: if debug:
print('DEBUG: Adding initial likes to '+objectUrl) print('DEBUG: Adding initial likes to '+objectUrl)
likesJson={ likesJson = {
"@context": "https://www.w3.org/ns/activitystreams", "@context": "https://www.w3.org/ns/activitystreams",
'id': objectUrl, 'id': objectUrl,
'type': 'Collection', 'type': 'Collection',
@ -145,80 +150,77 @@ def updateLikesCollection(recentPostsCache: {}, \
'actor': actor 'actor': actor
}] }]
} }
postJsonObject['object']['likes']=likesJson postJsonObject['object']['likes'] = likesJson
else: else:
if not postJsonObject['object']['likes'].get('items'): if not postJsonObject['object']['likes'].get('items'):
postJsonObject['object']['likes']['items']=[] postJsonObject['object']['likes']['items'] = []
for likeItem in postJsonObject['object']['likes']['items']: for likeItem in postJsonObject['object']['likes']['items']:
if likeItem.get('actor'): if likeItem.get('actor'):
if likeItem['actor']==actor: if likeItem['actor'] == actor:
return return
newLike={ newLike = {
'type': 'Like', 'type': 'Like',
'actor': actor 'actor': actor
} }
postJsonObject['object']['likes']['items'].append(newLike) postJsonObject['object']['likes']['items'].append(newLike)
postJsonObject['object']['likes']['totalItems']= \ itlen = len(postJsonObject['object']['likes']['items'])
len(postJsonObject['object']['likes']['items']) postJsonObject['object']['likes']['totalItems'] = itlen
if debug: if debug:
print('DEBUG: saving post with likes added') print('DEBUG: saving post with likes added')
pprint(postJsonObject) pprint(postJsonObject)
saveJson(postJsonObject,postFilename) saveJson(postJsonObject, postFilename)
def like(recentPostsCache: {}, \
session,baseDir: str,federationList: [], \ def like(recentPostsCache: {},
nickname: str,domain: str,port: int, \ session, baseDir: str, federationList: [],
ccList: [],httpPrefix: str, \ nickname: str, domain: str, port: int,
objectUrl: str,actorLiked: str, \ ccList: [], httpPrefix: str,
clientToServer: bool, \ objectUrl: str, actorLiked: str,
sendThreads: [],postLog: [], \ clientToServer: bool,
personCache: {},cachedWebfingers: {}, \ sendThreads: [], postLog: [],
debug: bool,projectVersion: str) -> {}: personCache: {}, cachedWebfingers: {},
debug: bool, projectVersion: str) -> {}:
"""Creates a like """Creates a like
actor is the person doing the liking actor is the person doing the liking
'to' might be a specific person (actor) whose post was liked 'to' might be a specific person (actor) whose post was liked
object is typically the url of the message which was liked object is typically the url of the message which was liked
""" """
if not urlPermitted(objectUrl,federationList,"inbox:write"): if not urlPermitted(objectUrl, federationList, "inbox:write"):
return None return None
fullDomain=domain fullDomain = domain
if port: if port:
if port!=80 and port!=443: if port != 80 and port != 443:
if ':' not in domain: if ':' not in domain:
fullDomain=domain+':'+str(port) fullDomain = domain+':'+str(port)
likeTo=[] newLikeJson = {
if '/statuses/' in objectUrl:
likeTo=[objectUrl.split('/statuses/')[0]]
newLikeJson={
"@context": "https://www.w3.org/ns/activitystreams", "@context": "https://www.w3.org/ns/activitystreams",
'type': 'Like', 'type': 'Like',
'actor': httpPrefix+'://'+fullDomain+'/users/'+nickname, 'actor': httpPrefix+'://'+fullDomain+'/users/'+nickname,
'object': objectUrl 'object': objectUrl
} }
if ccList: if ccList:
if len(ccList)>0: if len(ccList) > 0:
newLikeJson['cc']=ccList newLikeJson['cc'] = ccList
# Extract the domain and nickname from a statuses link # Extract the domain and nickname from a statuses link
likedPostNickname=None likedPostNickname = None
likedPostDomain=None likedPostDomain = None
likedPostPort=None likedPostPort = None
if actorLiked: if actorLiked:
likedPostNickname=getNicknameFromActor(actorLiked) likedPostNickname = getNicknameFromActor(actorLiked)
likedPostDomain,likedPostPort=getDomainFromActor(actorLiked) likedPostDomain, likedPostPort = getDomainFromActor(actorLiked)
else: else:
if '/users/' in objectUrl or \ if '/users/' in objectUrl or \
'/channel/' in objectUrl or \ '/channel/' in objectUrl or \
'/profile/' in objectUrl: '/profile/' in objectUrl:
likedPostNickname=getNicknameFromActor(objectUrl) likedPostNickname = getNicknameFromActor(objectUrl)
likedPostDomain,likedPostPort=getDomainFromActor(objectUrl) likedPostDomain, likedPostPort = getDomainFromActor(objectUrl)
if likedPostNickname: if likedPostNickname:
postFilename=locatePost(baseDir,nickname,domain,objectUrl) postFilename = locatePost(baseDir, nickname, domain, objectUrl)
if not postFilename: if not postFilename:
print('DEBUG: like baseDir: '+baseDir) print('DEBUG: like baseDir: '+baseDir)
print('DEBUG: like nickname: '+nickname) print('DEBUG: like nickname: '+nickname)
@ -226,83 +228,72 @@ def like(recentPostsCache: {}, \
print('DEBUG: like objectUrl: '+objectUrl) print('DEBUG: like objectUrl: '+objectUrl)
return None return None
updateLikesCollection(recentPostsCache, \ updateLikesCollection(recentPostsCache,
baseDir,postFilename,objectUrl, \ baseDir, postFilename, objectUrl,
newLikeJson['actor'],domain,debug) newLikeJson['actor'], domain, debug)
sendSignedJson(newLikeJson,session,baseDir, \ sendSignedJson(newLikeJson, session, baseDir,
nickname,domain,port, \ nickname, domain, port,
likedPostNickname,likedPostDomain,likedPostPort, \ likedPostNickname, likedPostDomain, likedPostPort,
'https://www.w3.org/ns/activitystreams#Public', \ 'https://www.w3.org/ns/activitystreams#Public',
httpPrefix,True,clientToServer,federationList, \ httpPrefix, True, clientToServer, federationList,
sendThreads,postLog,cachedWebfingers,personCache, \ sendThreads, postLog, cachedWebfingers, personCache,
debug,projectVersion) debug, projectVersion)
return newLikeJson return newLikeJson
def likePost(recentPostsCache: {}, \
session,baseDir: str,federationList: [], \ def likePost(recentPostsCache: {},
nickname: str,domain: str,port: int,httpPrefix: str, \ session, baseDir: str, federationList: [],
likeNickname: str,likeDomain: str,likePort: int, \ nickname: str, domain: str, port: int, httpPrefix: str,
ccList: [], \ likeNickname: str, likeDomain: str, likePort: int,
likeStatusNumber: int,clientToServer: bool, \ ccList: [],
sendThreads: [],postLog: [], \ likeStatusNumber: int, clientToServer: bool,
personCache: {},cachedWebfingers: {}, \ sendThreads: [], postLog: [],
debug: bool,projectVersion: str) -> {}: personCache: {}, cachedWebfingers: {},
debug: bool, projectVersion: str) -> {}:
"""Likes a given status post. This is only used by unit tests """Likes a given status post. This is only used by unit tests
""" """
likeDomain=likeDomain likeDomain = likeDomain
if likePort: if likePort:
if likePort!=80 and likePort!=443: if likePort != 80 and likePort != 443:
if ':' not in likeDomain: if ':' not in likeDomain:
likeDomain=likeDomain+':'+str(likePort) likeDomain = likeDomain+':'+str(likePort)
actorLiked= \ actorLiked = httpPrefix + '://'+likeDomain+'/users/'+likeNickname
httpPrefix + '://'+likeDomain+'/users/'+likeNickname objectUrl = actorLiked+'/statuses/'+str(likeStatusNumber)
objectUrl=actorLiked+'/statuses/'+str(likeStatusNumber)
ccUrl=httpPrefix+'://'+likeDomain+'/users/'+likeNickname return like(recentPostsCache,
if likePort: session, baseDir, federationList, nickname, domain, port,
if likePort!=80 and likePort!=443: ccList, httpPrefix, objectUrl, actorLiked, clientToServer,
if ':' not in likeDomain: sendThreads, postLog, personCache, cachedWebfingers,
ccUrl= \ debug, projectVersion)
httpPrefix+'://'+likeDomain+':'+ \
str(likePort)+'/users/'+likeNickname
return like(recentPostsCache, \
session,baseDir,federationList,nickname,domain,port, \
ccList,httpPrefix,objectUrl,actorLiked,clientToServer, \
sendThreads,postLog,personCache,cachedWebfingers, \
debug,projectVersion)
def undolike(recentPostsCache: {}, \ def undolike(recentPostsCache: {},
session,baseDir: str,federationList: [], \ session, baseDir: str, federationList: [],
nickname: str,domain: str,port: int, \ nickname: str, domain: str, port: int,
ccList: [],httpPrefix: str, \ ccList: [], httpPrefix: str,
objectUrl: str,actorLiked: str, \ objectUrl: str, actorLiked: str,
clientToServer: bool, \ clientToServer: bool,
sendThreads: [],postLog: [], \ sendThreads: [], postLog: [],
personCache: {},cachedWebfingers: {}, \ personCache: {}, cachedWebfingers: {},
debug: bool,projectVersion: str) -> {}: debug: bool, projectVersion: str) -> {}:
"""Removes a like """Removes a like
actor is the person doing the liking actor is the person doing the liking
'to' might be a specific person (actor) whose post was liked 'to' might be a specific person (actor) whose post was liked
object is typically the url of the message which was liked object is typically the url of the message which was liked
""" """
if not urlPermitted(objectUrl,federationList,"inbox:write"): if not urlPermitted(objectUrl, federationList, "inbox:write"):
return None return None
fullDomain=domain fullDomain = domain
if port: if port:
if port!=80 and port!=443: if port != 80 and port != 443:
if ':' not in domain: if ':' not in domain:
fullDomain=domain+':'+str(port) fullDomain = domain+':'+str(port)
likeTo=[] newUndoLikeJson = {
if '/statuses/' in objectUrl:
likeTo=[objectUrl.split('/statuses/')[0]]
newUndoLikeJson={
"@context": "https://www.w3.org/ns/activitystreams", "@context": "https://www.w3.org/ns/activitystreams",
'type': 'Undo', 'type': 'Undo',
'actor': httpPrefix+'://'+fullDomain+'/users/'+nickname, 'actor': httpPrefix+'://'+fullDomain+'/users/'+nickname,
@ -313,126 +304,91 @@ def undolike(recentPostsCache: {}, \
} }
} }
if ccList: if ccList:
if len(ccList)>0: if len(ccList) > 0:
newUndoLikeJson['cc']=ccList newUndoLikeJson['cc'] = ccList
newUndoLikeJson['object']['cc']=ccList newUndoLikeJson['object']['cc'] = ccList
# Extract the domain and nickname from a statuses link # Extract the domain and nickname from a statuses link
likedPostNickname=None likedPostNickname = None
likedPostDomain=None likedPostDomain = None
likedPostPort=None likedPostPort = None
if actorLiked: if actorLiked:
likedPostNickname=getNicknameFromActor(actorLiked) likedPostNickname = getNicknameFromActor(actorLiked)
likedPostDomain,likedPostPort=getDomainFromActor(actorLiked) likedPostDomain, likedPostPort = getDomainFromActor(actorLiked)
else: else:
if '/users/' in objectUrl or \ if '/users/' in objectUrl or \
'/channel/' in objectUrl or \ '/channel/' in objectUrl or \
'/profile/' in objectUrl: '/profile/' in objectUrl:
likedPostNickname=getNicknameFromActor(objectUrl) likedPostNickname = getNicknameFromActor(objectUrl)
likedPostDomain,likedPostPort=getDomainFromActor(objectUrl) likedPostDomain, likedPostPort = getDomainFromActor(objectUrl)
if likedPostNickname: if likedPostNickname:
postFilename=locatePost(baseDir,nickname,domain,objectUrl) postFilename = locatePost(baseDir, nickname, domain, objectUrl)
if not postFilename: if not postFilename:
return None return None
undoLikesCollectionEntry(baseDir,postFilename,objectUrl, \ undoLikesCollectionEntry(baseDir, postFilename, objectUrl,
newLikeJson['actor'],domain,debug) newUndoLikeJson['actor'], domain, debug)
sendSignedJson(newUndoLikeJson,session,baseDir, \ sendSignedJson(newUndoLikeJson, session, baseDir,
nickname,domain,port, \ nickname, domain, port,
likedPostNickname,likedPostDomain,likedPostPort, \ likedPostNickname, likedPostDomain, likedPostPort,
'https://www.w3.org/ns/activitystreams#Public', \ 'https://www.w3.org/ns/activitystreams#Public',
httpPrefix,True,clientToServer,federationList, \ httpPrefix, True, clientToServer, federationList,
sendThreads,postLog,cachedWebfingers,personCache, \ sendThreads, postLog, cachedWebfingers, personCache,
debug,projectVersion) debug, projectVersion)
else: else:
return None return None
return newUndoLikeJson return newUndoLikeJson
def undoLikePost(recentPostsCache: {}, \
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:
if likePort!=80 and likePort!=443:
if ':' not in likeDomain:
likeDomain=likeDomain+':'+str(likePort)
objectUrl= \ def sendLikeViaServer(baseDir: str, session,
httpPrefix+'://'+likeDomain+'/users/'+likeNickname+ \ fromNickname: str, password: str,
'/statuses/'+str(likeStatusNumber) fromDomain: str, fromPort: int,
httpPrefix: str, likeUrl: str,
ccUrl=httpPrefix+'://'+likeDomain+'/users/'+likeNickname cachedWebfingers: {}, personCache: {},
if likePort: debug: bool, projectVersion: str) -> {}:
if likePort!=80 and likePort!=443:
if ':' not in likeDomain:
ccUrl= \
httpPrefix+'://'+likeDomain+':'+ \
str(likePort)+'/users/'+likeNickname
return undoLike(recentPostsCache, \
session,baseDir,federationList,nickname,domain,port, \
ccList,httpPrefix,objectUrl,clientToServer, \
sendThreads,postLog,personCache,cachedWebfingers,debug)
def sendLikeViaServer(baseDir: str,session, \
fromNickname: str,password: str,
fromDomain: str,fromPort: int, \
httpPrefix: str,likeUrl: str, \
cachedWebfingers: {},personCache: {}, \
debug: bool,projectVersion: str) -> {}:
"""Creates a like via c2s """Creates a like via c2s
""" """
if not session: if not session:
print('WARN: No session for sendLikeViaServer') print('WARN: No session for sendLikeViaServer')
return 6 return 6
fromDomainFull=fromDomain fromDomainFull = fromDomain
if fromPort: if fromPort:
if fromPort!=80 and fromPort!=443: if fromPort != 80 and fromPort != 443:
if ':' not in fromDomain: if ':' not in fromDomain:
fromDomainFull=fromDomain+':'+str(fromPort) fromDomainFull = fromDomain+':'+str(fromPort)
toUrl=['https://www.w3.org/ns/activitystreams#Public'] newLikeJson = {
ccUrl=httpPrefix+'://'+fromDomainFull+'/users/'+fromNickname+'/followers'
if '/statuses/' in likeUrl:
toUrl=[likeUrl.split('/statuses/')[0]]
newLikeJson={
"@context": "https://www.w3.org/ns/activitystreams", "@context": "https://www.w3.org/ns/activitystreams",
'type': 'Like', 'type': 'Like',
'actor': httpPrefix+'://'+fromDomainFull+'/users/'+fromNickname, 'actor': httpPrefix+'://'+fromDomainFull+'/users/'+fromNickname,
'object': likeUrl 'object': likeUrl
} }
handle=httpPrefix+'://'+fromDomainFull+'/@'+fromNickname handle = httpPrefix+'://'+fromDomainFull+'/@'+fromNickname
# lookup the inbox for the To handle # lookup the inbox for the To handle
wfRequest=webfingerHandle(session,handle,httpPrefix,cachedWebfingers, \ wfRequest = webfingerHandle(session, handle, httpPrefix,
fromDomain,projectVersion) cachedWebfingers,
fromDomain, projectVersion)
if not wfRequest: if not wfRequest:
if debug: if debug:
print('DEBUG: announce webfinger failed for '+handle) print('DEBUG: announce webfinger failed for '+handle)
return 1 return 1
postToBox='outbox' postToBox = 'outbox'
# get the actor inbox for the To handle # get the actor inbox for the To handle
inboxUrl,pubKeyId,pubKey,fromPersonId,sharedInbox,capabilityAcquisition,avatarUrl,displayName= \ (inboxUrl, pubKeyId, pubKey, fromPersonId,
getPersonBox(baseDir,session,wfRequest,personCache, \ sharedInbox, capabilityAcquisition,
projectVersion,httpPrefix,fromNickname, \ avatarUrl, displayName) = getPersonBox(baseDir, session, wfRequest,
fromDomain,postToBox) personCache,
projectVersion, httpPrefix,
fromNickname, fromDomain,
postToBox)
if not inboxUrl: if not inboxUrl:
if debug: if debug:
@ -443,50 +399,44 @@ def sendLikeViaServer(baseDir: str,session, \
print('DEBUG: No actor was found for '+handle) print('DEBUG: No actor was found for '+handle)
return 4 return 4
authHeader=createBasicAuthHeader(fromNickname,password) authHeader = createBasicAuthHeader(fromNickname, password)
headers={ headers = {
'host': fromDomain, \ 'host': fromDomain,
'Content-type': 'application/json', \ 'Content-type': 'application/json',
'Authorization': authHeader 'Authorization': authHeader
} }
postResult= \ postResult = postJson(session, newLikeJson, [], inboxUrl,
postJson(session,newLikeJson,[],inboxUrl,headers,"inbox:write") headers, "inbox:write")
#if not postResult: if not postResult:
# if debug: print('WARN: POST announce failed for c2s to ' + inboxUrl)
# print('DEBUG: POST announce failed for c2s to '+inboxUrl) return 5
# return 5
if debug: if debug:
print('DEBUG: c2s POST like success') print('DEBUG: c2s POST like success')
return newLikeJson return newLikeJson
def sendUndoLikeViaServer(baseDir: str,session, \
fromNickname: str,password: str, \ def sendUndoLikeViaServer(baseDir: str, session,
fromDomain: str,fromPort: int, \ fromNickname: str, password: str,
httpPrefix: str,likeUrl: str, \ fromDomain: str, fromPort: int,
cachedWebfingers: {},personCache: {}, \ httpPrefix: str, likeUrl: str,
debug: bool,projectVersion: str) -> {}: cachedWebfingers: {}, personCache: {},
debug: bool, projectVersion: str) -> {}:
"""Undo a like via c2s """Undo a like via c2s
""" """
if not session: if not session:
print('WARN: No session for sendUndoLikeViaServer') print('WARN: No session for sendUndoLikeViaServer')
return 6 return 6
fromDomainFull=fromDomain fromDomainFull = fromDomain
if fromPort: if fromPort:
if fromPort!=80 and fromPort!=443: if fromPort != 80 and fromPort != 443:
if ':' not in fromDomain: if ':' not in fromDomain:
fromDomainFull=fromDomain+':'+str(fromPort) fromDomainFull = fromDomain+':'+str(fromPort)
toUrl=['https://www.w3.org/ns/activitystreams#Public'] newUndoLikeJson = {
ccUrl=httpPrefix+'://'+fromDomainFull+'/users/'+fromNickname+'/followers'
if '/statuses/' in likeUrl:
toUrl=[likeUrl.split('/statuses/')[0]]
newUndoLikeJson={
"@context": "https://www.w3.org/ns/activitystreams", "@context": "https://www.w3.org/ns/activitystreams",
'type': 'Undo', 'type': 'Undo',
'actor': httpPrefix+'://'+fromDomainFull+'/users/'+fromNickname, 'actor': httpPrefix+'://'+fromDomainFull+'/users/'+fromNickname,
@ -497,24 +447,26 @@ def sendUndoLikeViaServer(baseDir: str,session, \
} }
} }
handle=httpPrefix+'://'+fromDomainFull+'/@'+fromNickname handle = httpPrefix+'://'+fromDomainFull+'/@'+fromNickname
# lookup the inbox for the To handle # lookup the inbox for the To handle
wfRequest= \ wfRequest = webfingerHandle(session, handle, httpPrefix,
webfingerHandle(session,handle,httpPrefix,cachedWebfingers, \ cachedWebfingers,
fromDomain,projectVersion) fromDomain, projectVersion)
if not wfRequest: if not wfRequest:
if debug: if debug:
print('DEBUG: announce webfinger failed for '+handle) print('DEBUG: announce webfinger failed for '+handle)
return 1 return 1
postToBox='outbox' postToBox = 'outbox'
# get the actor inbox for the To handle # get the actor inbox for the To handle
inboxUrl,pubKeyId,pubKey,fromPersonId,sharedInbox,capabilityAcquisition,avatarUrl,displayName= \ (inboxUrl, pubKeyId, pubKey, fromPersonId,
getPersonBox(baseDir,session,wfRequest,personCache, \ sharedInbox, capabilityAcquisition,
projectVersion,httpPrefix,fromNickname, \ avatarUrl, displayName) = getPersonBox(baseDir, session, wfRequest,
fromDomain,postToBox) personCache, projectVersion,
httpPrefix, fromNickname,
fromDomain, postToBox)
if not inboxUrl: if not inboxUrl:
if debug: if debug:
@ -525,36 +477,36 @@ def sendUndoLikeViaServer(baseDir: str,session, \
print('DEBUG: No actor was found for '+handle) print('DEBUG: No actor was found for '+handle)
return 4 return 4
authHeader=createBasicAuthHeader(fromNickname,password) authHeader = createBasicAuthHeader(fromNickname, password)
headers={ headers = {
'host': fromDomain, \ 'host': fromDomain,
'Content-type': 'application/json', \ 'Content-type': 'application/json',
'Authorization': authHeader 'Authorization': authHeader
} }
postResult= \ postResult = postJson(session, newUndoLikeJson, [], inboxUrl,
postJson(session,newUndoLikeJson,[],inboxUrl,headers,"inbox:write") headers, "inbox:write")
#if not postResult: if not postResult:
# if debug: print('WARN: POST announce failed for c2s to ' + inboxUrl)
# print('DEBUG: POST announce failed for c2s to '+inboxUrl) return 5
# return 5
if debug: if debug:
print('DEBUG: c2s POST undo like success') print('DEBUG: c2s POST undo like success')
return newUndoLikeJson return newUndoLikeJson
def outboxLike(recentPostsCache: {}, \
baseDir: str,httpPrefix: str, \ def outboxLike(recentPostsCache: {},
nickname: str,domain: str,port: int, \ baseDir: str, httpPrefix: str,
messageJson: {},debug: bool) -> None: nickname: str, domain: str, port: int,
messageJson: {}, debug: bool) -> None:
""" When a like request is received by the outbox from c2s """ When a like request is received by the outbox from c2s
""" """
if not messageJson.get('type'): if not messageJson.get('type'):
if debug: if debug:
print('DEBUG: like - no type') print('DEBUG: like - no type')
return return
if not messageJson['type']=='Like': if not messageJson['type'] == 'Like':
if debug: if debug:
print('DEBUG: not a like') print('DEBUG: not a like')
return return
@ -569,30 +521,31 @@ def outboxLike(recentPostsCache: {}, \
if debug: if debug:
print('DEBUG: c2s like request arrived in outbox') print('DEBUG: c2s like request arrived in outbox')
messageId=messageJson['object'].replace('/activity','') messageId = messageJson['object'].replace('/activity', '')
if ':' in domain: if ':' in domain:
domain=domain.split(':')[0] domain = domain.split(':')[0]
postFilename=locatePost(baseDir,nickname,domain,messageId) postFilename = locatePost(baseDir, nickname, domain, messageId)
if not postFilename: if not postFilename:
if debug: if debug:
print('DEBUG: c2s like post not found in inbox or outbox') print('DEBUG: c2s like post not found in inbox or outbox')
print(messageId) print(messageId)
return True return True
updateLikesCollection(recentPostsCache, \ updateLikesCollection(recentPostsCache,
baseDir,postFilename,messageId, \ baseDir, postFilename, messageId,
messageJson['actor'],domain,debug) messageJson['actor'], domain, debug)
if debug: if debug:
print('DEBUG: post liked via c2s - '+postFilename) print('DEBUG: post liked via c2s - '+postFilename)
def outboxUndoLike(recentPostsCache: {}, \
baseDir: str,httpPrefix: str, \ def outboxUndoLike(recentPostsCache: {},
nickname: str,domain: str,port: int, \ baseDir: str, httpPrefix: str,
messageJson: {},debug: bool) -> None: nickname: str, domain: str, port: int,
messageJson: {}, debug: bool) -> None:
""" When an undo like request is received by the outbox from c2s """ When an undo like request is received by the outbox from c2s
""" """
if not messageJson.get('type'): if not messageJson.get('type'):
return return
if not messageJson['type']=='Undo': if not messageJson['type'] == 'Undo':
return return
if not messageJson.get('object'): if not messageJson.get('object'):
return return
@ -604,7 +557,7 @@ def outboxUndoLike(recentPostsCache: {}, \
if debug: if debug:
print('DEBUG: undo like - no type') print('DEBUG: undo like - no type')
return return
if not messageJson['object']['type']=='Like': if not messageJson['object']['type'] == 'Like':
if debug: if debug:
print('DEBUG: not a undo like') print('DEBUG: not a undo like')
return return
@ -619,16 +572,17 @@ def outboxUndoLike(recentPostsCache: {}, \
if debug: if debug:
print('DEBUG: c2s undo like request arrived in outbox') print('DEBUG: c2s undo like request arrived in outbox')
messageId=messageJson['object']['object'].replace('/activity','') messageId = messageJson['object']['object'].replace('/activity', '')
if ':' in domain: if ':' in domain:
domain=domain.split(':')[0] domain = domain.split(':')[0]
postFilename=locatePost(baseDir,nickname,domain,messageId) postFilename = locatePost(baseDir, nickname, domain, messageId)
if not postFilename: if not postFilename:
if debug: if debug:
print('DEBUG: c2s undo like post not found in inbox or outbox') print('DEBUG: c2s undo like post not found in inbox or outbox')
print(messageId) print(messageId)
return True return True
undoLikesCollectionEntry(recentPostsCache,baseDir,postFilename,messageId, \ undoLikesCollectionEntry(recentPostsCache, baseDir, postFilename,
messageJson['actor'],domain,debug) messageId, messageJson['actor'],
domain, debug)
if debug: if debug:
print('DEBUG: post undo liked via c2s - '+postFilename) print('DEBUG: post undo liked via c2s - '+postFilename)