diff --git a/auth.py b/auth.py index 8b1df333e..0d861c59f 100644 --- a/auth.py +++ b/auth.py @@ -163,21 +163,39 @@ def storeBasicCredentials(baseDir: str, nickname: str, password: str) -> bool: storeStr = nickname + ':' + _hashPassword(password) if os.path.isfile(passwordFile): if nickname + ':' in open(passwordFile).read(): - with open(passwordFile, 'r') as fin: - with open(passwordFile + '.new', 'w+') as fout: - for line in fin: - if not line.startswith(nickname + ':'): - fout.write(line) - else: - fout.write(storeStr + '\n') - os.rename(passwordFile + '.new', passwordFile) + try: + with open(passwordFile, 'r') as fin: + with open(passwordFile + '.new', 'w+') as fout: + for line in fin: + if not line.startswith(nickname + ':'): + fout.write(line) + else: + 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: # append to password file - with open(passwordFile, 'a+') as passfile: - passfile.write(storeStr + '\n') + try: + with open(passwordFile, 'a+') as passfile: + passfile.write(storeStr + '\n') + except OSError: + print('EX: unable to append password') + return False else: - with open(passwordFile, 'w+') as passfile: - passfile.write(storeStr + '\n') + try: + with open(passwordFile, 'w+') as passfile: + passfile.write(storeStr + '\n') + except OSError: + print('EX: unable to create password file') + return False return True @@ -187,12 +205,21 @@ def removePassword(baseDir: str, nickname: str) -> None: """ passwordFile = baseDir + '/accounts/passwords' if os.path.isfile(passwordFile): - with open(passwordFile, 'r') as fin: - with open(passwordFile + '.new', 'w+') as fout: - for line in fin: - if not line.startswith(nickname + ':'): - fout.write(line) - os.rename(passwordFile + '.new', passwordFile) + try: + with open(passwordFile, 'r') as fin: + with open(passwordFile + '.new', 'w+') as fout: + for line in fin: + if not line.startswith(nickname + ':'): + 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: @@ -254,6 +281,6 @@ def recordLoginFailure(baseDir: str, ipAddress: str, 'Disconnecting invalid user epicyon ' + ipAddress + ' port 443: ' + 'Too many authentication failures [preauth]\n') - except BaseException: + except OSError: print('EX: recordLoginFailure failed ' + str(failureLog)) pass diff --git a/blocking.py b/blocking.py index aa6be2e83..44bf77b33 100644 --- a/blocking.py +++ b/blocking.py @@ -49,8 +49,12 @@ def addGlobalBlock(baseDir: str, if blockHandle in open(blockingFilename).read(): return False # block an account handle or domain - with open(blockingFilename, 'a+') as blockFile: - blockFile.write(blockHandle + '\n') + try: + with open(blockingFilename, 'a+') as blockFile: + blockFile.write(blockHandle + '\n') + except OSError: + print('EX: unable to save blocked handle ' + blockHandle) + return False else: blockHashtag = blockNickname # is the hashtag already blocked? @@ -58,8 +62,12 @@ def addGlobalBlock(baseDir: str, if blockHashtag + '\n' in open(blockingFilename).read(): return False # block a hashtag - with open(blockingFilename, 'a+') as blockFile: - blockFile.write(blockHashtag + '\n') + try: + with open(blockingFilename, 'a+') as blockFile: + blockFile.write(blockHashtag + '\n') + except OSError: + print('EX: unable to save blocked hashtag ' + blockHashtag) + return False return True @@ -83,25 +91,47 @@ def addBlock(baseDir: str, nickname: str, domain: str, if os.path.isfile(followingFilename): if blockHandle + '\n' in open(followingFilename).read(): followingStr = '' - with open(followingFilename, 'r') as followingFile: - followingStr = followingFile.read() - followingStr = followingStr.replace(blockHandle + '\n', '') - with open(followingFilename, 'w+') as followingFile: - followingFile.write(followingStr) + try: + with open(followingFilename, 'r') as followingFile: + followingStr = followingFile.read() + followingStr = followingStr.replace(blockHandle + '\n', '') + 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 followersFilename = acctDir(baseDir, nickname, domain) + '/followers.txt' if os.path.isfile(followersFilename): if blockHandle + '\n' in open(followersFilename).read(): followersStr = '' - with open(followersFilename, 'r') as followersFile: - followersStr = followersFile.read() - followersStr = followersStr.replace(blockHandle + '\n', '') - with open(followersFilename, 'w+') as followersFile: - followersFile.write(followersStr) + try: + with open(followersFilename, 'r') as followersFile: + followersStr = followersFile.read() + followersStr = followersStr.replace(blockHandle + '\n', '') + except OSError: + print('EX: Unable to read followers ' + followersFilename) + return False - with open(blockingFilename, 'a+') as blockFile: - blockFile.write(blockHandle + '\n') + try: + 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 @@ -116,11 +146,17 @@ def removeGlobalBlock(baseDir: str, if os.path.isfile(unblockingFilename): if unblockHandle in open(unblockingFilename).read(): with open(unblockingFilename, 'r') as fp: - with open(unblockingFilename + '.new', 'w+') as fpnew: - for line in fp: - handle = line.replace('\n', '').replace('\r', '') - if unblockHandle not in line: - fpnew.write(handle + '\n') + try: + with open(unblockingFilename + '.new', 'w+') as fpnew: + for line in fp: + handle = \ + 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'): os.rename(unblockingFilename + '.new', unblockingFilename) return True @@ -129,12 +165,17 @@ def removeGlobalBlock(baseDir: str, if os.path.isfile(unblockingFilename): if unblockHashtag + '\n' in open(unblockingFilename).read(): with open(unblockingFilename, 'r') as fp: - with open(unblockingFilename + '.new', 'w+') as fpnew: - for line in fp: - blockLine = \ - line.replace('\n', '').replace('\r', '') - if unblockHashtag not in line: - fpnew.write(blockLine + '\n') + try: + with open(unblockingFilename + '.new', 'w+') as fpnew: + for line in fp: + blockLine = \ + line.replace('\n', '').replace('\r', '') + 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'): os.rename(unblockingFilename + '.new', unblockingFilename) return True @@ -151,11 +192,16 @@ def removeBlock(baseDir: str, nickname: str, domain: str, if os.path.isfile(unblockingFilename): if unblockHandle in open(unblockingFilename).read(): with open(unblockingFilename, 'r') as fp: - with open(unblockingFilename + '.new', 'w+') as fpnew: - for line in fp: - handle = line.replace('\n', '').replace('\r', '') - if unblockHandle not in line: - fpnew.write(handle + '\n') + try: + with open(unblockingFilename + '.new', 'w+') as fpnew: + for line in fp: + handle = line.replace('\n', '').replace('\r', '') + 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'): os.rename(unblockingFilename + '.new', unblockingFilename) return True @@ -516,16 +562,20 @@ def mutePost(baseDir: str, nickname: str, domain: str, port: int, try: os.remove(cachedPostFilename) print('MUTE: cached post removed ' + cachedPostFilename) - except BaseException: + except OSError: print('EX: MUTE cached post not removed ' + cachedPostFilename) pass else: print('MUTE: cached post not found ' + cachedPostFilename) - with open(postFilename + '.muted', 'w+') as muteFile: - muteFile.write('\n') - print('MUTE: ' + postFilename + '.muted file added') + try: + with open(postFilename + '.muted', 'w+') as muteFile: + 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 recentPostsCache.get('index'): @@ -555,7 +605,7 @@ def mutePost(baseDir: str, nickname: str, domain: str, port: int, os.remove(cachedPostFilename) print('MUTE: cached referenced post removed ' + cachedPostFilename) - except BaseException: + except OSError: print('EX: ' + 'MUTE cached referenced post not removed ' + cachedPostFilename) @@ -587,11 +637,10 @@ def unmutePost(baseDir: str, nickname: str, domain: str, port: int, if os.path.isfile(muteFilename): try: os.remove(muteFilename) - except BaseException: + except OSError: if debug: print('EX: unmutePost mute filename not deleted ' + str(muteFilename)) - pass print('UNMUTE: ' + muteFilename + ' file removed') postJsonObj = postJsonObject @@ -638,11 +687,10 @@ def unmutePost(baseDir: str, nickname: str, domain: str, port: int, if os.path.isfile(cachedPostFilename): try: os.remove(cachedPostFilename) - except BaseException: + except OSError: if debug: print('EX: unmutePost cached post not deleted ' + str(cachedPostFilename)) - pass # if the post is in the recent posts cache then mark it as unmuted if recentPostsCache.get('index'): @@ -671,12 +719,11 @@ def unmutePost(baseDir: str, nickname: str, domain: str, port: int, os.remove(cachedPostFilename) print('MUTE: cached referenced post removed ' + cachedPostFilename) - except BaseException: + except OSError: if debug: print('EX: ' + 'unmutePost cached ref post not removed ' + str(cachedPostFilename)) - pass if recentPostsCache.get('json'): if recentPostsCache['json'].get(alsoUpdatePostId): @@ -818,10 +865,9 @@ def setBrochMode(baseDir: str, domainFull: str, enabled: bool) -> None: if os.path.isfile(allowFilename): try: os.remove(allowFilename) - except BaseException: + except OSError: print('EX: setBrochMode allow file not deleted ' + str(allowFilename)) - pass print('Broch mode turned off') else: if os.path.isfile(allowFilename): @@ -852,11 +898,15 @@ def setBrochMode(baseDir: str, domainFull: str, enabled: bool) -> None: break # write the allow file - with open(allowFilename, 'w+') as allowFile: - allowFile.write(domainFull + '\n') - for d in allowedDomains: - allowFile.write(d + '\n') - print('Broch mode enabled') + try: + with open(allowFilename, 'w+') as allowFile: + allowFile.write(domainFull + '\n') + for d in allowedDomains: + 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) @@ -885,10 +935,9 @@ def brochModeLapses(baseDir: str, lapseDays: int) -> bool: try: os.remove(allowFilename) removed = True - except BaseException: + except OSError: print('EX: brochModeLapses allow file not deleted ' + str(allowFilename)) - pass if removed: setConfigParam(baseDir, "brochMode", False) print('Broch mode has elapsed') diff --git a/blog.py b/blog.py index a136d36d0..de240103c 100644 --- a/blog.py +++ b/blog.py @@ -91,11 +91,16 @@ def _noOfBlogReplies(baseDir: str, httpPrefix: str, translate: {}, if lines and removals: print('Rewriting ' + postFilename + ' to remove ' + str(len(removals)) + ' entries') - with open(postFilename, 'w+') as f: - for replyPostId in lines: - replyPostId = replyPostId.replace('\n', '').replace('\r', '') - if replyPostId not in removals: - f.write(replyPostId + '\n') + try: + with open(postFilename, 'w+') as f: + for replyPostId in lines: + replyPostId = \ + 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 diff --git a/bookmarks.py b/bookmarks.py index 1016e3a2d..197e8aaeb 100644 --- a/bookmarks.py +++ b/bookmarks.py @@ -51,12 +51,11 @@ def undoBookmarksCollectionEntry(recentPostsCache: {}, if os.path.isfile(cachedPostFilename): try: os.remove(cachedPostFilename) - except BaseException: + except OSError: if debug: print('EX: undoBookmarksCollectionEntry ' + 'unable to delete cached post file ' + str(cachedPostFilename)) - pass removePostFromCache(postJsonObject, recentPostsCache) # remove from the index @@ -74,9 +73,12 @@ def undoBookmarksCollectionEntry(recentPostsCache: {}, indexStr = '' with open(bookmarksIndexFilename, 'r') as indexFile: indexStr = indexFile.read().replace(bookmarkIndex + '\n', '') - with open(bookmarksIndexFilename, 'w+') as bookmarksIndexFile: - bookmarksIndexFile.write(indexStr) - + try: + with open(bookmarksIndexFilename, 'w+') as bookmarksIndexFile: + bookmarksIndexFile.write(indexStr) + except OSError: + print('EX: unable to write bookmarks index ' + + bookmarksIndexFilename) if not postJsonObject.get('type'): return if postJsonObject['type'] != 'Create': @@ -163,12 +165,11 @@ def updateBookmarksCollection(recentPostsCache: {}, if os.path.isfile(cachedPostFilename): try: os.remove(cachedPostFilename) - except BaseException: + except OSError: if debug: print('EX: updateBookmarksCollection ' + 'unable to delete cached post ' + str(cachedPostFilename)) - pass removePostFromCache(postJsonObject, recentPostsCache) if not postJsonObject.get('object'): @@ -233,8 +234,12 @@ def updateBookmarksCollection(recentPostsCache: {}, print('WARN: Failed to write entry to bookmarks index ' + bookmarksIndexFilename + ' ' + str(e)) else: - with open(bookmarksIndexFilename, 'w+') as bookmarksIndexFile: - bookmarksIndexFile.write(bookmarkIndex + '\n') + try: + with open(bookmarksIndexFilename, 'w+') as bookmarksIndexFile: + bookmarksIndexFile.write(bookmarkIndex + '\n') + except OSError: + print('EX: unable to write bookmarks index ' + + bookmarksIndexFilename) def bookmark(recentPostsCache: {}, diff --git a/cache.py b/cache.py index 62ae4132e..bbc2cbb9f 100644 --- a/cache.py +++ b/cache.py @@ -26,9 +26,8 @@ def _removePersonFromCache(baseDir: str, personUrl: str, if os.path.isfile(cacheFilename): try: os.remove(cacheFilename) - except BaseException: + except OSError: print('EX: unable to delete cached actor ' + str(cacheFilename)) - pass if personCache.get(personUrl): del personCache[personUrl] diff --git a/categories.py b/categories.py index 07fbe51d0..25db73113 100644 --- a/categories.py +++ b/categories.py @@ -95,11 +95,10 @@ def updateHashtagCategories(baseDir: str) -> None: if os.path.isfile(categoryListFilename): try: os.remove(categoryListFilename) - except BaseException: + except OSError: print('EX: updateHashtagCategories ' + 'unable to delete cached category list ' + categoryListFilename) - pass return categoryList = [] @@ -112,8 +111,11 @@ def updateHashtagCategories(baseDir: str) -> None: categoryListStr += categoryStr + '\n' # save a list of available categories for quick lookup - with open(categoryListFilename, 'w+') as fp: - fp.write(categoryListStr) + try: + with open(categoryListFilename, 'w+') as fp: + fp.write(categoryListStr) + except OSError: + print('EX: unable to write category ' + categoryListFilename) def _validHashtagCategory(category: str) -> bool: @@ -159,12 +161,15 @@ def setHashtagCategory(baseDir: str, hashtag: str, category: str, # don't overwrite any existing categories if os.path.isfile(categoryFilename): return False - with open(categoryFilename, 'w+') as fp: - fp.write(category) - if update: - updateHashtagCategories(baseDir) - return True - + try: + with open(categoryFilename, 'w+') as fp: + fp.write(category) + if update: + updateHashtagCategories(baseDir) + return True + except OSError as e: + print('EX: unable to write category ' + categoryFilename + + ' ' + str(e)) return False diff --git a/content.py b/content.py index f409d43e0..e4dcfe99a 100644 --- a/content.py +++ b/content.py @@ -1015,21 +1015,19 @@ def saveMediaInFormPOST(mediaBytes, debug: bool, if os.path.isfile(possibleOtherFormat): try: os.remove(possibleOtherFormat) - except BaseException: + except OSError: if debug: print('EX: saveMediaInFormPOST ' + 'unable to delete other ' + str(possibleOtherFormat)) - pass if os.path.isfile(filenameBase): try: os.remove(filenameBase) - except BaseException: + except OSError: if debug: print('EX: saveMediaInFormPOST ' + 'unable to delete ' + str(filenameBase)) - pass if debug: print('DEBUG: No media found within POST') @@ -1097,12 +1095,11 @@ def saveMediaInFormPOST(mediaBytes, debug: bool, if os.path.isfile(possibleOtherFormat): try: os.remove(possibleOtherFormat) - except BaseException: + except OSError: if debug: print('EX: saveMediaInFormPOST ' + 'unable to delete other 2 ' + str(possibleOtherFormat)) - pass # don't allow scripts within svg files if detectedExtension == 'svg': @@ -1111,8 +1108,11 @@ def saveMediaInFormPOST(mediaBytes, debug: bool, if dangerousSVG(svgStr, False): return None, None - with open(filename, 'wb') as fp: - fp.write(mediaBytes[startPos:]) + try: + with open(filename, 'wb') as fp: + fp.write(mediaBytes[startPos:]) + except OSError: + print('EX: unable to write media') if not os.path.isfile(filename): print('WARN: Media file could not be written to file: ' + filename) diff --git a/conversation.py b/conversation.py index d44d8568b..96e515acf 100644 --- a/conversation.py +++ b/conversation.py @@ -45,19 +45,17 @@ def updateConversation(baseDir: str, nickname: str, domain: str, with open(conversationFilename, 'w+') as fp: fp.write(postId + '\n') return True - except BaseException: + except OSError: print('EX: updateConversation ' + 'unable to write to ' + conversationFilename) - pass elif postId + '\n' not in open(conversationFilename).read(): try: with open(conversationFilename, 'a+') as fp: fp.write(postId + '\n') return True - except BaseException: + except OSError: print('EX: updateConversation 2 ' + 'unable to write to ' + conversationFilename) - pass return False @@ -72,8 +70,11 @@ def muteConversation(baseDir: str, nickname: str, domain: str, return if os.path.isfile(conversationFilename + '.muted'): return - with open(conversationFilename + '.muted', 'w+') as fp: - fp.write('\n') + try: + 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, @@ -89,7 +90,6 @@ def unmuteConversation(baseDir: str, nickname: str, domain: str, return try: os.remove(conversationFilename + '.muted') - except BaseException: + except OSError: print('EX: unmuteConversation unable to delete ' + conversationFilename + '.muted') - pass diff --git a/daemon.py b/daemon.py index ff6562e19..dac884889 100644 --- a/daemon.py +++ b/daemon.py @@ -532,8 +532,12 @@ class PubServer(BaseHTTPRequestHandler): self.server.maxReplies, self.server.debug) # record the vote - with open(votesFilename, 'a+') as votesFile: - votesFile.write(messageId + '\n') + try: + 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, # so that it then will be recreated @@ -546,11 +550,10 @@ class PubServer(BaseHTTPRequestHandler): if os.path.isfile(cachedPostFilename): try: os.remove(cachedPostFilename) - except BaseException: + except OSError: print('EX: _sendReplyToQuestion ' + 'unable to delete ' + cachedPostFilename) - pass # remove from memory cache removePostFromCache(postJsonObject, self.server.recentPostsCache) @@ -838,19 +841,17 @@ class PubServer(BaseHTTPRequestHandler): try: with open(mediaFilename + '.etag', 'r') as etagFile: etag = etagFile.read() - except BaseException: + except OSError: print('EX: _set_headers_etag ' + 'unable to read ' + mediaFilename + '.etag') - pass if not etag: etag = md5(data).hexdigest() # nosec try: with open(mediaFilename + '.etag', 'w+') as etagFile: etagFile.write(etag) - except BaseException: + except OSError: print('EX: _set_headers_etag ' + 'unable to write ' + mediaFilename + '.etag') - pass # if etag: # self.send_header('ETag', '"' + etag + '"') if lastModified: @@ -872,12 +873,11 @@ class PubServer(BaseHTTPRequestHandler): # load the etag from file currEtag = '' try: - with open(mediaFilename, 'r') as etagFile: + with open(mediaFilename + '.etag', 'r') as etagFile: currEtag = etagFile.read() - except BaseException: + except OSError: print('EX: _etag_exists unable to read ' + str(mediaFilename)) - pass if currEtag and oldEtag == currEtag: # The file has not changed return True @@ -1758,15 +1758,15 @@ class PubServer(BaseHTTPRequestHandler): try: with open(saltFilename, 'r') as fp: salt = fp.read() - except Exception as e: - print('WARN: Unable to read salt for ' + + except OSError as e: + print('EX: Unable to read salt for ' + loginNickname + ' ' + str(e)) else: try: with open(saltFilename, 'w+') as fp: fp.write(salt) - except Exception as e: - print('WARN: Unable to save salt for ' + + except OSError as e: + print('EX: Unable to save salt for ' + loginNickname + ' ' + str(e)) tokenText = loginNickname + loginPassword + salt @@ -1779,8 +1779,8 @@ class PubServer(BaseHTTPRequestHandler): try: with open(tokenFilename, 'w+') as fp: fp.write(token) - except Exception as e: - print('WARN: Unable to save token for ' + + except OSError as e: + print('EX: Unable to save token for ' + loginNickname + ' ' + str(e)) personUpgradeActor(baseDir, None, loginHandle, @@ -2348,17 +2348,20 @@ class PubServer(BaseHTTPRequestHandler): if os.path.isfile(newswireBlockedFilename): try: os.remove(newswireBlockedFilename) - except BaseException: + except OSError: print('EX: _personOptions unable to delete ' + newswireBlockedFilename) - pass refreshNewswire(self.server.baseDir) else: if os.path.isdir(accountDir): nwFilename = newswireBlockedFilename - with open(nwFilename, 'w+') as noNewswireFile: - noNewswireFile.write('\n') - refreshNewswire(self.server.baseDir) + try: + with open(nwFilename, 'w+') as noNewswireFile: + noNewswireFile.write('\n') + refreshNewswire(self.server.baseDir) + except OSError as e: + print('EX: unable to write ' + nwFilename + + ' ' + str(e)) usersPathStr = \ usersPath + '/' + self.server.defaultTimeline + \ '?page=' + str(pageNumber) @@ -2388,17 +2391,20 @@ class PubServer(BaseHTTPRequestHandler): if os.path.isfile(featuresBlockedFilename): try: os.remove(featuresBlockedFilename) - except BaseException: + except OSError: print('EX: _personOptions unable to delete ' + featuresBlockedFilename) - pass refreshNewswire(self.server.baseDir) else: if os.path.isdir(accountDir): featFilename = featuresBlockedFilename - with open(featFilename, 'w+') as noFeaturesFile: - noFeaturesFile.write('\n') - refreshNewswire(self.server.baseDir) + try: + with open(featFilename, 'w+') as noFeaturesFile: + noFeaturesFile.write('\n') + refreshNewswire(self.server.baseDir) + except OSError as e: + print('EX: unable to write ' + featFilename + + ' ' + str(e)) usersPathStr = \ usersPath + '/' + self.server.defaultTimeline + \ '?page=' + str(pageNumber) @@ -2428,15 +2434,17 @@ class PubServer(BaseHTTPRequestHandler): if os.path.isfile(newswireModFilename): try: os.remove(newswireModFilename) - except BaseException: + except OSError: print('EX: _personOptions unable to delete ' + newswireModFilename) - pass else: if os.path.isdir(accountDir): nwFilename = newswireModFilename - with open(nwFilename, 'w+') as modNewswireFile: - modNewswireFile.write('\n') + try: + with open(nwFilename, 'w+') as modNewswireFile: + modNewswireFile.write('\n') + except OSError: + print('EX: unable to write ' + nwFilename) usersPathStr = \ usersPath + '/' + self.server.defaultTimeline + \ '?page=' + str(pageNumber) @@ -3582,8 +3590,11 @@ class PubServer(BaseHTTPRequestHandler): mediaFilename = \ mediaFilenameBase + '.' + \ getImageExtensionFromMimeType(self.headers['Content-type']) - with open(mediaFilename, 'wb') as avFile: - avFile.write(mediaBytes) + try: + with open(mediaFilename, 'wb') as avFile: + avFile.write(mediaBytes) + except OSError: + print('EX: unable to write ' + mediaFilename) if debug: print('DEBUG: image saved to ' + mediaFilename) self.send_response(201) @@ -3901,10 +3912,9 @@ class PubServer(BaseHTTPRequestHandler): if os.path.isfile(linksFilename): try: os.remove(linksFilename) - except BaseException: + except OSError: print('EX: _linksUpdate unable to delete ' + linksFilename) - pass adminNickname = \ getConfigParam(baseDir, 'admin') @@ -3919,10 +3929,9 @@ class PubServer(BaseHTTPRequestHandler): if os.path.isfile(aboutFilename): try: os.remove(aboutFilename) - except BaseException: + except OSError: print('EX: _linksUpdate unable to delete ' + aboutFilename) - pass if fields.get('editedTOS'): TOSStr = fields['editedTOS'] @@ -3934,10 +3943,9 @@ class PubServer(BaseHTTPRequestHandler): if os.path.isfile(TOSFilename): try: os.remove(TOSFilename) - except BaseException: + except OSError: print('EX: _linksUpdate unable to delete ' + TOSFilename) - pass # redirect back to the default timeline self._redirect_headers(actorStr + '/' + defaultTimeline, @@ -4037,10 +4045,9 @@ class PubServer(BaseHTTPRequestHandler): if os.path.isfile(categoryFilename): try: os.remove(categoryFilename) - except BaseException: + except OSError: print('EX: _setHashtagCategory unable to delete ' + categoryFilename) - pass # redirect back to the default timeline self._redirect_headers(tagScreenStr, @@ -4114,63 +4121,71 @@ class PubServer(BaseHTTPRequestHandler): extractTextFieldsInPOST(postBytes, boundary, debug) if fields.get('editedNewswire'): newswireStr = fields['editedNewswire'] - with open(newswireFilename, 'w+') as newswireFile: - newswireFile.write(newswireStr) + try: + with open(newswireFilename, 'w+') as newswireFile: + newswireFile.write(newswireStr) + except OSError: + print('EX: unable to write ' + newswireFilename) else: if os.path.isfile(newswireFilename): try: os.remove(newswireFilename) - except BaseException: + except OSError: print('EX: _newswireUpdate unable to delete ' + newswireFilename) - pass # save filtered words list for the newswire filterNewswireFilename = \ baseDir + '/accounts/' + \ 'news@' + domain + '/filters.txt' if fields.get('filteredWordsNewswire'): - with open(filterNewswireFilename, 'w+') as filterfile: - filterfile.write(fields['filteredWordsNewswire']) + try: + with open(filterNewswireFilename, 'w+') as filterfile: + filterfile.write(fields['filteredWordsNewswire']) + except OSError: + print('EX: unable to write ' + filterNewswireFilename) else: if os.path.isfile(filterNewswireFilename): try: os.remove(filterNewswireFilename) - except BaseException: + except OSError: print('EX: _newswireUpdate unable to delete ' + filterNewswireFilename) - pass # save news tagging rules hashtagRulesFilename = \ baseDir + '/accounts/hashtagrules.txt' if fields.get('hashtagRulesList'): - with open(hashtagRulesFilename, 'w+') as rulesfile: - rulesfile.write(fields['hashtagRulesList']) + try: + with open(hashtagRulesFilename, 'w+') as rulesfile: + rulesfile.write(fields['hashtagRulesList']) + except OSError: + print('EX: unable to write ' + hashtagRulesFilename) else: if os.path.isfile(hashtagRulesFilename): try: os.remove(hashtagRulesFilename) - except BaseException: + except OSError: print('EX: _newswireUpdate unable to delete ' + hashtagRulesFilename) - pass newswireTrustedFilename = baseDir + '/accounts/newswiretrusted.txt' if fields.get('trustedNewswire'): newswireTrusted = fields['trustedNewswire'] if not newswireTrusted.endswith('\n'): newswireTrusted += '\n' - with open(newswireTrustedFilename, 'w+') as trustFile: - trustFile.write(newswireTrusted) + try: + with open(newswireTrustedFilename, 'w+') as trustFile: + trustFile.write(newswireTrusted) + except OSError: + print('EX: unable to write ' + newswireTrustedFilename) else: if os.path.isfile(newswireTrustedFilename): try: os.remove(newswireTrustedFilename) - except BaseException: + except OSError: print('EX: _newswireUpdate unable to delete ' + newswireTrustedFilename) - pass # redirect back to the default timeline self._redirect_headers(actorStr + '/' + defaultTimeline, @@ -4197,10 +4212,9 @@ class PubServer(BaseHTTPRequestHandler): if os.path.isfile(citationsFilename): try: os.remove(citationsFilename) - except BaseException: + except OSError: print('EX: _citationsUpdate unable to delete ' + citationsFilename) - pass if newswire and \ ' boundary=' in self.headers['Content-type']: @@ -4257,8 +4271,11 @@ class PubServer(BaseHTTPRequestHandler): citationsStr += citationDate + '\n' # save citations dates, so that they can be added when # reloading the newblog screen - with open(citationsFilename, 'w+') as citationsFile: - citationsFile.write(citationsStr) + try: + with open(citationsFilename, 'w+') as citationsFile: + citationsFile.write(citationsStr) + except OSError: + print('EX: unable to write ' + citationsFilename) # redirect back to the default timeline self._redirect_headers(actorStr + '/newblog', @@ -4504,10 +4521,9 @@ class PubServer(BaseHTTPRequestHandler): if os.path.isfile(filenameBase): try: os.remove(filenameBase) - except BaseException: + except OSError: print('EX: _profileUpdate unable to delete ' + filenameBase) - pass else: filenameBase = \ acctDir(baseDir, nickname, domain) + \ @@ -4541,10 +4557,9 @@ class PubServer(BaseHTTPRequestHandler): if os.path.isfile(postImageFilename + '.etag'): try: os.remove(postImageFilename + '.etag') - except BaseException: + except OSError: print('EX: _profileUpdate unable to delete ' + postImageFilename + '.etag') - pass city = getSpoofedCity(self.server.city, baseDir, nickname, domain) @@ -4712,8 +4727,11 @@ class PubServer(BaseHTTPRequestHandler): if fields.get('cityDropdown'): cityFilename = \ acctDir(baseDir, nickname, domain) + '/city.txt' - with open(cityFilename, 'w+') as fp: - fp.write(fields['cityDropdown']) + try: + with open(cityFilename, 'w+') as fp: + fp.write(fields['cityDropdown']) + except OSError: + print('EX: unable to write ' + cityFilename) # change displayed name if fields.get('displayNickname'): @@ -5597,11 +5615,10 @@ class PubServer(BaseHTTPRequestHandler): try: os.remove(baseDir + '/fonts/custom.' + ext) - except BaseException: + except OSError: print('EX: _profileUpdate ' + 'unable to delete ' + baseDir + '/fonts/custom.' + ext) - pass if os.path.isfile(baseDir + '/fonts/custom.' + ext + '.etag'): @@ -5609,12 +5626,11 @@ class PubServer(BaseHTTPRequestHandler): os.remove(baseDir + '/fonts/custom.' + ext + '.etag') - except BaseException: + except OSError: print('EX: _profileUpdate ' + 'unable to delete ' + baseDir + '/fonts/custom.' + ext + '.etag') - pass currTheme = getTheme(baseDir) if currTheme: self.server.themeName = currTheme @@ -5664,11 +5680,10 @@ class PubServer(BaseHTTPRequestHandler): if os.path.isfile(followDMsFilename): try: os.remove(followDMsFilename) - except BaseException: + except OSError: print('EX: _profileUpdate ' + 'unable to delete ' + followDMsFilename) - pass # remove Twitter retweets removeTwitterFilename = \ @@ -5685,11 +5700,10 @@ class PubServer(BaseHTTPRequestHandler): if os.path.isfile(removeTwitterFilename): try: os.remove(removeTwitterFilename) - except BaseException: + except OSError: print('EX: _profileUpdate ' + 'unable to delete ' + removeTwitterFilename) - pass # hide Like button hideLikeButtonFile = \ @@ -5708,20 +5722,18 @@ class PubServer(BaseHTTPRequestHandler): if os.path.isfile(notifyLikesFilename): try: os.remove(notifyLikesFilename) - except BaseException: + except OSError: print('EX: _profileUpdate ' + 'unable to delete ' + notifyLikesFilename) - pass if not hideLikeButtonActive: if os.path.isfile(hideLikeButtonFile): try: os.remove(hideLikeButtonFile) - except BaseException: + except OSError: print('EX: _profileUpdate ' + 'unable to delete ' + hideLikeButtonFile) - pass # hide Reaction button hideReactionButtonFile = \ @@ -5740,20 +5752,18 @@ class PubServer(BaseHTTPRequestHandler): if os.path.isfile(notifyReactionsFilename): try: os.remove(notifyReactionsFilename) - except BaseException: + except OSError: print('EX: _profileUpdate ' + 'unable to delete ' + notifyReactionsFilename) - pass if not hideReactionButtonActive: if os.path.isfile(hideReactionButtonFile): try: os.remove(hideReactionButtonFile) - except BaseException: + except OSError: print('EX: _profileUpdate ' + 'unable to delete ' + hideReactionButtonFile) - pass # notify about new Likes if onFinalWelcomeScreen: @@ -5773,11 +5783,10 @@ class PubServer(BaseHTTPRequestHandler): if os.path.isfile(notifyLikesFilename): try: os.remove(notifyLikesFilename) - except BaseException: + except OSError: print('EX: _profileUpdate ' + 'unable to delete ' + notifyLikesFilename) - pass notifyReactionsFilename = \ acctDir(baseDir, nickname, domain) + \ @@ -5800,11 +5809,10 @@ class PubServer(BaseHTTPRequestHandler): if os.path.isfile(notifyReactionsFilename): try: os.remove(notifyReactionsFilename) - except BaseException: + except OSError: print('EX: _profileUpdate ' + 'unable to delete ' + notifyReactionsFilename) - pass # this account is a bot if fields.get('isBot'): @@ -5865,11 +5873,10 @@ class PubServer(BaseHTTPRequestHandler): if os.path.isfile(filterFilename): try: os.remove(filterFilename) - except BaseException: + except OSError: print('EX: _profileUpdate ' + 'unable to delete ' + filterFilename) - pass # word replacements switchFilename = \ @@ -5882,11 +5889,10 @@ class PubServer(BaseHTTPRequestHandler): if os.path.isfile(switchFilename): try: os.remove(switchFilename) - except BaseException: + except OSError: print('EX: _profileUpdate ' + 'unable to delete ' + switchFilename) - pass # autogenerated tags autoTagsFilename = \ @@ -5899,11 +5905,10 @@ class PubServer(BaseHTTPRequestHandler): if os.path.isfile(autoTagsFilename): try: os.remove(autoTagsFilename) - except BaseException: + except OSError: print('EX: _profileUpdate ' + 'unable to delete ' + autoTagsFilename) - pass # autogenerated content warnings autoCWFilename = \ @@ -5916,11 +5921,10 @@ class PubServer(BaseHTTPRequestHandler): if os.path.isfile(autoCWFilename): try: os.remove(autoCWFilename) - except BaseException: + except OSError: print('EX: _profileUpdate ' + 'unable to delete ' + autoCWFilename) - pass # save blocked accounts list blockedFilename = \ @@ -5933,11 +5937,10 @@ class PubServer(BaseHTTPRequestHandler): if os.path.isfile(blockedFilename): try: os.remove(blockedFilename) - except BaseException: + except OSError: print('EX: _profileUpdate ' + 'unable to delete ' + blockedFilename) - pass # Save DM allowed instances list. # The allow list for incoming DMs, @@ -5952,11 +5955,10 @@ class PubServer(BaseHTTPRequestHandler): if os.path.isfile(dmAllowedInstancesFilename): try: os.remove(dmAllowedInstancesFilename) - except BaseException: + except OSError: print('EX: _profileUpdate ' + 'unable to delete ' + dmAllowedInstancesFilename) - pass # save allowed instances list # This is the account level allow list @@ -5970,11 +5972,10 @@ class PubServer(BaseHTTPRequestHandler): if os.path.isfile(allowedInstancesFilename): try: os.remove(allowedInstancesFilename) - except BaseException: + except OSError: print('EX: _profileUpdate ' + 'unable to delete ' + allowedInstancesFilename) - pass if isModerator(self.server.baseDir, nickname): # set selected content warning lists @@ -6036,11 +6037,10 @@ class PubServer(BaseHTTPRequestHandler): if os.path.isfile(peertubeInstancesFile): try: os.remove(peertubeInstancesFile) - except BaseException: + except OSError: print('EX: _profileUpdate ' + 'unable to delete ' + peertubeInstancesFile) - pass self.server.peertubeInstances.clear() # save git project names list @@ -6054,11 +6054,10 @@ class PubServer(BaseHTTPRequestHandler): if os.path.isfile(gitProjectsFilename): try: os.remove(gitProjectsFilename) - except BaseException: + except OSError: print('EX: _profileUpdate ' + 'unable to delete ' + gitProjectsFilename) - pass # save actor json file within accounts if actorChanged: @@ -15946,10 +15945,9 @@ class PubServer(BaseHTTPRequestHandler): try: with open(mediaTagFilename, 'r') as etagFile: etag = etagFile.read() - except BaseException: + except OSError: print('EX: do_HEAD unable to read ' + mediaTagFilename) - pass else: with open(mediaFilename, 'rb') as avFile: mediaBinary = avFile.read() @@ -15957,10 +15955,9 @@ class PubServer(BaseHTTPRequestHandler): try: with open(mediaTagFilename, 'w+') as etagFile: etagFile.write(etag) - except BaseException: + except OSError: print('EX: do_HEAD unable to write ' + mediaTagFilename) - pass mediaFileType = mediaFileMimeType(checkPath) self._set_headers_head(mediaFileType, fileLength, @@ -16127,10 +16124,9 @@ class PubServer(BaseHTTPRequestHandler): try: with open(lastUsedFilename, 'w+') as lastUsedFile: lastUsedFile.write(str(int(time.time()))) - except BaseException: + except OSError: print('EX: _receiveNewPostProcess unable to write ' + lastUsedFilename) - pass mentionsStr = '' if fields.get('mentions'): @@ -16296,10 +16292,9 @@ class PubServer(BaseHTTPRequestHandler): print('Edited blog post, removing cached html') try: os.remove(cachedFilename) - except BaseException: + except OSError: print('EX: _receiveNewPostProcess ' + 'unable to delete ' + cachedFilename) - pass # remove from memory cache removePostFromCache(postJsonObject, self.server.recentPostsCache) @@ -16732,10 +16727,9 @@ class PubServer(BaseHTTPRequestHandler): if os.path.isfile(filename): try: os.remove(filename) - except BaseException: + except OSError: print('EX: _receiveNewPostProcess ' + 'unable to delete ' + filename) - pass self.postToNickname = nickname return 1 return -1 diff --git a/delete.py b/delete.py index bd67f5dd6..74c084a60 100644 --- a/delete.py +++ b/delete.py @@ -201,6 +201,5 @@ def removeOldHashtags(baseDir: str, maxMonths: int) -> str: for removeFilename in removeHashtags: try: os.remove(removeFilename) - except BaseException: + except OSError: print('EX: removeOldHashtags unable to delete ' + removeFilename) - pass diff --git a/devices.py b/devices.py index e306b3dd8..19997fa09 100644 --- a/devices.py +++ b/devices.py @@ -46,9 +46,8 @@ def E2EEremoveDevice(baseDir: str, nickname: str, domain: str, if os.path.isfile(deviceFilename): try: os.remove(deviceFilename) - except BaseException: + except OSError: print('EX: E2EEremoveDevice unable to delete ' + deviceFilename) - pass return True return False diff --git a/epicyon.py b/epicyon.py index 7cc492481..9dced32f0 100644 --- a/epicyon.py +++ b/epicyon.py @@ -895,9 +895,8 @@ if args.socnet: with open('socnet.dot', 'w+') as fp: fp.write(dotGraph) print('Saved to socnet.dot') - except BaseException: + except OSError: print('EX: commandline unable to write socnet.dot') - pass sys.exit() if args.postsraw: diff --git a/follow.py b/follow.py index b8953131f..1708f9a21 100644 --- a/follow.py +++ b/follow.py @@ -296,12 +296,15 @@ def unfollowAccount(baseDir: str, nickname: str, domain: str, return with open(filename, 'r') as f: lines = f.readlines() - with open(filename, 'w+') as f: - for line in lines: - checkHandle = line.strip("\n").strip("\r").lower() - if checkHandle != handleToUnfollowLower and \ - checkHandle != '!' + handleToUnfollowLower: - f.write(line) + try: + with open(filename, 'w+') as f: + for line in lines: + checkHandle = line.strip("\n").strip("\r").lower() + if checkHandle != handleToUnfollowLower and \ + 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 # 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: f.write(handleToUnfollow + '\n') else: - with open(unfollowedFilename, 'w+') as f: - f.write(handleToUnfollow + '\n') + try: + with open(unfollowedFilename, 'w+') as f: + f.write(handleToUnfollow + '\n') + except OSError: + print('EX: unable to write ' + unfollowedFilename) return True @@ -341,9 +347,8 @@ def clearFollows(baseDir: str, nickname: str, domain: str, if os.path.isfile(filename): try: os.remove(filename) - except BaseException: + except OSError: print('EX: clearFollows unable to delete ' + filename) - pass def clearFollowers(baseDir: str, nickname: str, domain: str) -> None: @@ -651,8 +656,11 @@ def _storeFollowRequest(baseDir: str, print('DEBUG: ' + approveHandleStored + ' is already awaiting approval') else: - with open(approveFollowsFilename, 'w+') as fp: - fp.write(approveHandleStored + '\n') + try: + 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 # 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 ' + str(e)) else: - with open(followersFilename, 'w+') as followersFile: - followersFile.write(approveHandle + '\n') + try: + with open(followersFilename, 'w+') as followersFile: + followersFile.write(approveHandle + '\n') + except OSError: + print('EX: unable to write ' + followersFilename) print('Beginning follow accept') return followedAccountAccepts(session, baseDir, httpPrefix, @@ -908,10 +919,9 @@ def followedAccountAccepts(session, baseDir: str, httpPrefix: str, if os.path.isfile(followActivityfilename): try: os.remove(followActivityfilename) - except BaseException: + except OSError: print('EX: followedAccountAccepts unable to delete ' + followActivityfilename) - pass groupAccount = False if followJson: @@ -983,10 +993,9 @@ def followedAccountRejects(session, baseDir: str, httpPrefix: str, # remove the follow request json try: os.remove(followActivityfilename) - except BaseException: + except OSError: print('EX: followedAccountRejects unable to delete ' + followActivityfilename) - pass # send the reject activity return sendSignedJson(rejectJson, session, baseDir, nicknameToFollow, domainToFollow, port, @@ -1049,8 +1058,11 @@ def sendFollowRequest(session, baseDir: str, unfollowedFile = \ unfollowedFile.replace(followHandle + '\n', '') if unfollowedFile: - with open(unfollowedFilename, 'w+') as fp: - fp.write(unfollowedFile) + try: + with open(unfollowedFilename, 'w+') as fp: + fp.write(unfollowedFile) + except OSError: + print('EX: unable to write ' + unfollowedFilename) newFollowJson = { '@context': 'https://www.w3.org/ns/activitystreams', diff --git a/followingCalendar.py b/followingCalendar.py index 5782f801e..c179690fe 100644 --- a/followingCalendar.py +++ b/followingCalendar.py @@ -46,8 +46,11 @@ def receivingCalendarEvents(baseDir: str, nickname: str, domain: str, # create a new calendar file from the following file with open(followingFilename, 'r') as followingFile: followingHandles = followingFile.read() - with open(calendarFilename, 'w+') as fp: - fp.write(followingHandles) + try: + with open(calendarFilename, 'w+') as fp: + fp.write(followingHandles) + except OSError: + print('EX: unable to write ' + calendarFilename) 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: followingHandles = followingFile.read() if add: - with open(calendarFilename, 'w+') as fp: - fp.write(followingHandles + handle + '\n') + try: + with open(calendarFilename, 'w+') as fp: + fp.write(followingHandles + handle + '\n') + except OSError: + print('EX: unable to write ' + calendarFilename) # already in the calendar file? if handle + '\n' in followingHandles: @@ -100,16 +106,22 @@ def _receiveCalendarEvents(baseDir: str, nickname: str, domain: str, return # remove from calendar file followingHandles = followingHandles.replace(handle + '\n', '') - with open(calendarFilename, 'w+') as fp: - fp.write(followingHandles) + try: + with open(calendarFilename, 'w+') as fp: + fp.write(followingHandles) + except OSError: + print('EX: unable to write ' + calendarFilename) else: print(handle + ' not in followingCalendar.txt') # not already in the calendar file if add: # append to the list of handles followingHandles += handle + '\n' - with open(calendarFilename, 'w+') as fp: - fp.write(followingHandles) + try: + 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, diff --git a/git.py b/git.py index 2cab9bf32..df0e4a638 100644 --- a/git.py +++ b/git.py @@ -208,11 +208,14 @@ def receiveGitPatch(baseDir: str, nickname: str, domain: str, return False patchStr = \ _gitAddFromHandle(patchStr, '@' + fromNickname + '@' + fromDomain) - with open(patchFilename, 'w+') as patchFile: - patchFile.write(patchStr) - patchNotifyFilename = \ - acctDir(baseDir, nickname, domain) + '/.newPatchContent' - with open(patchNotifyFilename, 'w+') as patchFile: + try: + with open(patchFilename, 'w+') as patchFile: 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 diff --git a/happening.py b/happening.py index 3151dee74..cab084c83 100644 --- a/happening.py +++ b/happening.py @@ -41,9 +41,8 @@ def _removeEventFromTimeline(eventId: str, tlEventsFilename: str) -> None: try: with open(tlEventsFilename, 'w+') as fp2: fp2.write(eventsTimeline) - except BaseException: + except OSError: print('EX: ERROR: unable to save events timeline') - pass 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: tlEventsFile.seek(0, 0) tlEventsFile.write(eventId + '\n' + content) - except Exception as e: - print('WARN: Failed to write entry to events file ' + + except OSError as e: + print('EX: Failed to write entry to events file ' + tlEventsFilename + ' ' + str(e)) return False else: - with open(tlEventsFilename, 'w+') as tlEventsFile: - tlEventsFile.write(eventId + '\n') + try: + 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 if not os.path.isdir(calendarPath + '/' + str(eventYear)): @@ -128,18 +130,24 @@ def saveEventPost(baseDir: str, handle: str, postId: str, return False # append the post Id to the file for the calendar month - with open(calendarFilename, 'a+') as calendarFile: - calendarFile.write(postId + '\n') + try: + 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 # a new event has been added - calendarNotificationFilename = \ - baseDir + '/accounts/' + handle + '/.newCalendar' - with open(calendarNotificationFilename, 'w+') as calendarNotificationFile: - notifyStr = \ - '/calendar?year=' + str(eventYear) + '?month=' + \ - str(eventMonthNumber) + '?day=' + str(eventDayOfMonth) - calendarNotificationFile.write(notifyStr) + calNotifyFilename = baseDir + '/accounts/' + handle + '/.newCalendar' + notifyStr = \ + '/calendar?year=' + str(eventYear) + '?month=' + \ + str(eventMonthNumber) + '?day=' + str(eventDayOfMonth) + try: + with open(calNotifyFilename, 'w+') as calendarNotificationFile: + calendarNotificationFile.write(notifyStr) + except OSError: + print('EX: unable to write ' + calNotifyFilename) + return False 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 recreateEventsFile: - with open(calendarFilename, 'w+') as calendarFile: - for postId in calendarPostIds: - calendarFile.write(postId + '\n') + try: + with open(calendarFilename, 'w+') as calendarFile: + for postId in calendarPostIds: + calendarFile.write(postId + '\n') + except OSError: + print('EX: unable to write ' + calendarFilename) 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 recreateEventsFile: - with open(calendarFilename, 'w+') as calendarFile: - for postId in calendarPostIds: - calendarFile.write(postId + '\n') + try: + with open(calendarFilename, 'w+') as calendarFile: + for postId in calendarPostIds: + calendarFile.write(postId + '\n') + except OSError: + print('EX: unable to write ' + calendarFilename) 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 recreateEventsFile: - with open(calendarFilename, 'w+') as calendarFile: - for postId in calendarPostIds: - calendarFile.write(postId + '\n') + try: + with open(calendarFilename, 'w+') as calendarFile: + for postId in calendarPostIds: + calendarFile.write(postId + '\n') + except OSError: + print('EX: unable to write ' + calendarFilename) return events @@ -449,7 +466,10 @@ def removeCalendarEvent(baseDir: str, nickname: str, domain: str, lines = f.readlines() if not lines: return - with open(calendarFilename, 'w+') as f: - for line in lines: - if messageId not in line: - f.write(line) + try: + with open(calendarFilename, 'w+') as f: + for line in lines: + if messageId not in line: + f.write(line) + except OSError: + print('EX: unable to write ' + calendarFilename) diff --git a/inbox.py b/inbox.py index db63e88b2..92c4493be 100644 --- a/inbox.py +++ b/inbox.py @@ -141,9 +141,8 @@ def _storeLastPostId(baseDir: str, nickname: str, domain: str, try: with open(actorFilename, 'w+') as fp: fp.write(postId) - except BaseException: + except OSError: print('EX: Unable to write last post id to ' + actorFilename) - pass 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: fp.write(newSwarmStr) return True - except BaseException: + except OSError: print('EX: unable to write cached hashtag swarm ' + cachedHashtagSwarmFilename) - pass return False @@ -238,8 +236,11 @@ def storeHashTags(baseDir: str, nickname: str, domain: str, tagline = str(daysSinceEpoch) + ' ' + nickname + ' ' + postUrl + '\n' hashtagsCtr += 1 if not os.path.isfile(tagsFilename): - with open(tagsFilename, 'w+') as tagsFile: - tagsFile.write(tagline) + try: + with open(tagsFilename, 'w+') as tagsFile: + tagsFile.write(tagline) + except OSError: + print('EX: unable to write ' + tagsFilename) else: if postUrl not in open(tagsFilename).read(): try: @@ -248,8 +249,8 @@ def storeHashTags(baseDir: str, nickname: str, domain: str, if tagline not in content: tagsFile.seek(0, 0) tagsFile.write(tagline + content) - except Exception as e: - print('WARN: Failed to write entry to tags file ' + + except OSError as e: + print('EX: Failed to write entry to tags file ' + tagsFilename + ' ' + str(e)) removeOldHashtags(baseDir, 3) @@ -920,7 +921,7 @@ def _receiveUpdateToQuestion(recentPostsCache: {}, messageJson: {}, if os.path.isfile(cachedPostFilename): try: os.remove(cachedPostFilename) - except BaseException: + except OSError: print('EX: _receiveUpdateToQuestion unable to delete ' + cachedPostFilename) # remove from memory cache @@ -1944,10 +1945,9 @@ def _receiveAnnounce(recentPostsCache: {}, # if the announce can't be downloaded then remove it try: os.remove(postFilename) - except BaseException: + except OSError: print('EX: _receiveAnnounce unable to delete ' + str(postFilename)) - pass else: if debug: print('DEBUG: Announce post downloaded for ' + @@ -1980,8 +1980,12 @@ def _receiveAnnounce(recentPostsCache: {}, postJsonObject, personCache, translate, lookupActor, themeName) - with open(postFilename + '.tts', 'w+') as ttsFile: - ttsFile.write('\n') + try: + with open(postFilename + '.tts', 'w+') as ttsFile: + ttsFile.write('\n') + except OSError: + print('EX: unable to write recent post ' + + postFilename) if debug: print('DEBUG: Obtaining actor for announce post ' + @@ -2059,10 +2063,9 @@ def _receiveUndoAnnounce(recentPostsCache: {}, if os.path.isfile(postFilename): try: os.remove(postFilename) - except BaseException: + except OSError: print('EX: _receiveUndoAnnounce unable to delete ' + str(postFilename)) - pass return True @@ -2146,11 +2149,17 @@ def populateReplies(baseDir: str, httpPrefix: str, domain: str, if numLines > maxReplies: return False if messageId not in open(postRepliesFilename).read(): - with open(postRepliesFilename, 'a+') as repliesFile: - repliesFile.write(messageId + '\n') + try: + with open(postRepliesFilename, 'a+') as repliesFile: + repliesFile.write(messageId + '\n') + except OSError: + print('EX: unable to append ' + postRepliesFilename) else: - with open(postRepliesFilename, 'w+') as repliesFile: - repliesFile.write(messageId + '\n') + try: + with open(postRepliesFilename, 'w+') as repliesFile: + repliesFile.write(messageId + '\n') + except OSError: + print('EX: unable to write ' + postRepliesFilename) return True @@ -2323,8 +2332,11 @@ def _dmNotify(baseDir: str, handle: str, url: str) -> None: return dmFile = accountDir + '/.newDM' if not os.path.isfile(dmFile): - with open(dmFile, 'w+') as fp: - fp.write(url) + try: + 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, @@ -2439,17 +2451,16 @@ def _likeNotify(baseDir: str, domain: str, onionDomain: str, try: with open(prevLikeFile, 'w+') as fp: fp.write(likeStr) - except BaseException: + except OSError: print('EX: ERROR: unable to save previous like notification ' + prevLikeFile) - pass + try: with open(likeFile, 'w+') as fp: fp.write(likeStr) - except BaseException: + except OSError: print('EX: ERROR: unable to write like notification file ' + likeFile) - pass def _reactionNotify(baseDir: str, domain: str, onionDomain: str, @@ -2504,17 +2515,16 @@ def _reactionNotify(baseDir: str, domain: str, onionDomain: str, try: with open(prevReactionFile, 'w+') as fp: fp.write(reactionStr) - except BaseException: + except OSError: print('EX: ERROR: unable to save previous reaction notification ' + prevReactionFile) - pass + try: with open(reactionFile, 'w+') as fp: fp.write(reactionStr) - except BaseException: + except OSError: print('EX: ERROR: unable to write reaction notification file ' + reactionFile) - pass 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() if url in existingNotificationMessage: return - with open(notifyFile, 'w+') as fp: - fp.write(url) + try: + 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: @@ -2544,8 +2557,11 @@ def _replyNotify(baseDir: str, handle: str, url: str) -> None: return replyFile = accountDir + '/.newReply' if not os.path.isfile(replyFile): - with open(replyFile, 'w+') as fp: - fp.write(url) + try: + with open(replyFile, 'w+') as fp: + fp.write(url) + except OSError: + print('EX: unable to write ' + replyFile) def _gitPatchNotify(baseDir: str, handle: str, @@ -2559,8 +2575,11 @@ def _gitPatchNotify(baseDir: str, handle: str, patchFile = accountDir + '/.newPatch' subject = subject.replace('[PATCH]', '').strip() handle = '@' + fromNickname + '@' + fromDomain - with open(patchFile, 'w+') as fp: - fp.write('git ' + handle + ' ' + subject) + try: + 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: @@ -2710,15 +2729,15 @@ def inboxUpdateIndex(boxname: str, baseDir: str, handle: str, indexFile.write(destinationFilename + '\n' + content) written = True return True - except Exception as e: - print('WARN: Failed to write entry to index ' + str(e)) + except OSError as e: + print('EX: Failed to write entry to index ' + str(e)) else: try: with open(indexFilename, 'w+') as indexFile: indexFile.write(destinationFilename + '\n') written = True - except Exception as e: - print('WARN: Failed to write initial entry to index ' + str(e)) + except OSError as e: + print('EX: Failed to write initial entry to index ' + str(e)) return written @@ -2750,8 +2769,11 @@ def _updateLastSeen(baseDir: str, handle: str, actor: str) -> None: if int(daysSinceEpochFile) == daysSinceEpoch: # value hasn't changed, so we can save writing anything to file return - with open(lastSeenFilename, 'w+') as lastSeenFile: - lastSeenFile.write(str(daysSinceEpoch)) + try: + 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, @@ -2973,7 +2995,7 @@ def _receiveQuestionVote(baseDir: str, nickname: str, domain: str, if os.path.isfile(cachedPostFilename): try: os.remove(cachedPostFilename) - except BaseException: + except OSError: print('EX: replytoQuestion unable to delete ' + cachedPostFilename) @@ -3486,8 +3508,12 @@ def _inboxAfterInitial(recentPostsCache: {}, maxRecentPosts: int, # This enables you to ignore a threat that's getting boring if isReplyToMutedPost: print('MUTE REPLY: ' + destinationFilename) - with open(destinationFilename + '.muted', 'w+') as muteFile: - muteFile.write('\n') + destinationFilenameMuted = destinationFilename + '.muted' + try: + with open(destinationFilenameMuted, 'w+') as muteFile: + muteFile.write('\n') + except OSError: + print('EX: unable to write ' + destinationFilenameMuted) # update the indexes for different timelines for boxname in updateIndexList: @@ -3592,9 +3618,8 @@ def clearQueueItems(baseDir: str, queue: []) -> None: try: os.remove(os.path.join(queueDir, qfile)) ctr += 1 - except BaseException: + except OSError: print('EX: clearQueueItems unable to delete ' + qfile) - pass break break if ctr > 0: @@ -3659,10 +3684,9 @@ def _inboxQuotaExceeded(queue: {}, queueFilename: str, if len(queue) > 0: try: os.remove(queueFilename) - except BaseException: + except OSError: print('EX: _inboxQuotaExceeded unable to delete ' + str(queueFilename)) - pass queue.pop(0) return True quotasDaily['domains'][postDomain] += 1 @@ -3682,10 +3706,9 @@ def _inboxQuotaExceeded(queue: {}, queueFilename: str, if len(queue) > 0: try: os.remove(queueFilename) - except BaseException: + except OSError: print('EX: _inboxQuotaExceeded unable to delete ' + str(queueFilename)) - pass queue.pop(0) return True quotasPerMin['domains'][postDomain] += 1 @@ -3704,10 +3727,9 @@ def _inboxQuotaExceeded(queue: {}, queueFilename: str, if len(queue) > 0: try: os.remove(queueFilename) - except BaseException: + except OSError: print('EX: _inboxQuotaExceeded unable to delete ' + str(queueFilename)) - pass queue.pop(0) return True quotasDaily['accounts'][postHandle] += 1 @@ -3728,10 +3750,9 @@ def _inboxQuotaExceeded(queue: {}, queueFilename: str, if len(queue) > 0: try: os.remove(queueFilename) - except BaseException: + except OSError: print('EX: _inboxQuotaExceeded unable to delete ' + str(queueFilename)) - pass queue.pop(0) return True quotasPerMin['accounts'][postHandle] += 1 @@ -3779,8 +3800,11 @@ def _checkJsonSignature(baseDir: str, queueJson: {}) -> (bool, bool): alreadyUnknown = True if not alreadyUnknown: - with open(unknownContextsFile, 'a+') as unknownFile: - unknownFile.write(unknownContext + '\n') + try: + with open(unknownContextsFile, 'a+') as unknownFile: + unknownFile.write(unknownContext + '\n') + except OSError: + print('EX: unable to append ' + unknownContextsFile) else: print('Unrecognized jsonld signature type: ' + jwebsigType) @@ -3794,8 +3818,11 @@ def _checkJsonSignature(baseDir: str, queueJson: {}) -> (bool, bool): alreadyUnknown = True if not alreadyUnknown: - with open(unknownSignaturesFile, 'a+') as unknownFile: - unknownFile.write(jwebsigType + '\n') + try: + with open(unknownSignaturesFile, 'a+') as unknownFile: + unknownFile.write(jwebsigType + '\n') + except OSError: + print('EX: unable to append ' + unknownSignaturesFile) return hasJsonSignature, jwebsigType @@ -3913,10 +3940,9 @@ def runInboxQueue(recentPostsCache: {}, maxRecentPosts: int, if os.path.isfile(queueFilename): try: os.remove(queueFilename) - except BaseException: + except OSError: print('EX: runInboxQueue 1 unable to delete ' + str(queueFilename)) - pass continue # clear the daily quotas for maximum numbers of received posts @@ -3988,10 +4014,9 @@ def runInboxQueue(recentPostsCache: {}, maxRecentPosts: int, if os.path.isfile(queueFilename): try: os.remove(queueFilename) - except BaseException: + except OSError: print('EX: runInboxQueue 2 unable to delete ' + str(queueFilename)) - pass if len(queue) > 0: queue.pop(0) continue @@ -4041,10 +4066,9 @@ def runInboxQueue(recentPostsCache: {}, maxRecentPosts: int, if os.path.isfile(queueFilename): try: os.remove(queueFilename) - except BaseException: + except OSError: print('EX: runInboxQueue 3 unable to delete ' + str(queueFilename)) - pass if len(queue) > 0: queue.pop(0) continue @@ -4063,10 +4087,9 @@ def runInboxQueue(recentPostsCache: {}, maxRecentPosts: int, if os.path.isfile(queueFilename): try: os.remove(queueFilename) - except BaseException: + except OSError: print('EX: runInboxQueue 4 unable to delete ' + str(queueFilename)) - pass if len(queue) > 0: queue.pop(0) continue @@ -4094,10 +4117,9 @@ def runInboxQueue(recentPostsCache: {}, maxRecentPosts: int, if os.path.isfile(queueFilename): try: os.remove(queueFilename) - except BaseException: + except OSError: print('EX: runInboxQueue 5 unable to delete ' + str(queueFilename)) - pass if len(queue) > 0: queue.pop(0) continue @@ -4117,10 +4139,9 @@ def runInboxQueue(recentPostsCache: {}, maxRecentPosts: int, if os.path.isfile(queueFilename): try: os.remove(queueFilename) - except BaseException: + except OSError: print('EX: runInboxQueue 6 unable to delete ' + str(queueFilename)) - pass if len(queue) > 0: queue.pop(0) print('Queue: Follow activity for ' + keyId + @@ -4140,10 +4161,9 @@ def runInboxQueue(recentPostsCache: {}, maxRecentPosts: int, if os.path.isfile(queueFilename): try: os.remove(queueFilename) - except BaseException: + except OSError: print('EX: runInboxQueue 7 unable to delete ' + str(queueFilename)) - pass if len(queue) > 0: queue.pop(0) continue @@ -4163,10 +4183,9 @@ def runInboxQueue(recentPostsCache: {}, maxRecentPosts: int, if os.path.isfile(queueFilename): try: os.remove(queueFilename) - except BaseException: + except OSError: print('EX: runInboxQueue 8 unable to delete ' + str(queueFilename)) - pass if len(queue) > 0: queue.pop(0) continue @@ -4183,10 +4202,9 @@ def runInboxQueue(recentPostsCache: {}, maxRecentPosts: int, if os.path.isfile(queueFilename): try: os.remove(queueFilename) - except BaseException: + except OSError: print('EX: runInboxQueue 9 unable to delete ' + str(queueFilename)) - pass if len(queue) > 0: queue.pop(0) continue @@ -4265,9 +4283,8 @@ def runInboxQueue(recentPostsCache: {}, maxRecentPosts: int, if os.path.isfile(queueFilename): try: os.remove(queueFilename) - except BaseException: + except OSError: print('EX: runInboxQueue 10 unable to delete ' + str(queueFilename)) - pass if len(queue) > 0: queue.pop(0) diff --git a/like.py b/like.py index ef1c57a5d..390e3e622 100644 --- a/like.py +++ b/like.py @@ -430,10 +430,9 @@ def updateLikesCollection(recentPostsCache: {}, if os.path.isfile(cachedPostFilename): try: os.remove(cachedPostFilename) - except BaseException: + except OSError: print('EX: updateLikesCollection unable to delete ' + cachedPostFilename) - pass obj = postJsonObject if hasObjectDict(postJsonObject): diff --git a/manualapprove.py b/manualapprove.py index 4af4146a9..acad597a0 100644 --- a/manualapprove.py +++ b/manualapprove.py @@ -46,8 +46,11 @@ def manualDenyFollowRequest(session, baseDir: str, removeFromFollowRequests(baseDir, nickname, domain, denyHandle, debug) # Store rejected follows - with open(rejectedFollowsFilename, 'a+') as rejectsFile: - rejectsFile.write(denyHandle + '\n') + try: + with open(rejectedFollowsFilename, 'a+') as rejectsFile: + rejectsFile.write(denyHandle + '\n') + except OSError: + print('EX: unable to append ' + rejectedFollowsFilename) denyNickname = denyHandle.split('@')[0] denyDomain = \ @@ -104,11 +107,17 @@ def _approveFollowerHandle(accountDir: str, approveHandle: str) -> None: approvedFilename = accountDir + '/approved.txt' if os.path.isfile(approvedFilename): if approveHandle not in open(approvedFilename).read(): - with open(approvedFilename, 'a+') as approvedFile: - approvedFile.write(approveHandle + '\n') + try: + with open(approvedFilename, 'a+') as approvedFile: + approvedFile.write(approveHandle + '\n') + except OSError: + print('EX: unable to append ' + approvedFilename) else: - with open(approvedFilename, 'w+') as approvedFile: - approvedFile.write(approveHandle + '\n') + try: + with open(approvedFilename, 'w+') as approvedFile: + approvedFile.write(approveHandle + '\n') + except OSError: + print('EX: unable to write ' + approvedFilename) def manualApproveFollowRequest(session, baseDir: str, @@ -239,8 +248,11 @@ def manualApproveFollowRequest(session, baseDir: str, else: print('Manual follow accept: first follower accepted for ' + handle + ' is ' + approveHandleFull) - with open(followersFilename, 'w+') as followersFile: - followersFile.write(approveHandleFull + '\n') + try: + 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 # in followers.txt @@ -254,17 +266,15 @@ def manualApproveFollowRequest(session, baseDir: str, if os.path.isfile(followActivityfilename): try: os.remove(followActivityfilename) - except BaseException: + except OSError: print('EX: manualApproveFollowRequest unable to delete ' + followActivityfilename) - pass else: try: os.remove(approveFollowsFilename + '.new') - except BaseException: + except OSError: print('EX: manualApproveFollowRequest unable to delete ' + approveFollowsFilename + '.new') - pass def manualApproveFollowRequestThread(session, baseDir: str, diff --git a/media.py b/media.py index 5b742a5e1..81c101f0d 100644 --- a/media.py +++ b/media.py @@ -126,9 +126,8 @@ def _spoofMetaData(baseDir: str, nickname: str, domain: str, try: with open(decoySeedFilename, 'w+') as fp: fp.write(str(decoySeed)) - except BaseException: + except OSError: print('EX: unable to write ' + decoySeedFilename) - pass if os.path.isfile('/usr/bin/exiftool'): print('Spoofing metadata in ' + outputFilename + ' using exiftool') @@ -168,10 +167,9 @@ def convertImageToLowBandwidth(imageFilename: str) -> None: if os.path.isfile(lowBandwidthFilename): try: os.remove(lowBandwidthFilename) - except BaseException: + except OSError: print('EX: convertImageToLowBandwidth unable to delete ' + lowBandwidthFilename) - pass cmd = \ '/usr/bin/convert +noise Multiplicative ' + \ @@ -191,10 +189,9 @@ def convertImageToLowBandwidth(imageFilename: str) -> None: if os.path.isfile(lowBandwidthFilename): try: os.remove(imageFilename) - except BaseException: + except OSError: print('EX: convertImageToLowBandwidth unable to delete ' + imageFilename) - pass os.rename(lowBandwidthFilename, imageFilename) if os.path.isfile(imageFilename): print('Image converted to low bandwidth ' + imageFilename) @@ -280,9 +277,8 @@ def _updateEtag(mediaFilename: str) -> None: try: with open(mediaFilename, 'rb') as mediaFile: data = mediaFile.read() - except BaseException: + except OSError: print('EX: _updateEtag unable to read ' + str(mediaFilename)) - pass if not data: return @@ -292,10 +288,9 @@ def _updateEtag(mediaFilename: str) -> None: try: with open(mediaFilename + '.etag', 'w+') as etagFile: etagFile.write(etag) - except BaseException: + except OSError: print('EX: _updateEtag unable to write ' + str(mediaFilename) + '.etag') - pass def attachMedia(baseDir: str, httpPrefix: str, diff --git a/newsdaemon.py b/newsdaemon.py index 80c69bbb8..dc5b35e0b 100644 --- a/newsdaemon.py +++ b/newsdaemon.py @@ -57,15 +57,21 @@ def _updateFeedsOutboxIndex(baseDir: str, domain: str, postId: str) -> None: print('WARN: Failed to write entry to feeds posts index ' + indexFilename + ' ' + str(e)) else: - with open(indexFilename, 'w+') as feedsFile: - feedsFile.write(postId + '\n') + try: + 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: """Saves the time when an rss post arrived to a file """ - with open(postFilename + '.arrived', 'w+') as arrivedFile: - arrivedFile.write(arrived) + try: + with open(postFilename + '.arrived', 'w+') as arrivedFile: + arrivedFile.write(arrived) + except OSError: + print('EX: unable to write ' + postFilename + '.arrived') def _removeControlCharacters(content: str) -> str: @@ -483,8 +489,11 @@ def _createNewsMirror(baseDir: str, domain: str, for removePostId in removals: indexContent = \ indexContent.replace(removePostId + '\n', '') - with open(mirrorIndexFilename, 'w+') as indexFile: - indexFile.write(indexContent) + try: + with open(mirrorIndexFilename, 'w+') as indexFile: + indexFile.write(indexContent) + except OSError: + print('EX: unable to write ' + mirrorIndexFilename) mirrorArticleDir = mirrorDir + '/' + postIdNumber if os.path.isdir(mirrorArticleDir): @@ -509,11 +518,17 @@ def _createNewsMirror(baseDir: str, domain: str, # append the post Id number to the index file if os.path.isfile(mirrorIndexFilename): - with open(mirrorIndexFilename, 'a+') as indexFile: - indexFile.write(postIdNumber + '\n') + try: + with open(mirrorIndexFilename, 'a+') as indexFile: + indexFile.write(postIdNumber + '\n') + except OSError: + print('EX: unable to append ' + mirrorIndexFilename) else: - with open(mirrorIndexFilename, 'w+') as indexFile: - indexFile.write(postIdNumber + '\n') + try: + with open(mirrorIndexFilename, 'w+') as indexFile: + indexFile.write(postIdNumber + '\n') + except OSError: + print('EX: unable to write ' + mirrorIndexFilename) return True @@ -727,10 +742,9 @@ def _convertRSStoActivityPub(baseDir: str, httpPrefix: str, if os.path.isfile(filename + '.arrived'): try: os.remove(filename + '.arrived') - except BaseException: + except OSError: print('EX: _convertRSStoActivityPub ' + 'unable to delete ' + filename + '.arrived') - pass # setting the url here links to the activitypub object # stored locally @@ -843,10 +857,9 @@ def runNewswireDaemon(baseDir: str, httpd, if os.path.isfile(refreshFilename): try: os.remove(refreshFilename) - except BaseException: + except OSError: print('EX: runNewswireDaemon unable to delete ' + str(refreshFilename)) - pass break diff --git a/newswire.py b/newswire.py index 60928ae28..b069e8ba5 100644 --- a/newswire.py +++ b/newswire.py @@ -1045,10 +1045,9 @@ def _addBlogsToNewswire(baseDir: str, domain: str, newswire: {}, if os.path.isfile(newswireModerationFilename): try: os.remove(newswireModerationFilename) - except BaseException: + except OSError: print('EX: _addBlogsToNewswire unable to delete ' + str(newswireModerationFilename)) - pass def getDictFromNewswire(session, baseDir: str, domain: str, diff --git a/outbox.py b/outbox.py index f9f42de9f..eab5d2542 100644 --- a/outbox.py +++ b/outbox.py @@ -400,10 +400,9 @@ def postMessageToOutbox(session, translate: {}, if os.path.isfile(citationsFilename): try: os.remove(citationsFilename) - except BaseException: + except OSError: print('EX: postMessageToOutbox unable to delete ' + citationsFilename) - pass # The following activity types get added to the index files indexedActivities = ( diff --git a/person.py b/person.py index ada52381e..8823a10a1 100644 --- a/person.py +++ b/person.py @@ -507,16 +507,22 @@ def _createPersonBase(baseDir: str, nickname: str, domain: str, port: int, if not os.path.isdir(baseDir + privateKeysSubdir): os.mkdir(baseDir + privateKeysSubdir) filename = baseDir + privateKeysSubdir + '/' + handle + '.key' - with open(filename, 'w+') as text_file: - print(privateKeyPem, file=text_file) + try: + with open(filename, 'w+') as text_file: + print(privateKeyPem, file=text_file) + except OSError: + print('EX: unable to save ' + filename) # save the public key publicKeysSubdir = '/keys/public' if not os.path.isdir(baseDir + publicKeysSubdir): os.mkdir(baseDir + publicKeysSubdir) filename = baseDir + publicKeysSubdir + '/' + handle + '.pem' - with open(filename, 'w+') as text_file: - print(publicKeyPem, file=text_file) + try: + with open(filename, 'w+') as text_file: + print(publicKeyPem, file=text_file) + except OSError: + print('EX: unable to save 2 ' + filename) if password: password = removeLineEndings(password) @@ -625,22 +631,31 @@ def createPerson(baseDir: str, nickname: str, domain: str, port: int, if manualFollowerApproval: followDMsFilename = acctDir(baseDir, nickname, domain) + '/.followDMs' - with open(followDMsFilename, 'w+') as fFile: - fFile.write('\n') + try: + with open(followDMsFilename, 'w+') as fFile: + fFile.write('\n') + except OSError: + print('EX: unable to write ' + followDMsFilename) # notify when posts are liked if nickname != 'news': notifyLikesFilename = \ acctDir(baseDir, nickname, domain) + '/.notifyLikes' - with open(notifyLikesFilename, 'w+') as nFile: - nFile.write('\n') + try: + with open(notifyLikesFilename, 'w+') as nFile: + nFile.write('\n') + except OSError: + print('EX: unable to write ' + notifyLikesFilename) # notify when posts have emoji reactions if nickname != 'news': notifyReactionsFilename = \ acctDir(baseDir, nickname, domain) + '/.notifyReactions' - with open(notifyReactionsFilename, 'w+') as nFile: - nFile.write('\n') + try: + with open(notifyReactionsFilename, 'w+') as nFile: + nFile.write('\n') + except OSError: + print('EX: unable to write ' + notifyReactionsFilename) theme = getConfigParam(baseDir, 'theme') if not theme: @@ -1016,10 +1031,14 @@ def reenableAccount(baseDir: str, nickname: str) -> None: lines = [] with open(suspendedFilename, 'r') as f: lines = f.readlines() - with open(suspendedFilename, 'w+') as suspendedFile: - for suspended in lines: - if suspended.strip('\n').strip('\r') != nickname: - suspendedFile.write(suspended) + try: + with open(suspendedFilename, 'w+') as suspendedFile: + for suspended in lines: + 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: @@ -1045,16 +1064,14 @@ def suspendAccount(baseDir: str, nickname: str, domain: str) -> None: if os.path.isfile(saltFilename): try: os.remove(saltFilename) - except BaseException: + except OSError: print('EX: suspendAccount unable to delete ' + saltFilename) - pass tokenFilename = acctDir(baseDir, nickname, domain) + '/.token' if os.path.isfile(tokenFilename): try: os.remove(tokenFilename) - except BaseException: + except OSError: print('EX: suspendAccount unable to delete ' + tokenFilename) - pass suspendedFilename = baseDir + '/accounts/suspended.txt' if os.path.isfile(suspendedFilename): @@ -1063,11 +1080,17 @@ def suspendAccount(baseDir: str, nickname: str, domain: str) -> None: for suspended in lines: if suspended.strip('\n').strip('\r') == nickname: return - with open(suspendedFilename, 'a+') as suspendedFile: - suspendedFile.write(nickname + '\n') + try: + with open(suspendedFilename, 'a+') as suspendedFile: + suspendedFile.write(nickname + '\n') + except OSError: + print('EX: unable to append ' + suspendedFilename) else: - with open(suspendedFilename, 'w+') as suspendedFile: - suspendedFile.write(nickname + '\n') + try: + with open(suspendedFilename, 'w+') as suspendedFile: + suspendedFile.write(nickname + '\n') + except OSError: + print('EX: unable to write ' + suspendedFilename) def canRemovePost(baseDir: str, nickname: str, @@ -1124,10 +1147,13 @@ def _removeTagsForNickname(baseDir: str, nickname: str, lines = [] with open(tagFilename, 'r') as f: lines = f.readlines() - with open(tagFilename, 'w+') as tagFile: - for tagline in lines: - if matchStr not in tagline: - tagFile.write(tagline) + try: + with open(tagFilename, 'w+') as tagFile: + for tagline in lines: + if matchStr not in tagline: + tagFile.write(tagline) + except OSError: + print('EX: unable to write ' + tagFilename) def removeAccount(baseDir: str, nickname: str, @@ -1163,41 +1189,36 @@ def removeAccount(baseDir: str, nickname: str, if os.path.isfile(baseDir + '/accounts/' + handle + '.json'): try: os.remove(baseDir + '/accounts/' + handle + '.json') - except BaseException: + except OSError: print('EX: removeAccount unable to delete ' + baseDir + '/accounts/' + handle + '.json') - pass if os.path.isfile(baseDir + '/wfendpoints/' + handle + '.json'): try: os.remove(baseDir + '/wfendpoints/' + handle + '.json') - except BaseException: + except OSError: print('EX: removeAccount unable to delete ' + baseDir + '/wfendpoints/' + handle + '.json') - pass if os.path.isfile(baseDir + '/keys/private/' + handle + '.key'): try: os.remove(baseDir + '/keys/private/' + handle + '.key') - except BaseException: + except OSError: print('EX: removeAccount unable to delete ' + baseDir + '/keys/private/' + handle + '.key') - pass if os.path.isfile(baseDir + '/keys/public/' + handle + '.pem'): try: os.remove(baseDir + '/keys/public/' + handle + '.pem') - except BaseException: + except OSError: print('EX: removeAccount unable to delete ' + baseDir + '/keys/public/' + handle + '.pem') - pass if os.path.isdir(baseDir + '/sharefiles/' + nickname): shutil.rmtree(baseDir + '/sharefiles/' + nickname, ignore_errors=False, onerror=None) if os.path.isfile(baseDir + '/wfdeactivated/' + handle + '.json'): try: os.remove(baseDir + '/wfdeactivated/' + handle + '.json') - except BaseException: + except OSError: print('EX: removeAccount unable to delete ' + baseDir + '/wfdeactivated/' + handle + '.json') - pass if os.path.isdir(baseDir + '/sharefilesdeactivated/' + nickname): shutil.rmtree(baseDir + '/sharefilesdeactivated/' + nickname, ignore_errors=False, onerror=None) @@ -1297,8 +1318,11 @@ def isPersonSnoozed(baseDir: str, nickname: str, domain: str, with open(snoozedFilename, 'r') as snoozedFile: content = snoozedFile.read().replace(replaceStr, '') if content: - with open(snoozedFilename, 'w+') as writeSnoozedFile: - writeSnoozedFile.write(content) + try: + with open(snoozedFilename, 'w+') as writeSnoozedFile: + writeSnoozedFile.write(content) + except OSError: + print('EX: unable to write ' + snoozedFilename) if snoozeActor + ' ' in open(snoozedFilename).read(): return True @@ -1317,9 +1341,12 @@ def personSnooze(baseDir: str, nickname: str, domain: str, if os.path.isfile(snoozedFilename): if snoozeActor + ' ' in open(snoozedFilename).read(): return - with open(snoozedFilename, 'a+') as snoozedFile: - snoozedFile.write(snoozeActor + ' ' + - str(int(time.time())) + '\n') + try: + with open(snoozedFilename, 'a+') as snoozedFile: + snoozedFile.write(snoozeActor + ' ' + + str(int(time.time())) + '\n') + except OSError: + print('EX: unable to append ' + snoozedFilename) 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: content = snoozedFile.read().replace(replaceStr, '') if content: - with open(snoozedFilename, 'w+') as writeSnoozedFile: - writeSnoozedFile.write(content) + try: + 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, @@ -1362,8 +1392,12 @@ def setPersonNotes(baseDir: str, nickname: str, domain: str, if not os.path.isdir(notesDir): os.mkdir(notesDir) notesFilename = notesDir + '/' + handle + '.txt' - with open(notesFilename, 'w+') as notesFile: - notesFile.write(notes) + try: + with open(notesFilename, 'w+') as notesFile: + notesFile.write(notes) + except OSError: + print('EX: unable to write ' + notesFilename) + return False return True diff --git a/petnames.py b/petnames.py index e0230c1be..22da32888 100644 --- a/petnames.py +++ b/petnames.py @@ -41,17 +41,29 @@ def setPetName(baseDir: str, nickname: str, domain: str, else: newPetnamesStr += entry # save the updated petnames file - with open(petnamesFilename, 'w+') as petnamesFile: - petnamesFile.write(newPetnamesStr) + try: + with open(petnamesFilename, 'w+') as petnamesFile: + petnamesFile.write(newPetnamesStr) + except OSError: + print('EX: unable to save ' + petnamesFilename) + return False return True # entry does not exist in the petnames file - with open(petnamesFilename, 'a+') as petnamesFile: - petnamesFile.write(entry) + try: + with open(petnamesFilename, 'a+') as petnamesFile: + petnamesFile.write(entry) + except OSError: + print('EX: unable to append ' + petnamesFilename) + return False return True # first entry - with open(petnamesFilename, 'w+') as petnamesFile: - petnamesFile.write(entry) + try: + with open(petnamesFilename, 'w+') as petnamesFile: + petnamesFile.write(entry) + except OSError: + print('EX: unable to write ' + petnamesFilename) + return False return True diff --git a/posts.py b/posts.py index 2837a224f..c91471479 100644 --- a/posts.py +++ b/posts.py @@ -1573,8 +1573,11 @@ def pinPost(baseDir: str, nickname: str, domain: str, """ accountDir = acctDir(baseDir, nickname, domain) pinnedFilename = accountDir + '/pinToProfile.txt' - with open(pinnedFilename, 'w+') as pinFile: - pinFile.write(pinnedContent) + try: + 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: @@ -1585,7 +1588,7 @@ def undoPinnedPost(baseDir: str, nickname: str, domain: str) -> None: if os.path.isfile(pinnedFilename): try: os.remove(pinnedFilename) - except BaseException: + except OSError: print('EX: undoPinnedPost unable to delete ' + pinnedFilename) @@ -2122,9 +2125,8 @@ def createReportPost(baseDir: str, try: with open(newReportFile, 'w+') as fp: fp.write(toUrl + '/moderation') - except BaseException: + except OSError: print('EX: createReportPost unable to write ' + newReportFile) - pass return postJsonObject @@ -3966,10 +3968,9 @@ def archivePostsForPerson(httpPrefix: str, nickname: str, domain: str, if os.path.isfile(postCacheFilename): try: os.remove(postCacheFilename) - except BaseException: + except OSError: print('EX: archivePostsForPerson unable to delete ' + postCacheFilename) - pass noOfPosts -= 1 removeCtr += 1 @@ -5135,7 +5136,7 @@ def editedPostFilename(baseDir: str, nickname: str, domain: str, try: with open(actorFilename, 'r') as fp: lastpostId = fp.read() - except BaseException: + except OSError: print('EX: editedPostFilename unable to read ' + actorFilename) return '' if not lastpostId: diff --git a/reaction.py b/reaction.py index 92485804d..834c55a01 100644 --- a/reaction.py +++ b/reaction.py @@ -460,10 +460,9 @@ def updateReactionCollection(recentPostsCache: {}, if os.path.isfile(cachedPostFilename): try: os.remove(cachedPostFilename) - except BaseException: + except OSError: print('EX: updateReactionCollection unable to delete ' + cachedPostFilename) - pass obj = postJsonObject if hasObjectDict(postJsonObject): diff --git a/schedule.py b/schedule.py index 804bc16b2..edef6d7df 100644 --- a/schedule.py +++ b/schedule.py @@ -48,10 +48,9 @@ def _updatePostSchedule(baseDir: str, handle: str, httpd, if os.path.isfile(postFilename): try: os.remove(postFilename) - except BaseException: + except OSError: print('EX: _updatePostSchedule unable to delete ' + str(postFilename)) - pass continue # create the new index file indexLines.append(line) @@ -133,10 +132,9 @@ def _updatePostSchedule(baseDir: str, handle: str, httpd, indexLines.remove(line) try: os.remove(postFilename) - except BaseException: + except OSError: print('EX: _updatePostSchedule unable to delete ' + str(postFilename)) - pass continue # move to the outbox @@ -206,10 +204,9 @@ def removeScheduledPosts(baseDir: str, nickname: str, domain: str) -> None: if os.path.isfile(scheduleIndexFilename): try: os.remove(scheduleIndexFilename) - except BaseException: + except OSError: print('EX: removeScheduledPosts unable to delete ' + scheduleIndexFilename) - pass # remove the scheduled posts scheduledDir = acctDir(baseDir, nickname, domain) + '/scheduled' if not os.path.isdir(scheduledDir): @@ -219,7 +216,6 @@ def removeScheduledPosts(baseDir: str, nickname: str, domain: str) -> None: if os.path.isfile(filePath): try: os.remove(filePath) - except BaseException: + except OSError: print('EX: removeScheduledPosts unable to delete ' + filePath) - pass diff --git a/session.py b/session.py index a1f51f017..4eedae57e 100644 --- a/session.py +++ b/session.py @@ -439,10 +439,9 @@ def downloadImage(session, baseDir: str, url: str, if os.path.isfile(imageFilename): try: os.remove(imageFilename) - except BaseException: + except OSError: print('EX: downloadImage unable to delete ' + imageFilename) - pass else: with open(imageFilename, 'wb') as f: f.write(result.content) diff --git a/shares.py b/shares.py index 9df356597..e9d47c403 100644 --- a/shares.py +++ b/shares.py @@ -148,10 +148,9 @@ def removeSharedItem(baseDir: str, nickname: str, domain: str, if os.path.isfile(itemIDfile + '.' + ext): try: os.remove(itemIDfile + '.' + ext) - except BaseException: + except OSError: print('EX: removeSharedItem unable to delete ' + itemIDfile + '.' + ext) - pass # remove the item itself del sharesJson[itemID] saveJson(sharesJson, sharesFilename) @@ -294,10 +293,9 @@ def _indicateNewShareAvailable(baseDir: str, httpPrefix: str, fp.write(localActor + '/tlshares') else: fp.write(localActor + '/tlwanted') - except BaseException: + except OSError: print('EX: _indicateNewShareAvailable unable to write ' + str(newShareFile)) - pass break @@ -368,10 +366,9 @@ def addShare(baseDir: str, if moveImage: try: os.remove(imageFilename) - except BaseException: + except OSError: print('EX: addShare unable to delete ' + str(imageFilename)) - pass imageUrl = \ httpPrefix + '://' + domainFull + \ '/sharefiles/' + nickname + '/' + itemID + '.' + ext @@ -442,10 +439,9 @@ def _expireSharesForAccount(baseDir: str, nickname: str, domain: str, if os.path.isfile(itemIDfile + '.' + ext): try: os.remove(itemIDfile + '.' + ext) - except BaseException: + except OSError: print('EX: _expireSharesForAccount unable to delete ' + itemIDfile + '.' + ext) - pass saveJson(sharesJson, sharesFilename) diff --git a/tests.py b/tests.py index 9ed6a6506..07f6524a6 100644 --- a/tests.py +++ b/tests.py @@ -3478,7 +3478,7 @@ def _testJsonString() -> None: assert messageStr in encodedStr try: os.remove(filename) - except BaseException: + except OSError: pass @@ -3492,7 +3492,7 @@ def _testSaveLoadJson(): if os.path.isfile(testFilename): try: os.remove(testFilename) - except BaseException: + except OSError: pass assert saveJson(testJson, testFilename) assert os.path.isfile(testFilename) @@ -3504,7 +3504,7 @@ def _testSaveLoadJson(): assert testLoadJson['param2'] == '"Crème brûlée यह एक परीक्षण ह"' try: os.remove(testFilename) - except BaseException: + except OSError: pass diff --git a/theme.py b/theme.py index 481b478d0..273e54667 100644 --- a/theme.py +++ b/theme.py @@ -90,9 +90,8 @@ def exportTheme(baseDir: str, theme: str) -> bool: if os.path.isfile(exportFilename): try: os.remove(exportFilename) - except BaseException: + except OSError: print('EX: exportTheme unable to delete ' + str(exportFilename)) - pass try: make_archive(baseDir + '/exports/' + theme, 'zip', themeDir) except BaseException: @@ -264,10 +263,9 @@ def _removeTheme(baseDir: str): continue try: os.remove(baseDir + '/' + filename) - except BaseException: + except OSError: print('EX: _removeTheme unable to delete ' + baseDir + '/' + filename) - pass def setCSSparam(css: str, param: str, value: str) -> str: @@ -451,10 +449,9 @@ def disableGrayscale(baseDir: str) -> None: if os.path.isfile(grayscaleFilename): try: os.remove(grayscaleFilename) - except BaseException: + except OSError: print('EX: disableGrayscale unable to delete ' + grayscaleFilename) - pass def _setCustomFont(baseDir: str): @@ -596,20 +593,18 @@ def _setTextModeTheme(baseDir: str, name: str) -> None: try: copyfile(textModeLogoFilename, baseDir + '/accounts/logo.txt') - except BaseException: + except OSError: print('EX: _setTextModeTheme unable to copy ' + textModeLogoFilename + ' ' + baseDir + '/accounts/logo.txt') - pass else: try: copyfile(baseDir + '/img/logo.txt', baseDir + '/accounts/logo.txt') - except BaseException: + except OSError: print('EX: _setTextModeTheme unable to copy ' + baseDir + '/img/logo.txt ' + baseDir + '/accounts/logo.txt') - pass # set the text mode banner which appears in browsers such as Lynx textModeBannerFilename = \ @@ -617,19 +612,17 @@ def _setTextModeTheme(baseDir: str, name: str) -> None: if os.path.isfile(baseDir + '/accounts/banner.txt'): try: os.remove(baseDir + '/accounts/banner.txt') - except BaseException: + except OSError: print('EX: _setTextModeTheme unable to delete ' + baseDir + '/accounts/banner.txt') - pass if os.path.isfile(textModeBannerFilename): try: copyfile(textModeBannerFilename, baseDir + '/accounts/banner.txt') - except BaseException: + except OSError: print('EX: _setTextModeTheme unable to copy ' + textModeBannerFilename + ' ' + baseDir + '/accounts/banner.txt') - pass def _setThemeImages(baseDir: str, name: str) -> None: @@ -679,10 +672,9 @@ def _setThemeImages(baseDir: str, name: str) -> None: baseDir + '/accounts/' + backgroundType + '-background.' + ext) continue - except BaseException: + except OSError: print('EX: _setThemeImages unable to copy ' + backgroundImageFilename) - pass # background image was not found # so remove any existing file if os.path.isfile(baseDir + '/accounts/' + @@ -690,38 +682,34 @@ def _setThemeImages(baseDir: str, name: str) -> None: try: os.remove(baseDir + '/accounts/' + backgroundType + '-background.' + ext) - except BaseException: + except OSError: print('EX: _setThemeImages unable to delete ' + baseDir + '/accounts/' + backgroundType + '-background.' + ext) - pass if os.path.isfile(profileImageFilename) and \ os.path.isfile(bannerFilename): try: copyfile(profileImageFilename, accountDir + '/image.png') - except BaseException: + except OSError: print('EX: _setThemeImages unable to copy ' + profileImageFilename) - pass try: copyfile(bannerFilename, accountDir + '/banner.png') - except BaseException: + except OSError: print('EX: _setThemeImages unable to copy ' + bannerFilename) - pass try: if os.path.isfile(searchBannerFilename): copyfile(searchBannerFilename, accountDir + '/search_banner.png') - except BaseException: + except OSError: print('EX: _setThemeImages unable to copy ' + searchBannerFilename) - pass try: if os.path.isfile(leftColImageFilename): @@ -731,14 +719,12 @@ def _setThemeImages(baseDir: str, name: str) -> None: '/left_col_image.png'): try: os.remove(accountDir + '/left_col_image.png') - except BaseException: + except OSError: print('EX: _setThemeImages unable to delete ' + accountDir + '/left_col_image.png') - pass - except BaseException: + except OSError: print('EX: _setThemeImages unable to copy ' + leftColImageFilename) - pass try: if os.path.isfile(rightColImageFilename): @@ -749,14 +735,12 @@ def _setThemeImages(baseDir: str, name: str) -> None: '/right_col_image.png'): try: os.remove(accountDir + '/right_col_image.png') - except BaseException: + except OSError: print('EX: _setThemeImages unable to delete ' + accountDir + '/right_col_image.png') - pass - except BaseException: + except OSError: print('EX: _setThemeImages unable to copy ' + rightColImageFilename) - pass break @@ -779,9 +763,8 @@ def setNewsAvatar(baseDir: str, name: str, if os.path.isfile(filename): try: os.remove(filename) - except BaseException: + except OSError: print('EX: setNewsAvatar unable to delete ' + filename) - pass if os.path.isdir(baseDir + '/cache/avatars'): copyfile(newFilename, filename) accountDir = acctDir(baseDir, nickname, domain) diff --git a/threads.py b/threads.py index c4d3be8a8..f5f4287f4 100644 --- a/threads.py +++ b/threads.py @@ -149,7 +149,6 @@ def removeDormantThreads(baseDir: str, threadsList: [], debug: bool, logFile.write(currTime.strftime("%Y-%m-%dT%H:%M:%SZ") + ',' + str(noOfActiveThreads) + ',' + str(len(threadsList)) + '\n') - except BaseException: + except OSError: print('EX: removeDormantThreads unable to write ' + sendLogFilename) - pass diff --git a/utils.py b/utils.py index 7592bd1c1..077839ef0 100644 --- a/utils.py +++ b/utils.py @@ -625,10 +625,9 @@ def removeAvatarFromCache(baseDir: str, actorStr: str) -> None: if os.path.isfile(avatarFilename): try: os.remove(avatarFilename) - except BaseException: + except OSError: print('EX: removeAvatarFromCache ' + 'unable to delete cached avatar ' + str(avatarFilename)) - pass def saveJson(jsonObject: {}, filename: str) -> bool: @@ -640,7 +639,7 @@ def saveJson(jsonObject: {}, filename: str) -> bool: with open(filename, 'w+') as fp: fp.write(json.dumps(jsonObject)) return True - except BaseException: + except OSError: print('EX: saveJson ' + str(tries)) time.sleep(1) tries += 1 @@ -1287,10 +1286,9 @@ def clearFromPostCaches(baseDir: str, recentPostsCache: {}, if os.path.isfile(postFilename): try: os.remove(postFilename) - except BaseException: + except OSError: print('EX: clearFromPostCaches file not removed ' + str(postFilename)) - pass # if the post is in the recent posts cache then remove it if recentPostsCache.get('index'): if postId in recentPostsCache['index']: @@ -1450,18 +1448,16 @@ def _removeAttachment(baseDir: str, httpPrefix: str, domain: str, if os.path.isfile(mediaFilename): try: os.remove(mediaFilename) - except BaseException: + except OSError: print('EX: _removeAttachment unable to delete media file ' + str(mediaFilename)) - pass etagFilename = mediaFilename + '.etag' if os.path.isfile(etagFilename): try: os.remove(etagFilename) - except BaseException: + except OSError: print('EX: _removeAttachment unable to delete etag file ' + str(etagFilename)) - pass postJson['attachment'] = [] @@ -1528,10 +1524,9 @@ def _deletePostRemoveReplies(baseDir: str, nickname: str, domain: str, # remove the replies file try: os.remove(repliesFilename) - except BaseException: + except OSError: print('EX: _deletePostRemoveReplies unable to delete replies file ' + str(repliesFilename)) - pass 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): try: os.remove(cachedPostFilename) - except BaseException: + except OSError: print('EX: _deleteCachedHtml ' + 'unable to delete cached post file ' + str(cachedPostFilename)) - pass 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 try: os.remove(tagIndexFilename) - except BaseException: + except OSError: print('EX: _deleteHashtagsOnPost unable to delete tag index ' + str(tagIndexFilename)) - pass else: # write the new hashtag index without the given post in it with open(tagIndexFilename, 'w+') as f: @@ -1681,18 +1674,16 @@ def _deleteConversationPost(baseDir: str, nickname: str, domain: str, if os.path.isfile(conversationFilename + '.muted'): try: os.remove(conversationFilename + '.muted') - except BaseException: + except OSError: print('EX: _deleteConversationPost ' + 'unable to remove conversation ' + str(conversationFilename) + '.muted') - pass try: os.remove(conversationFilename) - except BaseException: + except OSError: print('EX: _deleteConversationPost ' + 'unable to remove conversation ' + str(conversationFilename)) - pass def deletePost(baseDir: str, httpPrefix: str, @@ -1709,11 +1700,10 @@ def deletePost(baseDir: str, httpPrefix: str, # finally, remove the post itself try: os.remove(postFilename) - except BaseException: + except OSError: if debug: print('EX: deletePost unable to delete post ' + str(postFilename)) - pass return # don't allow deletion of bookmarked posts @@ -1740,10 +1730,9 @@ def deletePost(baseDir: str, httpPrefix: str, if os.path.isfile(extFilename): try: os.remove(extFilename) - except BaseException: + except OSError: print('EX: deletePost unable to remove ext ' + str(extFilename)) - pass # remove cached html version of the post _deleteCachedHtml(baseDir, nickname, domain, postJsonObject) @@ -1771,10 +1760,9 @@ def deletePost(baseDir: str, httpPrefix: str, # finally, remove the post itself try: os.remove(postFilename) - except BaseException: + except OSError: if debug: print('EX: deletePost unable to delete post ' + str(postFilename)) - pass def isValidLanguage(text: str) -> bool: @@ -2213,11 +2201,10 @@ def undoLikesCollectionEntry(recentPostsCache: {}, if os.path.isfile(cachedPostFilename): try: os.remove(cachedPostFilename) - except BaseException: + except OSError: print('EX: undoLikesCollectionEntry ' + 'unable to delete cached post ' + str(cachedPostFilename)) - pass removePostFromCache(postJsonObject, recentPostsCache) if not postJsonObject.get('type'): @@ -2278,11 +2265,10 @@ def undoReactionCollectionEntry(recentPostsCache: {}, if os.path.isfile(cachedPostFilename): try: os.remove(cachedPostFilename) - except BaseException: + except OSError: print('EX: undoReactionCollectionEntry ' + 'unable to delete cached post ' + str(cachedPostFilename)) - pass removePostFromCache(postJsonObject, recentPostsCache) if not postJsonObject.get('type'): @@ -2344,12 +2330,11 @@ def undoAnnounceCollectionEntry(recentPostsCache: {}, if os.path.isfile(cachedPostFilename): try: os.remove(cachedPostFilename) - except BaseException: + except OSError: if debug: print('EX: undoAnnounceCollectionEntry ' + 'unable to delete cached post ' + str(cachedPostFilename)) - pass removePostFromCache(postJsonObject, recentPostsCache) if not postJsonObject.get('type'): @@ -2412,12 +2397,11 @@ def updateAnnounceCollection(recentPostsCache: {}, if os.path.isfile(cachedPostFilename): try: os.remove(cachedPostFilename) - except BaseException: + except OSError: if debug: print('EX: updateAnnounceCollection ' + 'unable to delete cached post ' + str(cachedPostFilename)) - pass removePostFromCache(postJsonObject, recentPostsCache) if not hasObjectDict(postJsonObject): diff --git a/webapp_calendar.py b/webapp_calendar.py index c20a5f35b..e4fba3cb6 100644 --- a/webapp_calendar.py +++ b/webapp_calendar.py @@ -108,9 +108,8 @@ def _htmlCalendarDay(personCache: {}, cssCache: {}, translate: {}, if os.path.isfile(calendarFile): try: os.remove(calendarFile) - except BaseException: + except OSError: print('EX: _htmlCalendarDay unable to delete ' + calendarFile) - pass cssFilename = baseDir + '/epicyon-calendar.css' if os.path.isfile(baseDir + '/calendar.css'): diff --git a/webapp_minimalbutton.py b/webapp_minimalbutton.py index db31ad964..1ec4997a1 100644 --- a/webapp_minimalbutton.py +++ b/webapp_minimalbutton.py @@ -36,9 +36,11 @@ def setMinimal(baseDir: str, domain: str, nickname: str, if minimal and minimalFileExists: try: os.remove(minimalFilename) - except BaseException: + except OSError: print('EX: setMinimal unable to delete ' + minimalFilename) - pass elif not minimal and not minimalFileExists: - with open(minimalFilename, 'w+') as fp: - fp.write('\n') + try: + with open(minimalFilename, 'w+') as fp: + fp.write('\n') + except OSError: + print('EX: unable to write minimal ' + minimalFilename) diff --git a/webapp_search.py b/webapp_search.py index 6873d345a..49021a3c7 100644 --- a/webapp_search.py +++ b/webapp_search.py @@ -433,20 +433,18 @@ def htmlSearch(cssCache: {}, translate: {}, try: with open(cachedHashtagSwarmFilename, 'r') as fp: swarmStr = fp.read() - except BaseException: + except OSError: print('EX: htmlSearch unable to read cached hashtag swarm ' + cachedHashtagSwarmFilename) - pass if not swarmStr: swarmStr = htmlHashTagSwarm(baseDir, actor, translate) if swarmStr: try: with open(cachedHashtagSwarmFilename, 'w+') as fp: fp.write(swarmStr) - except BaseException: + except OSError: print('EX: htmlSearch unable to save cached hashtag swarm ' + cachedHashtagSwarmFilename) - pass followStr += '
\n' followStr += ' \n' diff --git a/webapp_timeline.py b/webapp_timeline.py index 842fffca4..29ee85fa0 100644 --- a/webapp_timeline.py +++ b/webapp_timeline.py @@ -476,9 +476,8 @@ def htmlTimeline(cssCache: {}, defaultTimeline: str, if boxName == 'dm': try: os.remove(dmFile) - except BaseException: + except OSError: print('EX: htmlTimeline unable to delete ' + dmFile) - pass # should the Replies button be highlighted? newReply = False @@ -488,9 +487,8 @@ def htmlTimeline(cssCache: {}, defaultTimeline: str, if boxName == 'tlreplies': try: os.remove(replyFile) - except BaseException: + except OSError: print('EX: htmlTimeline unable to delete ' + replyFile) - pass # should the Shares button be highlighted? newShare = False @@ -500,9 +498,8 @@ def htmlTimeline(cssCache: {}, defaultTimeline: str, if boxName == 'tlshares': try: os.remove(newShareFile) - except BaseException: + except OSError: print('EX: htmlTimeline unable to delete ' + newShareFile) - pass # should the Wanted button be highlighted? newWanted = False @@ -512,9 +509,8 @@ def htmlTimeline(cssCache: {}, defaultTimeline: str, if boxName == 'tlwanted': try: os.remove(newWantedFile) - except BaseException: + except OSError: print('EX: htmlTimeline unable to delete ' + newWantedFile) - pass # should the Moderation/reports button be highlighted? newReport = False @@ -524,9 +520,8 @@ def htmlTimeline(cssCache: {}, defaultTimeline: str, if boxName == 'moderation': try: os.remove(newReportFile) - except BaseException: + except OSError: print('EX: htmlTimeline unable to delete ' + newReportFile) - pass separatorStr = '' if boxName != 'tlmedia': diff --git a/webapp_utils.py b/webapp_utils.py index 0647d899b..327cb3d8b 100644 --- a/webapp_utils.py +++ b/webapp_utils.py @@ -283,10 +283,9 @@ def updateAvatarImageCache(signingPrivateKeyPem: str, if os.path.isfile(avatarImageFilename): try: os.remove(avatarImageFilename) - except BaseException: + except OSError: print('EX: updateAvatarImageCache unable to delete ' + avatarImageFilename) - pass else: with open(avatarImageFilename, 'wb') as f: f.write(result.content)