From df7d650b5b88365526dcb4e7cda2ed3b5e3ad139 Mon Sep 17 00:00:00 2001 From: Bob Mottram Date: Tue, 22 Jun 2021 12:25:28 +0100 Subject: [PATCH 1/4] Less indentation --- cache.py | 13 +++++++------ webapp_post.py | 2 +- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/cache.py b/cache.py index e00156703..dce95453a 100644 --- a/cache.py +++ b/cache.py @@ -66,12 +66,13 @@ def storePersonInCache(baseDir: str, personUrl: str, return # store to file - if allowWriteToFile: - if os.path.isdir(baseDir+'/cache/actors'): - cacheFilename = baseDir + '/cache/actors/' + \ - personUrl.replace('/', '#')+'.json' - if not os.path.isfile(cacheFilename): - saveJson(personJson, cacheFilename) + if not allowWriteToFile: + return + if os.path.isdir(baseDir+'/cache/actors'): + cacheFilename = baseDir + '/cache/actors/' + \ + personUrl.replace('/', '#')+'.json' + if not os.path.isfile(cacheFilename): + saveJson(personJson, cacheFilename) def getPersonFromCache(baseDir: str, personUrl: str, personCache: {}, diff --git a/webapp_post.py b/webapp_post.py index f1f845b73..584817a2e 100644 --- a/webapp_post.py +++ b/webapp_post.py @@ -161,7 +161,7 @@ def _saveIndividualPostAsHtmlToCache(baseDir: str, fp.write(postHtml) return True except Exception as e: - print('ERROR: saving post to cache ' + str(e)) + print('ERROR: saving post to cache, ' + str(e)) return False From 25d0cd8c65919388c84098359bea861b38ceb10c Mon Sep 17 00:00:00 2001 From: Bob Mottram Date: Tue, 22 Jun 2021 13:27:10 +0100 Subject: [PATCH 2/4] Use with style when writing files --- blocking.py | 21 ++--- bookmarks.py | 8 +- daemon.py | 207 ++++++++++++++++++++-------------------------- desktop_client.py | 4 +- filters.py | 10 +-- follow.py | 27 +++--- happening.py | 51 +++++------- inbox.py | 32 ++----- manualapprove.py | 121 ++++++++++++++------------- newsdaemon.py | 16 +--- person.py | 35 +++----- posts.py | 24 ++---- question.py | 8 +- schedule.py | 4 +- tests.py | 4 +- theme.py | 9 +- utils.py | 9 +- webapp_post.py | 4 +- webapp_welcome.py | 4 +- 19 files changed, 240 insertions(+), 358 deletions(-) diff --git a/blocking.py b/blocking.py index 86a6c052d..1ef3bed20 100644 --- a/blocking.py +++ b/blocking.py @@ -39,10 +39,8 @@ def addGlobalBlock(baseDir: str, if blockHandle in open(blockingFilename).read(): return False # block an account handle or domain - blockFile = open(blockingFilename, "a+") - if blockFile: + with open(blockingFilename, 'a+') as blockFile: blockFile.write(blockHandle + '\n') - blockFile.close() else: blockHashtag = blockNickname # is the hashtag already blocked? @@ -50,10 +48,8 @@ def addGlobalBlock(baseDir: str, if blockHashtag + '\n' in open(blockingFilename).read(): return False # block a hashtag - blockFile = open(blockingFilename, "a+") - if blockFile: + with open(blockingFilename, 'a+') as blockFile: blockFile.write(blockHashtag + '\n') - blockFile.close() return True @@ -69,9 +65,8 @@ def addBlock(baseDir: str, nickname: str, domain: str, if os.path.isfile(blockingFilename): if blockHandle in open(blockingFilename).read(): return False - blockFile = open(blockingFilename, "a+") - blockFile.write(blockHandle + '\n') - blockFile.close() + with open(blockingFilename, 'a+') as blockFile: + blockFile.write(blockHandle + '\n') return True @@ -493,10 +488,8 @@ def mutePost(baseDir: str, nickname: str, domain: str, port: int, if os.path.isfile(cachedPostFilename): os.remove(cachedPostFilename) - muteFile = open(postFilename + '.muted', 'w+') - if muteFile: + with open(postFilename + '.muted', 'w+') as muteFile: muteFile.write('\n') - muteFile.close() print('MUTE: ' + postFilename + '.muted file added') # if the post is in the recent posts cache then mark it as muted @@ -751,12 +744,10 @@ def setBrochMode(baseDir: str, domainFull: str, enabled: bool) -> None: break # write the allow file - allowFile = open(allowFilename, "w+") - if allowFile: + with open(allowFilename, 'w+') as allowFile: allowFile.write(domainFull + '\n') for d in allowedDomains: allowFile.write(d + '\n') - allowFile.close() print('Broch mode enabled') setConfigParam(baseDir, "brochMode", enabled) diff --git a/bookmarks.py b/bookmarks.py index 58a772b3d..9eece3f02 100644 --- a/bookmarks.py +++ b/bookmarks.py @@ -61,10 +61,8 @@ def undoBookmarksCollectionEntry(recentPostsCache: {}, indexStr = '' with open(bookmarksIndexFilename, 'r') as indexFile: indexStr = indexFile.read().replace(bookmarkIndex + '\n', '') - bookmarksIndexFile = open(bookmarksIndexFilename, 'w+') - if bookmarksIndexFile: + with open(bookmarksIndexFilename, 'w+') as bookmarksIndexFile: bookmarksIndexFile.write(indexStr) - bookmarksIndexFile.close() if not postJsonObject.get('type'): return @@ -219,10 +217,8 @@ def updateBookmarksCollection(recentPostsCache: {}, print('WARN: Failed to write entry to bookmarks index ' + bookmarksIndexFilename + ' ' + str(e)) else: - bookmarksIndexFile = open(bookmarksIndexFilename, 'w+') - if bookmarksIndexFile: + with open(bookmarksIndexFilename, 'w+') as bookmarksIndexFile: bookmarksIndexFile.write(bookmarkIndex + '\n') - bookmarksIndexFile.close() def bookmark(recentPostsCache: {}, diff --git a/daemon.py b/daemon.py index 223eace39..34fd4cac2 100644 --- a/daemon.py +++ b/daemon.py @@ -431,10 +431,8 @@ class PubServer(BaseHTTPRequestHandler): self.server.maxReplies, self.server.debug) # record the vote - votesFile = open(votesFilename, 'a+') - if votesFile: + with open(votesFilename, 'a+') as votesFile: votesFile.write(messageId + '\n') - votesFile.close() # ensure that the cached post is removed if it exists, # so that it then will be recreated @@ -2104,10 +2102,9 @@ class PubServer(BaseHTTPRequestHandler): refreshNewswire(self.server.baseDir) else: if os.path.isdir(accountDir): - noNewswireFile = open(newswireBlockedFilename, "w+") - if noNewswireFile: + nwFilename = newswireBlockedFilename + with open(nwFilename, 'w+') as noNewswireFile: noNewswireFile.write('\n') - noNewswireFile.close() refreshNewswire(self.server.baseDir) usersPathStr = \ usersPath + '/' + self.server.defaultTimeline + \ @@ -2140,10 +2137,9 @@ class PubServer(BaseHTTPRequestHandler): refreshNewswire(self.server.baseDir) else: if os.path.isdir(accountDir): - noFeaturesFile = open(featuresBlockedFilename, "w+") - if noFeaturesFile: + featFilename = featuresBlockedFilename + with open(featFilename, 'w+') as noFeaturesFile: noFeaturesFile.write('\n') - noFeaturesFile.close() refreshNewswire(self.server.baseDir) usersPathStr = \ usersPath + '/' + self.server.defaultTimeline + \ @@ -2175,10 +2171,9 @@ class PubServer(BaseHTTPRequestHandler): os.remove(newswireModFilename) else: if os.path.isdir(accountDir): - modNewswireFile = open(newswireModFilename, "w+") - if modNewswireFile: + nwFilename = newswireModFilename + with open(nwFilename, 'w+') as modNewswireFile: modNewswireFile.write('\n') - modNewswireFile.close() usersPathStr = \ usersPath + '/' + self.server.defaultTimeline + \ '?page=' + str(pageNumber) @@ -3459,10 +3454,8 @@ class PubServer(BaseHTTPRequestHandler): if fields.get('editedLinks'): linksStr = fields['editedLinks'] - linksFile = open(linksFilename, "w+") - if linksFile: + with open(linksFilename, 'w+') as linksFile: linksFile.write(linksStr) - linksFile.close() else: if os.path.isfile(linksFilename): os.remove(linksFilename) @@ -3474,10 +3467,8 @@ class PubServer(BaseHTTPRequestHandler): aboutStr = fields['editedAbout'] if not dangerousMarkup(aboutStr, allowLocalNetworkAccess): - aboutFile = open(aboutFilename, "w+") - if aboutFile: + with open(aboutFilename, 'w+') as aboutFile: aboutFile.write(aboutStr) - aboutFile.close() else: if os.path.isfile(aboutFilename): os.remove(aboutFilename) @@ -3486,10 +3477,8 @@ class PubServer(BaseHTTPRequestHandler): TOSStr = fields['editedTOS'] if not dangerousMarkup(TOSStr, allowLocalNetworkAccess): - TOSFile = open(TOSFilename, "w+") - if TOSFile: + with open(TOSFilename, 'w+') as TOSFile: TOSFile.write(TOSStr) - TOSFile.close() else: if os.path.isfile(TOSFilename): os.remove(TOSFilename) @@ -3664,10 +3653,8 @@ class PubServer(BaseHTTPRequestHandler): extractTextFieldsInPOST(postBytes, boundary, debug) if fields.get('editedNewswire'): newswireStr = fields['editedNewswire'] - newswireFile = open(newswireFilename, "w+") - if newswireFile: + with open(newswireFilename, 'w+') as newswireFile: newswireFile.write(newswireStr) - newswireFile.close() else: if os.path.isfile(newswireFilename): os.remove(newswireFilename) @@ -3698,10 +3685,8 @@ class PubServer(BaseHTTPRequestHandler): newswireTrusted = fields['trustedNewswire'] if not newswireTrusted.endswith('\n'): newswireTrusted += '\n' - trustFile = open(newswireTrustedFilename, "w+") - if trustFile: + with open(newswireTrustedFilename, 'w+') as trustFile: trustFile.write(newswireTrusted) - trustFile.close() else: if os.path.isfile(newswireTrustedFilename): os.remove(newswireTrustedFilename) @@ -3787,10 +3772,8 @@ class PubServer(BaseHTTPRequestHandler): citationsStr += citationDate + '\n' # save citations dates, so that they can be added when # reloading the newblog screen - citationsFile = open(citationsFilename, "w+") - if citationsFile: + with open(citationsFilename, 'w+') as citationsFile: citationsFile.write(citationsStr) - citationsFile.close() # redirect back to the default timeline self._redirect_headers(actorStr + '/newblog', @@ -4710,17 +4693,16 @@ class PubServer(BaseHTTPRequestHandler): clearModeratorStatus(baseDir) if ',' in fields['moderators']: # if the list was given as comma separated - modFile = open(moderatorsFile, "w+") - mods = fields['moderators'].split(',') - for modNick in mods: - modNick = modNick.strip() - modDir = baseDir + \ - '/accounts/' + modNick + \ - '@' + domain - if os.path.isdir(modDir): - modFile.write(modNick + '\n') - modFile.close() mods = fields['moderators'].split(',') + with open(moderatorsFile, 'w+') as modFile: + for modNick in mods: + modNick = modNick.strip() + modDir = baseDir + \ + '/accounts/' + modNick + \ + '@' + domain + if os.path.isdir(modDir): + modFile.write(modNick + '\n') + for modNick in mods: modNick = modNick.strip() modDir = baseDir + \ @@ -4732,18 +4714,17 @@ class PubServer(BaseHTTPRequestHandler): 'moderator') else: # nicknames on separate lines - modFile = open(moderatorsFile, "w+") - mods = fields['moderators'].split('\n') - for modNick in mods: - modNick = modNick.strip() - modDir = \ - baseDir + \ - '/accounts/' + modNick + \ - '@' + domain - if os.path.isdir(modDir): - modFile.write(modNick + '\n') - modFile.close() mods = fields['moderators'].split('\n') + with open(moderatorsFile, 'w+') as modFile: + for modNick in mods: + modNick = modNick.strip() + modDir = \ + baseDir + \ + '/accounts/' + modNick + \ + '@' + domain + if os.path.isdir(modDir): + modFile.write(modNick + '\n') + for modNick in mods: modNick = modNick.strip() modDir = \ @@ -4766,17 +4747,16 @@ class PubServer(BaseHTTPRequestHandler): clearEditorStatus(baseDir) if ',' in fields['editors']: # if the list was given as comma separated - edFile = open(editorsFile, "w+") - eds = fields['editors'].split(',') - for edNick in eds: - edNick = edNick.strip() - edDir = baseDir + \ - '/accounts/' + edNick + \ - '@' + domain - if os.path.isdir(edDir): - edFile.write(edNick + '\n') - edFile.close() eds = fields['editors'].split(',') + with open(editorsFile, 'w+') as edFile: + for edNick in eds: + edNick = edNick.strip() + edDir = baseDir + \ + '/accounts/' + edNick + \ + '@' + domain + if os.path.isdir(edDir): + edFile.write(edNick + '\n') + for edNick in eds: edNick = edNick.strip() edDir = baseDir + \ @@ -4788,18 +4768,17 @@ class PubServer(BaseHTTPRequestHandler): 'editor') else: # nicknames on separate lines - edFile = open(editorsFile, "w+") - eds = fields['editors'].split('\n') - for edNick in eds: - edNick = edNick.strip() - edDir = \ - baseDir + \ - '/accounts/' + edNick + \ - '@' + domain - if os.path.isdir(edDir): - edFile.write(edNick + '\n') - edFile.close() eds = fields['editors'].split('\n') + with open(editorsFile, 'w+') as edFile: + for edNick in eds: + edNick = edNick.strip() + edDir = \ + baseDir + \ + '/accounts/' + edNick + \ + '@' + domain + if os.path.isdir(edDir): + edFile.write(edNick + '\n') + for edNick in eds: edNick = edNick.strip() edDir = \ @@ -4822,17 +4801,16 @@ class PubServer(BaseHTTPRequestHandler): clearCounselorStatus(baseDir) if ',' in fields['counselors']: # if the list was given as comma separated - edFile = open(counselorsFile, "w+") - eds = fields['counselors'].split(',') - for edNick in eds: - edNick = edNick.strip() - edDir = baseDir + \ - '/accounts/' + edNick + \ - '@' + domain - if os.path.isdir(edDir): - edFile.write(edNick + '\n') - edFile.close() eds = fields['counselors'].split(',') + with open(counselorsFile, 'w+') as edFile: + for edNick in eds: + edNick = edNick.strip() + edDir = baseDir + \ + '/accounts/' + edNick + \ + '@' + domain + if os.path.isdir(edDir): + edFile.write(edNick + '\n') + for edNick in eds: edNick = edNick.strip() edDir = baseDir + \ @@ -4844,18 +4822,17 @@ class PubServer(BaseHTTPRequestHandler): 'counselor') else: # nicknames on separate lines - edFile = open(counselorsFile, "w+") - eds = fields['counselors'].split('\n') - for edNick in eds: - edNick = edNick.strip() - edDir = \ - baseDir + \ - '/accounts/' + edNick + \ - '@' + domain - if os.path.isdir(edDir): - edFile.write(edNick + '\n') - edFile.close() eds = fields['counselors'].split('\n') + with open(counselorsFile, 'w+') as edFile: + for edNick in eds: + edNick = edNick.strip() + edDir = \ + baseDir + \ + '/accounts/' + edNick + \ + '@' + domain + if os.path.isdir(edDir): + edFile.write(edNick + '\n') + for edNick in eds: edNick = edNick.strip() edDir = \ @@ -4878,17 +4855,16 @@ class PubServer(BaseHTTPRequestHandler): clearArtistStatus(baseDir) if ',' in fields['artists']: # if the list was given as comma separated - edFile = open(artistsFile, "w+") - eds = fields['artists'].split(',') - for edNick in eds: - edNick = edNick.strip() - edDir = baseDir + \ - '/accounts/' + edNick + \ - '@' + domain - if os.path.isdir(edDir): - edFile.write(edNick + '\n') - edFile.close() eds = fields['artists'].split(',') + with open(artistsFile, 'w+') as edFile: + for edNick in eds: + edNick = edNick.strip() + edDir = baseDir + \ + '/accounts/' + edNick + \ + '@' + domain + if os.path.isdir(edDir): + edFile.write(edNick + '\n') + for edNick in eds: edNick = edNick.strip() edDir = baseDir + \ @@ -4900,18 +4876,17 @@ class PubServer(BaseHTTPRequestHandler): 'artist') else: # nicknames on separate lines - edFile = open(artistsFile, "w+") - eds = fields['artists'].split('\n') - for edNick in eds: - edNick = edNick.strip() - edDir = \ - baseDir + \ - '/accounts/' + edNick + \ - '@' + domain - if os.path.isdir(edDir): - edFile.write(edNick + '\n') - edFile.close() eds = fields['artists'].split('\n') + with open(artistsFile, 'w+') as edFile: + for edNick in eds: + edNick = edNick.strip() + edDir = \ + baseDir + \ + '/accounts/' + edNick + \ + '@' + domain + if os.path.isdir(edDir): + edFile.write(edNick + '\n') + for edNick in eds: edNick = edNick.strip() edDir = \ @@ -13327,10 +13302,8 @@ class PubServer(BaseHTTPRequestHandler): self.server.baseDir + '/accounts/' + \ nickname + '@' + self.server.domain + '/.lastUsed' try: - lastUsedFile = open(lastUsedFilename, 'w+') - if lastUsedFile: + with open(lastUsedFilename, 'w+') as lastUsedFile: lastUsedFile.write(str(int(time.time()))) - lastUsedFile.close() except BaseException: pass diff --git a/desktop_client.py b/desktop_client.py index ce47c52aa..d27e3d6b3 100644 --- a/desktop_client.py +++ b/desktop_client.py @@ -175,10 +175,8 @@ def _markPostAsRead(actor: str, postId: str, postCategory: str) -> None: except Exception as e: print('WARN: Failed to mark post as read' + str(e)) else: - readFile = open(readPostsFilename, 'w+') - if readFile: + with open(readPostsFilename, 'w+') as readFile: readFile.write(postId + '\n') - readFile.close() def _hasReadPost(actor: str, postId: str, postCategory: str) -> bool: diff --git a/filters.py b/filters.py index f7dc2193b..67ca4d98d 100644 --- a/filters.py +++ b/filters.py @@ -17,9 +17,8 @@ def addFilter(baseDir: str, nickname: str, domain: str, words: str) -> bool: if os.path.isfile(filtersFilename): if words in open(filtersFilename).read(): return False - filtersFile = open(filtersFilename, "a+") - filtersFile.write(words + '\n') - filtersFile.close() + with open(filtersFilename, 'a+') as filtersFile: + filtersFile.write(words + '\n') return True @@ -35,9 +34,8 @@ def addGlobalFilter(baseDir: str, words: str) -> bool: if os.path.isfile(filtersFilename): if words in open(filtersFilename).read(): return False - filtersFile = open(filtersFilename, "a+") - filtersFile.write(words + '\n') - filtersFile.close() + with open(filtersFilename, 'a+') as filtersFile: + filtersFile.write(words + '\n') return True diff --git a/follow.py b/follow.py index f7a48ed10..b635c25c3 100644 --- a/follow.py +++ b/follow.py @@ -115,17 +115,17 @@ def _removeFromFollowBase(baseDir: str, break if not actorFound: return - approvefilenew = open(approveFollowsFilename + '.new', 'w+') - with open(approveFollowsFilename, 'r') as approvefile: - if not acceptDenyActor: - for approveHandle in approvefile: - if not approveHandle.startswith(acceptOrDenyHandle): - approvefilenew.write(approveHandle) - else: - for approveHandle in approvefile: - if acceptDenyActor not in approveHandle: - approvefilenew.write(approveHandle) - approvefilenew.close() + with open(approveFollowsFilename + '.new', 'w+') as approvefilenew: + with open(approveFollowsFilename, 'r') as approvefile: + if not acceptDenyActor: + for approveHandle in approvefile: + if not approveHandle.startswith(acceptOrDenyHandle): + approvefilenew.write(approveHandle) + else: + for approveHandle in approvefile: + if acceptDenyActor not in approveHandle: + approvefilenew.write(approveHandle) + os.rename(approveFollowsFilename + '.new', approveFollowsFilename) @@ -765,9 +765,8 @@ def receiveFollowRequest(session, baseDir: str, httpPrefix: str, 'Failed to write entry to followers file ' + str(e)) else: - followersFile = open(followersFilename, "w+") - followersFile.write(approveHandle + '\n') - followersFile.close() + with open(followersFilename, 'w+') as followersFile: + followersFile.write(approveHandle + '\n') print('Beginning follow accept') return followedAccountAccepts(session, baseDir, httpPrefix, diff --git a/happening.py b/happening.py index f1443164a..028da1416 100644 --- a/happening.py +++ b/happening.py @@ -105,9 +105,8 @@ def saveEventPost(baseDir: str, handle: str, postId: str, tlEventsFilename + ' ' + str(e)) return False else: - tlEventsFile = open(tlEventsFilename, 'w+') - tlEventsFile.write(eventId + '\n') - tlEventsFile.close() + with open(tlEventsFilename, 'w+') as tlEventsFile: + tlEventsFile.write(eventId + '\n') # create a directory for the calendar year if not os.path.isdir(calendarPath + '/' + str(eventYear)): @@ -124,27 +123,20 @@ def saveEventPost(baseDir: str, handle: str, postId: str, return False # append the post Id to the file for the calendar month - calendarFile = open(calendarFilename, 'a+') - if not calendarFile: - return False - calendarFile.write(postId + '\n') - calendarFile.close() + with open(calendarFilename, 'a+') as calendarFile: + calendarFile.write(postId + '\n') # create a file which will trigger a notification that # a new event has been added calendarNotificationFilename = \ baseDir + '/accounts/' + handle + '/.newCalendar' - calendarNotificationFile = \ - open(calendarNotificationFilename, 'w+') - if not calendarNotificationFile: - return False - calendarNotificationFile.write('/calendar?year=' + - str(eventYear) + - '?month=' + - str(eventMonthNumber) + - '?day=' + - str(eventDayOfMonth)) - calendarNotificationFile.close() + with open(calendarNotificationFilename, 'w+') as calendarNotificationFile: + calendarNotificationFile.write('/calendar?year=' + + str(eventYear) + + '?month=' + + str(eventMonthNumber) + + '?day=' + + str(eventDayOfMonth)) return True @@ -251,10 +243,9 @@ def getTodaysEvents(baseDir: str, nickname: str, domain: str, # if some posts have been deleted then regenerate the calendar file if recreateEventsFile: - calendarFile = open(calendarFilename, 'w+') - for postId in calendarPostIds: - calendarFile.write(postId + '\n') - calendarFile.close() + with open(calendarFilename, 'w+') as calendarFile: + for postId in calendarPostIds: + calendarFile.write(postId + '\n') return events @@ -368,10 +359,9 @@ def getThisWeeksEvents(baseDir: str, nickname: str, domain: str) -> {}: # if some posts have been deleted then regenerate the calendar file if recreateEventsFile: - calendarFile = open(calendarFilename, 'w+') - for postId in calendarPostIds: - calendarFile.write(postId + '\n') - calendarFile.close() + with open(calendarFilename, 'w+') as calendarFile: + for postId in calendarPostIds: + calendarFile.write(postId + '\n') return events @@ -433,10 +423,9 @@ def getCalendarEvents(baseDir: str, nickname: str, domain: str, # if some posts have been deleted then regenerate the calendar file if recreateEventsFile: - calendarFile = open(calendarFilename, 'w+') - for postId in calendarPostIds: - calendarFile.write(postId + '\n') - calendarFile.close() + with open(calendarFilename, 'w+') as calendarFile: + for postId in calendarPostIds: + calendarFile.write(postId + '\n') return events diff --git a/inbox.py b/inbox.py index 9e9751f26..f92f8441b 100644 --- a/inbox.py +++ b/inbox.py @@ -127,10 +127,8 @@ def storeHashTags(baseDir: str, nickname: str, postJsonObject: {}) -> None: daysSinceEpoch = daysDiff.days tagline = str(daysSinceEpoch) + ' ' + nickname + ' ' + postUrl + '\n' if not os.path.isfile(tagsFilename): - tagsFile = open(tagsFilename, "w+") - if tagsFile: + with open(tagsFilename, 'w+') as tagsFile: tagsFile.write(tagline) - tagsFile.close() else: if postUrl not in open(tagsFilename).read(): try: @@ -1460,10 +1458,8 @@ def _receiveAnnounce(recentPostsCache: {}, postJsonObject, personCache, translate, lookupActor, themeName) - ttsFile = open(postFilename + '.tts', "w+") - if ttsFile: + with open(postFilename + '.tts', 'w+') as ttsFile: ttsFile.write('\n') - ttsFile.close() if debug: print('DEBUG: Obtaining actor for announce post ' + @@ -1642,15 +1638,11 @@ def populateReplies(baseDir: str, httpPrefix: str, domain: str, if numLines > maxReplies: return False if messageId not in open(postRepliesFilename).read(): - repliesFile = open(postRepliesFilename, 'a+') - if repliesFile: + with open(postRepliesFilename, 'a+') as repliesFile: repliesFile.write(messageId + '\n') - repliesFile.close() else: - repliesFile = open(postRepliesFilename, 'w+') - if repliesFile: + with open(postRepliesFilename, 'w+') as repliesFile: repliesFile.write(messageId + '\n') - repliesFile.close() return True @@ -2107,10 +2099,8 @@ def inboxUpdateIndex(boxname: str, baseDir: str, handle: str, print('WARN: Failed to write entry to index ' + str(e)) else: try: - indexFile = open(indexFilename, 'w+') - if indexFile: + with open(indexFilename, 'w+') as indexFile: indexFile.write(destinationFilename + '\n') - indexFile.close() except Exception as e: print('WARN: Failed to write initial entry to index ' + str(e)) @@ -2590,10 +2580,8 @@ def _inboxAfterInitial(recentPostsCache: {}, maxRecentPosts: int, # This enables you to ignore a threat that's getting boring if isReplyToMutedPost: print('MUTE REPLY: ' + destinationFilename) - muteFile = open(destinationFilename + '.muted', 'w+') - if muteFile: + with open(destinationFilename + '.muted', 'w+') as muteFile: muteFile.write('\n') - muteFile.close() # update the indexes for different timelines for boxname in updateIndexList: @@ -2851,10 +2839,8 @@ def _checkJsonSignature(baseDir: str, queueJson: {}) -> (bool, bool): alreadyUnknown = True if not alreadyUnknown: - unknownFile = open(unknownContextsFile, "a+") - if unknownFile: + with open(unknownContextsFile, 'a+') as unknownFile: unknownFile.write(unknownContext + '\n') - unknownFile.close() else: print('Unrecognized jsonld signature type: ' + jwebsigType) @@ -2869,10 +2855,8 @@ def _checkJsonSignature(baseDir: str, queueJson: {}) -> (bool, bool): alreadyUnknown = True if not alreadyUnknown: - unknownFile = open(unknownSignaturesFile, "a+") - if unknownFile: + with open(unknownSignaturesFile, 'a+') as unknownFile: unknownFile.write(jwebsigType + '\n') - unknownFile.close() return hasJsonSignature, jwebsigType diff --git a/manualapprove.py b/manualapprove.py index d89f23a79..dccc65320 100644 --- a/manualapprove.py +++ b/manualapprove.py @@ -41,9 +41,8 @@ def manualDenyFollowRequest(session, baseDir: str, removeFromFollowRequests(baseDir, nickname, domain, denyHandle, debug) # Store rejected follows - rejectsFile = open(rejectedFollowsFilename, "a+") - rejectsFile.write(denyHandle + '\n') - rejectsFile.close() + with open(rejectedFollowsFilename, 'a+') as rejectsFile: + rejectsFile.write(denyHandle + '\n') denyNickname = denyHandle.split('@')[0] denyDomain = \ @@ -70,13 +69,11 @@ def _approveFollowerHandle(accountDir: str, approveHandle: str) -> None: approvedFilename = accountDir + '/approved.txt' if os.path.isfile(approvedFilename): if approveHandle not in open(approvedFilename).read(): - approvedFile = open(approvedFilename, "a+") - approvedFile.write(approveHandle + '\n') - approvedFile.close() + with open(approvedFilename, 'a+') as approvedFile: + approvedFile.write(approveHandle + '\n') else: - approvedFile = open(approvedFilename, "w+") - approvedFile.write(approveHandle + '\n') - approvedFile.close() + with open(approvedFilename, 'w+') as approvedFile: + approvedFile.write(approveHandle + '\n') def manualApproveFollowRequest(session, baseDir: str, @@ -131,53 +128,60 @@ def manualApproveFollowRequest(session, baseDir: str, '" ' + approveFollowsFilename) return - approvefilenew = open(approveFollowsFilename + '.new', 'w+') - updateApprovedFollowers = False - followActivityfilename = None - with open(approveFollowsFilename, 'r') as approvefile: - for handleOfFollowRequester in approvefile: - # is this the approved follow? - if handleOfFollowRequester.startswith(approveHandleFull): - handleOfFollowRequester = \ - handleOfFollowRequester.replace('\n', '').replace('\r', '') - port2 = port - if ':' in handleOfFollowRequester: - port2Str = handleOfFollowRequester.split(':')[1] - if port2Str.isdigit(): - port2 = int(port2Str) - requestsDir = accountDir + '/requests' - followActivityfilename = \ - requestsDir + '/' + handleOfFollowRequester + '.follow' - if os.path.isfile(followActivityfilename): - followJson = loadJson(followActivityfilename) - if followJson: - approveNickname = approveHandle.split('@')[0] - approveDomain = approveHandle.split('@')[1] - approveDomain = \ - approveDomain.replace('\n', '').replace('\r', '') - approvePort = port2 - if ':' in approveDomain: - approvePort = approveDomain.split(':')[1] - approveDomain = approveDomain.split(':')[0] - print('Manual follow accept: Sending Accept for ' + - handle + ' follow request from ' + - approveNickname + '@' + approveDomain) - followedAccountAccepts(session, baseDir, httpPrefix, - nickname, domain, port, - approveNickname, approveDomain, - approvePort, - followJson['actor'], - federationList, - followJson, - sendThreads, postLog, - cachedWebfingers, personCache, - debug, projectVersion, False) - updateApprovedFollowers = True - else: - # this isn't the approved follow so it will remain - # in the requests file - approvefilenew.write(handleOfFollowRequester) - approvefilenew.close() + with open(approveFollowsFilename + '.new', 'w+') as approvefilenew: + updateApprovedFollowers = False + followActivityfilename = None + with open(approveFollowsFilename, 'r') as approvefile: + for handleOfFollowRequester in approvefile: + # is this the approved follow? + if handleOfFollowRequester.startswith(approveHandleFull): + handleOfFollowRequester = \ + handleOfFollowRequester.replace('\n', '') + handleOfFollowRequester = \ + handleOfFollowRequester.replace('\r', '') + port2 = port + if ':' in handleOfFollowRequester: + port2Str = handleOfFollowRequester.split(':')[1] + if port2Str.isdigit(): + port2 = int(port2Str) + requestsDir = accountDir + '/requests' + followActivityfilename = \ + requestsDir + '/' + handleOfFollowRequester + '.follow' + if os.path.isfile(followActivityfilename): + followJson = loadJson(followActivityfilename) + if followJson: + approveNickname = approveHandle.split('@')[0] + approveDomain = approveHandle.split('@')[1] + approveDomain = \ + approveDomain.replace('\n', '') + approveDomain = \ + approveDomain.replace('\r', '') + approvePort = port2 + if ':' in approveDomain: + approvePort = approveDomain.split(':')[1] + approveDomain = approveDomain.split(':')[0] + print('Manual follow accept: Sending Accept for ' + + handle + ' follow request from ' + + approveNickname + '@' + approveDomain) + followedAccountAccepts(session, baseDir, + httpPrefix, + nickname, domain, port, + approveNickname, + approveDomain, + approvePort, + followJson['actor'], + federationList, + followJson, + sendThreads, postLog, + cachedWebfingers, + personCache, + debug, + projectVersion, False) + updateApprovedFollowers = True + else: + # this isn't the approved follow so it will remain + # in the requests file + approvefilenew.write(handleOfFollowRequester) followersFilename = accountDir + '/followers.txt' if updateApprovedFollowers: @@ -201,9 +205,8 @@ def manualApproveFollowRequest(session, baseDir: str, else: print('Manual follow accept: first follower accepted for ' + handle + ' is ' + approveHandleFull) - followersFile = open(followersFilename, "w+") - followersFile.write(approveHandleFull + '\n') - followersFile.close() + with open(followersFilename, 'w+') as followersFile: + followersFile.write(approveHandleFull + '\n') # only update the follow requests file if the follow is confirmed to be # in followers.txt diff --git a/newsdaemon.py b/newsdaemon.py index bc8e4f5f0..79431c794 100644 --- a/newsdaemon.py +++ b/newsdaemon.py @@ -55,19 +55,15 @@ def _updateFeedsOutboxIndex(baseDir: str, domain: str, postId: str) -> None: print('WARN: Failed to write entry to feeds posts index ' + indexFilename + ' ' + str(e)) else: - feedsFile = open(indexFilename, 'w+') - if feedsFile: + with open(indexFilename, 'w+') as feedsFile: feedsFile.write(postId + '\n') - feedsFile.close() def _saveArrivedTime(baseDir: str, postFilename: str, arrived: str) -> None: """Saves the time when an rss post arrived to a file """ - arrivedFile = open(postFilename + '.arrived', 'w+') - if arrivedFile: + with open(postFilename + '.arrived', 'w+') as arrivedFile: arrivedFile.write(arrived) - arrivedFile.close() def _removeControlCharacters(content: str) -> str: @@ -435,15 +431,11 @@ def _createNewsMirror(baseDir: str, domain: str, # append the post Id number to the index file if os.path.isfile(mirrorIndexFilename): - indexFile = open(mirrorIndexFilename, "a+") - if indexFile: + with open(mirrorIndexFilename, 'a+') as indexFile: indexFile.write(postIdNumber + '\n') - indexFile.close() else: - indexFile = open(mirrorIndexFilename, "w+") - if indexFile: + with open(mirrorIndexFilename, 'w+') as indexFile: indexFile.write(postIdNumber + '\n') - indexFile.close() return True diff --git a/person.py b/person.py index 0771bd115..401a4c00b 100644 --- a/person.py +++ b/person.py @@ -879,13 +879,13 @@ def reenableAccount(baseDir: str, nickname: str) -> None: """ suspendedFilename = baseDir + '/accounts/suspended.txt' if os.path.isfile(suspendedFilename): + lines = [] with open(suspendedFilename, "r") as f: lines = f.readlines() - suspendedFile = open(suspendedFilename, "w+") - for suspended in lines: - if suspended.strip('\n').strip('\r') != nickname: - suspendedFile.write(suspended) - suspendedFile.close() + with open(suspendedFilename, 'w+') as suspendedFile: + for suspended in lines: + if suspended.strip('\n').strip('\r') != nickname: + suspendedFile.write(suspended) def suspendAccount(baseDir: str, nickname: str, domain: str) -> None: @@ -923,15 +923,11 @@ def suspendAccount(baseDir: str, nickname: str, domain: str) -> None: for suspended in lines: if suspended.strip('\n').strip('\r') == nickname: return - suspendedFile = open(suspendedFilename, 'a+') - if suspendedFile: + with open(suspendedFilename, 'a+') as suspendedFile: suspendedFile.write(nickname + '\n') - suspendedFile.close() else: - suspendedFile = open(suspendedFilename, 'w+') - if suspendedFile: + with open(suspendedFilename, 'w+') as suspendedFile: suspendedFile.write(nickname + '\n') - suspendedFile.close() def canRemovePost(baseDir: str, nickname: str, @@ -983,14 +979,13 @@ def _removeTagsForNickname(baseDir: str, nickname: str, continue if matchStr not in open(tagFilename).read(): continue + lines = [] with open(tagFilename, "r") as f: lines = f.readlines() - tagFile = open(tagFilename, "w+") - if tagFile: + with open(tagFilename, 'w+') as tagFile: for tagline in lines: if matchStr not in tagline: tagFile.write(tagline) - tagFile.close() def removeAccount(baseDir: str, nickname: str, @@ -1132,10 +1127,8 @@ def isPersonSnoozed(baseDir: str, nickname: str, domain: str, with open(snoozedFilename, 'r') as snoozedFile: content = snoozedFile.read().replace(replaceStr, '') if content: - writeSnoozedFile = open(snoozedFilename, 'w+') - if writeSnoozedFile: + with open(snoozedFilename, 'w+') as writeSnoozedFile: writeSnoozedFile.write(content) - writeSnoozedFile.close() if snoozeActor + ' ' in open(snoozedFilename).read(): return True @@ -1154,11 +1147,9 @@ def personSnooze(baseDir: str, nickname: str, domain: str, if os.path.isfile(snoozedFilename): if snoozeActor + ' ' in open(snoozedFilename).read(): return - snoozedFile = open(snoozedFilename, "a+") - if snoozedFile: + with open(snoozedFilename, 'a+') as snoozedFile: snoozedFile.write(snoozeActor + ' ' + str(int(time.time())) + '\n') - snoozedFile.close() def personUnsnooze(baseDir: str, nickname: str, domain: str, @@ -1185,10 +1176,8 @@ def personUnsnooze(baseDir: str, nickname: str, domain: str, with open(snoozedFilename, 'r') as snoozedFile: content = snoozedFile.read().replace(replaceStr, '') if content: - writeSnoozedFile = open(snoozedFilename, 'w+') - if writeSnoozedFile: + with open(snoozedFilename, 'w+') as writeSnoozedFile: writeSnoozedFile.write(content) - writeSnoozedFile.close() def setPersonNotes(baseDir: str, nickname: str, domain: str, diff --git a/posts.py b/posts.py index 5b54e0c8c..a5b562d4b 100644 --- a/posts.py +++ b/posts.py @@ -728,10 +728,8 @@ def _updateHashtagsIndex(baseDir: str, tag: {}, newPostId: str) -> None: if not os.path.isfile(tagsFilename): # create a new tags index file - tagsFile = open(tagsFilename, "w+") - if tagsFile: + with open(tagsFilename, 'w+') as tagsFile: tagsFile.write(tagline) - tagsFile.close() else: # prepend to tags index file if tagline not in open(tagsFilename).read(): @@ -767,10 +765,8 @@ def _addSchedulePost(baseDir: str, nickname: str, domain: str, print('WARN: Failed to write entry to scheduled posts index ' + scheduleIndexFilename + ' ' + str(e)) else: - scheduleFile = open(scheduleIndexFilename, 'w+') - if scheduleFile: + with open(scheduleIndexFilename, 'w+') as scheduleFile: scheduleFile.write(indexStr + '\n') - scheduleFile.close() def _appendEventFields(newPost: {}, @@ -1194,10 +1190,8 @@ def _createPostBase(baseDir: str, nickname: str, domain: str, port: int, newPost['moderationStatus'] = 'pending' # save to index file moderationIndexFile = baseDir + '/accounts/moderation.txt' - modFile = open(moderationIndexFile, "a+") - if modFile: + with open(moderationIndexFile, 'a+') as modFile: modFile.write(newPostId + '\n') - modFile.close() # If a patch has been posted - i.e. the output from # git format-patch - then convert the activitypub type @@ -1305,10 +1299,8 @@ def pinPost(baseDir: str, nickname: str, domain: str, """ accountDir = baseDir + '/accounts/' + nickname + '@' + domain pinnedFilename = accountDir + '/pinToProfile.txt' - pinFile = open(pinnedFilename, "w+") - if pinFile: + with open(pinnedFilename, 'w+') as pinFile: pinFile.write(pinnedContent) - pinFile.close() def undoPinnedPost(baseDir: str, nickname: str, domain: str) -> None: @@ -3452,10 +3444,8 @@ def archivePostsForPerson(httpPrefix: str, nickname: str, domain: str, break # save the new index file if len(newIndex) > 0: - indexFile = open(indexFilename, 'w+') - if indexFile: + with open(indexFilename, 'w+') as indexFile: indexFile.write(newIndex) - indexFile.close() postsInBoxDict = {} postsCtr = 0 @@ -3919,10 +3909,8 @@ def _rejectAnnounce(announceFilename: str, # reject the post referenced by the announce activity object if not os.path.isfile(announceFilename + '.reject'): - rejectAnnounceFile = open(announceFilename + '.reject', "w+") - if rejectAnnounceFile: + with open(announceFilename + '.reject', 'w+') as rejectAnnounceFile: rejectAnnounceFile.write('\n') - rejectAnnounceFile.close() def downloadAnnounce(session, baseDir: str, httpPrefix: str, diff --git a/question.py b/question.py index 7b7328f44..bdf09aa9e 100644 --- a/question.py +++ b/question.py @@ -67,21 +67,17 @@ def questionUpdateVotes(baseDir: str, nickname: str, domain: str, votersFilename = questionPostFilename.replace('.json', '.voters') if not os.path.isfile(votersFilename): # create a new voters file - votersFile = open(votersFilename, 'w+') - if votersFile: + with open(votersFilename, 'w+') as votersFile: votersFile.write(replyJson['actor'] + votersFileSeparator + foundAnswer + '\n') - votersFile.close() else: if replyJson['actor'] not in open(votersFilename).read(): # append to the voters file - votersFile = open(votersFilename, "a+") - if votersFile: + with open(votersFilename, 'a+') as votersFile: votersFile.write(replyJson['actor'] + votersFileSeparator + foundAnswer + '\n') - votersFile.close() else: # change an entry in the voters file with open(votersFilename, "r") as votersFile: diff --git a/schedule.py b/schedule.py index de9a0b244..5a8275bb5 100644 --- a/schedule.py +++ b/schedule.py @@ -129,11 +129,9 @@ def _updatePostSchedule(baseDir: str, handle: str, httpd, # write the new schedule index file scheduleIndexFile = \ baseDir + '/accounts/' + handle + '/schedule.index' - scheduleFile = open(scheduleIndexFile, "w+") - if scheduleFile: + with open(scheduleIndexFile, 'w+') as scheduleFile: for line in indexLines: scheduleFile.write(line) - scheduleFile.close() def runPostSchedule(baseDir: str, httpd, maxScheduledPosts: int): diff --git a/tests.py b/tests.py index f270ae9e1..58ca52853 100644 --- a/tests.py +++ b/tests.py @@ -3883,10 +3883,8 @@ def _testSpoofGeolocation() -> None: kmlStr += '\n' kmlStr += '' - kmlFile = open('unittest_decoy.kml', 'w+') - if kmlFile: + with open('unittest_decoy.kml', 'w+') as kmlFile: kmlFile.write(kmlStr) - kmlFile.close() def _testSkills() -> None: diff --git a/theme.py b/theme.py index 7fdb0d720..def0348ce 100644 --- a/theme.py +++ b/theme.py @@ -808,9 +808,6 @@ def updateDefaultThemesList(baseDir: str) -> None: """ themeNames = getThemesList(baseDir) defaultThemesFilename = baseDir + '/defaultthemes.txt' - defaultThemesFile = open(defaultThemesFilename, "w+") - if not defaultThemesFile: - return - for name in themeNames: - defaultThemesFile.write(name + '\n') - defaultThemesFile.close() + with open(defaultThemesFilename, 'w+') as defaultThemesFile: + for name in themeNames: + defaultThemesFile.write(name + '\n') diff --git a/utils.py b/utils.py index fd159e8af..311d0e70f 100644 --- a/utils.py +++ b/utils.py @@ -43,9 +43,8 @@ def refreshNewswire(baseDir: str): refreshNewswireFilename = baseDir + '/accounts/.refresh_newswire' if os.path.isfile(refreshNewswireFilename): return - refreshFile = open(refreshNewswireFilename, 'w+') - refreshFile.write('\n') - refreshFile.close() + with open(refreshNewswireFilename, 'w+') as refreshFile: + refreshFile.write('\n') def getSHA256(msg: str): @@ -2198,10 +2197,8 @@ def rejectPostId(baseDir: str, nickname: str, domain: str, if recentPostsCache['html'].get(postUrl): del recentPostsCache['html'][postUrl] - rejectFile = open(postFilename + '.reject', "w+") - if rejectFile: + with open(postFilename + '.reject', 'w+') as rejectFile: rejectFile.write('\n') - rejectFile.close() def isDM(postJsonObject: {}) -> bool: diff --git a/webapp_post.py b/webapp_post.py index 584817a2e..b4bf0a33e 100644 --- a/webapp_post.py +++ b/webapp_post.py @@ -1332,10 +1332,8 @@ def individualPostAsHtml(allowDownloads: bool, postJsonObject, personCache, translate, postJsonObject['actor'], themeName) - ttsFile = open(announceFilename + '.tts', "w+") - if ttsFile: + with open(announceFilename + '.tts', 'w+') as ttsFile: ttsFile.write('\n') - ttsFile.close() isAnnounced = True diff --git a/webapp_welcome.py b/webapp_welcome.py index 78e1cf441..7fd59b7ae 100644 --- a/webapp_welcome.py +++ b/webapp_welcome.py @@ -34,10 +34,8 @@ def welcomeScreenIsComplete(baseDir: str, if not os.path.isdir(accountPath): return completeFilename = accountPath + '/.welcome_complete' - completeFile = open(completeFilename, 'w+') - if completeFile: + with open(completeFilename, 'w+') as completeFile: completeFile.write('\n') - completeFile.close() def htmlWelcomeScreen(baseDir: str, nickname: str, From b4783c510d4d9246f9ec922e07ae6dce3b6aca28 Mon Sep 17 00:00:00 2001 From: Bob Mottram Date: Tue, 22 Jun 2021 13:29:17 +0100 Subject: [PATCH 3/4] Spaces --- auth.py | 2 +- cache.py | 2 +- daemon.py | 4 ++-- inbox.py | 2 +- shares.py | 10 +++++----- webapp_utils.py | 2 +- 6 files changed, 11 insertions(+), 11 deletions(-) diff --git a/auth.py b/auth.py index 87b94e5e2..a73d4c3f3 100644 --- a/auth.py +++ b/auth.py @@ -126,7 +126,7 @@ def authorizeBasic(baseDir: str, path: str, authHeader: str, ') does not match the one in the Authorization header (' + nickname + ')') return False - passwordFile = baseDir+'/accounts/passwords' + passwordFile = baseDir + '/accounts/passwords' if not os.path.isfile(passwordFile): if debug: print('DEBUG: passwords file missing') diff --git a/cache.py b/cache.py index dce95453a..bf9e5a351 100644 --- a/cache.py +++ b/cache.py @@ -68,7 +68,7 @@ def storePersonInCache(baseDir: str, personUrl: str, # store to file if not allowWriteToFile: return - if os.path.isdir(baseDir+'/cache/actors'): + if os.path.isdir(baseDir + '/cache/actors'): cacheFilename = baseDir + '/cache/actors/' + \ personUrl.replace('/', '#')+'.json' if not os.path.isfile(cacheFilename): diff --git a/daemon.py b/daemon.py index 34fd4cac2..63393695f 100644 --- a/daemon.py +++ b/daemon.py @@ -1532,7 +1532,7 @@ class PubServer(BaseHTTPRequestHandler): # This produces a deterministic token based # on nick+password+salt saltFilename = \ - baseDir+'/accounts/' + \ + baseDir + '/accounts/' + \ loginNickname + '@' + domain + '/.salt' salt = createPassword(32) if os.path.isfile(saltFilename): @@ -1555,7 +1555,7 @@ class PubServer(BaseHTTPRequestHandler): self.server.tokens[loginNickname] = token loginHandle = loginNickname + '@' + domain tokenFilename = \ - baseDir+'/accounts/' + \ + baseDir + '/accounts/' + \ loginHandle + '/.token' try: with open(tokenFilename, 'w+') as fp: diff --git a/inbox.py b/inbox.py index f92f8441b..4fdc8ce04 100644 --- a/inbox.py +++ b/inbox.py @@ -189,7 +189,7 @@ def validInbox(baseDir: str, nickname: str, domain: str) -> bool: """ if ':' in domain: domain = domain.split(':')[0] - inboxDir = baseDir+'/accounts/' + nickname + '@' + domain + '/inbox' + inboxDir = baseDir + '/accounts/' + nickname + '@' + domain + '/inbox' if not os.path.isdir(inboxDir): return True for subdir, dirs, files in os.walk(inboxDir): diff --git a/shares.py b/shares.py index 4fb62daad..59e960b1f 100644 --- a/shares.py +++ b/shares.py @@ -264,8 +264,8 @@ def getSharesFeedForPerson(baseDir: str, idStr = httpPrefix + '://' + domain + '/users/' + nickname shares = { '@context': 'https://www.w3.org/ns/activitystreams', - 'first': idStr+'/shares?page=1', - 'id': idStr+'/shares', + 'first': idStr + '/shares?page=1', + 'id': idStr + '/shares', 'totalItems': str(noOfShares), 'type': 'OrderedCollection' } @@ -278,9 +278,9 @@ def getSharesFeedForPerson(baseDir: str, idStr = httpPrefix + '://' + domain + '/users/' + nickname shares = { '@context': 'https://www.w3.org/ns/activitystreams', - 'id': idStr+'/shares?page='+str(pageNumber), + 'id': idStr + '/shares?page=' + str(pageNumber), 'orderedItems': [], - 'partOf': idStr+'/shares', + 'partOf': idStr + '/shares', 'totalItems': 0, 'type': 'OrderedCollectionPage' } @@ -339,7 +339,7 @@ def sendShareViaServer(baseDir, session, "@context": "https://www.w3.org/ns/activitystreams", 'type': 'Add', 'actor': actor, - 'target': actor+'/shares', + 'target': actor + '/shares', 'object': { "type": "Offer", "displayName": displayName, diff --git a/webapp_utils.py b/webapp_utils.py index 7797d040c..79163cf19 100644 --- a/webapp_utils.py +++ b/webapp_utils.py @@ -1242,7 +1242,7 @@ def getPostAttachmentsAsHtml(postJsonObject: {}, boxName: str, translate: {}, galleryStr += \ ' ' + replyStr + announceStr + \ likeStr + bookmarkStr + \ - deleteStr + muteStr+'\n' + deleteStr + muteStr + '\n' galleryStr += ' \n' galleryStr += '
\n' galleryStr += ' ' + avatarLink + '\n' From 80f43a728a428761436311a251998d9d38d0c0a7 Mon Sep 17 00:00:00 2001 From: Bob Mottram Date: Tue, 22 Jun 2021 13:42:52 +0100 Subject: [PATCH 4/4] Spaces --- acceptreject.py | 10 +++++----- announce.py | 3 ++- auth.py | 2 +- availability.py | 4 ++-- bookmarks.py | 6 +++--- cache.py | 6 +++--- content.py | 8 ++++---- epicyon.py | 2 +- inbox.py | 2 +- person.py | 2 +- posts.py | 12 ++++++------ tests.py | 4 ++-- utils.py | 6 +++--- webapp_headerbuttons.py | 2 +- webapp_profile.py | 4 ++-- 15 files changed, 37 insertions(+), 36 deletions(-) diff --git a/acceptreject.py b/acceptreject.py index 9ce38ca9f..5bbba45ec 100644 --- a/acceptreject.py +++ b/acceptreject.py @@ -38,7 +38,7 @@ def _createAcceptReject(baseDir: str, federationList: [], newAccept = { "@context": "https://www.w3.org/ns/activitystreams", 'type': acceptType, - 'actor': httpPrefix+'://' + domain + '/users/' + nickname, + 'actor': httpPrefix + '://' + domain + '/users/' + nickname, 'to': [toUrl], 'cc': [], 'object': objectJson @@ -120,9 +120,9 @@ def _acceptFollow(baseDir: str, domain: str, messageJson: {}, print('DEBUG: unrecognized actor ' + thisActor) return else: - if not '/' + acceptedDomain+'/users/' + nickname in thisActor: + if not '/' + acceptedDomain + '/users/' + nickname in thisActor: if debug: - print('Expected: /' + acceptedDomain+'/users/' + nickname) + print('Expected: /' + acceptedDomain + '/users/' + nickname) print('Actual: ' + thisActor) print('DEBUG: unrecognized actor ' + thisActor) return @@ -134,7 +134,7 @@ def _acceptFollow(baseDir: str, domain: str, messageJson: {}, return followedDomainFull = followedDomain if port: - followedDomainFull = followedDomain+':' + str(port) + followedDomainFull = followedDomain + ':' + str(port) followedNickname = getNicknameFromActor(followedActor) if not followedNickname: print('DEBUG: no nickname found within Follow activity object ' + @@ -168,7 +168,7 @@ def _acceptFollow(baseDir: str, domain: str, messageJson: {}, else: if debug: print('DEBUG: Unable to create follow - ' + - nickname + '@' + acceptedDomain+' -> ' + + nickname + '@' + acceptedDomain + ' -> ' + followedNickname + '@' + followedDomain) diff --git a/announce.py b/announce.py index 97c9d4fb1..0f41fb0f1 100644 --- a/announce.py +++ b/announce.py @@ -198,9 +198,10 @@ def sendAnnounceViaServer(baseDir: str, session, statusNumber, published = getStatusNumber() newAnnounceId = httpPrefix + '://' + fromDomainFull + '/users/' + \ fromNickname + '/statuses/' + statusNumber + actorStr = httpPrefix + '://' + fromDomainFull + '/users/' + fromNickname newAnnounceJson = { "@context": "https://www.w3.org/ns/activitystreams", - 'actor': httpPrefix+'://'+fromDomainFull+'/users/'+fromNickname, + 'actor': actorStr, 'atomUri': newAnnounceId, 'cc': [ccUrl], 'id': newAnnounceId + '/activity', diff --git a/auth.py b/auth.py index a73d4c3f3..42cf25fa2 100644 --- a/auth.py +++ b/auth.py @@ -134,7 +134,7 @@ def authorizeBasic(baseDir: str, path: str, authHeader: str, providedPassword = plain.split(':')[1] passfile = open(passwordFile, "r") for line in passfile: - if line.startswith(nickname+':'): + if line.startswith(nickname + ':'): storedPassword = \ line.split(':')[1].replace('\n', '').replace('\r', '') success = _verifyPassword(storedPassword, providedPassword) diff --git a/availability.py b/availability.py index 9df2173bd..3cedea24a 100644 --- a/availability.py +++ b/availability.py @@ -95,8 +95,8 @@ def sendAvailabilityViaServer(baseDir: str, session, newAvailabilityJson = { 'type': 'Availability', - 'actor': httpPrefix+'://'+domainFull+'/users/'+nickname, - 'object': '"'+status+'"', + 'actor': httpPrefix + '://' + domainFull + '/users/' + nickname, + 'object': '"' + status + '"', 'to': [toUrl], 'cc': [ccUrl] } diff --git a/bookmarks.py b/bookmarks.py index 9eece3f02..a2b595d91 100644 --- a/bookmarks.py +++ b/bookmarks.py @@ -243,7 +243,7 @@ def bookmark(recentPostsCache: {}, newBookmarkJson = { "@context": "https://www.w3.org/ns/activitystreams", 'type': 'Bookmark', - 'actor': httpPrefix+'://'+fullDomain+'/users/'+nickname, + 'actor': httpPrefix + '://' + fullDomain + '/users/' + nickname, 'object': objectUrl } if ccList: @@ -302,10 +302,10 @@ def undoBookmark(recentPostsCache: {}, newUndoBookmarkJson = { "@context": "https://www.w3.org/ns/activitystreams", 'type': 'Undo', - 'actor': httpPrefix+'://'+fullDomain+'/users/'+nickname, + 'actor': httpPrefix + '://' + fullDomain + '/users/' + nickname, 'object': { 'type': 'Bookmark', - 'actor': httpPrefix+'://'+fullDomain+'/users/'+nickname, + 'actor': httpPrefix + '://' + fullDomain + '/users/' + nickname, 'object': objectUrl } } diff --git a/cache.py b/cache.py index bf9e5a351..96608524e 100644 --- a/cache.py +++ b/cache.py @@ -20,7 +20,7 @@ def _removePersonFromCache(baseDir: str, personUrl: str, """Removes an actor from the cache """ cacheFilename = baseDir + '/cache/actors/' + \ - personUrl.replace('/', '#')+'.json' + personUrl.replace('/', '#') + '.json' if os.path.isfile(cacheFilename): try: os.remove(cacheFilename) @@ -70,7 +70,7 @@ def storePersonInCache(baseDir: str, personUrl: str, return if os.path.isdir(baseDir + '/cache/actors'): cacheFilename = baseDir + '/cache/actors/' + \ - personUrl.replace('/', '#')+'.json' + personUrl.replace('/', '#') + '.json' if not os.path.isfile(cacheFilename): saveJson(personJson, cacheFilename) @@ -84,7 +84,7 @@ def getPersonFromCache(baseDir: str, personUrl: str, personCache: {}, if not personCache.get(personUrl): # does the person exist as a cached file? cacheFilename = baseDir + '/cache/actors/' + \ - personUrl.replace('/', '#')+'.json' + personUrl.replace('/', '#') + '.json' actorFilename = getFileCaseInsensitive(cacheFilename) if actorFilename: personJson = loadJson(actorFilename) diff --git a/content.py b/content.py index 22ba06f0b..79d8b4dd0 100644 --- a/content.py +++ b/content.py @@ -306,7 +306,7 @@ def _addMusicTag(content: str, tag: str) -> str: musicSites = ('soundcloud.com', 'bandcamp.com') musicSiteFound = False for site in musicSites: - if site+'/' in content: + if site + '/' in content: musicSiteFound = True break if not musicSiteFound: @@ -458,7 +458,7 @@ def _addEmoji(baseDir: str, wordStr: str, 'type': 'Image', 'url': emojiUrl }, - 'name': ':'+emoji+':', + 'name': ':' + emoji + ':', "updated": fileLastModified(emojiFilename), "id": emojiUrl.replace('.png', ''), 'type': 'Emoji' @@ -820,7 +820,7 @@ def addHtmlTags(baseDir: str, httpPrefix: str, continue elif ':' in wordStr: wordStr2 = wordStr.split(':')[1] -# print('TAG: emoji located - '+wordStr) +# print('TAG: emoji located - ' + wordStr) if not emojiDict: # emoji.json is generated so that it can be customized and # the changes will be retained even if default_emoji.json @@ -830,7 +830,7 @@ def addHtmlTags(baseDir: str, httpPrefix: str, baseDir + '/emoji/emoji.json') emojiDict = loadJson(baseDir + '/emoji/emoji.json') -# print('TAG: looking up emoji for :'+wordStr2+':') +# print('TAG: looking up emoji for :' + wordStr2 + ':') _addEmoji(baseDir, ':' + wordStr2 + ':', httpPrefix, originalDomain, replaceEmoji, hashtags, emojiDict) diff --git a/epicyon.py b/epicyon.py index a36e4af93..34baebdff 100644 --- a/epicyon.py +++ b/epicyon.py @@ -1092,7 +1092,7 @@ if args.message: toDomain = 'public' toPort = port - # ccUrl=httpPrefix+'://'+domain+'/users/'+nickname+'/followers' + # ccUrl = httpPrefix + '://' + domain + '/users/' + nickname + '/followers' ccUrl = None sendMessage = args.message followersOnly = args.followersonly diff --git a/inbox.py b/inbox.py index 4fdc8ce04..a87a15f53 100644 --- a/inbox.py +++ b/inbox.py @@ -506,7 +506,7 @@ def _inboxPostRecipientsAdd(baseDir: str, httpPrefix: str, toList: [], if domainMatch in recipient: # get the handle for the local account nickname = recipient.split(domainMatch)[1] - handle = nickname+'@'+domain + handle = nickname + '@' + domain if os.path.isdir(baseDir + '/accounts/' + handle): recipientsDict[handle] = None else: diff --git a/person.py b/person.py index 401a4c00b..44468e4de 100644 --- a/person.py +++ b/person.py @@ -131,7 +131,7 @@ def setProfileImage(baseDir: str, httpPrefix: str, nickname: str, domain: str, personJson[iconFilenameBase]['mediaType'] = mediaType personJson[iconFilenameBase]['url'] = \ httpPrefix + '://' + fullDomain + '/users/' + \ - nickname + '/'+iconFilename + nickname + '/' + iconFilename saveJson(personJson, personFilename) cmd = \ diff --git a/posts.py b/posts.py index a5b562d4b..0788f4a60 100644 --- a/posts.py +++ b/posts.py @@ -1060,7 +1060,7 @@ def _createPostBase(baseDir: str, nickname: str, domain: str, port: int, httpPrefix + '://' + domain + '/users/' + nickname + \ '/statuses/' + statusNumber + '/replies' newPostUrl = \ - httpPrefix + '://' + domain + '/@' + nickname + '/'+statusNumber + httpPrefix + '://' + domain + '/@' + nickname + '/' + statusNumber newPostAttributedTo = \ httpPrefix + '://' + domain + '/users/' + nickname newPost = { @@ -1120,7 +1120,7 @@ def _createPostBase(baseDir: str, nickname: str, domain: str, port: int, httpPrefix + '://' + domain + '/users/' + nickname + \ '/statuses/' + statusNumber + '/replies' newPostUrl = \ - httpPrefix + '://' + domain + '/@' + nickname+'/' + statusNumber + httpPrefix + '://' + domain + '/@' + nickname + '/' + statusNumber newPost = { "@context": postContext, 'id': newPostId, @@ -2896,7 +2896,7 @@ def createModeration(baseDir: str, nickname: str, domain: str, port: int, pageNumber = 1 pageStr = '?page=' + str(pageNumber) - boxUrl = httpPrefix+'://'+domain+'/users/'+nickname+'/'+boxname + boxUrl = httpPrefix + '://' + domain + '/users/' + nickname + '/' + boxname boxHeader = { '@context': 'https://www.w3.org/ns/activitystreams', 'first': boxUrl + '?page=true', @@ -3849,8 +3849,8 @@ def populateRepliesJson(baseDir: str, nickname: str, domain: str, searchFilename = \ baseDir + \ '/accounts/' + nickname + '@' + \ - domain+'/' + \ - boxname+'/' + \ + domain + '/' + \ + boxname + '/' + \ messageId2.replace('/', '#') + '.json' if os.path.isfile(searchFilename): if authorized or \ @@ -3877,7 +3877,7 @@ def populateRepliesJson(baseDir: str, nickname: str, domain: str, searchFilename = \ baseDir + \ '/accounts/inbox@' + \ - domain+'/inbox/' + \ + domain + '/inbox/' + \ messageId2.replace('/', '#') + '.json' if os.path.isfile(searchFilename): if authorized or \ diff --git a/tests.py b/tests.py index 58ca52853..b5e8c9b01 100644 --- a/tests.py +++ b/tests.py @@ -2045,7 +2045,7 @@ def _testAddEmoji(): tags.append(tag) content = contentModified contentModified = replaceEmojiFromTags(content, tags, 'content') - # print('contentModified: '+contentModified) + # print('contentModified: ' + contentModified) assert contentModified == '

Emoji 🍋 🍓 🍌

' os.chdir(baseDirOriginal) @@ -2124,7 +2124,7 @@ def _testRecentPostsCache(): htmlStr = '' for i in range(5): postJsonObject = { - "id": "https://somesite.whatever/users/someuser/statuses/"+str(i) + "id": "https://somesite.whatever/users/someuser/statuses/" + str(i) } updateRecentPostsCache(recentPostsCache, maxRecentPosts, postJsonObject, htmlStr) diff --git a/utils.py b/utils.py index 311d0e70f..47a1b392f 100644 --- a/utils.py +++ b/utils.py @@ -1563,10 +1563,10 @@ def getCachedPostFilename(baseDir: str, nickname: str, domain: str, """ cachedPostDir = getCachedPostDirectory(baseDir, nickname, domain) if not os.path.isdir(cachedPostDir): - # print('ERROR: invalid html cache directory '+cachedPostDir) + # print('ERROR: invalid html cache directory ' + cachedPostDir) return None if '@' not in cachedPostDir: - # print('ERROR: invalid html cache directory '+cachedPostDir) + # print('ERROR: invalid html cache directory ' + cachedPostDir) return None cachedPostId = removeIdEnding(postJsonObject['id']) cachedPostFilename = cachedPostDir + '/' + cachedPostId.replace('/', '#') @@ -1866,7 +1866,7 @@ def undoLikesCollectionEntry(recentPostsCache: {}, if not postJsonObject.get('object'): if debug: pprint(postJsonObject) - print('DEBUG: post '+objectUrl+' has no object') + print('DEBUG: post ' + objectUrl + ' has no object') return if not isinstance(postJsonObject['object'], dict): return diff --git a/webapp_headerbuttons.py b/webapp_headerbuttons.py index 61c239c1c..825dcc302 100644 --- a/webapp_headerbuttons.py +++ b/webapp_headerbuttons.py @@ -116,7 +116,7 @@ def headerButtonsTimeline(defaultTimeline: str, tlStr += \ '' if not featuresHeader: diff --git a/webapp_profile.py b/webapp_profile.py index 5a08d2659..d73a0601f 100644 --- a/webapp_profile.py +++ b/webapp_profile.py @@ -534,7 +534,7 @@ def htmlProfile(rssIconAtTop: bool, if xmppAddress: donateSection += \ '

' + translate['XMPP'] + ': '+xmppAddress + '

\n' + xmppAddress + '">' + xmppAddress + '

\n' if matrixAddress: donateSection += \ '

' + translate['Matrix'] + ': ' + matrixAddress + '

\n' @@ -1675,7 +1675,7 @@ def htmlEditProfile(cssCache: {}, translate: {}, baseDir: str, path: str, translate['Matrix'] + '
\n' editProfileForm += \ ' \n' + matrixAddress + '">\n' editProfileForm += '
\n' editProfileForm += \