epicyon/person.py

1246 lines
46 KiB
Python
Raw Normal View History

2020-04-03 18:12:08 +00:00
__filename__ = "person.py"
__author__ = "Bob Mottram"
__license__ = "AGPL3+"
2021-01-26 10:07:42 +00:00
__version__ = "1.2.0"
2020-04-03 18:12:08 +00:00
__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
import pyqrcode
from random import randint
2019-07-12 14:31:56 +00:00
from pathlib import Path
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
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
2021-03-11 18:15:04 +00:00
from posts import getUserUrl
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-10-07 09:10:42 +00:00
from posts import createNewsTimeline
2020-02-24 14:39:25 +00:00
from posts import createBlogsTimeline
2020-11-27 12:29:20 +00:00
from posts import createFeaturesTimeline
2019-11-17 14:01:49 +00:00
from posts import createBookmarksTimeline
2020-08-23 11:13:35 +00:00
from posts import createEventsTimeline
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
2020-12-16 11:04:46 +00:00
from utils import getFullDomain
2019-07-27 22:48:34 +00:00
from utils import validNickname
2019-10-22 11:55:06 +00:00
from utils import loadJson
from utils import saveJson
2020-10-06 08:58:44 +00:00
from utils import setConfigParam
from utils import getConfigParam
from utils import refreshNewswire
2021-03-11 18:15:04 +00:00
from utils import getProtocolPrefixes
from utils import hasUsersPath
from session import createSession
from session import getJson
from webfinger import webfingerHandle
from pprint import pprint
2019-06-28 18:55:29 +00:00
2020-04-03 18:12:08 +00:00
def generateRSAKey() -> (str, str):
key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend()
)
privateKeyPem = key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption()
)
pubkey = key.public_key()
publicKeyPem = pubkey.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo,
)
privateKeyPem = privateKeyPem.decode("utf-8")
publicKeyPem = publicKeyPem.decode("utf-8")
2020-04-03 18:12:08 +00:00
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
2021-01-11 22:27:57 +00:00
imageFilename.endswith('.svg') or
2019-07-12 13:51:04 +00:00
imageFilename.endswith('.gif')):
2021-01-11 22:27:57 +00:00
print('Profile image must be png, jpg, gif or svg format')
2019-07-12 14:31:56 +00:00
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]
2020-12-16 11:04:46 +00:00
fullDomain = getFullDomain(domain, port)
2019-07-12 13:51:04 +00:00
2020-09-15 09:16:03 +00:00
handle = nickname + '@' + domain
2020-04-03 18:12:08 +00:00
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'
2021-01-11 22:27:57 +00:00
if imageFilename.endswith('.svg'):
mediaType = 'image/svg+xml'
iconFilename = iconFilenameBase + '.svg'
2020-04-03 18:12:08 +00:00
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]
2020-07-08 15:09:27 +00:00
# NOTE: these files don't need to have cryptographically
# secure names
2020-07-08 15:17:00 +00:00
randStr = str(randint(10000000000000, 99999999999999)) # nosec
2020-04-03 18:12:08 +00:00
personJson['icon']['url'] = \
2020-12-18 23:44:44 +00:00
personId + '/avatar' + randStr + '.' + existingExtension
2020-04-03 18:12:08 +00:00
lastPartOfFilename = personJson['image']['url'].split('/')[-1]
existingExtension = lastPartOfFilename.split('.')[1]
2020-07-08 15:17:00 +00:00
randStr = str(randint(10000000000000, 99999999999999)) # nosec
2020-04-03 18:12:08 +00:00
personJson['image']['url'] = \
2020-07-08 15:17:00 +00:00
personId + '/image' + randStr + '.' + existingExtension
2020-04-03 18:12:08 +00:00
2020-08-05 10:28:54 +00:00
def getDefaultPersonContext() -> str:
2020-08-05 10:33:47 +00:00
"""Gets the default actor context
"""
2020-08-05 10:28:54 +00:00
return {
'Curve25519Key': 'toot:Curve25519Key',
'Device': 'toot:Device',
'Ed25519Key': 'toot:Ed25519Key',
'Ed25519Signature': 'toot:Ed25519Signature',
'EncryptedMessage': 'toot:EncryptedMessage',
'IdentityProof': 'toot:IdentityProof',
'PropertyValue': 'schema:PropertyValue',
'alsoKnownAs': {'@id': 'as:alsoKnownAs', '@type': '@id'},
'cipherText': 'toot:cipherText',
'claim': {'@id': 'toot:claim', '@type': '@id'},
'deviceId': 'toot:deviceId',
'devices': {'@id': 'toot:devices', '@type': '@id'},
'discoverable': 'toot:discoverable',
'featured': {'@id': 'toot:featured', '@type': '@id'},
'featuredTags': {'@id': 'toot:featuredTags', '@type': '@id'},
2020-08-05 10:28:54 +00:00
'fingerprintKey': {'@id': 'toot:fingerprintKey', '@type': '@id'},
'focalPoint': {'@container': '@list', '@id': 'toot:focalPoint'},
'identityKey': {'@id': 'toot:identityKey', '@type': '@id'},
'manuallyApprovesFollowers': 'as:manuallyApprovesFollowers',
2020-08-05 10:28:54 +00:00
'messageFranking': 'toot:messageFranking',
'messageType': 'toot:messageType',
'movedTo': {'@id': 'as:movedTo', '@type': '@id'},
2020-12-17 22:59:11 +00:00
'publicKeyBase64': 'toot:publicKeyBase64',
'schema': 'http://schema.org#',
'suspended': 'toot:suspended',
'toot': 'http://joinmastodon.org/ns#',
'value': 'schema:value'
2020-08-05 10:28:54 +00:00
}
def _createPersonBase(baseDir: str, nickname: str, domain: str, port: int,
httpPrefix: str, saveToFile: bool,
manualFollowerApproval: 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-09-15 09:16:03 +00:00
handle = nickname + '@' + domain
2020-04-03 18:12:08 +00:00
originalDomain = domain
2020-12-16 11:04:46 +00:00
domain = getFullDomain(domain, port)
2020-04-03 18:12:08 +00:00
personType = 'Person'
2020-07-12 11:58:32 +00:00
# Enable follower approval by default
2020-07-12 12:31:28 +00:00
approveFollowers = manualFollowerApproval
2020-04-03 18:12:08 +00:00
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'
2020-10-27 16:00:57 +00:00
elif nickname == 'news':
personUrl = httpPrefix + '://' + domain + \
'/about/more?news_actor=true'
approveFollowers = True
personType = 'Application'
2020-04-03 18:12:08 +00:00
2020-07-08 15:09:27 +00:00
# NOTE: these image files don't need to have
# cryptographically secure names
2020-04-03 18:12:08 +00:00
imageUrl = \
personId + '/image' + \
2020-07-08 15:17:00 +00:00
str(randint(10000000000000, 99999999999999)) + '.png' # nosec
2020-04-03 18:12:08 +00:00
iconUrl = \
personId + '/avatar' + \
2020-07-08 15:17:00 +00:00
str(randint(10000000000000, 99999999999999)) + '.png' # nosec
2020-04-03 18:12:08 +00:00
newPerson = {
'@context': [
'https://www.w3.org/ns/activitystreams',
'https://w3id.org/security/v1',
2020-08-05 10:28:54 +00:00
getDefaultPersonContext()
2020-04-03 18:12:08 +00:00
],
2020-03-22 20:36:19 +00:00
'alsoKnownAs': [],
'attachment': [],
2020-08-05 10:28:54 +00:00
'devices': personId + '/collections/devices',
2020-03-22 20:36:19 +00:00
'endpoints': {
'id': personId + '/endpoints',
2021-03-03 09:52:38 +00:00
'sharedInbox': httpPrefix + '://' + domain + '/inbox',
2020-03-22 20:36:19 +00:00
},
'featured': personId + '/collections/featured',
'featuredTags': personId + '/collections/tags',
'followers': personId + '/followers',
'following': personId + '/following',
2021-03-03 09:52:38 +00:00
'tts': personId + '/speaker',
'shares': personId + '/shares',
2020-03-22 20:36:19 +00:00
'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,
'discoverable': True,
2020-03-22 20:36:19 +00:00
'name': personName,
'outbox': personId + '/outbox',
2020-03-22 20:36:19 +00:00
'preferredUsername': personName,
'summary': '',
'publicKey': {
'id': personId + '#main-key',
2020-03-22 20:36:19 +00:00
'owner': personId,
'publicKeyPem': publicKeyPem
},
'tag': [],
'type': personType,
'url': personUrl
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 + '/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'
2020-08-29 11:14:19 +00:00
with open(filename, 'w+') as text_file:
2019-06-28 18:55:29 +00:00
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'
2020-08-29 11:14:19 +00:00
with open(filename, 'w+') as text_file:
2019-06-28 18:55:29 +00:00
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,
2020-07-12 12:31:28 +00:00
nickname: str, password: str,
manualFollowerApproval: bool) -> bool:
2019-08-08 13:38:33 +00:00
"""Registers a new account from the web interface
"""
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,
2020-07-12 12:31:28 +00:00
manualFollowerApproval,
2020-04-03 18:12:08 +00:00
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,
2020-07-12 12:31:28 +00:00
False, password)
2020-04-03 18:12:08 +00:00
newPerson['type'] = 'Group'
return privateKeyPem, publicKeyPem, newPerson, webfingerEndpoint
def savePersonQrcode(baseDir: str,
nickname: str, domain: str, port: int,
scale=6) -> None:
"""Saves a qrcode image for the handle of the person
This helps to transfer onion or i2p handles to a mobile device
"""
qrcodeFilename = baseDir + '/accounts/' + \
nickname + '@' + domain + '/qrcode.png'
if os.path.isfile(qrcodeFilename):
return
2020-12-16 11:04:46 +00:00
handle = getFullDomain('@' + nickname + '@' + domain, port)
url = pyqrcode.create(handle)
url.png(qrcodeFilename, scale)
2020-04-03 18:12:08 +00:00
def createPerson(baseDir: str, nickname: str, domain: str, port: int,
httpPrefix: str, saveToFile: bool,
2020-07-12 12:31:28 +00:00
manualFollowerApproval: bool,
2020-04-03 18:12:08 +00:00
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-11-24 12:42:33 +00:00
if nickname != 'news':
remainingConfigExists = \
getConfigParam(baseDir, 'registrationsRemaining')
if remainingConfigExists:
registrationsRemaining = int(remainingConfigExists)
if registrationsRemaining <= 0:
return None, None, None, None
else:
if os.path.isdir(baseDir + '/accounts/news@' + domain):
# news account already exists
2020-04-03 18:12:08 +00:00
return None, None, None, None
(privateKeyPem, publicKeyPem,
newPerson, webfingerEndpoint) = _createPersonBase(baseDir, nickname,
domain, port,
httpPrefix,
saveToFile,
manualFollowerApproval,
password)
if not getConfigParam(baseDir, 'admin'):
2020-11-24 12:42:33 +00:00
if nickname != 'news':
# print(nickname+' becomes the instance admin and a moderator')
setConfigParam(baseDir, 'admin', nickname)
setRole(baseDir, nickname, domain, 'instance', 'admin')
setRole(baseDir, nickname, domain, 'instance', 'moderator')
setRole(baseDir, nickname, domain, 'instance', 'editor')
setRole(baseDir, nickname, domain, 'instance', 'delegator')
2020-04-03 18:12:08 +00:00
2020-08-29 11:14:19 +00:00
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)
2020-07-12 13:28:03 +00:00
if manualFollowerApproval:
followDMsFilename = baseDir + '/accounts/' + \
nickname + '@' + domain + '/.followDMs'
2020-08-29 11:14:19 +00:00
with open(followDMsFilename, 'w+') as fFile:
2020-07-12 13:28:03 +00:00
fFile.write('\n')
2020-08-27 09:23:21 +00:00
# notify when posts are liked
2020-11-24 12:42:33 +00:00
if nickname != 'news':
notifyLikesFilename = baseDir + '/accounts/' + \
nickname + '@' + domain + '/.notifyLikes'
with open(notifyLikesFilename, 'w+') as nFile:
nFile.write('\n')
2020-04-03 18:12:08 +00:00
theme = getConfigParam(baseDir, 'theme')
2020-11-14 12:02:12 +00:00
if not theme:
theme = 'default'
2020-11-24 12:42:33 +00:00
if nickname != 'news':
if os.path.isfile(baseDir + '/img/default-avatar.png'):
copyfile(baseDir + '/img/default-avatar.png',
baseDir + '/accounts/' + nickname + '@' + domain +
'/avatar.png')
else:
newsAvatar = baseDir + '/theme/' + theme + '/icons/avatar_news.png'
if os.path.isfile(newsAvatar):
copyfile(newsAvatar,
baseDir + '/accounts/' + nickname + '@' + domain +
'/avatar.png')
2020-11-14 12:44:24 +00:00
defaultProfileImageFilename = baseDir + '/theme/default/image.png'
if theme:
2020-11-14 12:44:24 +00:00
if os.path.isfile(baseDir + '/theme/' + theme + '/image.png'):
2020-11-24 12:19:35 +00:00
defaultProfileImageFilename = \
baseDir + '/theme/' + theme + '/image.png'
if os.path.isfile(defaultProfileImageFilename):
2020-04-03 18:12:08 +00:00
copyfile(defaultProfileImageFilename, baseDir +
'/accounts/' + nickname + '@' + domain + '/image.png')
2020-11-14 12:44:24 +00:00
defaultBannerFilename = baseDir + '/theme/default/banner.png'
if theme:
2020-11-14 12:44:24 +00:00
if os.path.isfile(baseDir + '/theme/' + theme + '/banner.png'):
defaultBannerFilename = baseDir + '/theme/' + theme + '/banner.png'
if os.path.isfile(defaultBannerFilename):
2020-04-03 18:12:08 +00:00
copyfile(defaultBannerFilename, baseDir + '/accounts/' +
nickname + '@' + domain + '/banner.png')
2020-11-24 12:42:33 +00:00
if nickname != 'news' and remainingConfigExists:
2020-04-03 18:12:08 +00:00
registrationsRemaining -= 1
setConfigParam(baseDir, 'registrationsRemaining',
str(registrationsRemaining))
savePersonQrcode(baseDir, nickname, domain, port)
2020-04-03 18:12:08 +00:00
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
"""
return _createPersonBase(baseDir, nickname, domain, port, httpPrefix,
True, True, None)
2020-04-03 18:12:08 +00:00
2020-10-07 16:01:45 +00:00
def createNewsInbox(baseDir: str, domain: str, port: int,
httpPrefix: str) -> (str, str, {}, {}):
"""Generates the news inbox
"""
2020-11-24 12:42:33 +00:00
return createPerson(baseDir, 'news', domain, port,
httpPrefix, True, True, None)
2020-10-07 16:01:45 +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:58:50 +00:00
if updateActor:
2021-03-03 09:52:38 +00:00
# add a speaker endpoint
if not personJson.get('tts'):
personJson['tts'] = personJson['id'] + '/speaker'
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',
2021-01-11 22:27:57 +00:00
'.png', '.jpg', '.gif', '.svg', '.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,
2020-10-08 19:47:23 +00:00
authorized: bool,
2020-10-09 12:15:20 +00:00
newswireVotesThreshold: int, positiveVoting: bool,
votingTimeMins: int) -> {}:
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 \
2020-10-07 09:10:42 +00:00
boxname != 'tlblogs' and boxname != 'tlnews' and \
2020-11-27 12:29:20 +00:00
boxname != 'tlfeatures' and \
2020-04-03 18:12:08 +00:00
boxname != 'outbox' and boxname != 'moderation' and \
2020-08-23 11:13:35 +00:00
boxname != 'tlbookmarks' and boxname != 'bookmarks' and \
2020-08-26 09:29:51 +00:00
boxname != 'tlevents':
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,
2020-09-27 19:27:24 +00:00
noOfItems, headerOnly, pageNumber)
2020-04-03 18:12:08 +00:00
elif boxname == 'dm':
return createDMTimeline(recentPostsCache,
session, baseDir, nickname, domain, port,
2020-04-03 18:12:08 +00:00
httpPrefix,
2020-09-27 19:27:24 +00:00
noOfItems, headerOnly, 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,
2020-09-27 19:27:24 +00:00
noOfItems, headerOnly,
2020-04-03 18:12:08 +00:00
pageNumber)
2020-08-26 09:29:51 +00:00
elif boxname == 'tlevents':
return createEventsTimeline(recentPostsCache,
session, baseDir, nickname, domain,
2020-08-23 11:13:35 +00:00
port, httpPrefix,
2020-09-27 19:27:24 +00:00
noOfItems, headerOnly,
2020-08-23 11:13:35 +00:00
pageNumber)
2020-04-03 18:12:08 +00:00
elif boxname == 'tlreplies':
return createRepliesTimeline(recentPostsCache,
session, baseDir, nickname, domain,
2020-04-03 18:12:08 +00:00
port, httpPrefix,
2020-09-27 19:27:24 +00:00
noOfItems, headerOnly,
2020-04-03 18:12:08 +00:00
pageNumber)
elif boxname == 'tlmedia':
return createMediaTimeline(session, baseDir, nickname, domain, port,
2020-09-27 19:27:24 +00:00
httpPrefix, noOfItems, headerOnly,
2020-04-03 18:12:08 +00:00
pageNumber)
2020-10-07 09:10:42 +00:00
elif boxname == 'tlnews':
return createNewsTimeline(session, baseDir, nickname, domain, port,
httpPrefix, noOfItems, headerOnly,
2020-10-08 19:47:23 +00:00
newswireVotesThreshold, positiveVoting,
2020-10-09 12:15:20 +00:00
votingTimeMins, pageNumber)
2020-11-27 12:29:20 +00:00
elif boxname == 'tlfeatures':
return createFeaturesTimeline(session, baseDir, nickname, domain, port,
httpPrefix, noOfItems, headerOnly,
pageNumber)
2020-04-03 18:12:08 +00:00
elif boxname == 'tlblogs':
return createBlogsTimeline(session, baseDir, nickname, domain, port,
2020-09-27 19:27:24 +00:00
httpPrefix, noOfItems, headerOnly,
2020-04-03 18:12:08 +00:00
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,
2020-09-28 17:11:48 +00:00
noOfItems, headerOnly,
2020-04-03 18:12:08 +00:00
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 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-09-15 09:16:03 +00:00
handle = nickname + '@' + domain
filename = baseDir + '/accounts/' + handle + '.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-09-15 09:16:03 +00:00
handle = nickname + '@' + domain
filename = baseDir + '/accounts/' + handle + '.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 reenableAccount(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')
2020-10-10 16:10:32 +00:00
if not adminNickname:
return
2020-04-03 18:12:08 +00:00
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-12-16 11:04:46 +00:00
domainFull = getFullDomain(domain, port)
# is the post by the admin?
2020-04-03 18:12:08 +00:00
adminNickname = getConfigParam(baseDir, 'admin')
2020-10-10 16:10:32 +00:00
if not adminNickname:
return False
2020-04-03 18:12:08 +00:00
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-12-16 11:04:46 +00:00
domainFull = getFullDomain(domain, port)
2020-04-03 18:12:08 +00:00
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-09-12 09:50:24 +00:00
try:
tagFilename = os.path.join(directory, filename)
except BaseException:
continue
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')
2020-10-10 16:10:32 +00:00
if not adminNickname:
return False
2020-04-03 18:12:08 +00:00
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
reenableAccount(baseDir, nickname)
2020-04-03 18:12:08 +00:00
handle = nickname + '@' + domain
removePassword(baseDir, nickname)
_removeTagsForNickname(baseDir, nickname, domain, port)
2020-04-03 18:12:08 +00:00
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)
refreshNewswire(baseDir)
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)
refreshNewswire(baseDir)
2020-04-03 18:12:08 +00:00
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
refreshNewswire(baseDir)
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-07-12 20:04:58 +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-07-12 20:04:58 +00:00
writeSnoozedFile = open(snoozedFilename, 'w+')
2019-11-06 11:39:41 +00:00
if writeSnoozedFile:
writeSnoozedFile.write(content)
writeSnoozedFile.close()
2020-08-05 21:12:09 +00:00
def setPersonNotes(baseDir: str, nickname: str, domain: str,
handle: str, notes: str) -> bool:
"""Adds notes about a person
"""
if '@' not in handle:
return False
if handle.startswith('@'):
handle = handle[1:]
2020-08-05 21:24:35 +00:00
notesDir = baseDir + '/accounts/' + \
nickname + '@' + domain + '/notes'
if not os.path.isdir(notesDir):
os.mkdir(notesDir)
2020-08-05 21:29:26 +00:00
notesFilename = notesDir + '/' + handle + '.txt'
2020-08-05 21:12:09 +00:00
with open(notesFilename, 'w+') as notesFile:
notesFile.write(notes)
return True
2021-03-11 18:15:04 +00:00
def getActorJson(handle: str, http: bool, gnunet: bool, quiet=False) -> {}:
"""Returns the actor json
"""
originalActor = handle
if '/@' in handle or \
'/users/' in handle or \
handle.startswith('http') or \
handle.startswith('dat'):
# format: https://domain/@nick
prefixes = getProtocolPrefixes()
for prefix in prefixes:
handle = handle.replace(prefix, '')
handle = handle.replace('/@', '/users/')
if not hasUsersPath(handle):
if not quiet:
print('Expected actor format: ' +
'https://domain/@nick or https://domain/users/nick')
return None
if '/users/' in handle:
nickname = handle.split('/users/')[1]
nickname = nickname.replace('\n', '').replace('\r', '')
domain = handle.split('/users/')[0]
elif '/profile/' in handle:
nickname = handle.split('/profile/')[1]
nickname = nickname.replace('\n', '').replace('\r', '')
domain = handle.split('/profile/')[0]
elif '/channel/' in handle:
nickname = handle.split('/channel/')[1]
nickname = nickname.replace('\n', '').replace('\r', '')
domain = handle.split('/channel/')[0]
elif '/accounts/' in handle:
nickname = handle.split('/accounts/')[1]
nickname = nickname.replace('\n', '').replace('\r', '')
domain = handle.split('/accounts/')[0]
elif '/u/' in handle:
nickname = handle.split('/u/')[1]
nickname = nickname.replace('\n', '').replace('\r', '')
domain = handle.split('/u/')[0]
else:
# format: @nick@domain
if '@' not in handle:
if not quiet:
print('Syntax: --actor nickname@domain')
return None
if handle.startswith('@'):
handle = handle[1:]
if '@' not in handle:
if not quiet:
print('Syntax: --actor nickname@domain')
return None
nickname = handle.split('@')[0]
domain = handle.split('@')[1]
domain = domain.replace('\n', '').replace('\r', '')
cachedWebfingers = {}
proxyType = None
if http or domain.endswith('.onion'):
httpPrefix = 'http'
proxyType = 'tor'
elif domain.endswith('.i2p'):
httpPrefix = 'http'
proxyType = 'i2p'
elif gnunet:
httpPrefix = 'gnunet'
proxyType = 'gnunet'
else:
httpPrefix = 'https'
session = createSession(proxyType)
if nickname == 'inbox':
nickname = domain
handle = nickname + '@' + domain
wfRequest = webfingerHandle(session, handle,
httpPrefix, cachedWebfingers,
None, __version__)
if not wfRequest:
if not quiet:
print('Unable to webfinger ' + handle)
return None
if not isinstance(wfRequest, dict):
if not quiet:
print('Webfinger for ' + handle + ' did not return a dict. ' +
str(wfRequest))
return None
if not quiet:
pprint(wfRequest)
personUrl = None
if wfRequest.get('errors'):
if not quiet:
print('wfRequest error: ' + str(wfRequest['errors']))
if hasUsersPath(handle):
personUrl = originalActor
else:
return None
profileStr = 'https://www.w3.org/ns/activitystreams'
asHeader = {
'Accept': 'application/activity+json; profile="' + profileStr + '"'
}
if not personUrl:
personUrl = getUserUrl(wfRequest)
if nickname == domain:
personUrl = personUrl.replace('/users/', '/actor/')
personUrl = personUrl.replace('/accounts/', '/actor/')
personUrl = personUrl.replace('/channel/', '/actor/')
personUrl = personUrl.replace('/profile/', '/actor/')
personUrl = personUrl.replace('/u/', '/actor/')
if not personUrl:
# try single user instance
personUrl = httpPrefix + '://' + domain
profileStr = 'https://www.w3.org/ns/activitystreams'
asHeader = {
'Accept': 'application/ld+json; profile="' + profileStr + '"'
}
if '/channel/' in personUrl or '/accounts/' in personUrl:
profileStr = 'https://www.w3.org/ns/activitystreams'
asHeader = {
'Accept': 'application/ld+json; profile="' + profileStr + '"'
}
personJson = \
getJson(session, personUrl, asHeader, None, __version__,
httpPrefix, None, 20, quiet)
if personJson:
if not quiet:
pprint(personJson)
else:
profileStr = 'https://www.w3.org/ns/activitystreams'
asHeader = {
'Accept': 'application/jrd+json; profile="' + profileStr + '"'
}
personJson = \
getJson(session, personUrl, asHeader, None,
__version__, httpPrefix, None)
if not quiet:
if personJson:
pprint(personJson)
else:
print('Failed to get ' + personUrl)
return personJson