Use with style when writing files

merge-requests/30/head
Bob Mottram 2021-06-22 13:27:10 +01:00
parent df7d650b5b
commit 25d0cd8c65
19 changed files with 240 additions and 358 deletions

View File

@ -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)

View File

@ -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: {},

207
daemon.py
View File

@ -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

View File

@ -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:

View File

@ -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

View File

@ -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,

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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,

View File

@ -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,

View File

@ -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:

View File

@ -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):

View File

@ -3883,10 +3883,8 @@ def _testSpoofGeolocation() -> None:
kmlStr += '</Document>\n'
kmlStr += '</kml>'
kmlFile = open('unittest_decoy.kml', 'w+')
if kmlFile:
with open('unittest_decoy.kml', 'w+') as kmlFile:
kmlFile.write(kmlStr)
kmlFile.close()
def _testSkills() -> None:

View File

@ -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')

View File

@ -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:

View File

@ -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

View File

@ -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,