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

292
like.py
View File

@ -7,8 +7,6 @@ __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,17 +22,19 @@ 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: {},
baseDir: str, postFilename: str, objectUrl: str,
actor: str, domain: str, debug: bool) -> None: 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
# like icon is changed
nickname = getNicknameFromActor(actor) nickname = getNicknameFromActor(actor)
cachedPostFilename= \ cachedPostFilename = getCachedPostFilename(baseDir, nickname,
getCachedPostFilename(baseDir,nickname,domain,postJsonObject) domain, postJsonObject)
if cachedPostFilename: if cachedPostFilename:
if os.path.isfile(cachedPostFilename): if os.path.isfile(cachedPostFilename):
os.remove(cachedPostFilename) os.remove(cachedPostFilename)
@ -75,10 +75,12 @@ def undoLikesCollectionEntry(recentPostsCache: {}, \
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) saveJson(postJsonObject, postFilename)
def likedByPerson(postJsonObject: {}, nickname: str, domain: str) -> bool: 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
""" """
@ -90,6 +92,7 @@ def likedByPerson(postJsonObject: {}, nickname: str,domain: str) -> bool:
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
""" """
@ -106,18 +109,20 @@ def noOfLikes(postJsonObject: {}) -> int:
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,
objectUrl: str,
actor: str, domain: str, debug: bool) -> None: 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
# like icon is changed
nickname = getNicknameFromActor(actor) nickname = getNicknameFromActor(actor)
cachedPostFilename= \ cachedPostFilename = getCachedPostFilename(baseDir, nickname,
getCachedPostFilename(baseDir,nickname,domain,postJsonObject) domain, postJsonObject)
if cachedPostFilename: if cachedPostFilename:
if os.path.isfile(cachedPostFilename): if os.path.isfile(cachedPostFilename):
os.remove(cachedPostFilename) os.remove(cachedPostFilename)
@ -158,22 +163,23 @@ def updateLikesCollection(recentPostsCache: {}, \
'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: [],
personCache: {}, cachedWebfingers: {},
debug: bool, projectVersion: str) -> {}: debug: bool, projectVersion: str) -> {}:
"""Creates a like """Creates a like
actor is the person doing the liking actor is the person doing the liking
@ -189,10 +195,6 @@ def like(recentPostsCache: {}, \
if ':' not in domain: if ':' not in domain:
fullDomain = domain+':'+str(port) fullDomain = domain+':'+str(port)
likeTo=[]
if '/statuses/' in objectUrl:
likeTo=[objectUrl.split('/statuses/')[0]]
newLikeJson = { newLikeJson = {
"@context": "https://www.w3.org/ns/activitystreams", "@context": "https://www.w3.org/ns/activitystreams",
'type': 'Like', 'type': 'Like',
@ -226,28 +228,29 @@ 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: [],
personCache: {}, cachedWebfingers: {},
debug: bool, projectVersion: str) -> {}: 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
""" """
@ -257,32 +260,24 @@ def likePost(recentPostsCache: {}, \
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= \
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) debug, projectVersion)
def undolike(recentPostsCache: {}, \
session,baseDir: str,federationList: [], \ def undolike(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: [],
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
@ -298,10 +293,6 @@ def undolike(recentPostsCache: {}, \
if ':' not in domain: if ':' not in domain:
fullDomain = domain+':'+str(port) fullDomain = domain+':'+str(port)
likeTo=[]
if '/statuses/' in objectUrl:
likeTo=[objectUrl.split('/statuses/')[0]]
newUndoLikeJson = { newUndoLikeJson = {
"@context": "https://www.w3.org/ns/activitystreams", "@context": "https://www.w3.org/ns/activitystreams",
'type': 'Undo', 'type': 'Undo',
@ -336,60 +327,27 @@ def undolike(recentPostsCache: {}, \
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+ \
'/statuses/'+str(likeStatusNumber)
ccUrl=httpPrefix+'://'+likeDomain+'/users/'+likeNickname
if likePort:
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, fromNickname: str, password: str,
fromDomain: str,fromPort: int, \ fromDomain: str, fromPort: int,
httpPrefix: str,likeUrl: str, \ httpPrefix: str, likeUrl: str,
cachedWebfingers: {},personCache: {}, \ cachedWebfingers: {}, personCache: {},
debug: bool, projectVersion: str) -> {}: debug: bool, projectVersion: str) -> {}:
"""Creates a like via c2s """Creates a like via c2s
""" """
@ -403,12 +361,6 @@ def sendLikeViaServer(baseDir: str,session, \
if ':' not in fromDomain: if ':' not in fromDomain:
fromDomainFull = fromDomain+':'+str(fromPort) fromDomainFull = fromDomain+':'+str(fromPort)
toUrl=['https://www.w3.org/ns/activitystreams#Public']
ccUrl=httpPrefix+'://'+fromDomainFull+'/users/'+fromNickname+'/followers'
if '/statuses/' in likeUrl:
toUrl=[likeUrl.split('/statuses/')[0]]
newLikeJson = { newLikeJson = {
"@context": "https://www.w3.org/ns/activitystreams", "@context": "https://www.w3.org/ns/activitystreams",
'type': 'Like', 'type': 'Like',
@ -419,7 +371,8 @@ def sendLikeViaServer(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=webfingerHandle(session,handle,httpPrefix,cachedWebfingers, \ wfRequest = webfingerHandle(session, handle, httpPrefix,
cachedWebfingers,
fromDomain, projectVersion) fromDomain, projectVersion)
if not wfRequest: if not wfRequest:
if debug: if debug:
@ -429,10 +382,13 @@ def sendLikeViaServer(baseDir: str,session, \
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:
@ -446,27 +402,27 @@ def sendLikeViaServer(baseDir: str,session, \
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,
cachedWebfingers: {}, personCache: {},
debug: bool, projectVersion: str) -> {}: debug: bool, projectVersion: str) -> {}:
"""Undo a like via c2s """Undo a like via c2s
""" """
@ -480,12 +436,6 @@ def sendUndoLikeViaServer(baseDir: str,session, \
if ':' not in fromDomain: if ':' not in fromDomain:
fromDomainFull = fromDomain+':'+str(fromPort) fromDomainFull = fromDomain+':'+str(fromPort)
toUrl=['https://www.w3.org/ns/activitystreams#Public']
ccUrl=httpPrefix+'://'+fromDomainFull+'/users/'+fromNickname+'/followers'
if '/statuses/' in likeUrl:
toUrl=[likeUrl.split('/statuses/')[0]]
newUndoLikeJson = { newUndoLikeJson = {
"@context": "https://www.w3.org/ns/activitystreams", "@context": "https://www.w3.org/ns/activitystreams",
'type': 'Undo', 'type': 'Undo',
@ -500,8 +450,8 @@ 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:
@ -511,9 +461,11 @@ def sendUndoLikeViaServer(baseDir: str,session, \
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,
personCache, projectVersion,
httpPrefix, fromNickname,
fromDomain, postToBox) fromDomain, postToBox)
if not inboxUrl: if not inboxUrl:
@ -528,25 +480,25 @@ def sendUndoLikeViaServer(baseDir: str,session, \
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,
nickname: str, domain: str, port: int,
messageJson: {}, debug: bool) -> None: 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
""" """
@ -578,15 +530,16 @@ def outboxLike(recentPostsCache: {}, \
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,
nickname: str, domain: str, port: int,
messageJson: {}, debug: bool) -> None: 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
""" """
@ -628,7 +581,8 @@ def outboxUndoLike(recentPostsCache: {}, \
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)