flake8 format

main
Bob Mottram 2020-04-04 12:35:55 +01:00
parent b7fc2b948d
commit 05d2d3d983
1 changed files with 85 additions and 72 deletions

157
skills.py
View File

@ -1,14 +1,12 @@
__filename__="skills.py" __filename__ = "skills.py"
__author__="Bob Mottram" __author__ = "Bob Mottram"
__license__="AGPL3+" __license__ = "AGPL3+"
__version__="1.1.0" __version__ = "1.1.0"
__maintainer__="Bob Mottram" __maintainer__ = "Bob Mottram"
__email__="bob@freedombone.net" __email__ = "bob@freedombone.net"
__status__="Production" __status__ = "Production"
import json
import os import os
import time
from webfinger import webfingerHandle from webfinger import webfingerHandle
from auth import createBasicAuthHeader from auth import createBasicAuthHeader
from posts import getPersonBox from posts import getPersonBox
@ -18,58 +16,63 @@ from utils import getDomainFromActor
from utils import loadJson from utils import loadJson
from utils import saveJson from utils import saveJson
def setSkillLevel(baseDir: str,nickname: str,domain: str, \
skill: str,skillLevelPercent: int) -> bool: def setSkillLevel(baseDir: str, nickname: str, domain: str,
skill: str, skillLevelPercent: int) -> bool:
"""Set a skill level for a person """Set a skill level for a person
Setting skill level to zero removes it Setting skill level to zero removes it
""" """
if skillLevelPercent<0 or skillLevelPercent>100: if skillLevelPercent < 0 or skillLevelPercent > 100:
return False return False
actorFilename=baseDir+'/accounts/'+nickname+'@'+domain+'.json' actorFilename = baseDir + '/accounts/' + nickname + '@' + domain + '.json'
if not os.path.isfile(actorFilename): if not os.path.isfile(actorFilename):
return False return False
actorJson=loadJson(actorFilename) actorJson = loadJson(actorFilename)
if actorJson: if actorJson:
if not actorJson.get('skills'): if not actorJson.get('skills'):
actorJson['skills']={} actorJson['skills'] = {}
if skillLevelPercent>0: if skillLevelPercent > 0:
actorJson['skills'][skill]=skillLevelPercent actorJson['skills'][skill] = skillLevelPercent
else: else:
del actorJson['skills'][skill] del actorJson['skills'][skill]
saveJson(actorJson,actorFilename) saveJson(actorJson, actorFilename)
return True return True
def setSkills(baseDir: str,nickname: str,domain: str,skills: {}) -> None:
actorFilename=baseDir+'/accounts/'+nickname+'@'+domain+'.json' def setSkills(baseDir: str, nickname: str, domain: str, skills: {}) -> None:
actorFilename = baseDir + '/accounts/' + nickname + '@' + domain + '.json'
if not os.path.isfile(actorFilename): if not os.path.isfile(actorFilename):
return False return False
actorJson=loadJson(actorFilename) actorJson = loadJson(actorFilename)
if actorJson: if actorJson:
actorJson['skills']=skills actorJson['skills'] = skills
saveJson(actorJson,actorFilename) saveJson(actorJson, actorFilename)
def getSkills(baseDir: str,nickname: str,domain: str) -> []:
def getSkills(baseDir: str, nickname: str, domain: str) -> []:
"""Returns the skills for a given person """Returns the skills for a given person
""" """
actorFilename=baseDir+'/accounts/'+nickname+'@'+domain+'.json' actorFilename = baseDir + '/accounts/' + nickname + '@' + domain + '.json'
if not os.path.isfile(actorFilename): if not os.path.isfile(actorFilename):
return False return False
actorJson=loadJson(actorFilename) actorJson = loadJson(actorFilename)
if actorJson: if actorJson:
if not actorJson.get('skills'): if not actorJson.get('skills'):
return None return None
return actorJson['skills'] return actorJson['skills']
return None return None
def outboxSkills(baseDir: str,nickname: str,messageJson: {},debug: bool) -> bool:
def outboxSkills(baseDir: str, nickname: str, messageJson: {},
debug: bool) -> bool:
"""Handles receiving a skills update """Handles receiving a skills update
""" """
if not messageJson.get('type'): if not messageJson.get('type'):
return False return False
if not messageJson['type']=='Skill': if not messageJson['type'] == 'Skill':
return False return False
if not messageJson.get('actor'): if not messageJson.get('actor'):
return False return False
@ -78,91 +81,101 @@ def outboxSkills(baseDir: str,nickname: str,messageJson: {},debug: bool) -> bool
if not isinstance(messageJson['object'], str): if not isinstance(messageJson['object'], str):
return False return False
actorNickname=getNicknameFromActor(messageJson['actor']) actorNickname = getNicknameFromActor(messageJson['actor'])
if actorNickname!=nickname: if actorNickname != nickname:
return False return False
domain,port=getDomainFromActor(messageJson['actor']) domain, port = getDomainFromActor(messageJson['actor'])
skill=messageJson['object'].replace('"','').split(';')[0].strip() skill = messageJson['object'].replace('"', '').split(';')[0].strip()
skillLevelPercentStr=messageJson['object'].replace('"','').split(';')[1].strip() skillLevelPercentStr = \
skillLevelPercent=50 messageJson['object'].replace('"', '').split(';')[1].strip()
skillLevelPercent = 50
if skillLevelPercentStr.isdigit(): if skillLevelPercentStr.isdigit():
skillLevelPercent=int(skillLevelPercentStr) skillLevelPercent = int(skillLevelPercentStr)
return setSkillLevel(baseDir,nickname,domain, \ return setSkillLevel(baseDir, nickname, domain,
skill,skillLevelPercent) skill, skillLevelPercent)
def sendSkillViaServer(baseDir: str,session,nickname: str,password: str,
domain: str,port: int, \ def sendSkillViaServer(baseDir: str, session, nickname: str, password: str,
httpPrefix: str, \ domain: str, port: int,
skill: str,skillLevelPercent: int, \ httpPrefix: str,
cachedWebfingers: {},personCache: {}, \ skill: str, skillLevelPercent: int,
debug: bool,projectVersion: str) -> {}: cachedWebfingers: {}, personCache: {},
debug: bool, projectVersion: str) -> {}:
"""Sets a skill for a person via c2s """Sets a skill for a person via c2s
""" """
if not session: if not session:
print('WARN: No session for sendSkillViaServer') print('WARN: No session for sendSkillViaServer')
return 6 return 6
domainFull=domain domainFull = domain
if port: if port:
if port!=80 and port!=443: if port != 80 and port != 443:
if ':' not in domain: if ':' not in domain:
domainFull=domain+':'+str(port) domainFull = domain + ':' + str(port)
toUrl=httpPrefix+'://'+domainFull+'/users/'+nickname actor = httpPrefix + '://' + domainFull + '/users/' + nickname
ccUrl=httpPrefix+'://'+domainFull+'/users/'+nickname+'/followers' toUrl = actor
ccUrl = actor + '/followers'
if skillLevelPercent: if skillLevelPercent:
skillStr=skill+';'+str(skillLevelPercent) skillStr = skill + ';' + str(skillLevelPercent)
else: else:
skillStr=skill+';0' skillStr = skill + ';0'
newSkillJson={
newSkillJson = {
'type': 'Skill', 'type': 'Skill',
'actor': httpPrefix+'://'+domainFull+'/users/'+nickname, 'actor': actor,
'object': '"'+skillStr+'"', 'object': '"'+skillStr+'"',
'to': [toUrl], 'to': [toUrl],
'cc': [ccUrl] 'cc': [ccUrl]
} }
handle=httpPrefix+'://'+domainFull+'/@'+nickname handle = httpPrefix + '://' + domainFull + '/@' + nickname
# lookup the inbox for the To handle # lookup the inbox for the To handle
wfRequest=webfingerHandle(session,handle,httpPrefix,cachedWebfingers, \ wfRequest = \
domain,projectVersion) webfingerHandle(session, handle, httpPrefix,
cachedWebfingers,
domain, projectVersion)
if not wfRequest: if not wfRequest:
if debug: if debug:
print('DEBUG: announce webfinger failed for '+handle) print('DEBUG: announce webfinger failed for ' + handle)
return 1 return 1
postToBox='outbox' postToBox = 'outbox'
# get the actor inbox for the To handle # get the actor inbox for the To handle
inboxUrl,pubKeyId,pubKey,fromPersonId,sharedInbox,capabilityAcquisition,avatarUrl,displayName= \ (inboxUrl, pubKeyId, pubKey,
getPersonBox(baseDir,session,wfRequest,personCache, \ fromPersonId, sharedInbox,
projectVersion,httpPrefix,nickname,domain,postToBox) capabilityAcquisition,
avatarUrl, displayName) = getPersonBox(baseDir, session, wfRequest,
personCache, projectVersion,
httpPrefix, nickname, domain,
postToBox)
if not inboxUrl: if not inboxUrl:
if debug: if debug:
print('DEBUG: No '+postToBox+' was found for '+handle) print('DEBUG: No ' + postToBox + ' was found for ' + handle)
return 3 return 3
if not fromPersonId: if not fromPersonId:
if debug: if debug:
print('DEBUG: No actor was found for '+handle) print('DEBUG: No actor was found for ' + handle)
return 4 return 4
authHeader=createBasicAuthHeader(Nickname,password) authHeader = createBasicAuthHeader(nickname, password)
headers={ headers = {
'host': domain, \ 'host': domain,
'Content-type': 'application/json', \ 'Content-type': 'application/json',
'Authorization': authHeader 'Authorization': authHeader
} }
postResult= \ postResult = \
postJson(session,newSkillJson,[],inboxUrl,headers,"inbox:write") postJson(session, newSkillJson, [], inboxUrl, headers, "inbox:write")
#if not postResult: if not postResult:
# if debug: if debug:
# print('DEBUG: 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 skill success') print('DEBUG: c2s POST skill success')