Merge branch 'main' of gitlab.com:bashrc2/epicyon

main
Bob Mottram 2021-11-25 22:45:24 +00:00
commit 7101e26657
39 changed files with 745 additions and 589 deletions

65
auth.py
View File

@ -163,21 +163,39 @@ def storeBasicCredentials(baseDir: str, nickname: str, password: str) -> bool:
storeStr = nickname + ':' + _hashPassword(password) storeStr = nickname + ':' + _hashPassword(password)
if os.path.isfile(passwordFile): if os.path.isfile(passwordFile):
if nickname + ':' in open(passwordFile).read(): if nickname + ':' in open(passwordFile).read():
with open(passwordFile, 'r') as fin: try:
with open(passwordFile + '.new', 'w+') as fout: with open(passwordFile, 'r') as fin:
for line in fin: with open(passwordFile + '.new', 'w+') as fout:
if not line.startswith(nickname + ':'): for line in fin:
fout.write(line) if not line.startswith(nickname + ':'):
else: fout.write(line)
fout.write(storeStr + '\n') else:
os.rename(passwordFile + '.new', passwordFile) fout.write(storeStr + '\n')
except OSError as e:
print('EX: unable to save password ' + passwordFile +
' ' + str(e))
return False
try:
os.rename(passwordFile + '.new', passwordFile)
except OSError:
print('EX: unable to save password 2')
return False
else: else:
# append to password file # append to password file
with open(passwordFile, 'a+') as passfile: try:
passfile.write(storeStr + '\n') with open(passwordFile, 'a+') as passfile:
passfile.write(storeStr + '\n')
except OSError:
print('EX: unable to append password')
return False
else: else:
with open(passwordFile, 'w+') as passfile: try:
passfile.write(storeStr + '\n') with open(passwordFile, 'w+') as passfile:
passfile.write(storeStr + '\n')
except OSError:
print('EX: unable to create password file')
return False
return True return True
@ -187,12 +205,21 @@ def removePassword(baseDir: str, nickname: str) -> None:
""" """
passwordFile = baseDir + '/accounts/passwords' passwordFile = baseDir + '/accounts/passwords'
if os.path.isfile(passwordFile): if os.path.isfile(passwordFile):
with open(passwordFile, 'r') as fin: try:
with open(passwordFile + '.new', 'w+') as fout: with open(passwordFile, 'r') as fin:
for line in fin: with open(passwordFile + '.new', 'w+') as fout:
if not line.startswith(nickname + ':'): for line in fin:
fout.write(line) if not line.startswith(nickname + ':'):
os.rename(passwordFile + '.new', passwordFile) fout.write(line)
except OSError as e:
print('EX: unable to remove password from file ' + str(e))
return
try:
os.rename(passwordFile + '.new', passwordFile)
except OSError:
print('EX: unable to remove password from file 2')
return
def authorize(baseDir: str, path: str, authHeader: str, debug: bool) -> bool: def authorize(baseDir: str, path: str, authHeader: str, debug: bool) -> bool:
@ -254,6 +281,6 @@ def recordLoginFailure(baseDir: str, ipAddress: str,
'Disconnecting invalid user epicyon ' + 'Disconnecting invalid user epicyon ' +
ipAddress + ' port 443: ' + ipAddress + ' port 443: ' +
'Too many authentication failures [preauth]\n') 'Too many authentication failures [preauth]\n')
except BaseException: except OSError:
print('EX: recordLoginFailure failed ' + str(failureLog)) print('EX: recordLoginFailure failed ' + str(failureLog))
pass pass

View File

@ -49,8 +49,12 @@ def addGlobalBlock(baseDir: str,
if blockHandle in open(blockingFilename).read(): if blockHandle in open(blockingFilename).read():
return False return False
# block an account handle or domain # block an account handle or domain
with open(blockingFilename, 'a+') as blockFile: try:
blockFile.write(blockHandle + '\n') with open(blockingFilename, 'a+') as blockFile:
blockFile.write(blockHandle + '\n')
except OSError:
print('EX: unable to save blocked handle ' + blockHandle)
return False
else: else:
blockHashtag = blockNickname blockHashtag = blockNickname
# is the hashtag already blocked? # is the hashtag already blocked?
@ -58,8 +62,12 @@ def addGlobalBlock(baseDir: str,
if blockHashtag + '\n' in open(blockingFilename).read(): if blockHashtag + '\n' in open(blockingFilename).read():
return False return False
# block a hashtag # block a hashtag
with open(blockingFilename, 'a+') as blockFile: try:
blockFile.write(blockHashtag + '\n') with open(blockingFilename, 'a+') as blockFile:
blockFile.write(blockHashtag + '\n')
except OSError:
print('EX: unable to save blocked hashtag ' + blockHashtag)
return False
return True return True
@ -83,25 +91,47 @@ def addBlock(baseDir: str, nickname: str, domain: str,
if os.path.isfile(followingFilename): if os.path.isfile(followingFilename):
if blockHandle + '\n' in open(followingFilename).read(): if blockHandle + '\n' in open(followingFilename).read():
followingStr = '' followingStr = ''
with open(followingFilename, 'r') as followingFile: try:
followingStr = followingFile.read() with open(followingFilename, 'r') as followingFile:
followingStr = followingStr.replace(blockHandle + '\n', '') followingStr = followingFile.read()
with open(followingFilename, 'w+') as followingFile: followingStr = followingStr.replace(blockHandle + '\n', '')
followingFile.write(followingStr) except OSError:
print('EX: Unable to read following ' + followingFilename)
return False
try:
with open(followingFilename, 'w+') as followingFile:
followingFile.write(followingStr)
except OSError:
print('EX: Unable to write following ' + followingStr)
return False
# if they are a follower then remove them # if they are a follower then remove them
followersFilename = acctDir(baseDir, nickname, domain) + '/followers.txt' followersFilename = acctDir(baseDir, nickname, domain) + '/followers.txt'
if os.path.isfile(followersFilename): if os.path.isfile(followersFilename):
if blockHandle + '\n' in open(followersFilename).read(): if blockHandle + '\n' in open(followersFilename).read():
followersStr = '' followersStr = ''
with open(followersFilename, 'r') as followersFile: try:
followersStr = followersFile.read() with open(followersFilename, 'r') as followersFile:
followersStr = followersStr.replace(blockHandle + '\n', '') followersStr = followersFile.read()
with open(followersFilename, 'w+') as followersFile: followersStr = followersStr.replace(blockHandle + '\n', '')
followersFile.write(followersStr) except OSError:
print('EX: Unable to read followers ' + followersFilename)
return False
with open(blockingFilename, 'a+') as blockFile: try:
blockFile.write(blockHandle + '\n') with open(followersFilename, 'w+') as followersFile:
followersFile.write(followersStr)
except OSError:
print('EX: Unable to write followers ' + followersStr)
return False
try:
with open(blockingFilename, 'a+') as blockFile:
blockFile.write(blockHandle + '\n')
except OSError:
print('EX: unable to append block handle ' + blockHandle)
return False
return True return True
@ -116,11 +146,17 @@ def removeGlobalBlock(baseDir: str,
if os.path.isfile(unblockingFilename): if os.path.isfile(unblockingFilename):
if unblockHandle in open(unblockingFilename).read(): if unblockHandle in open(unblockingFilename).read():
with open(unblockingFilename, 'r') as fp: with open(unblockingFilename, 'r') as fp:
with open(unblockingFilename + '.new', 'w+') as fpnew: try:
for line in fp: with open(unblockingFilename + '.new', 'w+') as fpnew:
handle = line.replace('\n', '').replace('\r', '') for line in fp:
if unblockHandle not in line: handle = \
fpnew.write(handle + '\n') line.replace('\n', '').replace('\r', '')
if unblockHandle not in line:
fpnew.write(handle + '\n')
except OSError as e:
print('EX: failed to remove global block ' +
unblockingFilename + ' ' + str(e))
return False
if os.path.isfile(unblockingFilename + '.new'): if os.path.isfile(unblockingFilename + '.new'):
os.rename(unblockingFilename + '.new', unblockingFilename) os.rename(unblockingFilename + '.new', unblockingFilename)
return True return True
@ -129,12 +165,17 @@ def removeGlobalBlock(baseDir: str,
if os.path.isfile(unblockingFilename): if os.path.isfile(unblockingFilename):
if unblockHashtag + '\n' in open(unblockingFilename).read(): if unblockHashtag + '\n' in open(unblockingFilename).read():
with open(unblockingFilename, 'r') as fp: with open(unblockingFilename, 'r') as fp:
with open(unblockingFilename + '.new', 'w+') as fpnew: try:
for line in fp: with open(unblockingFilename + '.new', 'w+') as fpnew:
blockLine = \ for line in fp:
line.replace('\n', '').replace('\r', '') blockLine = \
if unblockHashtag not in line: line.replace('\n', '').replace('\r', '')
fpnew.write(blockLine + '\n') if unblockHashtag not in line:
fpnew.write(blockLine + '\n')
except OSError as e:
print('EX: failed to remove global hashtag block ' +
unblockingFilename + ' ' + str(e))
return False
if os.path.isfile(unblockingFilename + '.new'): if os.path.isfile(unblockingFilename + '.new'):
os.rename(unblockingFilename + '.new', unblockingFilename) os.rename(unblockingFilename + '.new', unblockingFilename)
return True return True
@ -151,11 +192,16 @@ def removeBlock(baseDir: str, nickname: str, domain: str,
if os.path.isfile(unblockingFilename): if os.path.isfile(unblockingFilename):
if unblockHandle in open(unblockingFilename).read(): if unblockHandle in open(unblockingFilename).read():
with open(unblockingFilename, 'r') as fp: with open(unblockingFilename, 'r') as fp:
with open(unblockingFilename + '.new', 'w+') as fpnew: try:
for line in fp: with open(unblockingFilename + '.new', 'w+') as fpnew:
handle = line.replace('\n', '').replace('\r', '') for line in fp:
if unblockHandle not in line: handle = line.replace('\n', '').replace('\r', '')
fpnew.write(handle + '\n') if unblockHandle not in line:
fpnew.write(handle + '\n')
except OSError as e:
print('EX: failed to remove block ' +
unblockingFilename + ' ' + str(e))
return False
if os.path.isfile(unblockingFilename + '.new'): if os.path.isfile(unblockingFilename + '.new'):
os.rename(unblockingFilename + '.new', unblockingFilename) os.rename(unblockingFilename + '.new', unblockingFilename)
return True return True
@ -516,16 +562,20 @@ def mutePost(baseDir: str, nickname: str, domain: str, port: int,
try: try:
os.remove(cachedPostFilename) os.remove(cachedPostFilename)
print('MUTE: cached post removed ' + cachedPostFilename) print('MUTE: cached post removed ' + cachedPostFilename)
except BaseException: except OSError:
print('EX: MUTE cached post not removed ' + print('EX: MUTE cached post not removed ' +
cachedPostFilename) cachedPostFilename)
pass pass
else: else:
print('MUTE: cached post not found ' + cachedPostFilename) print('MUTE: cached post not found ' + cachedPostFilename)
with open(postFilename + '.muted', 'w+') as muteFile: try:
muteFile.write('\n') with open(postFilename + '.muted', 'w+') as muteFile:
print('MUTE: ' + postFilename + '.muted file added') muteFile.write('\n')
print('MUTE: ' + postFilename + '.muted file added')
except OSError:
print('EX: Failed to save mute file ' + postFilename + '.muted')
return
# if the post is in the recent posts cache then mark it as muted # if the post is in the recent posts cache then mark it as muted
if recentPostsCache.get('index'): if recentPostsCache.get('index'):
@ -555,7 +605,7 @@ def mutePost(baseDir: str, nickname: str, domain: str, port: int,
os.remove(cachedPostFilename) os.remove(cachedPostFilename)
print('MUTE: cached referenced post removed ' + print('MUTE: cached referenced post removed ' +
cachedPostFilename) cachedPostFilename)
except BaseException: except OSError:
print('EX: ' + print('EX: ' +
'MUTE cached referenced post not removed ' + 'MUTE cached referenced post not removed ' +
cachedPostFilename) cachedPostFilename)
@ -587,11 +637,10 @@ def unmutePost(baseDir: str, nickname: str, domain: str, port: int,
if os.path.isfile(muteFilename): if os.path.isfile(muteFilename):
try: try:
os.remove(muteFilename) os.remove(muteFilename)
except BaseException: except OSError:
if debug: if debug:
print('EX: unmutePost mute filename not deleted ' + print('EX: unmutePost mute filename not deleted ' +
str(muteFilename)) str(muteFilename))
pass
print('UNMUTE: ' + muteFilename + ' file removed') print('UNMUTE: ' + muteFilename + ' file removed')
postJsonObj = postJsonObject postJsonObj = postJsonObject
@ -638,11 +687,10 @@ def unmutePost(baseDir: str, nickname: str, domain: str, port: int,
if os.path.isfile(cachedPostFilename): if os.path.isfile(cachedPostFilename):
try: try:
os.remove(cachedPostFilename) os.remove(cachedPostFilename)
except BaseException: except OSError:
if debug: if debug:
print('EX: unmutePost cached post not deleted ' + print('EX: unmutePost cached post not deleted ' +
str(cachedPostFilename)) str(cachedPostFilename))
pass
# if the post is in the recent posts cache then mark it as unmuted # if the post is in the recent posts cache then mark it as unmuted
if recentPostsCache.get('index'): if recentPostsCache.get('index'):
@ -671,12 +719,11 @@ def unmutePost(baseDir: str, nickname: str, domain: str, port: int,
os.remove(cachedPostFilename) os.remove(cachedPostFilename)
print('MUTE: cached referenced post removed ' + print('MUTE: cached referenced post removed ' +
cachedPostFilename) cachedPostFilename)
except BaseException: except OSError:
if debug: if debug:
print('EX: ' + print('EX: ' +
'unmutePost cached ref post not removed ' + 'unmutePost cached ref post not removed ' +
str(cachedPostFilename)) str(cachedPostFilename))
pass
if recentPostsCache.get('json'): if recentPostsCache.get('json'):
if recentPostsCache['json'].get(alsoUpdatePostId): if recentPostsCache['json'].get(alsoUpdatePostId):
@ -818,10 +865,9 @@ def setBrochMode(baseDir: str, domainFull: str, enabled: bool) -> None:
if os.path.isfile(allowFilename): if os.path.isfile(allowFilename):
try: try:
os.remove(allowFilename) os.remove(allowFilename)
except BaseException: except OSError:
print('EX: setBrochMode allow file not deleted ' + print('EX: setBrochMode allow file not deleted ' +
str(allowFilename)) str(allowFilename))
pass
print('Broch mode turned off') print('Broch mode turned off')
else: else:
if os.path.isfile(allowFilename): if os.path.isfile(allowFilename):
@ -852,11 +898,15 @@ def setBrochMode(baseDir: str, domainFull: str, enabled: bool) -> None:
break break
# write the allow file # write the allow file
with open(allowFilename, 'w+') as allowFile: try:
allowFile.write(domainFull + '\n') with open(allowFilename, 'w+') as allowFile:
for d in allowedDomains: allowFile.write(domainFull + '\n')
allowFile.write(d + '\n') for d in allowedDomains:
print('Broch mode enabled') allowFile.write(d + '\n')
print('Broch mode enabled')
except OSError as e:
print('EX: Broch mode not enabled due to file write ' + str(e))
return
setConfigParam(baseDir, "brochMode", enabled) setConfigParam(baseDir, "brochMode", enabled)
@ -885,10 +935,9 @@ def brochModeLapses(baseDir: str, lapseDays: int) -> bool:
try: try:
os.remove(allowFilename) os.remove(allowFilename)
removed = True removed = True
except BaseException: except OSError:
print('EX: brochModeLapses allow file not deleted ' + print('EX: brochModeLapses allow file not deleted ' +
str(allowFilename)) str(allowFilename))
pass
if removed: if removed:
setConfigParam(baseDir, "brochMode", False) setConfigParam(baseDir, "brochMode", False)
print('Broch mode has elapsed') print('Broch mode has elapsed')

15
blog.py
View File

@ -91,11 +91,16 @@ def _noOfBlogReplies(baseDir: str, httpPrefix: str, translate: {},
if lines and removals: if lines and removals:
print('Rewriting ' + postFilename + ' to remove ' + print('Rewriting ' + postFilename + ' to remove ' +
str(len(removals)) + ' entries') str(len(removals)) + ' entries')
with open(postFilename, 'w+') as f: try:
for replyPostId in lines: with open(postFilename, 'w+') as f:
replyPostId = replyPostId.replace('\n', '').replace('\r', '') for replyPostId in lines:
if replyPostId not in removals: replyPostId = \
f.write(replyPostId + '\n') replyPostId.replace('\n', '').replace('\r', '')
if replyPostId not in removals:
f.write(replyPostId + '\n')
except OSError as e:
print('EX: unable to remove replies from post ' +
postFilename + ' ' + str(e))
return replies return replies

View File

@ -51,12 +51,11 @@ def undoBookmarksCollectionEntry(recentPostsCache: {},
if os.path.isfile(cachedPostFilename): if os.path.isfile(cachedPostFilename):
try: try:
os.remove(cachedPostFilename) os.remove(cachedPostFilename)
except BaseException: except OSError:
if debug: if debug:
print('EX: undoBookmarksCollectionEntry ' + print('EX: undoBookmarksCollectionEntry ' +
'unable to delete cached post file ' + 'unable to delete cached post file ' +
str(cachedPostFilename)) str(cachedPostFilename))
pass
removePostFromCache(postJsonObject, recentPostsCache) removePostFromCache(postJsonObject, recentPostsCache)
# remove from the index # remove from the index
@ -74,9 +73,12 @@ def undoBookmarksCollectionEntry(recentPostsCache: {},
indexStr = '' indexStr = ''
with open(bookmarksIndexFilename, 'r') as indexFile: with open(bookmarksIndexFilename, 'r') as indexFile:
indexStr = indexFile.read().replace(bookmarkIndex + '\n', '') indexStr = indexFile.read().replace(bookmarkIndex + '\n', '')
with open(bookmarksIndexFilename, 'w+') as bookmarksIndexFile: try:
bookmarksIndexFile.write(indexStr) with open(bookmarksIndexFilename, 'w+') as bookmarksIndexFile:
bookmarksIndexFile.write(indexStr)
except OSError:
print('EX: unable to write bookmarks index ' +
bookmarksIndexFilename)
if not postJsonObject.get('type'): if not postJsonObject.get('type'):
return return
if postJsonObject['type'] != 'Create': if postJsonObject['type'] != 'Create':
@ -163,12 +165,11 @@ def updateBookmarksCollection(recentPostsCache: {},
if os.path.isfile(cachedPostFilename): if os.path.isfile(cachedPostFilename):
try: try:
os.remove(cachedPostFilename) os.remove(cachedPostFilename)
except BaseException: except OSError:
if debug: if debug:
print('EX: updateBookmarksCollection ' + print('EX: updateBookmarksCollection ' +
'unable to delete cached post ' + 'unable to delete cached post ' +
str(cachedPostFilename)) str(cachedPostFilename))
pass
removePostFromCache(postJsonObject, recentPostsCache) removePostFromCache(postJsonObject, recentPostsCache)
if not postJsonObject.get('object'): if not postJsonObject.get('object'):
@ -233,8 +234,12 @@ def updateBookmarksCollection(recentPostsCache: {},
print('WARN: Failed to write entry to bookmarks index ' + print('WARN: Failed to write entry to bookmarks index ' +
bookmarksIndexFilename + ' ' + str(e)) bookmarksIndexFilename + ' ' + str(e))
else: else:
with open(bookmarksIndexFilename, 'w+') as bookmarksIndexFile: try:
bookmarksIndexFile.write(bookmarkIndex + '\n') with open(bookmarksIndexFilename, 'w+') as bookmarksIndexFile:
bookmarksIndexFile.write(bookmarkIndex + '\n')
except OSError:
print('EX: unable to write bookmarks index ' +
bookmarksIndexFilename)
def bookmark(recentPostsCache: {}, def bookmark(recentPostsCache: {},

View File

@ -26,9 +26,8 @@ def _removePersonFromCache(baseDir: str, personUrl: str,
if os.path.isfile(cacheFilename): if os.path.isfile(cacheFilename):
try: try:
os.remove(cacheFilename) os.remove(cacheFilename)
except BaseException: except OSError:
print('EX: unable to delete cached actor ' + str(cacheFilename)) print('EX: unable to delete cached actor ' + str(cacheFilename))
pass
if personCache.get(personUrl): if personCache.get(personUrl):
del personCache[personUrl] del personCache[personUrl]

View File

@ -95,11 +95,10 @@ def updateHashtagCategories(baseDir: str) -> None:
if os.path.isfile(categoryListFilename): if os.path.isfile(categoryListFilename):
try: try:
os.remove(categoryListFilename) os.remove(categoryListFilename)
except BaseException: except OSError:
print('EX: updateHashtagCategories ' + print('EX: updateHashtagCategories ' +
'unable to delete cached category list ' + 'unable to delete cached category list ' +
categoryListFilename) categoryListFilename)
pass
return return
categoryList = [] categoryList = []
@ -112,8 +111,11 @@ def updateHashtagCategories(baseDir: str) -> None:
categoryListStr += categoryStr + '\n' categoryListStr += categoryStr + '\n'
# save a list of available categories for quick lookup # save a list of available categories for quick lookup
with open(categoryListFilename, 'w+') as fp: try:
fp.write(categoryListStr) with open(categoryListFilename, 'w+') as fp:
fp.write(categoryListStr)
except OSError:
print('EX: unable to write category ' + categoryListFilename)
def _validHashtagCategory(category: str) -> bool: def _validHashtagCategory(category: str) -> bool:
@ -159,12 +161,15 @@ def setHashtagCategory(baseDir: str, hashtag: str, category: str,
# don't overwrite any existing categories # don't overwrite any existing categories
if os.path.isfile(categoryFilename): if os.path.isfile(categoryFilename):
return False return False
with open(categoryFilename, 'w+') as fp: try:
fp.write(category) with open(categoryFilename, 'w+') as fp:
if update: fp.write(category)
updateHashtagCategories(baseDir) if update:
return True updateHashtagCategories(baseDir)
return True
except OSError as e:
print('EX: unable to write category ' + categoryFilename +
' ' + str(e))
return False return False

View File

@ -1015,21 +1015,19 @@ def saveMediaInFormPOST(mediaBytes, debug: bool,
if os.path.isfile(possibleOtherFormat): if os.path.isfile(possibleOtherFormat):
try: try:
os.remove(possibleOtherFormat) os.remove(possibleOtherFormat)
except BaseException: except OSError:
if debug: if debug:
print('EX: saveMediaInFormPOST ' + print('EX: saveMediaInFormPOST ' +
'unable to delete other ' + 'unable to delete other ' +
str(possibleOtherFormat)) str(possibleOtherFormat))
pass
if os.path.isfile(filenameBase): if os.path.isfile(filenameBase):
try: try:
os.remove(filenameBase) os.remove(filenameBase)
except BaseException: except OSError:
if debug: if debug:
print('EX: saveMediaInFormPOST ' + print('EX: saveMediaInFormPOST ' +
'unable to delete ' + 'unable to delete ' +
str(filenameBase)) str(filenameBase))
pass
if debug: if debug:
print('DEBUG: No media found within POST') print('DEBUG: No media found within POST')
@ -1097,12 +1095,11 @@ def saveMediaInFormPOST(mediaBytes, debug: bool,
if os.path.isfile(possibleOtherFormat): if os.path.isfile(possibleOtherFormat):
try: try:
os.remove(possibleOtherFormat) os.remove(possibleOtherFormat)
except BaseException: except OSError:
if debug: if debug:
print('EX: saveMediaInFormPOST ' + print('EX: saveMediaInFormPOST ' +
'unable to delete other 2 ' + 'unable to delete other 2 ' +
str(possibleOtherFormat)) str(possibleOtherFormat))
pass
# don't allow scripts within svg files # don't allow scripts within svg files
if detectedExtension == 'svg': if detectedExtension == 'svg':
@ -1111,8 +1108,11 @@ def saveMediaInFormPOST(mediaBytes, debug: bool,
if dangerousSVG(svgStr, False): if dangerousSVG(svgStr, False):
return None, None return None, None
with open(filename, 'wb') as fp: try:
fp.write(mediaBytes[startPos:]) with open(filename, 'wb') as fp:
fp.write(mediaBytes[startPos:])
except OSError:
print('EX: unable to write media')
if not os.path.isfile(filename): if not os.path.isfile(filename):
print('WARN: Media file could not be written to file: ' + filename) print('WARN: Media file could not be written to file: ' + filename)

View File

@ -45,19 +45,17 @@ def updateConversation(baseDir: str, nickname: str, domain: str,
with open(conversationFilename, 'w+') as fp: with open(conversationFilename, 'w+') as fp:
fp.write(postId + '\n') fp.write(postId + '\n')
return True return True
except BaseException: except OSError:
print('EX: updateConversation ' + print('EX: updateConversation ' +
'unable to write to ' + conversationFilename) 'unable to write to ' + conversationFilename)
pass
elif postId + '\n' not in open(conversationFilename).read(): elif postId + '\n' not in open(conversationFilename).read():
try: try:
with open(conversationFilename, 'a+') as fp: with open(conversationFilename, 'a+') as fp:
fp.write(postId + '\n') fp.write(postId + '\n')
return True return True
except BaseException: except OSError:
print('EX: updateConversation 2 ' + print('EX: updateConversation 2 ' +
'unable to write to ' + conversationFilename) 'unable to write to ' + conversationFilename)
pass
return False return False
@ -72,8 +70,11 @@ def muteConversation(baseDir: str, nickname: str, domain: str,
return return
if os.path.isfile(conversationFilename + '.muted'): if os.path.isfile(conversationFilename + '.muted'):
return return
with open(conversationFilename + '.muted', 'w+') as fp: try:
fp.write('\n') with open(conversationFilename + '.muted', 'w+') as fp:
fp.write('\n')
except OSError:
print('EX: unable to write mute ' + conversationFilename)
def unmuteConversation(baseDir: str, nickname: str, domain: str, def unmuteConversation(baseDir: str, nickname: str, domain: str,
@ -89,7 +90,6 @@ def unmuteConversation(baseDir: str, nickname: str, domain: str,
return return
try: try:
os.remove(conversationFilename + '.muted') os.remove(conversationFilename + '.muted')
except BaseException: except OSError:
print('EX: unmuteConversation unable to delete ' + print('EX: unmuteConversation unable to delete ' +
conversationFilename + '.muted') conversationFilename + '.muted')
pass

224
daemon.py
View File

@ -532,8 +532,12 @@ class PubServer(BaseHTTPRequestHandler):
self.server.maxReplies, self.server.maxReplies,
self.server.debug) self.server.debug)
# record the vote # record the vote
with open(votesFilename, 'a+') as votesFile: try:
votesFile.write(messageId + '\n') with open(votesFilename, 'a+') as votesFile:
votesFile.write(messageId + '\n')
except OSError:
print('EX: unable to write vote ' +
votesFilename)
# ensure that the cached post is removed if it exists, # ensure that the cached post is removed if it exists,
# so that it then will be recreated # so that it then will be recreated
@ -546,11 +550,10 @@ class PubServer(BaseHTTPRequestHandler):
if os.path.isfile(cachedPostFilename): if os.path.isfile(cachedPostFilename):
try: try:
os.remove(cachedPostFilename) os.remove(cachedPostFilename)
except BaseException: except OSError:
print('EX: _sendReplyToQuestion ' + print('EX: _sendReplyToQuestion ' +
'unable to delete ' + 'unable to delete ' +
cachedPostFilename) cachedPostFilename)
pass
# remove from memory cache # remove from memory cache
removePostFromCache(postJsonObject, removePostFromCache(postJsonObject,
self.server.recentPostsCache) self.server.recentPostsCache)
@ -838,19 +841,17 @@ class PubServer(BaseHTTPRequestHandler):
try: try:
with open(mediaFilename + '.etag', 'r') as etagFile: with open(mediaFilename + '.etag', 'r') as etagFile:
etag = etagFile.read() etag = etagFile.read()
except BaseException: except OSError:
print('EX: _set_headers_etag ' + print('EX: _set_headers_etag ' +
'unable to read ' + mediaFilename + '.etag') 'unable to read ' + mediaFilename + '.etag')
pass
if not etag: if not etag:
etag = md5(data).hexdigest() # nosec etag = md5(data).hexdigest() # nosec
try: try:
with open(mediaFilename + '.etag', 'w+') as etagFile: with open(mediaFilename + '.etag', 'w+') as etagFile:
etagFile.write(etag) etagFile.write(etag)
except BaseException: except OSError:
print('EX: _set_headers_etag ' + print('EX: _set_headers_etag ' +
'unable to write ' + mediaFilename + '.etag') 'unable to write ' + mediaFilename + '.etag')
pass
# if etag: # if etag:
# self.send_header('ETag', '"' + etag + '"') # self.send_header('ETag', '"' + etag + '"')
if lastModified: if lastModified:
@ -872,12 +873,11 @@ class PubServer(BaseHTTPRequestHandler):
# load the etag from file # load the etag from file
currEtag = '' currEtag = ''
try: try:
with open(mediaFilename, 'r') as etagFile: with open(mediaFilename + '.etag', 'r') as etagFile:
currEtag = etagFile.read() currEtag = etagFile.read()
except BaseException: except OSError:
print('EX: _etag_exists unable to read ' + print('EX: _etag_exists unable to read ' +
str(mediaFilename)) str(mediaFilename))
pass
if currEtag and oldEtag == currEtag: if currEtag and oldEtag == currEtag:
# The file has not changed # The file has not changed
return True return True
@ -1758,15 +1758,15 @@ class PubServer(BaseHTTPRequestHandler):
try: try:
with open(saltFilename, 'r') as fp: with open(saltFilename, 'r') as fp:
salt = fp.read() salt = fp.read()
except Exception as e: except OSError as e:
print('WARN: Unable to read salt for ' + print('EX: Unable to read salt for ' +
loginNickname + ' ' + str(e)) loginNickname + ' ' + str(e))
else: else:
try: try:
with open(saltFilename, 'w+') as fp: with open(saltFilename, 'w+') as fp:
fp.write(salt) fp.write(salt)
except Exception as e: except OSError as e:
print('WARN: Unable to save salt for ' + print('EX: Unable to save salt for ' +
loginNickname + ' ' + str(e)) loginNickname + ' ' + str(e))
tokenText = loginNickname + loginPassword + salt tokenText = loginNickname + loginPassword + salt
@ -1779,8 +1779,8 @@ class PubServer(BaseHTTPRequestHandler):
try: try:
with open(tokenFilename, 'w+') as fp: with open(tokenFilename, 'w+') as fp:
fp.write(token) fp.write(token)
except Exception as e: except OSError as e:
print('WARN: Unable to save token for ' + print('EX: Unable to save token for ' +
loginNickname + ' ' + str(e)) loginNickname + ' ' + str(e))
personUpgradeActor(baseDir, None, loginHandle, personUpgradeActor(baseDir, None, loginHandle,
@ -2348,17 +2348,20 @@ class PubServer(BaseHTTPRequestHandler):
if os.path.isfile(newswireBlockedFilename): if os.path.isfile(newswireBlockedFilename):
try: try:
os.remove(newswireBlockedFilename) os.remove(newswireBlockedFilename)
except BaseException: except OSError:
print('EX: _personOptions unable to delete ' + print('EX: _personOptions unable to delete ' +
newswireBlockedFilename) newswireBlockedFilename)
pass
refreshNewswire(self.server.baseDir) refreshNewswire(self.server.baseDir)
else: else:
if os.path.isdir(accountDir): if os.path.isdir(accountDir):
nwFilename = newswireBlockedFilename nwFilename = newswireBlockedFilename
with open(nwFilename, 'w+') as noNewswireFile: try:
noNewswireFile.write('\n') with open(nwFilename, 'w+') as noNewswireFile:
refreshNewswire(self.server.baseDir) noNewswireFile.write('\n')
refreshNewswire(self.server.baseDir)
except OSError as e:
print('EX: unable to write ' + nwFilename +
' ' + str(e))
usersPathStr = \ usersPathStr = \
usersPath + '/' + self.server.defaultTimeline + \ usersPath + '/' + self.server.defaultTimeline + \
'?page=' + str(pageNumber) '?page=' + str(pageNumber)
@ -2388,17 +2391,20 @@ class PubServer(BaseHTTPRequestHandler):
if os.path.isfile(featuresBlockedFilename): if os.path.isfile(featuresBlockedFilename):
try: try:
os.remove(featuresBlockedFilename) os.remove(featuresBlockedFilename)
except BaseException: except OSError:
print('EX: _personOptions unable to delete ' + print('EX: _personOptions unable to delete ' +
featuresBlockedFilename) featuresBlockedFilename)
pass
refreshNewswire(self.server.baseDir) refreshNewswire(self.server.baseDir)
else: else:
if os.path.isdir(accountDir): if os.path.isdir(accountDir):
featFilename = featuresBlockedFilename featFilename = featuresBlockedFilename
with open(featFilename, 'w+') as noFeaturesFile: try:
noFeaturesFile.write('\n') with open(featFilename, 'w+') as noFeaturesFile:
refreshNewswire(self.server.baseDir) noFeaturesFile.write('\n')
refreshNewswire(self.server.baseDir)
except OSError as e:
print('EX: unable to write ' + featFilename +
' ' + str(e))
usersPathStr = \ usersPathStr = \
usersPath + '/' + self.server.defaultTimeline + \ usersPath + '/' + self.server.defaultTimeline + \
'?page=' + str(pageNumber) '?page=' + str(pageNumber)
@ -2428,15 +2434,17 @@ class PubServer(BaseHTTPRequestHandler):
if os.path.isfile(newswireModFilename): if os.path.isfile(newswireModFilename):
try: try:
os.remove(newswireModFilename) os.remove(newswireModFilename)
except BaseException: except OSError:
print('EX: _personOptions unable to delete ' + print('EX: _personOptions unable to delete ' +
newswireModFilename) newswireModFilename)
pass
else: else:
if os.path.isdir(accountDir): if os.path.isdir(accountDir):
nwFilename = newswireModFilename nwFilename = newswireModFilename
with open(nwFilename, 'w+') as modNewswireFile: try:
modNewswireFile.write('\n') with open(nwFilename, 'w+') as modNewswireFile:
modNewswireFile.write('\n')
except OSError:
print('EX: unable to write ' + nwFilename)
usersPathStr = \ usersPathStr = \
usersPath + '/' + self.server.defaultTimeline + \ usersPath + '/' + self.server.defaultTimeline + \
'?page=' + str(pageNumber) '?page=' + str(pageNumber)
@ -3582,8 +3590,11 @@ class PubServer(BaseHTTPRequestHandler):
mediaFilename = \ mediaFilename = \
mediaFilenameBase + '.' + \ mediaFilenameBase + '.' + \
getImageExtensionFromMimeType(self.headers['Content-type']) getImageExtensionFromMimeType(self.headers['Content-type'])
with open(mediaFilename, 'wb') as avFile: try:
avFile.write(mediaBytes) with open(mediaFilename, 'wb') as avFile:
avFile.write(mediaBytes)
except OSError:
print('EX: unable to write ' + mediaFilename)
if debug: if debug:
print('DEBUG: image saved to ' + mediaFilename) print('DEBUG: image saved to ' + mediaFilename)
self.send_response(201) self.send_response(201)
@ -3901,10 +3912,9 @@ class PubServer(BaseHTTPRequestHandler):
if os.path.isfile(linksFilename): if os.path.isfile(linksFilename):
try: try:
os.remove(linksFilename) os.remove(linksFilename)
except BaseException: except OSError:
print('EX: _linksUpdate unable to delete ' + print('EX: _linksUpdate unable to delete ' +
linksFilename) linksFilename)
pass
adminNickname = \ adminNickname = \
getConfigParam(baseDir, 'admin') getConfigParam(baseDir, 'admin')
@ -3919,10 +3929,9 @@ class PubServer(BaseHTTPRequestHandler):
if os.path.isfile(aboutFilename): if os.path.isfile(aboutFilename):
try: try:
os.remove(aboutFilename) os.remove(aboutFilename)
except BaseException: except OSError:
print('EX: _linksUpdate unable to delete ' + print('EX: _linksUpdate unable to delete ' +
aboutFilename) aboutFilename)
pass
if fields.get('editedTOS'): if fields.get('editedTOS'):
TOSStr = fields['editedTOS'] TOSStr = fields['editedTOS']
@ -3934,10 +3943,9 @@ class PubServer(BaseHTTPRequestHandler):
if os.path.isfile(TOSFilename): if os.path.isfile(TOSFilename):
try: try:
os.remove(TOSFilename) os.remove(TOSFilename)
except BaseException: except OSError:
print('EX: _linksUpdate unable to delete ' + print('EX: _linksUpdate unable to delete ' +
TOSFilename) TOSFilename)
pass
# redirect back to the default timeline # redirect back to the default timeline
self._redirect_headers(actorStr + '/' + defaultTimeline, self._redirect_headers(actorStr + '/' + defaultTimeline,
@ -4037,10 +4045,9 @@ class PubServer(BaseHTTPRequestHandler):
if os.path.isfile(categoryFilename): if os.path.isfile(categoryFilename):
try: try:
os.remove(categoryFilename) os.remove(categoryFilename)
except BaseException: except OSError:
print('EX: _setHashtagCategory unable to delete ' + print('EX: _setHashtagCategory unable to delete ' +
categoryFilename) categoryFilename)
pass
# redirect back to the default timeline # redirect back to the default timeline
self._redirect_headers(tagScreenStr, self._redirect_headers(tagScreenStr,
@ -4114,63 +4121,71 @@ class PubServer(BaseHTTPRequestHandler):
extractTextFieldsInPOST(postBytes, boundary, debug) extractTextFieldsInPOST(postBytes, boundary, debug)
if fields.get('editedNewswire'): if fields.get('editedNewswire'):
newswireStr = fields['editedNewswire'] newswireStr = fields['editedNewswire']
with open(newswireFilename, 'w+') as newswireFile: try:
newswireFile.write(newswireStr) with open(newswireFilename, 'w+') as newswireFile:
newswireFile.write(newswireStr)
except OSError:
print('EX: unable to write ' + newswireFilename)
else: else:
if os.path.isfile(newswireFilename): if os.path.isfile(newswireFilename):
try: try:
os.remove(newswireFilename) os.remove(newswireFilename)
except BaseException: except OSError:
print('EX: _newswireUpdate unable to delete ' + print('EX: _newswireUpdate unable to delete ' +
newswireFilename) newswireFilename)
pass
# save filtered words list for the newswire # save filtered words list for the newswire
filterNewswireFilename = \ filterNewswireFilename = \
baseDir + '/accounts/' + \ baseDir + '/accounts/' + \
'news@' + domain + '/filters.txt' 'news@' + domain + '/filters.txt'
if fields.get('filteredWordsNewswire'): if fields.get('filteredWordsNewswire'):
with open(filterNewswireFilename, 'w+') as filterfile: try:
filterfile.write(fields['filteredWordsNewswire']) with open(filterNewswireFilename, 'w+') as filterfile:
filterfile.write(fields['filteredWordsNewswire'])
except OSError:
print('EX: unable to write ' + filterNewswireFilename)
else: else:
if os.path.isfile(filterNewswireFilename): if os.path.isfile(filterNewswireFilename):
try: try:
os.remove(filterNewswireFilename) os.remove(filterNewswireFilename)
except BaseException: except OSError:
print('EX: _newswireUpdate unable to delete ' + print('EX: _newswireUpdate unable to delete ' +
filterNewswireFilename) filterNewswireFilename)
pass
# save news tagging rules # save news tagging rules
hashtagRulesFilename = \ hashtagRulesFilename = \
baseDir + '/accounts/hashtagrules.txt' baseDir + '/accounts/hashtagrules.txt'
if fields.get('hashtagRulesList'): if fields.get('hashtagRulesList'):
with open(hashtagRulesFilename, 'w+') as rulesfile: try:
rulesfile.write(fields['hashtagRulesList']) with open(hashtagRulesFilename, 'w+') as rulesfile:
rulesfile.write(fields['hashtagRulesList'])
except OSError:
print('EX: unable to write ' + hashtagRulesFilename)
else: else:
if os.path.isfile(hashtagRulesFilename): if os.path.isfile(hashtagRulesFilename):
try: try:
os.remove(hashtagRulesFilename) os.remove(hashtagRulesFilename)
except BaseException: except OSError:
print('EX: _newswireUpdate unable to delete ' + print('EX: _newswireUpdate unable to delete ' +
hashtagRulesFilename) hashtagRulesFilename)
pass
newswireTrustedFilename = baseDir + '/accounts/newswiretrusted.txt' newswireTrustedFilename = baseDir + '/accounts/newswiretrusted.txt'
if fields.get('trustedNewswire'): if fields.get('trustedNewswire'):
newswireTrusted = fields['trustedNewswire'] newswireTrusted = fields['trustedNewswire']
if not newswireTrusted.endswith('\n'): if not newswireTrusted.endswith('\n'):
newswireTrusted += '\n' newswireTrusted += '\n'
with open(newswireTrustedFilename, 'w+') as trustFile: try:
trustFile.write(newswireTrusted) with open(newswireTrustedFilename, 'w+') as trustFile:
trustFile.write(newswireTrusted)
except OSError:
print('EX: unable to write ' + newswireTrustedFilename)
else: else:
if os.path.isfile(newswireTrustedFilename): if os.path.isfile(newswireTrustedFilename):
try: try:
os.remove(newswireTrustedFilename) os.remove(newswireTrustedFilename)
except BaseException: except OSError:
print('EX: _newswireUpdate unable to delete ' + print('EX: _newswireUpdate unable to delete ' +
newswireTrustedFilename) newswireTrustedFilename)
pass
# redirect back to the default timeline # redirect back to the default timeline
self._redirect_headers(actorStr + '/' + defaultTimeline, self._redirect_headers(actorStr + '/' + defaultTimeline,
@ -4197,10 +4212,9 @@ class PubServer(BaseHTTPRequestHandler):
if os.path.isfile(citationsFilename): if os.path.isfile(citationsFilename):
try: try:
os.remove(citationsFilename) os.remove(citationsFilename)
except BaseException: except OSError:
print('EX: _citationsUpdate unable to delete ' + print('EX: _citationsUpdate unable to delete ' +
citationsFilename) citationsFilename)
pass
if newswire and \ if newswire and \
' boundary=' in self.headers['Content-type']: ' boundary=' in self.headers['Content-type']:
@ -4257,8 +4271,11 @@ class PubServer(BaseHTTPRequestHandler):
citationsStr += citationDate + '\n' citationsStr += citationDate + '\n'
# save citations dates, so that they can be added when # save citations dates, so that they can be added when
# reloading the newblog screen # reloading the newblog screen
with open(citationsFilename, 'w+') as citationsFile: try:
citationsFile.write(citationsStr) with open(citationsFilename, 'w+') as citationsFile:
citationsFile.write(citationsStr)
except OSError:
print('EX: unable to write ' + citationsFilename)
# redirect back to the default timeline # redirect back to the default timeline
self._redirect_headers(actorStr + '/newblog', self._redirect_headers(actorStr + '/newblog',
@ -4504,10 +4521,9 @@ class PubServer(BaseHTTPRequestHandler):
if os.path.isfile(filenameBase): if os.path.isfile(filenameBase):
try: try:
os.remove(filenameBase) os.remove(filenameBase)
except BaseException: except OSError:
print('EX: _profileUpdate unable to delete ' + print('EX: _profileUpdate unable to delete ' +
filenameBase) filenameBase)
pass
else: else:
filenameBase = \ filenameBase = \
acctDir(baseDir, nickname, domain) + \ acctDir(baseDir, nickname, domain) + \
@ -4541,10 +4557,9 @@ class PubServer(BaseHTTPRequestHandler):
if os.path.isfile(postImageFilename + '.etag'): if os.path.isfile(postImageFilename + '.etag'):
try: try:
os.remove(postImageFilename + '.etag') os.remove(postImageFilename + '.etag')
except BaseException: except OSError:
print('EX: _profileUpdate unable to delete ' + print('EX: _profileUpdate unable to delete ' +
postImageFilename + '.etag') postImageFilename + '.etag')
pass
city = getSpoofedCity(self.server.city, city = getSpoofedCity(self.server.city,
baseDir, nickname, domain) baseDir, nickname, domain)
@ -4712,8 +4727,11 @@ class PubServer(BaseHTTPRequestHandler):
if fields.get('cityDropdown'): if fields.get('cityDropdown'):
cityFilename = \ cityFilename = \
acctDir(baseDir, nickname, domain) + '/city.txt' acctDir(baseDir, nickname, domain) + '/city.txt'
with open(cityFilename, 'w+') as fp: try:
fp.write(fields['cityDropdown']) with open(cityFilename, 'w+') as fp:
fp.write(fields['cityDropdown'])
except OSError:
print('EX: unable to write ' + cityFilename)
# change displayed name # change displayed name
if fields.get('displayNickname'): if fields.get('displayNickname'):
@ -5597,11 +5615,10 @@ class PubServer(BaseHTTPRequestHandler):
try: try:
os.remove(baseDir + os.remove(baseDir +
'/fonts/custom.' + ext) '/fonts/custom.' + ext)
except BaseException: except OSError:
print('EX: _profileUpdate ' + print('EX: _profileUpdate ' +
'unable to delete ' + 'unable to delete ' +
baseDir + '/fonts/custom.' + ext) baseDir + '/fonts/custom.' + ext)
pass
if os.path.isfile(baseDir + if os.path.isfile(baseDir +
'/fonts/custom.' + ext + '/fonts/custom.' + ext +
'.etag'): '.etag'):
@ -5609,12 +5626,11 @@ class PubServer(BaseHTTPRequestHandler):
os.remove(baseDir + os.remove(baseDir +
'/fonts/custom.' + ext + '/fonts/custom.' + ext +
'.etag') '.etag')
except BaseException: except OSError:
print('EX: _profileUpdate ' + print('EX: _profileUpdate ' +
'unable to delete ' + 'unable to delete ' +
baseDir + '/fonts/custom.' + baseDir + '/fonts/custom.' +
ext + '.etag') ext + '.etag')
pass
currTheme = getTheme(baseDir) currTheme = getTheme(baseDir)
if currTheme: if currTheme:
self.server.themeName = currTheme self.server.themeName = currTheme
@ -5664,11 +5680,10 @@ class PubServer(BaseHTTPRequestHandler):
if os.path.isfile(followDMsFilename): if os.path.isfile(followDMsFilename):
try: try:
os.remove(followDMsFilename) os.remove(followDMsFilename)
except BaseException: except OSError:
print('EX: _profileUpdate ' + print('EX: _profileUpdate ' +
'unable to delete ' + 'unable to delete ' +
followDMsFilename) followDMsFilename)
pass
# remove Twitter retweets # remove Twitter retweets
removeTwitterFilename = \ removeTwitterFilename = \
@ -5685,11 +5700,10 @@ class PubServer(BaseHTTPRequestHandler):
if os.path.isfile(removeTwitterFilename): if os.path.isfile(removeTwitterFilename):
try: try:
os.remove(removeTwitterFilename) os.remove(removeTwitterFilename)
except BaseException: except OSError:
print('EX: _profileUpdate ' + print('EX: _profileUpdate ' +
'unable to delete ' + 'unable to delete ' +
removeTwitterFilename) removeTwitterFilename)
pass
# hide Like button # hide Like button
hideLikeButtonFile = \ hideLikeButtonFile = \
@ -5708,20 +5722,18 @@ class PubServer(BaseHTTPRequestHandler):
if os.path.isfile(notifyLikesFilename): if os.path.isfile(notifyLikesFilename):
try: try:
os.remove(notifyLikesFilename) os.remove(notifyLikesFilename)
except BaseException: except OSError:
print('EX: _profileUpdate ' + print('EX: _profileUpdate ' +
'unable to delete ' + 'unable to delete ' +
notifyLikesFilename) notifyLikesFilename)
pass
if not hideLikeButtonActive: if not hideLikeButtonActive:
if os.path.isfile(hideLikeButtonFile): if os.path.isfile(hideLikeButtonFile):
try: try:
os.remove(hideLikeButtonFile) os.remove(hideLikeButtonFile)
except BaseException: except OSError:
print('EX: _profileUpdate ' + print('EX: _profileUpdate ' +
'unable to delete ' + 'unable to delete ' +
hideLikeButtonFile) hideLikeButtonFile)
pass
# hide Reaction button # hide Reaction button
hideReactionButtonFile = \ hideReactionButtonFile = \
@ -5740,20 +5752,18 @@ class PubServer(BaseHTTPRequestHandler):
if os.path.isfile(notifyReactionsFilename): if os.path.isfile(notifyReactionsFilename):
try: try:
os.remove(notifyReactionsFilename) os.remove(notifyReactionsFilename)
except BaseException: except OSError:
print('EX: _profileUpdate ' + print('EX: _profileUpdate ' +
'unable to delete ' + 'unable to delete ' +
notifyReactionsFilename) notifyReactionsFilename)
pass
if not hideReactionButtonActive: if not hideReactionButtonActive:
if os.path.isfile(hideReactionButtonFile): if os.path.isfile(hideReactionButtonFile):
try: try:
os.remove(hideReactionButtonFile) os.remove(hideReactionButtonFile)
except BaseException: except OSError:
print('EX: _profileUpdate ' + print('EX: _profileUpdate ' +
'unable to delete ' + 'unable to delete ' +
hideReactionButtonFile) hideReactionButtonFile)
pass
# notify about new Likes # notify about new Likes
if onFinalWelcomeScreen: if onFinalWelcomeScreen:
@ -5773,11 +5783,10 @@ class PubServer(BaseHTTPRequestHandler):
if os.path.isfile(notifyLikesFilename): if os.path.isfile(notifyLikesFilename):
try: try:
os.remove(notifyLikesFilename) os.remove(notifyLikesFilename)
except BaseException: except OSError:
print('EX: _profileUpdate ' + print('EX: _profileUpdate ' +
'unable to delete ' + 'unable to delete ' +
notifyLikesFilename) notifyLikesFilename)
pass
notifyReactionsFilename = \ notifyReactionsFilename = \
acctDir(baseDir, nickname, domain) + \ acctDir(baseDir, nickname, domain) + \
@ -5800,11 +5809,10 @@ class PubServer(BaseHTTPRequestHandler):
if os.path.isfile(notifyReactionsFilename): if os.path.isfile(notifyReactionsFilename):
try: try:
os.remove(notifyReactionsFilename) os.remove(notifyReactionsFilename)
except BaseException: except OSError:
print('EX: _profileUpdate ' + print('EX: _profileUpdate ' +
'unable to delete ' + 'unable to delete ' +
notifyReactionsFilename) notifyReactionsFilename)
pass
# this account is a bot # this account is a bot
if fields.get('isBot'): if fields.get('isBot'):
@ -5865,11 +5873,10 @@ class PubServer(BaseHTTPRequestHandler):
if os.path.isfile(filterFilename): if os.path.isfile(filterFilename):
try: try:
os.remove(filterFilename) os.remove(filterFilename)
except BaseException: except OSError:
print('EX: _profileUpdate ' + print('EX: _profileUpdate ' +
'unable to delete ' + 'unable to delete ' +
filterFilename) filterFilename)
pass
# word replacements # word replacements
switchFilename = \ switchFilename = \
@ -5882,11 +5889,10 @@ class PubServer(BaseHTTPRequestHandler):
if os.path.isfile(switchFilename): if os.path.isfile(switchFilename):
try: try:
os.remove(switchFilename) os.remove(switchFilename)
except BaseException: except OSError:
print('EX: _profileUpdate ' + print('EX: _profileUpdate ' +
'unable to delete ' + 'unable to delete ' +
switchFilename) switchFilename)
pass
# autogenerated tags # autogenerated tags
autoTagsFilename = \ autoTagsFilename = \
@ -5899,11 +5905,10 @@ class PubServer(BaseHTTPRequestHandler):
if os.path.isfile(autoTagsFilename): if os.path.isfile(autoTagsFilename):
try: try:
os.remove(autoTagsFilename) os.remove(autoTagsFilename)
except BaseException: except OSError:
print('EX: _profileUpdate ' + print('EX: _profileUpdate ' +
'unable to delete ' + 'unable to delete ' +
autoTagsFilename) autoTagsFilename)
pass
# autogenerated content warnings # autogenerated content warnings
autoCWFilename = \ autoCWFilename = \
@ -5916,11 +5921,10 @@ class PubServer(BaseHTTPRequestHandler):
if os.path.isfile(autoCWFilename): if os.path.isfile(autoCWFilename):
try: try:
os.remove(autoCWFilename) os.remove(autoCWFilename)
except BaseException: except OSError:
print('EX: _profileUpdate ' + print('EX: _profileUpdate ' +
'unable to delete ' + 'unable to delete ' +
autoCWFilename) autoCWFilename)
pass
# save blocked accounts list # save blocked accounts list
blockedFilename = \ blockedFilename = \
@ -5933,11 +5937,10 @@ class PubServer(BaseHTTPRequestHandler):
if os.path.isfile(blockedFilename): if os.path.isfile(blockedFilename):
try: try:
os.remove(blockedFilename) os.remove(blockedFilename)
except BaseException: except OSError:
print('EX: _profileUpdate ' + print('EX: _profileUpdate ' +
'unable to delete ' + 'unable to delete ' +
blockedFilename) blockedFilename)
pass
# Save DM allowed instances list. # Save DM allowed instances list.
# The allow list for incoming DMs, # The allow list for incoming DMs,
@ -5952,11 +5955,10 @@ class PubServer(BaseHTTPRequestHandler):
if os.path.isfile(dmAllowedInstancesFilename): if os.path.isfile(dmAllowedInstancesFilename):
try: try:
os.remove(dmAllowedInstancesFilename) os.remove(dmAllowedInstancesFilename)
except BaseException: except OSError:
print('EX: _profileUpdate ' + print('EX: _profileUpdate ' +
'unable to delete ' + 'unable to delete ' +
dmAllowedInstancesFilename) dmAllowedInstancesFilename)
pass
# save allowed instances list # save allowed instances list
# This is the account level allow list # This is the account level allow list
@ -5970,11 +5972,10 @@ class PubServer(BaseHTTPRequestHandler):
if os.path.isfile(allowedInstancesFilename): if os.path.isfile(allowedInstancesFilename):
try: try:
os.remove(allowedInstancesFilename) os.remove(allowedInstancesFilename)
except BaseException: except OSError:
print('EX: _profileUpdate ' + print('EX: _profileUpdate ' +
'unable to delete ' + 'unable to delete ' +
allowedInstancesFilename) allowedInstancesFilename)
pass
if isModerator(self.server.baseDir, nickname): if isModerator(self.server.baseDir, nickname):
# set selected content warning lists # set selected content warning lists
@ -6036,11 +6037,10 @@ class PubServer(BaseHTTPRequestHandler):
if os.path.isfile(peertubeInstancesFile): if os.path.isfile(peertubeInstancesFile):
try: try:
os.remove(peertubeInstancesFile) os.remove(peertubeInstancesFile)
except BaseException: except OSError:
print('EX: _profileUpdate ' + print('EX: _profileUpdate ' +
'unable to delete ' + 'unable to delete ' +
peertubeInstancesFile) peertubeInstancesFile)
pass
self.server.peertubeInstances.clear() self.server.peertubeInstances.clear()
# save git project names list # save git project names list
@ -6054,11 +6054,10 @@ class PubServer(BaseHTTPRequestHandler):
if os.path.isfile(gitProjectsFilename): if os.path.isfile(gitProjectsFilename):
try: try:
os.remove(gitProjectsFilename) os.remove(gitProjectsFilename)
except BaseException: except OSError:
print('EX: _profileUpdate ' + print('EX: _profileUpdate ' +
'unable to delete ' + 'unable to delete ' +
gitProjectsFilename) gitProjectsFilename)
pass
# save actor json file within accounts # save actor json file within accounts
if actorChanged: if actorChanged:
@ -15946,10 +15945,9 @@ class PubServer(BaseHTTPRequestHandler):
try: try:
with open(mediaTagFilename, 'r') as etagFile: with open(mediaTagFilename, 'r') as etagFile:
etag = etagFile.read() etag = etagFile.read()
except BaseException: except OSError:
print('EX: do_HEAD unable to read ' + print('EX: do_HEAD unable to read ' +
mediaTagFilename) mediaTagFilename)
pass
else: else:
with open(mediaFilename, 'rb') as avFile: with open(mediaFilename, 'rb') as avFile:
mediaBinary = avFile.read() mediaBinary = avFile.read()
@ -15957,10 +15955,9 @@ class PubServer(BaseHTTPRequestHandler):
try: try:
with open(mediaTagFilename, 'w+') as etagFile: with open(mediaTagFilename, 'w+') as etagFile:
etagFile.write(etag) etagFile.write(etag)
except BaseException: except OSError:
print('EX: do_HEAD unable to write ' + print('EX: do_HEAD unable to write ' +
mediaTagFilename) mediaTagFilename)
pass
mediaFileType = mediaFileMimeType(checkPath) mediaFileType = mediaFileMimeType(checkPath)
self._set_headers_head(mediaFileType, fileLength, self._set_headers_head(mediaFileType, fileLength,
@ -16127,10 +16124,9 @@ class PubServer(BaseHTTPRequestHandler):
try: try:
with open(lastUsedFilename, 'w+') as lastUsedFile: with open(lastUsedFilename, 'w+') as lastUsedFile:
lastUsedFile.write(str(int(time.time()))) lastUsedFile.write(str(int(time.time())))
except BaseException: except OSError:
print('EX: _receiveNewPostProcess unable to write ' + print('EX: _receiveNewPostProcess unable to write ' +
lastUsedFilename) lastUsedFilename)
pass
mentionsStr = '' mentionsStr = ''
if fields.get('mentions'): if fields.get('mentions'):
@ -16296,10 +16292,9 @@ class PubServer(BaseHTTPRequestHandler):
print('Edited blog post, removing cached html') print('Edited blog post, removing cached html')
try: try:
os.remove(cachedFilename) os.remove(cachedFilename)
except BaseException: except OSError:
print('EX: _receiveNewPostProcess ' + print('EX: _receiveNewPostProcess ' +
'unable to delete ' + cachedFilename) 'unable to delete ' + cachedFilename)
pass
# remove from memory cache # remove from memory cache
removePostFromCache(postJsonObject, removePostFromCache(postJsonObject,
self.server.recentPostsCache) self.server.recentPostsCache)
@ -16732,10 +16727,9 @@ class PubServer(BaseHTTPRequestHandler):
if os.path.isfile(filename): if os.path.isfile(filename):
try: try:
os.remove(filename) os.remove(filename)
except BaseException: except OSError:
print('EX: _receiveNewPostProcess ' + print('EX: _receiveNewPostProcess ' +
'unable to delete ' + filename) 'unable to delete ' + filename)
pass
self.postToNickname = nickname self.postToNickname = nickname
return 1 return 1
return -1 return -1

View File

@ -201,6 +201,5 @@ def removeOldHashtags(baseDir: str, maxMonths: int) -> str:
for removeFilename in removeHashtags: for removeFilename in removeHashtags:
try: try:
os.remove(removeFilename) os.remove(removeFilename)
except BaseException: except OSError:
print('EX: removeOldHashtags unable to delete ' + removeFilename) print('EX: removeOldHashtags unable to delete ' + removeFilename)
pass

View File

@ -46,9 +46,8 @@ def E2EEremoveDevice(baseDir: str, nickname: str, domain: str,
if os.path.isfile(deviceFilename): if os.path.isfile(deviceFilename):
try: try:
os.remove(deviceFilename) os.remove(deviceFilename)
except BaseException: except OSError:
print('EX: E2EEremoveDevice unable to delete ' + deviceFilename) print('EX: E2EEremoveDevice unable to delete ' + deviceFilename)
pass
return True return True
return False return False

View File

@ -895,9 +895,8 @@ if args.socnet:
with open('socnet.dot', 'w+') as fp: with open('socnet.dot', 'w+') as fp:
fp.write(dotGraph) fp.write(dotGraph)
print('Saved to socnet.dot') print('Saved to socnet.dot')
except BaseException: except OSError:
print('EX: commandline unable to write socnet.dot') print('EX: commandline unable to write socnet.dot')
pass
sys.exit() sys.exit()
if args.postsraw: if args.postsraw:

View File

@ -296,12 +296,15 @@ def unfollowAccount(baseDir: str, nickname: str, domain: str,
return return
with open(filename, 'r') as f: with open(filename, 'r') as f:
lines = f.readlines() lines = f.readlines()
with open(filename, 'w+') as f: try:
for line in lines: with open(filename, 'w+') as f:
checkHandle = line.strip("\n").strip("\r").lower() for line in lines:
if checkHandle != handleToUnfollowLower and \ checkHandle = line.strip("\n").strip("\r").lower()
checkHandle != '!' + handleToUnfollowLower: if checkHandle != handleToUnfollowLower and \
f.write(line) checkHandle != '!' + handleToUnfollowLower:
f.write(line)
except OSError as e:
print('EX: unable to write ' + filename + ' ' + str(e))
# write to an unfollowed file so that if a follow accept # write to an unfollowed file so that if a follow accept
# later arrives then it can be ignored # later arrives then it can be ignored
@ -312,8 +315,11 @@ def unfollowAccount(baseDir: str, nickname: str, domain: str,
with open(unfollowedFilename, 'a+') as f: with open(unfollowedFilename, 'a+') as f:
f.write(handleToUnfollow + '\n') f.write(handleToUnfollow + '\n')
else: else:
with open(unfollowedFilename, 'w+') as f: try:
f.write(handleToUnfollow + '\n') with open(unfollowedFilename, 'w+') as f:
f.write(handleToUnfollow + '\n')
except OSError:
print('EX: unable to write ' + unfollowedFilename)
return True return True
@ -341,9 +347,8 @@ def clearFollows(baseDir: str, nickname: str, domain: str,
if os.path.isfile(filename): if os.path.isfile(filename):
try: try:
os.remove(filename) os.remove(filename)
except BaseException: except OSError:
print('EX: clearFollows unable to delete ' + filename) print('EX: clearFollows unable to delete ' + filename)
pass
def clearFollowers(baseDir: str, nickname: str, domain: str) -> None: def clearFollowers(baseDir: str, nickname: str, domain: str) -> None:
@ -651,8 +656,11 @@ def _storeFollowRequest(baseDir: str,
print('DEBUG: ' + approveHandleStored + print('DEBUG: ' + approveHandleStored +
' is already awaiting approval') ' is already awaiting approval')
else: else:
with open(approveFollowsFilename, 'w+') as fp: try:
fp.write(approveHandleStored + '\n') with open(approveFollowsFilename, 'w+') as fp:
fp.write(approveHandleStored + '\n')
except OSError:
print('EX: unable to write ' + approveFollowsFilename)
# store the follow request in its own directory # store the follow request in its own directory
# We don't rely upon the inbox because items in there could expire # We don't rely upon the inbox because items in there could expire
@ -852,8 +860,11 @@ def receiveFollowRequest(session, baseDir: str, httpPrefix: str,
'Failed to write entry to followers file ' + 'Failed to write entry to followers file ' +
str(e)) str(e))
else: else:
with open(followersFilename, 'w+') as followersFile: try:
followersFile.write(approveHandle + '\n') with open(followersFilename, 'w+') as followersFile:
followersFile.write(approveHandle + '\n')
except OSError:
print('EX: unable to write ' + followersFilename)
print('Beginning follow accept') print('Beginning follow accept')
return followedAccountAccepts(session, baseDir, httpPrefix, return followedAccountAccepts(session, baseDir, httpPrefix,
@ -908,10 +919,9 @@ def followedAccountAccepts(session, baseDir: str, httpPrefix: str,
if os.path.isfile(followActivityfilename): if os.path.isfile(followActivityfilename):
try: try:
os.remove(followActivityfilename) os.remove(followActivityfilename)
except BaseException: except OSError:
print('EX: followedAccountAccepts unable to delete ' + print('EX: followedAccountAccepts unable to delete ' +
followActivityfilename) followActivityfilename)
pass
groupAccount = False groupAccount = False
if followJson: if followJson:
@ -983,10 +993,9 @@ def followedAccountRejects(session, baseDir: str, httpPrefix: str,
# remove the follow request json # remove the follow request json
try: try:
os.remove(followActivityfilename) os.remove(followActivityfilename)
except BaseException: except OSError:
print('EX: followedAccountRejects unable to delete ' + print('EX: followedAccountRejects unable to delete ' +
followActivityfilename) followActivityfilename)
pass
# send the reject activity # send the reject activity
return sendSignedJson(rejectJson, session, baseDir, return sendSignedJson(rejectJson, session, baseDir,
nicknameToFollow, domainToFollow, port, nicknameToFollow, domainToFollow, port,
@ -1049,8 +1058,11 @@ def sendFollowRequest(session, baseDir: str,
unfollowedFile = \ unfollowedFile = \
unfollowedFile.replace(followHandle + '\n', '') unfollowedFile.replace(followHandle + '\n', '')
if unfollowedFile: if unfollowedFile:
with open(unfollowedFilename, 'w+') as fp: try:
fp.write(unfollowedFile) with open(unfollowedFilename, 'w+') as fp:
fp.write(unfollowedFile)
except OSError:
print('EX: unable to write ' + unfollowedFilename)
newFollowJson = { newFollowJson = {
'@context': 'https://www.w3.org/ns/activitystreams', '@context': 'https://www.w3.org/ns/activitystreams',

View File

@ -46,8 +46,11 @@ def receivingCalendarEvents(baseDir: str, nickname: str, domain: str,
# create a new calendar file from the following file # create a new calendar file from the following file
with open(followingFilename, 'r') as followingFile: with open(followingFilename, 'r') as followingFile:
followingHandles = followingFile.read() followingHandles = followingFile.read()
with open(calendarFilename, 'w+') as fp: try:
fp.write(followingHandles) with open(calendarFilename, 'w+') as fp:
fp.write(followingHandles)
except OSError:
print('EX: unable to write ' + calendarFilename)
return handle + '\n' in open(calendarFilename).read() return handle + '\n' in open(calendarFilename).read()
@ -89,8 +92,11 @@ def _receiveCalendarEvents(baseDir: str, nickname: str, domain: str,
with open(followingFilename, 'r') as followingFile: with open(followingFilename, 'r') as followingFile:
followingHandles = followingFile.read() followingHandles = followingFile.read()
if add: if add:
with open(calendarFilename, 'w+') as fp: try:
fp.write(followingHandles + handle + '\n') with open(calendarFilename, 'w+') as fp:
fp.write(followingHandles + handle + '\n')
except OSError:
print('EX: unable to write ' + calendarFilename)
# already in the calendar file? # already in the calendar file?
if handle + '\n' in followingHandles: if handle + '\n' in followingHandles:
@ -100,16 +106,22 @@ def _receiveCalendarEvents(baseDir: str, nickname: str, domain: str,
return return
# remove from calendar file # remove from calendar file
followingHandles = followingHandles.replace(handle + '\n', '') followingHandles = followingHandles.replace(handle + '\n', '')
with open(calendarFilename, 'w+') as fp: try:
fp.write(followingHandles) with open(calendarFilename, 'w+') as fp:
fp.write(followingHandles)
except OSError:
print('EX: unable to write ' + calendarFilename)
else: else:
print(handle + ' not in followingCalendar.txt') print(handle + ' not in followingCalendar.txt')
# not already in the calendar file # not already in the calendar file
if add: if add:
# append to the list of handles # append to the list of handles
followingHandles += handle + '\n' followingHandles += handle + '\n'
with open(calendarFilename, 'w+') as fp: try:
fp.write(followingHandles) with open(calendarFilename, 'w+') as fp:
fp.write(followingHandles)
except OSError:
print('EX: unable to write ' + calendarFilename)
def addPersonToCalendar(baseDir: str, nickname: str, domain: str, def addPersonToCalendar(baseDir: str, nickname: str, domain: str,

15
git.py
View File

@ -208,11 +208,14 @@ def receiveGitPatch(baseDir: str, nickname: str, domain: str,
return False return False
patchStr = \ patchStr = \
_gitAddFromHandle(patchStr, '@' + fromNickname + '@' + fromDomain) _gitAddFromHandle(patchStr, '@' + fromNickname + '@' + fromDomain)
with open(patchFilename, 'w+') as patchFile: try:
patchFile.write(patchStr) with open(patchFilename, 'w+') as patchFile:
patchNotifyFilename = \
acctDir(baseDir, nickname, domain) + '/.newPatchContent'
with open(patchNotifyFilename, 'w+') as patchFile:
patchFile.write(patchStr) patchFile.write(patchStr)
return True patchNotifyFilename = \
acctDir(baseDir, nickname, domain) + '/.newPatchContent'
with open(patchNotifyFilename, 'w+') as patchFile:
patchFile.write(patchStr)
return True
except OSError as e:
print('EX: unable to write patch ' + patchFilename + ' ' + str(e))
return False return False

View File

@ -41,9 +41,8 @@ def _removeEventFromTimeline(eventId: str, tlEventsFilename: str) -> None:
try: try:
with open(tlEventsFilename, 'w+') as fp2: with open(tlEventsFilename, 'w+') as fp2:
fp2.write(eventsTimeline) fp2.write(eventsTimeline)
except BaseException: except OSError:
print('EX: ERROR: unable to save events timeline') print('EX: ERROR: unable to save events timeline')
pass
def saveEventPost(baseDir: str, handle: str, postId: str, def saveEventPost(baseDir: str, handle: str, postId: str,
@ -105,13 +104,16 @@ def saveEventPost(baseDir: str, handle: str, postId: str,
if eventId + '\n' not in content: if eventId + '\n' not in content:
tlEventsFile.seek(0, 0) tlEventsFile.seek(0, 0)
tlEventsFile.write(eventId + '\n' + content) tlEventsFile.write(eventId + '\n' + content)
except Exception as e: except OSError as e:
print('WARN: Failed to write entry to events file ' + print('EX: Failed to write entry to events file ' +
tlEventsFilename + ' ' + str(e)) tlEventsFilename + ' ' + str(e))
return False return False
else: else:
with open(tlEventsFilename, 'w+') as tlEventsFile: try:
tlEventsFile.write(eventId + '\n') with open(tlEventsFilename, 'w+') as tlEventsFile:
tlEventsFile.write(eventId + '\n')
except OSError:
print('EX: unable to write ' + tlEventsFilename)
# create a directory for the calendar year # create a directory for the calendar year
if not os.path.isdir(calendarPath + '/' + str(eventYear)): if not os.path.isdir(calendarPath + '/' + str(eventYear)):
@ -128,18 +130,24 @@ def saveEventPost(baseDir: str, handle: str, postId: str,
return False return False
# append the post Id to the file for the calendar month # append the post Id to the file for the calendar month
with open(calendarFilename, 'a+') as calendarFile: try:
calendarFile.write(postId + '\n') with open(calendarFilename, 'a+') as calendarFile:
calendarFile.write(postId + '\n')
except OSError:
print('EX: unable to append ' + calendarFilename)
# create a file which will trigger a notification that # create a file which will trigger a notification that
# a new event has been added # a new event has been added
calendarNotificationFilename = \ calNotifyFilename = baseDir + '/accounts/' + handle + '/.newCalendar'
baseDir + '/accounts/' + handle + '/.newCalendar' notifyStr = \
with open(calendarNotificationFilename, 'w+') as calendarNotificationFile: '/calendar?year=' + str(eventYear) + '?month=' + \
notifyStr = \ str(eventMonthNumber) + '?day=' + str(eventDayOfMonth)
'/calendar?year=' + str(eventYear) + '?month=' + \ try:
str(eventMonthNumber) + '?day=' + str(eventDayOfMonth) with open(calNotifyFilename, 'w+') as calendarNotificationFile:
calendarNotificationFile.write(notifyStr) calendarNotificationFile.write(notifyStr)
except OSError:
print('EX: unable to write ' + calNotifyFilename)
return False
return True return True
@ -244,9 +252,12 @@ def getTodaysEvents(baseDir: str, nickname: str, domain: str,
# if some posts have been deleted then regenerate the calendar file # if some posts have been deleted then regenerate the calendar file
if recreateEventsFile: if recreateEventsFile:
with open(calendarFilename, 'w+') as calendarFile: try:
for postId in calendarPostIds: with open(calendarFilename, 'w+') as calendarFile:
calendarFile.write(postId + '\n') for postId in calendarPostIds:
calendarFile.write(postId + '\n')
except OSError:
print('EX: unable to write ' + calendarFilename)
return events return events
@ -360,9 +371,12 @@ def getThisWeeksEvents(baseDir: str, nickname: str, domain: str) -> {}:
# if some posts have been deleted then regenerate the calendar file # if some posts have been deleted then regenerate the calendar file
if recreateEventsFile: if recreateEventsFile:
with open(calendarFilename, 'w+') as calendarFile: try:
for postId in calendarPostIds: with open(calendarFilename, 'w+') as calendarFile:
calendarFile.write(postId + '\n') for postId in calendarPostIds:
calendarFile.write(postId + '\n')
except OSError:
print('EX: unable to write ' + calendarFilename)
return events return events
@ -424,9 +438,12 @@ def getCalendarEvents(baseDir: str, nickname: str, domain: str,
# if some posts have been deleted then regenerate the calendar file # if some posts have been deleted then regenerate the calendar file
if recreateEventsFile: if recreateEventsFile:
with open(calendarFilename, 'w+') as calendarFile: try:
for postId in calendarPostIds: with open(calendarFilename, 'w+') as calendarFile:
calendarFile.write(postId + '\n') for postId in calendarPostIds:
calendarFile.write(postId + '\n')
except OSError:
print('EX: unable to write ' + calendarFilename)
return events return events
@ -449,7 +466,10 @@ def removeCalendarEvent(baseDir: str, nickname: str, domain: str,
lines = f.readlines() lines = f.readlines()
if not lines: if not lines:
return return
with open(calendarFilename, 'w+') as f: try:
for line in lines: with open(calendarFilename, 'w+') as f:
if messageId not in line: for line in lines:
f.write(line) if messageId not in line:
f.write(line)
except OSError:
print('EX: unable to write ' + calendarFilename)

173
inbox.py
View File

@ -141,9 +141,8 @@ def _storeLastPostId(baseDir: str, nickname: str, domain: str,
try: try:
with open(actorFilename, 'w+') as fp: with open(actorFilename, 'w+') as fp:
fp.write(postId) fp.write(postId)
except BaseException: except OSError:
print('EX: Unable to write last post id to ' + actorFilename) print('EX: Unable to write last post id to ' + actorFilename)
pass
def _updateCachedHashtagSwarm(baseDir: str, nickname: str, domain: str, def _updateCachedHashtagSwarm(baseDir: str, nickname: str, domain: str,
@ -185,10 +184,9 @@ def _updateCachedHashtagSwarm(baseDir: str, nickname: str, domain: str,
with open(cachedHashtagSwarmFilename, 'w+') as fp: with open(cachedHashtagSwarmFilename, 'w+') as fp:
fp.write(newSwarmStr) fp.write(newSwarmStr)
return True return True
except BaseException: except OSError:
print('EX: unable to write cached hashtag swarm ' + print('EX: unable to write cached hashtag swarm ' +
cachedHashtagSwarmFilename) cachedHashtagSwarmFilename)
pass
return False return False
@ -238,8 +236,11 @@ def storeHashTags(baseDir: str, nickname: str, domain: str,
tagline = str(daysSinceEpoch) + ' ' + nickname + ' ' + postUrl + '\n' tagline = str(daysSinceEpoch) + ' ' + nickname + ' ' + postUrl + '\n'
hashtagsCtr += 1 hashtagsCtr += 1
if not os.path.isfile(tagsFilename): if not os.path.isfile(tagsFilename):
with open(tagsFilename, 'w+') as tagsFile: try:
tagsFile.write(tagline) with open(tagsFilename, 'w+') as tagsFile:
tagsFile.write(tagline)
except OSError:
print('EX: unable to write ' + tagsFilename)
else: else:
if postUrl not in open(tagsFilename).read(): if postUrl not in open(tagsFilename).read():
try: try:
@ -248,8 +249,8 @@ def storeHashTags(baseDir: str, nickname: str, domain: str,
if tagline not in content: if tagline not in content:
tagsFile.seek(0, 0) tagsFile.seek(0, 0)
tagsFile.write(tagline + content) tagsFile.write(tagline + content)
except Exception as e: except OSError as e:
print('WARN: Failed to write entry to tags file ' + print('EX: Failed to write entry to tags file ' +
tagsFilename + ' ' + str(e)) tagsFilename + ' ' + str(e))
removeOldHashtags(baseDir, 3) removeOldHashtags(baseDir, 3)
@ -920,7 +921,7 @@ def _receiveUpdateToQuestion(recentPostsCache: {}, messageJson: {},
if os.path.isfile(cachedPostFilename): if os.path.isfile(cachedPostFilename):
try: try:
os.remove(cachedPostFilename) os.remove(cachedPostFilename)
except BaseException: except OSError:
print('EX: _receiveUpdateToQuestion unable to delete ' + print('EX: _receiveUpdateToQuestion unable to delete ' +
cachedPostFilename) cachedPostFilename)
# remove from memory cache # remove from memory cache
@ -1944,10 +1945,9 @@ def _receiveAnnounce(recentPostsCache: {},
# if the announce can't be downloaded then remove it # if the announce can't be downloaded then remove it
try: try:
os.remove(postFilename) os.remove(postFilename)
except BaseException: except OSError:
print('EX: _receiveAnnounce unable to delete ' + print('EX: _receiveAnnounce unable to delete ' +
str(postFilename)) str(postFilename))
pass
else: else:
if debug: if debug:
print('DEBUG: Announce post downloaded for ' + print('DEBUG: Announce post downloaded for ' +
@ -1980,8 +1980,12 @@ def _receiveAnnounce(recentPostsCache: {},
postJsonObject, personCache, postJsonObject, personCache,
translate, lookupActor, translate, lookupActor,
themeName) themeName)
with open(postFilename + '.tts', 'w+') as ttsFile: try:
ttsFile.write('\n') with open(postFilename + '.tts', 'w+') as ttsFile:
ttsFile.write('\n')
except OSError:
print('EX: unable to write recent post ' +
postFilename)
if debug: if debug:
print('DEBUG: Obtaining actor for announce post ' + print('DEBUG: Obtaining actor for announce post ' +
@ -2059,10 +2063,9 @@ def _receiveUndoAnnounce(recentPostsCache: {},
if os.path.isfile(postFilename): if os.path.isfile(postFilename):
try: try:
os.remove(postFilename) os.remove(postFilename)
except BaseException: except OSError:
print('EX: _receiveUndoAnnounce unable to delete ' + print('EX: _receiveUndoAnnounce unable to delete ' +
str(postFilename)) str(postFilename))
pass
return True return True
@ -2146,11 +2149,17 @@ def populateReplies(baseDir: str, httpPrefix: str, domain: str,
if numLines > maxReplies: if numLines > maxReplies:
return False return False
if messageId not in open(postRepliesFilename).read(): if messageId not in open(postRepliesFilename).read():
with open(postRepliesFilename, 'a+') as repliesFile: try:
repliesFile.write(messageId + '\n') with open(postRepliesFilename, 'a+') as repliesFile:
repliesFile.write(messageId + '\n')
except OSError:
print('EX: unable to append ' + postRepliesFilename)
else: else:
with open(postRepliesFilename, 'w+') as repliesFile: try:
repliesFile.write(messageId + '\n') with open(postRepliesFilename, 'w+') as repliesFile:
repliesFile.write(messageId + '\n')
except OSError:
print('EX: unable to write ' + postRepliesFilename)
return True return True
@ -2323,8 +2332,11 @@ def _dmNotify(baseDir: str, handle: str, url: str) -> None:
return return
dmFile = accountDir + '/.newDM' dmFile = accountDir + '/.newDM'
if not os.path.isfile(dmFile): if not os.path.isfile(dmFile):
with open(dmFile, 'w+') as fp: try:
fp.write(url) with open(dmFile, 'w+') as fp:
fp.write(url)
except OSError:
print('EX: unable to write ' + dmFile)
def _alreadyLiked(baseDir: str, nickname: str, domain: str, def _alreadyLiked(baseDir: str, nickname: str, domain: str,
@ -2439,17 +2451,16 @@ def _likeNotify(baseDir: str, domain: str, onionDomain: str,
try: try:
with open(prevLikeFile, 'w+') as fp: with open(prevLikeFile, 'w+') as fp:
fp.write(likeStr) fp.write(likeStr)
except BaseException: except OSError:
print('EX: ERROR: unable to save previous like notification ' + print('EX: ERROR: unable to save previous like notification ' +
prevLikeFile) prevLikeFile)
pass
try: try:
with open(likeFile, 'w+') as fp: with open(likeFile, 'w+') as fp:
fp.write(likeStr) fp.write(likeStr)
except BaseException: except OSError:
print('EX: ERROR: unable to write like notification file ' + print('EX: ERROR: unable to write like notification file ' +
likeFile) likeFile)
pass
def _reactionNotify(baseDir: str, domain: str, onionDomain: str, def _reactionNotify(baseDir: str, domain: str, onionDomain: str,
@ -2504,17 +2515,16 @@ def _reactionNotify(baseDir: str, domain: str, onionDomain: str,
try: try:
with open(prevReactionFile, 'w+') as fp: with open(prevReactionFile, 'w+') as fp:
fp.write(reactionStr) fp.write(reactionStr)
except BaseException: except OSError:
print('EX: ERROR: unable to save previous reaction notification ' + print('EX: ERROR: unable to save previous reaction notification ' +
prevReactionFile) prevReactionFile)
pass
try: try:
with open(reactionFile, 'w+') as fp: with open(reactionFile, 'w+') as fp:
fp.write(reactionStr) fp.write(reactionStr)
except BaseException: except OSError:
print('EX: ERROR: unable to write reaction notification file ' + print('EX: ERROR: unable to write reaction notification file ' +
reactionFile) reactionFile)
pass
def _notifyPostArrival(baseDir: str, handle: str, url: str) -> None: def _notifyPostArrival(baseDir: str, handle: str, url: str) -> None:
@ -2532,8 +2542,11 @@ def _notifyPostArrival(baseDir: str, handle: str, url: str) -> None:
existingNotificationMessage = fp.read() existingNotificationMessage = fp.read()
if url in existingNotificationMessage: if url in existingNotificationMessage:
return return
with open(notifyFile, 'w+') as fp: try:
fp.write(url) with open(notifyFile, 'w+') as fp:
fp.write(url)
except OSError:
print('EX: unable to write ' + notifyFile)
def _replyNotify(baseDir: str, handle: str, url: str) -> None: def _replyNotify(baseDir: str, handle: str, url: str) -> None:
@ -2544,8 +2557,11 @@ def _replyNotify(baseDir: str, handle: str, url: str) -> None:
return return
replyFile = accountDir + '/.newReply' replyFile = accountDir + '/.newReply'
if not os.path.isfile(replyFile): if not os.path.isfile(replyFile):
with open(replyFile, 'w+') as fp: try:
fp.write(url) with open(replyFile, 'w+') as fp:
fp.write(url)
except OSError:
print('EX: unable to write ' + replyFile)
def _gitPatchNotify(baseDir: str, handle: str, def _gitPatchNotify(baseDir: str, handle: str,
@ -2559,8 +2575,11 @@ def _gitPatchNotify(baseDir: str, handle: str,
patchFile = accountDir + '/.newPatch' patchFile = accountDir + '/.newPatch'
subject = subject.replace('[PATCH]', '').strip() subject = subject.replace('[PATCH]', '').strip()
handle = '@' + fromNickname + '@' + fromDomain handle = '@' + fromNickname + '@' + fromDomain
with open(patchFile, 'w+') as fp: try:
fp.write('git ' + handle + ' ' + subject) with open(patchFile, 'w+') as fp:
fp.write('git ' + handle + ' ' + subject)
except OSError:
print('EX: unable to write ' + patchFile)
def _groupHandle(baseDir: str, handle: str) -> bool: def _groupHandle(baseDir: str, handle: str) -> bool:
@ -2710,15 +2729,15 @@ def inboxUpdateIndex(boxname: str, baseDir: str, handle: str,
indexFile.write(destinationFilename + '\n' + content) indexFile.write(destinationFilename + '\n' + content)
written = True written = True
return True return True
except Exception as e: except OSError as e:
print('WARN: Failed to write entry to index ' + str(e)) print('EX: Failed to write entry to index ' + str(e))
else: else:
try: try:
with open(indexFilename, 'w+') as indexFile: with open(indexFilename, 'w+') as indexFile:
indexFile.write(destinationFilename + '\n') indexFile.write(destinationFilename + '\n')
written = True written = True
except Exception as e: except OSError as e:
print('WARN: Failed to write initial entry to index ' + str(e)) print('EX: Failed to write initial entry to index ' + str(e))
return written return written
@ -2750,8 +2769,11 @@ def _updateLastSeen(baseDir: str, handle: str, actor: str) -> None:
if int(daysSinceEpochFile) == daysSinceEpoch: if int(daysSinceEpochFile) == daysSinceEpoch:
# value hasn't changed, so we can save writing anything to file # value hasn't changed, so we can save writing anything to file
return return
with open(lastSeenFilename, 'w+') as lastSeenFile: try:
lastSeenFile.write(str(daysSinceEpoch)) with open(lastSeenFilename, 'w+') as lastSeenFile:
lastSeenFile.write(str(daysSinceEpoch))
except OSError:
print('EX: unable to write ' + lastSeenFilename)
def _bounceDM(senderPostId: str, session, httpPrefix: str, def _bounceDM(senderPostId: str, session, httpPrefix: str,
@ -2973,7 +2995,7 @@ def _receiveQuestionVote(baseDir: str, nickname: str, domain: str,
if os.path.isfile(cachedPostFilename): if os.path.isfile(cachedPostFilename):
try: try:
os.remove(cachedPostFilename) os.remove(cachedPostFilename)
except BaseException: except OSError:
print('EX: replytoQuestion unable to delete ' + print('EX: replytoQuestion unable to delete ' +
cachedPostFilename) cachedPostFilename)
@ -3486,8 +3508,12 @@ def _inboxAfterInitial(recentPostsCache: {}, maxRecentPosts: int,
# This enables you to ignore a threat that's getting boring # This enables you to ignore a threat that's getting boring
if isReplyToMutedPost: if isReplyToMutedPost:
print('MUTE REPLY: ' + destinationFilename) print('MUTE REPLY: ' + destinationFilename)
with open(destinationFilename + '.muted', 'w+') as muteFile: destinationFilenameMuted = destinationFilename + '.muted'
muteFile.write('\n') try:
with open(destinationFilenameMuted, 'w+') as muteFile:
muteFile.write('\n')
except OSError:
print('EX: unable to write ' + destinationFilenameMuted)
# update the indexes for different timelines # update the indexes for different timelines
for boxname in updateIndexList: for boxname in updateIndexList:
@ -3592,9 +3618,8 @@ def clearQueueItems(baseDir: str, queue: []) -> None:
try: try:
os.remove(os.path.join(queueDir, qfile)) os.remove(os.path.join(queueDir, qfile))
ctr += 1 ctr += 1
except BaseException: except OSError:
print('EX: clearQueueItems unable to delete ' + qfile) print('EX: clearQueueItems unable to delete ' + qfile)
pass
break break
break break
if ctr > 0: if ctr > 0:
@ -3659,10 +3684,9 @@ def _inboxQuotaExceeded(queue: {}, queueFilename: str,
if len(queue) > 0: if len(queue) > 0:
try: try:
os.remove(queueFilename) os.remove(queueFilename)
except BaseException: except OSError:
print('EX: _inboxQuotaExceeded unable to delete ' + print('EX: _inboxQuotaExceeded unable to delete ' +
str(queueFilename)) str(queueFilename))
pass
queue.pop(0) queue.pop(0)
return True return True
quotasDaily['domains'][postDomain] += 1 quotasDaily['domains'][postDomain] += 1
@ -3682,10 +3706,9 @@ def _inboxQuotaExceeded(queue: {}, queueFilename: str,
if len(queue) > 0: if len(queue) > 0:
try: try:
os.remove(queueFilename) os.remove(queueFilename)
except BaseException: except OSError:
print('EX: _inboxQuotaExceeded unable to delete ' + print('EX: _inboxQuotaExceeded unable to delete ' +
str(queueFilename)) str(queueFilename))
pass
queue.pop(0) queue.pop(0)
return True return True
quotasPerMin['domains'][postDomain] += 1 quotasPerMin['domains'][postDomain] += 1
@ -3704,10 +3727,9 @@ def _inboxQuotaExceeded(queue: {}, queueFilename: str,
if len(queue) > 0: if len(queue) > 0:
try: try:
os.remove(queueFilename) os.remove(queueFilename)
except BaseException: except OSError:
print('EX: _inboxQuotaExceeded unable to delete ' + print('EX: _inboxQuotaExceeded unable to delete ' +
str(queueFilename)) str(queueFilename))
pass
queue.pop(0) queue.pop(0)
return True return True
quotasDaily['accounts'][postHandle] += 1 quotasDaily['accounts'][postHandle] += 1
@ -3728,10 +3750,9 @@ def _inboxQuotaExceeded(queue: {}, queueFilename: str,
if len(queue) > 0: if len(queue) > 0:
try: try:
os.remove(queueFilename) os.remove(queueFilename)
except BaseException: except OSError:
print('EX: _inboxQuotaExceeded unable to delete ' + print('EX: _inboxQuotaExceeded unable to delete ' +
str(queueFilename)) str(queueFilename))
pass
queue.pop(0) queue.pop(0)
return True return True
quotasPerMin['accounts'][postHandle] += 1 quotasPerMin['accounts'][postHandle] += 1
@ -3779,8 +3800,11 @@ def _checkJsonSignature(baseDir: str, queueJson: {}) -> (bool, bool):
alreadyUnknown = True alreadyUnknown = True
if not alreadyUnknown: if not alreadyUnknown:
with open(unknownContextsFile, 'a+') as unknownFile: try:
unknownFile.write(unknownContext + '\n') with open(unknownContextsFile, 'a+') as unknownFile:
unknownFile.write(unknownContext + '\n')
except OSError:
print('EX: unable to append ' + unknownContextsFile)
else: else:
print('Unrecognized jsonld signature type: ' + jwebsigType) print('Unrecognized jsonld signature type: ' + jwebsigType)
@ -3794,8 +3818,11 @@ def _checkJsonSignature(baseDir: str, queueJson: {}) -> (bool, bool):
alreadyUnknown = True alreadyUnknown = True
if not alreadyUnknown: if not alreadyUnknown:
with open(unknownSignaturesFile, 'a+') as unknownFile: try:
unknownFile.write(jwebsigType + '\n') with open(unknownSignaturesFile, 'a+') as unknownFile:
unknownFile.write(jwebsigType + '\n')
except OSError:
print('EX: unable to append ' + unknownSignaturesFile)
return hasJsonSignature, jwebsigType return hasJsonSignature, jwebsigType
@ -3913,10 +3940,9 @@ def runInboxQueue(recentPostsCache: {}, maxRecentPosts: int,
if os.path.isfile(queueFilename): if os.path.isfile(queueFilename):
try: try:
os.remove(queueFilename) os.remove(queueFilename)
except BaseException: except OSError:
print('EX: runInboxQueue 1 unable to delete ' + print('EX: runInboxQueue 1 unable to delete ' +
str(queueFilename)) str(queueFilename))
pass
continue continue
# clear the daily quotas for maximum numbers of received posts # clear the daily quotas for maximum numbers of received posts
@ -3988,10 +4014,9 @@ def runInboxQueue(recentPostsCache: {}, maxRecentPosts: int,
if os.path.isfile(queueFilename): if os.path.isfile(queueFilename):
try: try:
os.remove(queueFilename) os.remove(queueFilename)
except BaseException: except OSError:
print('EX: runInboxQueue 2 unable to delete ' + print('EX: runInboxQueue 2 unable to delete ' +
str(queueFilename)) str(queueFilename))
pass
if len(queue) > 0: if len(queue) > 0:
queue.pop(0) queue.pop(0)
continue continue
@ -4041,10 +4066,9 @@ def runInboxQueue(recentPostsCache: {}, maxRecentPosts: int,
if os.path.isfile(queueFilename): if os.path.isfile(queueFilename):
try: try:
os.remove(queueFilename) os.remove(queueFilename)
except BaseException: except OSError:
print('EX: runInboxQueue 3 unable to delete ' + print('EX: runInboxQueue 3 unable to delete ' +
str(queueFilename)) str(queueFilename))
pass
if len(queue) > 0: if len(queue) > 0:
queue.pop(0) queue.pop(0)
continue continue
@ -4063,10 +4087,9 @@ def runInboxQueue(recentPostsCache: {}, maxRecentPosts: int,
if os.path.isfile(queueFilename): if os.path.isfile(queueFilename):
try: try:
os.remove(queueFilename) os.remove(queueFilename)
except BaseException: except OSError:
print('EX: runInboxQueue 4 unable to delete ' + print('EX: runInboxQueue 4 unable to delete ' +
str(queueFilename)) str(queueFilename))
pass
if len(queue) > 0: if len(queue) > 0:
queue.pop(0) queue.pop(0)
continue continue
@ -4094,10 +4117,9 @@ def runInboxQueue(recentPostsCache: {}, maxRecentPosts: int,
if os.path.isfile(queueFilename): if os.path.isfile(queueFilename):
try: try:
os.remove(queueFilename) os.remove(queueFilename)
except BaseException: except OSError:
print('EX: runInboxQueue 5 unable to delete ' + print('EX: runInboxQueue 5 unable to delete ' +
str(queueFilename)) str(queueFilename))
pass
if len(queue) > 0: if len(queue) > 0:
queue.pop(0) queue.pop(0)
continue continue
@ -4117,10 +4139,9 @@ def runInboxQueue(recentPostsCache: {}, maxRecentPosts: int,
if os.path.isfile(queueFilename): if os.path.isfile(queueFilename):
try: try:
os.remove(queueFilename) os.remove(queueFilename)
except BaseException: except OSError:
print('EX: runInboxQueue 6 unable to delete ' + print('EX: runInboxQueue 6 unable to delete ' +
str(queueFilename)) str(queueFilename))
pass
if len(queue) > 0: if len(queue) > 0:
queue.pop(0) queue.pop(0)
print('Queue: Follow activity for ' + keyId + print('Queue: Follow activity for ' + keyId +
@ -4140,10 +4161,9 @@ def runInboxQueue(recentPostsCache: {}, maxRecentPosts: int,
if os.path.isfile(queueFilename): if os.path.isfile(queueFilename):
try: try:
os.remove(queueFilename) os.remove(queueFilename)
except BaseException: except OSError:
print('EX: runInboxQueue 7 unable to delete ' + print('EX: runInboxQueue 7 unable to delete ' +
str(queueFilename)) str(queueFilename))
pass
if len(queue) > 0: if len(queue) > 0:
queue.pop(0) queue.pop(0)
continue continue
@ -4163,10 +4183,9 @@ def runInboxQueue(recentPostsCache: {}, maxRecentPosts: int,
if os.path.isfile(queueFilename): if os.path.isfile(queueFilename):
try: try:
os.remove(queueFilename) os.remove(queueFilename)
except BaseException: except OSError:
print('EX: runInboxQueue 8 unable to delete ' + print('EX: runInboxQueue 8 unable to delete ' +
str(queueFilename)) str(queueFilename))
pass
if len(queue) > 0: if len(queue) > 0:
queue.pop(0) queue.pop(0)
continue continue
@ -4183,10 +4202,9 @@ def runInboxQueue(recentPostsCache: {}, maxRecentPosts: int,
if os.path.isfile(queueFilename): if os.path.isfile(queueFilename):
try: try:
os.remove(queueFilename) os.remove(queueFilename)
except BaseException: except OSError:
print('EX: runInboxQueue 9 unable to delete ' + print('EX: runInboxQueue 9 unable to delete ' +
str(queueFilename)) str(queueFilename))
pass
if len(queue) > 0: if len(queue) > 0:
queue.pop(0) queue.pop(0)
continue continue
@ -4265,9 +4283,8 @@ def runInboxQueue(recentPostsCache: {}, maxRecentPosts: int,
if os.path.isfile(queueFilename): if os.path.isfile(queueFilename):
try: try:
os.remove(queueFilename) os.remove(queueFilename)
except BaseException: except OSError:
print('EX: runInboxQueue 10 unable to delete ' + print('EX: runInboxQueue 10 unable to delete ' +
str(queueFilename)) str(queueFilename))
pass
if len(queue) > 0: if len(queue) > 0:
queue.pop(0) queue.pop(0)

View File

@ -430,10 +430,9 @@ def updateLikesCollection(recentPostsCache: {},
if os.path.isfile(cachedPostFilename): if os.path.isfile(cachedPostFilename):
try: try:
os.remove(cachedPostFilename) os.remove(cachedPostFilename)
except BaseException: except OSError:
print('EX: updateLikesCollection unable to delete ' + print('EX: updateLikesCollection unable to delete ' +
cachedPostFilename) cachedPostFilename)
pass
obj = postJsonObject obj = postJsonObject
if hasObjectDict(postJsonObject): if hasObjectDict(postJsonObject):

View File

@ -46,8 +46,11 @@ def manualDenyFollowRequest(session, baseDir: str,
removeFromFollowRequests(baseDir, nickname, domain, denyHandle, debug) removeFromFollowRequests(baseDir, nickname, domain, denyHandle, debug)
# Store rejected follows # Store rejected follows
with open(rejectedFollowsFilename, 'a+') as rejectsFile: try:
rejectsFile.write(denyHandle + '\n') with open(rejectedFollowsFilename, 'a+') as rejectsFile:
rejectsFile.write(denyHandle + '\n')
except OSError:
print('EX: unable to append ' + rejectedFollowsFilename)
denyNickname = denyHandle.split('@')[0] denyNickname = denyHandle.split('@')[0]
denyDomain = \ denyDomain = \
@ -104,11 +107,17 @@ def _approveFollowerHandle(accountDir: str, approveHandle: str) -> None:
approvedFilename = accountDir + '/approved.txt' approvedFilename = accountDir + '/approved.txt'
if os.path.isfile(approvedFilename): if os.path.isfile(approvedFilename):
if approveHandle not in open(approvedFilename).read(): if approveHandle not in open(approvedFilename).read():
with open(approvedFilename, 'a+') as approvedFile: try:
approvedFile.write(approveHandle + '\n') with open(approvedFilename, 'a+') as approvedFile:
approvedFile.write(approveHandle + '\n')
except OSError:
print('EX: unable to append ' + approvedFilename)
else: else:
with open(approvedFilename, 'w+') as approvedFile: try:
approvedFile.write(approveHandle + '\n') with open(approvedFilename, 'w+') as approvedFile:
approvedFile.write(approveHandle + '\n')
except OSError:
print('EX: unable to write ' + approvedFilename)
def manualApproveFollowRequest(session, baseDir: str, def manualApproveFollowRequest(session, baseDir: str,
@ -239,8 +248,11 @@ def manualApproveFollowRequest(session, baseDir: str,
else: else:
print('Manual follow accept: first follower accepted for ' + print('Manual follow accept: first follower accepted for ' +
handle + ' is ' + approveHandleFull) handle + ' is ' + approveHandleFull)
with open(followersFilename, 'w+') as followersFile: try:
followersFile.write(approveHandleFull + '\n') with open(followersFilename, 'w+') as followersFile:
followersFile.write(approveHandleFull + '\n')
except OSError:
print('EX: unable to write ' + followersFilename)
# only update the follow requests file if the follow is confirmed to be # only update the follow requests file if the follow is confirmed to be
# in followers.txt # in followers.txt
@ -254,17 +266,15 @@ def manualApproveFollowRequest(session, baseDir: str,
if os.path.isfile(followActivityfilename): if os.path.isfile(followActivityfilename):
try: try:
os.remove(followActivityfilename) os.remove(followActivityfilename)
except BaseException: except OSError:
print('EX: manualApproveFollowRequest unable to delete ' + print('EX: manualApproveFollowRequest unable to delete ' +
followActivityfilename) followActivityfilename)
pass
else: else:
try: try:
os.remove(approveFollowsFilename + '.new') os.remove(approveFollowsFilename + '.new')
except BaseException: except OSError:
print('EX: manualApproveFollowRequest unable to delete ' + print('EX: manualApproveFollowRequest unable to delete ' +
approveFollowsFilename + '.new') approveFollowsFilename + '.new')
pass
def manualApproveFollowRequestThread(session, baseDir: str, def manualApproveFollowRequestThread(session, baseDir: str,

View File

@ -126,9 +126,8 @@ def _spoofMetaData(baseDir: str, nickname: str, domain: str,
try: try:
with open(decoySeedFilename, 'w+') as fp: with open(decoySeedFilename, 'w+') as fp:
fp.write(str(decoySeed)) fp.write(str(decoySeed))
except BaseException: except OSError:
print('EX: unable to write ' + decoySeedFilename) print('EX: unable to write ' + decoySeedFilename)
pass
if os.path.isfile('/usr/bin/exiftool'): if os.path.isfile('/usr/bin/exiftool'):
print('Spoofing metadata in ' + outputFilename + ' using exiftool') print('Spoofing metadata in ' + outputFilename + ' using exiftool')
@ -168,10 +167,9 @@ def convertImageToLowBandwidth(imageFilename: str) -> None:
if os.path.isfile(lowBandwidthFilename): if os.path.isfile(lowBandwidthFilename):
try: try:
os.remove(lowBandwidthFilename) os.remove(lowBandwidthFilename)
except BaseException: except OSError:
print('EX: convertImageToLowBandwidth unable to delete ' + print('EX: convertImageToLowBandwidth unable to delete ' +
lowBandwidthFilename) lowBandwidthFilename)
pass
cmd = \ cmd = \
'/usr/bin/convert +noise Multiplicative ' + \ '/usr/bin/convert +noise Multiplicative ' + \
@ -191,10 +189,9 @@ def convertImageToLowBandwidth(imageFilename: str) -> None:
if os.path.isfile(lowBandwidthFilename): if os.path.isfile(lowBandwidthFilename):
try: try:
os.remove(imageFilename) os.remove(imageFilename)
except BaseException: except OSError:
print('EX: convertImageToLowBandwidth unable to delete ' + print('EX: convertImageToLowBandwidth unable to delete ' +
imageFilename) imageFilename)
pass
os.rename(lowBandwidthFilename, imageFilename) os.rename(lowBandwidthFilename, imageFilename)
if os.path.isfile(imageFilename): if os.path.isfile(imageFilename):
print('Image converted to low bandwidth ' + imageFilename) print('Image converted to low bandwidth ' + imageFilename)
@ -280,9 +277,8 @@ def _updateEtag(mediaFilename: str) -> None:
try: try:
with open(mediaFilename, 'rb') as mediaFile: with open(mediaFilename, 'rb') as mediaFile:
data = mediaFile.read() data = mediaFile.read()
except BaseException: except OSError:
print('EX: _updateEtag unable to read ' + str(mediaFilename)) print('EX: _updateEtag unable to read ' + str(mediaFilename))
pass
if not data: if not data:
return return
@ -292,10 +288,9 @@ def _updateEtag(mediaFilename: str) -> None:
try: try:
with open(mediaFilename + '.etag', 'w+') as etagFile: with open(mediaFilename + '.etag', 'w+') as etagFile:
etagFile.write(etag) etagFile.write(etag)
except BaseException: except OSError:
print('EX: _updateEtag unable to write ' + print('EX: _updateEtag unable to write ' +
str(mediaFilename) + '.etag') str(mediaFilename) + '.etag')
pass
def attachMedia(baseDir: str, httpPrefix: str, def attachMedia(baseDir: str, httpPrefix: str,

View File

@ -57,15 +57,21 @@ def _updateFeedsOutboxIndex(baseDir: str, domain: str, postId: str) -> None:
print('WARN: Failed to write entry to feeds posts index ' + print('WARN: Failed to write entry to feeds posts index ' +
indexFilename + ' ' + str(e)) indexFilename + ' ' + str(e))
else: else:
with open(indexFilename, 'w+') as feedsFile: try:
feedsFile.write(postId + '\n') with open(indexFilename, 'w+') as feedsFile:
feedsFile.write(postId + '\n')
except OSError:
print('EX: unable to write ' + indexFilename)
def _saveArrivedTime(baseDir: str, postFilename: str, arrived: str) -> None: def _saveArrivedTime(baseDir: str, postFilename: str, arrived: str) -> None:
"""Saves the time when an rss post arrived to a file """Saves the time when an rss post arrived to a file
""" """
with open(postFilename + '.arrived', 'w+') as arrivedFile: try:
arrivedFile.write(arrived) with open(postFilename + '.arrived', 'w+') as arrivedFile:
arrivedFile.write(arrived)
except OSError:
print('EX: unable to write ' + postFilename + '.arrived')
def _removeControlCharacters(content: str) -> str: def _removeControlCharacters(content: str) -> str:
@ -483,8 +489,11 @@ def _createNewsMirror(baseDir: str, domain: str,
for removePostId in removals: for removePostId in removals:
indexContent = \ indexContent = \
indexContent.replace(removePostId + '\n', '') indexContent.replace(removePostId + '\n', '')
with open(mirrorIndexFilename, 'w+') as indexFile: try:
indexFile.write(indexContent) with open(mirrorIndexFilename, 'w+') as indexFile:
indexFile.write(indexContent)
except OSError:
print('EX: unable to write ' + mirrorIndexFilename)
mirrorArticleDir = mirrorDir + '/' + postIdNumber mirrorArticleDir = mirrorDir + '/' + postIdNumber
if os.path.isdir(mirrorArticleDir): if os.path.isdir(mirrorArticleDir):
@ -509,11 +518,17 @@ def _createNewsMirror(baseDir: str, domain: str,
# append the post Id number to the index file # append the post Id number to the index file
if os.path.isfile(mirrorIndexFilename): if os.path.isfile(mirrorIndexFilename):
with open(mirrorIndexFilename, 'a+') as indexFile: try:
indexFile.write(postIdNumber + '\n') with open(mirrorIndexFilename, 'a+') as indexFile:
indexFile.write(postIdNumber + '\n')
except OSError:
print('EX: unable to append ' + mirrorIndexFilename)
else: else:
with open(mirrorIndexFilename, 'w+') as indexFile: try:
indexFile.write(postIdNumber + '\n') with open(mirrorIndexFilename, 'w+') as indexFile:
indexFile.write(postIdNumber + '\n')
except OSError:
print('EX: unable to write ' + mirrorIndexFilename)
return True return True
@ -727,10 +742,9 @@ def _convertRSStoActivityPub(baseDir: str, httpPrefix: str,
if os.path.isfile(filename + '.arrived'): if os.path.isfile(filename + '.arrived'):
try: try:
os.remove(filename + '.arrived') os.remove(filename + '.arrived')
except BaseException: except OSError:
print('EX: _convertRSStoActivityPub ' + print('EX: _convertRSStoActivityPub ' +
'unable to delete ' + filename + '.arrived') 'unable to delete ' + filename + '.arrived')
pass
# setting the url here links to the activitypub object # setting the url here links to the activitypub object
# stored locally # stored locally
@ -843,10 +857,9 @@ def runNewswireDaemon(baseDir: str, httpd,
if os.path.isfile(refreshFilename): if os.path.isfile(refreshFilename):
try: try:
os.remove(refreshFilename) os.remove(refreshFilename)
except BaseException: except OSError:
print('EX: runNewswireDaemon unable to delete ' + print('EX: runNewswireDaemon unable to delete ' +
str(refreshFilename)) str(refreshFilename))
pass
break break

View File

@ -1045,10 +1045,9 @@ def _addBlogsToNewswire(baseDir: str, domain: str, newswire: {},
if os.path.isfile(newswireModerationFilename): if os.path.isfile(newswireModerationFilename):
try: try:
os.remove(newswireModerationFilename) os.remove(newswireModerationFilename)
except BaseException: except OSError:
print('EX: _addBlogsToNewswire unable to delete ' + print('EX: _addBlogsToNewswire unable to delete ' +
str(newswireModerationFilename)) str(newswireModerationFilename))
pass
def getDictFromNewswire(session, baseDir: str, domain: str, def getDictFromNewswire(session, baseDir: str, domain: str,

View File

@ -400,10 +400,9 @@ def postMessageToOutbox(session, translate: {},
if os.path.isfile(citationsFilename): if os.path.isfile(citationsFilename):
try: try:
os.remove(citationsFilename) os.remove(citationsFilename)
except BaseException: except OSError:
print('EX: postMessageToOutbox unable to delete ' + print('EX: postMessageToOutbox unable to delete ' +
citationsFilename) citationsFilename)
pass
# The following activity types get added to the index files # The following activity types get added to the index files
indexedActivities = ( indexedActivities = (

124
person.py
View File

@ -507,16 +507,22 @@ def _createPersonBase(baseDir: str, nickname: str, domain: str, port: int,
if not os.path.isdir(baseDir + privateKeysSubdir): if not os.path.isdir(baseDir + privateKeysSubdir):
os.mkdir(baseDir + privateKeysSubdir) os.mkdir(baseDir + privateKeysSubdir)
filename = baseDir + privateKeysSubdir + '/' + handle + '.key' filename = baseDir + privateKeysSubdir + '/' + handle + '.key'
with open(filename, 'w+') as text_file: try:
print(privateKeyPem, file=text_file) with open(filename, 'w+') as text_file:
print(privateKeyPem, file=text_file)
except OSError:
print('EX: unable to save ' + filename)
# save the public key # save the public key
publicKeysSubdir = '/keys/public' publicKeysSubdir = '/keys/public'
if not os.path.isdir(baseDir + publicKeysSubdir): if not os.path.isdir(baseDir + publicKeysSubdir):
os.mkdir(baseDir + publicKeysSubdir) os.mkdir(baseDir + publicKeysSubdir)
filename = baseDir + publicKeysSubdir + '/' + handle + '.pem' filename = baseDir + publicKeysSubdir + '/' + handle + '.pem'
with open(filename, 'w+') as text_file: try:
print(publicKeyPem, file=text_file) with open(filename, 'w+') as text_file:
print(publicKeyPem, file=text_file)
except OSError:
print('EX: unable to save 2 ' + filename)
if password: if password:
password = removeLineEndings(password) password = removeLineEndings(password)
@ -625,22 +631,31 @@ def createPerson(baseDir: str, nickname: str, domain: str, port: int,
if manualFollowerApproval: if manualFollowerApproval:
followDMsFilename = acctDir(baseDir, nickname, domain) + '/.followDMs' followDMsFilename = acctDir(baseDir, nickname, domain) + '/.followDMs'
with open(followDMsFilename, 'w+') as fFile: try:
fFile.write('\n') with open(followDMsFilename, 'w+') as fFile:
fFile.write('\n')
except OSError:
print('EX: unable to write ' + followDMsFilename)
# notify when posts are liked # notify when posts are liked
if nickname != 'news': if nickname != 'news':
notifyLikesFilename = \ notifyLikesFilename = \
acctDir(baseDir, nickname, domain) + '/.notifyLikes' acctDir(baseDir, nickname, domain) + '/.notifyLikes'
with open(notifyLikesFilename, 'w+') as nFile: try:
nFile.write('\n') with open(notifyLikesFilename, 'w+') as nFile:
nFile.write('\n')
except OSError:
print('EX: unable to write ' + notifyLikesFilename)
# notify when posts have emoji reactions # notify when posts have emoji reactions
if nickname != 'news': if nickname != 'news':
notifyReactionsFilename = \ notifyReactionsFilename = \
acctDir(baseDir, nickname, domain) + '/.notifyReactions' acctDir(baseDir, nickname, domain) + '/.notifyReactions'
with open(notifyReactionsFilename, 'w+') as nFile: try:
nFile.write('\n') with open(notifyReactionsFilename, 'w+') as nFile:
nFile.write('\n')
except OSError:
print('EX: unable to write ' + notifyReactionsFilename)
theme = getConfigParam(baseDir, 'theme') theme = getConfigParam(baseDir, 'theme')
if not theme: if not theme:
@ -1016,10 +1031,14 @@ def reenableAccount(baseDir: str, nickname: str) -> None:
lines = [] lines = []
with open(suspendedFilename, 'r') as f: with open(suspendedFilename, 'r') as f:
lines = f.readlines() lines = f.readlines()
with open(suspendedFilename, 'w+') as suspendedFile: try:
for suspended in lines: with open(suspendedFilename, 'w+') as suspendedFile:
if suspended.strip('\n').strip('\r') != nickname: for suspended in lines:
suspendedFile.write(suspended) if suspended.strip('\n').strip('\r') != nickname:
suspendedFile.write(suspended)
except OSError as e:
print('EX: unable to save ' + suspendedFilename +
' ' + str(e))
def suspendAccount(baseDir: str, nickname: str, domain: str) -> None: def suspendAccount(baseDir: str, nickname: str, domain: str) -> None:
@ -1045,16 +1064,14 @@ def suspendAccount(baseDir: str, nickname: str, domain: str) -> None:
if os.path.isfile(saltFilename): if os.path.isfile(saltFilename):
try: try:
os.remove(saltFilename) os.remove(saltFilename)
except BaseException: except OSError:
print('EX: suspendAccount unable to delete ' + saltFilename) print('EX: suspendAccount unable to delete ' + saltFilename)
pass
tokenFilename = acctDir(baseDir, nickname, domain) + '/.token' tokenFilename = acctDir(baseDir, nickname, domain) + '/.token'
if os.path.isfile(tokenFilename): if os.path.isfile(tokenFilename):
try: try:
os.remove(tokenFilename) os.remove(tokenFilename)
except BaseException: except OSError:
print('EX: suspendAccount unable to delete ' + tokenFilename) print('EX: suspendAccount unable to delete ' + tokenFilename)
pass
suspendedFilename = baseDir + '/accounts/suspended.txt' suspendedFilename = baseDir + '/accounts/suspended.txt'
if os.path.isfile(suspendedFilename): if os.path.isfile(suspendedFilename):
@ -1063,11 +1080,17 @@ def suspendAccount(baseDir: str, nickname: str, domain: str) -> None:
for suspended in lines: for suspended in lines:
if suspended.strip('\n').strip('\r') == nickname: if suspended.strip('\n').strip('\r') == nickname:
return return
with open(suspendedFilename, 'a+') as suspendedFile: try:
suspendedFile.write(nickname + '\n') with open(suspendedFilename, 'a+') as suspendedFile:
suspendedFile.write(nickname + '\n')
except OSError:
print('EX: unable to append ' + suspendedFilename)
else: else:
with open(suspendedFilename, 'w+') as suspendedFile: try:
suspendedFile.write(nickname + '\n') with open(suspendedFilename, 'w+') as suspendedFile:
suspendedFile.write(nickname + '\n')
except OSError:
print('EX: unable to write ' + suspendedFilename)
def canRemovePost(baseDir: str, nickname: str, def canRemovePost(baseDir: str, nickname: str,
@ -1124,10 +1147,13 @@ def _removeTagsForNickname(baseDir: str, nickname: str,
lines = [] lines = []
with open(tagFilename, 'r') as f: with open(tagFilename, 'r') as f:
lines = f.readlines() lines = f.readlines()
with open(tagFilename, 'w+') as tagFile: try:
for tagline in lines: with open(tagFilename, 'w+') as tagFile:
if matchStr not in tagline: for tagline in lines:
tagFile.write(tagline) if matchStr not in tagline:
tagFile.write(tagline)
except OSError:
print('EX: unable to write ' + tagFilename)
def removeAccount(baseDir: str, nickname: str, def removeAccount(baseDir: str, nickname: str,
@ -1163,41 +1189,36 @@ def removeAccount(baseDir: str, nickname: str,
if os.path.isfile(baseDir + '/accounts/' + handle + '.json'): if os.path.isfile(baseDir + '/accounts/' + handle + '.json'):
try: try:
os.remove(baseDir + '/accounts/' + handle + '.json') os.remove(baseDir + '/accounts/' + handle + '.json')
except BaseException: except OSError:
print('EX: removeAccount unable to delete ' + print('EX: removeAccount unable to delete ' +
baseDir + '/accounts/' + handle + '.json') baseDir + '/accounts/' + handle + '.json')
pass
if os.path.isfile(baseDir + '/wfendpoints/' + handle + '.json'): if os.path.isfile(baseDir + '/wfendpoints/' + handle + '.json'):
try: try:
os.remove(baseDir + '/wfendpoints/' + handle + '.json') os.remove(baseDir + '/wfendpoints/' + handle + '.json')
except BaseException: except OSError:
print('EX: removeAccount unable to delete ' + print('EX: removeAccount unable to delete ' +
baseDir + '/wfendpoints/' + handle + '.json') baseDir + '/wfendpoints/' + handle + '.json')
pass
if os.path.isfile(baseDir + '/keys/private/' + handle + '.key'): if os.path.isfile(baseDir + '/keys/private/' + handle + '.key'):
try: try:
os.remove(baseDir + '/keys/private/' + handle + '.key') os.remove(baseDir + '/keys/private/' + handle + '.key')
except BaseException: except OSError:
print('EX: removeAccount unable to delete ' + print('EX: removeAccount unable to delete ' +
baseDir + '/keys/private/' + handle + '.key') baseDir + '/keys/private/' + handle + '.key')
pass
if os.path.isfile(baseDir + '/keys/public/' + handle + '.pem'): if os.path.isfile(baseDir + '/keys/public/' + handle + '.pem'):
try: try:
os.remove(baseDir + '/keys/public/' + handle + '.pem') os.remove(baseDir + '/keys/public/' + handle + '.pem')
except BaseException: except OSError:
print('EX: removeAccount unable to delete ' + print('EX: removeAccount unable to delete ' +
baseDir + '/keys/public/' + handle + '.pem') baseDir + '/keys/public/' + handle + '.pem')
pass
if os.path.isdir(baseDir + '/sharefiles/' + nickname): if os.path.isdir(baseDir + '/sharefiles/' + nickname):
shutil.rmtree(baseDir + '/sharefiles/' + nickname, shutil.rmtree(baseDir + '/sharefiles/' + nickname,
ignore_errors=False, onerror=None) ignore_errors=False, onerror=None)
if os.path.isfile(baseDir + '/wfdeactivated/' + handle + '.json'): if os.path.isfile(baseDir + '/wfdeactivated/' + handle + '.json'):
try: try:
os.remove(baseDir + '/wfdeactivated/' + handle + '.json') os.remove(baseDir + '/wfdeactivated/' + handle + '.json')
except BaseException: except OSError:
print('EX: removeAccount unable to delete ' + print('EX: removeAccount unable to delete ' +
baseDir + '/wfdeactivated/' + handle + '.json') baseDir + '/wfdeactivated/' + handle + '.json')
pass
if os.path.isdir(baseDir + '/sharefilesdeactivated/' + nickname): if os.path.isdir(baseDir + '/sharefilesdeactivated/' + nickname):
shutil.rmtree(baseDir + '/sharefilesdeactivated/' + nickname, shutil.rmtree(baseDir + '/sharefilesdeactivated/' + nickname,
ignore_errors=False, onerror=None) ignore_errors=False, onerror=None)
@ -1297,8 +1318,11 @@ def isPersonSnoozed(baseDir: str, nickname: str, domain: str,
with open(snoozedFilename, 'r') as snoozedFile: with open(snoozedFilename, 'r') as snoozedFile:
content = snoozedFile.read().replace(replaceStr, '') content = snoozedFile.read().replace(replaceStr, '')
if content: if content:
with open(snoozedFilename, 'w+') as writeSnoozedFile: try:
writeSnoozedFile.write(content) with open(snoozedFilename, 'w+') as writeSnoozedFile:
writeSnoozedFile.write(content)
except OSError:
print('EX: unable to write ' + snoozedFilename)
if snoozeActor + ' ' in open(snoozedFilename).read(): if snoozeActor + ' ' in open(snoozedFilename).read():
return True return True
@ -1317,9 +1341,12 @@ def personSnooze(baseDir: str, nickname: str, domain: str,
if os.path.isfile(snoozedFilename): if os.path.isfile(snoozedFilename):
if snoozeActor + ' ' in open(snoozedFilename).read(): if snoozeActor + ' ' in open(snoozedFilename).read():
return return
with open(snoozedFilename, 'a+') as snoozedFile: try:
snoozedFile.write(snoozeActor + ' ' + with open(snoozedFilename, 'a+') as snoozedFile:
str(int(time.time())) + '\n') snoozedFile.write(snoozeActor + ' ' +
str(int(time.time())) + '\n')
except OSError:
print('EX: unable to append ' + snoozedFilename)
def personUnsnooze(baseDir: str, nickname: str, domain: str, def personUnsnooze(baseDir: str, nickname: str, domain: str,
@ -1346,8 +1373,11 @@ def personUnsnooze(baseDir: str, nickname: str, domain: str,
with open(snoozedFilename, 'r') as snoozedFile: with open(snoozedFilename, 'r') as snoozedFile:
content = snoozedFile.read().replace(replaceStr, '') content = snoozedFile.read().replace(replaceStr, '')
if content: if content:
with open(snoozedFilename, 'w+') as writeSnoozedFile: try:
writeSnoozedFile.write(content) with open(snoozedFilename, 'w+') as writeSnoozedFile:
writeSnoozedFile.write(content)
except OSError:
print('EX: unable to write ' + snoozedFilename)
def setPersonNotes(baseDir: str, nickname: str, domain: str, def setPersonNotes(baseDir: str, nickname: str, domain: str,
@ -1362,8 +1392,12 @@ def setPersonNotes(baseDir: str, nickname: str, domain: str,
if not os.path.isdir(notesDir): if not os.path.isdir(notesDir):
os.mkdir(notesDir) os.mkdir(notesDir)
notesFilename = notesDir + '/' + handle + '.txt' notesFilename = notesDir + '/' + handle + '.txt'
with open(notesFilename, 'w+') as notesFile: try:
notesFile.write(notes) with open(notesFilename, 'w+') as notesFile:
notesFile.write(notes)
except OSError:
print('EX: unable to write ' + notesFilename)
return False
return True return True

View File

@ -41,17 +41,29 @@ def setPetName(baseDir: str, nickname: str, domain: str,
else: else:
newPetnamesStr += entry newPetnamesStr += entry
# save the updated petnames file # save the updated petnames file
with open(petnamesFilename, 'w+') as petnamesFile: try:
petnamesFile.write(newPetnamesStr) with open(petnamesFilename, 'w+') as petnamesFile:
petnamesFile.write(newPetnamesStr)
except OSError:
print('EX: unable to save ' + petnamesFilename)
return False
return True return True
# entry does not exist in the petnames file # entry does not exist in the petnames file
with open(petnamesFilename, 'a+') as petnamesFile: try:
petnamesFile.write(entry) with open(petnamesFilename, 'a+') as petnamesFile:
petnamesFile.write(entry)
except OSError:
print('EX: unable to append ' + petnamesFilename)
return False
return True return True
# first entry # first entry
with open(petnamesFilename, 'w+') as petnamesFile: try:
petnamesFile.write(entry) with open(petnamesFilename, 'w+') as petnamesFile:
petnamesFile.write(entry)
except OSError:
print('EX: unable to write ' + petnamesFilename)
return False
return True return True

View File

@ -1573,8 +1573,11 @@ def pinPost(baseDir: str, nickname: str, domain: str,
""" """
accountDir = acctDir(baseDir, nickname, domain) accountDir = acctDir(baseDir, nickname, domain)
pinnedFilename = accountDir + '/pinToProfile.txt' pinnedFilename = accountDir + '/pinToProfile.txt'
with open(pinnedFilename, 'w+') as pinFile: try:
pinFile.write(pinnedContent) with open(pinnedFilename, 'w+') as pinFile:
pinFile.write(pinnedContent)
except OSError:
print('EX: unable to write ' + pinnedFilename)
def undoPinnedPost(baseDir: str, nickname: str, domain: str) -> None: def undoPinnedPost(baseDir: str, nickname: str, domain: str) -> None:
@ -1585,7 +1588,7 @@ def undoPinnedPost(baseDir: str, nickname: str, domain: str) -> None:
if os.path.isfile(pinnedFilename): if os.path.isfile(pinnedFilename):
try: try:
os.remove(pinnedFilename) os.remove(pinnedFilename)
except BaseException: except OSError:
print('EX: undoPinnedPost unable to delete ' + pinnedFilename) print('EX: undoPinnedPost unable to delete ' + pinnedFilename)
@ -2122,9 +2125,8 @@ def createReportPost(baseDir: str,
try: try:
with open(newReportFile, 'w+') as fp: with open(newReportFile, 'w+') as fp:
fp.write(toUrl + '/moderation') fp.write(toUrl + '/moderation')
except BaseException: except OSError:
print('EX: createReportPost unable to write ' + newReportFile) print('EX: createReportPost unable to write ' + newReportFile)
pass
return postJsonObject return postJsonObject
@ -3966,10 +3968,9 @@ def archivePostsForPerson(httpPrefix: str, nickname: str, domain: str,
if os.path.isfile(postCacheFilename): if os.path.isfile(postCacheFilename):
try: try:
os.remove(postCacheFilename) os.remove(postCacheFilename)
except BaseException: except OSError:
print('EX: archivePostsForPerson unable to delete ' + print('EX: archivePostsForPerson unable to delete ' +
postCacheFilename) postCacheFilename)
pass
noOfPosts -= 1 noOfPosts -= 1
removeCtr += 1 removeCtr += 1
@ -5135,7 +5136,7 @@ def editedPostFilename(baseDir: str, nickname: str, domain: str,
try: try:
with open(actorFilename, 'r') as fp: with open(actorFilename, 'r') as fp:
lastpostId = fp.read() lastpostId = fp.read()
except BaseException: except OSError:
print('EX: editedPostFilename unable to read ' + actorFilename) print('EX: editedPostFilename unable to read ' + actorFilename)
return '' return ''
if not lastpostId: if not lastpostId:

View File

@ -460,10 +460,9 @@ def updateReactionCollection(recentPostsCache: {},
if os.path.isfile(cachedPostFilename): if os.path.isfile(cachedPostFilename):
try: try:
os.remove(cachedPostFilename) os.remove(cachedPostFilename)
except BaseException: except OSError:
print('EX: updateReactionCollection unable to delete ' + print('EX: updateReactionCollection unable to delete ' +
cachedPostFilename) cachedPostFilename)
pass
obj = postJsonObject obj = postJsonObject
if hasObjectDict(postJsonObject): if hasObjectDict(postJsonObject):

View File

@ -48,10 +48,9 @@ def _updatePostSchedule(baseDir: str, handle: str, httpd,
if os.path.isfile(postFilename): if os.path.isfile(postFilename):
try: try:
os.remove(postFilename) os.remove(postFilename)
except BaseException: except OSError:
print('EX: _updatePostSchedule unable to delete ' + print('EX: _updatePostSchedule unable to delete ' +
str(postFilename)) str(postFilename))
pass
continue continue
# create the new index file # create the new index file
indexLines.append(line) indexLines.append(line)
@ -133,10 +132,9 @@ def _updatePostSchedule(baseDir: str, handle: str, httpd,
indexLines.remove(line) indexLines.remove(line)
try: try:
os.remove(postFilename) os.remove(postFilename)
except BaseException: except OSError:
print('EX: _updatePostSchedule unable to delete ' + print('EX: _updatePostSchedule unable to delete ' +
str(postFilename)) str(postFilename))
pass
continue continue
# move to the outbox # move to the outbox
@ -206,10 +204,9 @@ def removeScheduledPosts(baseDir: str, nickname: str, domain: str) -> None:
if os.path.isfile(scheduleIndexFilename): if os.path.isfile(scheduleIndexFilename):
try: try:
os.remove(scheduleIndexFilename) os.remove(scheduleIndexFilename)
except BaseException: except OSError:
print('EX: removeScheduledPosts unable to delete ' + print('EX: removeScheduledPosts unable to delete ' +
scheduleIndexFilename) scheduleIndexFilename)
pass
# remove the scheduled posts # remove the scheduled posts
scheduledDir = acctDir(baseDir, nickname, domain) + '/scheduled' scheduledDir = acctDir(baseDir, nickname, domain) + '/scheduled'
if not os.path.isdir(scheduledDir): if not os.path.isdir(scheduledDir):
@ -219,7 +216,6 @@ def removeScheduledPosts(baseDir: str, nickname: str, domain: str) -> None:
if os.path.isfile(filePath): if os.path.isfile(filePath):
try: try:
os.remove(filePath) os.remove(filePath)
except BaseException: except OSError:
print('EX: removeScheduledPosts unable to delete ' + print('EX: removeScheduledPosts unable to delete ' +
filePath) filePath)
pass

View File

@ -439,10 +439,9 @@ def downloadImage(session, baseDir: str, url: str,
if os.path.isfile(imageFilename): if os.path.isfile(imageFilename):
try: try:
os.remove(imageFilename) os.remove(imageFilename)
except BaseException: except OSError:
print('EX: downloadImage unable to delete ' + print('EX: downloadImage unable to delete ' +
imageFilename) imageFilename)
pass
else: else:
with open(imageFilename, 'wb') as f: with open(imageFilename, 'wb') as f:
f.write(result.content) f.write(result.content)

View File

@ -148,10 +148,9 @@ def removeSharedItem(baseDir: str, nickname: str, domain: str,
if os.path.isfile(itemIDfile + '.' + ext): if os.path.isfile(itemIDfile + '.' + ext):
try: try:
os.remove(itemIDfile + '.' + ext) os.remove(itemIDfile + '.' + ext)
except BaseException: except OSError:
print('EX: removeSharedItem unable to delete ' + print('EX: removeSharedItem unable to delete ' +
itemIDfile + '.' + ext) itemIDfile + '.' + ext)
pass
# remove the item itself # remove the item itself
del sharesJson[itemID] del sharesJson[itemID]
saveJson(sharesJson, sharesFilename) saveJson(sharesJson, sharesFilename)
@ -294,10 +293,9 @@ def _indicateNewShareAvailable(baseDir: str, httpPrefix: str,
fp.write(localActor + '/tlshares') fp.write(localActor + '/tlshares')
else: else:
fp.write(localActor + '/tlwanted') fp.write(localActor + '/tlwanted')
except BaseException: except OSError:
print('EX: _indicateNewShareAvailable unable to write ' + print('EX: _indicateNewShareAvailable unable to write ' +
str(newShareFile)) str(newShareFile))
pass
break break
@ -368,10 +366,9 @@ def addShare(baseDir: str,
if moveImage: if moveImage:
try: try:
os.remove(imageFilename) os.remove(imageFilename)
except BaseException: except OSError:
print('EX: addShare unable to delete ' + print('EX: addShare unable to delete ' +
str(imageFilename)) str(imageFilename))
pass
imageUrl = \ imageUrl = \
httpPrefix + '://' + domainFull + \ httpPrefix + '://' + domainFull + \
'/sharefiles/' + nickname + '/' + itemID + '.' + ext '/sharefiles/' + nickname + '/' + itemID + '.' + ext
@ -442,10 +439,9 @@ def _expireSharesForAccount(baseDir: str, nickname: str, domain: str,
if os.path.isfile(itemIDfile + '.' + ext): if os.path.isfile(itemIDfile + '.' + ext):
try: try:
os.remove(itemIDfile + '.' + ext) os.remove(itemIDfile + '.' + ext)
except BaseException: except OSError:
print('EX: _expireSharesForAccount unable to delete ' + print('EX: _expireSharesForAccount unable to delete ' +
itemIDfile + '.' + ext) itemIDfile + '.' + ext)
pass
saveJson(sharesJson, sharesFilename) saveJson(sharesJson, sharesFilename)

View File

@ -3478,7 +3478,7 @@ def _testJsonString() -> None:
assert messageStr in encodedStr assert messageStr in encodedStr
try: try:
os.remove(filename) os.remove(filename)
except BaseException: except OSError:
pass pass
@ -3492,7 +3492,7 @@ def _testSaveLoadJson():
if os.path.isfile(testFilename): if os.path.isfile(testFilename):
try: try:
os.remove(testFilename) os.remove(testFilename)
except BaseException: except OSError:
pass pass
assert saveJson(testJson, testFilename) assert saveJson(testJson, testFilename)
assert os.path.isfile(testFilename) assert os.path.isfile(testFilename)
@ -3504,7 +3504,7 @@ def _testSaveLoadJson():
assert testLoadJson['param2'] == '"Crème brûlée यह एक परीक्षण ह"' assert testLoadJson['param2'] == '"Crème brûlée यह एक परीक्षण ह"'
try: try:
os.remove(testFilename) os.remove(testFilename)
except BaseException: except OSError:
pass pass

View File

@ -90,9 +90,8 @@ def exportTheme(baseDir: str, theme: str) -> bool:
if os.path.isfile(exportFilename): if os.path.isfile(exportFilename):
try: try:
os.remove(exportFilename) os.remove(exportFilename)
except BaseException: except OSError:
print('EX: exportTheme unable to delete ' + str(exportFilename)) print('EX: exportTheme unable to delete ' + str(exportFilename))
pass
try: try:
make_archive(baseDir + '/exports/' + theme, 'zip', themeDir) make_archive(baseDir + '/exports/' + theme, 'zip', themeDir)
except BaseException: except BaseException:
@ -264,10 +263,9 @@ def _removeTheme(baseDir: str):
continue continue
try: try:
os.remove(baseDir + '/' + filename) os.remove(baseDir + '/' + filename)
except BaseException: except OSError:
print('EX: _removeTheme unable to delete ' + print('EX: _removeTheme unable to delete ' +
baseDir + '/' + filename) baseDir + '/' + filename)
pass
def setCSSparam(css: str, param: str, value: str) -> str: def setCSSparam(css: str, param: str, value: str) -> str:
@ -451,10 +449,9 @@ def disableGrayscale(baseDir: str) -> None:
if os.path.isfile(grayscaleFilename): if os.path.isfile(grayscaleFilename):
try: try:
os.remove(grayscaleFilename) os.remove(grayscaleFilename)
except BaseException: except OSError:
print('EX: disableGrayscale unable to delete ' + print('EX: disableGrayscale unable to delete ' +
grayscaleFilename) grayscaleFilename)
pass
def _setCustomFont(baseDir: str): def _setCustomFont(baseDir: str):
@ -596,20 +593,18 @@ def _setTextModeTheme(baseDir: str, name: str) -> None:
try: try:
copyfile(textModeLogoFilename, copyfile(textModeLogoFilename,
baseDir + '/accounts/logo.txt') baseDir + '/accounts/logo.txt')
except BaseException: except OSError:
print('EX: _setTextModeTheme unable to copy ' + print('EX: _setTextModeTheme unable to copy ' +
textModeLogoFilename + ' ' + textModeLogoFilename + ' ' +
baseDir + '/accounts/logo.txt') baseDir + '/accounts/logo.txt')
pass
else: else:
try: try:
copyfile(baseDir + '/img/logo.txt', copyfile(baseDir + '/img/logo.txt',
baseDir + '/accounts/logo.txt') baseDir + '/accounts/logo.txt')
except BaseException: except OSError:
print('EX: _setTextModeTheme unable to copy ' + print('EX: _setTextModeTheme unable to copy ' +
baseDir + '/img/logo.txt ' + baseDir + '/img/logo.txt ' +
baseDir + '/accounts/logo.txt') baseDir + '/accounts/logo.txt')
pass
# set the text mode banner which appears in browsers such as Lynx # set the text mode banner which appears in browsers such as Lynx
textModeBannerFilename = \ textModeBannerFilename = \
@ -617,19 +612,17 @@ def _setTextModeTheme(baseDir: str, name: str) -> None:
if os.path.isfile(baseDir + '/accounts/banner.txt'): if os.path.isfile(baseDir + '/accounts/banner.txt'):
try: try:
os.remove(baseDir + '/accounts/banner.txt') os.remove(baseDir + '/accounts/banner.txt')
except BaseException: except OSError:
print('EX: _setTextModeTheme unable to delete ' + print('EX: _setTextModeTheme unable to delete ' +
baseDir + '/accounts/banner.txt') baseDir + '/accounts/banner.txt')
pass
if os.path.isfile(textModeBannerFilename): if os.path.isfile(textModeBannerFilename):
try: try:
copyfile(textModeBannerFilename, copyfile(textModeBannerFilename,
baseDir + '/accounts/banner.txt') baseDir + '/accounts/banner.txt')
except BaseException: except OSError:
print('EX: _setTextModeTheme unable to copy ' + print('EX: _setTextModeTheme unable to copy ' +
textModeBannerFilename + ' ' + textModeBannerFilename + ' ' +
baseDir + '/accounts/banner.txt') baseDir + '/accounts/banner.txt')
pass
def _setThemeImages(baseDir: str, name: str) -> None: def _setThemeImages(baseDir: str, name: str) -> None:
@ -679,10 +672,9 @@ def _setThemeImages(baseDir: str, name: str) -> None:
baseDir + '/accounts/' + baseDir + '/accounts/' +
backgroundType + '-background.' + ext) backgroundType + '-background.' + ext)
continue continue
except BaseException: except OSError:
print('EX: _setThemeImages unable to copy ' + print('EX: _setThemeImages unable to copy ' +
backgroundImageFilename) backgroundImageFilename)
pass
# background image was not found # background image was not found
# so remove any existing file # so remove any existing file
if os.path.isfile(baseDir + '/accounts/' + if os.path.isfile(baseDir + '/accounts/' +
@ -690,38 +682,34 @@ def _setThemeImages(baseDir: str, name: str) -> None:
try: try:
os.remove(baseDir + '/accounts/' + os.remove(baseDir + '/accounts/' +
backgroundType + '-background.' + ext) backgroundType + '-background.' + ext)
except BaseException: except OSError:
print('EX: _setThemeImages unable to delete ' + print('EX: _setThemeImages unable to delete ' +
baseDir + '/accounts/' + baseDir + '/accounts/' +
backgroundType + '-background.' + ext) backgroundType + '-background.' + ext)
pass
if os.path.isfile(profileImageFilename) and \ if os.path.isfile(profileImageFilename) and \
os.path.isfile(bannerFilename): os.path.isfile(bannerFilename):
try: try:
copyfile(profileImageFilename, copyfile(profileImageFilename,
accountDir + '/image.png') accountDir + '/image.png')
except BaseException: except OSError:
print('EX: _setThemeImages unable to copy ' + print('EX: _setThemeImages unable to copy ' +
profileImageFilename) profileImageFilename)
pass
try: try:
copyfile(bannerFilename, copyfile(bannerFilename,
accountDir + '/banner.png') accountDir + '/banner.png')
except BaseException: except OSError:
print('EX: _setThemeImages unable to copy ' + print('EX: _setThemeImages unable to copy ' +
bannerFilename) bannerFilename)
pass
try: try:
if os.path.isfile(searchBannerFilename): if os.path.isfile(searchBannerFilename):
copyfile(searchBannerFilename, copyfile(searchBannerFilename,
accountDir + '/search_banner.png') accountDir + '/search_banner.png')
except BaseException: except OSError:
print('EX: _setThemeImages unable to copy ' + print('EX: _setThemeImages unable to copy ' +
searchBannerFilename) searchBannerFilename)
pass
try: try:
if os.path.isfile(leftColImageFilename): if os.path.isfile(leftColImageFilename):
@ -731,14 +719,12 @@ def _setThemeImages(baseDir: str, name: str) -> None:
'/left_col_image.png'): '/left_col_image.png'):
try: try:
os.remove(accountDir + '/left_col_image.png') os.remove(accountDir + '/left_col_image.png')
except BaseException: except OSError:
print('EX: _setThemeImages unable to delete ' + print('EX: _setThemeImages unable to delete ' +
accountDir + '/left_col_image.png') accountDir + '/left_col_image.png')
pass except OSError:
except BaseException:
print('EX: _setThemeImages unable to copy ' + print('EX: _setThemeImages unable to copy ' +
leftColImageFilename) leftColImageFilename)
pass
try: try:
if os.path.isfile(rightColImageFilename): if os.path.isfile(rightColImageFilename):
@ -749,14 +735,12 @@ def _setThemeImages(baseDir: str, name: str) -> None:
'/right_col_image.png'): '/right_col_image.png'):
try: try:
os.remove(accountDir + '/right_col_image.png') os.remove(accountDir + '/right_col_image.png')
except BaseException: except OSError:
print('EX: _setThemeImages unable to delete ' + print('EX: _setThemeImages unable to delete ' +
accountDir + '/right_col_image.png') accountDir + '/right_col_image.png')
pass except OSError:
except BaseException:
print('EX: _setThemeImages unable to copy ' + print('EX: _setThemeImages unable to copy ' +
rightColImageFilename) rightColImageFilename)
pass
break break
@ -779,9 +763,8 @@ def setNewsAvatar(baseDir: str, name: str,
if os.path.isfile(filename): if os.path.isfile(filename):
try: try:
os.remove(filename) os.remove(filename)
except BaseException: except OSError:
print('EX: setNewsAvatar unable to delete ' + filename) print('EX: setNewsAvatar unable to delete ' + filename)
pass
if os.path.isdir(baseDir + '/cache/avatars'): if os.path.isdir(baseDir + '/cache/avatars'):
copyfile(newFilename, filename) copyfile(newFilename, filename)
accountDir = acctDir(baseDir, nickname, domain) accountDir = acctDir(baseDir, nickname, domain)

View File

@ -149,7 +149,6 @@ def removeDormantThreads(baseDir: str, threadsList: [], debug: bool,
logFile.write(currTime.strftime("%Y-%m-%dT%H:%M:%SZ") + logFile.write(currTime.strftime("%Y-%m-%dT%H:%M:%SZ") +
',' + str(noOfActiveThreads) + ',' + str(noOfActiveThreads) +
',' + str(len(threadsList)) + '\n') ',' + str(len(threadsList)) + '\n')
except BaseException: except OSError:
print('EX: removeDormantThreads unable to write ' + print('EX: removeDormantThreads unable to write ' +
sendLogFilename) sendLogFilename)
pass

View File

@ -625,10 +625,9 @@ def removeAvatarFromCache(baseDir: str, actorStr: str) -> None:
if os.path.isfile(avatarFilename): if os.path.isfile(avatarFilename):
try: try:
os.remove(avatarFilename) os.remove(avatarFilename)
except BaseException: except OSError:
print('EX: removeAvatarFromCache ' + print('EX: removeAvatarFromCache ' +
'unable to delete cached avatar ' + str(avatarFilename)) 'unable to delete cached avatar ' + str(avatarFilename))
pass
def saveJson(jsonObject: {}, filename: str) -> bool: def saveJson(jsonObject: {}, filename: str) -> bool:
@ -640,7 +639,7 @@ def saveJson(jsonObject: {}, filename: str) -> bool:
with open(filename, 'w+') as fp: with open(filename, 'w+') as fp:
fp.write(json.dumps(jsonObject)) fp.write(json.dumps(jsonObject))
return True return True
except BaseException: except OSError:
print('EX: saveJson ' + str(tries)) print('EX: saveJson ' + str(tries))
time.sleep(1) time.sleep(1)
tries += 1 tries += 1
@ -1287,10 +1286,9 @@ def clearFromPostCaches(baseDir: str, recentPostsCache: {},
if os.path.isfile(postFilename): if os.path.isfile(postFilename):
try: try:
os.remove(postFilename) os.remove(postFilename)
except BaseException: except OSError:
print('EX: clearFromPostCaches file not removed ' + print('EX: clearFromPostCaches file not removed ' +
str(postFilename)) str(postFilename))
pass
# if the post is in the recent posts cache then remove it # if the post is in the recent posts cache then remove it
if recentPostsCache.get('index'): if recentPostsCache.get('index'):
if postId in recentPostsCache['index']: if postId in recentPostsCache['index']:
@ -1450,18 +1448,16 @@ def _removeAttachment(baseDir: str, httpPrefix: str, domain: str,
if os.path.isfile(mediaFilename): if os.path.isfile(mediaFilename):
try: try:
os.remove(mediaFilename) os.remove(mediaFilename)
except BaseException: except OSError:
print('EX: _removeAttachment unable to delete media file ' + print('EX: _removeAttachment unable to delete media file ' +
str(mediaFilename)) str(mediaFilename))
pass
etagFilename = mediaFilename + '.etag' etagFilename = mediaFilename + '.etag'
if os.path.isfile(etagFilename): if os.path.isfile(etagFilename):
try: try:
os.remove(etagFilename) os.remove(etagFilename)
except BaseException: except OSError:
print('EX: _removeAttachment unable to delete etag file ' + print('EX: _removeAttachment unable to delete etag file ' +
str(etagFilename)) str(etagFilename))
pass
postJson['attachment'] = [] postJson['attachment'] = []
@ -1528,10 +1524,9 @@ def _deletePostRemoveReplies(baseDir: str, nickname: str, domain: str,
# remove the replies file # remove the replies file
try: try:
os.remove(repliesFilename) os.remove(repliesFilename)
except BaseException: except OSError:
print('EX: _deletePostRemoveReplies unable to delete replies file ' + print('EX: _deletePostRemoveReplies unable to delete replies file ' +
str(repliesFilename)) str(repliesFilename))
pass
def _isBookmarked(baseDir: str, nickname: str, domain: str, def _isBookmarked(baseDir: str, nickname: str, domain: str,
@ -1589,11 +1584,10 @@ def _deleteCachedHtml(baseDir: str, nickname: str, domain: str,
if os.path.isfile(cachedPostFilename): if os.path.isfile(cachedPostFilename):
try: try:
os.remove(cachedPostFilename) os.remove(cachedPostFilename)
except BaseException: except OSError:
print('EX: _deleteCachedHtml ' + print('EX: _deleteCachedHtml ' +
'unable to delete cached post file ' + 'unable to delete cached post file ' +
str(cachedPostFilename)) str(cachedPostFilename))
pass
def _deleteHashtagsOnPost(baseDir: str, postJsonObject: {}) -> None: def _deleteHashtagsOnPost(baseDir: str, postJsonObject: {}) -> None:
@ -1641,10 +1635,9 @@ def _deleteHashtagsOnPost(baseDir: str, postJsonObject: {}) -> None:
# if there are no lines then remove the hashtag file # if there are no lines then remove the hashtag file
try: try:
os.remove(tagIndexFilename) os.remove(tagIndexFilename)
except BaseException: except OSError:
print('EX: _deleteHashtagsOnPost unable to delete tag index ' + print('EX: _deleteHashtagsOnPost unable to delete tag index ' +
str(tagIndexFilename)) str(tagIndexFilename))
pass
else: else:
# write the new hashtag index without the given post in it # write the new hashtag index without the given post in it
with open(tagIndexFilename, 'w+') as f: with open(tagIndexFilename, 'w+') as f:
@ -1681,18 +1674,16 @@ def _deleteConversationPost(baseDir: str, nickname: str, domain: str,
if os.path.isfile(conversationFilename + '.muted'): if os.path.isfile(conversationFilename + '.muted'):
try: try:
os.remove(conversationFilename + '.muted') os.remove(conversationFilename + '.muted')
except BaseException: except OSError:
print('EX: _deleteConversationPost ' + print('EX: _deleteConversationPost ' +
'unable to remove conversation ' + 'unable to remove conversation ' +
str(conversationFilename) + '.muted') str(conversationFilename) + '.muted')
pass
try: try:
os.remove(conversationFilename) os.remove(conversationFilename)
except BaseException: except OSError:
print('EX: _deleteConversationPost ' + print('EX: _deleteConversationPost ' +
'unable to remove conversation ' + 'unable to remove conversation ' +
str(conversationFilename)) str(conversationFilename))
pass
def deletePost(baseDir: str, httpPrefix: str, def deletePost(baseDir: str, httpPrefix: str,
@ -1709,11 +1700,10 @@ def deletePost(baseDir: str, httpPrefix: str,
# finally, remove the post itself # finally, remove the post itself
try: try:
os.remove(postFilename) os.remove(postFilename)
except BaseException: except OSError:
if debug: if debug:
print('EX: deletePost unable to delete post ' + print('EX: deletePost unable to delete post ' +
str(postFilename)) str(postFilename))
pass
return return
# don't allow deletion of bookmarked posts # don't allow deletion of bookmarked posts
@ -1740,10 +1730,9 @@ def deletePost(baseDir: str, httpPrefix: str,
if os.path.isfile(extFilename): if os.path.isfile(extFilename):
try: try:
os.remove(extFilename) os.remove(extFilename)
except BaseException: except OSError:
print('EX: deletePost unable to remove ext ' + print('EX: deletePost unable to remove ext ' +
str(extFilename)) str(extFilename))
pass
# remove cached html version of the post # remove cached html version of the post
_deleteCachedHtml(baseDir, nickname, domain, postJsonObject) _deleteCachedHtml(baseDir, nickname, domain, postJsonObject)
@ -1771,10 +1760,9 @@ def deletePost(baseDir: str, httpPrefix: str,
# finally, remove the post itself # finally, remove the post itself
try: try:
os.remove(postFilename) os.remove(postFilename)
except BaseException: except OSError:
if debug: if debug:
print('EX: deletePost unable to delete post ' + str(postFilename)) print('EX: deletePost unable to delete post ' + str(postFilename))
pass
def isValidLanguage(text: str) -> bool: def isValidLanguage(text: str) -> bool:
@ -2213,11 +2201,10 @@ def undoLikesCollectionEntry(recentPostsCache: {},
if os.path.isfile(cachedPostFilename): if os.path.isfile(cachedPostFilename):
try: try:
os.remove(cachedPostFilename) os.remove(cachedPostFilename)
except BaseException: except OSError:
print('EX: undoLikesCollectionEntry ' + print('EX: undoLikesCollectionEntry ' +
'unable to delete cached post ' + 'unable to delete cached post ' +
str(cachedPostFilename)) str(cachedPostFilename))
pass
removePostFromCache(postJsonObject, recentPostsCache) removePostFromCache(postJsonObject, recentPostsCache)
if not postJsonObject.get('type'): if not postJsonObject.get('type'):
@ -2278,11 +2265,10 @@ def undoReactionCollectionEntry(recentPostsCache: {},
if os.path.isfile(cachedPostFilename): if os.path.isfile(cachedPostFilename):
try: try:
os.remove(cachedPostFilename) os.remove(cachedPostFilename)
except BaseException: except OSError:
print('EX: undoReactionCollectionEntry ' + print('EX: undoReactionCollectionEntry ' +
'unable to delete cached post ' + 'unable to delete cached post ' +
str(cachedPostFilename)) str(cachedPostFilename))
pass
removePostFromCache(postJsonObject, recentPostsCache) removePostFromCache(postJsonObject, recentPostsCache)
if not postJsonObject.get('type'): if not postJsonObject.get('type'):
@ -2344,12 +2330,11 @@ def undoAnnounceCollectionEntry(recentPostsCache: {},
if os.path.isfile(cachedPostFilename): if os.path.isfile(cachedPostFilename):
try: try:
os.remove(cachedPostFilename) os.remove(cachedPostFilename)
except BaseException: except OSError:
if debug: if debug:
print('EX: undoAnnounceCollectionEntry ' + print('EX: undoAnnounceCollectionEntry ' +
'unable to delete cached post ' + 'unable to delete cached post ' +
str(cachedPostFilename)) str(cachedPostFilename))
pass
removePostFromCache(postJsonObject, recentPostsCache) removePostFromCache(postJsonObject, recentPostsCache)
if not postJsonObject.get('type'): if not postJsonObject.get('type'):
@ -2412,12 +2397,11 @@ def updateAnnounceCollection(recentPostsCache: {},
if os.path.isfile(cachedPostFilename): if os.path.isfile(cachedPostFilename):
try: try:
os.remove(cachedPostFilename) os.remove(cachedPostFilename)
except BaseException: except OSError:
if debug: if debug:
print('EX: updateAnnounceCollection ' + print('EX: updateAnnounceCollection ' +
'unable to delete cached post ' + 'unable to delete cached post ' +
str(cachedPostFilename)) str(cachedPostFilename))
pass
removePostFromCache(postJsonObject, recentPostsCache) removePostFromCache(postJsonObject, recentPostsCache)
if not hasObjectDict(postJsonObject): if not hasObjectDict(postJsonObject):

View File

@ -108,9 +108,8 @@ def _htmlCalendarDay(personCache: {}, cssCache: {}, translate: {},
if os.path.isfile(calendarFile): if os.path.isfile(calendarFile):
try: try:
os.remove(calendarFile) os.remove(calendarFile)
except BaseException: except OSError:
print('EX: _htmlCalendarDay unable to delete ' + calendarFile) print('EX: _htmlCalendarDay unable to delete ' + calendarFile)
pass
cssFilename = baseDir + '/epicyon-calendar.css' cssFilename = baseDir + '/epicyon-calendar.css'
if os.path.isfile(baseDir + '/calendar.css'): if os.path.isfile(baseDir + '/calendar.css'):

View File

@ -36,9 +36,11 @@ def setMinimal(baseDir: str, domain: str, nickname: str,
if minimal and minimalFileExists: if minimal and minimalFileExists:
try: try:
os.remove(minimalFilename) os.remove(minimalFilename)
except BaseException: except OSError:
print('EX: setMinimal unable to delete ' + minimalFilename) print('EX: setMinimal unable to delete ' + minimalFilename)
pass
elif not minimal and not minimalFileExists: elif not minimal and not minimalFileExists:
with open(minimalFilename, 'w+') as fp: try:
fp.write('\n') with open(minimalFilename, 'w+') as fp:
fp.write('\n')
except OSError:
print('EX: unable to write minimal ' + minimalFilename)

View File

@ -433,20 +433,18 @@ def htmlSearch(cssCache: {}, translate: {},
try: try:
with open(cachedHashtagSwarmFilename, 'r') as fp: with open(cachedHashtagSwarmFilename, 'r') as fp:
swarmStr = fp.read() swarmStr = fp.read()
except BaseException: except OSError:
print('EX: htmlSearch unable to read cached hashtag swarm ' + print('EX: htmlSearch unable to read cached hashtag swarm ' +
cachedHashtagSwarmFilename) cachedHashtagSwarmFilename)
pass
if not swarmStr: if not swarmStr:
swarmStr = htmlHashTagSwarm(baseDir, actor, translate) swarmStr = htmlHashTagSwarm(baseDir, actor, translate)
if swarmStr: if swarmStr:
try: try:
with open(cachedHashtagSwarmFilename, 'w+') as fp: with open(cachedHashtagSwarmFilename, 'w+') as fp:
fp.write(swarmStr) fp.write(swarmStr)
except BaseException: except OSError:
print('EX: htmlSearch unable to save cached hashtag swarm ' + print('EX: htmlSearch unable to save cached hashtag swarm ' +
cachedHashtagSwarmFilename) cachedHashtagSwarmFilename)
pass
followStr += ' <p class="hashtagswarm">' + swarmStr + '</p>\n' followStr += ' <p class="hashtagswarm">' + swarmStr + '</p>\n'
followStr += ' </center>\n' followStr += ' </center>\n'

View File

@ -476,9 +476,8 @@ def htmlTimeline(cssCache: {}, defaultTimeline: str,
if boxName == 'dm': if boxName == 'dm':
try: try:
os.remove(dmFile) os.remove(dmFile)
except BaseException: except OSError:
print('EX: htmlTimeline unable to delete ' + dmFile) print('EX: htmlTimeline unable to delete ' + dmFile)
pass
# should the Replies button be highlighted? # should the Replies button be highlighted?
newReply = False newReply = False
@ -488,9 +487,8 @@ def htmlTimeline(cssCache: {}, defaultTimeline: str,
if boxName == 'tlreplies': if boxName == 'tlreplies':
try: try:
os.remove(replyFile) os.remove(replyFile)
except BaseException: except OSError:
print('EX: htmlTimeline unable to delete ' + replyFile) print('EX: htmlTimeline unable to delete ' + replyFile)
pass
# should the Shares button be highlighted? # should the Shares button be highlighted?
newShare = False newShare = False
@ -500,9 +498,8 @@ def htmlTimeline(cssCache: {}, defaultTimeline: str,
if boxName == 'tlshares': if boxName == 'tlshares':
try: try:
os.remove(newShareFile) os.remove(newShareFile)
except BaseException: except OSError:
print('EX: htmlTimeline unable to delete ' + newShareFile) print('EX: htmlTimeline unable to delete ' + newShareFile)
pass
# should the Wanted button be highlighted? # should the Wanted button be highlighted?
newWanted = False newWanted = False
@ -512,9 +509,8 @@ def htmlTimeline(cssCache: {}, defaultTimeline: str,
if boxName == 'tlwanted': if boxName == 'tlwanted':
try: try:
os.remove(newWantedFile) os.remove(newWantedFile)
except BaseException: except OSError:
print('EX: htmlTimeline unable to delete ' + newWantedFile) print('EX: htmlTimeline unable to delete ' + newWantedFile)
pass
# should the Moderation/reports button be highlighted? # should the Moderation/reports button be highlighted?
newReport = False newReport = False
@ -524,9 +520,8 @@ def htmlTimeline(cssCache: {}, defaultTimeline: str,
if boxName == 'moderation': if boxName == 'moderation':
try: try:
os.remove(newReportFile) os.remove(newReportFile)
except BaseException: except OSError:
print('EX: htmlTimeline unable to delete ' + newReportFile) print('EX: htmlTimeline unable to delete ' + newReportFile)
pass
separatorStr = '' separatorStr = ''
if boxName != 'tlmedia': if boxName != 'tlmedia':

View File

@ -283,10 +283,9 @@ def updateAvatarImageCache(signingPrivateKeyPem: str,
if os.path.isfile(avatarImageFilename): if os.path.isfile(avatarImageFilename):
try: try:
os.remove(avatarImageFilename) os.remove(avatarImageFilename)
except BaseException: except OSError:
print('EX: updateAvatarImageCache unable to delete ' + print('EX: updateAvatarImageCache unable to delete ' +
avatarImageFilename) avatarImageFilename)
pass
else: else:
with open(avatarImageFilename, 'wb') as f: with open(avatarImageFilename, 'wb') as f:
f.write(result.content) f.write(result.content)