Snake case

main
Bob Mottram 2021-12-25 23:51:19 +00:00
parent 77fc7ddc8e
commit 49308fbcb5
17 changed files with 742 additions and 738 deletions

View File

@ -41,7 +41,7 @@ def _create_accept_reject(base_dir: str, federation_list: [],
domain = getFullDomain(domain, port)
newAccept = {
new_accept = {
"@context": "https://www.w3.org/ns/activitystreams",
'type': acceptType,
'actor': localActorUrl(http_prefix, nickname, domain),
@ -51,8 +51,8 @@ def _create_accept_reject(base_dir: str, federation_list: [],
}
if ccUrl:
if len(ccUrl) > 0:
newAccept['cc'] = [ccUrl]
return newAccept
new_accept['cc'] = [ccUrl]
return new_accept
def createAccept(base_dir: str, federation_list: [],
@ -75,30 +75,30 @@ def createReject(base_dir: str, federation_list: [],
http_prefix, objectJson, 'Reject')
def _acceptFollow(base_dir: str, domain: str, messageJson: {},
def _acceptFollow(base_dir: str, domain: str, message_json: {},
federation_list: [], debug: bool) -> None:
"""Receiving a follow Accept activity
"""
if not hasObjectStringType(messageJson, debug):
if not hasObjectStringType(message_json, debug):
return
if not messageJson['object']['type'] == 'Follow':
if not messageJson['object']['type'] == 'Join':
if not message_json['object']['type'] == 'Follow':
if not message_json['object']['type'] == 'Join':
return
if debug:
print('DEBUG: receiving Follow activity')
if not messageJson['object'].get('actor'):
if not message_json['object'].get('actor'):
print('DEBUG: no actor in Follow activity')
return
# no, this isn't a mistake
if not hasObjectStringObject(messageJson, debug):
if not hasObjectStringObject(message_json, debug):
return
if not messageJson.get('to'):
if not message_json.get('to'):
if debug:
print('DEBUG: No "to" parameter in follow Accept')
return
if debug:
print('DEBUG: follow Accept received')
thisActor = messageJson['object']['actor']
thisActor = message_json['object']['actor']
nickname = getNicknameFromActor(thisActor)
if not nickname:
print('WARN: no nickname found in ' + thisActor)
@ -129,7 +129,7 @@ def _acceptFollow(base_dir: str, domain: str, messageJson: {},
print('Actual: ' + thisActor)
print('DEBUG: unrecognized actor ' + thisActor)
return
followedActor = messageJson['object']['object']
followedActor = message_json['object']['object']
followedDomain, port = getDomainFromActor(followedActor)
if not followedDomain:
print('DEBUG: no domain found within Follow activity object ' +
@ -183,35 +183,37 @@ def _acceptFollow(base_dir: str, domain: str, messageJson: {},
def receiveAcceptReject(session, base_dir: str,
http_prefix: str, domain: str, port: int,
send_threads: [], postLog: [], cached_webfingers: {},
person_cache: {}, messageJson: {}, federation_list: [],
send_threads: [], postLog: [],
cached_webfingers: {},
person_cache: {}, message_json: {},
federation_list: [],
debug: bool) -> bool:
"""Receives an Accept or Reject within the POST section of HTTPServer
"""
if messageJson['type'] != 'Accept' and messageJson['type'] != 'Reject':
if message_json['type'] != 'Accept' and message_json['type'] != 'Reject':
return False
if not hasActor(messageJson, debug):
if not hasActor(message_json, debug):
return False
if not hasUsersPath(messageJson['actor']):
if not hasUsersPath(message_json['actor']):
if debug:
print('DEBUG: "users" or "profile" missing from actor in ' +
messageJson['type'] + '. Assuming single user instance.')
domain, tempPort = getDomainFromActor(messageJson['actor'])
message_json['type'] + '. Assuming single user instance.')
domain, tempPort = getDomainFromActor(message_json['actor'])
if not domainPermitted(domain, federation_list):
if debug:
print('DEBUG: ' + messageJson['type'] +
print('DEBUG: ' + message_json['type'] +
' from domain not permitted - ' + domain)
return False
nickname = getNicknameFromActor(messageJson['actor'])
nickname = getNicknameFromActor(message_json['actor'])
if not nickname:
# single user instance
nickname = 'dev'
if debug:
print('DEBUG: ' + messageJson['type'] +
print('DEBUG: ' + message_json['type'] +
' does not contain a nickname. ' +
'Assuming single user instance.')
# receive follow accept
_acceptFollow(base_dir, domain, messageJson, federation_list, debug)
_acceptFollow(base_dir, domain, message_json, federation_list, debug)
if debug:
print('DEBUG: Uh, ' + messageJson['type'] + ', I guess')
print('DEBUG: Uh, ' + message_json['type'] + ', I guess')
return True

View File

@ -52,52 +52,52 @@ def isSelfAnnounce(post_json_object: {}) -> bool:
def outboxAnnounce(recentPostsCache: {},
base_dir: str, messageJson: {}, debug: bool) -> bool:
base_dir: str, message_json: {}, debug: bool) -> bool:
""" Adds or removes announce entries from the shares collection
within a given post
"""
if not hasActor(messageJson, debug):
if not hasActor(message_json, debug):
return False
if not isinstance(messageJson['actor'], str):
if not isinstance(message_json['actor'], str):
return False
if not messageJson.get('type'):
if not message_json.get('type'):
return False
if not messageJson.get('object'):
if not message_json.get('object'):
return False
if messageJson['type'] == 'Announce':
if not isinstance(messageJson['object'], str):
if message_json['type'] == 'Announce':
if not isinstance(message_json['object'], str):
return False
if isSelfAnnounce(messageJson):
if isSelfAnnounce(message_json):
return False
nickname = getNicknameFromActor(messageJson['actor'])
nickname = getNicknameFromActor(message_json['actor'])
if not nickname:
print('WARN: no nickname found in ' + messageJson['actor'])
print('WARN: no nickname found in ' + message_json['actor'])
return False
domain, port = getDomainFromActor(messageJson['actor'])
domain, port = getDomainFromActor(message_json['actor'])
postFilename = locatePost(base_dir, nickname, domain,
messageJson['object'])
message_json['object'])
if postFilename:
updateAnnounceCollection(recentPostsCache, base_dir, postFilename,
messageJson['actor'],
message_json['actor'],
nickname, domain, debug)
return True
elif messageJson['type'] == 'Undo':
if not hasObjectStringType(messageJson, debug):
elif message_json['type'] == 'Undo':
if not hasObjectStringType(message_json, debug):
return False
if messageJson['object']['type'] == 'Announce':
if not isinstance(messageJson['object']['object'], str):
if message_json['object']['type'] == 'Announce':
if not isinstance(message_json['object']['object'], str):
return False
nickname = getNicknameFromActor(messageJson['actor'])
nickname = getNicknameFromActor(message_json['actor'])
if not nickname:
print('WARN: no nickname found in ' + messageJson['actor'])
print('WARN: no nickname found in ' + message_json['actor'])
return False
domain, port = getDomainFromActor(messageJson['actor'])
domain, port = getDomainFromActor(message_json['actor'])
postFilename = locatePost(base_dir, nickname, domain,
messageJson['object']['object'])
message_json['object']['object'])
if postFilename:
undoAnnounceCollectionEntry(recentPostsCache,
base_dir, postFilename,
messageJson['actor'],
message_json['actor'],
domain, debug)
return True
return False
@ -389,25 +389,25 @@ def sendUndoAnnounceViaServer(base_dir: str, session,
def outboxUndoAnnounce(recentPostsCache: {},
base_dir: str, http_prefix: str,
nickname: str, domain: str, port: int,
messageJson: {}, debug: bool) -> None:
message_json: {}, debug: bool) -> None:
""" When an undo announce is received by the outbox from c2s
"""
if not messageJson.get('type'):
if not message_json.get('type'):
return
if not messageJson['type'] == 'Undo':
if not message_json['type'] == 'Undo':
return
if not hasObjectStringType(messageJson, debug):
if not hasObjectStringType(message_json, debug):
return
if not messageJson['object']['type'] == 'Announce':
if not message_json['object']['type'] == 'Announce':
if debug:
print('DEBUG: not a undo announce')
return
if not hasObjectStringObject(messageJson, debug):
if not hasObjectStringObject(message_json, debug):
return
if debug:
print('DEBUG: c2s undo announce request arrived in outbox')
messageId = removeIdEnding(messageJson['object']['object'])
messageId = removeIdEnding(message_json['object']['object'])
domain = removeDomainPort(domain)
postFilename = locatePost(base_dir, nickname, domain, messageId)
if not postFilename:
@ -416,6 +416,6 @@ def outboxUndoAnnounce(recentPostsCache: {},
print(messageId)
return True
undoAnnounceCollectionEntry(recentPostsCache, base_dir, postFilename,
messageJson['actor'], domain, debug)
message_json['actor'], domain, debug)
if debug:
print('DEBUG: post undo announce via c2s - ' + postFilename)

View File

@ -54,24 +54,24 @@ def getAvailability(base_dir: str, nickname: str, domain: str) -> str:
return None
def outboxAvailability(base_dir: str, nickname: str, messageJson: {},
def outboxAvailability(base_dir: str, nickname: str, message_json: {},
debug: bool) -> bool:
"""Handles receiving an availability update
"""
if not messageJson.get('type'):
if not message_json.get('type'):
return False
if not messageJson['type'] == 'Availability':
if not message_json['type'] == 'Availability':
return False
if not hasActor(messageJson, debug):
if not hasActor(message_json, debug):
return False
if not hasObjectString(messageJson, debug):
if not hasObjectString(message_json, debug):
return False
actorNickname = getNicknameFromActor(messageJson['actor'])
actorNickname = getNicknameFromActor(message_json['actor'])
if actorNickname != nickname:
return False
domain, port = getDomainFromActor(messageJson['actor'])
status = messageJson['object'].replace('"', '')
domain, port = getDomainFromActor(message_json['actor'])
status = message_json['object'].replace('"', '')
return setAvailability(base_dir, nickname, domain, status)

View File

@ -416,23 +416,23 @@ def isBlocked(base_dir: str, nickname: str, domain: str,
def outboxBlock(base_dir: str, http_prefix: str,
nickname: str, domain: str, port: int,
messageJson: {}, debug: bool) -> bool:
message_json: {}, debug: bool) -> bool:
""" When a block request is received by the outbox from c2s
"""
if not messageJson.get('type'):
if not message_json.get('type'):
if debug:
print('DEBUG: block - no type')
return False
if not messageJson['type'] == 'Block':
if not message_json['type'] == 'Block':
if debug:
print('DEBUG: not a block')
return False
if not hasObjectString(messageJson, debug):
if not hasObjectString(message_json, debug):
return False
if debug:
print('DEBUG: c2s block request arrived in outbox')
messageId = removeIdEnding(messageJson['object'])
messageId = removeIdEnding(message_json['object'])
if '/statuses/' not in messageId:
if debug:
print('DEBUG: c2s block object is not a status')
@ -448,11 +448,11 @@ def outboxBlock(base_dir: str, http_prefix: str,
print('DEBUG: c2s block post not found in inbox or outbox')
print(messageId)
return False
nicknameBlocked = getNicknameFromActor(messageJson['object'])
nicknameBlocked = getNicknameFromActor(message_json['object'])
if not nicknameBlocked:
print('WARN: unable to find nickname in ' + messageJson['object'])
print('WARN: unable to find nickname in ' + message_json['object'])
return False
domainBlocked, portBlocked = getDomainFromActor(messageJson['object'])
domainBlocked, portBlocked = getDomainFromActor(message_json['object'])
domainBlockedFull = getFullDomain(domainBlocked, portBlocked)
addBlock(base_dir, nickname, domain,
@ -465,30 +465,30 @@ def outboxBlock(base_dir: str, http_prefix: str,
def outboxUndoBlock(base_dir: str, http_prefix: str,
nickname: str, domain: str, port: int,
messageJson: {}, debug: bool) -> None:
message_json: {}, debug: bool) -> None:
""" When an undo block request is received by the outbox from c2s
"""
if not messageJson.get('type'):
if not message_json.get('type'):
if debug:
print('DEBUG: undo block - no type')
return
if not messageJson['type'] == 'Undo':
if not message_json['type'] == 'Undo':
if debug:
print('DEBUG: not an undo block')
return
if not hasObjectStringType(messageJson, debug):
if not hasObjectStringType(message_json, debug):
return
if not messageJson['object']['type'] == 'Block':
if not message_json['object']['type'] == 'Block':
if debug:
print('DEBUG: not an undo block')
return
if not hasObjectStringObject(messageJson, debug):
if not hasObjectStringObject(message_json, debug):
return
if debug:
print('DEBUG: c2s undo block request arrived in outbox')
messageId = removeIdEnding(messageJson['object']['object'])
messageId = removeIdEnding(message_json['object']['object'])
if '/statuses/' not in messageId:
if debug:
print('DEBUG: c2s undo block object is not a status')
@ -504,12 +504,12 @@ def outboxUndoBlock(base_dir: str, http_prefix: str,
print('DEBUG: c2s undo block post not found in inbox or outbox')
print(messageId)
return
nicknameBlocked = getNicknameFromActor(messageJson['object']['object'])
nicknameBlocked = getNicknameFromActor(message_json['object']['object'])
if not nicknameBlocked:
print('WARN: unable to find nickname in ' +
messageJson['object']['object'])
message_json['object']['object'])
return
domainObject = messageJson['object']['object']
domainObject = message_json['object']['object']
domainBlocked, portBlocked = getDomainFromActor(domainObject)
domainBlockedFull = getFullDomain(domainBlocked, portBlocked)
@ -770,25 +770,25 @@ def unmutePost(base_dir: str, nickname: str, domain: str, port: int,
def outboxMute(base_dir: str, http_prefix: str,
nickname: str, domain: str, port: int,
messageJson: {}, debug: bool,
message_json: {}, debug: bool,
recentPostsCache: {}) -> None:
"""When a mute is received by the outbox from c2s
"""
if not messageJson.get('type'):
if not message_json.get('type'):
return
if not hasActor(messageJson, debug):
if not hasActor(message_json, debug):
return
domainFull = getFullDomain(domain, port)
if not messageJson['actor'].endswith(domainFull + '/users/' + nickname):
if not message_json['actor'].endswith(domainFull + '/users/' + nickname):
return
if not messageJson['type'] == 'Ignore':
if not message_json['type'] == 'Ignore':
return
if not hasObjectString(messageJson, debug):
if not hasObjectString(message_json, debug):
return
if debug:
print('DEBUG: c2s mute request arrived in outbox')
messageId = removeIdEnding(messageJson['object'])
messageId = removeIdEnding(message_json['object'])
if '/statuses/' not in messageId:
if debug:
print('DEBUG: c2s mute object is not a status')
@ -804,13 +804,13 @@ def outboxMute(base_dir: str, http_prefix: str,
print('DEBUG: c2s mute post not found in inbox or outbox')
print(messageId)
return
nicknameMuted = getNicknameFromActor(messageJson['object'])
nicknameMuted = getNicknameFromActor(message_json['object'])
if not nicknameMuted:
print('WARN: unable to find nickname in ' + messageJson['object'])
print('WARN: unable to find nickname in ' + message_json['object'])
return
mutePost(base_dir, nickname, domain, port,
http_prefix, messageJson['object'], recentPostsCache,
http_prefix, message_json['object'], recentPostsCache,
debug)
if debug:
@ -819,31 +819,31 @@ def outboxMute(base_dir: str, http_prefix: str,
def outboxUndoMute(base_dir: str, http_prefix: str,
nickname: str, domain: str, port: int,
messageJson: {}, debug: bool,
message_json: {}, debug: bool,
recentPostsCache: {}) -> None:
"""When an undo mute is received by the outbox from c2s
"""
if not messageJson.get('type'):
if not message_json.get('type'):
return
if not hasActor(messageJson, debug):
if not hasActor(message_json, debug):
return
domainFull = getFullDomain(domain, port)
if not messageJson['actor'].endswith(domainFull + '/users/' + nickname):
if not message_json['actor'].endswith(domainFull + '/users/' + nickname):
return
if not messageJson['type'] == 'Undo':
if not message_json['type'] == 'Undo':
return
if not hasObjectStringType(messageJson, debug):
if not hasObjectStringType(message_json, debug):
return
if messageJson['object']['type'] != 'Ignore':
if message_json['object']['type'] != 'Ignore':
return
if not isinstance(messageJson['object']['object'], str):
if not isinstance(message_json['object']['object'], str):
if debug:
print('DEBUG: undo mute object is not a string')
return
if debug:
print('DEBUG: c2s undo mute request arrived in outbox')
messageId = removeIdEnding(messageJson['object']['object'])
messageId = removeIdEnding(message_json['object']['object'])
if '/statuses/' not in messageId:
if debug:
print('DEBUG: c2s undo mute object is not a status')
@ -859,14 +859,14 @@ def outboxUndoMute(base_dir: str, http_prefix: str,
print('DEBUG: c2s undo mute post not found in inbox or outbox')
print(messageId)
return
nicknameMuted = getNicknameFromActor(messageJson['object']['object'])
nicknameMuted = getNicknameFromActor(message_json['object']['object'])
if not nicknameMuted:
print('WARN: unable to find nickname in ' +
messageJson['object']['object'])
message_json['object']['object'])
return
unmutePost(base_dir, nickname, domain, port,
http_prefix, messageJson['object']['object'],
http_prefix, message_json['object']['object'],
recentPostsCache, debug)
if debug:

View File

@ -553,45 +553,45 @@ def sendUndoBookmarkViaServer(base_dir: str, session,
def outboxBookmark(recentPostsCache: {},
base_dir: str, http_prefix: str,
nickname: str, domain: str, port: int,
messageJson: {}, debug: bool) -> None:
message_json: {}, debug: bool) -> None:
""" When a bookmark request is received by the outbox from c2s
"""
if not messageJson.get('type'):
if not message_json.get('type'):
return
if messageJson['type'] != 'Add':
if message_json['type'] != 'Add':
return
if not hasActor(messageJson, debug):
if not hasActor(message_json, debug):
return
if not messageJson.get('target'):
if not message_json.get('target'):
if debug:
print('DEBUG: no target in bookmark Add')
return
if not hasObjectStringType(messageJson, debug):
if not hasObjectStringType(message_json, debug):
return
if not isinstance(messageJson['target'], str):
if not isinstance(message_json['target'], str):
if debug:
print('DEBUG: bookmark Add target is not string')
return
domainFull = getFullDomain(domain, port)
if not messageJson['target'].endswith('://' + domainFull +
'/users/' + nickname +
'/tlbookmarks'):
if not message_json['target'].endswith('://' + domainFull +
'/users/' + nickname +
'/tlbookmarks'):
if debug:
print('DEBUG: bookmark Add target invalid ' +
messageJson['target'])
message_json['target'])
return
if messageJson['object']['type'] != 'Document':
if message_json['object']['type'] != 'Document':
if debug:
print('DEBUG: bookmark Add type is not Document')
return
if not messageJson['object'].get('url'):
if not message_json['object'].get('url'):
if debug:
print('DEBUG: bookmark Add missing url')
return
if debug:
print('DEBUG: c2s bookmark Add request arrived in outbox')
messageUrl = removeIdEnding(messageJson['object']['url'])
messageUrl = removeIdEnding(message_json['object']['url'])
domain = removeDomainPort(domain)
postFilename = locatePost(base_dir, nickname, domain, messageUrl)
if not postFilename:
@ -601,7 +601,7 @@ def outboxBookmark(recentPostsCache: {},
return True
updateBookmarksCollection(recentPostsCache,
base_dir, postFilename, messageUrl,
messageJson['actor'], domain, debug)
message_json['actor'], domain, debug)
if debug:
print('DEBUG: post bookmarked via c2s - ' + postFilename)
@ -609,45 +609,45 @@ def outboxBookmark(recentPostsCache: {},
def outboxUndoBookmark(recentPostsCache: {},
base_dir: str, http_prefix: str,
nickname: str, domain: str, port: int,
messageJson: {}, debug: bool) -> None:
message_json: {}, debug: bool) -> None:
""" When an undo bookmark request is received by the outbox from c2s
"""
if not messageJson.get('type'):
if not message_json.get('type'):
return
if messageJson['type'] != 'Remove':
if message_json['type'] != 'Remove':
return
if not hasActor(messageJson, debug):
if not hasActor(message_json, debug):
return
if not messageJson.get('target'):
if not message_json.get('target'):
if debug:
print('DEBUG: no target in unbookmark Remove')
return
if not hasObjectStringType(messageJson, debug):
if not hasObjectStringType(message_json, debug):
return
if not isinstance(messageJson['target'], str):
if not isinstance(message_json['target'], str):
if debug:
print('DEBUG: unbookmark Remove target is not string')
return
domainFull = getFullDomain(domain, port)
if not messageJson['target'].endswith('://' + domainFull +
'/users/' + nickname +
'/tlbookmarks'):
if not message_json['target'].endswith('://' + domainFull +
'/users/' + nickname +
'/tlbookmarks'):
if debug:
print('DEBUG: unbookmark Remove target invalid ' +
messageJson['target'])
message_json['target'])
return
if messageJson['object']['type'] != 'Document':
if message_json['object']['type'] != 'Document':
if debug:
print('DEBUG: unbookmark Remove type is not Document')
return
if not messageJson['object'].get('url'):
if not message_json['object'].get('url'):
if debug:
print('DEBUG: unbookmark Remove missing url')
return
if debug:
print('DEBUG: c2s unbookmark Remove request arrived in outbox')
messageUrl = removeIdEnding(messageJson['object']['url'])
messageUrl = removeIdEnding(message_json['object']['url'])
domain = removeDomainPort(domain)
postFilename = locatePost(base_dir, nickname, domain, messageUrl)
if not postFilename:
@ -657,6 +657,6 @@ def outboxUndoBookmark(recentPostsCache: {},
return True
updateBookmarksCollection(recentPostsCache,
base_dir, postFilename, messageUrl,
messageJson['actor'], domain, debug)
message_json['actor'], domain, debug)
if debug:
print('DEBUG: post unbookmarked via c2s - ' + postFilename)

176
daemon.py
View File

@ -499,7 +499,7 @@ class PubServer(BaseHTTPRequestHandler):
self.server.base_dir,
nickname, self.server.domain)
messageJson = \
message_json = \
createPublicPost(self.server.base_dir,
nickname,
self.server.domain, self.server.port,
@ -519,10 +519,10 @@ class PubServer(BaseHTTPRequestHandler):
conversationId,
self.server.low_bandwidth,
self.server.content_license_url)
if messageJson:
if message_json:
# name field contains the answer
messageJson['object']['name'] = answer
if self._postToOutbox(messageJson,
message_json['object']['name'] = answer
if self._postToOutbox(message_json,
self.server.project_version, nickname):
postFilename = \
locatePost(self.server.base_dir, nickname,
@ -1258,7 +1258,7 @@ class PubServer(BaseHTTPRequestHandler):
self._404()
return True
def _postToOutbox(self, messageJson: {}, version: str,
def _postToOutbox(self, message_json: {}, version: str,
postToNickname: str) -> bool:
"""post is received by the outbox
Client to server message post
@ -1275,7 +1275,7 @@ class PubServer(BaseHTTPRequestHandler):
return postMessageToOutbox(self.server.session,
self.server.translate,
messageJson, self.postToNickname,
message_json, self.postToNickname,
self.server, self.server.base_dir,
self.server.http_prefix,
self.server.domain,
@ -1341,7 +1341,7 @@ class PubServer(BaseHTTPRequestHandler):
self.server.outboxThread[acct][index].kill()
return index
def _postToOutboxThread(self, messageJson: {}) -> bool:
def _postToOutboxThread(self, message_json: {}) -> bool:
"""Creates a thread to send a post
"""
accountOutboxThreadName = self.postToNickname
@ -1355,14 +1355,14 @@ class PubServer(BaseHTTPRequestHandler):
str(self.server.outbox_thread_index[accountOutboxThreadName]))
self.server.outboxThread[accountOutboxThreadName][index] = \
threadWithTrace(target=self._postToOutbox,
args=(messageJson.copy(),
args=(message_json.copy(),
self.server.project_version, None),
daemon=True)
print('Starting outbox thread')
self.server.outboxThread[accountOutboxThreadName][index].start()
return True
def _updateInboxQueue(self, nickname: str, messageJson: {},
def _updateInboxQueue(self, nickname: str, message_json: {},
messageBytes: str) -> int:
"""Update the inbox queue
"""
@ -1374,7 +1374,7 @@ class PubServer(BaseHTTPRequestHandler):
# check that the incoming message has a fully recognized
# linked data context
if not hasValidContext(messageJson):
if not hasValidContext(message_json):
print('Message arriving at inbox queue has no valid context')
self._400()
self.server.POSTbusy = False
@ -1382,14 +1382,14 @@ class PubServer(BaseHTTPRequestHandler):
# check for blocked domains so that they can be rejected early
messageDomain = None
if not hasActor(messageJson, self.server.debug):
if not hasActor(message_json, self.server.debug):
print('Message arriving at inbox queue has no actor')
self._400()
self.server.POSTbusy = False
return 3
# actor should be a string
if not isinstance(messageJson['actor'], str):
if not isinstance(message_json['actor'], str):
self._400()
self.server.POSTbusy = False
return 3
@ -1397,9 +1397,9 @@ class PubServer(BaseHTTPRequestHandler):
# check that some additional fields are strings
stringFields = ('id', 'type', 'published')
for checkField in stringFields:
if not messageJson.get(checkField):
if not message_json.get(checkField):
continue
if not isinstance(messageJson[checkField], str):
if not isinstance(message_json[checkField], str):
self._400()
self.server.POSTbusy = False
return 3
@ -1407,40 +1407,40 @@ class PubServer(BaseHTTPRequestHandler):
# check that to/cc fields are lists
listFields = ('to', 'cc')
for checkField in listFields:
if not messageJson.get(checkField):
if not message_json.get(checkField):
continue
if not isinstance(messageJson[checkField], list):
if not isinstance(message_json[checkField], list):
self._400()
self.server.POSTbusy = False
return 3
if hasObjectDict(messageJson):
if hasObjectDict(message_json):
stringFields = (
'id', 'actor', 'type', 'content', 'published',
'summary', 'url', 'attributedTo'
)
for checkField in stringFields:
if not messageJson['object'].get(checkField):
if not message_json['object'].get(checkField):
continue
if not isinstance(messageJson['object'][checkField], str):
if not isinstance(message_json['object'][checkField], str):
self._400()
self.server.POSTbusy = False
return 3
# check that some fields are lists
listFields = ('to', 'cc', 'attachment')
for checkField in listFields:
if not messageJson['object'].get(checkField):
if not message_json['object'].get(checkField):
continue
if not isinstance(messageJson['object'][checkField], list):
if not isinstance(message_json['object'][checkField], list):
self._400()
self.server.POSTbusy = False
return 3
# actor should look like a url
if '://' not in messageJson['actor'] or \
'.' not in messageJson['actor']:
if '://' not in message_json['actor'] or \
'.' not in message_json['actor']:
print('POST actor does not look like a url ' +
messageJson['actor'])
message_json['actor'])
self._400()
self.server.POSTbusy = False
return 3
@ -1449,15 +1449,15 @@ class PubServer(BaseHTTPRequestHandler):
if not self.server.allow_local_network_access:
localNetworkPatternList = getLocalNetworkAddresses()
for localNetworkPattern in localNetworkPatternList:
if localNetworkPattern in messageJson['actor']:
if localNetworkPattern in message_json['actor']:
print('POST actor contains local network address ' +
messageJson['actor'])
message_json['actor'])
self._400()
self.server.POSTbusy = False
return 3
messageDomain, messagePort = \
getDomainFromActor(messageJson['actor'])
getDomainFromActor(message_json['actor'])
self.server.blockedCacheLastUpdated = \
updateBlockedCache(self.server.base_dir,
@ -1476,7 +1476,7 @@ class PubServer(BaseHTTPRequestHandler):
if len(self.server.inbox_queue) >= self.server.max_queue_length:
if messageDomain:
print('Queue: Inbox queue is full. Incoming post from ' +
messageJson['actor'])
message_json['actor'])
else:
print('Queue: Inbox queue is full')
self._503()
@ -1506,15 +1506,15 @@ class PubServer(BaseHTTPRequestHandler):
elif self.headers.get('content-length'):
headersDict['content-length'] = self.headers['content-length']
originalMessageJson = messageJson.copy()
originalMessageJson = message_json.copy()
# whether to add a 'to' field to the message
addToFieldTypes = (
'Follow', 'Like', 'EmojiReact', 'Add', 'Remove', 'Ignore'
)
for addToType in addToFieldTypes:
messageJson, toFieldExists = \
addToField(addToType, messageJson, self.server.debug)
message_json, toFieldExists = \
addToField(addToType, message_json, self.server.debug)
beginSaveTime = time.time()
# save the json for later queue processing
@ -1536,7 +1536,7 @@ class PubServer(BaseHTTPRequestHandler):
self.server.http_prefix,
nickname,
self.server.domainFull,
messageJson, originalMessageJson,
message_json, originalMessageJson,
messageBytesDecoded,
headersDict,
self.path,
@ -13957,20 +13957,20 @@ class PubServer(BaseHTTPRequestHandler):
nickname, self.server.domain,
self.server.domainFull,
self.server.system_language)
messageJson = {}
message_json = {}
if pinnedPostJson:
postId = removeIdEnding(pinnedPostJson['id'])
messageJson = \
message_json = \
outboxMessageCreateWrap(self.server.http_prefix,
nickname,
self.server.domain,
self.server.port,
pinnedPostJson)
messageJson['id'] = postId + '/activity'
messageJson['object']['id'] = postId
messageJson['object']['url'] = replaceUsersWithAt(postId)
messageJson['object']['atomUri'] = postId
msg = json.dumps(messageJson,
message_json['id'] = postId + '/activity'
message_json['object']['id'] = postId
message_json['object']['url'] = replaceUsersWithAt(postId)
message_json['object']['atomUri'] = postId
msg = json.dumps(message_json,
ensure_ascii=False).encode('utf-8')
msglen = len(msg)
self._set_headers('application/json',
@ -16614,7 +16614,7 @@ class PubServer(BaseHTTPRequestHandler):
conversationId = None
if fields.get('conversationId'):
conversationId = fields['conversationId']
messageJson = \
message_json = \
createPublicPost(self.server.base_dir,
nickname,
self.server.domain,
@ -16633,25 +16633,25 @@ class PubServer(BaseHTTPRequestHandler):
conversationId,
self.server.low_bandwidth,
self.server.content_license_url)
if messageJson:
if message_json:
if fields['schedulePost']:
return 1
if pinToProfile:
contentStr = \
getBaseContentFromPost(messageJson,
getBaseContentFromPost(message_json,
self.server.system_language)
followersOnly = False
pinPost(self.server.base_dir,
nickname, self.server.domain, contentStr,
followersOnly)
return 1
if self._postToOutbox(messageJson,
if self._postToOutbox(message_json,
self.server.project_version,
nickname):
populateReplies(self.server.base_dir,
self.server.http_prefix,
self.server.domainFull,
messageJson,
message_json,
self.server.max_replies,
self.server.debug)
return 1
@ -16660,7 +16660,7 @@ class PubServer(BaseHTTPRequestHandler):
elif postType == 'newblog':
# citations button on newblog screen
if citationsButtonPress:
messageJson = \
message_json = \
htmlCitations(self.server.base_dir,
nickname,
self.server.domain,
@ -16674,13 +16674,13 @@ class PubServer(BaseHTTPRequestHandler):
filename, attachmentMediaType,
fields['imageDescription'],
self.server.theme_name)
if messageJson:
messageJson = messageJson.encode('utf-8')
messageJsonLen = len(messageJson)
if message_json:
message_json = message_json.encode('utf-8')
message_jsonLen = len(message_json)
self._set_headers('text/html',
messageJsonLen,
message_jsonLen,
cookie, callingDomain, False)
self._write(messageJson)
self._write(message_json)
return 1
else:
return -1
@ -16698,7 +16698,7 @@ class PubServer(BaseHTTPRequestHandler):
conversationId = None
if fields.get('conversationId'):
conversationId = fields['conversationId']
messageJson = \
message_json = \
createBlogPost(self.server.base_dir, nickname,
self.server.domain, self.server.port,
self.server.http_prefix,
@ -16718,17 +16718,17 @@ class PubServer(BaseHTTPRequestHandler):
conversationId,
self.server.low_bandwidth,
self.server.content_license_url)
if messageJson:
if message_json:
if fields['schedulePost']:
return 1
if self._postToOutbox(messageJson,
if self._postToOutbox(message_json,
self.server.project_version,
nickname):
refreshNewswire(self.server.base_dir)
populateReplies(self.server.base_dir,
self.server.http_prefix,
self.server.domainFull,
messageJson,
message_json,
self.server.max_replies,
self.server.debug)
return 1
@ -16849,7 +16849,7 @@ class PubServer(BaseHTTPRequestHandler):
if fields.get('conversationId'):
conversationId = fields['conversationId']
messageJson = \
message_json = \
createUnlistedPost(self.server.base_dir,
nickname,
self.server.domain, self.server.port,
@ -16871,16 +16871,16 @@ class PubServer(BaseHTTPRequestHandler):
conversationId,
self.server.low_bandwidth,
self.server.content_license_url)
if messageJson:
if message_json:
if fields['schedulePost']:
return 1
if self._postToOutbox(messageJson,
if self._postToOutbox(message_json,
self.server.project_version,
nickname):
populateReplies(self.server.base_dir,
self.server.http_prefix,
self.server.domain,
messageJson,
message_json,
self.server.max_replies,
self.server.debug)
return 1
@ -16899,7 +16899,7 @@ class PubServer(BaseHTTPRequestHandler):
if fields.get('conversationId'):
conversationId = fields['conversationId']
messageJson = \
message_json = \
createFollowersOnlyPost(self.server.base_dir,
nickname,
self.server.domain,
@ -16923,23 +16923,23 @@ class PubServer(BaseHTTPRequestHandler):
conversationId,
self.server.low_bandwidth,
self.server.content_license_url)
if messageJson:
if message_json:
if fields['schedulePost']:
return 1
if self._postToOutbox(messageJson,
if self._postToOutbox(message_json,
self.server.project_version,
nickname):
populateReplies(self.server.base_dir,
self.server.http_prefix,
self.server.domain,
messageJson,
message_json,
self.server.max_replies,
self.server.debug)
return 1
else:
return -1
elif postType == 'newdm':
messageJson = None
message_json = None
print('A DM was posted')
if '@' in mentionsStr:
city = getSpoofedCity(self.server.city,
@ -16955,7 +16955,7 @@ class PubServer(BaseHTTPRequestHandler):
conversationId = fields['conversationId']
content_license_url = self.server.content_license_url
messageJson = \
message_json = \
createDirectMessagePost(self.server.base_dir,
nickname,
self.server.domain,
@ -16980,25 +16980,25 @@ class PubServer(BaseHTTPRequestHandler):
conversationId,
self.server.low_bandwidth,
content_license_url)
if messageJson:
if message_json:
if fields['schedulePost']:
return 1
print('Sending new DM to ' +
str(messageJson['object']['to']))
if self._postToOutbox(messageJson,
str(message_json['object']['to']))
if self._postToOutbox(message_json,
self.server.project_version,
nickname):
populateReplies(self.server.base_dir,
self.server.http_prefix,
self.server.domain,
messageJson,
message_json,
self.server.max_replies,
self.server.debug)
return 1
else:
return -1
elif postType == 'newreminder':
messageJson = None
message_json = None
handle = nickname + '@' + self.server.domainFull
print('A reminder was posted for ' + handle)
if '@' + handle not in mentionsStr:
@ -17012,7 +17012,7 @@ class PubServer(BaseHTTPRequestHandler):
client_to_server = False
commentsEnabled = False
conversationId = None
messageJson = \
message_json = \
createDirectMessagePost(self.server.base_dir,
nickname,
self.server.domain,
@ -17034,12 +17034,12 @@ class PubServer(BaseHTTPRequestHandler):
conversationId,
self.server.low_bandwidth,
self.server.content_license_url)
if messageJson:
if message_json:
if fields['schedulePost']:
return 1
print('DEBUG: new reminder to ' +
str(messageJson['object']['to']))
if self._postToOutbox(messageJson,
str(message_json['object']['to']))
if self._postToOutbox(message_json,
self.server.project_version,
nickname):
return 1
@ -17057,7 +17057,7 @@ class PubServer(BaseHTTPRequestHandler):
self.server.base_dir,
nickname,
self.server.domain)
messageJson = \
message_json = \
createReportPost(self.server.base_dir,
nickname,
self.server.domain, self.server.port,
@ -17071,8 +17071,8 @@ class PubServer(BaseHTTPRequestHandler):
self.server.system_language,
self.server.low_bandwidth,
self.server.content_license_url)
if messageJson:
if self._postToOutbox(messageJson,
if message_json:
if self._postToOutbox(message_json,
self.server.project_version,
nickname):
return 1
@ -17096,7 +17096,7 @@ class PubServer(BaseHTTPRequestHandler):
nickname,
self.server.domain)
intDuration = int(fields['duration'])
messageJson = \
message_json = \
createQuestionPost(self.server.base_dir,
nickname,
self.server.domain,
@ -17113,10 +17113,10 @@ class PubServer(BaseHTTPRequestHandler):
self.server.system_language,
self.server.low_bandwidth,
self.server.content_license_url)
if messageJson:
if message_json:
if self.server.debug:
print('DEBUG: new Question')
if self._postToOutbox(messageJson,
if self._postToOutbox(message_json,
self.server.project_version,
nickname):
return 1
@ -18215,7 +18215,7 @@ class PubServer(BaseHTTPRequestHandler):
return
# convert the raw bytes to json
messageJson = json.loads(messageBytes)
message_json = json.loads(messageBytes)
fitnessPerformance(POSTstartTime, self.server.fitness,
'_POST', 'load json',
@ -18223,10 +18223,10 @@ class PubServer(BaseHTTPRequestHandler):
# https://www.w3.org/TR/activitypub/#object-without-create
if self.outboxAuthenticated:
if self._postToOutbox(messageJson,
if self._postToOutbox(message_json,
self.server.project_version, None):
if messageJson.get('id'):
locnStr = removeIdEnding(messageJson['id'])
if message_json.get('id'):
locnStr = removeIdEnding(message_json['id'])
self.headers['Location'] = locnStr
self.send_response(201)
self.end_headers()
@ -18248,7 +18248,7 @@ class PubServer(BaseHTTPRequestHandler):
if self.server.debug:
print('DEBUG: Check message has params')
if not messageJson:
if not message_json:
self.send_response(403)
self.end_headers()
self.server.POSTbusy = False
@ -18256,7 +18256,7 @@ class PubServer(BaseHTTPRequestHandler):
if self.path.endswith('/inbox') or \
self.path == '/sharedInbox':
if not inboxMessageHasParams(messageJson):
if not inboxMessageHasParams(message_json):
if self.server.debug:
print("DEBUG: inbox message doesn't have the " +
"required parameters")
@ -18287,7 +18287,7 @@ class PubServer(BaseHTTPRequestHandler):
if not self.server.unit_test:
if not inboxPermittedMessage(self.server.domain,
messageJson,
message_json,
self.server.federation_list):
if self.server.debug:
# https://www.youtube.com/watch?v=K3PrSj9XEu4
@ -18313,7 +18313,7 @@ class PubServer(BaseHTTPRequestHandler):
if self.postToNickname:
queueStatus = \
self._updateInboxQueue(self.postToNickname,
messageJson, messageBytes)
message_json, messageBytes)
if queueStatus >= 0 and queueStatus <= 3:
self.server.POSTbusy = False
return
@ -18332,7 +18332,7 @@ class PubServer(BaseHTTPRequestHandler):
if self.server.debug:
print('DEBUG: POST to shared inbox')
queueStatus = \
self._updateInboxQueue('inbox', messageJson, messageBytes)
self._updateInboxQueue('inbox', message_json, messageBytes)
if queueStatus >= 0 and queueStatus <= 3:
self.server.POSTbusy = False
return

View File

@ -114,31 +114,31 @@ def sendDeleteViaServer(base_dir: str, session,
def outboxDelete(base_dir: str, http_prefix: str,
nickname: str, domain: str,
messageJson: {}, debug: bool,
message_json: {}, debug: bool,
allow_deletion: bool,
recentPostsCache: {}) -> None:
""" When a delete request is received by the outbox from c2s
"""
if not messageJson.get('type'):
if not message_json.get('type'):
if debug:
print('DEBUG: delete - no type')
return
if not messageJson['type'] == 'Delete':
if not message_json['type'] == 'Delete':
if debug:
print('DEBUG: not a delete')
return
if not hasObjectString(messageJson, debug):
if not hasObjectString(message_json, debug):
return
if debug:
print('DEBUG: c2s delete request arrived in outbox')
deletePrefix = http_prefix + '://' + domain
if (not allow_deletion and
(not messageJson['object'].startswith(deletePrefix) or
not messageJson['actor'].startswith(deletePrefix))):
(not message_json['object'].startswith(deletePrefix) or
not message_json['actor'].startswith(deletePrefix))):
if debug:
print('DEBUG: delete not permitted from other instances')
return
messageId = removeIdEnding(messageJson['object'])
messageId = removeIdEnding(message_json['object'])
if '/statuses/' not in messageId:
if debug:
print('DEBUG: c2s delete object is not a status')

View File

@ -169,7 +169,7 @@ def E2EEdevicesCollection(base_dir: str, nickname: str, domain: str,
return devicesDict
def E2EEdecryptMessageFromDevice(messageJson: {}) -> str:
def E2EEdecryptMessageFromDevice(message_json: {}) -> str:
"""Locally decrypts a message on the device.
This should probably be a link to a local script
or native app, such that what the user sees isn't

View File

@ -1375,47 +1375,47 @@ def getFollowersOfActor(base_dir: str, actor: str, debug: bool) -> {}:
return recipientsDict
def outboxUndoFollow(base_dir: str, messageJson: {}, debug: bool) -> None:
def outboxUndoFollow(base_dir: str, message_json: {}, debug: bool) -> None:
"""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
"""
if not messageJson.get('type'):
if not message_json.get('type'):
return
if not messageJson['type'] == 'Undo':
if not message_json['type'] == 'Undo':
return
if not hasObjectStringType(messageJson, debug):
if not hasObjectStringType(message_json, debug):
return
if not messageJson['object']['type'] == 'Follow':
if not messageJson['object']['type'] == 'Join':
if not message_json['object']['type'] == 'Follow':
if not message_json['object']['type'] == 'Join':
return
if not hasObjectStringObject(messageJson, debug):
if not hasObjectStringObject(message_json, debug):
return
if not messageJson['object'].get('actor'):
if not message_json['object'].get('actor'):
return
if debug:
print('DEBUG: undo follow arrived in outbox')
nicknameFollower = getNicknameFromActor(messageJson['object']['actor'])
nicknameFollower = getNicknameFromActor(message_json['object']['actor'])
if not nicknameFollower:
print('WARN: unable to find nickname in ' +
messageJson['object']['actor'])
message_json['object']['actor'])
return
domainFollower, portFollower = \
getDomainFromActor(messageJson['object']['actor'])
getDomainFromActor(message_json['object']['actor'])
domainFollowerFull = getFullDomain(domainFollower, portFollower)
nicknameFollowing = getNicknameFromActor(messageJson['object']['object'])
nicknameFollowing = getNicknameFromActor(message_json['object']['object'])
if not nicknameFollowing:
print('WARN: unable to find nickname in ' +
messageJson['object']['object'])
message_json['object']['object'])
return
domainFollowing, portFollowing = \
getDomainFromActor(messageJson['object']['object'])
getDomainFromActor(message_json['object']['object'])
domainFollowingFull = getFullDomain(domainFollowing, portFollowing)
groupAccount = \
hasGroupType(base_dir, messageJson['object']['object'], None)
hasGroupType(base_dir, message_json['object']['object'], None)
if unfollowAccount(base_dir, nicknameFollower, domainFollowerFull,
nicknameFollowing, domainFollowingFull,
debug, groupAccount):

604
inbox.py

File diff suppressed because it is too large Load Diff

View File

@ -90,15 +90,15 @@ def setActorLanguages(base_dir: str, actorJson: {}, languagesStr: str) -> None:
def understoodPostLanguage(base_dir: str, nickname: str, domain: str,
messageJson: {}, system_language: str,
message_json: {}, system_language: str,
http_prefix: str, domainFull: str,
person_cache: {}) -> bool:
"""Returns true if the post is written in a language
understood by this account
"""
msgObject = messageJson
if hasObjectDict(messageJson):
msgObject = messageJson['object']
msgObject = message_json
if hasObjectDict(message_json):
msgObject = message_json['object']
if not msgObject.get('contentMap'):
return True
if not isinstance(msgObject['contentMap'], dict):

28
like.py
View File

@ -341,23 +341,23 @@ def sendUndoLikeViaServer(base_dir: str, session,
def outboxLike(recentPostsCache: {},
base_dir: str, http_prefix: str,
nickname: str, domain: str, port: int,
messageJson: {}, debug: bool) -> None:
message_json: {}, debug: bool) -> None:
""" When a like request is received by the outbox from c2s
"""
if not messageJson.get('type'):
if not message_json.get('type'):
if debug:
print('DEBUG: like - no type')
return
if not messageJson['type'] == 'Like':
if not message_json['type'] == 'Like':
if debug:
print('DEBUG: not a like')
return
if not hasObjectString(messageJson, debug):
if not hasObjectString(message_json, debug):
return
if debug:
print('DEBUG: c2s like request arrived in outbox')
messageId = removeIdEnding(messageJson['object'])
messageId = removeIdEnding(message_json['object'])
domain = removeDomainPort(domain)
postFilename = locatePost(base_dir, nickname, domain, messageId)
if not postFilename:
@ -367,7 +367,7 @@ def outboxLike(recentPostsCache: {},
return True
updateLikesCollection(recentPostsCache,
base_dir, postFilename, messageId,
messageJson['actor'],
message_json['actor'],
nickname, domain, debug, None)
if debug:
print('DEBUG: post liked via c2s - ' + postFilename)
@ -376,25 +376,25 @@ def outboxLike(recentPostsCache: {},
def outboxUndoLike(recentPostsCache: {},
base_dir: str, http_prefix: str,
nickname: str, domain: str, port: int,
messageJson: {}, debug: bool) -> None:
message_json: {}, debug: bool) -> None:
""" When an undo like request is received by the outbox from c2s
"""
if not messageJson.get('type'):
if not message_json.get('type'):
return
if not messageJson['type'] == 'Undo':
if not message_json['type'] == 'Undo':
return
if not hasObjectStringType(messageJson, debug):
if not hasObjectStringType(message_json, debug):
return
if not messageJson['object']['type'] == 'Like':
if not message_json['object']['type'] == 'Like':
if debug:
print('DEBUG: not a undo like')
return
if not hasObjectStringObject(messageJson, debug):
if not hasObjectStringObject(message_json, debug):
return
if debug:
print('DEBUG: c2s undo like request arrived in outbox')
messageId = removeIdEnding(messageJson['object']['object'])
messageId = removeIdEnding(message_json['object']['object'])
domain = removeDomainPort(domain)
postFilename = locatePost(base_dir, nickname, domain, messageId)
if not postFilename:
@ -403,7 +403,7 @@ def outboxUndoLike(recentPostsCache: {},
print(messageId)
return True
undoLikesCollectionEntry(recentPostsCache, base_dir, postFilename,
messageId, messageJson['actor'],
messageId, message_json['actor'],
domain, debug, None)
if debug:
print('DEBUG: post undo liked via c2s - ' + postFilename)

184
outbox.py
View File

@ -61,63 +61,63 @@ from webapp_post import individualPostAsHtml
def _outboxPersonReceiveUpdate(recentPostsCache: {},
base_dir: str, http_prefix: str,
nickname: str, domain: str, port: int,
messageJson: {}, debug: bool) -> None:
message_json: {}, debug: bool) -> None:
""" Receive an actor update from c2s
For example, setting the PGP key from the desktop client
"""
# these attachments are updatable via c2s
updatableAttachments = ('PGP', 'OpenPGP', 'Email')
if not messageJson.get('type'):
if not message_json.get('type'):
return
if not isinstance(messageJson['type'], str):
if not isinstance(message_json['type'], str):
if debug:
print('DEBUG: c2s actor update type is not a string')
return
if messageJson['type'] != 'Update':
if message_json['type'] != 'Update':
return
if not hasObjectStringType(messageJson, debug):
if not hasObjectStringType(message_json, debug):
return
if not isinstance(messageJson['object']['type'], str):
if not isinstance(message_json['object']['type'], str):
if debug:
print('DEBUG: c2s actor update object type is not a string')
return
if messageJson['object']['type'] != 'Person':
if message_json['object']['type'] != 'Person':
if debug:
print('DEBUG: not a c2s actor update')
return
if not messageJson.get('to'):
if not message_json.get('to'):
if debug:
print('DEBUG: c2s actor update has no "to" field')
return
if not hasActor(messageJson, debug):
if not hasActor(message_json, debug):
return
if not messageJson.get('id'):
if not message_json.get('id'):
if debug:
print('DEBUG: c2s actor update has no id field')
return
if not isinstance(messageJson['id'], str):
if not isinstance(message_json['id'], str):
if debug:
print('DEBUG: c2s actor update id is not a string')
return
domainFull = getFullDomain(domain, port)
actor = localActorUrl(http_prefix, nickname, domainFull)
if len(messageJson['to']) != 1:
if len(message_json['to']) != 1:
if debug:
print('DEBUG: c2s actor update - to does not contain one actor ' +
str(messageJson['to']))
str(message_json['to']))
return
if messageJson['to'][0] != actor:
if message_json['to'][0] != actor:
if debug:
print('DEBUG: c2s actor update - to does not contain actor ' +
str(messageJson['to']) + ' ' + actor)
str(message_json['to']) + ' ' + actor)
return
if not messageJson['id'].startswith(actor + '#updates/'):
if not message_json['id'].startswith(actor + '#updates/'):
if debug:
print('DEBUG: c2s actor update - unexpected id ' +
messageJson['id'])
message_json['id'])
return
updatedActorJson = messageJson['object']
updatedActorJson = message_json['object']
# load actor from file
actorFilename = acctDir(base_dir, nickname, domain) + '.json'
if not os.path.isfile(actorFilename):
@ -172,13 +172,13 @@ def _outboxPersonReceiveUpdate(recentPostsCache: {},
print('actor saved: ' + actorFilename)
if debug:
print('New attachment: ' + str(actorJson['attachment']))
messageJson['object'] = actorJson
message_json['object'] = actorJson
if debug:
print('DEBUG: actor update via c2s - ' + nickname + '@' + domain)
def postMessageToOutbox(session, translate: {},
messageJson: {}, postToNickname: str,
message_json: {}, postToNickname: str,
server, base_dir: str, http_prefix: str,
domain: str, domainFull: str,
onion_domain: str, i2p_domain: str, port: int,
@ -205,97 +205,97 @@ def postMessageToOutbox(session, translate: {},
Client to server message post
https://www.w3.org/TR/activitypub/#client-to-server-outbox-delivery
"""
if not messageJson.get('type'):
if not message_json.get('type'):
if debug:
print('DEBUG: POST to outbox has no "type" parameter')
return False
if not messageJson.get('object') and messageJson.get('content'):
if messageJson['type'] != 'Create':
if not message_json.get('object') and message_json.get('content'):
if message_json['type'] != 'Create':
# https://www.w3.org/TR/activitypub/#object-without-create
if debug:
print('DEBUG: POST to outbox - adding Create wrapper')
messageJson = \
message_json = \
outboxMessageCreateWrap(http_prefix,
postToNickname,
domain, port,
messageJson)
message_json)
# check that the outgoing post doesn't contain any markup
# which can be used to implement exploits
if hasObjectDict(messageJson):
contentStr = getBaseContentFromPost(messageJson, system_language)
if hasObjectDict(message_json):
contentStr = getBaseContentFromPost(message_json, system_language)
if contentStr:
if dangerousMarkup(contentStr, allow_local_network_access):
print('POST to outbox contains dangerous markup: ' +
str(messageJson))
str(message_json))
return False
if messageJson['type'] == 'Create':
if not (messageJson.get('id') and
messageJson.get('type') and
messageJson.get('actor') and
messageJson.get('object') and
messageJson.get('to')):
if not messageJson.get('id'):
if message_json['type'] == 'Create':
if not (message_json.get('id') and
message_json.get('type') and
message_json.get('actor') and
message_json.get('object') and
message_json.get('to')):
if not message_json.get('id'):
if debug:
print('DEBUG: POST to outbox - ' +
'Create does not have the id parameter ' +
str(messageJson))
elif not messageJson.get('id'):
str(message_json))
elif not message_json.get('id'):
if debug:
print('DEBUG: POST to outbox - ' +
'Create does not have the type parameter ' +
str(messageJson))
elif not messageJson.get('id'):
str(message_json))
elif not message_json.get('id'):
if debug:
print('DEBUG: POST to outbox - ' +
'Create does not have the actor parameter ' +
str(messageJson))
elif not messageJson.get('id'):
str(message_json))
elif not message_json.get('id'):
if debug:
print('DEBUG: POST to outbox - ' +
'Create does not have the object parameter ' +
str(messageJson))
str(message_json))
else:
if debug:
print('DEBUG: POST to outbox - ' +
'Create does not have the "to" parameter ' +
str(messageJson))
str(message_json))
return False
# actor should be a string
if not isinstance(messageJson['actor'], str):
if not isinstance(message_json['actor'], str):
return False
# actor should look like a url
if '://' not in messageJson['actor'] or \
'.' not in messageJson['actor']:
if '://' not in message_json['actor'] or \
'.' not in message_json['actor']:
return False
# sent by an actor on a local network address?
if not allow_local_network_access:
localNetworkPatternList = getLocalNetworkAddresses()
for localNetworkPattern in localNetworkPatternList:
if localNetworkPattern in messageJson['actor']:
if localNetworkPattern in message_json['actor']:
return False
testDomain, testPort = getDomainFromActor(messageJson['actor'])
testDomain, testPort = getDomainFromActor(message_json['actor'])
testDomain = getFullDomain(testDomain, testPort)
if isBlockedDomain(base_dir, testDomain):
if debug:
print('DEBUG: domain is blocked: ' + messageJson['actor'])
print('DEBUG: domain is blocked: ' + message_json['actor'])
return False
# replace youtube, so that google gets less tracking data
replaceYouTube(messageJson, yt_replace_domain, system_language)
replaceYouTube(message_json, yt_replace_domain, system_language)
# replace twitter, so that twitter posts can be shown without
# having a twitter account
replaceTwitter(messageJson, twitter_replacement_domain,
replaceTwitter(message_json, twitter_replacement_domain,
system_language)
# https://www.w3.org/TR/activitypub/#create-activity-outbox
messageJson['object']['attributedTo'] = messageJson['actor']
if messageJson['object'].get('attachment'):
message_json['object']['attributedTo'] = message_json['actor']
if message_json['object'].get('attachment'):
attachmentIndex = 0
attach = messageJson['object']['attachment'][attachmentIndex]
attach = message_json['object']['attachment'][attachmentIndex]
if attach.get('mediaType'):
fileExtension = 'png'
mediaTypeStr = \
@ -323,7 +323,7 @@ def postMessageToOutbox(session, translate: {},
postToNickname + '@' + domain
uploadMediaFilename = mediaDir + '/upload.' + fileExtension
if not os.path.isfile(uploadMediaFilename):
del messageJson['object']['attachment']
del message_json['object']['attachment']
else:
# generate a path for the uploaded image
mPath = getMediaPath()
@ -345,13 +345,13 @@ def postMessageToOutbox(session, translate: {},
'Create', 'Announce', 'Like', 'EmojiReact', 'Follow', 'Undo',
'Update', 'Add', 'Remove', 'Block', 'Delete', 'Skill', 'Ignore'
)
if messageJson['type'] not in permittedOutboxTypes:
if message_json['type'] not in permittedOutboxTypes:
if debug:
print('DEBUG: POST to outbox - ' + messageJson['type'] +
print('DEBUG: POST to outbox - ' + message_json['type'] +
' is not a permitted activity type')
return False
if messageJson.get('id'):
postId = removeIdEnding(messageJson['id'])
if message_json.get('id'):
postId = removeIdEnding(message_json['id'])
if debug:
print('DEBUG: id attribute exists within POST to outbox')
else:
@ -360,14 +360,14 @@ def postMessageToOutbox(session, translate: {},
postId = None
if debug:
print('DEBUG: savePostToBox')
if messageJson['type'] != 'Upgrade':
if message_json['type'] != 'Upgrade':
outboxName = 'outbox'
# if this is a blog post or an event then save to its own box
if messageJson['type'] == 'Create':
if hasObjectDict(messageJson):
if messageJson['object'].get('type'):
if messageJson['object']['type'] == 'Article':
if message_json['type'] == 'Create':
if hasObjectDict(message_json):
if message_json['object'].get('type'):
if message_json['object']['type'] == 'Article':
outboxName = 'tlblogs'
savedFilename = \
@ -375,7 +375,7 @@ def postMessageToOutbox(session, translate: {},
http_prefix,
postId,
postToNickname, domainFull,
messageJson, outboxName)
message_json, outboxName)
if not savedFilename:
print('WARN: post not saved to outbox ' + outboxName)
return False
@ -410,7 +410,7 @@ def postMessageToOutbox(session, translate: {},
'Create', 'Question', 'Note', 'EncryptedMessage', 'Article',
'Patch', 'Announce'
)
if messageJson['type'] in indexedActivities:
if message_json['type'] in indexedActivities:
indexes = [outboxName, "inbox"]
selfActor = \
localActorUrl(http_prefix, postToNickname, domainFull)
@ -422,7 +422,7 @@ def postMessageToOutbox(session, translate: {},
if boxNameIndex == 'inbox':
if isImageMedia(session, base_dir, http_prefix,
postToNickname, domain,
messageJson,
message_json,
translate,
yt_replace_domain,
twitter_replacement_domain,
@ -439,7 +439,7 @@ def postMessageToOutbox(session, translate: {},
# avoid duplicates of the message if already going
# back to the inbox of the same account
if selfActor not in messageJson['to']:
if selfActor not in message_json['to']:
# show sent post within the inbox,
# as is the typical convention
inboxUpdateIndex(boxNameIndex, base_dir,
@ -461,7 +461,7 @@ def postMessageToOutbox(session, translate: {},
cached_webfingers,
person_cache,
postToNickname, domain, port,
messageJson, None, True,
message_json, None, True,
allow_deletion,
http_prefix, __version__,
boxNameIndex,
@ -479,7 +479,7 @@ def postMessageToOutbox(session, translate: {},
cw_lists, lists_enabled)
if outboxAnnounce(recentPostsCache,
base_dir, messageJson, debug):
base_dir, message_json, debug):
if debug:
print('DEBUG: Updated announcements (shares) collection ' +
'for the post associated with the Announce activity')
@ -520,7 +520,7 @@ def postMessageToOutbox(session, translate: {},
postLog,
cached_webfingers,
person_cache,
messageJson, debug,
message_json, debug,
version,
shared_items_federated_domains,
sharedItemFederationTokens,
@ -529,67 +529,67 @@ def postMessageToOutbox(session, translate: {},
if debug:
print('DEBUG: handle any unfollow requests')
outboxUndoFollow(base_dir, messageJson, debug)
outboxUndoFollow(base_dir, message_json, debug)
if debug:
print('DEBUG: handle skills changes requests')
outboxSkills(base_dir, postToNickname, messageJson, debug)
outboxSkills(base_dir, postToNickname, message_json, debug)
if debug:
print('DEBUG: handle availability changes requests')
outboxAvailability(base_dir, postToNickname, messageJson, debug)
outboxAvailability(base_dir, postToNickname, message_json, debug)
if debug:
print('DEBUG: handle any like requests')
outboxLike(recentPostsCache,
base_dir, http_prefix,
postToNickname, domain, port,
messageJson, debug)
message_json, debug)
if debug:
print('DEBUG: handle any undo like requests')
outboxUndoLike(recentPostsCache,
base_dir, http_prefix,
postToNickname, domain, port,
messageJson, debug)
message_json, debug)
if debug:
print('DEBUG: handle any emoji reaction requests')
outboxReaction(recentPostsCache,
base_dir, http_prefix,
postToNickname, domain, port,
messageJson, debug)
message_json, debug)
if debug:
print('DEBUG: handle any undo emoji reaction requests')
outboxUndoReaction(recentPostsCache,
base_dir, http_prefix,
postToNickname, domain, port,
messageJson, debug)
message_json, debug)
if debug:
print('DEBUG: handle any undo announce requests')
outboxUndoAnnounce(recentPostsCache,
base_dir, http_prefix,
postToNickname, domain, port,
messageJson, debug)
message_json, debug)
if debug:
print('DEBUG: handle any bookmark requests')
outboxBookmark(recentPostsCache,
base_dir, http_prefix,
postToNickname, domain, port,
messageJson, debug)
message_json, debug)
if debug:
print('DEBUG: handle any undo bookmark requests')
outboxUndoBookmark(recentPostsCache,
base_dir, http_prefix,
postToNickname, domain, port,
messageJson, debug)
message_json, debug)
if debug:
print('DEBUG: handle delete requests')
outboxDelete(base_dir, http_prefix,
postToNickname, domain,
messageJson, debug,
message_json, debug,
allow_deletion,
recentPostsCache)
@ -598,20 +598,20 @@ def postMessageToOutbox(session, translate: {},
outboxBlock(base_dir, http_prefix,
postToNickname, domain,
port,
messageJson, debug)
message_json, debug)
if debug:
print('DEBUG: handle undo block requests')
outboxUndoBlock(base_dir, http_prefix,
postToNickname, domain,
port, messageJson, debug)
port, message_json, debug)
if debug:
print('DEBUG: handle mute requests')
outboxMute(base_dir, http_prefix,
postToNickname, domain,
port,
messageJson, debug,
message_json, debug,
recentPostsCache)
if debug:
@ -619,13 +619,13 @@ def postMessageToOutbox(session, translate: {},
outboxUndoMute(base_dir, http_prefix,
postToNickname, domain,
port,
messageJson, debug,
message_json, debug,
recentPostsCache)
if debug:
print('DEBUG: handle share uploads')
outboxShareUpload(base_dir, http_prefix, postToNickname, domain,
port, messageJson, debug, city,
port, message_json, debug, city,
system_language, translate, low_bandwidth,
content_license_url)
@ -633,21 +633,21 @@ def postMessageToOutbox(session, translate: {},
print('DEBUG: handle undo share uploads')
outboxUndoShareUpload(base_dir, http_prefix,
postToNickname, domain,
port, messageJson, debug)
port, message_json, debug)
if debug:
print('DEBUG: handle actor updates from c2s')
_outboxPersonReceiveUpdate(recentPostsCache,
base_dir, http_prefix,
postToNickname, domain, port,
messageJson, debug)
message_json, debug)
if debug:
print('DEBUG: sending c2s post to named addresses')
if messageJson.get('to'):
if message_json.get('to'):
print('c2s sender: ' +
postToNickname + '@' + domain + ':' + str(port) +
' recipient: ' + str(messageJson['to']))
' recipient: ' + str(message_json['to']))
else:
print('c2s sender: ' +
postToNickname + '@' + domain + ':' + str(port))
@ -661,7 +661,7 @@ def postMessageToOutbox(session, translate: {},
postLog,
cached_webfingers,
person_cache,
messageJson, debug,
message_json, debug,
version,
shared_items_federated_domains,
sharedItemFederationTokens,

View File

@ -1564,30 +1564,30 @@ def _createPostBase(base_dir: str,
def outboxMessageCreateWrap(http_prefix: str,
nickname: str, domain: str, port: int,
messageJson: {}) -> {}:
message_json: {}) -> {}:
"""Wraps a received message in a Create
https://www.w3.org/TR/activitypub/#object-without-create
"""
domain = getFullDomain(domain, port)
statusNumber, published = getStatusNumber()
if messageJson.get('published'):
published = messageJson['published']
if message_json.get('published'):
published = message_json['published']
newPostId = \
localActorUrl(http_prefix, nickname, domain) + \
'/statuses/' + statusNumber
cc = []
if messageJson.get('cc'):
cc = messageJson['cc']
if message_json.get('cc'):
cc = message_json['cc']
newPost = {
"@context": "https://www.w3.org/ns/activitystreams",
'id': newPostId + '/activity',
'type': 'Create',
'actor': localActorUrl(http_prefix, nickname, domain),
'published': published,
'to': messageJson['to'],
'to': message_json['to'],
'cc': cc,
'object': messageJson
'object': message_json
}
newPost['object']['id'] = newPost['id']
newPost['object']['url'] = \
@ -1909,7 +1909,7 @@ def createQuestionPost(base_dir: str,
"""
domainFull = getFullDomain(domain, port)
localActor = localActorUrl(http_prefix, nickname, domainFull)
messageJson = \
message_json = \
_createPostBase(base_dir, nickname, domain, port,
'https://www.w3.org/ns/activitystreams#Public',
localActor + '/followers',
@ -1922,17 +1922,17 @@ def createQuestionPost(base_dir: str,
None, None, None,
None, None, None, None, None, system_language,
None, low_bandwidth, content_license_url)
messageJson['object']['type'] = 'Question'
messageJson['object']['oneOf'] = []
messageJson['object']['votersCount'] = 0
message_json['object']['type'] = 'Question'
message_json['object']['oneOf'] = []
message_json['object']['votersCount'] = 0
currTime = datetime.datetime.utcnow()
daysSinceEpoch = \
int((currTime - datetime.datetime(1970, 1, 1)).days + durationDays)
endTime = datetime.datetime(1970, 1, 1) + \
datetime.timedelta(daysSinceEpoch)
messageJson['object']['endTime'] = endTime.strftime("%Y-%m-%dT%H:%M:%SZ")
message_json['object']['endTime'] = endTime.strftime("%Y-%m-%dT%H:%M:%SZ")
for questionOption in qOptions:
messageJson['object']['oneOf'].append({
message_json['object']['oneOf'].append({
"type": "Note",
"name": questionOption,
"replies": {
@ -1940,7 +1940,7 @@ def createQuestionPost(base_dir: str,
"totalItems": 0
}
})
return messageJson
return message_json
def createUnlistedPost(base_dir: str,
@ -2072,7 +2072,7 @@ def createDirectMessagePost(base_dir: str,
return None
postTo = None
postCc = None
messageJson = \
message_json = \
_createPostBase(base_dir, nickname, domain, port,
postTo, postCc,
http_prefix, content, followersOnly, saveToFile,
@ -2087,15 +2087,15 @@ def createDirectMessagePost(base_dir: str,
conversationId, low_bandwidth,
content_license_url)
# mentioned recipients go into To rather than Cc
messageJson['to'] = messageJson['object']['cc']
messageJson['object']['to'] = messageJson['to']
messageJson['cc'] = []
messageJson['object']['cc'] = []
message_json['to'] = message_json['object']['cc']
message_json['object']['to'] = message_json['to']
message_json['cc'] = []
message_json['object']['cc'] = []
if schedulePost:
postId = removeIdEnding(messageJson['object']['id'])
postId = removeIdEnding(message_json['object']['id'])
savePostToBox(base_dir, http_prefix, postId,
nickname, domain, messageJson, 'scheduled')
return messageJson
nickname, domain, message_json, 'scheduled')
return message_json
def createReportPost(base_dir: str,

View File

@ -357,33 +357,33 @@ def sendUndoReactionViaServer(base_dir: str, session,
def outboxReaction(recentPostsCache: {},
base_dir: str, http_prefix: str,
nickname: str, domain: str, port: int,
messageJson: {}, debug: bool) -> None:
message_json: {}, debug: bool) -> None:
""" When a reaction request is received by the outbox from c2s
"""
if not messageJson.get('type'):
if not message_json.get('type'):
if debug:
print('DEBUG: reaction - no type')
return
if not messageJson['type'] == 'EmojiReact':
if not message_json['type'] == 'EmojiReact':
if debug:
print('DEBUG: not a reaction')
return
if not hasObjectString(messageJson, debug):
if not hasObjectString(message_json, debug):
return
if not messageJson.get('content'):
if not message_json.get('content'):
return
if not isinstance(messageJson['content'], str):
if not isinstance(message_json['content'], str):
return
if not validEmojiContent(messageJson['content']):
if not validEmojiContent(message_json['content']):
print('outboxReaction: Invalid emoji reaction: "' +
messageJson['content'] + '"')
message_json['content'] + '"')
return
if debug:
print('DEBUG: c2s reaction request arrived in outbox')
messageId = removeIdEnding(messageJson['object'])
messageId = removeIdEnding(message_json['object'])
domain = removeDomainPort(domain)
emojiContent = messageJson['content']
emojiContent = message_json['content']
postFilename = locatePost(base_dir, nickname, domain, messageId)
if not postFilename:
if debug:
@ -392,7 +392,7 @@ def outboxReaction(recentPostsCache: {},
return True
updateReactionCollection(recentPostsCache,
base_dir, postFilename, messageId,
messageJson['actor'],
message_json['actor'],
nickname, domain, debug, None, emojiContent)
if debug:
print('DEBUG: post reaction via c2s - ' + postFilename)
@ -401,30 +401,30 @@ def outboxReaction(recentPostsCache: {},
def outboxUndoReaction(recentPostsCache: {},
base_dir: str, http_prefix: str,
nickname: str, domain: str, port: int,
messageJson: {}, debug: bool) -> None:
message_json: {}, debug: bool) -> None:
""" When an undo reaction request is received by the outbox from c2s
"""
if not messageJson.get('type'):
if not message_json.get('type'):
return
if not messageJson['type'] == 'Undo':
if not message_json['type'] == 'Undo':
return
if not hasObjectStringType(messageJson, debug):
if not hasObjectStringType(message_json, debug):
return
if not messageJson['object']['type'] == 'EmojiReact':
if not message_json['object']['type'] == 'EmojiReact':
if debug:
print('DEBUG: not a undo reaction')
return
if not messageJson['object'].get('content'):
if not message_json['object'].get('content'):
return
if not isinstance(messageJson['object']['content'], str):
if not isinstance(message_json['object']['content'], str):
return
if not hasObjectStringObject(messageJson, debug):
if not hasObjectStringObject(message_json, debug):
return
if debug:
print('DEBUG: c2s undo reaction request arrived in outbox')
messageId = removeIdEnding(messageJson['object']['object'])
emojiContent = messageJson['object']['content']
messageId = removeIdEnding(message_json['object']['object'])
emojiContent = message_json['object']['content']
domain = removeDomainPort(domain)
postFilename = locatePost(base_dir, nickname, domain, messageId)
if not postFilename:
@ -433,7 +433,7 @@ def outboxUndoReaction(recentPostsCache: {},
print(messageId)
return True
undoReactionCollectionEntry(recentPostsCache, base_dir, postFilename,
messageId, messageJson['actor'],
messageId, message_json['actor'],
domain, debug, None, emojiContent)
if debug:
print('DEBUG: post undo reaction via c2s - ' + postFilename)

View File

@ -1029,70 +1029,70 @@ def getSharedItemsCatalogViaServer(base_dir, session,
def outboxShareUpload(base_dir: str, http_prefix: str,
nickname: str, domain: str, port: int,
messageJson: {}, debug: bool, city: str,
message_json: {}, debug: bool, city: str,
system_language: str, translate: {},
low_bandwidth: bool,
content_license_url: str) -> None:
""" When a shared item is received by the outbox from c2s
"""
if not messageJson.get('type'):
if not message_json.get('type'):
return
if not messageJson['type'] == 'Add':
if not message_json['type'] == 'Add':
return
if not hasObjectStringType(messageJson, debug):
if not hasObjectStringType(message_json, debug):
return
if not messageJson['object']['type'] == 'Offer':
if not message_json['object']['type'] == 'Offer':
if debug:
print('DEBUG: not an Offer activity')
return
if not messageJson['object'].get('displayName'):
if not message_json['object'].get('displayName'):
if debug:
print('DEBUG: displayName missing from Offer')
return
if not messageJson['object'].get('summary'):
if not message_json['object'].get('summary'):
if debug:
print('DEBUG: summary missing from Offer')
return
if not messageJson['object'].get('itemQty'):
if not message_json['object'].get('itemQty'):
if debug:
print('DEBUG: itemQty missing from Offer')
return
if not messageJson['object'].get('itemType'):
if not message_json['object'].get('itemType'):
if debug:
print('DEBUG: itemType missing from Offer')
return
if not messageJson['object'].get('category'):
if not message_json['object'].get('category'):
if debug:
print('DEBUG: category missing from Offer')
return
if not messageJson['object'].get('duration'):
if not message_json['object'].get('duration'):
if debug:
print('DEBUG: duration missing from Offer')
return
itemQty = float(messageJson['object']['itemQty'])
itemQty = float(message_json['object']['itemQty'])
location = ''
if messageJson['object'].get('location'):
location = messageJson['object']['location']
if message_json['object'].get('location'):
location = message_json['object']['location']
imageFilename = None
if messageJson['object'].get('imageFilename'):
imageFilename = messageJson['object']['imageFilename']
if message_json['object'].get('imageFilename'):
imageFilename = message_json['object']['imageFilename']
if debug:
print('Adding shared item')
pprint(messageJson)
pprint(message_json)
addShare(base_dir,
http_prefix, nickname, domain, port,
messageJson['object']['displayName'],
messageJson['object']['summary'],
message_json['object']['displayName'],
message_json['object']['summary'],
imageFilename,
itemQty,
messageJson['object']['itemType'],
messageJson['object']['category'],
message_json['object']['itemType'],
message_json['object']['category'],
location,
messageJson['object']['duration'],
message_json['object']['duration'],
debug, city,
messageJson['object']['itemPrice'],
messageJson['object']['itemCurrency'],
message_json['object']['itemPrice'],
message_json['object']['itemCurrency'],
system_language, translate, 'shares',
low_bandwidth, content_license_url)
if debug:
@ -1101,26 +1101,26 @@ def outboxShareUpload(base_dir: str, http_prefix: str,
def outboxUndoShareUpload(base_dir: str, http_prefix: str,
nickname: str, domain: str, port: int,
messageJson: {}, debug: bool) -> None:
message_json: {}, debug: bool) -> None:
""" When a shared item is removed via c2s
"""
if not messageJson.get('type'):
if not message_json.get('type'):
return
if not messageJson['type'] == 'Remove':
if not message_json['type'] == 'Remove':
return
if not hasObjectStringType(messageJson, debug):
if not hasObjectStringType(message_json, debug):
return
if not messageJson['object']['type'] == 'Offer':
if not message_json['object']['type'] == 'Offer':
if debug:
print('DEBUG: not an Offer activity')
return
if not messageJson['object'].get('displayName'):
if not message_json['object'].get('displayName'):
if debug:
print('DEBUG: displayName missing from Offer')
return
domainFull = getFullDomain(domain, port)
removeSharedItem(base_dir, nickname, domain,
messageJson['object']['displayName'],
message_json['object']['displayName'],
http_prefix, domainFull, 'shares')
if debug:
print('DEBUG: shared item removed via c2s')

View File

@ -144,26 +144,26 @@ def getSkills(base_dir: str, nickname: str, domain: str) -> []:
return None
def outboxSkills(base_dir: str, nickname: str, messageJson: {},
def outboxSkills(base_dir: str, nickname: str, message_json: {},
debug: bool) -> bool:
"""Handles receiving a skills update
"""
if not messageJson.get('type'):
if not message_json.get('type'):
return False
if not messageJson['type'] == 'Skill':
if not message_json['type'] == 'Skill':
return False
if not hasActor(messageJson, debug):
if not hasActor(message_json, debug):
return False
if not hasObjectString(messageJson, debug):
if not hasObjectString(message_json, debug):
return False
actorNickname = getNicknameFromActor(messageJson['actor'])
actorNickname = getNicknameFromActor(message_json['actor'])
if actorNickname != nickname:
return False
domain, port = getDomainFromActor(messageJson['actor'])
skill = messageJson['object'].replace('"', '').split(';')[0].strip()
domain, port = getDomainFromActor(message_json['actor'])
skill = message_json['object'].replace('"', '').split(';')[0].strip()
skillLevelPercentStr = \
messageJson['object'].replace('"', '').split(';')[1].strip()
message_json['object'].replace('"', '').split(';')[1].strip()
skillLevelPercent = 50
if skillLevelPercentStr.isdigit():
skillLevelPercent = int(skillLevelPercentStr)