diff --git a/acceptreject.py b/acceptreject.py index fe88202ed..e61b6d558 100644 --- a/acceptreject.py +++ b/acceptreject.py @@ -16,6 +16,7 @@ from utils import getNicknameFromActor from utils import domainPermitted from utils import followPerson from utils import hasObjectDict +from utils import acctDir def _createAcceptReject(baseDir: str, federationList: [], @@ -147,8 +148,8 @@ def _acceptFollow(baseDir: str, domain: str, messageJson: {}, acceptedDomainFull = acceptedDomain + ':' + str(acceptedPort) # has this person already been unfollowed? - unfollowedFilename = baseDir + '/accounts/' + \ - nickname + '@' + acceptedDomainFull + '/unfollowed.txt' + unfollowedFilename = \ + acctDir(baseDir, nickname, acceptedDomainFull) + '/unfollowed.txt' if os.path.isfile(unfollowedFilename): if followedNickname + '@' + followedDomainFull in \ open(unfollowedFilename).read(): diff --git a/auth.py b/auth.py index 02db756c6..5103365f3 100644 --- a/auth.py +++ b/auth.py @@ -202,7 +202,7 @@ def authorize(baseDir: str, path: str, authHeader: str, debug: bool) -> bool: return False -def createPassword(length=10): +def createPassword(length: int = 10): validChars = 'abcdefghijklmnopqrstuvwxyz' + \ 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' return ''.join((secrets.choice(validChars) for i in range(length))) diff --git a/availability.py b/availability.py index 32e63481b..ce7f01d11 100644 --- a/availability.py +++ b/availability.py @@ -17,6 +17,7 @@ from utils import getNicknameFromActor from utils import getDomainFromActor from utils import loadJson from utils import saveJson +from utils import acctDir def setAvailability(baseDir: str, nickname: str, domain: str, @@ -26,7 +27,7 @@ def setAvailability(baseDir: str, nickname: str, domain: str, # avoid giant strings if len(status) > 128: return False - actorFilename = baseDir + '/accounts/' + nickname + '@' + domain + '.json' + actorFilename = acctDir(baseDir, nickname, domain) + '.json' if not os.path.isfile(actorFilename): return False actorJson = loadJson(actorFilename) @@ -39,7 +40,7 @@ def setAvailability(baseDir: str, nickname: str, domain: str, def getAvailability(baseDir: str, nickname: str, domain: str) -> str: """Returns the availability for a given person """ - actorFilename = baseDir + '/accounts/' + nickname + '@' + domain + '.json' + actorFilename = acctDir(baseDir, nickname, domain) + '.json' if not os.path.isfile(actorFilename): return False actorJson = loadJson(actorFilename) diff --git a/blocking.py b/blocking.py index c26b07728..6988bc310 100644 --- a/blocking.py +++ b/blocking.py @@ -27,6 +27,7 @@ from utils import locatePost from utils import evilIncarnate from utils import getDomainFromActor from utils import getNicknameFromActor +from utils import acctDir def addGlobalBlock(baseDir: str, @@ -60,8 +61,7 @@ def addBlock(baseDir: str, nickname: str, domain: str, """Block the given account """ domain = removeDomainPort(domain) - blockingFilename = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/blocking.txt' + blockingFilename = acctDir(baseDir, nickname, domain) + '/blocking.txt' blockHandle = blockNickname + '@' + blockDomain if os.path.isfile(blockingFilename): if blockHandle in open(blockingFilename).read(): @@ -112,8 +112,7 @@ def removeBlock(baseDir: str, nickname: str, domain: str, """Unblock the given account """ domain = removeDomainPort(domain) - unblockingFilename = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/blocking.txt' + unblockingFilename = acctDir(baseDir, nickname, domain) + '/blocking.txt' unblockHandle = unblockNickname + '@' + unblockDomain if os.path.isfile(unblockingFilename): if unblockHandle in open(unblockingFilename).read(): @@ -287,7 +286,7 @@ def isBlocked(baseDir: str, nickname: str, domain: str, return True # account level allow list - accountDir = baseDir + '/accounts/' + nickname + '@' + domain + accountDir = acctDir(baseDir, nickname, domain) allowFilename = accountDir + '/allowedinstances.txt' if os.path.isfile(allowFilename): if blockDomain not in open(allowFilename).read(): @@ -741,7 +740,7 @@ def setBrochMode(baseDir: str, domainFull: str, enabled: bool) -> None: setConfigParam(baseDir, "brochMode", enabled) -def brochModeLapses(baseDir: str, lapseDays=7) -> bool: +def brochModeLapses(baseDir: str, lapseDays: int = 7) -> bool: """After broch mode is enabled it automatically elapses after a period of time """ diff --git a/blog.py b/blog.py index 45c71dd79..7823ae3b0 100644 --- a/blog.py +++ b/blog.py @@ -27,6 +27,7 @@ from utils import locatePost from utils import loadJson from utils import firstParagraphFromString from utils import getActorPropertyUrl +from utils import acctDir from posts import createBlogsTimeline from newswire import rss2Header from newswire import rss2Footer @@ -46,8 +47,8 @@ def _noOfBlogReplies(baseDir: str, httpPrefix: str, translate: {}, tryPostBox = ('tlblogs', 'inbox', 'outbox') boxFound = False for postBox in tryPostBox: - postFilename = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/' + postBox + '/' + \ + postFilename = \ + acctDir(baseDir, nickname, domain) + '/' + postBox + '/' + \ postId.replace('/', '#') + '.replies' if os.path.isfile(postFilename): boxFound = True @@ -55,8 +56,8 @@ def _noOfBlogReplies(baseDir: str, httpPrefix: str, translate: {}, if not boxFound: # post may exist but has no replies for postBox in tryPostBox: - postFilename = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/' + postBox + '/' + \ + postFilename = \ + acctDir(baseDir, nickname, domain) + '/' + postBox + '/' + \ postId.replace('/', '#') if os.path.isfile(postFilename): return 1 @@ -106,8 +107,8 @@ def _getBlogReplies(baseDir: str, httpPrefix: str, translate: {}, tryPostBox = ('tlblogs', 'inbox', 'outbox') boxFound = False for postBox in tryPostBox: - postFilename = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/' + postBox + '/' + \ + postFilename = \ + acctDir(baseDir, nickname, domain) + '/' + postBox + '/' + \ postId.replace('/', '#') + '.replies' if os.path.isfile(postFilename): boxFound = True @@ -115,12 +116,11 @@ def _getBlogReplies(baseDir: str, httpPrefix: str, translate: {}, if not boxFound: # post may exist but has no replies for postBox in tryPostBox: - postFilename = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/' + postBox + '/' + \ + postFilename = \ + acctDir(baseDir, nickname, domain) + '/' + postBox + '/' + \ postId.replace('/', '#') + '.json' if os.path.isfile(postFilename): - postFilename = baseDir + '/accounts/' + \ - nickname + '@' + domain + \ + postFilename = acctDir(baseDir, nickname, domain) + \ '/postcache/' + \ postId.replace('/', '#') + '.html' if os.path.isfile(postFilename): @@ -135,8 +135,7 @@ def _getBlogReplies(baseDir: str, httpPrefix: str, translate: {}, replyPostId = replyPostId.replace('\n', '').replace('\r', '') replyPostId = replyPostId.replace('.json', '') replyPostId = replyPostId.replace('.replies', '') - postFilename = baseDir + '/accounts/' + \ - nickname + '@' + domain + \ + postFilename = acctDir(baseDir, nickname, domain) + \ '/postcache/' + \ replyPostId.replace('/', '#') + '.html' if not os.path.isfile(postFilename): @@ -469,8 +468,7 @@ def htmlBlogPage(authorized: bool, session, blogStr = htmlHeaderWithExternalStyle(cssFilename, instanceTitle) _htmlBlogRemoveCwButton(blogStr, translate) - blogsIndex = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/tlblogs.index' + blogsIndex = acctDir(baseDir, nickname, domain) + '/tlblogs.index' if not os.path.isfile(blogsIndex): return blogStr + htmlFooter() @@ -558,8 +556,7 @@ def htmlBlogPageRSS2(authorized: bool, session, blogRSS2 = rss2Header(httpPrefix, nickname, domainFull, 'Blog', translate) - blogsIndex = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/tlblogs.index' + blogsIndex = acctDir(baseDir, nickname, domain) + '/tlblogs.index' if not os.path.isfile(blogsIndex): if includeHeader: return blogRSS2 + rss2Footer() @@ -610,8 +607,7 @@ def htmlBlogPageRSS3(authorized: bool, session, blogRSS3 = '' - blogsIndex = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/tlblogs.index' + blogsIndex = acctDir(baseDir, nickname, domain) + '/tlblogs.index' if not os.path.isfile(blogsIndex): return blogRSS3 @@ -876,8 +872,7 @@ def pathContainsBlogLink(baseDir: str, if not userEnding2[1].isdigit(): return None, None # check for blog posts - blogIndexFilename = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/tlblogs.index' + blogIndexFilename = acctDir(baseDir, nickname, domain) + '/tlblogs.index' if not os.path.isfile(blogIndexFilename): return None, None if '#' + userEnding2[1] + '.' not in open(blogIndexFilename).read(): diff --git a/bookmarks.py b/bookmarks.py index 5cee25bc1..cc27e1aba 100644 --- a/bookmarks.py +++ b/bookmarks.py @@ -24,6 +24,7 @@ from utils import getCachedPostFilename from utils import loadJson from utils import saveJson from utils import hasObjectDict +from utils import acctDir from posts import getPersonBox from session import postJson @@ -49,8 +50,8 @@ def undoBookmarksCollectionEntry(recentPostsCache: {}, removePostFromCache(postJsonObject, recentPostsCache) # remove from the index - bookmarksIndexFilename = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/bookmarks.index' + bookmarksIndexFilename = \ + acctDir(baseDir, nickname, domain) + '/bookmarks.index' if not os.path.isfile(bookmarksIndexFilename): return if '/' in postFilename: @@ -198,8 +199,8 @@ def updateBookmarksCollection(recentPostsCache: {}, saveJson(postJsonObject, postFilename) # prepend to the index - bookmarksIndexFilename = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/bookmarks.index' + bookmarksIndexFilename = \ + acctDir(baseDir, nickname, domain) + '/bookmarks.index' bookmarkIndex = postFilename.split('/')[-1] if os.path.isfile(bookmarksIndexFilename): if bookmarkIndex not in open(bookmarksIndexFilename).read(): diff --git a/city.py b/city.py index 4fa0049e4..161ef9b5a 100644 --- a/city.py +++ b/city.py @@ -12,6 +12,7 @@ import datetime import random import math from random import randint +from utils import acctDir # states which the simulated city dweller can be in PERSON_SLEEP = 0 @@ -291,8 +292,7 @@ def getSpoofedCity(city: str, baseDir: str, nickname: str, domain: str) -> str: """Returns the name of the city to use as a GPS spoofing location for image metadata """ - cityFilename = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/city.txt' + cityFilename = acctDir(baseDir, nickname, domain) + '/city.txt' if os.path.isfile(cityFilename): with open(cityFilename, 'r') as fp: city = fp.read().replace('\n', '') diff --git a/content.py b/content.py index ff384c7f8..3f3b1d8ec 100644 --- a/content.py +++ b/content.py @@ -20,6 +20,7 @@ from utils import getLinkPrefixes from utils import dangerousMarkup from utils import isPGPEncrypted from utils import containsPGPPublicKey +from utils import acctDir from petnames import getPetName @@ -210,8 +211,8 @@ def switchWords(baseDir: str, nickname: str, domain: str, content: str, return content if not rules: - switchWordsFilename = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/replacewords.txt' + switchWordsFilename = \ + acctDir(baseDir, nickname, domain) + '/replacewords.txt' if not os.path.isfile(switchWordsFilename): return content with open(switchWordsFilename, 'r') as fp: @@ -705,8 +706,7 @@ def _loadAutoTags(baseDir: str, nickname: str, domain: str) -> []: """Loads automatic tags file and returns a list containing the lines of the file """ - filename = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/autotags.txt' + filename = acctDir(baseDir, nickname, domain) + '/autotags.txt' if not os.path.isfile(filename): return [] with open(filename, 'r') as f: @@ -775,8 +775,7 @@ def addHtmlTags(baseDir: str, httpPrefix: str, emojiDict = {} originalDomain = domain domain = removeDomainPort(domain) - followingFilename = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/following.txt' + followingFilename = acctDir(baseDir, nickname, domain) + '/following.txt' # read the following list so that we can detect just @nick # in addition to @nick@domain diff --git a/daemon.py b/daemon.py index d7cc9ed55..4f247e267 100644 --- a/daemon.py +++ b/daemon.py @@ -208,6 +208,7 @@ from shares import addShare from shares import removeShare from shares import expireShares from categories import setHashtagCategory +from utils import acctDir from utils import getImageExtensionFromMimeType from utils import getImageMimeType from utils import hasObjectDict @@ -378,8 +379,9 @@ class PubServer(BaseHTTPRequestHandler): answer: str) -> None: """Sends a reply to a question """ - votesFilename = self.server.baseDir + '/accounts/' + \ - nickname + '@' + self.server.domain + '/questions.txt' + votesFilename = \ + acctDir(self.server.baseDir, nickname, self.server.domain) + \ + '/questions.txt' if os.path.isfile(votesFilename): # have we already voted on this? @@ -1545,8 +1547,7 @@ class PubServer(BaseHTTPRequestHandler): # This produces a deterministic token based # on nick+password+salt saltFilename = \ - baseDir + '/accounts/' + \ - loginNickname + '@' + domain + '/.salt' + acctDir(baseDir, loginNickname, domain) + '/.salt' salt = createPassword(32) if os.path.isfile(saltFilename): try: @@ -1885,8 +1886,7 @@ class PubServer(BaseHTTPRequestHandler): if saveKeys: accessKeysFilename = \ - baseDir + '/accounts/' + nickname + '@' + domain + \ - '/accessKeys.json' + acctDir(baseDir, nickname, domain) + '/accessKeys.json' saveJson(accessKeys, accessKeysFilename) if not self.server.keyShortcuts.get(nickname): self.server.keyShortcuts[nickname] = accessKeys.copy() @@ -2134,8 +2134,8 @@ class PubServer(BaseHTTPRequestHandler): postsToNews = optionsConfirmParams.split('postsToNews=')[1] if '&' in postsToNews: postsToNews = postsToNews.split('&')[0] - accountDir = self.server.baseDir + '/accounts/' + \ - optionsNickname + '@' + optionsDomain + accountDir = acctDir(self.server.baseDir, + optionsNickname, optionsDomain) newswireBlockedFilename = accountDir + '/.nonewswire' if postsToNews == 'on': if os.path.isfile(newswireBlockedFilename): @@ -2169,8 +2169,8 @@ class PubServer(BaseHTTPRequestHandler): optionsConfirmParams.split('postsToFeatures=')[1] if '&' in postsToFeatures: postsToFeatures = postsToFeatures.split('&')[0] - accountDir = self.server.baseDir + '/accounts/' + \ - optionsNickname + '@' + optionsDomain + accountDir = acctDir(self.server.baseDir, + optionsNickname, optionsDomain) featuresBlockedFilename = accountDir + '/.nofeatures' if postsToFeatures == 'on': if os.path.isfile(featuresBlockedFilename): @@ -2204,8 +2204,8 @@ class PubServer(BaseHTTPRequestHandler): optionsConfirmParams.split('modNewsPosts=')[1] if '&' in modPostsToNews: modPostsToNews = modPostsToNews.split('&')[0] - accountDir = self.server.baseDir + '/accounts/' + \ - optionsNickname + '@' + optionsDomain + accountDir = acctDir(self.server.baseDir, + optionsNickname, optionsDomain) newswireModFilename = accountDir + '/.newswiremoderated' if modPostsToNews != 'on': if os.path.isfile(newswireModFilename): @@ -3218,9 +3218,7 @@ class PubServer(BaseHTTPRequestHandler): self.server.POSTbusy = False return self.postFromNickname = pathUsersSection.split('/')[0] - accountsDir = \ - baseDir + '/accounts/' + \ - self.postFromNickname + '@' + domain + accountsDir = acctDir(baseDir, self.postFromNickname, domain) if not os.path.isdir(accountsDir): self._404() self.server.POSTbusy = False @@ -3744,8 +3742,7 @@ class PubServer(BaseHTTPRequestHandler): nickname = getNicknameFromActor(actorStr) citationsFilename = \ - baseDir + '/accounts/' + \ - nickname + '@' + domain + '/.citations.txt' + acctDir(baseDir, nickname, domain) + '/.citations.txt' # remove any existing citations file if os.path.isfile(citationsFilename): os.remove(citationsFilename) @@ -4051,8 +4048,7 @@ class PubServer(BaseHTTPRequestHandler): os.remove(filenameBase) else: filenameBase = \ - baseDir + '/accounts/' + \ - nickname + '@' + domain + \ + acctDir(baseDir, nickname, domain) + \ '/' + mType + '.temp' filename, attachmentMediaType = \ @@ -4148,8 +4144,7 @@ class PubServer(BaseHTTPRequestHandler): # load the json for the actor for this user actorFilename = \ - baseDir + '/accounts/' + \ - nickname + '@' + domain + '.json' + acctDir(baseDir, nickname, domain) + '.json' if os.path.isfile(actorFilename): actorJson = loadJson(actorFilename) if actorJson: @@ -4240,8 +4235,8 @@ class PubServer(BaseHTTPRequestHandler): # change city if fields.get('cityDropdown'): - cityFilename = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/city.txt' + cityFilename = \ + acctDir(baseDir, nickname, domain) + '/city.txt' with open(cityFilename, 'w+') as fp: fp.write(fields['cityDropdown']) @@ -5015,8 +5010,7 @@ class PubServer(BaseHTTPRequestHandler): # only receive DMs from accounts you follow followDMsFilename = \ - baseDir + '/accounts/' + \ - nickname + '@' + domain + '/.followDMs' + acctDir(baseDir, nickname, domain) + '/.followDMs' if onFinalWelcomeScreen: # initial default setting created via # the welcome screen @@ -5036,8 +5030,7 @@ class PubServer(BaseHTTPRequestHandler): # remove Twitter retweets removeTwitterFilename = \ - baseDir + '/accounts/' + \ - nickname + '@' + domain + \ + acctDir(baseDir, nickname, domain) + \ '/.removeTwitter' removeTwitterActive = False if fields.get('removeTwitter'): @@ -5052,12 +5045,10 @@ class PubServer(BaseHTTPRequestHandler): # hide Like button hideLikeButtonFile = \ - baseDir + '/accounts/' + \ - nickname + '@' + domain + \ + acctDir(baseDir, nickname, domain) + \ '/.hideLikeButton' notifyLikesFilename = \ - baseDir + '/accounts/' + \ - nickname + '@' + domain + \ + acctDir(baseDir, nickname, domain) + \ '/.notifyLikes' hideLikeButtonActive = False if fields.get('hideLikeButton'): @@ -5123,8 +5114,7 @@ class PubServer(BaseHTTPRequestHandler): # save filtered words list filterFilename = \ - baseDir + '/accounts/' + \ - nickname + '@' + domain + \ + acctDir(baseDir, nickname, domain) + \ '/filters.txt' if fields.get('filteredWords'): with open(filterFilename, 'w+') as filterfile: @@ -5135,8 +5125,7 @@ class PubServer(BaseHTTPRequestHandler): # word replacements switchFilename = \ - baseDir + '/accounts/' + \ - nickname + '@' + domain + \ + acctDir(baseDir, nickname, domain) + \ '/replacewords.txt' if fields.get('switchWords'): with open(switchFilename, 'w+') as switchfile: @@ -5147,8 +5136,7 @@ class PubServer(BaseHTTPRequestHandler): # autogenerated tags autoTagsFilename = \ - baseDir + '/accounts/' + \ - nickname + '@' + domain + \ + acctDir(baseDir, nickname, domain) + \ '/autotags.txt' if fields.get('autoTags'): with open(autoTagsFilename, 'w+') as autoTagsFile: @@ -5159,8 +5147,7 @@ class PubServer(BaseHTTPRequestHandler): # autogenerated content warnings autoCWFilename = \ - baseDir + '/accounts/' + \ - nickname + '@' + domain + \ + acctDir(baseDir, nickname, domain) + \ '/autocw.txt' if fields.get('autoCW'): with open(autoCWFilename, 'w+') as autoCWFile: @@ -5171,8 +5158,7 @@ class PubServer(BaseHTTPRequestHandler): # save blocked accounts list blockedFilename = \ - baseDir + '/accounts/' + \ - nickname + '@' + domain + \ + acctDir(baseDir, nickname, domain) + \ '/blocking.txt' if fields.get('blocked'): with open(blockedFilename, 'w+') as blockedfile: @@ -5185,8 +5171,8 @@ class PubServer(BaseHTTPRequestHandler): # The allow list for incoming DMs, # if the .followDMs flag file exists dmAllowedInstancesFilename = \ - baseDir + '/accounts/' + \ - nickname + '@' + domain + '/dmAllowedinstances.txt' + acctDir(baseDir, nickname, domain) + \ + '/dmAllowedinstances.txt' if fields.get('dmAllowedInstances'): with open(dmAllowedInstancesFilename, 'w+') as aFile: aFile.write(fields['dmAllowedInstances']) @@ -5197,8 +5183,8 @@ class PubServer(BaseHTTPRequestHandler): # save allowed instances list # This is the account level allow list allowedInstancesFilename = \ - baseDir + '/accounts/' + \ - nickname + '@' + domain + '/allowedinstances.txt' + acctDir(baseDir, nickname, domain) + \ + '/allowedinstances.txt' if fields.get('allowedInstances'): with open(allowedInstancesFilename, 'w+') as aFile: aFile.write(fields['allowedInstances']) @@ -5254,8 +5240,7 @@ class PubServer(BaseHTTPRequestHandler): # save git project names list gitProjectsFilename = \ - baseDir + '/accounts/' + \ - nickname + '@' + domain + \ + acctDir(baseDir, nickname, domain) + \ '/gitprojects.txt' if fields.get('gitProjects'): with open(gitProjectsFilename, 'w+') as aFile: @@ -5506,7 +5491,7 @@ class PubServer(BaseHTTPRequestHandler): if '/' in nickname: nickname = nickname.split('/')[0] speakerFilename = \ - baseDir + '/accounts/' + nickname + '@' + domain + '/speaker.json' + acctDir(baseDir, nickname, domain) + '/speaker.json' if not os.path.isfile(speakerFilename): self._404() return @@ -5607,8 +5592,8 @@ class PubServer(BaseHTTPRequestHandler): if '/' in nickname: nickname = nickname.split('/')[0] if not nickname.startswith('rss.'): - if os.path.isdir(self.server.baseDir + - '/accounts/' + nickname + '@' + domain): + accountDir = acctDir(self.server.baseDir, nickname, domain) + if os.path.isdir(accountDir): if not self.server.session: print('Starting new session during RSS request') self.server.session = \ @@ -5793,8 +5778,8 @@ class PubServer(BaseHTTPRequestHandler): if '/' in nickname: nickname = nickname.split('/')[0] if not nickname.startswith('rss.'): - if os.path.isdir(baseDir + - '/accounts/' + nickname + '@' + domain): + accountDir = acctDir(baseDir, nickname, domain) + if os.path.isdir(accountDir): if not self.server.session: print('Starting new session during RSS3 request') self.server.session = \ @@ -7265,7 +7250,7 @@ class PubServer(BaseHTTPRequestHandler): boxname = 'outbox' # get the replies file postDir = \ - baseDir + '/accounts/' + nickname + '@' + domain + '/' + boxname + acctDir(baseDir, nickname, domain) + '/' + boxname postRepliesFilename = \ postDir + '/' + \ httpPrefix + ':##' + domainFull + '#users#' + \ @@ -7465,8 +7450,7 @@ class PubServer(BaseHTTPRequestHandler): postSections = namedStatus.split('/') nickname = postSections[0] - actorFilename = \ - baseDir + '/accounts/' + nickname + '@' + domain + '.json' + actorFilename = acctDir(baseDir, nickname, domain) + '.json' if not os.path.isfile(actorFilename): return False @@ -7562,9 +7546,7 @@ class PubServer(BaseHTTPRequestHandler): if '/' in namedStatus: postSections = namedStatus.split('/') nickname = postSections[0] - actorFilename = \ - baseDir + '/accounts/' + \ - nickname + '@' + domain + '.json' + actorFilename = acctDir(baseDir, nickname, domain) + '.json' if os.path.isfile(actorFilename): actorJson = loadJson(actorFilename) if actorJson: @@ -7691,7 +7673,7 @@ class PubServer(BaseHTTPRequestHandler): return False postFilename = \ - baseDir + '/accounts/' + nickname + '@' + domain + '/outbox/' + \ + acctDir(baseDir, nickname, domain) + '/outbox/' + \ httpPrefix + ':##' + domainFull + '#users#' + nickname + \ '#statuses#' + statusNumber + '.json' @@ -7809,7 +7791,7 @@ class PubServer(BaseHTTPRequestHandler): return False postFilename = \ - baseDir + '/accounts/' + nickname + '@' + domain + '/outbox/' + \ + acctDir(baseDir, nickname, domain) + '/outbox/' + \ httpPrefix + ':##' + domainFull + '#users#' + nickname + \ '#statuses#' + statusNumber + '.json' @@ -9868,7 +9850,7 @@ class PubServer(BaseHTTPRequestHandler): nickname = getNicknameFromActor(path) savePersonQrcode(baseDir, nickname, domain, port) qrFilename = \ - baseDir + '/accounts/' + nickname + '@' + domain + '/qrcode.png' + acctDir(baseDir, nickname, domain) + '/qrcode.png' if os.path.isfile(qrFilename): if self._etag_exists(qrFilename): # The file has not changed @@ -9906,8 +9888,7 @@ class PubServer(BaseHTTPRequestHandler): """ nickname = getNicknameFromActor(path) bannerFilename = \ - baseDir + '/accounts/' + \ - nickname + '@' + domain + '/search_banner.png' + acctDir(baseDir, nickname, domain) + '/search_banner.png' if os.path.isfile(bannerFilename): if self._etag_exists(bannerFilename): # The file has not changed @@ -9949,8 +9930,7 @@ class PubServer(BaseHTTPRequestHandler): self._404() return True bannerFilename = \ - baseDir + '/accounts/' + \ - nickname + '@' + domain + '/' + side + '_col_image.png' + acctDir(baseDir, nickname, domain) + '/' + side + '_col_image.png' if os.path.isfile(bannerFilename): if self._etag_exists(bannerFilename): # The file has not changed @@ -10099,8 +10079,7 @@ class PubServer(BaseHTTPRequestHandler): elif avatarFile.startswith('right_col_image'): avatarFile = 'right_col_image.' + avatarFileExt avatarFilename = \ - baseDir + '/accounts/' + \ - avatarNickname + '@' + domain + '/' + avatarFile + acctDir(baseDir, avatarNickname, domain) + '/' + avatarFile if not os.path.isfile(avatarFilename): return False if self._etag_exists(avatarFilename): @@ -11071,8 +11050,8 @@ class PubServer(BaseHTTPRequestHandler): self.path.endswith('/followingaccounts'): nickname = getNicknameFromActor(self.path) followingFilename = \ - self.server.baseDir + '/accounts/' + \ - nickname + '@' + self.server.domain + '/following.txt' + acctDir(self.server.baseDir, + nickname, self.server.domain) + '/following.txt' if not os.path.isfile(followingFilename): self._404() return @@ -12966,8 +12945,8 @@ class PubServer(BaseHTTPRequestHandler): # Note: a .temp extension is used here so that at no time is # an image with metadata publicly exposed, even for a few mS filenameBase = \ - self.server.baseDir + '/accounts/' + \ - nickname + '@' + self.server.domain + '/upload.temp' + acctDir(self.server.baseDir, + nickname, self.server.domain) + '/upload.temp' filename, attachmentMediaType = \ saveMediaInFormPOST(mediaBytes, self.server.debug, @@ -13061,8 +13040,8 @@ class PubServer(BaseHTTPRequestHandler): # since epoch when an attempt to post something was made. # This is then used for active monthly users counts lastUsedFilename = \ - self.server.baseDir + '/accounts/' + \ - nickname + '@' + self.server.domain + '/.lastUsed' + acctDir(self.server.baseDir, + nickname, self.server.domain) + '/.lastUsed' try: with open(lastUsedFilename, 'w+') as lastUsedFile: lastUsedFile.write(str(int(time.time()))) @@ -13203,8 +13182,8 @@ class PubServer(BaseHTTPRequestHandler): postJsonObject = loadJson(postFilename) if postJsonObject: cachedFilename = \ - self.server.baseDir + '/accounts/' + \ - nickname + '@' + self.server.domain + \ + acctDir(self.server.baseDir, + nickname, self.server.domain) + \ '/postcache/' + \ fields['postUrl'].replace('/', '#') + '.html' if os.path.isfile(cachedFilename): diff --git a/desktop_client.py b/desktop_client.py index 9cf3d799f..0e2b0bd85 100644 --- a/desktop_client.py +++ b/desktop_client.py @@ -340,7 +340,7 @@ def _speakerPicospeaker(pitch: int, rate: int, systemLanguage: str, os.system(speakerCmd) -def _playNotificationSound(soundFilename: str, player='ffplay') -> None: +def _playNotificationSound(soundFilename: str, player: str = 'ffplay') -> None: """Plays a sound """ if not os.path.isfile(soundFilename): diff --git a/devices.py b/devices.py index 0ec994cd5..b2fb09707 100644 --- a/devices.py +++ b/devices.py @@ -33,13 +33,14 @@ __module_group__ = "Security" import os from utils import loadJson from utils import saveJson +from utils import acctDir def E2EEremoveDevice(baseDir: str, nickname: str, domain: str, deviceId: str) -> bool: """Unregisters a device for e2ee """ - personDir = baseDir + '/accounts/' + nickname + '@' + domain + personDir = acctDir(baseDir, nickname, domain) deviceFilename = personDir + '/devices/' + deviceId + '.json' if os.path.isfile(deviceFilename): os.remove(deviceFilename) @@ -111,7 +112,7 @@ def E2EEaddDevice(baseDir: str, nickname: str, domain: str, '?' in deviceId or '#' in deviceId or \ '.' in deviceId: return False - personDir = baseDir + '/accounts/' + nickname + '@' + domain + personDir = acctDir(baseDir, nickname, domain) if not os.path.isdir(personDir): return False if not os.path.isdir(personDir + '/devices'): @@ -138,7 +139,7 @@ def E2EEdevicesCollection(baseDir: str, nickname: str, domain: str, domainFull: str, httpPrefix: str) -> {}: """Returns a list of registered devices """ - personDir = baseDir + '/accounts/' + nickname + '@' + domain + personDir = acctDir(baseDir, nickname, domain) if not os.path.isdir(personDir): return {} personId = httpPrefix + '://' + domainFull + '/users/' + nickname diff --git a/epicyon.py b/epicyon.py index 3d6fe6d1b..0fc7f86d6 100644 --- a/epicyon.py +++ b/epicyon.py @@ -72,6 +72,7 @@ from utils import getNicknameFromActor from utils import followPerson from utils import validNickname from utils import getProtocolPrefixes +from utils import acctDir from media import archiveMedia from media import getAttachmentMediaType from delete import sendDeleteViaServer @@ -1040,7 +1041,7 @@ if args.followerspending: print('Specify a nickname with the --nickname option') sys.exit() - accountsDir = baseDir + '/accounts/' + args.nickname + '@' + domain + accountsDir = acctDir(baseDir, args.nickname, domain) approveFollowsFilename = accountsDir + '/followrequests.txt' approveCtr = 0 if os.path.isfile(approveFollowsFilename): @@ -1788,7 +1789,8 @@ if args.addaccount: if len(args.password.strip()) < 8: print('Password should be at least 8 characters') sys.exit() - if os.path.isdir(baseDir + '/accounts/' + nickname + '@' + domain): + accountDir = acctDir(baseDir, nickname, domain) + if os.path.isdir(accountDir): print('Account already exists') sys.exit() if os.path.isdir(baseDir + '/deactivated/' + nickname + '@' + domain): @@ -1800,7 +1802,7 @@ if args.addaccount: httpPrefix = 'http' createPerson(baseDir, nickname, domain, port, httpPrefix, True, not args.noapproval, args.password.strip()) - if os.path.isdir(baseDir + '/accounts/' + nickname + '@' + domain): + if os.path.isdir(accountDir): print('Account created for ' + nickname + '@' + domain) else: print('Account creation failed') @@ -1827,12 +1829,13 @@ if args.addgroup: if len(args.password.strip()) < 8: print('Password should be at least 8 characters') sys.exit() - if os.path.isdir(baseDir + '/accounts/' + nickname + '@' + domain): + accountDir = acctDir(baseDir, nickname, domain) + if os.path.isdir(accountDir): print('Group already exists') sys.exit() createGroup(baseDir, nickname, domain, port, httpPrefix, True, args.password.strip()) - if os.path.isdir(baseDir + '/accounts/' + nickname + '@' + domain): + if os.path.isdir(accountDir): print('Group created for ' + nickname + '@' + domain) else: print('Group creation failed') @@ -1910,7 +1913,8 @@ if args.changepassword: if len(newPassword) < 8: print('Password should be at least 8 characters') sys.exit() - if not os.path.isdir(baseDir + '/accounts/' + nickname + '@' + domain): + accountDir = acctDir(baseDir, nickname, domain) + if not os.path.isdir(accountDir): print('Account ' + nickname + '@' + domain + ' not found') sys.exit() passwordFile = baseDir + '/accounts/passwords' diff --git a/filters.py b/filters.py index fef1ed171..581f75eb0 100644 --- a/filters.py +++ b/filters.py @@ -8,13 +8,13 @@ __status__ = "Production" __module_group__ = "Moderation" import os +from utils import acctDir def addFilter(baseDir: str, nickname: str, domain: str, words: str) -> bool: """Adds a filter for particular words within the content of a incoming posts """ - filtersFilename = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/filters.txt' + filtersFilename = acctDir(baseDir, nickname, domain) + '/filters.txt' if os.path.isfile(filtersFilename): if words in open(filtersFilename).read(): return False @@ -44,8 +44,7 @@ def removeFilter(baseDir: str, nickname: str, domain: str, words: str) -> bool: """Removes a word filter """ - filtersFilename = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/filters.txt' + filtersFilename = acctDir(baseDir, nickname, domain) + '/filters.txt' if not os.path.isfile(filtersFilename): return False if words not in open(filtersFilename).read(): @@ -134,12 +133,11 @@ def isFiltered(baseDir: str, nickname: str, domain: str, content: str) -> bool: return False # optionally remove retweets - removeTwitter = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/.removeTwitter' + removeTwitter = acctDir(baseDir, nickname, domain) + '/.removeTwitter' if os.path.isfile(removeTwitter): if _isTwitterPost(content): return True - accountFiltersFilename = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/filters.txt' + accountFiltersFilename = \ + acctDir(baseDir, nickname, domain) + '/filters.txt' return _isFilteredBase(accountFiltersFilename, content) diff --git a/follow.py b/follow.py index 9389a55e1..2654989e4 100644 --- a/follow.py +++ b/follow.py @@ -27,6 +27,7 @@ from utils import loadJson from utils import saveJson from utils import isAccountDir from utils import getUserPaths +from utils import acctDir from acceptreject import createAccept from acceptreject import createReject from webfinger import webfingerHandle @@ -207,8 +208,7 @@ def isFollowerOfPerson(baseDir: str, nickname: str, domain: str, """is the given nickname a follower of followerNickname? """ domain = removeDomainPort(domain) - followersFile = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/followers.txt' + followersFile = acctDir(baseDir, nickname, domain) + '/followers.txt' if not os.path.isfile(followersFile): return False handle = followerNickname + '@' + followerDomain @@ -806,8 +806,8 @@ def followedAccountAccepts(session, baseDir: str, httpPrefix: str, if removeFollowActivity: # remove the follow request json followActivityfilename = \ - baseDir + '/accounts/' + \ - nicknameToFollow + '@' + domainToFollow + '/requests/' + \ + acctDir(baseDir, nicknameToFollow, domainToFollow) + \ + '/requests/' + \ nickname + '@' + domain + '.follow' if os.path.isfile(followActivityfilename): try: @@ -844,8 +844,7 @@ def followedAccountRejects(session, baseDir: str, httpPrefix: str, # get the json for the original follow request followActivityfilename = \ - baseDir + '/accounts/' + \ - nicknameToFollow + '@' + domainToFollow + '/requests/' + \ + acctDir(baseDir, nicknameToFollow, domainToFollow) + '/requests/' + \ nickname + '@' + domain + '.follow' followJson = loadJson(followActivityfilename) if not followJson: @@ -1433,7 +1432,7 @@ def followerApprovalActive(baseDir: str, nickname: str, domain: str) -> bool: """Returns true if the given account requires follower approval """ manuallyApprovesFollowers = False - actorFilename = baseDir + '/accounts/' + nickname + '@' + domain + '.json' + actorFilename = acctDir(baseDir, nickname, domain) + '.json' if os.path.isfile(actorFilename): actorJson = loadJson(actorFilename) if actorJson: diff --git a/followingCalendar.py b/followingCalendar.py index af38b10b0..9f038899e 100644 --- a/followingCalendar.py +++ b/followingCalendar.py @@ -10,6 +10,9 @@ __module_group__ = "Calendar" import os +def _dirAcct(baseDir: str, nickname: str, domain: str) -> str: + return baseDir + '/accounts/' + nickname + '@' + domain + def _portDomainRemove(domain: str) -> str: """If the domain has a port appended then remove it eg. mydomain.com:80 becomes mydomain.com @@ -31,12 +34,12 @@ def receivingCalendarEvents(baseDir: str, nickname: str, domain: str, if followingNickname == nickname and followingDomain == domain: # reminder post return True - calendarFilename = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/followingCalendar.txt' + calendarFilename = \ + _dirAcct(baseDir, nickname, domain) + '/followingCalendar.txt' handle = followingNickname + '@' + followingDomain if not os.path.isfile(calendarFilename): - followingFilename = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/following.txt' + followingFilename = \ + _dirAcct(baseDir, nickname, domain) + '/following.txt' if not os.path.isfile(followingFilename): return False # create a new calendar file from the following file @@ -56,8 +59,7 @@ def _receiveCalendarEvents(baseDir: str, nickname: str, domain: str, """ # check that a following file exists domain = _portDomainRemove(domain) - followingFilename = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/following.txt' + followingFilename = _dirAcct(baseDir, nickname, domain) + '/following.txt' if not os.path.isfile(followingFilename): print("WARN: following.txt doesn't exist for " + nickname + '@' + domain) @@ -69,8 +71,8 @@ def _receiveCalendarEvents(baseDir: str, nickname: str, domain: str, print('WARN: ' + handle + ' is not in ' + followingFilename) return - calendarFilename = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/followingCalendar.txt' + calendarFilename = \ + _dirAcct(baseDir, nickname, domain) + '/followingCalendar.txt' # get the contents of the calendar file, which is # a set of handles diff --git a/git.py b/git.py index d198d4c93..7556d4840 100644 --- a/git.py +++ b/git.py @@ -10,6 +10,7 @@ __module_group__ = "Profile Metadata" import os import html from utils import hasObjectDict +from utils import acctDir def _gitFormatContent(content: str) -> str: @@ -32,7 +33,7 @@ def _getGitProjectName(baseDir: str, nickname: str, domain: str, holder wants to receive """ gitProjectsFilename = \ - baseDir + '/accounts/' + nickname + '@' + domain + '/gitprojects.txt' + acctDir(baseDir, nickname, domain) + '/gitprojects.txt' if not os.path.isfile(gitProjectsFilename): return None subjectLineWords = subject.lower().split(' ') @@ -186,9 +187,7 @@ def receiveGitPatch(baseDir: str, nickname: str, domain: str, patchLines = patchStr.split('\n') patchFilename = None projectDir = None - patchesDir = \ - baseDir + '/accounts/' + nickname + '@' + domain + \ - '/patches' + patchesDir = acctDir(baseDir, nickname, domain) + '/patches' # get the subject line and turn it into a filename for line in patchLines: if line.startswith('Subject:'): @@ -213,8 +212,7 @@ def receiveGitPatch(baseDir: str, nickname: str, domain: str, with open(patchFilename, 'w+') as patchFile: patchFile.write(patchStr) patchNotifyFilename = \ - baseDir + '/accounts/' + \ - nickname + '@' + domain + '/.newPatchContent' + acctDir(baseDir, nickname, domain) + '/.newPatchContent' with open(patchNotifyFilename, 'w+') as patchFile: patchFile.write(patchStr) return True diff --git a/happening.py b/happening.py index 25ff7ff67..8583ac0b2 100644 --- a/happening.py +++ b/happening.py @@ -17,9 +17,10 @@ from utils import loadJson from utils import saveJson from utils import locatePost from utils import hasObjectDict +from utils import acctDir -def _validUuid(testUuid: str, version=4): +def _validUuid(testUuid: str, version: int = 4): """Check if uuid_to_test is a valid UUID """ try: @@ -182,7 +183,7 @@ def getTodaysEvents(baseDir: str, nickname: str, domain: str, dayNumber = currDayOfMonth calendarFilename = \ - baseDir + '/accounts/' + nickname + '@' + domain + \ + acctDir(baseDir, nickname, domain) + \ '/calendar/' + str(year) + '/' + str(monthNumber) + '.txt' events = {} if not os.path.isfile(calendarFilename): @@ -255,7 +256,7 @@ def dayEventsCheck(baseDir: str, nickname: str, domain: str, currDate) -> bool: dayNumber = currDate.day calendarFilename = \ - baseDir + '/accounts/' + nickname + '@' + domain + \ + acctDir(baseDir, nickname, domain) + \ '/calendar/' + str(year) + '/' + str(monthNumber) + '.txt' if not os.path.isfile(calendarFilename): return False @@ -308,7 +309,7 @@ def getThisWeeksEvents(baseDir: str, nickname: str, domain: str) -> {}: monthNumber = now.month calendarFilename = \ - baseDir + '/accounts/' + nickname + '@' + domain + \ + acctDir(baseDir, nickname, domain) + \ '/calendar/' + str(year) + '/' + str(monthNumber) + '.txt' events = {} @@ -370,7 +371,7 @@ def getCalendarEvents(baseDir: str, nickname: str, domain: str, Event and Place activities """ calendarFilename = \ - baseDir + '/accounts/' + nickname + '@' + domain + \ + acctDir(baseDir, nickname, domain) + \ '/calendar/' + str(year) + '/' + str(monthNumber) + '.txt' events = {} @@ -432,7 +433,7 @@ def removeCalendarEvent(baseDir: str, nickname: str, domain: str, """Removes a calendar event """ calendarFilename = \ - baseDir + '/accounts/' + nickname + '@' + domain + \ + acctDir(baseDir, nickname, domain) + \ '/calendar/' + str(year) + '/' + str(monthNumber) + '.txt' if not os.path.isfile(calendarFilename): return diff --git a/inbox.py b/inbox.py index 24ed00f90..1a129dae3 100644 --- a/inbox.py +++ b/inbox.py @@ -13,6 +13,7 @@ import datetime import time import random from linked_data_sig import verifyJsonSignature +from utils import acctDir from utils import removeDomainPort from utils import getPortFromDomain from utils import hasObjectDict @@ -190,7 +191,7 @@ def validInbox(baseDir: str, nickname: str, domain: str) -> bool: """Checks whether files were correctly saved to the inbox """ domain = removeDomainPort(domain) - inboxDir = baseDir + '/accounts/' + nickname + '@' + domain + '/inbox' + inboxDir = acctDir(baseDir, nickname, domain) + '/inbox' if not os.path.isdir(inboxDir): return True for subdir, dirs, files in os.walk(inboxDir): @@ -212,7 +213,7 @@ def validInboxFilenames(baseDir: str, nickname: str, domain: str, domain names within saved post filenames """ domain = removeDomainPort(domain) - inboxDir = baseDir + '/accounts/' + nickname + '@' + domain + '/inbox' + inboxDir = acctDir(baseDir, nickname, domain) + '/inbox' if not os.path.isdir(inboxDir): return True expectedStr = expectedDomain + ':' + str(expectedPort) @@ -2078,7 +2079,7 @@ def _updateLastSeen(baseDir: str, handle: str, actor: str) -> None: nickname = handle.split('@')[0] domain = handle.split('@')[1] domain = removeDomainPort(domain) - accountPath = baseDir + '/accounts/' + nickname + '@' + domain + accountPath = acctDir(baseDir, nickname, domain) if not os.path.isdir(accountPath): return if not isFollowingActor(baseDir, nickname, domain, actor): @@ -2191,8 +2192,7 @@ def _isValidDM(baseDir: str, nickname: str, domain: str, port: int, # check for the flag file which indicates to # only receive DMs from people you are following - followDMsFilename = \ - baseDir + '/accounts/' + nickname + '@' + domain + '/.followDMs' + followDMsFilename = acctDir(baseDir, nickname, domain) + '/.followDMs' if not os.path.isfile(followDMsFilename): # dm index will be updated updateIndexList.append('dm') @@ -2201,9 +2201,7 @@ def _isValidDM(baseDir: str, nickname: str, domain: str, port: int, return True # get the file containing following handles - followingFilename = \ - baseDir + '/accounts/' + \ - nickname + '@' + domain + '/following.txt' + followingFilename = acctDir(baseDir, nickname, domain) + '/following.txt' # who is sending a DM? if not postJsonObject.get('actor'): return False diff --git a/manualapprove.py b/manualapprove.py index 968b016e3..18b1b320b 100644 --- a/manualapprove.py +++ b/manualapprove.py @@ -15,6 +15,7 @@ from utils import loadJson from utils import removeDomainPort from utils import getPortFromDomain from utils import getUserPaths +from utils import acctDir def manualDenyFollowRequest(session, baseDir: str, @@ -28,8 +29,7 @@ def manualDenyFollowRequest(session, baseDir: str, projectVersion: str) -> None: """Manually deny a follow request """ - handle = nickname + '@' + domain - accountsDir = baseDir + '/accounts/' + handle + accountsDir = acctDir(baseDir, nickname, domain) # has this handle already been rejected? rejectedFollowsFilename = accountsDir + '/followrejects.txt' diff --git a/mastoapiv1.py b/mastoapiv1.py index bd0d9c131..93271f86d 100644 --- a/mastoapiv1.py +++ b/mastoapiv1.py @@ -10,6 +10,7 @@ __module_group__ = "API" import os from utils import loadJson from utils import getConfigParam +from utils import acctDir from metadata import metaDataInstance @@ -54,8 +55,7 @@ def _getMastoApiV1Account(baseDir: str, nickname: str, domain: str) -> {}: blob/master/Using-the-API/API.md#account Authorization has already been performed """ - accountFilename = \ - baseDir + '/accounts/' + nickname + '@' + domain + '.json' + accountFilename = acctDir(baseDir, nickname, domain) + '.json' if not os.path.isfile(accountFilename): return {} accountJson = loadJson(accountFilename) diff --git a/media.py b/media.py index 0206a10ba..dc4ba5346 100644 --- a/media.py +++ b/media.py @@ -19,6 +19,7 @@ from utils import getVideoExtensions from utils import getAudioExtensions from utils import getMediaExtensions from utils import hasObjectDict +from utils import acctDir from shutil import copyfile from shutil import rmtree from shutil import move @@ -67,8 +68,7 @@ def _spoofMetaData(baseDir: str, nickname: str, domain: str, return # get the random seed used to generate a unique pattern for this account - decoySeedFilename = \ - baseDir + '/accounts/' + nickname + '@' + domain + '/decoyseed' + decoySeedFilename = acctDir(baseDir, nickname, domain) + '/decoyseed' decoySeed = 63725 if os.path.isfile(decoySeedFilename): with open(decoySeedFilename, 'r') as fp: @@ -267,7 +267,8 @@ def attachMedia(baseDir: str, httpPrefix: str, return postJson -def archiveMedia(baseDir: str, archiveDirectory: str, maxWeeks=4) -> None: +def archiveMedia(baseDir: str, archiveDirectory: str, + maxWeeks: int = 4) -> None: """Any media older than the given number of weeks gets archived """ if maxWeeks == 0: diff --git a/migrate.py b/migrate.py index 94fafe932..2163a1509 100644 --- a/migrate.py +++ b/migrate.py @@ -11,6 +11,7 @@ import os from utils import isAccountDir from utils import getNicknameFromActor from utils import getDomainFromActor +from utils import acctDir from webfinger import webfingerHandle from blocking import isBlocked from posts import getUserUrl @@ -25,8 +26,7 @@ def _moveFollowingHandlesForAccount(baseDir: str, nickname: str, domain: str, """Goes through all follows for an account and updates any that have moved """ ctr = 0 - followingFilename = \ - baseDir + '/accounts/' + nickname + '@' + domain + '/following.txt' + followingFilename = acctDir(baseDir, nickname, domain) + '/following.txt' if not os.path.isfile(followingFilename): return ctr with open(followingFilename, 'r') as f: @@ -111,8 +111,7 @@ def _updateMovedHandle(baseDir: str, nickname: str, domain: str, 'following.txt', debug) return ctr - followingFilename = \ - baseDir + '/accounts/' + nickname + '@' + domain + '/following.txt' + followingFilename = acctDir(baseDir, nickname, domain) + '/following.txt' if os.path.isfile(followingFilename): with open(followingFilename, 'r') as f: followingHandles = f.readlines() @@ -121,8 +120,7 @@ def _updateMovedHandle(baseDir: str, nickname: str, domain: str, handleLower = handle.lower() refollowFilename = \ - baseDir + '/accounts/' + \ - nickname + '@' + domain + '/refollow.txt' + acctDir(baseDir, nickname, domain) + '/refollow.txt' # unfollow the old handle with open(followingFilename, 'w+') as f: @@ -150,7 +148,7 @@ def _updateMovedHandle(baseDir: str, nickname: str, domain: str, f.write(movedToHandle + '\n') followersFilename = \ - baseDir + '/accounts/' + nickname + '@' + domain + '/followers.txt' + acctDir(baseDir, nickname, domain) + '/followers.txt' if os.path.isfile(followersFilename): with open(followersFilename, 'r') as f: followerHandles = f.readlines() diff --git a/newsdaemon.py b/newsdaemon.py index 71913bb9a..21b01c67a 100644 --- a/newsdaemon.py +++ b/newsdaemon.py @@ -527,8 +527,7 @@ def _convertRSStoActivityPub(baseDir: str, httpPrefix: str, os.mkdir(basePath) # oldest items first - newswireReverse = \ - OrderedDict(sorted(newswire.items(), reverse=False)) + newswireReverse = OrderedDict(sorted(newswire.items(), reverse=False)) for dateStr, item in newswireReverse.items(): originalDateStr = dateStr diff --git a/newswire.py b/newswire.py index 63379a605..5fba2748e 100644 --- a/newswire.py +++ b/newswire.py @@ -28,6 +28,7 @@ from utils import isSuspended from utils import containsInvalidChars from utils import removeHtml from utils import isAccountDir +from utils import acctDir from blocking import isBlockedDomain from blocking import isBlockedHashtag from filters import isFiltered @@ -918,8 +919,7 @@ def _addAccountBlogsToNewswire(baseDir: str, nickname: str, domain: str, # local blogs can potentially be moderated moderatedFilename = \ - baseDir + '/accounts/' + nickname + '@' + domain + \ - '/.newswiremoderated' + acctDir(baseDir, nickname, domain) + '/.newswiremoderated' if os.path.isfile(moderatedFilename): moderated = True diff --git a/notifyOnPost.py b/notifyOnPost.py index 2c40e7d2e..e967e5d93 100644 --- a/notifyOnPost.py +++ b/notifyOnPost.py @@ -9,6 +9,7 @@ __module_group__ = "Calendar" import os from utils import removeDomainPort +from utils import acctDir def _notifyOnPostArrival(baseDir: str, nickname: str, domain: str, @@ -20,8 +21,7 @@ def _notifyOnPostArrival(baseDir: str, nickname: str, domain: str, """ # check that a following file exists domain = removeDomainPort(domain) - followingFilename = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/following.txt' + followingFilename = acctDir(baseDir, nickname, domain) + '/following.txt' if not os.path.isfile(followingFilename): print("WARN: following.txt doesn't exist for " + nickname + '@' + domain) @@ -33,8 +33,8 @@ def _notifyOnPostArrival(baseDir: str, nickname: str, domain: str, print('WARN: ' + handle + ' is not in ' + followingFilename) return - notifyOnPostFilename = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/notifyOnPost.txt' + notifyOnPostFilename = \ + acctDir(baseDir, nickname, domain) + '/notifyOnPost.txt' # get the contents of the notifyOnPost file, which is # a set of handles @@ -95,7 +95,7 @@ def notifyWhenPersonPosts(baseDir: str, nickname: str, domain: str, if followingNickname == nickname and followingDomain == domain: return False notifyOnPostFilename = \ - baseDir + '/accounts/' + nickname + '@' + domain + '/notifyOnPost.txt' + acctDir(baseDir, nickname, domain) + '/notifyOnPost.txt' handle = followingNickname + '@' + followingDomain if not os.path.isfile(notifyOnPostFilename): # create a new notifyOnPost file diff --git a/outbox.py b/outbox.py index 779c92da0..25bc2d163 100644 --- a/outbox.py +++ b/outbox.py @@ -25,6 +25,7 @@ from utils import dangerousMarkup from utils import isFeaturedWriter from utils import loadJson from utils import saveJson +from utils import acctDir from blocking import isBlockedDomain from blocking import outboxBlock from blocking import outboxUndoBlock @@ -106,7 +107,7 @@ def _outboxPersonReceiveUpdate(recentPostsCache: {}, return updatedActorJson = messageJson['object'] # load actor from file - actorFilename = baseDir + '/accounts/' + nickname + '@' + domain + '.json' + actorFilename = acctDir(baseDir, nickname, domain) + '.json' if not os.path.isfile(actorFilename): print('actorFilename not found: ' + actorFilename) return @@ -127,30 +128,31 @@ def _outboxPersonReceiveUpdate(recentPostsCache: {}, continue if newPropertyValue['type'] != 'PropertyValue': continue - if 'attachment' in actorJson: - found = False - for attachIdx in range(len(actorJson['attachment'])): - if actorJson['attachment'][attachIdx]['type'] != \ - 'PropertyValue': - continue - if actorJson['attachment'][attachIdx]['name'] != \ - newPropertyValue['name']: - continue - else: - if actorJson['attachment'][attachIdx]['value'] != \ - newPropertyValue['value']: - actorJson['attachment'][attachIdx]['value'] = \ - newPropertyValue['value'] - actorChanged = True - found = True - break - if not found: - actorJson['attachment'].append({ - "name": newPropertyValue['name'], - "type": "PropertyValue", - "value": newPropertyValue['value'] - }) - actorChanged = True + if 'attachment' not in actorJson: + continue + found = False + for attachIdx in range(len(actorJson['attachment'])): + if actorJson['attachment'][attachIdx]['type'] != \ + 'PropertyValue': + continue + if actorJson['attachment'][attachIdx]['name'] != \ + newPropertyValue['name']: + continue + else: + if actorJson['attachment'][attachIdx]['value'] != \ + newPropertyValue['value']: + actorJson['attachment'][attachIdx]['value'] = \ + newPropertyValue['value'] + actorChanged = True + found = True + break + if not found: + actorJson['attachment'].append({ + "name": newPropertyValue['name'], + "type": "PropertyValue", + "value": newPropertyValue['value'] + }) + actorChanged = True # save actor to file if actorChanged: saveJson(actorJson, actorFilename) diff --git a/person.py b/person.py index 98f16d737..1ee5180cb 100644 --- a/person.py +++ b/person.py @@ -51,6 +51,7 @@ from utils import hasUsersPath from utils import getImageExtensions from utils import isImageFile from utils import getUserPaths +from utils import acctDir from session import createSession from session import getJson from webfinger import webfingerHandle @@ -153,7 +154,8 @@ def _accountExists(baseDir: str, nickname: str, domain: str) -> bool: """Returns true if the given account exists """ domain = removeDomainPort(domain) - return os.path.isdir(baseDir + '/accounts/' + nickname + '@' + domain) or \ + accountDir = acctDir(baseDir, nickname, domain) + return os.path.isdir(accountDir) or \ os.path.isdir(baseDir + '/deactivated/' + nickname + '@' + domain) @@ -443,8 +445,7 @@ def savePersonQrcode(baseDir: str, """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' + qrcodeFilename = acctDir(baseDir, nickname, domain) + '/qrcode.png' if os.path.isfile(qrcodeFilename): return handle = getFullDomain('@' + nickname + '@' + domain, port) @@ -492,19 +493,19 @@ def createPerson(baseDir: str, nickname: str, domain: str, port: int, 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) + accountDir = acctDir(baseDir, nickname, domain) + if not os.path.isdir(accountDir): + os.mkdir(accountDir) if manualFollowerApproval: - followDMsFilename = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/.followDMs' + followDMsFilename = acctDir(baseDir, nickname, domain) + '/.followDMs' with open(followDMsFilename, 'w+') as fFile: fFile.write('\n') # notify when posts are liked if nickname != 'news': - notifyLikesFilename = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/.notifyLikes' + notifyLikesFilename = \ + acctDir(baseDir, nickname, domain) + '/.notifyLikes' with open(notifyLikesFilename, 'w+') as nFile: nFile.write('\n') @@ -514,15 +515,14 @@ def createPerson(baseDir: str, nickname: str, domain: str, port: int, if nickname != 'news': if os.path.isfile(baseDir + '/img/default-avatar.png'): + accountDir = acctDir(baseDir, nickname, domain) copyfile(baseDir + '/img/default-avatar.png', - baseDir + '/accounts/' + nickname + '@' + domain + - '/avatar.png') + accountDir + '/avatar.png') else: newsAvatar = baseDir + '/theme/' + theme + '/icons/avatar_news.png' if os.path.isfile(newsAvatar): - copyfile(newsAvatar, - baseDir + '/accounts/' + nickname + '@' + domain + - '/avatar.png') + accountDir = acctDir(baseDir, nickname, domain) + copyfile(newsAvatar, accountDir + '/avatar.png') defaultProfileImageFilename = baseDir + '/theme/default/image.png' if theme: @@ -530,15 +530,15 @@ def createPerson(baseDir: str, nickname: str, domain: str, port: int, defaultProfileImageFilename = \ baseDir + '/theme/' + theme + '/image.png' if os.path.isfile(defaultProfileImageFilename): - copyfile(defaultProfileImageFilename, baseDir + - '/accounts/' + nickname + '@' + domain + '/image.png') + accountDir = acctDir(baseDir, nickname, domain) + copyfile(defaultProfileImageFilename, accountDir + '/image.png') defaultBannerFilename = baseDir + '/theme/default/banner.png' if theme: if os.path.isfile(baseDir + '/theme/' + theme + '/banner.png'): defaultBannerFilename = baseDir + '/theme/' + theme + '/banner.png' if os.path.isfile(defaultBannerFilename): - copyfile(defaultBannerFilename, baseDir + '/accounts/' + - nickname + '@' + domain + '/banner.png') + accountDir = acctDir(baseDir, nickname, domain) + copyfile(defaultBannerFilename, accountDir + '/banner.png') if nickname != 'news' and remainingConfigExists: registrationsRemaining -= 1 setConfigParam(baseDir, 'registrationsRemaining', @@ -899,12 +899,10 @@ def suspendAccount(baseDir: str, nickname: str, domain: str) -> None: if moderator.strip('\n').strip('\r') == nickname: return - saltFilename = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/.salt' + saltFilename = acctDir(baseDir, nickname, domain) + '/.salt' if os.path.isfile(saltFilename): os.remove(saltFilename) - tokenFilename = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/.token' + tokenFilename = acctDir(baseDir, nickname, domain) + '/.token' if os.path.isfile(tokenFilename): os.remove(tokenFilename) @@ -1090,8 +1088,7 @@ def isPersonSnoozed(baseDir: str, nickname: str, domain: str, snoozeActor: str) -> bool: """Returns true if the given actor is snoozed """ - snoozedFilename = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/snoozed.txt' + snoozedFilename = acctDir(baseDir, nickname, domain) + '/snoozed.txt' if not os.path.isfile(snoozedFilename): return False if snoozeActor + ' ' not in open(snoozedFilename).read(): @@ -1131,7 +1128,7 @@ def personSnooze(baseDir: str, nickname: str, domain: str, snoozeActor: str) -> None: """Temporarily ignores the given actor """ - accountDir = baseDir + '/accounts/' + nickname + '@' + domain + accountDir = acctDir(baseDir, nickname, domain) if not os.path.isdir(accountDir): print('ERROR: unknown account ' + accountDir) return @@ -1148,7 +1145,7 @@ def personUnsnooze(baseDir: str, nickname: str, domain: str, snoozeActor: str) -> None: """Undoes a temporarily ignore of the given actor """ - accountDir = baseDir + '/accounts/' + nickname + '@' + domain + accountDir = acctDir(baseDir, nickname, domain) if not os.path.isdir(accountDir): print('ERROR: unknown account ' + accountDir) return @@ -1180,8 +1177,7 @@ def setPersonNotes(baseDir: str, nickname: str, domain: str, return False if handle.startswith('@'): handle = handle[1:] - notesDir = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/notes' + notesDir = acctDir(baseDir, nickname, domain) + '/notes' if not os.path.isdir(notesDir): os.mkdir(notesDir) notesFilename = notesDir + '/' + handle + '.txt' diff --git a/petnames.py b/petnames.py index 9f61c0885..6346c22f5 100644 --- a/petnames.py +++ b/petnames.py @@ -8,6 +8,7 @@ __status__ = "Production" __module_group__ = "Core" import os +from utils import acctDir def setPetName(baseDir: str, nickname: str, domain: str, @@ -22,8 +23,7 @@ def setPetName(baseDir: str, nickname: str, domain: str, handle = handle[1:] if petname.startswith('@'): petname = petname[1:] - petnamesFilename = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/petnames.txt' + petnamesFilename = acctDir(baseDir, nickname, domain) + '/petnames.txt' entry = petname + ' ' + handle + '\n' # does this entry already exist? @@ -63,8 +63,7 @@ def getPetName(baseDir: str, nickname: str, domain: str, return '' if handle.startswith('@'): handle = handle[1:] - petnamesFilename = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/petnames.txt' + petnamesFilename = acctDir(baseDir, nickname, domain) + '/petnames.txt' if not os.path.isfile(petnamesFilename): return '' @@ -91,8 +90,7 @@ def _getPetNameHandle(baseDir: str, nickname: str, domain: str, """ if petname.startswith('@'): petname = petname[1:] - petnamesFilename = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/petnames.txt' + petnamesFilename = acctDir(baseDir, nickname, domain) + '/petnames.txt' if not os.path.isfile(petnamesFilename): return '' diff --git a/posts.py b/posts.py index 44cc5a662..757751e31 100644 --- a/posts.py +++ b/posts.py @@ -59,6 +59,7 @@ from utils import locateNewsArrival from utils import votesOnNewswireItem from utils import removeHtml from utils import dangerousMarkup +from utils import acctDir from media import attachMedia from media import replaceYouTube from content import limitRepeatedWords @@ -775,8 +776,7 @@ def _loadAutoCW(baseDir: str, nickname: str, domain: str) -> []: """Loads automatic CWs file and returns a list containing the lines of the file """ - filename = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/autocw.txt' + filename = acctDir(baseDir, nickname, domain) + '/autocw.txt' if not os.path.isfile(filename): return [] with open(filename, 'r') as f: @@ -1324,7 +1324,7 @@ def pinPost(baseDir: str, nickname: str, domain: str, pinnedContent: str) -> None: """Pins the given post Id to the profile of then given account """ - accountDir = baseDir + '/accounts/' + nickname + '@' + domain + accountDir = acctDir(baseDir, nickname, domain) pinnedFilename = accountDir + '/pinToProfile.txt' with open(pinnedFilename, 'w+') as pinFile: pinFile.write(pinnedContent) @@ -1333,7 +1333,7 @@ def pinPost(baseDir: str, nickname: str, domain: str, def undoPinnedPost(baseDir: str, nickname: str, domain: str) -> None: """Removes pinned content for then given account """ - accountDir = baseDir + '/accounts/' + nickname + '@' + domain + accountDir = acctDir(baseDir, nickname, domain) pinnedFilename = accountDir + '/pinToProfile.txt' if os.path.isfile(pinnedFilename): os.remove(pinnedFilename) @@ -1344,7 +1344,7 @@ def getPinnedPostAsJson(baseDir: str, httpPrefix: str, domainFull: str) -> {}: """Returns the pinned profile post as json """ - accountDir = baseDir + '/accounts/' + nickname + '@' + domain + accountDir = acctDir(baseDir, nickname, domain) pinnedFilename = accountDir + '/pinToProfile.txt' pinnedPostJson = {} actor = httpPrefix + '://' + domainFull + '/users/' + nickname @@ -1464,8 +1464,7 @@ def _appendCitationsToBlogPost(baseDir: str, """ # append citations tags, stored in a file citationsFilename = \ - baseDir + '/accounts/' + \ - nickname + '@' + domain + '/.citations.txt' + acctDir(baseDir, nickname, domain) + '/.citations.txt' if not os.path.isfile(citationsFilename): return citationsSeparator = '#####' @@ -3815,9 +3814,7 @@ def populateRepliesJson(baseDir: str, nickname: str, domain: str, for boxname in repliesBoxes: messageId2 = messageId.replace('\n', '').replace('\r', '') searchFilename = \ - baseDir + \ - '/accounts/' + nickname + '@' + \ - domain + '/' + \ + acctDir(baseDir, nickname, domain) + '/' + \ boxname + '/' + \ messageId2.replace('/', '#') + '.json' if os.path.isfile(searchFilename): @@ -4419,7 +4416,7 @@ def postIsMuted(baseDir: str, nickname: str, domain: str, isMuted = postJsonObject.get('muted') if isMuted is True or isMuted is False: return isMuted - postDir = baseDir + '/accounts/' + nickname + '@' + domain + postDir = acctDir(baseDir, nickname, domain) muteFilename = \ postDir + '/inbox/' + messageId.replace('/', '#') + '.json.muted' if os.path.isfile(muteFilename): diff --git a/pyjsonld.py b/pyjsonld.py index 36d0df1fa..fec0a1e34 100644 --- a/pyjsonld.py +++ b/pyjsonld.py @@ -4298,7 +4298,8 @@ class JsonLdProcessor(object): elif v not in urls: urls[v] = False - def _retrieve_context_urls(self, input_, cycles, load_document, base=''): + def _retrieve_context_urls(self, input_, cycles, load_document, + base: str = ''): """ Retrieves external @context URLs using the given document loader. Each instance of @context in the input that refers to a URL will be @@ -4860,7 +4861,7 @@ class ActiveContextCache(object): the overhead of recomputing them. """ - def __init__(self, size=100): + def __init__(self, size: int = 100): self.order = deque() self.cache = {} self.size = size diff --git a/roles.py b/roles.py index ec0286f1d..1dccf2073 100644 --- a/roles.py +++ b/roles.py @@ -12,6 +12,7 @@ from utils import loadJson from utils import saveJson from utils import getStatusNumber from utils import removeDomainPort +from utils import acctDir def _clearRoleStatus(baseDir: str, role: str) -> None: @@ -98,8 +99,8 @@ def _addRole(baseDir: str, nickname: str, domain: str, f.write(roleNickname + '\n') else: with open(roleFile, 'w+') as f: - if os.path.isdir(baseDir + '/accounts/' + - nickname + '@' + domain): + accountDir = acctDir(baseDir, nickname, domain) + if os.path.isdir(accountDir): f.write(nickname + '\n') @@ -230,7 +231,7 @@ def setRole(baseDir: str, nickname: str, domain: str, # avoid giant strings if len(role) > 128: return False - actorFilename = baseDir + '/accounts/' + nickname + '@' + domain + '.json' + actorFilename = acctDir(baseDir, nickname, domain) + '.json' if not os.path.isfile(actorFilename): return False diff --git a/schedule.py b/schedule.py index 3e3543384..de3564d45 100644 --- a/schedule.py +++ b/schedule.py @@ -14,6 +14,7 @@ from utils import hasObjectDict from utils import getStatusNumber from utils import loadJson from utils import isAccountDir +from utils import acctDir from outbox import postMessageToOutbox @@ -179,12 +180,11 @@ def removeScheduledPosts(baseDir: str, nickname: str, domain: str) -> None: """ # remove the index scheduleIndexFilename = \ - baseDir + '/accounts/' + nickname + '@' + domain + '/schedule.index' + acctDir(baseDir, nickname, domain) + '/schedule.index' if os.path.isfile(scheduleIndexFilename): os.remove(scheduleIndexFilename) # remove the scheduled posts - scheduledDir = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/scheduled' + scheduledDir = acctDir(baseDir, nickname, domain) + '/scheduled' if not os.path.isdir(scheduledDir): return for scheduledPostFilename in os.listdir(scheduledDir): diff --git a/session.py b/session.py index 7e48cde5a..b1f0b8d89 100644 --- a/session.py +++ b/session.py @@ -53,8 +53,8 @@ def createSession(proxyType: str): return session -def urlExists(session, url: str, timeoutSec=3, - httpPrefix='https', domain='testdomain') -> bool: +def urlExists(session, url: str, timeoutSec: int = 3, + httpPrefix: str = 'https', domain: str = 'testdomain') -> bool: if not isinstance(url, str): print('url: ' + str(url)) print('ERROR: urlExists failed, url should be a string') diff --git a/shares.py b/shares.py index 4407a3234..20605c12a 100644 --- a/shares.py +++ b/shares.py @@ -22,6 +22,7 @@ from utils import getImageExtensions from utils import hasObjectDict from utils import removeDomainPort from utils import isAccountDir +from utils import acctDir from media import processMetaData @@ -44,8 +45,7 @@ def removeShare(baseDir: str, nickname: str, domain: str, displayName: str) -> None: """Removes a share for a person """ - sharesFilename = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/shares.json' + sharesFilename = acctDir(baseDir, nickname, domain) + '/shares.json' if not os.path.isfile(sharesFilename): print('ERROR: missing shares.json ' + sharesFilename) return @@ -101,8 +101,7 @@ def addShare(baseDir: str, duration: str, debug: bool, city: str) -> None: """Adds a new share """ - sharesFilename = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/shares.json' + sharesFilename = acctDir(baseDir, nickname, domain) + '/shares.json' sharesJson = {} if os.path.isfile(sharesFilename): sharesJson = loadJson(sharesFilename) @@ -118,7 +117,7 @@ def addShare(baseDir: str, moveImage = False if not imageFilename: sharesImageFilename = \ - baseDir + '/accounts/' + nickname + '@' + domain + '/upload' + acctDir(baseDir, nickname, domain) + '/upload' formats = getImageExtensions() for ext in formats: if os.path.isfile(sharesImageFilename + '.' + ext): @@ -257,8 +256,7 @@ def getSharesFeedForPerson(baseDir: str, domain = getFullDomain(domain, port) handleDomain = removeDomainPort(domain) - handle = nickname + '@' + handleDomain - sharesFilename = baseDir + '/accounts/' + handle + '/shares.json' + sharesFilename = acctDir(baseDir, nickname, handleDomain) + '/shares.json' if headerOnly: noOfShares = 0 diff --git a/siteactive.py b/siteactive.py index c5e96f821..3fb7173e9 100644 --- a/siteactive.py +++ b/siteactive.py @@ -93,7 +93,7 @@ def _siteActiveHttpRequest(loc, timeout: int): return result -def siteIsActive(url: str, timeout=10) -> bool: +def siteIsActive(url: str, timeout: int = 10) -> bool: """Returns true if the current url is resolvable. This can be used to check that an instance is online before trying to send posts to it. diff --git a/skills.py b/skills.py index db4a01a50..0c034a5a0 100644 --- a/skills.py +++ b/skills.py @@ -18,6 +18,7 @@ from utils import getDomainFromActor from utils import loadJson from utils import getOccupationSkills from utils import setOccupationSkillsList +from utils import acctDir def setSkillsFromDict(actorJson: {}, skillsDict: {}) -> []: @@ -115,7 +116,7 @@ def setSkillLevel(baseDir: str, nickname: str, domain: str, """ if skillLevelPercent < 0 or skillLevelPercent > 100: return False - actorFilename = baseDir + '/accounts/' + nickname + '@' + domain + '.json' + actorFilename = acctDir(baseDir, nickname, domain) + '.json' if not os.path.isfile(actorFilename): return False @@ -127,7 +128,7 @@ def setSkillLevel(baseDir: str, nickname: str, domain: str, def getSkills(baseDir: str, nickname: str, domain: str) -> []: """Returns the skills for a given person """ - actorFilename = baseDir + '/accounts/' + nickname + '@' + domain + '.json' + actorFilename = acctDir(baseDir, nickname, domain) + '.json' if not os.path.isfile(actorFilename): return False diff --git a/speaker.py b/speaker.py index 2d8d788d1..2c413abd6 100644 --- a/speaker.py +++ b/speaker.py @@ -23,6 +23,7 @@ from utils import loadJson from utils import saveJson from utils import isPGPEncrypted from utils import hasObjectDict +from utils import acctDir from content import htmlReplaceQuoteMarks speakerRemoveChars = ('.\n', '. ', ',', ';', '?', '!') @@ -356,7 +357,7 @@ def getSSMLbox(baseDir: str, path: str, if '/' in nickname: nickname = nickname.split('/')[0] speakerFilename = \ - baseDir + '/accounts/' + nickname + '@' + domain + '/speaker.json' + acctDir(baseDir, nickname, domain) + '/speaker.json' if not os.path.isfile(speakerFilename): return None speakerJson = loadJson(speakerFilename) @@ -491,7 +492,7 @@ def _postToSpeakerJson(baseDir: str, httpPrefix: str, followRequestsExist = False followRequestsList = [] - accountsDir = baseDir + '/accounts/' + nickname + '@' + domainFull + accountsDir = acctDir(baseDir, nickname, domainFull) approveFollowsFilename = accountsDir + '/followrequests.txt' if os.path.isfile(approveFollowsFilename): with open(approveFollowsFilename, 'r') as fp: @@ -544,6 +545,5 @@ def updateSpeaker(baseDir: str, httpPrefix: str, postJsonObject, personCache, translate, announcingActor, themeName) - speakerFilename = \ - baseDir + '/accounts/' + nickname + '@' + domain + '/speaker.json' + speakerFilename = acctDir(baseDir, nickname, domain) + '/speaker.json' saveJson(speakerJson, speakerFilename) diff --git a/tests.py b/tests.py index c496b4a81..54f16e1e7 100644 --- a/tests.py +++ b/tests.py @@ -57,6 +57,7 @@ from utils import getStatusNumber from utils import getFollowersOfPerson from utils import removeHtml from utils import dangerousMarkup +from utils import acctDir from pgp import extractPGPPublicKey from pgp import pgpPublicKeyUpload from utils import containsPGPPublicKey @@ -1405,8 +1406,8 @@ def _testFollows(): followPerson(baseDir, nickname, domain, 'giraffe', 'trees.com', federationList, False) - f = open(baseDir + '/accounts/' + nickname + '@' + domain + - '/following.txt', 'r') + accountDir = acctDir(baseDir, nickname, domain) + f = open(accountDir + '/following.txt', 'r') domainFound = False for followingDomain in f: testDomain = followingDomain.split('@')[1] @@ -1440,8 +1441,8 @@ def _testFollows(): followerOfPerson(baseDir, nickname, domain, 'giraffe', 'trees.com', federationList, False) - f = open(baseDir + '/accounts/' + nickname + '@' + domain + - '/followers.txt', 'r') + accountDir = acctDir(baseDir, nickname, domain) + f = open(accountDir + '/followers.txt', 'r') for followerDomain in f: testDomain = followerDomain.split('@')[1] testDomain = testDomain.replace('\n', '').replace('\r', '') diff --git a/theme.py b/theme.py index 46062ca8a..7f8d96086 100644 --- a/theme.py +++ b/theme.py @@ -13,6 +13,7 @@ from utils import loadJson from utils import saveJson from utils import getImageExtensions from utils import copytree +from utils import acctDir from shutil import copyfile from shutil import make_archive from shutil import unpack_archive @@ -721,9 +722,8 @@ def setNewsAvatar(baseDir: str, name: str, os.remove(filename) if os.path.isdir(baseDir + '/cache/avatars'): copyfile(newFilename, filename) - copyfile(newFilename, - baseDir + '/accounts/' + - nickname + '@' + domain + '/avatar.png') + accountDir = acctDir(baseDir, nickname, domain) + copyfile(newFilename, accountDir + '/avatar.png') def _setClearCacheFlag(baseDir: str) -> None: diff --git a/threads.py b/threads.py index fa9ab9acd..d49981f90 100644 --- a/threads.py +++ b/threads.py @@ -71,7 +71,7 @@ class threadWithTrace(threading.Thread): def removeDormantThreads(baseDir: str, threadsList: [], debug: bool, - timeoutMins=30) -> None: + timeoutMins: int = 30) -> None: """Removes threads whose execution has completed """ if len(threadsList) == 0: diff --git a/utils.py b/utils.py index 434b07132..997cf68ce 100644 --- a/utils.py +++ b/utils.py @@ -28,13 +28,16 @@ invalidCharacters = ( ) +def acctDir(baseDir: str, nickname: str, domain: str) -> str: + return baseDir + '/accounts/' + nickname + '@' + domain + + def isFeaturedWriter(baseDir: str, nickname: str, domain: str) -> bool: """Is the given account a featured writer, appearing in the features timeline on news instances? """ featuresBlockedFilename = \ - baseDir + '/accounts/' + \ - nickname + '@' + domain + '/.nofeatures' + acctDir(baseDir, nickname, domain) + '/.nofeatures' return not os.path.isfile(featuresBlockedFilename) @@ -153,12 +156,11 @@ def getFullDomain(domain: str, port: int) -> str: def isDormant(baseDir: str, nickname: str, domain: str, actor: str, - dormantMonths=3) -> bool: + dormantMonths: int = 3) -> bool: """Is the given followed actor dormant, from the standpoint of the given account """ - lastSeenFilename = \ - baseDir + '/accounts/' + nickname + '@' + domain + \ + lastSeenFilename = acctDir(baseDir, nickname, domain) + \ '/lastseen/' + actor.replace('/', '#') + '.txt' if not os.path.isfile(lastSeenFilename): @@ -440,8 +442,7 @@ def getFollowersList(baseDir: str, followFile='following.txt') -> []: """Returns a list of followers for the given account """ - filename = \ - baseDir + '/accounts/' + nickname + '@' + domain + '/' + followFile + filename = acctDir(baseDir, nickname, domain) + '/' + followFile if not os.path.isfile(filename): return [] @@ -544,7 +545,7 @@ def saveJson(jsonObject: {}, filename: str) -> bool: return False -def loadJson(filename: str, delaySec=2, maxTries=5) -> {}: +def loadJson(filename: str, delaySec: int = 2, maxTries: int = 5) -> {}: """Makes a few attempts to load a json formatted file """ jsonObject = None @@ -564,7 +565,7 @@ def loadJson(filename: str, delaySec=2, maxTries=5) -> {}: def loadJsonOnionify(filename: str, domain: str, onionDomain: str, - delaySec=2) -> {}: + delaySec: int = 2) -> {}: """Makes a few attempts to load a json formatted file This also converts the domain name to the onion domain """ @@ -950,7 +951,7 @@ def _setDefaultPetName(baseDir: str, nickname: str, domain: str, This helps especially when using onion or i2p address """ domain = removeDomainPort(domain) - userPath = baseDir + '/accounts/' + nickname + '@' + domain + userPath = acctDir(baseDir, nickname, domain) petnamesFilename = userPath + '/petnames.txt' petnameLookupEntry = followNickname + ' ' + \ @@ -1180,7 +1181,7 @@ def locatePost(baseDir: str, nickname: str, domain: str, # search boxes boxes = ('inbox', 'outbox', 'tlblogs') - accountDir = baseDir + '/accounts/' + nickname + '@' + domain + '/' + accountDir = acctDir(baseDir, nickname, domain) + '/' for boxName in boxes: postFilename = accountDir + boxName + '/' + postUrl if os.path.isfile(postFilename): @@ -1251,8 +1252,7 @@ def _isReplyToBlogPost(baseDir: str, nickname: str, domain: str, return False if not isinstance(postJsonObject['object']['inReplyTo'], str): return False - blogsIndexFilename = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/tlblogs.index' + blogsIndexFilename = acctDir(baseDir, nickname, domain) + '/tlblogs.index' if not os.path.isfile(blogsIndexFilename): return False postId = removeIdEnding(postJsonObject['object']['inReplyTo']) @@ -1290,8 +1290,7 @@ def _isBookmarked(baseDir: str, nickname: str, domain: str, """Returns True if the given post is bookmarked """ bookmarksIndexFilename = \ - baseDir + '/accounts/' + nickname + '@' + domain + \ - '/bookmarks.index' + acctDir(baseDir, nickname, domain) + '/bookmarks.index' if os.path.isfile(bookmarksIndexFilename): bookmarkIndex = postFilename.split('/')[-1] + '\n' if bookmarkIndex in open(bookmarksIndexFilename).read(): @@ -1626,8 +1625,7 @@ def copytree(src: str, dst: str, symlinks: str = False, ignore: bool = None): def getCachedPostDirectory(baseDir: str, nickname: str, domain: str) -> str: """Returns the directory where the html post cache exists """ - htmlPostCacheDir = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/postcache' + htmlPostCacheDir = acctDir(baseDir, nickname, domain) + '/postcache' return htmlPostCacheDir @@ -1780,11 +1778,10 @@ def _searchVirtualBoxPosts(baseDir: str, nickname: str, domain: str, """Searches through a virtual box, which is typically an index on the inbox """ indexFilename = \ - baseDir + '/accounts/' + nickname + '@' + domain + '/' + \ - boxName + '.index' + acctDir(baseDir, nickname, domain) + '/' + boxName + '.index' if boxName == 'bookmarks': boxName = 'inbox' - path = baseDir + '/accounts/' + nickname + '@' + domain + '/' + boxName + path = acctDir(baseDir, nickname, domain) + '/' + boxName if not os.path.isdir(path): return [] @@ -1833,7 +1830,7 @@ def searchBoxPosts(baseDir: str, nickname: str, domain: str, """Search your posts and return a list of the filenames containing matching strings """ - path = baseDir + '/accounts/' + nickname + '@' + domain + '/' + boxName + path = acctDir(baseDir, nickname, domain) + '/' + boxName # is this a virtual box, such as direct messages? if not os.path.isdir(path): if os.path.isfile(path + '.index'): @@ -2163,7 +2160,7 @@ def mediaFileMimeType(filename: str) -> str: return extensions[fileExt] -def isRecentPost(postJsonObject: {}, maxDays=3) -> bool: +def isRecentPost(postJsonObject: {}, maxDays: int = 3) -> bool: """ Is the given post recent? """ if not hasObjectDict(postJsonObject): @@ -2349,8 +2346,7 @@ def dmAllowedFromDomain(baseDir: str, a few particular instances that you trust """ dmAllowedInstancesFilename = \ - baseDir + '/accounts/' + \ - nickname + '@' + domain + '/dmAllowedInstances.txt' + acctDir(baseDir, nickname, domain) + '/dmAllowedInstances.txt' if not os.path.isfile(dmAllowedInstancesFilename): return False if sendingActorDomain + '\n' in open(dmAllowedInstancesFilename).read(): diff --git a/webapp_accesskeys.py b/webapp_accesskeys.py index c901a59c1..a8eba7c16 100644 --- a/webapp_accesskeys.py +++ b/webapp_accesskeys.py @@ -11,6 +11,7 @@ import os from utils import isAccountDir from utils import loadJson from utils import getConfigParam +from utils import acctDir from webapp_utils import htmlHeaderWithExternalStyle from webapp_utils import htmlFooter @@ -46,7 +47,7 @@ def htmlAccessKeys(cssCache: {}, baseDir: str, """Show and edit key shortcuts """ accessKeysFilename = \ - baseDir + '/accounts/' + nickname + '@' + domain + '/accessKeys.json' + acctDir(baseDir, nickname, domain) + '/accessKeys.json' if os.path.isfile(accessKeysFilename): accessKeysFromFile = loadJson(accessKeysFilename) if accessKeysFromFile: diff --git a/webapp_calendar.py b/webapp_calendar.py index a01ffeb55..10e480fc1 100644 --- a/webapp_calendar.py +++ b/webapp_calendar.py @@ -20,6 +20,7 @@ from utils import loadJson from utils import weekDayOfMonthStart from utils import getAltPath from utils import removeDomainPort +from utils import acctDir from happening import getTodaysEvents from happening import getCalendarEvents from webapp_utils import htmlHeaderWithExternalStyle @@ -104,7 +105,7 @@ def _htmlCalendarDay(personCache: {}, cssCache: {}, translate: {}, monthName: str, actor: str) -> str: """Show a day within the calendar """ - accountDir = baseDir + '/accounts/' + nickname + '@' + domain + accountDir = acctDir(baseDir, nickname, domain) calendarFile = accountDir + '/.newCalendar' if os.path.isfile(calendarFile): os.remove(calendarFile) diff --git a/webapp_column_right.py b/webapp_column_right.py index 2327c8149..ad89d56e0 100644 --- a/webapp_column_right.py +++ b/webapp_column_right.py @@ -19,6 +19,7 @@ from utils import getNicknameFromActor from utils import isEditor from utils import getConfigParam from utils import removeDomainPort +from utils import acctDir from posts import isModerator from webapp_utils import getRightImageFile from webapp_utils import htmlHeaderWithExternalStyle @@ -337,8 +338,7 @@ def htmlCitations(baseDir: str, nickname: str, domain: str, # create a list of dates for citations # these can then be used to re-select checkboxes later citationsFilename = \ - baseDir + '/accounts/' + \ - nickname + '@' + domain + '/.citations.txt' + acctDir(baseDir, nickname, domain) + '/.citations.txt' citationsSelected = [] if os.path.isfile(citationsFilename): citationsSeparator = '#####' diff --git a/webapp_confirm.py b/webapp_confirm.py index fdbdc0ff5..7c820ea39 100644 --- a/webapp_confirm.py +++ b/webapp_confirm.py @@ -16,6 +16,7 @@ from utils import locatePost from utils import loadJson from utils import getConfigParam from utils import getAltPath +from utils import acctDir from webapp_utils import htmlHeaderWithExternalStyle from webapp_utils import htmlFooter from webapp_post import individualPostAsHtml @@ -111,8 +112,7 @@ def htmlConfirmRemoveSharedItem(cssCache: {}, translate: {}, baseDir: str, nickname = getNicknameFromActor(actor) domain, port = getDomainFromActor(actor) domainFull = getFullDomain(domain, port) - sharesFile = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/shares.json' + sharesFile = acctDir(baseDir, nickname, domain) + '/shares.json' if not os.path.isfile(sharesFile): print('ERROR: no shares file ' + sharesFile) return None diff --git a/webapp_create_post.py b/webapp_create_post.py index cb75eb018..4c6b7fbd6 100644 --- a/webapp_create_post.py +++ b/webapp_create_post.py @@ -14,6 +14,7 @@ from utils import getDomainFromActor from utils import getImageFormats from utils import getMediaFormats from utils import getConfigParam +from utils import acctDir from webapp_utils import getBannerFile from webapp_utils import htmlHeaderWithExternalStyle from webapp_utils import htmlFooter @@ -25,7 +26,7 @@ def _htmlFollowingDataList(baseDir: str, nickname: str, """ listStr = '\n' followingFilename = \ - baseDir + '/accounts/' + nickname + '@' + domain + '/following.txt' + acctDir(baseDir, nickname, domain) + '/following.txt' msg = None if os.path.isfile(followingFilename): with open(followingFilename, 'r') as followingFile: @@ -36,7 +37,7 @@ def _htmlFollowingDataList(baseDir: str, nickname: str, if msg: # include petnames petnamesFilename = \ - baseDir + '/accounts/' + nickname + '@' + domain + '/petnames.txt' + acctDir(baseDir, nickname, domain) + '/petnames.txt' if os.path.isfile(petnamesFilename): followingList = [] with open(petnamesFilename, 'r') as petnamesFile: @@ -403,8 +404,7 @@ def htmlNewPost(cssCache: {}, mediaInstance: bool, translate: {}, citationsStr = '' if endpoint == 'newblog': citationsFilename = \ - baseDir + '/accounts/' + \ - nickname + '@' + domain + '/.citations.txt' + acctDir(baseDir, nickname, domain) + '/.citations.txt' if os.path.isfile(citationsFilename): citationsStr = '
\n' citationsStr += '


\n' - cityFilename = baseDir + '/accounts/' + \ - nickname + '@' + domain + '/city.txt' + cityFilename = acctDir(baseDir, nickname, domain) + '/city.txt' if os.path.isfile(cityFilename): with open(cityFilename, 'r') as fp: city = fp.read().replace('\n', '') @@ -1907,8 +1899,7 @@ def htmlEditProfile(cssCache: {}, translate: {}, baseDir: str, path: str, return '' domainFull = getFullDomain(domain, port) - actorFilename = \ - baseDir + '/accounts/' + nickname + '@' + domain + '.json' + actorFilename = acctDir(baseDir, nickname, domain) + '.json' if not os.path.isfile(actorFilename): return '' @@ -1961,17 +1952,14 @@ def htmlEditProfile(cssCache: {}, translate: {}, baseDir: str, path: str, elif actorJson['type'] == 'Group': isGroup = 'checked' isBot = '' - if os.path.isfile(baseDir + '/accounts/' + - nickname + '@' + domain + '/.followDMs'): + accountDir = acctDir(baseDir, nickname, domain) + if os.path.isfile(accountDir + '/.followDMs'): followDMs = 'checked' - if os.path.isfile(baseDir + '/accounts/' + - nickname + '@' + domain + '/.removeTwitter'): + if os.path.isfile(accountDir + '/.removeTwitter'): removeTwitter = 'checked' - if os.path.isfile(baseDir + '/accounts/' + - nickname + '@' + domain + '/.notifyLikes'): + if os.path.isfile(accountDir + '/.notifyLikes'): notifyLikes = 'checked' - if os.path.isfile(baseDir + '/accounts/' + - nickname + '@' + domain + '/.hideLikeButton'): + if os.path.isfile(accountDir + '/.hideLikeButton'): hideLikeButton = 'checked' mediaInstance = getConfigParam(baseDir, "mediaInstance") diff --git a/webapp_question.py b/webapp_question.py index ba04dae62..bf198642e 100644 --- a/webapp_question.py +++ b/webapp_question.py @@ -10,6 +10,7 @@ __module_group__ = "Web Interface" import os from question import isQuestion from utils import removeIdEnding +from utils import acctDir def insertQuestion(baseDir: str, translate: {}, @@ -30,7 +31,7 @@ def insertQuestion(baseDir: str, translate: {}, pageNumberStr = '?page=' + str(pageNumber) votesFilename = \ - baseDir + '/accounts/' + nickname + '@' + domain + '/questions.txt' + acctDir(baseDir, nickname, domain) + '/questions.txt' showQuestionResults = False if os.path.isfile(votesFilename): diff --git a/webapp_search.py b/webapp_search.py index 9d7a4d753..9f2202add 100644 --- a/webapp_search.py +++ b/webapp_search.py @@ -23,6 +23,7 @@ from utils import isPublicPost from utils import firstParagraphFromString from utils import searchBoxPosts from utils import getAltPath +from utils import acctDir from skills import noOfActorSkills from skills import getSkillsFromList from categories import getHashtagCategory @@ -658,7 +659,8 @@ def htmlHashtagSearch(cssCache: {}, # check that the directory for the nickname exists if nickname: - if not os.path.isdir(baseDir + '/accounts/' + nickname + '@' + domain): + accountDir = acctDir(baseDir, nickname, domain) + if not os.path.isdir(accountDir): nickname = None # read the index @@ -835,8 +837,8 @@ def rssHashtagSearch(nickname: str, domain: str, port: int, # check that the directory for the nickname exists if nickname: - if not os.path.isdir(baseDir + '/accounts/' + - nickname + '@' + domain): + accountDir = acctDir(baseDir, nickname, domain) + if not os.path.isdir(accountDir): nickname = None # read the index diff --git a/webapp_timeline.py b/webapp_timeline.py index 3ab1800fd..7ade66c82 100644 --- a/webapp_timeline.py +++ b/webapp_timeline.py @@ -15,6 +15,7 @@ from utils import getConfigParam from utils import getFullDomain from utils import isEditor from utils import removeIdEnding +from utils import acctDir from follow import followerApprovalActive from person import isPersonSnoozed from markdown import markdownToHtml @@ -364,7 +365,7 @@ def htmlTimeline(cssCache: {}, defaultTimeline: str, timelineStartTime = time.time() - accountDir = baseDir + '/accounts/' + nickname + '@' + domain + accountDir = acctDir(baseDir, nickname, domain) # should the calendar icon be highlighted? newCalendarEvent = False @@ -498,8 +499,7 @@ def htmlTimeline(cssCache: {}, defaultTimeline: str, # show an icon for new follow approvals followApprovals = '' followRequestsFilename = \ - baseDir + '/accounts/' + \ - nickname + '@' + domain + '/followrequests.txt' + acctDir(baseDir, nickname, domain) + '/followrequests.txt' if os.path.isfile(followRequestsFilename): with open(followRequestsFilename, 'r') as f: for line in f: diff --git a/webapp_utils.py b/webapp_utils.py index 336eea016..5f5938365 100644 --- a/webapp_utils.py +++ b/webapp_utils.py @@ -16,6 +16,7 @@ from utils import getProtocolPrefixes from utils import loadJson from utils import getCachedPostFilename from utils import getConfigParam +from utils import acctDir from cache import storePersonInCache from content import addHtmlTags from content import replaceEmojiFromTags @@ -321,7 +322,7 @@ def scheduledPostsExist(baseDir: str, nickname: str, domain: str) -> bool: """Returns true if there are posts scheduled to be delivered """ scheduleIndexFilename = \ - baseDir + '/accounts/' + nickname + '@' + domain + '/schedule.index' + acctDir(baseDir, nickname, domain) + '/schedule.index' if not os.path.isfile(scheduleIndexFilename): return False if '#users#' in open(scheduleIndexFilename).read(): @@ -424,30 +425,30 @@ def _getImageFile(baseDir: str, name: str, directory: str, def getBannerFile(baseDir: str, nickname: str, domain: str, theme: str) -> (str, str): - return _getImageFile(baseDir, 'banner', - baseDir + '/accounts/' + nickname + '@' + domain, + accountDir = acctDir(baseDir, nickname, domain) + return _getImageFile(baseDir, 'banner', accountDir, nickname, domain, theme) def getSearchBannerFile(baseDir: str, nickname: str, domain: str, theme: str) -> (str, str): - return _getImageFile(baseDir, 'search_banner', - baseDir + '/accounts/' + nickname + '@' + domain, + accountDir = acctDir(baseDir, nickname, domain) + return _getImageFile(baseDir, 'search_banner', accountDir, nickname, domain, theme) def getLeftImageFile(baseDir: str, nickname: str, domain: str, theme: str) -> (str, str): - return _getImageFile(baseDir, 'left_col_image', - baseDir + '/accounts/' + nickname + '@' + domain, + accountDir = acctDir(baseDir, nickname, domain) + return _getImageFile(baseDir, 'left_col_image', accountDir, nickname, domain, theme) def getRightImageFile(baseDir: str, nickname: str, domain: str, theme: str) -> (str, str): + accountDir = acctDir(baseDir, nickname, domain) return _getImageFile(baseDir, 'right_col_image', - baseDir + '/accounts/' + nickname + '@' + domain, - nickname, domain, theme) + accountDir, nickname, domain, theme) def htmlHeaderWithExternalStyle(cssFilename: str, instanceTitle: str, diff --git a/webapp_welcome.py b/webapp_welcome.py index 0e970fc5b..11bca121c 100644 --- a/webapp_welcome.py +++ b/webapp_welcome.py @@ -11,6 +11,7 @@ import os from shutil import copyfile from utils import getConfigParam from utils import removeHtml +from utils import acctDir from webapp_utils import htmlHeaderWithExternalStyle from webapp_utils import htmlFooter from markdown import markdownToHtml @@ -19,7 +20,7 @@ from markdown import markdownToHtml def isWelcomeScreenComplete(baseDir: str, nickname: str, domain: str) -> bool: """Returns true if the welcome screen is complete for the given account """ - accountPath = baseDir + '/accounts/' + nickname + '@' + domain + accountPath = acctDir(baseDir, nickname, domain) if not os.path.isdir(accountPath): return completeFilename = accountPath + '/.welcome_complete' @@ -30,7 +31,7 @@ def welcomeScreenIsComplete(baseDir: str, nickname: str, domain: str) -> None: """Indicates that the welcome screen has been shown for a given account """ - accountPath = baseDir + '/accounts/' + nickname + '@' + domain + accountPath = acctDir(baseDir, nickname, domain) if not os.path.isdir(accountPath): return completeFilename = accountPath + '/.welcome_complete' diff --git a/webapp_welcome_profile.py b/webapp_welcome_profile.py index 1362aa344..76aff001a 100644 --- a/webapp_welcome_profile.py +++ b/webapp_welcome_profile.py @@ -14,6 +14,7 @@ from utils import loadJson from utils import getConfigParam from utils import getImageExtensions from utils import getImageFormats +from utils import acctDir from webapp_utils import htmlHeaderWithExternalStyle from webapp_utils import htmlFooter from markdown import markdownToHtml @@ -69,7 +70,7 @@ def htmlWelcomeProfile(baseDir: str, nickname: str, domain: str, # get the url of the avatar for ext in getImageExtensions(): avatarFilename = \ - baseDir + '/accounts/' + nickname + '@' + domain + '/avatar.' + ext + acctDir(baseDir, nickname, domain) + '/avatar.' + ext if os.path.isfile(avatarFilename): break avatarUrl = \ @@ -97,7 +98,7 @@ def htmlWelcomeProfile(baseDir: str, nickname: str, domain: str, 'name="previewAvatar">' + translate['Preview'] + ' ' profileForm += '\n' - actorFilename = baseDir + '/accounts/' + nickname + '@' + domain + '.json' + actorFilename = acctDir(baseDir, nickname, domain) + '.json' actorJson = loadJson(actorFilename) displayNickname = actorJson['name'] profileForm += '