epicyon/person.py

1026 lines
38 KiB
Python
Raw Normal View History

2020-04-03 18:12:08 +00:00
__filename__ = "person.py"
__author__ = "Bob Mottram"
__license__ = "AGPL3+"
__version__ = "1.1.0"
__maintainer__ = "Bob Mottram"
__email__ = "bob@freedombone.net"
__status__ = "Production"
2019-10-11 18:03:58 +00:00
import time
2019-06-28 18:55:29 +00:00
import os
2019-07-12 14:31:56 +00:00
import subprocess
2019-08-13 11:59:38 +00:00
import shutil
from random import randint
2019-07-12 14:31:56 +00:00
from pathlib import Path
2020-03-04 09:59:08 +00:00
try:
from Cryptodome.PublicKey import RSA
except ImportError:
from Crypto.PublicKey import RSA
2019-07-12 13:51:04 +00:00
from shutil import copyfile
2019-06-28 18:55:29 +00:00
from webfinger import createWebfingerEndpoint
from webfinger import storeWebfingerEndpoint
2019-08-25 16:09:56 +00:00
from posts import createDMTimeline
2019-09-23 19:53:18 +00:00
from posts import createRepliesTimeline
2019-09-28 11:40:42 +00:00
from posts import createMediaTimeline
2020-02-24 14:39:25 +00:00
from posts import createBlogsTimeline
2019-11-17 14:01:49 +00:00
from posts import createBookmarksTimeline
2019-07-25 16:50:48 +00:00
from posts import createInbox
2019-06-29 14:35:26 +00:00
from posts import createOutbox
2019-08-12 13:22:17 +00:00
from posts import createModeration
from auth import storeBasicCredentials
2019-08-13 11:59:38 +00:00
from auth import removePassword
2019-07-18 15:09:23 +00:00
from roles import setRole
from media import removeMetaData
2019-07-27 22:48:34 +00:00
from utils import validNickname
2019-08-08 11:24:26 +00:00
from utils import noOfAccounts
2019-10-22 11:55:06 +00:00
from utils import loadJson
from utils import saveJson
2019-08-08 10:50:58 +00:00
from config import setConfigParam
2020-03-22 21:16:02 +00:00
from config import getConfigParam
2019-06-28 18:55:29 +00:00
2020-04-03 18:12:08 +00:00
def generateRSAKey() -> (str, str):
key = RSA.generate(2048)
privateKeyPem = key.exportKey("PEM").decode("utf-8")
publicKeyPem = key.publickey().exportKey("PEM").decode("utf-8")
return privateKeyPem, publicKeyPem
def setProfileImage(baseDir: str, httpPrefix: str, nickname: str, domain: str,
port: int, imageFilename: str, imageType: str,
resolution: str) -> bool:
2019-07-12 13:51:04 +00:00
"""Saves the given image file as an avatar or background
image for the given person
"""
2020-05-22 11:32:38 +00:00
imageFilename = imageFilename.replace('\n', '').replace('\r', '')
2020-04-03 18:12:08 +00:00
if not (imageFilename.endswith('.png') or
imageFilename.endswith('.jpg') or
imageFilename.endswith('.jpeg') or
2019-07-12 13:51:04 +00:00
imageFilename.endswith('.gif')):
2019-07-12 14:31:56 +00:00
print('Profile image must be png, jpg or gif format')
return False
2019-07-12 13:51:04 +00:00
2019-07-12 14:31:56 +00:00
if imageFilename.startswith('~/'):
2020-04-03 18:12:08 +00:00
imageFilename = imageFilename.replace('~/', str(Path.home()) + '/')
2019-07-12 14:31:56 +00:00
if ':' in domain:
2020-04-03 18:12:08 +00:00
domain = domain.split(':')[0]
fullDomain = domain
if port:
2020-04-03 18:12:08 +00:00
if port != 80 and port != 443:
if ':' not in domain:
2020-04-03 18:12:08 +00:00
fullDomain = domain + ':' + str(port)
2019-07-12 13:51:04 +00:00
2020-04-03 18:12:08 +00:00
handle = nickname.lower() + '@' + domain.lower()
personFilename = baseDir + '/accounts/' + handle + '.json'
2019-07-12 13:51:04 +00:00
if not os.path.isfile(personFilename):
2020-04-03 18:12:08 +00:00
print('person definition not found: ' + personFilename)
2019-07-12 14:31:56 +00:00
return False
2020-04-03 18:12:08 +00:00
if not os.path.isdir(baseDir + '/accounts/' + handle):
print('Account not found: ' + baseDir + '/accounts/' + handle)
2019-07-12 14:31:56 +00:00
return False
2019-07-12 13:51:04 +00:00
2020-04-03 18:12:08 +00:00
iconFilenameBase = 'icon'
if imageType == 'avatar' or imageType == 'icon':
iconFilenameBase = 'icon'
2019-07-12 13:51:04 +00:00
else:
2020-04-03 18:12:08 +00:00
iconFilenameBase = 'image'
2020-03-22 21:16:02 +00:00
2020-04-03 18:12:08 +00:00
mediaType = 'image/png'
iconFilename = iconFilenameBase + '.png'
2019-07-12 13:51:04 +00:00
if imageFilename.endswith('.jpg') or \
imageFilename.endswith('.jpeg'):
2020-04-03 18:12:08 +00:00
mediaType = 'image/jpeg'
iconFilename = iconFilenameBase + '.jpg'
2019-07-12 13:51:04 +00:00
if imageFilename.endswith('.gif'):
2020-04-03 18:12:08 +00:00
mediaType = 'image/gif'
iconFilename = iconFilenameBase + '.gif'
profileFilename = baseDir + '/accounts/' + handle + '/' + iconFilename
2019-07-12 13:51:04 +00:00
2020-04-03 18:12:08 +00:00
personJson = loadJson(personFilename)
2019-09-30 22:39:02 +00:00
if personJson:
2020-04-03 18:12:08 +00:00
personJson[iconFilenameBase]['mediaType'] = mediaType
personJson[iconFilenameBase]['url'] = \
httpPrefix + '://' + fullDomain + '/users/' + \
nickname + '/'+iconFilename
saveJson(personJson, personFilename)
cmd = \
'/usr/bin/convert ' + imageFilename + ' -size ' + \
resolution + ' -quality 50 ' + profileFilename
2019-07-12 14:31:56 +00:00
subprocess.call(cmd, shell=True)
2020-04-03 18:12:08 +00:00
removeMetaData(profileFilename, profileFilename)
2019-07-12 14:31:56 +00:00
return True
return False
2019-07-12 13:51:04 +00:00
2020-04-03 18:12:08 +00:00
def setOrganizationScheme(baseDir: str, nickname: str, domain: str,
schema: str) -> bool:
"""Set the organization schema within which a person exists
This will define how roles, skills and availability are assembled
into organizations
"""
# avoid giant strings
2020-04-03 18:12:08 +00:00
if len(schema) > 256:
return False
2020-04-03 18:12:08 +00:00
actorFilename = baseDir + '/accounts/' + nickname + '@' + domain + '.json'
if not os.path.isfile(actorFilename):
return False
2019-09-30 22:39:02 +00:00
2020-04-03 18:12:08 +00:00
actorJson = loadJson(actorFilename)
2019-09-30 22:39:02 +00:00
if actorJson:
2020-04-03 18:12:08 +00:00
actorJson['orgSchema'] = schema
saveJson(actorJson, actorFilename)
return True
2020-04-03 18:12:08 +00:00
def accountExists(baseDir: str, nickname: str, domain: str) -> bool:
"""Returns true if the given account exists
"""
if ':' in domain:
2020-04-03 18:12:08 +00:00
domain = domain.split(':')[0]
return os.path.isdir(baseDir + '/accounts/' + nickname + '@' + domain) or \
os.path.isdir(baseDir + '/deactivated/' + nickname + '@' + domain)
def randomizeActorImages(personJson: {}) -> None:
"""Randomizes the filenames for avatar image and background
This causes other instances to update their cached avatar image
"""
2020-04-03 18:12:08 +00:00
personId = personJson['id']
lastPartOfFilename = personJson['icon']['url'].split('/')[-1]
existingExtension = lastPartOfFilename.split('.')[1]
personJson['icon']['url'] = \
personId + '/avatar' + str(randint(10000000000000, 99999999999999)) + \
'.' + existingExtension
lastPartOfFilename = personJson['image']['url'].split('/')[-1]
existingExtension = lastPartOfFilename.split('.')[1]
personJson['image']['url'] = \
personId + '/image' + str(randint(10000000000000, 99999999999999)) + \
'.' + existingExtension
def createPersonBase(baseDir: str, nickname: str, domain: str, port: int,
httpPrefix: str, saveToFile: bool,
password=None) -> (str, str, {}, {}):
2019-06-28 18:55:29 +00:00
"""Returns the private key, public key, actor and webfinger endpoint
"""
2020-04-03 18:12:08 +00:00
privateKeyPem, publicKeyPem = generateRSAKey()
webfingerEndpoint = \
createWebfingerEndpoint(nickname, domain, port,
httpPrefix, publicKeyPem)
2019-06-28 18:55:29 +00:00
if saveToFile:
2020-04-03 18:12:08 +00:00
storeWebfingerEndpoint(nickname, domain, port,
baseDir, webfingerEndpoint)
2019-06-30 18:23:18 +00:00
2020-04-03 18:12:08 +00:00
handle = nickname.lower() + '@' + domain.lower()
originalDomain = domain
if port:
2020-04-03 18:12:08 +00:00
if port != 80 and port != 443:
if ':' not in domain:
2020-04-03 18:12:08 +00:00
domain = domain + ':' + str(port)
personType = 'Person'
approveFollowers = False
personName = nickname
personId = httpPrefix + '://' + domain + '/users/' + nickname
inboxStr = personId + '/inbox'
personUrl = httpPrefix + '://' + domain + '/@' + personName
if nickname == 'inbox':
# shared inbox
2020-04-03 18:12:08 +00:00
inboxStr = httpPrefix + '://' + domain + '/actor/inbox'
personId = httpPrefix + '://' + domain + '/actor'
personUrl = httpPrefix + '://' + domain + \
'/about/more?instance_actor=true'
personName = originalDomain
approveFollowers = True
personType = 'Application'
imageUrl = \
personId + '/image' + \
str(randint(10000000000000, 99999999999999)) + '.png'
iconUrl = \
personId + '/avatar' + \
str(randint(10000000000000, 99999999999999)) + '.png'
contextDict = {
'Emoji': 'toot:Emoji',
'Hashtag': 'as:Hashtag',
'IdentityProof': 'toot:IdentityProof',
'PropertyValue': 'schema:PropertyValue',
'alsoKnownAs': {
'@id': 'as:alsoKnownAs', '@type': '@id'
},
'focalPoint': {
'@container': '@list', '@id': 'toot:focalPoint'
},
'manuallyApprovesFollowers': 'as:manuallyApprovesFollowers',
'movedTo': {
'@id': 'as:movedTo', '@type': '@id'
},
'schema': 'http://schema.org#',
'value': 'schema:value'
}
newPerson = {
'@context': [
'https://www.w3.org/ns/activitystreams',
'https://w3id.org/security/v1',
contextDict
],
2020-03-22 20:36:19 +00:00
'attachment': [],
'alsoKnownAs': [],
'discoverable': False,
'endpoints': {
'id': personId+'/endpoints',
'sharedInbox': httpPrefix+'://'+domain+'/inbox',
},
'capabilityAcquisitionEndpoint': httpPrefix+'://'+domain+'/caps/new',
'followers': personId+'/followers',
'following': personId+'/following',
'shares': personId+'/shares',
'orgSchema': None,
'skills': {},
'roles': {},
'availability': None,
'icon': {
'mediaType': 'image/png',
'type': 'Image',
2020-04-03 18:12:08 +00:00
'url': iconUrl
2020-03-22 20:36:19 +00:00
},
'id': personId,
'image': {
'mediaType': 'image/png',
'type': 'Image',
2020-04-03 18:12:08 +00:00
'url': imageUrl
2020-03-22 20:36:19 +00:00
},
'inbox': inboxStr,
'manuallyApprovesFollowers': approveFollowers,
'name': personName,
'outbox': personId+'/outbox',
'preferredUsername': personName,
'summary': '',
'publicKey': {
'id': personId+'#main-key',
'owner': personId,
'publicKeyPem': publicKeyPem
},
'tag': [],
'type': personType,
'url': personUrl,
'nomadicLocations': [{
'id': personId,
'type': 'nomadicLocation',
2020-04-03 18:12:08 +00:00
'locationAddress': 'acct:' + nickname + '@' + domain,
'locationPrimary': True,
'locationDeleted': False
2020-03-22 20:36:19 +00:00
}]
2019-06-28 18:55:29 +00:00
}
2020-04-03 18:12:08 +00:00
if nickname == 'inbox':
# fields not needed by the shared inbox
del newPerson['outbox']
del newPerson['icon']
del newPerson['image']
del newPerson['skills']
del newPerson['shares']
del newPerson['roles']
del newPerson['tag']
del newPerson['availability']
del newPerson['followers']
del newPerson['following']
del newPerson['attachment']
2019-06-28 18:55:29 +00:00
if saveToFile:
# save person to file
2020-04-03 18:12:08 +00:00
peopleSubdir = '/accounts'
if not os.path.isdir(baseDir + peopleSubdir):
os.mkdir(baseDir + peopleSubdir)
if not os.path.isdir(baseDir + peopleSubdir + '/' + handle):
os.mkdir(baseDir + peopleSubdir + '/' + handle)
if not os.path.isdir(baseDir + peopleSubdir + '/' + handle + '/inbox'):
os.mkdir(baseDir + peopleSubdir + '/' + handle + '/inbox')
if not os.path.isdir(baseDir + peopleSubdir + '/' +
handle + '/outbox'):
os.mkdir(baseDir + peopleSubdir + '/' + handle + '/outbox')
if not os.path.isdir(baseDir + peopleSubdir + '/' + handle + '/ocap'):
os.mkdir(baseDir + peopleSubdir + '/' + handle + '/ocap')
if not os.path.isdir(baseDir + peopleSubdir + '/' + handle + '/queue'):
os.mkdir(baseDir + peopleSubdir + '/' + handle + '/queue')
filename = baseDir + peopleSubdir + '/' + handle + '.json'
saveJson(newPerson, filename)
2019-06-28 18:55:29 +00:00
2019-08-22 14:43:43 +00:00
# save to cache
2020-04-03 18:12:08 +00:00
if not os.path.isdir(baseDir + '/cache'):
os.mkdir(baseDir + '/cache')
if not os.path.isdir(baseDir + '/cache/actors'):
os.mkdir(baseDir + '/cache/actors')
cacheFilename = baseDir + '/cache/actors/' + \
newPerson['id'].replace('/', '#') + '.json'
saveJson(newPerson, cacheFilename)
2019-08-22 14:43:43 +00:00
2019-06-28 18:55:29 +00:00
# save the private key
2020-04-03 18:12:08 +00:00
privateKeysSubdir = '/keys/private'
if not os.path.isdir(baseDir + '/keys'):
os.mkdir(baseDir + '/keys')
if not os.path.isdir(baseDir + privateKeysSubdir):
os.mkdir(baseDir + privateKeysSubdir)
filename = baseDir + privateKeysSubdir + '/' + handle + '.key'
2019-06-28 18:55:29 +00:00
with open(filename, "w") as text_file:
print(privateKeyPem, file=text_file)
# save the public key
2020-04-03 18:12:08 +00:00
publicKeysSubdir = '/keys/public'
if not os.path.isdir(baseDir + publicKeysSubdir):
os.mkdir(baseDir + publicKeysSubdir)
filename = baseDir + publicKeysSubdir + '/' + handle + '.pem'
2019-06-28 18:55:29 +00:00
with open(filename, "w") as text_file:
print(publicKeyPem, file=text_file)
if password:
2020-04-03 18:12:08 +00:00
storeBasicCredentials(baseDir, nickname, password)
2020-04-03 18:12:08 +00:00
return privateKeyPem, publicKeyPem, newPerson, webfingerEndpoint
2019-06-28 18:55:29 +00:00
2020-04-03 18:12:08 +00:00
def registerAccount(baseDir: str, httpPrefix: str, domain: str, port: int,
nickname: str, password: str) -> bool:
2019-08-08 13:38:33 +00:00
"""Registers a new account from the web interface
"""
2020-04-03 18:12:08 +00:00
if accountExists(baseDir, nickname, domain):
return False
2020-04-03 18:12:08 +00:00
if not validNickname(domain, nickname):
print('REGISTER: Nickname ' + nickname + ' is invalid')
2019-08-08 13:38:33 +00:00
return False
2020-04-03 18:12:08 +00:00
if len(password) < 8:
2019-08-08 13:38:33 +00:00
print('REGISTER: Password should be at least 8 characters')
return False
2020-04-03 18:12:08 +00:00
(privateKeyPem, publicKeyPem,
newPerson, webfingerEndpoint) = createPerson(baseDir, nickname,
domain, port,
httpPrefix, True,
password)
2019-08-08 13:38:33 +00:00
if privateKeyPem:
return True
return False
2020-04-03 18:12:08 +00:00
def createGroup(baseDir: str, nickname: str, domain: str, port: int,
httpPrefix: str, saveToFile: bool,
password=None) -> (str, str, {}, {}):
2019-10-04 12:39:46 +00:00
"""Returns a group
"""
2020-04-03 18:12:08 +00:00
(privateKeyPem, publicKeyPem,
newPerson, webfingerEndpoint) = createPerson(baseDir, nickname,
domain, port,
httpPrefix, saveToFile,
password)
newPerson['type'] = 'Group'
return privateKeyPem, publicKeyPem, newPerson, webfingerEndpoint
def createPerson(baseDir: str, nickname: str, domain: str, port: int,
httpPrefix: str, saveToFile: bool,
password=None) -> (str, str, {}, {}):
2019-07-05 11:27:18 +00:00
"""Returns the private key, public key, actor and webfinger endpoint
"""
2020-04-03 18:12:08 +00:00
if not validNickname(domain, nickname):
return None, None, None, None
2019-08-08 10:50:58 +00:00
2019-08-09 09:14:31 +00:00
# If a config.json file doesn't exist then don't decrement
# remaining registrations counter
2020-04-03 18:12:08 +00:00
remainingConfigExists = getConfigParam(baseDir, 'registrationsRemaining')
2019-08-09 09:13:08 +00:00
if remainingConfigExists:
2020-04-03 18:12:08 +00:00
registrationsRemaining = int(remainingConfigExists)
if registrationsRemaining <= 0:
return None, None, None, None
(privateKeyPem, publicKeyPem,
newPerson, webfingerEndpoint) = createPersonBase(baseDir, nickname,
domain, port,
httpPrefix,
saveToFile, password)
if noOfAccounts(baseDir) == 1:
# print(nickname+' becomes the instance admin and a moderator')
setRole(baseDir, nickname, domain, 'instance', 'admin')
setRole(baseDir, nickname, domain, 'instance', 'moderator')
setRole(baseDir, nickname, domain, 'instance', 'delegator')
setConfigParam(baseDir, 'admin', nickname)
if not os.path.isdir(baseDir + '/accounts'):
os.mkdir(baseDir + '/accounts')
if not os.path.isdir(baseDir + '/accounts/' + nickname + '@' + domain):
os.mkdir(baseDir + '/accounts/' + nickname + '@' + domain)
if os.path.isfile(baseDir + '/img/default-avatar.png'):
copyfile(baseDir + '/img/default-avatar.png',
baseDir + '/accounts/' + nickname + '@' + domain +
'/avatar.png')
theme = getConfigParam(baseDir, 'theme')
defaultProfileImageFilename = baseDir + '/img/image.png'
if theme:
2020-04-03 18:12:08 +00:00
if os.path.isfile(baseDir + '/img/image_' + theme + '.png'):
defaultBannerFilename = baseDir + '/img/image_' + theme + '.png'
if os.path.isfile(defaultProfileImageFilename):
2020-04-03 18:12:08 +00:00
copyfile(defaultProfileImageFilename, baseDir +
'/accounts/' + nickname + '@' + domain + '/image.png')
defaultBannerFilename = baseDir + '/img/banner.png'
if theme:
2020-04-03 18:12:08 +00:00
if os.path.isfile(baseDir + '/img/banner_' + theme + '.png'):
defaultBannerFilename = baseDir + '/img/banner_' + theme + '.png'
if os.path.isfile(defaultBannerFilename):
2020-04-03 18:12:08 +00:00
copyfile(defaultBannerFilename, baseDir + '/accounts/' +
nickname + '@' + domain + '/banner.png')
2019-08-09 09:13:08 +00:00
if remainingConfigExists:
2020-04-03 18:12:08 +00:00
registrationsRemaining -= 1
setConfigParam(baseDir, 'registrationsRemaining',
str(registrationsRemaining))
return privateKeyPem, publicKeyPem, newPerson, webfingerEndpoint
2019-07-05 11:27:18 +00:00
2020-04-03 18:12:08 +00:00
def createSharedInbox(baseDir: str, nickname: str, domain: str, port: int,
httpPrefix: str) -> (str, str, {}, {}):
2019-07-05 11:27:18 +00:00
"""Generates the shared inbox
"""
2020-04-03 18:12:08 +00:00
return createPersonBase(baseDir, nickname, domain, port, httpPrefix,
True, None)
2020-04-03 18:12:08 +00:00
def createCapabilitiesInbox(baseDir: str, nickname: str,
domain: str, port: int,
httpPrefix: str) -> (str, str, {}, {}):
"""Generates the capabilities inbox to sign requests
"""
2020-04-03 18:12:08 +00:00
return createPersonBase(baseDir, nickname, domain, port,
httpPrefix, True, None)
2020-01-19 20:29:39 +00:00
2020-04-03 18:12:08 +00:00
def personUpgradeActor(baseDir: str, personJson: {},
handle: str, filename: str) -> None:
2020-01-19 20:29:39 +00:00
"""Alter the actor to add any new properties
2020-01-19 20:43:03 +00:00
"""
2020-04-03 18:12:08 +00:00
updateActor = False
2020-01-19 20:43:03 +00:00
if not os.path.isfile(filename):
2020-04-03 18:12:08 +00:00
print('WARN: actor file not found ' + filename)
2020-01-19 20:43:03 +00:00
return
2020-03-22 21:16:02 +00:00
if not personJson:
2020-04-03 18:12:08 +00:00
personJson = loadJson(filename)
2020-01-19 20:29:39 +00:00
if not personJson.get('nomadicLocations'):
2020-04-03 18:12:08 +00:00
personJson['nomadicLocations'] = [{
2020-01-19 20:29:39 +00:00
'id': personJson['id'],
'type': 'nomadicLocation',
'locationAddress':'acct:'+handle,
'locationPrimary':True,
'locationDeleted':False
}]
2020-04-03 18:12:08 +00:00
print('Nomadic locations added to to actor ' + handle)
updateActor = True
2020-01-19 20:58:50 +00:00
if updateActor:
2020-04-03 18:12:08 +00:00
saveJson(personJson, filename)
2020-01-19 20:58:50 +00:00
# also update the actor within the cache
2020-04-03 18:12:08 +00:00
actorCacheFilename = \
baseDir + '/accounts/cache/actors/' + \
personJson['id'].replace('/', '#') + '.json'
2020-01-19 20:58:50 +00:00
if os.path.isfile(actorCacheFilename):
2020-04-03 18:12:08 +00:00
saveJson(personJson, actorCacheFilename)
2020-01-19 20:58:50 +00:00
# update domain/@nickname in actors cache
2020-04-03 18:12:08 +00:00
actorCacheFilename = \
baseDir + '/accounts/cache/actors/' + \
personJson['id'].replace('/users/', '/@').replace('/', '#') + \
'.json'
2020-01-19 20:58:50 +00:00
if os.path.isfile(actorCacheFilename):
2020-04-03 18:12:08 +00:00
saveJson(personJson, actorCacheFilename)
2020-01-19 20:29:39 +00:00
2020-04-03 18:12:08 +00:00
def personLookup(domain: str, path: str, baseDir: str) -> {}:
2019-07-03 09:40:27 +00:00
"""Lookup the person for an given nickname
2019-06-28 18:55:29 +00:00
"""
2019-07-04 18:26:37 +00:00
if path.endswith('#main-key'):
2020-04-03 18:12:08 +00:00
path = path.replace('#main-key', '')
2019-08-05 15:52:18 +00:00
# is this a shared inbox lookup?
2020-04-03 18:12:08 +00:00
isSharedInbox = False
if path == '/inbox' or path == '/users/inbox' or path == '/sharedInbox':
2019-08-23 13:47:29 +00:00
# shared inbox actor on @domain@domain
2020-04-03 18:12:08 +00:00
path = '/users/' + domain
isSharedInbox = True
2019-08-05 15:22:59 +00:00
else:
2020-04-03 18:12:08 +00:00
notPersonLookup = ('/inbox', '/outbox', '/outboxarchive',
'/followers', '/following', '/featured',
'.png', '.jpg', '.gif', '.mpv')
2020-03-22 21:16:02 +00:00
for ending in notPersonLookup:
2019-08-05 15:22:59 +00:00
if path.endswith(ending):
return None
2020-04-03 18:12:08 +00:00
nickname = None
2019-06-28 18:55:29 +00:00
if path.startswith('/users/'):
2020-04-03 18:12:08 +00:00
nickname = path.replace('/users/', '', 1)
2019-06-28 18:55:29 +00:00
if path.startswith('/@'):
2020-04-03 18:12:08 +00:00
nickname = path.replace('/@', '', 1)
2019-07-03 09:40:27 +00:00
if not nickname:
2019-06-28 18:55:29 +00:00
return None
2020-04-03 18:12:08 +00:00
if not isSharedInbox and not validNickname(domain, nickname):
2019-06-28 18:55:29 +00:00
return None
2019-07-01 21:01:43 +00:00
if ':' in domain:
2020-04-03 18:12:08 +00:00
domain = domain.split(':')[0]
handle = nickname + '@' + domain
filename = baseDir + '/accounts/' + handle + '.json'
2019-06-28 18:55:29 +00:00
if not os.path.isfile(filename):
return None
2020-04-03 18:12:08 +00:00
personJson = loadJson(filename)
personUpgradeActor(baseDir, personJson, handle, filename)
# if not personJson:
# personJson={"user": "unknown"}
2019-06-28 18:55:29 +00:00
return personJson
2019-06-29 14:35:26 +00:00
2020-04-03 18:12:08 +00:00
def personBoxJson(recentPostsCache: {},
session, baseDir: str, domain: str, port: int, path: str,
httpPrefix: str, noOfItems: int, boxname: str,
authorized: bool, ocapAlways: bool) -> {}:
2019-08-12 13:22:17 +00:00
"""Obtain the inbox/outbox/moderation feed for the given person
2019-06-29 14:35:26 +00:00
"""
2020-04-03 18:12:08 +00:00
if boxname != 'inbox' and boxname != 'dm' and \
boxname != 'tlreplies' and boxname != 'tlmedia' and \
boxname != 'tlblogs' and \
boxname != 'outbox' and boxname != 'moderation' and \
2020-05-21 19:58:21 +00:00
boxname != 'tlbookmarks' and boxname != 'bookmarks':
2019-07-04 16:24:23 +00:00
return None
2020-04-03 18:12:08 +00:00
if not '/' + boxname in path:
2019-06-29 16:47:37 +00:00
return None
2019-06-29 17:12:26 +00:00
# Only show the header by default
2020-04-03 18:12:08 +00:00
headerOnly = True
2019-06-29 17:12:26 +00:00
2019-06-29 16:47:37 +00:00
# handle page numbers
2020-04-03 18:12:08 +00:00
pageNumber = None
2019-06-29 16:47:37 +00:00
if '?page=' in path:
2020-04-03 18:12:08 +00:00
pageNumber = path.split('?page=')[1]
if pageNumber == 'true':
pageNumber = 1
2019-06-29 16:47:37 +00:00
else:
try:
2020-04-03 18:12:08 +00:00
pageNumber = int(pageNumber)
except BaseException:
2019-06-29 16:47:37 +00:00
pass
2020-04-03 18:12:08 +00:00
path = path.split('?page=')[0]
headerOnly = False
2019-06-29 16:47:37 +00:00
2020-04-03 18:12:08 +00:00
if not path.endswith('/' + boxname):
2019-06-29 15:18:35 +00:00
return None
2020-04-03 18:12:08 +00:00
nickname = None
2019-06-29 14:35:26 +00:00
if path.startswith('/users/'):
2020-04-03 18:12:08 +00:00
nickname = path.replace('/users/', '', 1).replace('/' + boxname, '')
2019-06-29 14:35:26 +00:00
if path.startswith('/@'):
2020-04-03 18:12:08 +00:00
nickname = path.replace('/@', '', 1).replace('/' + boxname, '')
2019-07-03 09:40:27 +00:00
if not nickname:
2019-06-29 15:18:35 +00:00
return None
2020-04-03 18:12:08 +00:00
if not validNickname(domain, nickname):
2019-06-29 15:18:35 +00:00
return None
2020-04-03 18:12:08 +00:00
if boxname == 'inbox':
return createInbox(recentPostsCache,
session, baseDir, nickname, domain, port,
httpPrefix,
noOfItems, headerOnly, ocapAlways, pageNumber)
elif boxname == 'dm':
return createDMTimeline(session, baseDir, nickname, domain, port,
httpPrefix,
noOfItems, headerOnly, ocapAlways, pageNumber)
2020-05-21 19:58:21 +00:00
elif boxname == 'tlbookmarks' or boxname == 'bookmarks':
2020-04-03 18:12:08 +00:00
return createBookmarksTimeline(session, baseDir, nickname, domain,
port, httpPrefix,
noOfItems, headerOnly, ocapAlways,
pageNumber)
elif boxname == 'tlreplies':
return createRepliesTimeline(session, baseDir, nickname, domain,
port, httpPrefix,
noOfItems, headerOnly, ocapAlways,
pageNumber)
elif boxname == 'tlmedia':
return createMediaTimeline(session, baseDir, nickname, domain, port,
httpPrefix,
noOfItems, headerOnly, ocapAlways,
pageNumber)
elif boxname == 'tlblogs':
return createBlogsTimeline(session, baseDir, nickname, domain, port,
httpPrefix,
noOfItems, headerOnly, ocapAlways,
pageNumber)
elif boxname == 'outbox':
return createOutbox(session, baseDir, nickname, domain, port,
httpPrefix,
noOfItems, headerOnly, authorized,
pageNumber)
elif boxname == 'moderation':
return createModeration(baseDir, nickname, domain, port,
httpPrefix,
noOfItems, headerOnly, authorized,
pageNumber)
2019-08-12 13:22:17 +00:00
return None
2019-06-29 14:35:26 +00:00
2020-04-03 18:12:08 +00:00
def personInboxJson(recentPostsCache: {},
baseDir: str, domain: str, port: int, path: str,
httpPrefix: str, noOfItems: int, ocapAlways: bool) -> []:
2019-07-04 16:24:23 +00:00
"""Obtain the inbox feed for the given person
Authentication is expected to have already happened
"""
2020-04-03 18:12:08 +00:00
if '/inbox' not in path:
2019-07-04 16:24:23 +00:00
return None
# Only show the header by default
2020-04-03 18:12:08 +00:00
headerOnly = True
2019-07-04 16:24:23 +00:00
# handle page numbers
2020-04-03 18:12:08 +00:00
pageNumber = None
2019-07-04 16:24:23 +00:00
if '?page=' in path:
2020-04-03 18:12:08 +00:00
pageNumber = path.split('?page=')[1]
if pageNumber == 'true':
pageNumber = 1
2019-07-04 16:24:23 +00:00
else:
try:
2020-04-03 18:12:08 +00:00
pageNumber = int(pageNumber)
except BaseException:
2019-07-04 16:24:23 +00:00
pass
2020-04-03 18:12:08 +00:00
path = path.split('?page=')[0]
headerOnly = False
2019-07-04 16:24:23 +00:00
if not path.endswith('/inbox'):
return None
2020-04-03 18:12:08 +00:00
nickname = None
2019-07-04 16:24:23 +00:00
if path.startswith('/users/'):
2020-04-03 18:12:08 +00:00
nickname = path.replace('/users/', '', 1).replace('/inbox', '')
2019-07-04 16:24:23 +00:00
if path.startswith('/@'):
2020-04-03 18:12:08 +00:00
nickname = path.replace('/@', '', 1).replace('/inbox', '')
2019-07-04 16:24:23 +00:00
if not nickname:
return None
2020-04-03 18:12:08 +00:00
if not validNickname(domain, nickname):
2019-07-04 16:24:23 +00:00
return None
2020-04-03 18:12:08 +00:00
return createInbox(recentPostsCache, baseDir, nickname,
domain, port, httpPrefix,
noOfItems, headerOnly, ocapAlways, pageNumber)
2019-07-04 16:24:23 +00:00
2020-04-03 18:12:08 +00:00
def setDisplayNickname(baseDir: str, nickname: str, domain: str,
displayName: str) -> bool:
2020-04-03 18:12:08 +00:00
if len(displayName) > 32:
2019-06-28 18:55:29 +00:00
return False
2020-04-03 18:12:08 +00:00
handle = nickname.lower() + '@' + domain.lower()
filename = baseDir + '/accounts/' + handle.lower() + '.json'
2019-06-28 18:55:29 +00:00
if not os.path.isfile(filename):
return False
2019-09-30 22:39:02 +00:00
2020-04-03 18:12:08 +00:00
personJson = loadJson(filename)
2019-06-28 18:55:29 +00:00
if not personJson:
return False
2020-04-03 18:12:08 +00:00
personJson['name'] = displayName
saveJson(personJson, filename)
2019-06-28 18:55:29 +00:00
return True
2019-06-28 20:00:25 +00:00
2020-04-03 18:12:08 +00:00
def setBio(baseDir: str, nickname: str, domain: str, bio: str) -> bool:
if len(bio) > 32:
2019-06-28 20:00:25 +00:00
return False
2020-04-03 18:12:08 +00:00
handle = nickname.lower() + '@' + domain.lower()
filename = baseDir + '/accounts/' + handle.lower() + '.json'
2019-06-28 20:00:25 +00:00
if not os.path.isfile(filename):
return False
2019-09-30 22:39:02 +00:00
2020-04-03 18:12:08 +00:00
personJson = loadJson(filename)
2019-06-28 20:00:25 +00:00
if not personJson:
return False
2019-07-31 12:44:08 +00:00
if not personJson.get('summary'):
2019-06-28 20:00:25 +00:00
return False
2020-04-03 18:12:08 +00:00
personJson['summary'] = bio
2019-09-30 22:39:02 +00:00
2020-04-03 18:12:08 +00:00
saveJson(personJson, filename)
2019-06-28 20:00:25 +00:00
return True
2019-08-13 09:24:55 +00:00
2020-04-03 18:12:08 +00:00
def isSuspended(baseDir: str, nickname: str) -> bool:
2019-08-13 09:24:55 +00:00
"""Returns true if the given nickname is suspended
"""
2020-04-03 18:12:08 +00:00
adminNickname = getConfigParam(baseDir, 'admin')
if nickname == adminNickname:
2019-08-13 09:24:55 +00:00
return False
2020-04-03 18:12:08 +00:00
suspendedFilename = baseDir + '/accounts/suspended.txt'
2019-08-13 09:24:55 +00:00
if os.path.isfile(suspendedFilename):
with open(suspendedFilename, "r") as f:
2020-04-03 18:12:08 +00:00
lines = f.readlines()
2019-08-13 09:24:55 +00:00
for suspended in lines:
2020-05-22 11:32:38 +00:00
if suspended.strip('\n').strip('\r') == nickname:
2019-08-13 09:24:55 +00:00
return True
return False
2020-04-03 18:12:08 +00:00
def unsuspendAccount(baseDir: str, nickname: str) -> None:
2019-08-13 09:24:55 +00:00
"""Removes an account suspention
"""
2020-04-03 18:12:08 +00:00
suspendedFilename = baseDir + '/accounts/suspended.txt'
2019-08-13 09:24:55 +00:00
if os.path.isfile(suspendedFilename):
with open(suspendedFilename, "r") as f:
2020-04-03 18:12:08 +00:00
lines = f.readlines()
suspendedFile = open(suspendedFilename, "w+")
2019-08-13 09:24:55 +00:00
for suspended in lines:
2020-05-22 11:32:38 +00:00
if suspended.strip('\n').strip('\r') != nickname:
2019-08-13 09:24:55 +00:00
suspendedFile.write(suspended)
suspendedFile.close()
2020-04-03 18:12:08 +00:00
def suspendAccount(baseDir: str, nickname: str, domain: str) -> None:
2019-08-13 09:24:55 +00:00
"""Suspends the given account
"""
# Don't suspend the admin
2020-04-03 18:12:08 +00:00
adminNickname = getConfigParam(baseDir, 'admin')
if nickname == adminNickname:
2019-08-13 09:24:55 +00:00
return
# Don't suspend moderators
2020-04-03 18:12:08 +00:00
moderatorsFile = baseDir + '/accounts/moderators.txt'
2019-08-13 09:24:55 +00:00
if os.path.isfile(moderatorsFile):
with open(moderatorsFile, "r") as f:
2020-04-03 18:12:08 +00:00
lines = f.readlines()
2019-08-13 09:24:55 +00:00
for moderator in lines:
2020-05-22 11:32:38 +00:00
if moderator.strip('\n').strip('\r') == nickname:
2019-08-13 09:24:55 +00:00
return
2020-04-03 18:12:08 +00:00
saltFilename = baseDir + '/accounts/' + \
nickname + '@' + domain + '/.salt'
if os.path.isfile(saltFilename):
os.remove(saltFilename)
2020-04-03 18:12:08 +00:00
tokenFilename = baseDir + '/accounts/' + \
nickname + '@' + domain + '/.token'
if os.path.isfile(tokenFilename):
os.remove(tokenFilename)
2020-03-22 21:16:02 +00:00
2020-04-03 18:12:08 +00:00
suspendedFilename = baseDir + '/accounts/suspended.txt'
2019-08-13 09:24:55 +00:00
if os.path.isfile(suspendedFilename):
with open(suspendedFilename, "r") as f:
2020-04-03 18:12:08 +00:00
lines = f.readlines()
2019-08-13 09:24:55 +00:00
for suspended in lines:
2020-05-22 11:32:38 +00:00
if suspended.strip('\n').strip('\r') == nickname:
2019-08-13 09:24:55 +00:00
return
2020-04-03 18:12:08 +00:00
suspendedFile = open(suspendedFilename, 'a+')
2019-08-13 09:24:55 +00:00
if suspendedFile:
2020-04-03 18:12:08 +00:00
suspendedFile.write(nickname + '\n')
2019-08-13 09:24:55 +00:00
suspendedFile.close()
else:
2020-04-03 18:12:08 +00:00
suspendedFile = open(suspendedFilename, 'w+')
2019-08-13 09:24:55 +00:00
if suspendedFile:
2020-04-03 18:12:08 +00:00
suspendedFile.write(nickname + '\n')
2019-08-13 09:24:55 +00:00
suspendedFile.close()
2019-08-13 11:59:38 +00:00
2020-04-03 18:12:08 +00:00
def canRemovePost(baseDir: str, nickname: str,
domain: str, port: int, postId: str) -> bool:
"""Returns true if the given post can be removed
"""
if '/statuses/' not in postId:
return False
2020-04-03 18:12:08 +00:00
domainFull = domain
if port:
2020-04-03 18:12:08 +00:00
if port != 80 and port != 443:
if ':' not in domain:
2020-04-03 18:12:08 +00:00
domainFull = domain + ':' + str(port)
# is the post by the admin?
2020-04-03 18:12:08 +00:00
adminNickname = getConfigParam(baseDir, 'admin')
if domainFull + '/users/' + adminNickname + '/' in postId:
return False
# is the post by a moderator?
2020-04-03 18:12:08 +00:00
moderatorsFile = baseDir + '/accounts/moderators.txt'
if os.path.isfile(moderatorsFile):
with open(moderatorsFile, "r") as f:
2020-04-03 18:12:08 +00:00
lines = f.readlines()
for moderator in lines:
2020-04-03 18:12:08 +00:00
if domainFull + '/users/' + moderator.strip('\n') + '/' in postId:
return False
return True
2020-04-03 18:12:08 +00:00
def removeTagsForNickname(baseDir: str, nickname: str,
domain: str, port: int) -> None:
2019-08-13 12:14:11 +00:00
"""Removes tags for a nickname
"""
2020-04-03 18:12:08 +00:00
if not os.path.isdir(baseDir + '/tags'):
2019-08-13 12:14:11 +00:00
return
2020-04-03 18:12:08 +00:00
domainFull = domain
2019-08-13 12:14:11 +00:00
if port:
2020-04-03 18:12:08 +00:00
if port != 80 and port != 443:
if ':' not in domain:
2020-04-03 18:12:08 +00:00
domainFull = domain + ':' + str(port)
matchStr = domainFull + '/users/' + nickname + '/'
directory = os.fsencode(baseDir + '/tags/')
2019-09-27 12:09:04 +00:00
for f in os.scandir(directory):
2020-04-03 18:12:08 +00:00
f = f.name
filename = os.fsdecode(f)
2019-08-13 12:14:11 +00:00
if not filename.endswith(".txt"):
continue
2020-04-03 18:12:08 +00:00
tagFilename = os.path.join(directory, filename)
2019-11-27 09:51:59 +00:00
if not os.path.isfile(tagFilename):
continue
2019-08-13 12:14:11 +00:00
if matchStr not in open(tagFilename).read():
continue
with open(tagFilename, "r") as f:
2020-04-03 18:12:08 +00:00
lines = f.readlines()
tagFile = open(tagFilename, "w+")
2019-08-13 12:14:11 +00:00
if tagFile:
for tagline in lines:
if matchStr not in tagline:
tagFile.write(tagline)
2020-03-22 21:16:02 +00:00
tagFile.close()
2019-08-13 12:14:11 +00:00
2020-04-03 18:12:08 +00:00
def removeAccount(baseDir: str, nickname: str,
domain: str, port: int) -> bool:
2019-08-13 11:59:38 +00:00
"""Removes an account
2020-03-22 21:16:02 +00:00
"""
2019-08-13 12:00:17 +00:00
# Don't remove the admin
2020-04-03 18:12:08 +00:00
adminNickname = getConfigParam(baseDir, 'admin')
if nickname == adminNickname:
2019-08-13 11:59:38 +00:00
return False
2019-08-13 12:00:17 +00:00
# Don't remove moderators
2020-04-03 18:12:08 +00:00
moderatorsFile = baseDir + '/accounts/moderators.txt'
2019-08-13 11:59:38 +00:00
if os.path.isfile(moderatorsFile):
with open(moderatorsFile, "r") as f:
2020-04-03 18:12:08 +00:00
lines = f.readlines()
2019-08-13 11:59:38 +00:00
for moderator in lines:
2020-04-03 18:12:08 +00:00
if moderator.strip('\n') == nickname:
2019-08-13 11:59:38 +00:00
return False
2020-04-03 18:12:08 +00:00
unsuspendAccount(baseDir, nickname)
handle = nickname + '@' + domain
removePassword(baseDir, nickname)
removeTagsForNickname(baseDir, nickname, domain, port)
if os.path.isdir(baseDir + '/deactivated/' + handle):
shutil.rmtree(baseDir + '/deactivated/' + handle)
if os.path.isdir(baseDir + '/accounts/' + handle):
shutil.rmtree(baseDir + '/accounts/' + handle)
if os.path.isfile(baseDir + '/accounts/' + handle + '.json'):
os.remove(baseDir + '/accounts/' + handle + '.json')
if os.path.isfile(baseDir + '/wfendpoints/' + handle + '.json'):
os.remove(baseDir + '/wfendpoints/' + handle + '.json')
if os.path.isfile(baseDir + '/keys/private/' + handle + '.key'):
os.remove(baseDir + '/keys/private/' + handle + '.key')
if os.path.isfile(baseDir + '/keys/public/' + handle + '.pem'):
os.remove(baseDir + '/keys/public/' + handle + '.pem')
if os.path.isdir(baseDir + '/sharefiles/' + nickname):
shutil.rmtree(baseDir + '/sharefiles/' + nickname)
if os.path.isfile(baseDir + '/wfdeactivated/' + handle + '.json'):
os.remove(baseDir + '/wfdeactivated/' + handle + '.json')
if os.path.isdir(baseDir + '/sharefilesdeactivated/' + nickname):
shutil.rmtree(baseDir + '/sharefilesdeactivated/' + nickname)
2019-08-13 11:59:38 +00:00
return True
2020-04-03 18:12:08 +00:00
def deactivateAccount(baseDir: str, nickname: str, domain: str) -> bool:
"""Makes an account temporarily unavailable
"""
2020-04-03 18:12:08 +00:00
handle = nickname + '@' + domain
2019-11-05 12:07:18 +00:00
2020-04-03 18:12:08 +00:00
accountDir = baseDir + '/accounts/' + handle
if not os.path.isdir(accountDir):
2019-11-05 10:37:37 +00:00
return False
2020-04-03 18:12:08 +00:00
deactivatedDir = baseDir + '/deactivated'
if not os.path.isdir(deactivatedDir):
os.mkdir(deactivatedDir)
2020-04-03 18:12:08 +00:00
shutil.move(accountDir, deactivatedDir + '/' + handle)
2019-11-05 12:07:18 +00:00
2020-04-03 18:12:08 +00:00
if os.path.isfile(baseDir + '/wfendpoints/' + handle + '.json'):
deactivatedWebfingerDir = baseDir + '/wfdeactivated'
2019-11-05 12:07:18 +00:00
if not os.path.isdir(deactivatedWebfingerDir):
os.mkdir(deactivatedWebfingerDir)
2020-04-03 18:12:08 +00:00
shutil.move(baseDir + '/wfendpoints/' + handle + '.json',
deactivatedWebfingerDir + '/' + handle + '.json')
2019-11-05 12:07:18 +00:00
2020-04-03 18:12:08 +00:00
if os.path.isdir(baseDir + '/sharefiles/' + nickname):
deactivatedSharefilesDir = baseDir + '/sharefilesdeactivated'
2019-11-05 12:07:18 +00:00
if not os.path.isdir(deactivatedSharefilesDir):
os.mkdir(deactivatedSharefilesDir)
2020-04-03 18:12:08 +00:00
shutil.move(baseDir + '/sharefiles/' + nickname,
deactivatedSharefilesDir + '/' + nickname)
return os.path.isdir(deactivatedDir + '/' + nickname + '@' + domain)
2020-04-03 18:12:08 +00:00
def activateAccount(baseDir: str, nickname: str, domain: str) -> None:
"""Makes a deactivated account available
"""
2020-04-03 18:12:08 +00:00
handle = nickname + '@' + domain
2019-11-05 12:07:18 +00:00
2020-04-03 18:12:08 +00:00
deactivatedDir = baseDir + '/deactivated'
deactivatedAccountDir = deactivatedDir + '/' + handle
2019-11-05 12:07:18 +00:00
if os.path.isdir(deactivatedAccountDir):
2020-04-03 18:12:08 +00:00
accountDir = baseDir + '/accounts/' + handle
2019-11-05 12:07:18 +00:00
if not os.path.isdir(accountDir):
2020-04-03 18:12:08 +00:00
shutil.move(deactivatedAccountDir, accountDir)
deactivatedWebfingerDir = baseDir + '/wfdeactivated'
if os.path.isfile(deactivatedWebfingerDir + '/' + handle + '.json'):
shutil.move(deactivatedWebfingerDir + '/' + handle + '.json',
baseDir + '/wfendpoints/' + handle + '.json')
2019-11-05 12:07:18 +00:00
2020-04-03 18:12:08 +00:00
deactivatedSharefilesDir = baseDir + '/sharefilesdeactivated'
if os.path.isdir(deactivatedSharefilesDir + '/' + nickname):
if not os.path.isdir(baseDir + '/sharefiles/' + nickname):
shutil.move(deactivatedSharefilesDir + '/' + nickname,
baseDir + '/sharefiles/' + nickname)
2019-11-05 12:07:18 +00:00
2019-11-06 11:39:41 +00:00
2020-04-03 18:12:08 +00:00
def isPersonSnoozed(baseDir: str, nickname: str, domain: str,
snoozeActor: str) -> bool:
2019-11-06 11:39:41 +00:00
"""Returns true if the given actor is snoozed
"""
2020-04-03 18:12:08 +00:00
snoozedFilename = baseDir + '/accounts/' + \
nickname + '@' + domain + '/snoozed.txt'
2019-11-06 11:39:41 +00:00
if not os.path.isfile(snoozedFilename):
return False
2020-04-03 18:12:08 +00:00
if snoozeActor + ' ' not in open(snoozedFilename).read():
2019-11-06 11:39:41 +00:00
return False
# remove the snooze entry if it has timed out
2020-04-03 18:12:08 +00:00
replaceStr = None
2019-11-06 11:39:41 +00:00
with open(snoozedFilename, 'r') as snoozedFile:
for line in snoozedFile:
# is this the entry for the actor?
2020-04-03 18:12:08 +00:00
if line.startswith(snoozeActor + ' '):
2020-05-22 11:32:38 +00:00
snoozedTimeStr = \
line.split(' ')[1].replace('\n', '').replace('\r', '')
2019-11-06 11:39:41 +00:00
# is there a time appended?
if snoozedTimeStr.isdigit():
2020-04-03 18:12:08 +00:00
snoozedTime = int(snoozedTimeStr)
currTime = int(time.time())
2019-11-06 11:39:41 +00:00
# has the snooze timed out?
2020-04-03 18:12:08 +00:00
if int(currTime - snoozedTime) > 60 * 60 * 24:
replaceStr = line
2019-11-06 11:39:41 +00:00
else:
2020-04-03 18:12:08 +00:00
replaceStr = line
2019-11-06 11:39:41 +00:00
break
if replaceStr:
2020-04-03 18:12:08 +00:00
content = None
2019-11-06 11:39:41 +00:00
with open(snoozedFilename, 'r') as snoozedFile:
2020-04-03 18:12:08 +00:00
content = snoozedFile.read().replace(replaceStr, '')
2019-11-06 11:39:41 +00:00
if content:
2020-04-03 18:12:08 +00:00
writeSnoozedFile = open(snoozedFilename, 'w')
2019-11-06 11:39:41 +00:00
if writeSnoozedFile:
writeSnoozedFile.write(content)
writeSnoozedFile.close()
2020-04-03 18:12:08 +00:00
if snoozeActor + ' ' in open(snoozedFilename).read():
2019-11-06 11:39:41 +00:00
return True
return False
2020-04-03 18:12:08 +00:00
def personSnooze(baseDir: str, nickname: str, domain: str,
snoozeActor: str) -> None:
2019-11-06 11:39:41 +00:00
"""Temporarily ignores the given actor
"""
2020-04-03 18:12:08 +00:00
accountDir = baseDir + '/accounts/' + nickname + '@' + domain
2019-11-06 11:39:41 +00:00
if not os.path.isdir(accountDir):
2020-04-03 18:12:08 +00:00
print('ERROR: unknown account ' + accountDir)
2019-11-06 11:39:41 +00:00
return
2020-04-03 18:12:08 +00:00
snoozedFilename = accountDir + '/snoozed.txt'
2019-11-06 11:57:43 +00:00
if os.path.isfile(snoozedFilename):
2020-04-03 18:12:08 +00:00
if snoozeActor + ' ' in open(snoozedFilename).read():
2019-11-06 11:57:43 +00:00
return
2020-04-03 18:12:08 +00:00
snoozedFile = open(snoozedFilename, "a+")
2019-11-06 11:39:41 +00:00
if snoozedFile:
2020-04-03 18:12:08 +00:00
snoozedFile.write(snoozeActor + ' ' +
str(int(time.time())) + '\n')
2019-11-06 11:39:41 +00:00
snoozedFile.close()
2020-04-03 18:12:08 +00:00
def personUnsnooze(baseDir: str, nickname: str, domain: str,
snoozeActor: str) -> None:
2019-11-06 11:39:41 +00:00
"""Undoes a temporarily ignore of the given actor
"""
2020-04-03 18:12:08 +00:00
accountDir = baseDir + '/accounts/' + nickname + '@' + domain
2019-11-06 11:39:41 +00:00
if not os.path.isdir(accountDir):
2020-04-03 18:12:08 +00:00
print('ERROR: unknown account ' + accountDir)
2019-11-06 11:39:41 +00:00
return
2020-04-03 18:12:08 +00:00
snoozedFilename = accountDir + '/snoozed.txt'
2019-11-06 11:39:41 +00:00
if not os.path.isfile(snoozedFilename):
return
2020-04-03 18:12:08 +00:00
if snoozeActor + ' ' not in open(snoozedFilename).read():
2019-11-06 11:39:41 +00:00
return
2020-04-03 18:12:08 +00:00
replaceStr = None
2019-11-06 11:39:41 +00:00
with open(snoozedFilename, 'r') as snoozedFile:
for line in snoozedFile:
2020-04-03 18:12:08 +00:00
if line.startswith(snoozeActor + ' '):
replaceStr = line
2019-11-06 11:39:41 +00:00
break
if replaceStr:
2020-04-03 18:12:08 +00:00
content = None
2019-11-06 11:39:41 +00:00
with open(snoozedFilename, 'r') as snoozedFile:
2020-04-03 18:12:08 +00:00
content = snoozedFile.read().replace(replaceStr, '')
2019-11-06 11:39:41 +00:00
if content:
2020-04-03 18:12:08 +00:00
writeSnoozedFile = open(snoozedFilename, 'w')
2019-11-06 11:39:41 +00:00
if writeSnoozedFile:
writeSnoozedFile.write(content)
writeSnoozedFile.close()