diff --git a/acceptreject.py b/acceptreject.py index 2b7a7021f..a58578611 100644 --- a/acceptreject.py +++ b/acceptreject.py @@ -75,7 +75,7 @@ def create_reject(base_dir: str, federation_list: [], http_prefix, object_json, 'Reject') -def _accept_follow(base_dir: str, domain: str, message_json: {}, +def _accept_follow(base_dir: str, message_json: {}, federation_list: [], debug: bool, curr_domain: str, onion_domain: str, i2p_domain: str) -> None: @@ -165,7 +165,7 @@ def _accept_follow(base_dir: str, domain: str, message_json: {}, acct_dir(base_dir, nickname, accepted_domain_full) + '/unfollowed.txt' if os.path.isfile(unfollowed_filename): if followed_nickname + '@' + followed_domain_full in \ - open(unfollowed_filename).read(): + open(unfollowed_filename, encoding='utf-8').read(): if debug: print('DEBUG: follow accept arrived for ' + nickname + '@' + accepted_domain_full + @@ -195,14 +195,8 @@ def _accept_follow(base_dir: str, domain: str, message_json: {}, followed_nickname + '@' + followed_domain) -def receive_accept_reject(session, base_dir: str, - http_prefix: str, domain: str, port: int, - send_threads: [], post_log: [], - cached_webfingers: {}, - person_cache: {}, message_json: {}, - federation_list: [], - debug: bool, - curr_domain: str, +def receive_accept_reject(base_dir: str, domain: str, message_json: {}, + federation_list: [], debug: bool, curr_domain: str, onion_domain: str, i2p_domain: str) -> bool: """Receives an Accept or Reject within the POST section of HTTPServer """ @@ -229,7 +223,7 @@ def receive_accept_reject(session, base_dir: str, ' does not contain a nickname. ' + 'Assuming single user instance.') # receive follow accept - _accept_follow(base_dir, domain, message_json, federation_list, debug, + _accept_follow(base_dir, message_json, federation_list, debug, curr_domain, onion_domain, i2p_domain) if debug: print('DEBUG: Uh, ' + message_json['type'] + ', I guess') diff --git a/announce.py b/announce.py index ef1dacac9..1bc3c538f 100644 --- a/announce.py +++ b/announce.py @@ -331,8 +331,7 @@ def send_announce_via_server(base_dir: str, session, def send_undo_announce_via_server(base_dir: str, session, undo_post_json_object: {}, nickname: str, password: str, - domain: str, port: int, - http_prefix: str, repeat_object_url: str, + domain: str, port: int, http_prefix: str, cached_webfingers: {}, person_cache: {}, debug: bool, project_version: str, signing_priv_key_pem: str) -> {}: @@ -413,8 +412,7 @@ def send_undo_announce_via_server(base_dir: str, session, def outbox_undo_announce(recent_posts_cache: {}, - base_dir: str, http_prefix: str, - nickname: str, domain: str, port: int, + base_dir: str, nickname: str, domain: str, message_json: {}, debug: bool) -> None: """ When an undo announce is received by the outbox from c2s """ diff --git a/auth.py b/auth.py index e137eeab6..e47dd6cbb 100644 --- a/auth.py +++ b/auth.py @@ -143,7 +143,7 @@ def authorize_basic(base_dir: str, path: str, auth_header: str, return False provided_password = plain.split(':')[1] try: - with open(password_file, 'r') as passfile: + with open(password_file, 'r', encoding='utf-8') as passfile: for line in passfile: if not line.startswith(nickname + ':'): continue @@ -177,10 +177,11 @@ def store_basic_credentials(base_dir: str, password_file = base_dir + '/accounts/passwords' store_str = nickname + ':' + _hash_password(password) if os.path.isfile(password_file): - if nickname + ':' in open(password_file).read(): + if nickname + ':' in open(password_file, encoding='utf-8').read(): try: - with open(password_file, 'r') as fin: - with open(password_file + '.new', 'w+') as fout: + with open(password_file, 'r', encoding='utf-8') as fin: + with open(password_file + '.new', 'w+', + encoding='utf-8') as fout: for line in fin: if not line.startswith(nickname + ':'): fout.write(line) @@ -199,14 +200,14 @@ def store_basic_credentials(base_dir: str, else: # append to password file try: - with open(password_file, 'a+') as passfile: + with open(password_file, 'a+', encoding='utf-8') as passfile: passfile.write(store_str + '\n') except OSError: print('EX: unable to append password') return False else: try: - with open(password_file, 'w+') as passfile: + with open(password_file, 'w+', encoding='utf-8') as passfile: passfile.write(store_str + '\n') except OSError: print('EX: unable to create password file') @@ -221,8 +222,9 @@ def remove_password(base_dir: str, nickname: str) -> None: password_file = base_dir + '/accounts/passwords' if os.path.isfile(password_file): try: - with open(password_file, 'r') as fin: - with open(password_file + '.new', 'w+') as fout: + with open(password_file, 'r', encoding='utf-8') as fin: + with open(password_file + '.new', 'w+', + encoding='utf-8') as fout: for line in fin: if not line.startswith(nickname + ':'): fout.write(line) @@ -289,7 +291,7 @@ def record_login_failure(base_dir: str, ip_address: str, curr_time = datetime.datetime.utcnow() curr_time_str = curr_time.strftime("%Y-%m-%d %H:%M:%SZ") try: - with open(failure_log, write_type) as fp_fail: + with open(failure_log, write_type, encoding='utf-8') as fp_fail: # here we use a similar format to an ssh log, so that # systems such as fail2ban can parse it fp_fail.write(curr_time_str + ' ' + diff --git a/blocking.py b/blocking.py index f73bc93d1..9d5c506c9 100644 --- a/blocking.py +++ b/blocking.py @@ -46,11 +46,12 @@ def add_global_block(base_dir: str, # is the handle already blocked? block_handle = block_nickname + '@' + block_domain if os.path.isfile(blocking_filename): - if block_handle in open(blocking_filename).read(): + if block_handle in open(blocking_filename, + encoding='utf-8').read(): return False # block an account handle or domain try: - with open(blocking_filename, 'a+') as block_file: + with open(blocking_filename, 'a+', encoding='utf-8') as block_file: block_file.write(block_handle + '\n') except OSError: print('EX: unable to save blocked handle ' + block_handle) @@ -59,11 +60,12 @@ def add_global_block(base_dir: str, block_hashtag = block_nickname # is the hashtag already blocked? if os.path.isfile(blocking_filename): - if block_hashtag + '\n' in open(blocking_filename).read(): + if block_hashtag + '\n' in \ + open(blocking_filename, encoding='utf-8').read(): return False # block a hashtag try: - with open(blocking_filename, 'a+') as block_file: + with open(blocking_filename, 'a+', encoding='utf-8') as block_file: block_file.write(block_hashtag + '\n') except OSError: print('EX: unable to save blocked hashtag ' + block_hashtag) @@ -83,17 +85,20 @@ def add_block(base_dir: str, nickname: str, domain: str, blocking_filename = acct_dir(base_dir, nickname, domain) + '/blocking.txt' block_handle = block_nickname + '@' + block_domain if os.path.isfile(blocking_filename): - if block_handle + '\n' in open(blocking_filename).read(): + if block_handle + '\n' in open(blocking_filename, + encoding='utf-8').read(): return False # if we are following then unfollow following_filename = \ acct_dir(base_dir, nickname, domain) + '/following.txt' if os.path.isfile(following_filename): - if block_handle + '\n' in open(following_filename).read(): + if block_handle + '\n' in open(following_filename, + encoding='utf-8').read(): following_str = '' try: - with open(following_filename, 'r') as foll_file: + with open(following_filename, 'r', + encoding='utf-8') as foll_file: following_str = foll_file.read() except OSError: print('EX: Unable to read following ' + following_filename) @@ -103,7 +108,8 @@ def add_block(base_dir: str, nickname: str, domain: str, following_str = following_str.replace(block_handle + '\n', '') try: - with open(following_filename, 'w+') as foll_file: + with open(following_filename, 'w+', + encoding='utf-8') as foll_file: foll_file.write(following_str) except OSError: print('EX: Unable to write following ' + following_str) @@ -113,10 +119,12 @@ def add_block(base_dir: str, nickname: str, domain: str, followers_filename = \ acct_dir(base_dir, nickname, domain) + '/followers.txt' if os.path.isfile(followers_filename): - if block_handle + '\n' in open(followers_filename).read(): + if block_handle + '\n' in open(followers_filename, + encoding='utf-8').read(): followers_str = '' try: - with open(followers_filename, 'r') as foll_file: + with open(followers_filename, 'r', + encoding='utf-8') as foll_file: followers_str = foll_file.read() except OSError: print('EX: Unable to read followers ' + followers_filename) @@ -126,14 +134,15 @@ def add_block(base_dir: str, nickname: str, domain: str, followers_str = followers_str.replace(block_handle + '\n', '') try: - with open(followers_filename, 'w+') as foll_file: + with open(followers_filename, 'w+', + encoding='utf-8') as foll_file: foll_file.write(followers_str) except OSError: print('EX: Unable to write followers ' + followers_str) return False try: - with open(blocking_filename, 'a+') as block_file: + with open(blocking_filename, 'a+', encoding='utf-8') as block_file: block_file.write(block_handle + '\n') except OSError: print('EX: unable to append block handle ' + block_handle) @@ -150,10 +159,13 @@ def remove_global_block(base_dir: str, if not unblock_nickname.startswith('#'): unblock_handle = unblock_nickname + '@' + unblock_domain if os.path.isfile(unblocking_filename): - if unblock_handle in open(unblocking_filename).read(): + if unblock_handle in open(unblocking_filename, + encoding='utf-8').read(): try: - with open(unblocking_filename, 'r') as fp_unblock: - with open(unblocking_filename + '.new', 'w+') as fpnew: + with open(unblocking_filename, 'r', + encoding='utf-8') as fp_unblock: + with open(unblocking_filename + '.new', 'w+', + encoding='utf-8') as fpnew: for line in fp_unblock: handle = \ line.replace('\n', '').replace('\r', '') @@ -175,10 +187,13 @@ def remove_global_block(base_dir: str, else: unblock_hashtag = unblock_nickname if os.path.isfile(unblocking_filename): - if unblock_hashtag + '\n' in open(unblocking_filename).read(): + if unblock_hashtag + '\n' in open(unblocking_filename, + encoding='utf-8').read(): try: - with open(unblocking_filename, 'r') as fp_unblock: - with open(unblocking_filename + '.new', 'w+') as fpnew: + with open(unblocking_filename, 'r', + encoding='utf-8') as fp_unblock: + with open(unblocking_filename + '.new', 'w+', + encoding='utf-8') as fpnew: for line in fp_unblock: block_line = \ line.replace('\n', '').replace('\r', '') @@ -209,10 +224,13 @@ def remove_block(base_dir: str, nickname: str, domain: str, acct_dir(base_dir, nickname, domain) + '/blocking.txt' unblock_handle = unblock_nickname + '@' + unblock_domain if os.path.isfile(unblocking_filename): - if unblock_handle in open(unblocking_filename).read(): + if unblock_handle in open(unblocking_filename, + encoding='utf-8').read(): try: - with open(unblocking_filename, 'r') as fp_unblock: - with open(unblocking_filename + '.new', 'w+') as fpnew: + with open(unblocking_filename, 'r', + encoding='utf-8') as fp_unblock: + with open(unblocking_filename + '.new', 'w+', + encoding='utf-8') as fpnew: for line in fp_unblock: handle = line.replace('\n', '').replace('\r', '') if unblock_handle not in line: @@ -244,7 +262,8 @@ def is_blocked_hashtag(base_dir: str, hashtag: str) -> bool: hashtag = hashtag.strip('\n').strip('\r') if not hashtag.startswith('#'): hashtag = '#' + hashtag - if hashtag + '\n' in open(global_blocking_filename).read(): + if hashtag + '\n' in open(global_blocking_filename, + encoding='utf-8').read(): return True return False @@ -263,7 +282,8 @@ def get_domain_blocklist(base_dir: str) -> str: if not os.path.isfile(global_blocking_filename): return blocked_str try: - with open(global_blocking_filename, 'r') as fp_blocked: + with open(global_blocking_filename, 'r', + encoding='utf-8') as fp_blocked: blocked_str += fp_blocked.read() except OSError: print('EX: unable to read ' + global_blocking_filename) @@ -287,7 +307,8 @@ def update_blocked_cache(base_dir: str, if not os.path.isfile(global_blocking_filename): return blocked_cache_last_updated try: - with open(global_blocking_filename, 'r') as fp_blocked: + with open(global_blocking_filename, 'r', + encoding='utf-8') as fp_blocked: blocked_lines = fp_blocked.readlines() # remove newlines for index, _ in enumerate(blocked_lines): @@ -337,7 +358,8 @@ def is_blocked_domain(base_dir: str, domain: str, global_blocking_filename = base_dir + '/accounts/blocking.txt' if os.path.isfile(global_blocking_filename): try: - with open(global_blocking_filename, 'r') as fp_blocked: + with open(global_blocking_filename, 'r', + encoding='utf-8') as fp_blocked: blocked_str = fp_blocked.read() if '*@' + domain + '\n' in blocked_str: return True @@ -351,10 +373,11 @@ def is_blocked_domain(base_dir: str, domain: str, allow_filename = base_dir + '/accounts/allowedinstances.txt' # instance allow list if not short_domain: - if domain not in open(allow_filename).read(): + if domain not in open(allow_filename, encoding='utf-8').read(): return True else: - if short_domain not in open(allow_filename).read(): + if short_domain not in open(allow_filename, + encoding='utf-8').read(): return True return False @@ -384,43 +407,49 @@ def is_blocked(base_dir: str, nickname: str, domain: str, else: global_blocks_filename = base_dir + '/accounts/blocking.txt' if os.path.isfile(global_blocks_filename): - if '*@' + block_domain in open(global_blocks_filename).read(): + if '*@' + block_domain in open(global_blocks_filename, + encoding='utf-8').read(): return True if block_handle: block_str = block_handle + '\n' - if block_str in open(global_blocks_filename).read(): + if block_str in open(global_blocks_filename, + encoding='utf-8').read(): return True else: # instance allow list allow_filename = base_dir + '/accounts/allowedinstances.txt' short_domain = _get_short_domain(block_domain) if not short_domain: - if block_domain + '\n' not in open(allow_filename).read(): + if block_domain + '\n' not in open(allow_filename, + encoding='utf-8').read(): return True else: - if short_domain + '\n' not in open(allow_filename).read(): + if short_domain + '\n' not in open(allow_filename, + encoding='utf-8').read(): return True # account level allow list account_dir = acct_dir(base_dir, nickname, domain) allow_filename = account_dir + '/allowedinstances.txt' if os.path.isfile(allow_filename): - if block_domain + '\n' not in open(allow_filename).read(): + if block_domain + '\n' not in open(allow_filename, + encoding='utf-8').read(): return True # account level block list blocking_filename = account_dir + '/blocking.txt' if os.path.isfile(blocking_filename): - if '*@' + block_domain + '\n' in open(blocking_filename).read(): + if '*@' + block_domain + '\n' in open(blocking_filename, + encoding='utf-8').read(): return True if block_handle: - if block_handle + '\n' in open(blocking_filename).read(): + if block_handle + '\n' in open(blocking_filename, + encoding='utf-8').read(): return True return False -def outbox_block(base_dir: str, http_prefix: str, - nickname: str, domain: str, port: int, +def outbox_block(base_dir: str, nickname: str, domain: str, message_json: {}, debug: bool) -> bool: """ When a block request is received by the outbox from c2s """ @@ -606,7 +635,8 @@ def mute_post(base_dir: str, nickname: str, domain: str, port: int, print('MUTE: cached post not found ' + cached_post_filename) try: - with open(post_filename + '.muted', 'w+') as mute_file: + with open(post_filename + '.muted', 'w+', + encoding='utf-8') as mute_file: mute_file.write('\n') except OSError: print('EX: Failed to save mute file ' + post_filename + '.muted') @@ -926,7 +956,8 @@ def set_broch_mode(base_dir: str, domain_full: str, enabled: bool) -> None: if not os.path.isfile(following_filename): continue try: - with open(following_filename, 'r') as foll_file: + with open(following_filename, 'r', + encoding='utf-8') as foll_file: follow_list = foll_file.readlines() for handle in follow_list: if '@' not in handle: @@ -942,7 +973,8 @@ def set_broch_mode(base_dir: str, domain_full: str, enabled: bool) -> None: # write the allow file try: - with open(allow_filename, 'w+') as allow_file: + with open(allow_filename, 'w+', + encoding='utf-8') as allow_file: allow_file.write(domain_full + '\n') for allowed in allowed_domains: allow_file.write(allowed + '\n') @@ -1083,7 +1115,7 @@ def add_cw_from_lists(post_json_object: {}, cw_lists: {}, translate: {}, post_json_object['object']['sensitive'] = True -def get_cw_list_variable(listName: str) -> str: +def get_cw_list_variable(list_name: str) -> str: """Returns the variable associated with a CW list """ - return 'list' + listName.replace(' ', '').replace("'", '') + return 'list' + list_name.replace(' ', '').replace("'", '') diff --git a/blog.py b/blog.py index 130dd8880..d60e73b69 100644 --- a/blog.py +++ b/blog.py @@ -41,7 +41,7 @@ from cache import get_person_from_cache def _no_of_blog_replies(base_dir: str, http_prefix: str, translate: {}, nickname: str, domain: str, domain_full: str, - post_id: str, depth=0) -> int: + post_id: str, depth: int = 0) -> int: """Returns the number of replies on the post This is recursive, so can handle replies to replies """ @@ -73,7 +73,7 @@ def _no_of_blog_replies(base_dir: str, http_prefix: str, translate: {}, replies = 0 lines = [] try: - with open(post_filename, 'r') as post_file: + with open(post_filename, 'r', encoding='utf-8') as post_file: lines = post_file.readlines() except OSError: print('EX: failed to read blog ' + post_filename) @@ -96,7 +96,7 @@ def _no_of_blog_replies(base_dir: str, http_prefix: str, translate: {}, print('Rewriting ' + post_filename + ' to remove ' + str(len(removals)) + ' entries') try: - with open(post_filename, 'w+') as post_file: + with open(post_filename, 'w+', encoding='utf-8') as post_file: for reply_post_id in lines: reply_post_id = \ reply_post_id.replace('\n', '').replace('\r', '') @@ -111,7 +111,7 @@ def _no_of_blog_replies(base_dir: str, http_prefix: str, translate: {}, def _get_blog_replies(base_dir: str, http_prefix: str, translate: {}, nickname: str, domain: str, domain_full: str, - post_id: str, depth=0) -> str: + post_id: str, depth: int = 0) -> str: """Returns a string containing html blog posts """ if depth > 4: @@ -140,7 +140,8 @@ def _get_blog_replies(base_dir: str, http_prefix: str, translate: {}, post_id.replace('/', '#') + '.html' if os.path.isfile(post_filename): try: - with open(post_filename, 'r') as post_file: + with open(post_filename, 'r', + encoding='utf-8') as post_file: return post_file.read() + '\n' except OSError: print('EX: unable to read blog 3 ' + post_filename) @@ -148,7 +149,7 @@ def _get_blog_replies(base_dir: str, http_prefix: str, translate: {}, lines = [] try: - with open(post_filename, 'r') as post_file: + with open(post_filename, 'r', encoding='utf-8') as post_file: lines = post_file.readlines() except OSError: print('EX: unable to read blog 4 ' + post_filename) @@ -165,7 +166,7 @@ def _get_blog_replies(base_dir: str, http_prefix: str, translate: {}, if not os.path.isfile(post_filename): continue try: - with open(post_filename, 'r') as post_file: + with open(post_filename, 'r', encoding='utf-8') as post_file: replies_str += post_file.read() + '\n' except OSError: print('EX: unable to read blog replies ' + post_filename) @@ -271,7 +272,7 @@ def _html_blog_post_content(debug: bool, session, authorized: bool, person_url = local_actor_url(http_prefix, nickname, domain_full) actor_json = \ - get_person_from_cache(base_dir, person_url, person_cache, False) + get_person_from_cache(base_dir, person_url, person_cache) languages_understood = [] if actor_json: languages_understood = get_actor_languages_list(actor_json) @@ -354,11 +355,8 @@ def _html_blog_post_content(debug: bool, session, authorized: bool, return blog_str -def _html_blog_post_rss2(authorized: bool, - base_dir: str, http_prefix: str, translate: {}, - nickname: str, domain: str, domain_full: str, - post_json_object: {}, - handle: str, restrict_to_domain: bool, +def _html_blog_post_rss2(domain: str, post_json_object: {}, + restrict_to_domain: bool, system_language: str) -> str: """Returns the RSS version 2 feed for a single blog post """ @@ -389,11 +387,8 @@ def _html_blog_post_rss2(authorized: bool, return rss_str -def _html_blog_post_rss3(authorized: bool, - base_dir: str, http_prefix: str, translate: {}, - nickname: str, domain: str, domain_full: str, - post_json_object: {}, - handle: str, restrict_to_domain: bool, +def _html_blog_post_rss3(domain: str, post_json_object: {}, + restrict_to_domain: bool, system_language: str) -> str: """Returns the RSS version 3 feed for a single blog post """ @@ -605,8 +600,7 @@ def html_blog_page(authorized: bool, session, return blog_str + html_footer() -def html_blog_page_rss2(authorized: bool, session, - base_dir: str, http_prefix: str, translate: {}, +def html_blog_page_rss2(base_dir: str, http_prefix: str, translate: {}, nickname: str, domain: str, port: int, no_of_items: int, page_number: int, include_header: bool, system_language: str) -> str: @@ -646,19 +640,14 @@ def html_blog_page_rss2(authorized: bool, session, continue blog_rss2 += \ - _html_blog_post_rss2(authorized, base_dir, - http_prefix, translate, - nickname, domain, - domain_full, item, - None, True, system_language) + _html_blog_post_rss2(domain, item, True, system_language) if include_header: return blog_rss2 + rss2footer() return blog_rss2 -def html_blog_page_rss3(authorized: bool, session, - base_dir: str, http_prefix: str, translate: {}, +def html_blog_page_rss3(base_dir: str, http_prefix: str, nickname: str, domain: str, port: int, no_of_items: int, page_number: int, system_language: str) -> str: @@ -668,8 +657,6 @@ def html_blog_page_rss3(authorized: bool, session, '\n' in nickname or '\r' in nickname: return None - domain_full = get_full_domain(domain, port) - blog_rss3 = '' blogs_index = acct_dir(base_dir, nickname, domain) + '/tlblogs.index' @@ -690,12 +677,7 @@ def html_blog_page_rss3(authorized: bool, session, continue blog_rss3 += \ - _html_blog_post_rss3(authorized, base_dir, - http_prefix, translate, - nickname, domain, - domain_full, item, - None, True, - system_language) + _html_blog_post_rss3(domain, item, True, system_language) return blog_rss3 @@ -760,7 +742,7 @@ def html_blog_view(authorized: bool, domain_full = get_full_domain(domain, port) - for subdir, dirs, files in os.walk(base_dir + '/accounts'): + for _, dirs, _ in os.walk(base_dir + '/accounts'): for acct in dirs: if not is_account_dir(acct): continue @@ -778,9 +760,7 @@ def html_blog_view(authorized: bool, def html_edit_blog(media_instance: bool, translate: {}, - base_dir: str, http_prefix: str, - path: str, - page_number: int, + base_dir: str, path: str, page_number: int, nickname: str, domain: str, post_url: str, system_language: str) -> str: """Edit a blog post after it was created @@ -800,7 +780,8 @@ def html_edit_blog(media_instance: bool, translate: {}, if os.path.isfile(base_dir + '/accounts/newpost.txt'): try: - with open(base_dir + '/accounts/newpost.txt', 'r') as file: + with open(base_dir + '/accounts/newpost.txt', 'r', + encoding='utf-8') as file: edit_blog_text = '
' + file.read() + '
' except OSError: print('EX: unable to read ' + base_dir + '/accounts/newpost.txt') @@ -948,7 +929,8 @@ def path_contains_blog_link(base_dir: str, acct_dir(base_dir, nickname, domain) + '/tlblogs.index' if not os.path.isfile(blog_index_filename): return None, None - if '#' + user_ending2[1] + '.' not in open(blog_index_filename).read(): + if '#' + user_ending2[1] + '.' not in open(blog_index_filename, + encoding='utf-8').read(): return None, None message_id = local_actor_url(http_prefix, nickname, domain_full) + \ '/statuses/' + user_ending2[1] diff --git a/bookmarks.py b/bookmarks.py index 6d8c78d1e..307b544f6 100644 --- a/bookmarks.py +++ b/bookmarks.py @@ -34,7 +34,6 @@ from session import post_json def undo_bookmarks_collection_entry(recent_posts_cache: {}, base_dir: str, post_filename: str, - object_url: str, actor: str, domain: str, debug: bool) -> None: """Undoes a bookmark for a particular actor @@ -72,17 +71,20 @@ def undo_bookmarks_collection_entry(recent_posts_cache: {}, else: bookmark_index = post_filename.strip() bookmark_index = bookmark_index.replace('\n', '').replace('\r', '') - if bookmark_index not in open(bookmarks_index_filename).read(): + if bookmark_index not in open(bookmarks_index_filename, + encoding='utf-8').read(): return index_str = '' try: - with open(bookmarks_index_filename, 'r') as index_file: + with open(bookmarks_index_filename, 'r', + encoding='utf-8') as index_file: index_str = index_file.read().replace(bookmark_index + '\n', '') except OSError: print('EX: unable to read ' + bookmarks_index_filename) if index_str: try: - with open(bookmarks_index_filename, 'w+') as bmi_file: + with open(bookmarks_index_filename, 'w+', + encoding='utf-8') as bmi_file: bmi_file.write(index_str) except OSError: print('EX: unable to write bookmarks index ' + @@ -164,106 +166,108 @@ def update_bookmarks_collection(recent_posts_cache: {}, """Updates the bookmarks collection within a post """ post_json_object = load_json(post_filename) - if post_json_object: - # remove any cached version of this post so that the - # bookmark icon is changed - nickname = get_nickname_from_actor(actor) - if not nickname: - return - cached_post_filename = \ - get_cached_post_filename(base_dir, nickname, - domain, post_json_object) - if cached_post_filename: - if os.path.isfile(cached_post_filename): - try: - os.remove(cached_post_filename) - except OSError: - if debug: - print('EX: update_bookmarks_collection ' + - 'unable to delete cached post ' + - str(cached_post_filename)) - remove_post_from_cache(post_json_object, recent_posts_cache) + if not post_json_object: + return - if not post_json_object.get('object'): - if debug: - print('DEBUG: no object in bookmarked post ' + - str(post_json_object)) - return - if not object_url.endswith('/bookmarks'): - object_url = object_url + '/bookmarks' - # does this post have bookmarks on it from differenent actors? - if not post_json_object['object'].get('bookmarks'): - if debug: - print('DEBUG: Adding initial bookmarks to ' + object_url) - bookmarks_json = { - "@context": "https://www.w3.org/ns/activitystreams", - 'id': object_url, - 'type': 'Collection', - "totalItems": 1, - 'items': [{ - 'type': 'Bookmark', - 'actor': actor - }] - } - post_json_object['object']['bookmarks'] = bookmarks_json - else: - if not post_json_object['object']['bookmarks'].get('items'): - post_json_object['object']['bookmarks']['items'] = [] - bm_items = post_json_object['object']['bookmarks']['items'] - for bookmark_item in bm_items: - if bookmark_item.get('actor'): - if bookmark_item['actor'] == actor: - return - new_bookmark = { + # remove any cached version of this post so that the + # bookmark icon is changed + nickname = get_nickname_from_actor(actor) + if not nickname: + return + cached_post_filename = \ + get_cached_post_filename(base_dir, nickname, + domain, post_json_object) + if cached_post_filename: + if os.path.isfile(cached_post_filename): + try: + os.remove(cached_post_filename) + except OSError: + if debug: + print('EX: update_bookmarks_collection ' + + 'unable to delete cached post ' + + str(cached_post_filename)) + remove_post_from_cache(post_json_object, recent_posts_cache) + + if not post_json_object.get('object'): + if debug: + print('DEBUG: no object in bookmarked post ' + + str(post_json_object)) + return + if not object_url.endswith('/bookmarks'): + object_url = object_url + '/bookmarks' + # does this post have bookmarks on it from differenent actors? + if not post_json_object['object'].get('bookmarks'): + if debug: + print('DEBUG: Adding initial bookmarks to ' + object_url) + bookmarks_json = { + "@context": "https://www.w3.org/ns/activitystreams", + 'id': object_url, + 'type': 'Collection', + "totalItems": 1, + 'items': [{ 'type': 'Bookmark', 'actor': actor - } - nbook = new_bookmark - bm_it = len(post_json_object['object']['bookmarks']['items']) - post_json_object['object']['bookmarks']['items'].append(nbook) - post_json_object['object']['bookmarks']['totalItems'] = bm_it + }] + } + post_json_object['object']['bookmarks'] = bookmarks_json + else: + if not post_json_object['object']['bookmarks'].get('items'): + post_json_object['object']['bookmarks']['items'] = [] + bm_items = post_json_object['object']['bookmarks']['items'] + for bookmark_item in bm_items: + if bookmark_item.get('actor'): + if bookmark_item['actor'] == actor: + return + new_bookmark = { + 'type': 'Bookmark', + 'actor': actor + } + nbook = new_bookmark + bm_it = len(post_json_object['object']['bookmarks']['items']) + post_json_object['object']['bookmarks']['items'].append(nbook) + post_json_object['object']['bookmarks']['totalItems'] = bm_it - if debug: - print('DEBUG: saving post with bookmarks added') - pprint(post_json_object) + if debug: + print('DEBUG: saving post with bookmarks added') + pprint(post_json_object) - save_json(post_json_object, post_filename) + save_json(post_json_object, post_filename) - # prepend to the index - bookmarks_index_filename = \ - acct_dir(base_dir, nickname, domain) + '/bookmarks.index' - bookmark_index = post_filename.split('/')[-1] - if os.path.isfile(bookmarks_index_filename): - if bookmark_index not in open(bookmarks_index_filename).read(): - try: - with open(bookmarks_index_filename, 'r+') as bmi_file: - content = bmi_file.read() - if bookmark_index + '\n' not in content: - bmi_file.seek(0, 0) - bmi_file.write(bookmark_index + '\n' + content) - if debug: - print('DEBUG: bookmark added to index') - except OSError as ex: - print('WARN: Failed to write entry to bookmarks index ' + - bookmarks_index_filename + ' ' + str(ex)) - else: + # prepend to the index + bookmarks_index_filename = \ + acct_dir(base_dir, nickname, domain) + '/bookmarks.index' + bookmark_index = post_filename.split('/')[-1] + if os.path.isfile(bookmarks_index_filename): + if bookmark_index not in open(bookmarks_index_filename, + encoding='utf-8').read(): try: - with open(bookmarks_index_filename, 'w+') as bm_file: - bm_file.write(bookmark_index + '\n') - except OSError: - print('EX: unable to write bookmarks index ' + - bookmarks_index_filename) + with open(bookmarks_index_filename, 'r+', + encoding='utf-8') as bmi_file: + content = bmi_file.read() + if bookmark_index + '\n' not in content: + bmi_file.seek(0, 0) + bmi_file.write(bookmark_index + '\n' + content) + if debug: + print('DEBUG: bookmark added to index') + except OSError as ex: + print('WARN: Failed to write entry to bookmarks index ' + + bookmarks_index_filename + ' ' + str(ex)) + else: + try: + with open(bookmarks_index_filename, 'w+', + encoding='utf-8') as bm_file: + bm_file.write(bookmark_index + '\n') + except OSError: + print('EX: unable to write bookmarks index ' + + bookmarks_index_filename) def bookmark_post(recent_posts_cache: {}, - session, base_dir: str, federation_list: [], + base_dir: str, federation_list: [], nickname: str, domain: str, port: int, - ccList: [], http_prefix: str, - object_url: str, actorBookmarked: str, - client_to_server: bool, - send_threads: [], post_log: [], - person_cache: {}, cached_webfingers: {}, - debug: bool, project_version: str) -> {}: + cc_list: [], http_prefix: str, + object_url: str, actor_bookmarked: str, + debug: bool) -> {}: """Creates a bookmark actor is the person doing the bookmarking 'to' might be a specific person (actor) whose post was bookmarked @@ -280,14 +284,14 @@ def bookmark_post(recent_posts_cache: {}, 'actor': local_actor_url(http_prefix, nickname, full_domain), 'object': object_url } - if ccList: - if len(ccList) > 0: - new_bookmark_json['cc'] = ccList + if cc_list: + if len(cc_list) > 0: + new_bookmark_json['cc'] = cc_list # Extract the domain and nickname from a statuses link bookmarked_post_nickname = None - if actorBookmarked: - ac_bm = actorBookmarked + if actor_bookmarked: + ac_bm = actor_bookmarked bookmarked_post_nickname = get_nickname_from_actor(ac_bm) _, _ = get_domain_from_actor(ac_bm) else: @@ -313,14 +317,11 @@ def bookmark_post(recent_posts_cache: {}, def undo_bookmark_post(recent_posts_cache: {}, - session, base_dir: str, federation_list: [], + base_dir: str, federation_list: [], nickname: str, domain: str, port: int, - ccList: [], http_prefix: str, - object_url: str, actorBookmarked: str, - client_to_server: bool, - send_threads: [], post_log: [], - person_cache: {}, cached_webfingers: {}, - debug: bool, project_version: str) -> {}: + cc_list: [], http_prefix: str, + object_url: str, actor_bookmarked: str, + debug: bool) -> {}: """Removes a bookmark actor is the person doing the bookmarking 'to' might be a specific person (actor) whose post was bookmarked @@ -341,15 +342,15 @@ def undo_bookmark_post(recent_posts_cache: {}, 'object': object_url } } - if ccList: - if len(ccList) > 0: - new_undo_bookmark_json['cc'] = ccList - new_undo_bookmark_json['object']['cc'] = ccList + if cc_list: + if len(cc_list) > 0: + new_undo_bookmark_json['cc'] = cc_list + new_undo_bookmark_json['object']['cc'] = cc_list # Extract the domain and nickname from a statuses link bookmarked_post_nickname = None - if actorBookmarked: - ac_bm = actorBookmarked + if actor_bookmarked: + ac_bm = actor_bookmarked bookmarked_post_nickname = get_nickname_from_actor(ac_bm) _, _ = get_domain_from_actor(ac_bm) else: @@ -364,7 +365,7 @@ def undo_bookmark_post(recent_posts_cache: {}, return None undo_bookmarks_collection_entry(recent_posts_cache, - base_dir, post_filename, object_url, + base_dir, post_filename, new_undo_bookmark_json['actor'], domain, debug) else: @@ -578,9 +579,10 @@ def outbox_bookmark(recent_posts_cache: {}, print('DEBUG: bookmark Add target is not string') return domain_full = get_full_domain(domain, port) - if not message_json['target'].endswith('://' + domain_full + - '/users/' + nickname + - '/tlbookmarks'): + expected_target = \ + http_prefix + '://' + domain_full + \ + '/users/' + nickname + '/tlbookmarks' + if message_json['target'] != expected_target: if debug: print('DEBUG: bookmark Add target invalid ' + message_json['target']) @@ -634,9 +636,10 @@ def outbox_undo_bookmark(recent_posts_cache: {}, print('DEBUG: unbookmark Remove target is not string') return domain_full = get_full_domain(domain, port) - if not message_json['target'].endswith('://' + domain_full + - '/users/' + nickname + - '/tlbookmarks'): + expected_target = \ + http_prefix + '://' + domain_full + \ + '/users/' + nickname + '/tlbookmarks' + if message_json['target'] != expected_target: if debug: print('DEBUG: unbookmark Remove target invalid ' + message_json['target']) diff --git a/cache.py b/cache.py index 4997946e7..e2bbe3c24 100644 --- a/cache.py +++ b/cache.py @@ -77,8 +77,8 @@ def store_person_in_cache(base_dir: str, person_url: str, save_json(person_json, cache_filename) -def get_person_from_cache(base_dir: str, person_url: str, person_cache: {}, - allow_write_to_file: bool) -> {}: +def get_person_from_cache(base_dir: str, person_url: str, + person_cache: {}) -> {}: """Get an actor from the cache """ # if the actor is not in memory then try to load it from file @@ -157,7 +157,7 @@ def get_person_pub_key(base_dir: str, session, person_url: str, person_url.replace(possible_users_path + 'inbox', '/inbox') break person_json = \ - get_person_from_cache(base_dir, person_url, person_cache, True) + get_person_from_cache(base_dir, person_url, person_cache) if not person_json: if debug: print('DEBUG: Obtaining public key for ' + person_url) diff --git a/categories.py b/categories.py index 3a0838a61..1ee488e63 100644 --- a/categories.py +++ b/categories.py @@ -29,7 +29,7 @@ def get_hashtag_category(base_dir: str, hashtag: str) -> str: category_str = None try: - with open(category_filename, 'r') as category_file: + with open(category_filename, 'r', encoding='utf-8') as category_file: category_str = category_file.read() except OSError: print('EX: unable to read category ' + category_filename) @@ -60,7 +60,7 @@ def get_hashtag_categories(base_dir: str, hashtag = catfile.split('.')[0] if len(hashtag) > MAX_TAG_LENGTH: continue - with open(category_filename, 'r') as fp_category: + with open(category_filename, 'r', encoding='utf-8') as fp_category: category_str = fp_category.read() if not category_str: @@ -120,7 +120,8 @@ def update_hashtag_categories(base_dir: str) -> None: # save a list of available categories for quick lookup try: - with open(category_list_filename, 'w+') as fp_category: + with open(category_list_filename, 'w+', + encoding='utf-8') as fp_category: fp_category.write(category_list_str) except OSError: print('EX: unable to write category ' + category_list_filename) @@ -171,7 +172,7 @@ def set_hashtag_category(base_dir: str, hashtag: str, category: str, category_written = False try: - with open(category_filename, 'w+') as fp_category: + with open(category_filename, 'w+', encoding='utf-8') as fp_category: fp_category.write(category) category_written = True except OSError as ex: diff --git a/city.py b/city.py index 4da36991a..512418e5d 100644 --- a/city.py +++ b/city.py @@ -211,7 +211,7 @@ def spoof_geolocation(base_dir: str, "", "", 0) cities = [] try: - with open(locations_filename, 'r') as loc_file: + with open(locations_filename, 'r', encoding='utf-8') as loc_file: cities = loc_file.readlines() except OSError: print('EX: unable to read locations ' + locations_filename) @@ -223,7 +223,7 @@ def spoof_geolocation(base_dir: str, if os.path.isfile(nogo_filename): nogo_list = [] try: - with open(nogo_filename, 'r') as nogo_file: + with open(nogo_filename, 'r', encoding='utf-8') as nogo_file: nogo_list = nogo_file.readlines() except OSError: print('EX: unable to read ' + nogo_filename) @@ -319,7 +319,7 @@ def get_spoofed_city(city: str, base_dir: str, city_filename = acct_dir(base_dir, nickname, domain) + '/city.txt' if os.path.isfile(city_filename): try: - with open(city_filename, 'r') as city_file: + with open(city_filename, 'r', encoding='utf-8') as city_file: city = city_file.read().replace('\n', '') except OSError: print('EX: unable to read ' + city_filename) diff --git a/content.py b/content.py index 5e5c1b769..21bed45d4 100644 --- a/content.py +++ b/content.py @@ -228,7 +228,7 @@ def dangerous_css(filename: str, allow_local_network_access: bool) -> bool: content = None try: - with open(filename, 'r') as css_file: + with open(filename, 'r', encoding='utf-8') as css_file: content = css_file.read().lower() except OSError: print('EX: unable to read css file ' + filename) @@ -281,7 +281,8 @@ def switch_words(base_dir: str, nickname: str, domain: str, content: str, if not os.path.isfile(switch_words_filename): return content try: - with open(switch_words_filename, 'r') as words_file: + with open(switch_words_filename, 'r', + encoding='utf-8') as words_file: rules = words_file.readlines() except OSError: print('EX: unable to read switches ' + switch_words_filename) @@ -376,7 +377,8 @@ def _update_common_emoji(base_dir: str, emoji_content: str) -> None: common_emoji = None if os.path.isfile(common_emoji_filename): try: - with open(common_emoji_filename, 'r') as fp_emoji: + with open(common_emoji_filename, 'r', + encoding='utf-8') as fp_emoji: common_emoji = fp_emoji.readlines() except OSError: print('EX: unable to load common emoji file') @@ -400,7 +402,8 @@ def _update_common_emoji(base_dir: str, emoji_content: str) -> None: new_common_emoji.append(str(1).zfill(16) + ' ' + emoji_content) new_common_emoji.sort(reverse=True) try: - with open(common_emoji_filename, 'w+') as fp_emoji: + with open(common_emoji_filename, 'w+', + encoding='utf-8') as fp_emoji: for line in new_common_emoji: fp_emoji.write(line + '\n') except OSError: @@ -409,7 +412,8 @@ def _update_common_emoji(base_dir: str, emoji_content: str) -> None: else: line = str(1).zfill(16) + ' ' + emoji_content + '\n' try: - with open(common_emoji_filename, 'w+') as fp_emoji: + with open(common_emoji_filename, 'w+', + encoding='utf-8') as fp_emoji: fp_emoji.write(line) except OSError: print('EX: error writing common emoji 2') @@ -929,19 +933,19 @@ def remove_long_words(content: str, max_word_length: int, continue if 'https:' in word_str: continue - elif 'http:' in word_str: + if 'http:' in word_str: continue - elif 'i2p:' in word_str: + if 'i2p:' in word_str: continue - elif 'gnunet:' in word_str: + if 'gnunet:' in word_str: continue - elif 'dat:' in word_str: + if 'dat:' in word_str: continue - elif 'rad:' in word_str: + if 'rad:' in word_str: continue - elif 'hyper:' in word_str: + if 'hyper:' in word_str: continue - elif 'briar:' in word_str: + if 'briar:' in word_str: continue if '<' in word_str: replace_word = word_str.split('<', 1)[0] @@ -973,7 +977,7 @@ def _load_auto_tags(base_dir: str, nickname: str, domain: str) -> []: if not os.path.isfile(filename): return [] try: - with open(filename, 'r') as tags_file: + with open(filename, 'r', encoding='utf-8') as tags_file: return tags_file.readlines() except OSError: print('EX: unable to read auto tags ' + filename) @@ -1052,7 +1056,8 @@ def add_html_tags(base_dir: str, http_prefix: str, if os.path.isfile(following_filename): following = [] try: - with open(following_filename, 'r') as foll_file: + with open(following_filename, 'r', + encoding='utf-8') as foll_file: following = foll_file.readlines() except OSError: print('EX: unable to read ' + following_filename) @@ -1557,7 +1562,7 @@ def import_emoji(base_dir: str, import_filename: str, session) -> None: return emoji_dict = load_json(base_dir + '/emoji/default_emoji.json', 0, 1) added = 0 - with open(import_filename, "r") as fp_emoji: + with open(import_filename, "r", encoding='utf-8') as fp_emoji: lines = fp_emoji.readlines() for line in lines: url = line.split(', ')[0] @@ -1713,7 +1718,8 @@ def remove_script(content: str, log_filename: str, if os.path.isfile(log_filename): write_type = 'w+' try: - with open(log_filename, write_type) as fp_log: + with open(log_filename, write_type, + encoding='utf-8') as fp_log: fp_log.write(log_str) except OSError: print('EX: cannot append to svg script log') diff --git a/conversation.py b/conversation.py index 448d46e7f..8b1e697e6 100644 --- a/conversation.py +++ b/conversation.py @@ -43,15 +43,18 @@ def update_conversation(base_dir: str, nickname: str, domain: str, post_id = remove_id_ending(post_json_object['object']['id']) if not os.path.isfile(conversation_filename): try: - with open(conversation_filename, 'w+') as conv_file: + with open(conversation_filename, 'w+', + encoding='utf-8') as conv_file: conv_file.write(post_id + '\n') return True except OSError: print('EX: update_conversation ' + 'unable to write to ' + conversation_filename) - elif post_id + '\n' not in open(conversation_filename).read(): + elif post_id + '\n' not in open(conversation_filename, + encoding='utf-8').read(): try: - with open(conversation_filename, 'a+') as conv_file: + with open(conversation_filename, 'a+', + encoding='utf-8') as conv_file: conv_file.write(post_id + '\n') return True except OSError: @@ -72,7 +75,8 @@ def mute_conversation(base_dir: str, nickname: str, domain: str, if os.path.isfile(conversation_filename + '.muted'): return try: - with open(conversation_filename + '.muted', 'w+') as conv_file: + with open(conversation_filename + '.muted', 'w+', + encoding='utf-8') as conv_file: conv_file.write('\n') except OSError: print('EX: unable to write mute ' + conversation_filename) diff --git a/crawlers.py b/crawlers.py index fcca4d056..1c9bc72b5 100644 --- a/crawlers.py +++ b/crawlers.py @@ -60,7 +60,7 @@ def load_known_web_bots(base_dir: str) -> []: return [] crawlers_str = None try: - with open(known_bots_filename, 'r') as fp_crawlers: + with open(known_bots_filename, 'r', encoding='utf-8') as fp_crawlers: crawlers_str = fp_crawlers.read() except OSError: print('EX: unable to load web bots from ' + @@ -88,7 +88,7 @@ def _save_known_web_bots(base_dir: str, known_bots: []) -> bool: for crawler in known_bots: known_bots_str += crawler.strip() + '\n' try: - with open(known_bots_filename, 'w+') as fp_crawlers: + with open(known_bots_filename, 'w+', encoding='utf-8') as fp_crawlers: fp_crawlers.write(known_bots_str) except OSError: print("EX: unable to save known web bots to " + diff --git a/daemon.py b/daemon.py index 22132280e..da56b2bec 100644 --- a/daemon.py +++ b/daemon.py @@ -510,7 +510,7 @@ class PubServer(BaseHTTPRequestHandler): if os.path.isfile(votes_filename): # have we already voted on this? - if message_id in open(votes_filename).read(): + if message_id in open(votes_filename, encoding='utf-8').read(): print('Already voted on message ' + message_id) return @@ -580,7 +580,8 @@ class PubServer(BaseHTTPRequestHandler): self.server.debug) # record the vote try: - with open(votes_filename, 'a+') as votes_file: + with open(votes_filename, 'a+', + encoding='utf-8') as votes_file: votes_file.write(message_id + '\n') except OSError: print('EX: unable to write vote ' + @@ -892,7 +893,8 @@ class PubServer(BaseHTTPRequestHandler): etag = None if os.path.isfile(media_filename + '.etag'): try: - with open(media_filename + '.etag', 'r') as efile: + with open(media_filename + '.etag', 'r', + encoding='utf-8') as efile: etag = efile.read() except OSError: print('EX: _set_headers_etag ' + @@ -900,7 +902,8 @@ class PubServer(BaseHTTPRequestHandler): if not etag: etag = md5(data).hexdigest() # nosec try: - with open(media_filename + '.etag', 'w+') as efile: + with open(media_filename + '.etag', 'w+', + encoding='utf-8') as efile: efile.write(etag) except OSError: print('EX: _set_headers_etag ' + @@ -926,7 +929,8 @@ class PubServer(BaseHTTPRequestHandler): # load the etag from file curr_etag = '' try: - with open(media_filename + '.etag', 'r') as efile: + with open(media_filename + '.etag', 'r', + encoding='utf-8') as efile: curr_etag = efile.read() except OSError: print('EX: _etag_exists unable to read ' + @@ -1953,9 +1957,9 @@ class PubServer(BaseHTTPRequestHandler): # to be authorized to use an account you don't own if '/' + nickname + '/' in self.path: return True - elif '/' + nickname + '?' in self.path: + if '/' + nickname + '?' in self.path: return True - elif self.path.endswith('/' + nickname): + if self.path.endswith('/' + nickname): return True if self.server.debug: print('AUTH: nickname ' + nickname + @@ -2128,14 +2132,16 @@ class PubServer(BaseHTTPRequestHandler): salt = create_password(32) if os.path.isfile(salt_filename): try: - with open(salt_filename, 'r') as fp_salt: + with open(salt_filename, 'r', + encoding='utf-8') as fp_salt: salt = fp_salt.read() except OSError as ex: print('EX: Unable to read salt for ' + login_nickname + ' ' + str(ex)) else: try: - with open(salt_filename, 'w+') as fp_salt: + with open(salt_filename, 'w+', + encoding='utf-8') as fp_salt: fp_salt.write(salt) except OSError as ex: print('EX: Unable to save salt for ' + @@ -2149,7 +2155,8 @@ class PubServer(BaseHTTPRequestHandler): base_dir + '/accounts/' + \ login_handle + '/.token' try: - with open(token_filename, 'w+') as fp_tok: + with open(token_filename, 'w+', + encoding='utf-8') as fp_tok: fp_tok.write(token) except OSError as ex: print('EX: Unable to save token for ' + @@ -2960,7 +2967,8 @@ class PubServer(BaseHTTPRequestHandler): feat_filename = features_blocked_filename feat_written = False try: - with open(feat_filename, 'w+') as nofile: + with open(feat_filename, 'w+', + encoding='utf-8') as nofile: nofile.write('\n') feat_written = True except OSError as ex: @@ -3004,7 +3012,8 @@ class PubServer(BaseHTTPRequestHandler): if os.path.isdir(account_dir): nw_filename = newswire_mod_filename try: - with open(nw_filename, 'w+') as modfile: + with open(nw_filename, 'w+', + encoding='utf-8') as modfile: modfile.write('\n') except OSError: print('EX: unable to write ' + nw_filename) @@ -4781,7 +4790,8 @@ class PubServer(BaseHTTPRequestHandler): links_str += '\n' links_str += fields['newColLink'] + '\n' try: - with open(links_filename, 'w+') as linksfile: + with open(links_filename, 'w+', + encoding='utf-8') as linksfile: linksfile.write(links_str) except OSError: print('EX: _links_update unable to write ' + @@ -4791,7 +4801,8 @@ class PubServer(BaseHTTPRequestHandler): # the text area is empty but there is a new link added links_str = fields['newColLink'] + '\n' try: - with open(links_filename, 'w+') as linksfile: + with open(links_filename, 'w+', + encoding='utf-8') as linksfile: linksfile.write(links_str) except OSError: print('EX: _links_update unable to write ' + @@ -4812,7 +4823,8 @@ class PubServer(BaseHTTPRequestHandler): if not dangerous_markup(about_str, allow_local_network_access): try: - with open(about_filename, 'w+') as aboutfile: + with open(about_filename, 'w+', + encoding='utf-8') as aboutfile: aboutfile.write(about_str) except OSError: print('EX: unable to write about ' + @@ -4830,7 +4842,8 @@ class PubServer(BaseHTTPRequestHandler): if not dangerous_markup(tos_str, allow_local_network_access): try: - with open(tos_filename, 'w+') as tosfile: + with open(tos_filename, 'w+', + encoding='utf-8') as tosfile: tosfile.write(tos_str) except OSError: print('EX: unable to write TOS ' + tos_filename) @@ -5024,7 +5037,8 @@ class PubServer(BaseHTTPRequestHandler): newswire_str += '\n' newswire_str += fields['newNewswireFeed'] + '\n' try: - with open(newswire_filename, 'w+') as newsfile: + with open(newswire_filename, 'w+', + encoding='utf-8') as newsfile: newsfile.write(newswire_str) except OSError: print('EX: unable to write ' + newswire_filename) @@ -5033,7 +5047,8 @@ class PubServer(BaseHTTPRequestHandler): # the text area is empty but there is a new feed added newswire_str = fields['newNewswireFeed'] + '\n' try: - with open(newswire_filename, 'w+') as newsfile: + with open(newswire_filename, 'w+', + encoding='utf-8') as newsfile: newsfile.write(newswire_str) except OSError: print('EX: unable to write ' + newswire_filename) @@ -5052,7 +5067,8 @@ class PubServer(BaseHTTPRequestHandler): 'news@' + domain + '/filters.txt' if fields.get('filteredWordsNewswire'): try: - with open(filter_newswire_filename, 'w+') as filterfile: + with open(filter_newswire_filename, 'w+', + encoding='utf-8') as filterfile: filterfile.write(fields['filteredWordsNewswire']) except OSError: print('EX: unable to write ' + filter_newswire_filename) @@ -5069,7 +5085,8 @@ class PubServer(BaseHTTPRequestHandler): base_dir + '/accounts/hashtagrules.txt' if fields.get('hashtagRulesList'): try: - with open(hashtag_rules_filename, 'w+') as rulesfile: + with open(hashtag_rules_filename, 'w+', + encoding='utf-8') as rulesfile: rulesfile.write(fields['hashtagRulesList']) except OSError: print('EX: unable to write ' + hashtag_rules_filename) @@ -5088,7 +5105,8 @@ class PubServer(BaseHTTPRequestHandler): if not newswire_trusted.endswith('\n'): newswire_trusted += '\n' try: - with open(newswire_tusted_filename, 'w+') as trustfile: + with open(newswire_tusted_filename, 'w+', + encoding='utf-8') as trustfile: trustfile.write(newswire_trusted) except OSError: print('EX: unable to write ' + newswire_tusted_filename) @@ -5188,7 +5206,8 @@ class PubServer(BaseHTTPRequestHandler): # save citations dates, so that they can be added when # reloading the newblog screen try: - with open(citations_filename, 'w+') as citfile: + with open(citations_filename, 'w+', + encoding='utf-8') as citfile: citfile.write(citations_str) except OSError: print('EX: unable to write ' + citations_filename) @@ -6315,8 +6334,8 @@ class PubServer(BaseHTTPRequestHandler): # if the list was given as comma separated mods = fields['moderators'].split(',') try: - with open(moderators_file, - 'w+') as modfile: + with open(moderators_file, 'w+', + encoding='utf-8') as modfile: for mod_nick in mods: mod_nick = mod_nick.strip() mod_dir = base_dir + \ @@ -6343,8 +6362,8 @@ class PubServer(BaseHTTPRequestHandler): # nicknames on separate lines mods = fields['moderators'].split('\n') try: - with open(moderators_file, - 'w+') as modfile: + with open(moderators_file, 'w+', + encoding='utf-8') as modfile: for mod_nick in mods: mod_nick = mod_nick.strip() mod_dir = \ @@ -6447,8 +6466,8 @@ class PubServer(BaseHTTPRequestHandler): # if the list was given as comma separated eds = fields['counselors'].split(',') try: - with open(counselors_file, - 'w+') as edfile: + with open(counselors_file, 'w+', + encoding='utf-8') as edfile: for ed_nick in eds: ed_nick = ed_nick.strip() ed_dir = base_dir + \ @@ -6475,8 +6494,8 @@ class PubServer(BaseHTTPRequestHandler): # nicknames on separate lines eds = fields['counselors'].split('\n') try: - with open(counselors_file, - 'w+') as edfile: + with open(counselors_file, 'w+', + encoding='utf-8') as edfile: for ed_nick in eds: ed_nick = ed_nick.strip() ed_dir = \ @@ -6515,7 +6534,8 @@ class PubServer(BaseHTTPRequestHandler): # if the list was given as comma separated eds = fields['artists'].split(',') try: - with open(artists_file, 'w+') as edfil: + with open(artists_file, 'w+', + encoding='utf-8') as edfil: for ed_nick in eds: ed_nick = ed_nick.strip() ed_dir = base_dir + \ @@ -6540,7 +6560,8 @@ class PubServer(BaseHTTPRequestHandler): # nicknames on separate lines eds = fields['artists'].split('\n') try: - with open(artists_file, 'w+') as edfil: + with open(artists_file, 'w+', + encoding='utf-8') as edfil: for ed_nick in eds: ed_nick = ed_nick.strip() ed_dir = \ @@ -6655,7 +6676,8 @@ class PubServer(BaseHTTPRequestHandler): # initial default setting created via # the welcome screen try: - with open(follow_dms_filename, 'w+') as ffile: + with open(follow_dms_filename, 'w+', + encoding='utf-8') as ffile: ffile.write('\n') except OSError: print('EX: unable to write follow DMs ' + @@ -6667,8 +6689,8 @@ class PubServer(BaseHTTPRequestHandler): if fields['followDMs'] == 'on': follow_dms_active = True try: - with open(follow_dms_filename, - 'w+') as ffile: + with open(follow_dms_filename, 'w+', + encoding='utf-8') as ffile: ffile.write('\n') except OSError: print('EX: unable to write follow DMs 2 ' + @@ -6691,8 +6713,8 @@ class PubServer(BaseHTTPRequestHandler): if fields['removeTwitter'] == 'on': remove_twitter_active = True try: - with open(remove_twitter_filename, - 'w+') as rfile: + with open(remove_twitter_filename, 'w+', + encoding='utf-8') as rfile: rfile.write('\n') except OSError: print('EX: unable to write remove twitter ' + @@ -6718,7 +6740,8 @@ class PubServer(BaseHTTPRequestHandler): if fields['hideLikeButton'] == 'on': hide_like_button_active = True try: - with open(hide_like_button_file, 'w+') as rfil: + with open(hide_like_button_file, 'w+', + encoding='utf-8') as rfil: rfil.write('\n') except OSError: print('EX: unable to write hide like ' + @@ -6752,8 +6775,8 @@ class PubServer(BaseHTTPRequestHandler): if fields['hideReactionButton'] == 'on': hide_reaction_button_active = True try: - with open(hide_reaction_button_file, - 'w+') as rfile: + with open(hide_reaction_button_file, 'w+', + encoding='utf-8') as rfile: rfile.write('\n') except OSError: print('EX: unable to write hide reaction ' + @@ -6785,8 +6808,8 @@ class PubServer(BaseHTTPRequestHandler): bold_reading = True self.server.bold_reading[nickname] = True try: - with open(bold_reading_filename, - 'w+') as rfile: + with open(bold_reading_filename, 'w+', + encoding='utf-8') as rfile: rfile.write('\n') except OSError: print('EX: unable to write bold reading ' + @@ -6806,7 +6829,8 @@ class PubServer(BaseHTTPRequestHandler): if on_final_welcome_screen: # default setting from welcome screen try: - with open(notify_likes_filename, 'w+') as rfile: + with open(notify_likes_filename, 'w+', + encoding='utf-8') as rfile: rfile.write('\n') except OSError: print('EX: unable to write notify likes ' + @@ -6819,8 +6843,8 @@ class PubServer(BaseHTTPRequestHandler): not hide_like_button_active: notify_likes_active = True try: - with open(notify_likes_filename, - 'w+') as rfile: + with open(notify_likes_filename, 'w+', + encoding='utf-8') as rfile: rfile.write('\n') except OSError: print('EX: unable to write notify likes ' + @@ -6841,7 +6865,8 @@ class PubServer(BaseHTTPRequestHandler): # default setting from welcome screen notify_react_filename = notify_reactions_filename try: - with open(notify_react_filename, 'w+') as rfile: + with open(notify_react_filename, 'w+', + encoding='utf-8') as rfile: rfile.write('\n') except OSError: print('EX: unable to write notify reactions ' + @@ -6854,8 +6879,8 @@ class PubServer(BaseHTTPRequestHandler): not hide_reaction_button_active: notify_reactions_active = True try: - with open(notify_reactions_filename, - 'w+') as rfile: + with open(notify_reactions_filename, 'w+', + encoding='utf-8') as rfile: rfile.write('\n') except OSError: print('EX: unable to write ' + @@ -6945,7 +6970,8 @@ class PubServer(BaseHTTPRequestHandler): '/filters.txt' if fields.get('filteredWords'): try: - with open(filter_filename, 'w+') as filterfile: + with open(filter_filename, 'w+', + encoding='utf-8') as filterfile: filterfile.write(fields['filteredWords']) except OSError: print('EX: unable to write filter ' + @@ -6965,7 +6991,8 @@ class PubServer(BaseHTTPRequestHandler): '/filters_bio.txt' if fields.get('filteredWordsBio'): try: - with open(filter_bio_filename, 'w+') as filterfile: + with open(filter_bio_filename, 'w+', + encoding='utf-8') as filterfile: filterfile.write(fields['filteredWordsBio']) except OSError: print('EX: unable to write bio filter ' + @@ -6985,7 +7012,8 @@ class PubServer(BaseHTTPRequestHandler): '/replacewords.txt' if fields.get('switchwords'): try: - with open(switch_filename, 'w+') as switchfile: + with open(switch_filename, 'w+', + encoding='utf-8') as switchfile: switchfile.write(fields['switchwords']) except OSError: print('EX: unable to write switches ' + @@ -7005,7 +7033,8 @@ class PubServer(BaseHTTPRequestHandler): '/autotags.txt' if fields.get('autoTags'): try: - with open(auto_tags_filename, 'w+') as autofile: + with open(auto_tags_filename, 'w+', + encoding='utf-8') as autofile: autofile.write(fields['autoTags']) except OSError: print('EX: unable to write auto tags ' + @@ -7025,7 +7054,8 @@ class PubServer(BaseHTTPRequestHandler): '/autocw.txt' if fields.get('autoCW'): try: - with open(auto_cw_filename, 'w+') as auto_cw_file: + with open(auto_cw_filename, 'w+', + encoding='utf-8') as auto_cw_file: auto_cw_file.write(fields['autoCW']) except OSError: print('EX: unable to write auto CW ' + @@ -7045,7 +7075,8 @@ class PubServer(BaseHTTPRequestHandler): '/blocking.txt' if fields.get('blocked'): try: - with open(blocked_filename, 'w+') as blockedfile: + with open(blocked_filename, 'w+', + encoding='utf-8') as blockedfile: blockedfile.write(fields['blocked']) except OSError: print('EX: unable to write blocked accounts ' + @@ -7067,8 +7098,8 @@ class PubServer(BaseHTTPRequestHandler): '/dmAllowedinstances.txt' if fields.get('dmAllowedInstances'): try: - with open(dm_allowed_instances_filename, - 'w+') as afile: + with open(dm_allowed_instances_filename, 'w+', + encoding='utf-8') as afile: afile.write(fields['dmAllowedInstances']) except OSError: print('EX: unable to write allowed DM instances ' + @@ -7090,7 +7121,8 @@ class PubServer(BaseHTTPRequestHandler): if fields.get('allowedInstances'): inst_filename = allowed_instances_filename try: - with open(inst_filename, 'w+') as afile: + with open(inst_filename, 'w+', + encoding='utf-8') as afile: afile.write(fields['allowedInstances']) except OSError: print('EX: unable to write allowed instances ' + @@ -7173,8 +7205,8 @@ class PubServer(BaseHTTPRequestHandler): if fields.get('ptInstances'): self.server.peertube_instances.clear() try: - with open(peertube_instances_file, - 'w+') as afile: + with open(peertube_instances_file, 'w+', + encoding='utf-8') as afile: afile.write(fields['ptInstances']) except OSError: print('EX: unable to write peertube ' + @@ -7205,7 +7237,8 @@ class PubServer(BaseHTTPRequestHandler): '/gitprojects.txt' if fields.get('gitProjects'): try: - with open(git_projects_filename, 'w+') as afile: + with open(git_projects_filename, 'w+', + encoding='utf-8') as afile: afile.write(fields['gitProjects'].lower()) except OSError: print('EX: unable to write git ' + @@ -7643,9 +7676,7 @@ class PubServer(BaseHTTPRequestHandler): return msg = \ - html_blog_page_rss2(authorized, - curr_session, - base_dir, + html_blog_page_rss2(base_dir, http_prefix, self.server.translate, nickname, @@ -7698,9 +7729,7 @@ class PubServer(BaseHTTPRequestHandler): nickname = acct.split('@')[0] domain = acct.split('@')[1] msg += \ - html_blog_page_rss2(authorized, - curr_session, - base_dir, + html_blog_page_rss2(base_dir, http_prefix, self.server.translate, nickname, @@ -7807,8 +7836,7 @@ class PubServer(BaseHTTPRequestHandler): path + ' ' + calling_domain) self._404() - def _get_rss3feed(self, authorized: bool, - calling_domain: str, path: str, + def _get_rss3feed(self, calling_domain: str, path: str, base_dir: str, http_prefix: str, domain: str, port: int, proxy_type: str, getreq_start_time, @@ -7829,10 +7857,7 @@ class PubServer(BaseHTTPRequestHandler): self._404() return msg = \ - html_blog_page_rss3(authorized, - curr_session, - base_dir, http_prefix, - self.server.translate, + html_blog_page_rss3(base_dir, http_prefix, nickname, domain, port, MAX_POSTS_IN_RSS_FEED, 1, system_language) @@ -7910,8 +7935,7 @@ class PubServer(BaseHTTPRequestHandler): actor_json = \ get_person_from_cache(base_dir, options_actor, - self.server.person_cache, - True) + self.server.person_cache) if actor_json: if actor_json.get('movedTo'): moved_to = actor_json['movedTo'] @@ -9966,20 +9990,10 @@ class PubServer(BaseHTTPRequestHandler): local_actor_url(http_prefix, self.post_to_nickname, domain_full) cc_list = [] bookmark_post(self.server.recent_posts_cache, - curr_session, - base_dir, - self.server.federation_list, - self.post_to_nickname, - domain, port, - cc_list, - http_prefix, - bookmark_url, bookmark_actor, False, - self.server.send_threads, - self.server.postLog, - self.server.person_cache, - self.server.cached_webfingers, - self.server.debug, - self.server.project_version) + base_dir, self.server.federation_list, + self.post_to_nickname, domain, port, + cc_list, http_prefix, bookmark_url, bookmark_actor, + self.server.debug) # clear the icon from the cache so that it gets updated if self.server.iconsCache.get('bookmark.png'): del self.server.iconsCache['bookmark.png'] @@ -10122,20 +10136,10 @@ class PubServer(BaseHTTPRequestHandler): local_actor_url(http_prefix, self.post_to_nickname, domain_full) cc_list = [] undo_bookmark_post(self.server.recent_posts_cache, - curr_session, - base_dir, - self.server.federation_list, + base_dir, self.server.federation_list, self.post_to_nickname, - domain, port, - cc_list, - http_prefix, - bookmark_url, undo_actor, False, - self.server.send_threads, - self.server.postLog, - self.server.person_cache, - self.server.cached_webfingers, - debug, - self.server.project_version) + domain, port, cc_list, http_prefix, + bookmark_url, undo_actor, debug) # clear the icon from the cache so that it gets updated if self.server.iconsCache.get('bookmark_inactive.png'): del self.server.iconsCache['bookmark_inactive.png'] @@ -11161,7 +11165,7 @@ class PubServer(BaseHTTPRequestHandler): return True ssml_str = None try: - with open(ssml_filename, 'r') as fp_ssml: + with open(ssml_filename, 'r', encoding='utf-8') as fp_ssml: ssml_str = fp_ssml.read() except OSError: pass @@ -14365,12 +14369,12 @@ class PubServer(BaseHTTPRequestHandler): """ image_extensions = get_image_extensions() for ext in image_extensions: - for bg in ('follow', 'options', 'login', 'welcome'): + for bg_im in ('follow', 'options', 'login', 'welcome'): # follow screen background image - if path.endswith('/' + bg + '-background.' + ext): + if path.endswith('/' + bg_im + '-background.' + ext): bg_filename = \ base_dir + '/accounts/' + \ - bg + '-background.' + ext + bg_im + '-background.' + ext if os.path.isfile(bg_filename): if self._etag_exists(bg_filename): # The file has not changed @@ -15662,8 +15666,7 @@ class PubServer(BaseHTTPRequestHandler): # RSS 3.0 if self.path.startswith('/blog/') and \ self.path.endswith('/rss.txt'): - self._get_rss3feed(authorized, - calling_domain, self.path, + self._get_rss3feed(calling_domain, self.path, self.server.base_dir, self.server.http_prefix, self.server.domain, @@ -17532,13 +17535,13 @@ class PubServer(BaseHTTPRequestHandler): in_reply_to_url = self.path.split('?replyto=')[1] if '?' in in_reply_to_url: mentions_list = in_reply_to_url.split('?') - for m in mentions_list: - if m.startswith('mention='): - reply_handle = m.replace('mention=', '') + for ment in mentions_list: + if ment.startswith('mention='): + reply_handle = ment.replace('mention=', '') if reply_handle not in reply_to_list: reply_to_list.append(reply_handle) - if m.startswith('page='): - reply_page_str = m.replace('page=', '') + if ment.startswith('page='): + reply_page_str = ment.replace('page=', '') if reply_page_str.isdigit(): reply_page_number = int(reply_page_str) # if m.startswith('actor='): @@ -17553,13 +17556,13 @@ class PubServer(BaseHTTPRequestHandler): in_reply_to_url = self.path.split('?replyunlisted=')[1] if '?' in in_reply_to_url: mentions_list = in_reply_to_url.split('?') - for m in mentions_list: - if m.startswith('mention='): - reply_handle = m.replace('mention=', '') + for ment in mentions_list: + if ment.startswith('mention='): + reply_handle = ment.replace('mention=', '') if reply_handle not in reply_to_list: reply_to_list.append(reply_handle) - if m.startswith('page='): - reply_page_str = m.replace('page=', '') + if ment.startswith('page='): + reply_page_str = ment.replace('page=', '') if reply_page_str.isdigit(): reply_page_number = int(reply_page_str) in_reply_to_url = mentions_list[0] @@ -17665,7 +17668,6 @@ class PubServer(BaseHTTPRequestHandler): msg = html_edit_blog(self.server.media_instance, self.server.translate, self.server.base_dir, - self.server.http_prefix, self.path, reply_page_number, nickname, self.server.domain, post_url, @@ -18830,7 +18832,8 @@ class PubServer(BaseHTTPRequestHandler): acct_dir(self.server.base_dir, nickname, self.server.domain) + '/.lastUsed' try: - with open(last_used_filename, 'w+') as lastfile: + with open(last_used_filename, 'w+', + encoding='utf-8') as lastfile: lastfile.write(str(int(time.time()))) except OSError: print('EX: _receive_new_post_process unable to write ' + diff --git a/desktop_client.py b/desktop_client.py index 8bbbbc5ca..9407a72e1 100644 --- a/desktop_client.py +++ b/desktop_client.py @@ -169,12 +169,14 @@ def _mark_post_as_read(actor: str, post_id: str, post_category: str) -> None: read_posts_dir = home_dir + '/.config/epicyon/' + handle read_posts_filename = read_posts_dir + '/' + post_category + '.txt' if os.path.isfile(read_posts_filename): - if post_id in open(read_posts_filename).read(): + if post_id in open(read_posts_filename, + encoding='utf-8').read(): return try: # prepend to read posts file post_id += '\n' - with open(read_posts_filename, 'r+') as read_file: + with open(read_posts_filename, 'r+', + encoding='utf-8') as read_file: content = read_file.read() if post_id not in content: read_file.seek(0, 0) @@ -182,7 +184,7 @@ def _mark_post_as_read(actor: str, post_id: str, post_category: str) -> None: except Exception as ex: print('EX: Failed to mark post as read' + str(ex)) else: - with open(read_posts_filename, 'w+') as read_file: + with open(read_posts_filename, 'w+', encoding='utf-8') as read_file: read_file.write(post_id + '\n') @@ -292,7 +294,7 @@ def _desktop_show_banner() -> None: banner_filename = 'theme/' + banner_theme + '/banner.txt' if not os.path.isfile(banner_filename): return - with open(banner_filename, 'r') as banner_file: + with open(banner_filename, 'r', encoding='utf-8') as banner_file: banner = banner_file.read() if banner: print(banner + '\n') @@ -1325,7 +1327,7 @@ def _desktop_show_follow_requests(follow_requests_json: {}, def _desktop_show_following(following_json: {}, translate: {}, page_number: int, indent: str, - followType='following') -> None: + follow_type: str = 'following') -> None: """Shows a page of accounts followed """ if not isinstance(following_json, dict): @@ -1335,9 +1337,9 @@ def _desktop_show_following(following_json: {}, translate: {}, if not following_json['orderedItems']: return print('') - if followType == 'following': + if follow_type == 'following': print(indent + 'Following page ' + str(page_number)) - elif followType == 'followers': + elif follow_type == 'followers': print(indent + 'Followers page ' + str(page_number)) print('') for item in following_json['orderedItems']: @@ -2198,7 +2200,7 @@ def run_desktop_client(base_dir: str, proxy_type: str, http_prefix: str, post_json_object, nickname, password, domain, port, - http_prefix, post_id, + http_prefix, cached_webfingers, person_cache, True, __version__, diff --git a/epicyon.py b/epicyon.py index 1a3dddbaa..cb5b1786f 100644 --- a/epicyon.py +++ b/epicyon.py @@ -1006,7 +1006,7 @@ def _command_options() -> None: __version__, argb.language, signing_priv_key_pem) try: - with open('socnet.dot', 'w+') as fp_soc: + with open('socnet.dot', 'w+', encoding='utf-8') as fp_soc: fp_soc.write(dot_graph) print('Saved to socnet.dot') except OSError: @@ -1453,7 +1453,8 @@ def _command_options() -> None: approve_follows_filename = accounts_dir + '/followrequests.txt' approve_ctr = 0 if os.path.isfile(approve_follows_filename): - with open(approve_follows_filename, 'r') as approvefile: + with open(approve_follows_filename, 'r', + encoding='utf-8') as approvefile: for approve in approvefile: print(approve.replace('\n', '').replace('\r', '')) approve_ctr += 1 diff --git a/filters.py b/filters.py index 77968a47d..97ca31432 100644 --- a/filters.py +++ b/filters.py @@ -16,10 +16,11 @@ def add_filter(base_dir: str, nickname: str, domain: str, words: str) -> bool: """ filters_filename = acct_dir(base_dir, nickname, domain) + '/filters.txt' if os.path.isfile(filters_filename): - if words in open(filters_filename).read(): + if words in open(filters_filename, encoding='utf-8').read(): return False try: - with open(filters_filename, 'a+') as filters_file: + with open(filters_filename, 'a+', + encoding='utf-8') as filters_file: filters_file.write(words + '\n') except OSError: print('EX: unable to append filters ' + filters_filename) @@ -36,10 +37,10 @@ def add_global_filter(base_dir: str, words: str) -> bool: return False filters_filename = base_dir + '/accounts/filters.txt' if os.path.isfile(filters_filename): - if words in open(filters_filename).read(): + if words in open(filters_filename, encoding='utf-8').read(): return False try: - with open(filters_filename, 'a+') as filters_file: + with open(filters_filename, 'a+', encoding='utf-8') as filters_file: filters_file.write(words + '\n') except OSError: print('EX: unable to append filters ' + filters_filename) @@ -53,12 +54,12 @@ def remove_filter(base_dir: str, nickname: str, domain: str, filters_filename = acct_dir(base_dir, nickname, domain) + '/filters.txt' if not os.path.isfile(filters_filename): return False - if words not in open(filters_filename).read(): + if words not in open(filters_filename, encoding='utf-8').read(): return False new_filters_filename = filters_filename + '.new' try: - with open(filters_filename, 'r') as fp_filt: - with open(new_filters_filename, 'w+') as fpnew: + with open(filters_filename, 'r', encoding='utf-8') as fp_filt: + with open(new_filters_filename, 'w+', encoding='utf-8') as fpnew: for line in fp_filt: line = line.replace('\n', '') if line != words: @@ -78,12 +79,12 @@ def remove_global_filter(base_dir: str, words: str) -> bool: filters_filename = base_dir + '/accounts/filters.txt' if not os.path.isfile(filters_filename): return False - if words not in open(filters_filename).read(): + if words not in open(filters_filename, encoding='utf-8').read(): return False new_filters_filename = filters_filename + '.new' try: - with open(filters_filename, 'r') as fp_filt: - with open(new_filters_filename, 'w+') as fpnew: + with open(filters_filename, 'r', encoding='utf-8') as fp_filt: + with open(new_filters_filename, 'w+', encoding='utf-8') as fpnew: for line in fp_filt: line = line.replace('\n', '') if line != words: @@ -118,7 +119,7 @@ def _is_filtered_base(filename: str, content: str) -> bool: return False try: - with open(filename, 'r') as fp_filt: + with open(filename, 'r', encoding='utf-8') as fp_filt: for line in fp_filt: filter_str = line.replace('\n', '').replace('\r', '') if not filter_str: diff --git a/follow.py b/follow.py index 03e53cd15..a9b482f71 100644 --- a/follow.py +++ b/follow.py @@ -56,7 +56,8 @@ def create_initial_last_seen(base_dir: str, http_prefix: str) -> None: os.mkdir(last_seen_dir) following_handles = [] try: - with open(following_filename, 'r') as fp_foll: + with open(following_filename, 'r', + encoding='utf-8') as fp_foll: following_handles = fp_foll.readlines() except OSError: print('EX: create_initial_last_seen ' + following_filename) @@ -75,7 +76,8 @@ def create_initial_last_seen(base_dir: str, http_prefix: str) -> None: last_seen_dir + '/' + actor.replace('/', '#') + '.txt' if not os.path.isfile(last_seen_filename): try: - with open(last_seen_filename, 'w+') as fp_last: + with open(last_seen_filename, 'w+', + encoding='utf-8') as fp_last: fp_last.write(str(100)) except OSError: print('EX: create_initial_last_seen 2 ' + @@ -92,7 +94,8 @@ def _pre_approved_follower(base_dir: str, account_dir = base_dir + '/accounts/' + handle approved_filename = account_dir + '/approved.txt' if os.path.isfile(approved_filename): - if approve_handle in open(approved_filename).read(): + if approve_handle in open(approved_filename, + encoding='utf-8').read(): return True return False @@ -112,7 +115,8 @@ def _remove_from_follow_base(base_dir: str, ' to remove ' + handle + ' from') return accept_deny_actor = None - if accept_or_deny_handle not in open(approve_follows_filename).read(): + if accept_or_deny_handle not in open(approve_follows_filename, + encoding='utf-8').read(): # is this stored in the file as an actor rather than a handle? accept_deny_nickname = accept_or_deny_handle.split('@')[0] accept_deny_domain = accept_or_deny_handle.split('@')[1] @@ -123,14 +127,17 @@ def _remove_from_follow_base(base_dir: str, for users_name in users_paths: accept_deny_actor = \ '://' + accept_deny_domain + users_name + accept_deny_nickname - if accept_deny_actor in open(approve_follows_filename).read(): + if accept_deny_actor in open(approve_follows_filename, + encoding='utf-8').read(): actor_found = True break if not actor_found: return try: - with open(approve_follows_filename + '.new', 'w+') as approvefilenew: - with open(approve_follows_filename, 'r') as approvefile: + with open(approve_follows_filename + '.new', 'w+', + encoding='utf-8') as approvefilenew: + with open(approve_follows_filename, 'r', + encoding='utf-8') as approvefile: if not accept_deny_actor: for approve_handle in approvefile: accept_deny_handle = accept_or_deny_handle @@ -179,7 +186,7 @@ def is_following_actor(base_dir: str, return False if actor.startswith('@'): actor = actor[1:] - if actor.lower() in open(following_file).read().lower(): + if actor.lower() in open(following_file, encoding='utf-8').read().lower(): return True following_nickname = get_nickname_from_actor(actor) if not following_nickname: @@ -189,7 +196,8 @@ def is_following_actor(base_dir: str, following_handle = \ get_full_domain(following_nickname + '@' + following_domain, following_port) - if following_handle.lower() in open(following_file).read().lower(): + if following_handle.lower() in open(following_file, + encoding='utf-8').read().lower(): return True return False @@ -232,7 +240,7 @@ def get_follower_domains(base_dir: str, nickname: str, domain: str) -> []: lines = [] try: - with open(followers_file, 'r') as fp_foll: + with open(followers_file, 'r', encoding='utf-8') as fp_foll: lines = fp_foll.readlines() except OSError: print('EX: get_follower_domains ' + followers_file) @@ -269,7 +277,7 @@ def is_follower_of_person(base_dir: str, nickname: str, domain: str, followers_str = '' try: - with open(followers_file, 'r') as fp_foll: + with open(followers_file, 'r', encoding='utf-8') as fp_foll: followers_str = fp_foll.read() except OSError: print('EX: is_follower_of_person ' + followers_file) @@ -309,20 +317,21 @@ def unfollow_account(base_dir: str, nickname: str, domain: str, print('DEBUG: follow file ' + filename + ' was not found') return False handle_to_unfollow_lower = handle_to_unfollow.lower() - if handle_to_unfollow_lower not in open(filename).read().lower(): + if handle_to_unfollow_lower not in open(filename, + encoding='utf-8').read().lower(): if debug: print('DEBUG: handle to unfollow ' + handle_to_unfollow + ' is not in ' + filename) return lines = [] try: - with open(filename, 'r') as fp_unfoll: + with open(filename, 'r', encoding='utf-8') as fp_unfoll: lines = fp_unfoll.readlines() except OSError: print('EX: unfollow_account ' + filename) if lines: try: - with open(filename, 'w+') as fp_unfoll: + with open(filename, 'w+', encoding='utf-8') as fp_unfoll: for line in lines: check_handle = line.strip("\n").strip("\r").lower() if check_handle not in (handle_to_unfollow_lower, @@ -336,15 +345,17 @@ def unfollow_account(base_dir: str, nickname: str, domain: str, unfollowed_filename = base_dir + '/accounts/' + handle + '/unfollowed.txt' if os.path.isfile(unfollowed_filename): if handle_to_unfollow_lower not in \ - open(unfollowed_filename).read().lower(): + open(unfollowed_filename, encoding='utf-8').read().lower(): try: - with open(unfollowed_filename, 'a+') as fp_unfoll: + with open(unfollowed_filename, 'a+', + encoding='utf-8') as fp_unfoll: fp_unfoll.write(handle_to_unfollow + '\n') except OSError: print('EX: unable to append ' + unfollowed_filename) else: try: - with open(unfollowed_filename, 'w+') as fp_unfoll: + with open(unfollowed_filename, 'w+', + encoding='utf-8') as fp_unfoll: fp_unfoll.write(handle_to_unfollow + '\n') except OSError: print('EX: unable to write ' + unfollowed_filename) @@ -400,7 +411,7 @@ def _get_no_of_follows(base_dir: str, nickname: str, domain: str, ctr = 0 lines = [] try: - with open(filename, 'r') as fp_foll: + with open(filename, 'r', encoding='utf-8') as fp_foll: lines = fp_foll.readlines() except OSError: print('EX: _get_no_of_follows ' + filename) @@ -517,7 +528,7 @@ def get_following_feed(base_dir: str, domain: str, port: int, path: str, total_ctr = 0 lines = [] try: - with open(filename, 'r') as fp_foll: + with open(filename, 'r', encoding='utf-8') as fp_foll: lines = fp_foll.readlines() except OSError: print('EX: get_following_feed ' + filename) @@ -606,7 +617,8 @@ def no_of_follow_requests(base_dir: str, ctr = 0 lines = [] try: - with open(approve_follows_filename, 'r') as fp_approve: + with open(approve_follows_filename, 'r', + encoding='utf-8') as fp_approve: lines = fp_approve.readlines() except OSError: print('EX: no_of_follow_requests ' + approve_follows_filename) @@ -650,7 +662,8 @@ def store_follow_request(base_dir: str, followers_str = '' try: - with open(followers_filename, 'r') as fp_foll: + with open(followers_filename, 'r', + encoding='utf-8') as fp_foll: followers_str = fp_foll.read() except OSError: print('EX: store_follow_request ' + followers_filename) @@ -675,7 +688,8 @@ def store_follow_request(base_dir: str, # should this follow be denied? deny_follows_filename = accounts_dir + '/followrejects.txt' if os.path.isfile(deny_follows_filename): - if approve_handle in open(deny_follows_filename).read(): + if approve_handle in open(deny_follows_filename, + encoding='utf-8').read(): remove_from_follow_requests(base_dir, nickname_to_follow, domain_to_follow, approve_handle, debug) @@ -694,9 +708,11 @@ def store_follow_request(base_dir: str, approve_handle = '!' + approve_handle if os.path.isfile(approve_follows_filename): - if approve_handle not in open(approve_follows_filename).read(): + if approve_handle not in open(approve_follows_filename, + encoding='utf-8').read(): try: - with open(approve_follows_filename, 'a+') as fp_approve: + with open(approve_follows_filename, 'a+', + encoding='utf-8') as fp_approve: fp_approve.write(approve_handle_stored + '\n') except OSError: print('EX: store_follow_request 2 ' + approve_follows_filename) @@ -706,7 +722,8 @@ def store_follow_request(base_dir: str, ' is already awaiting approval') else: try: - with open(approve_follows_filename, 'w+') as fp_approve: + with open(approve_follows_filename, 'w+', + encoding='utf-8') as fp_approve: fp_approve.write(approve_handle_stored + '\n') except OSError: print('EX: store_follow_request 3 ' + approve_follows_filename) @@ -907,10 +924,12 @@ def send_follow_request(session, base_dir: str, unfollowed_filename = \ acct_dir(base_dir, nickname, domain) + '/unfollowed.txt' if os.path.isfile(unfollowed_filename): - if follow_handle in open(unfollowed_filename).read(): + if follow_handle in open(unfollowed_filename, + encoding='utf-8').read(): unfollowed_file = None try: - with open(unfollowed_filename, 'r') as fp_unfoll: + with open(unfollowed_filename, 'r', + encoding='utf-8') as fp_unfoll: unfollowed_file = fp_unfoll.read() except OSError: print('EX: send_follow_request ' + unfollowed_filename) @@ -918,7 +937,8 @@ def send_follow_request(session, base_dir: str, unfollowed_file = \ unfollowed_file.replace(follow_handle + '\n', '') try: - with open(unfollowed_filename, 'w+') as fp_unfoll: + with open(unfollowed_filename, 'w+', + encoding='utf-8') as fp_unfoll: fp_unfoll.write(unfollowed_file) except OSError: print('EX: unable to write ' + unfollowed_filename) diff --git a/followingCalendar.py b/followingCalendar.py index 9c5f0340b..aae78b974 100644 --- a/followingCalendar.py +++ b/followingCalendar.py @@ -48,17 +48,20 @@ def receiving_calendar_events(base_dir: str, nickname: str, domain: str, # create a new calendar file from the following file following_handles = None try: - with open(following_filename, 'r') as following_file: + with open(following_filename, 'r', + encoding='utf-8') as following_file: following_handles = following_file.read() except OSError: print('EX: receiving_calendar_events ' + following_filename) if following_handles: try: - with open(calendar_filename, 'w+') as fp_cal: + with open(calendar_filename, 'w+', + encoding='utf-8') as fp_cal: fp_cal.write(following_handles) except OSError: print('EX: receiving_calendar_events 2 ' + calendar_filename) - return handle + '\n' in open(calendar_filename).read() + return handle + '\n' in open(calendar_filename, + encoding='utf-8').read() def _receive_calendar_events(base_dir: str, nickname: str, domain: str, @@ -79,7 +82,8 @@ def _receive_calendar_events(base_dir: str, nickname: str, domain: str, handle = following_nickname + '@' + following_domain # check that you are following this handle - if handle + '\n' not in open(following_filename).read(): + if handle + '\n' not in open(following_filename, + encoding='utf-8').read(): print('WARN: ' + handle + ' is not in ' + following_filename) return @@ -92,7 +96,8 @@ def _receive_calendar_events(base_dir: str, nickname: str, domain: str, if os.path.isfile(calendar_filename): print('Calendar file exists') try: - with open(calendar_filename, 'r') as calendar_file: + with open(calendar_filename, 'r', + encoding='utf-8') as calendar_file: following_handles = calendar_file.read() except OSError: print('EX: _receive_calendar_events ' + calendar_filename) @@ -101,13 +106,15 @@ def _receive_calendar_events(base_dir: str, nickname: str, domain: str, print('Creating calendar file ' + calendar_filename) following_handles = '' try: - with open(following_filename, 'r') as following_file: + with open(following_filename, 'r', + encoding='utf-8') as following_file: following_handles = following_file.read() except OSError: print('EX: _receive_calendar_events 2 ' + calendar_filename) if add: try: - with open(calendar_filename, 'w+') as fp_cal: + with open(calendar_filename, 'w+', + encoding='utf-8') as fp_cal: fp_cal.write(following_handles + handle + '\n') except OSError: print('EX: unable to write ' + calendar_filename) @@ -121,7 +128,8 @@ def _receive_calendar_events(base_dir: str, nickname: str, domain: str, # remove from calendar file following_handles = following_handles.replace(handle + '\n', '') try: - with open(calendar_filename, 'w+') as fp_cal: + with open(calendar_filename, 'w+', + encoding='utf-8') as fp_cal: fp_cal.write(following_handles) except OSError: print('EX: _receive_calendar_events 3 ' + calendar_filename) @@ -132,7 +140,8 @@ def _receive_calendar_events(base_dir: str, nickname: str, domain: str, # append to the list of handles following_handles += handle + '\n' try: - with open(calendar_filename, 'w+') as fp_cal: + with open(calendar_filename, 'w+', + encoding='utf-8') as fp_cal: fp_cal.write(following_handles) except OSError: print('EX: _receive_calendar_events 4 ' + calendar_filename) diff --git a/git.py b/git.py index f374fb3db..e0d51faa4 100644 --- a/git.py +++ b/git.py @@ -38,7 +38,7 @@ def _get_git_project_name(base_dir: str, nickname: str, domain: str, return None subject_line_words = subject.lower().split(' ') for word in subject_line_words: - if word in open(git_projects_filename).read(): + if word in open(git_projects_filename, encoding='utf-8').read(): return word return None @@ -208,11 +208,12 @@ def receive_git_patch(base_dir: str, nickname: str, domain: str, _git_add_from_handle(patch_str, '@' + from_nickname + '@' + from_domain) try: - with open(patch_filename, 'w+') as patch_file: + with open(patch_filename, 'w+', encoding='utf-8') as patch_file: patch_file.write(patch_str) patch_notify_filename = \ acct_dir(base_dir, nickname, domain) + '/.newPatchContent' - with open(patch_notify_filename, 'w+') as patch_file: + with open(patch_notify_filename, 'w+', + encoding='utf-8') as patch_file: patch_file.write(patch_str) return True except OSError as ex: diff --git a/happening.py b/happening.py index b5b0979d2..49df1a9d1 100644 --- a/happening.py +++ b/happening.py @@ -70,12 +70,15 @@ def _remove_event_from_timeline(event_id: str, tl_events_filename: str) -> None: """Removes the given event Id from the timeline """ - if event_id + '\n' not in open(tl_events_filename).read(): + if event_id + '\n' not in open(tl_events_filename, + encoding='utf-8').read(): return - with open(tl_events_filename, 'r') as fp_tl: + with open(tl_events_filename, 'r', + encoding='utf-8') as fp_tl: events_timeline = fp_tl.read().replace(event_id + '\n', '') try: - with open(tl_events_filename, 'w+') as fp2: + with open(tl_events_filename, 'w+', + encoding='utf-8') as fp2: fp2.write(events_timeline) except OSError: print('EX: ERROR: unable to save events timeline') @@ -135,7 +138,8 @@ def save_event_post(base_dir: str, handle: str, post_id: str, if os.path.isfile(tl_events_filename): _remove_event_from_timeline(event_id, tl_events_filename) try: - with open(tl_events_filename, 'r+') as tl_events_file: + with open(tl_events_filename, 'r+', + encoding='utf-8') as tl_events_file: content = tl_events_file.read() if event_id + '\n' not in content: tl_events_file.seek(0, 0) @@ -146,7 +150,8 @@ def save_event_post(base_dir: str, handle: str, post_id: str, return False else: try: - with open(tl_events_filename, 'w+') as tl_events_file: + with open(tl_events_filename, 'w+', + encoding='utf-8') as tl_events_file: tl_events_file.write(event_id + '\n') except OSError: print('EX: unable to write ' + tl_events_filename) @@ -161,13 +166,14 @@ def save_event_post(base_dir: str, handle: str, post_id: str, # Does this event post already exist within the calendar month? if os.path.isfile(calendar_filename): - if post_id in open(calendar_filename).read(): + if post_id in open(calendar_filename, + encoding='utf-8').read(): # Event post already exists return False # append the post Id to the file for the calendar month try: - with open(calendar_filename, 'a+') as calendar_file: + with open(calendar_filename, 'a+', encoding='utf-8') as calendar_file: calendar_file.write(post_id + '\n') except OSError: print('EX: unable to append ' + calendar_filename) @@ -179,7 +185,7 @@ def save_event_post(base_dir: str, handle: str, post_id: str, '/calendar?year=' + str(event_year) + '?month=' + \ str(event_month_number) + '?day=' + str(event_day_of_month) try: - with open(cal_notify_filename, 'w+') as cal_file: + with open(cal_notify_filename, 'w+', encoding='utf-8') as cal_file: cal_file.write(notify_str) except OSError: print('EX: unable to write ' + cal_notify_filename) @@ -255,7 +261,7 @@ def get_todays_events(base_dir: str, nickname: str, domain: str, calendar_post_ids = [] recreate_events_file = False - with open(calendar_filename, 'r') as events_file: + with open(calendar_filename, 'r', encoding='utf-8') as events_file: for post_id in events_file: post_id = post_id.replace('\n', '').replace('\r', '') post_filename = locate_post(base_dir, nickname, domain, post_id) @@ -321,7 +327,8 @@ def get_todays_events(base_dir: str, nickname: str, domain: str, # if some posts have been deleted then regenerate the calendar file if recreate_events_file: try: - with open(calendar_filename, 'w+') as calendar_file: + with open(calendar_filename, 'w+', + encoding='utf-8') as calendar_file: for post_id in calendar_post_ids: calendar_file.write(post_id + '\n') except OSError: @@ -553,7 +560,7 @@ def day_events_check(base_dir: str, nickname: str, domain: str, return False events_exist = False - with open(calendar_filename, 'r') as events_file: + with open(calendar_filename, 'r', encoding='utf-8') as events_file: for post_id in events_file: post_id = post_id.replace('\n', '').replace('\r', '') post_filename = locate_post(base_dir, nickname, domain, post_id) @@ -649,7 +656,8 @@ def get_this_weeks_events(base_dir: str, nickname: str, domain: str) -> {}: # if some posts have been deleted then regenerate the calendar file if recreate_events_file: try: - with open(calendar_filename, 'w+') as calendar_file: + with open(calendar_filename, 'w+', + encoding='utf-8') as calendar_file: for post_id in calendar_post_ids: calendar_file.write(post_id + '\n') except OSError: @@ -675,7 +683,7 @@ def get_calendar_events(base_dir: str, nickname: str, domain: str, calendar_post_ids = [] recreate_events_file = False - with open(calendar_filename, 'r') as events_file: + with open(calendar_filename, 'r', encoding='utf-8') as events_file: for post_id in events_file: post_id = post_id.replace('\n', '').replace('\r', '') post_filename = locate_post(base_dir, nickname, domain, post_id) @@ -730,7 +738,8 @@ def get_calendar_events(base_dir: str, nickname: str, domain: str, # if some posts have been deleted then regenerate the calendar file if recreate_events_file: try: - with open(calendar_filename, 'w+') as calendar_file: + with open(calendar_filename, 'w+', + encoding='utf-8') as calendar_file: for post_id in calendar_post_ids: calendar_file.write(post_id + '\n') except OSError: @@ -751,15 +760,15 @@ def remove_calendar_event(base_dir: str, nickname: str, domain: str, return if '/' in message_id: message_id = message_id.replace('/', '#') - if message_id not in open(calendar_filename).read(): + if message_id not in open(calendar_filename, encoding='utf-8').read(): return lines = None - with open(calendar_filename, 'r') as fp_cal: + with open(calendar_filename, 'r', encoding='utf-8') as fp_cal: lines = fp_cal.readlines() if not lines: return try: - with open(calendar_filename, 'w+') as fp_cal: + with open(calendar_filename, 'w+', encoding='utf-8') as fp_cal: for line in lines: if message_id not in line: fp_cal.write(line) diff --git a/inbox.py b/inbox.py index 1ed30a05f..07b53c5f2 100644 --- a/inbox.py +++ b/inbox.py @@ -245,7 +245,7 @@ def _store_last_post_id(base_dir: str, nickname: str, domain: str, os.mkdir(lastpost_dir) actor_filename = lastpost_dir + '/' + actor.replace('/', '#') try: - with open(actor_filename, 'w+') as fp_actor: + with open(actor_filename, 'w+', encoding='utf-8') as fp_actor: fp_actor.write(post_id) except OSError: print('EX: Unable to write last post id to ' + actor_filename) @@ -287,7 +287,8 @@ def _update_cached_hashtag_swarm(base_dir: str, nickname: str, domain: str, new_swarm_str = html_hash_tag_swarm(base_dir, actor, translate) if new_swarm_str: try: - with open(cached_hashtag_swarm_filename, 'w+') as fp_swarm: + with open(cached_hashtag_swarm_filename, 'w+', + encoding='utf-8') as fp_swarm: fp_swarm.write(new_swarm_str) return True except OSError: @@ -343,7 +344,7 @@ def store_hash_tags(base_dir: str, nickname: str, domain: str, hashtag_added = False if not os.path.isfile(tags_filename): try: - with open(tags_filename, 'w+') as tags_file: + with open(tags_filename, 'w+', encoding='utf-8') as tags_file: tags_file.write(tag_line) hashtag_added = True except OSError: @@ -351,14 +352,15 @@ def store_hash_tags(base_dir: str, nickname: str, domain: str, else: content = '' try: - with open(tags_filename, 'r') as tags_file: + with open(tags_filename, 'r', encoding='utf-8') as tags_file: content = tags_file.read() except OSError: pass if post_url not in content: content = tag_line + content try: - with open(tags_filename, 'w+') as tags_file: + with open(tags_filename, 'w+', + encoding='utf-8') as tags_file: tags_file.write(content) hashtag_added = True except OSError as ex: @@ -446,7 +448,7 @@ def valid_inbox(base_dir: str, nickname: str, domain: str) -> bool: if not os.path.isfile(filename): print('filename: ' + filename) return False - if 'postNickname' in open(filename).read(): + if 'postNickname' in open(filename, encoding='utf-8').read(): print('queue file incorrectly saved to ' + filename) return False break @@ -2056,7 +2058,6 @@ def _receive_undo_bookmark(recent_posts_cache: {}, undo_bookmarks_collection_entry(recent_posts_cache, base_dir, post_filename, - message_json['object']['url'], message_json['actor'], domain, debug) # regenerate the html bookmarked_post_json = load_json(post_filename, 0, 1) @@ -2384,7 +2385,8 @@ def _receive_announce(recent_posts_cache: {}, theme_name, system_language, 'inbox') try: - with open(post_filename + '.tts', 'w+') as ttsfile: + with open(post_filename + '.tts', 'w+', + encoding='utf-8') as ttsfile: ttsfile.write('\n') except OSError: print('EX: unable to write recent post ' + @@ -2551,18 +2553,22 @@ def populate_replies(base_dir: str, http_prefix: str, domain: str, post_replies_filename = post_filename.replace('.json', '.replies') message_id = remove_id_ending(message_json['id']) if os.path.isfile(post_replies_filename): - num_lines = sum(1 for line in open(post_replies_filename)) + num_lines = sum(1 for line in open(post_replies_filename, + encoding='utf-8')) if num_lines > max_replies: return False - if message_id not in open(post_replies_filename).read(): + if message_id not in open(post_replies_filename, + encoding='utf-8').read(): try: - with open(post_replies_filename, 'a+') as replies_file: + with open(post_replies_filename, 'a+', + encoding='utf-8') as replies_file: replies_file.write(message_id + '\n') except OSError: print('EX: unable to append ' + post_replies_filename) else: try: - with open(post_replies_filename, 'w+') as replies_file: + with open(post_replies_filename, 'w+', + encoding='utf-8') as replies_file: replies_file.write(message_id + '\n') except OSError: print('EX: unable to write ' + post_replies_filename) @@ -2775,7 +2781,7 @@ def _dm_notify(base_dir: str, handle: str, url: str) -> None: dm_file = account_dir + '/.newDM' if not os.path.isfile(dm_file): try: - with open(dm_file, 'w+') as fp_dm: + with open(dm_file, 'w+', encoding='utf-8') as fp_dm: fp_dm.write(url) except OSError: print('EX: unable to write ' + dm_file) @@ -2886,19 +2892,19 @@ def _like_notify(base_dir: str, domain: str, onion_domain: str, # was there a previous like notification? if os.path.isfile(prev_like_file): # is it the same as the current notification ? - with open(prev_like_file, 'r') as fp_like: + with open(prev_like_file, 'r', encoding='utf-8') as fp_like: prev_like_str = fp_like.read() if prev_like_str == like_str: return try: - with open(prev_like_file, 'w+') as fp_like: + with open(prev_like_file, 'w+', encoding='utf-8') as fp_like: fp_like.write(like_str) except OSError: print('EX: ERROR: unable to save previous like notification ' + prev_like_file) try: - with open(like_file, 'w+') as fp_like: + with open(like_file, 'w+', encoding='utf-8') as fp_like: fp_like.write(like_str) except OSError: print('EX: ERROR: unable to write like notification file ' + @@ -2931,7 +2937,7 @@ def _reaction_notify(base_dir: str, domain: str, onion_domain: str, reaction_file = account_dir + '/.newReaction' if os.path.isfile(reaction_file): - if '##sent##' not in open(reaction_file).read(): + if '##sent##' not in open(reaction_file, encoding='utf-8').read(): return reaction_nickname = get_nickname_from_actor(actor) @@ -2950,19 +2956,19 @@ def _reaction_notify(base_dir: str, domain: str, onion_domain: str, # was there a previous reaction notification? if os.path.isfile(prev_reaction_file): # is it the same as the current notification ? - with open(prev_reaction_file, 'r') as fp_react: + with open(prev_reaction_file, 'r', encoding='utf-8') as fp_react: prev_reaction_str = fp_react.read() if prev_reaction_str == reaction_str: return try: - with open(prev_reaction_file, 'w+') as fp_react: + with open(prev_reaction_file, 'w+', encoding='utf-8') as fp_react: fp_react.write(reaction_str) except OSError: print('EX: ERROR: unable to save previous reaction notification ' + prev_reaction_file) try: - with open(reaction_file, 'w+') as fp_react: + with open(reaction_file, 'w+', encoding='utf-8') as fp_react: fp_react.write(reaction_str) except OSError: print('EX: ERROR: unable to write reaction notification file ' + @@ -2980,12 +2986,12 @@ def _notify_post_arrival(base_dir: str, handle: str, url: str) -> None: notify_file = account_dir + '/.newNotifiedPost' if os.path.isfile(notify_file): # check that the same notification is not repeatedly sent - with open(notify_file, 'r') as fp_notify: + with open(notify_file, 'r', encoding='utf-8') as fp_notify: existing_notification_message = fp_notify.read() if url in existing_notification_message: return try: - with open(notify_file, 'w+') as fp_notify: + with open(notify_file, 'w+', encoding='utf-8') as fp_notify: fp_notify.write(url) except OSError: print('EX: unable to write ' + notify_file) @@ -3000,7 +3006,7 @@ def _reply_notify(base_dir: str, handle: str, url: str) -> None: reply_file = account_dir + '/.newReply' if not os.path.isfile(reply_file): try: - with open(reply_file, 'w+') as fp_reply: + with open(reply_file, 'w+', encoding='utf-8') as fp_reply: fp_reply.write(url) except OSError: print('EX: unable to write ' + reply_file) @@ -3018,7 +3024,7 @@ def _git_patch_notify(base_dir: str, handle: str, subject = subject.replace('[PATCH]', '').strip() handle = '@' + from_nickname + '@' + from_domain try: - with open(patch_file, 'w+') as fp_patch: + with open(patch_file, 'w+', encoding='utf-8') as fp_patch: fp_patch.write('git ' + handle + ' ' + subject) except OSError: print('EX: unable to write ' + patch_file) @@ -3175,7 +3181,7 @@ def inbox_update_index(boxname: str, base_dir: str, handle: str, written = False if os.path.isfile(index_filename): try: - with open(index_filename, 'r+') as index_file: + with open(index_filename, 'r+', encoding='utf-8') as index_file: content = index_file.read() if destination_filename + '\n' not in content: index_file.seek(0, 0) @@ -3186,7 +3192,7 @@ def inbox_update_index(boxname: str, base_dir: str, handle: str, print('EX: Failed to write entry to index ' + str(ex)) else: try: - with open(index_filename, 'w+') as index_file: + with open(index_filename, 'w+', encoding='utf-8') as index_file: index_file.write(destination_filename + '\n') written = True except OSError as ex: @@ -3218,13 +3224,15 @@ def _update_last_seen(base_dir: str, handle: str, actor: str) -> None: days_since_epoch = (curr_time - datetime.datetime(1970, 1, 1)).days # has the value changed? if os.path.isfile(last_seen_filename): - with open(last_seen_filename, 'r') as last_seen_file: + with open(last_seen_filename, 'r', + encoding='utf-8') as last_seen_file: days_since_epoch_file = last_seen_file.read() if int(days_since_epoch_file) == days_since_epoch: # value hasn't changed, so we can save writing anything to file return try: - with open(last_seen_filename, 'w+') as last_seen_file: + with open(last_seen_filename, 'w+', + encoding='utf-8') as last_seen_file: last_seen_file.write(str(days_since_epoch)) except OSError: print('EX: unable to write ' + last_seen_filename) @@ -4142,7 +4150,8 @@ def _inbox_after_initial(server, inbox_start_time, destination_filename_mitm = \ destination_filename.replace('.json', '') + '.mitm' try: - with open(destination_filename_mitm, 'w+') as mitm_file: + with open(destination_filename_mitm, 'w+', + encoding='utf-8') as mitm_file: mitm_file.write('\n') except OSError: print('EX: unable to write ' + destination_filename_mitm) @@ -4561,12 +4570,13 @@ def _check_json_signature(base_dir: str, queue_json: {}) -> (bool, bool): already_unknown = False if os.path.isfile(unknown_contexts_file): if unknown_context in \ - open(unknown_contexts_file).read(): + open(unknown_contexts_file, encoding='utf-8').read(): already_unknown = True if not already_unknown: try: - with open(unknown_contexts_file, 'a+') as unknown_file: + with open(unknown_contexts_file, 'a+', + encoding='utf-8') as unknown_file: unknown_file.write(unknown_context + '\n') except OSError: print('EX: unable to append ' + unknown_contexts_file) @@ -4579,7 +4589,7 @@ def _check_json_signature(base_dir: str, queue_json: {}) -> (bool, bool): already_unknown = False if os.path.isfile(unknown_signatures_file): if jwebsig_type in \ - open(unknown_signatures_file).read(): + open(unknown_signatures_file, encoding='utf-8').read(): already_unknown = True if not already_unknown: @@ -4818,7 +4828,8 @@ def _receive_follow_request(session, session_onion, session_i2p, print('Group cannot follow a group') return False try: - with open(followers_filename, 'r+') as followers_file: + with open(followers_filename, 'r+', + encoding='utf-8') as followers_file: content = followers_file.read() if approve_handle + '\n' not in content: followers_file.seek(0, 0) @@ -4834,7 +4845,8 @@ def _receive_follow_request(session, session_onion, session_i2p, str(ex)) else: try: - with open(followers_filename, 'w+') as followers_file: + with open(followers_filename, 'w+', + encoding='utf-8') as followers_file: followers_file.write(approve_handle + '\n') except OSError: print('EX: unable to write ' + followers_filename) @@ -5302,11 +5314,7 @@ def run_inbox_queue(server, if debug: print('DEBUG: No follow requests') - if receive_accept_reject(curr_session, - base_dir, http_prefix, domain, port, - send_threads, post_log, - cached_webfingers, person_cache, - queue_json['post'], + if receive_accept_reject(base_dir, domain, queue_json['post'], federation_list, debug, domain, onion_domain, i2p_domain): print('Queue: Accept/Reject received from ' + key_id) diff --git a/languages.py b/languages.py index 97918f737..7b4836692 100644 --- a/languages.py +++ b/languages.py @@ -39,7 +39,7 @@ def get_understood_languages(base_dir: str, http_prefix: str, """ person_url = local_actor_url(http_prefix, nickname, domain_full) actor_json = \ - get_person_from_cache(base_dir, person_url, person_cache, False) + get_person_from_cache(base_dir, person_url, person_cache) if not actor_json: print('WARN: unable to load actor to obtain languages ' + person_url) return [] @@ -117,7 +117,7 @@ def understood_post_language(base_dir: str, nickname: str, domain: str, return True person_url = local_actor_url(http_prefix, nickname, domain_full) actor_json = \ - get_person_from_cache(base_dir, person_url, person_cache, False) + get_person_from_cache(base_dir, person_url, person_cache) if not actor_json: print('WARN: unable to load actor to check languages ' + person_url) return False diff --git a/manualapprove.py b/manualapprove.py index 2a12f7c32..bda5a8f5e 100644 --- a/manualapprove.py +++ b/manualapprove.py @@ -38,7 +38,8 @@ def manual_deny_follow_request(session, session_onion, session_i2p, # has this handle already been rejected? rejected_follows_filename = accounts_dir + '/followrejects.txt' if os.path.isfile(rejected_follows_filename): - if deny_handle in open(rejected_follows_filename).read(): + if deny_handle in open(rejected_follows_filename, + encoding='utf-8').read(): remove_from_follow_requests(base_dir, nickname, domain, deny_handle, debug) print(deny_handle + @@ -49,7 +50,8 @@ def manual_deny_follow_request(session, session_onion, session_i2p, # Store rejected follows try: - with open(rejected_follows_filename, 'a+') as rejects_file: + with open(rejected_follows_filename, 'a+', + encoding='utf-8') as rejects_file: rejects_file.write(deny_handle + '\n') except OSError: print('EX: unable to append ' + rejected_follows_filename) @@ -153,7 +155,7 @@ def manual_approve_follow_request(session, session_onion, session_i2p, # is the handle in the requests file? approve_follows_str = '' - with open(approve_follows_filename, 'r') as fp_foll: + with open(approve_follows_filename, 'r', encoding='utf-8') as fp_foll: approve_follows_str = fp_foll.read() exists = False approve_handle_full = approve_handle @@ -181,10 +183,12 @@ def manual_approve_follow_request(session, session_onion, session_i2p, '" ' + approve_follows_filename) return - with open(approve_follows_filename + '.new', 'w+') as approvefilenew: + with open(approve_follows_filename + '.new', 'w+', + encoding='utf-8') as approvefilenew: update_approved_followers = False follow_activity_filename = None - with open(approve_follows_filename, 'r') as approvefile: + with open(approve_follows_filename, 'r', + encoding='utf-8') as approvefile: for handle_of_follow_requester in approvefile: # is this the approved follow? if handle_of_follow_requester.startswith(approve_handle_full): @@ -276,9 +280,11 @@ def manual_approve_follow_request(session, session_onion, session_i2p, # update the followers print('Manual follow accept: updating ' + followers_filename) if os.path.isfile(followers_filename): - if approve_handle_full not in open(followers_filename).read(): + if approve_handle_full not in open(followers_filename, + encoding='utf-8').read(): try: - with open(followers_filename, 'r+') as followers_file: + with open(followers_filename, 'r+', + encoding='utf-8') as followers_file: content = followers_file.read() if approve_handle_full + '\n' not in content: followers_file.seek(0, 0) @@ -294,14 +300,16 @@ def manual_approve_follow_request(session, session_onion, session_i2p, print('Manual follow accept: first follower accepted for ' + handle + ' is ' + approve_handle_full) try: - with open(followers_filename, 'w+') as followers_file: + with open(followers_filename, 'w+', + encoding='utf-8') as followers_file: followers_file.write(approve_handle_full + '\n') except OSError: print('EX: unable to write ' + followers_filename) # only update the follow requests file if the follow is confirmed to be # in followers.txt - if approve_handle_full in open(followers_filename).read(): + if approve_handle_full in open(followers_filename, + encoding='utf-8').read(): # mark this handle as approved for following _approve_follower_handle(account_dir, approve_handle) # update the follow requests with the handles not yet approved diff --git a/media.py b/media.py index 046b824df..c87a34dcd 100644 --- a/media.py +++ b/media.py @@ -533,7 +533,7 @@ def _update_etag(media_filename: str) -> None: etag = sha1(data).hexdigest() # nosec # save the hash try: - with open(media_filename + '.etag', 'w+') as efile: + with open(media_filename + '.etag', 'w+', encoding='utf-8') as efile: efile.write(etag) except OSError: print('EX: _update_etag unable to write ' + diff --git a/metadata.py b/metadata.py index d3d488a12..7352582f9 100644 --- a/metadata.py +++ b/metadata.py @@ -105,7 +105,7 @@ def meta_data_instance(show_accounts: bool, rules_filename = \ base_dir + '/accounts/tos.md' if os.path.isfile(rules_filename): - with open(rules_filename, 'r') as fp_rules: + with open(rules_filename, 'r', encoding='utf-8') as fp_rules: rules_lines = fp_rules.readlines() rule_ctr = 1 for line in rules_lines: diff --git a/migrate.py b/migrate.py index 9ff4a68ff..d2252c45b 100644 --- a/migrate.py +++ b/migrate.py @@ -34,7 +34,7 @@ def _move_following_handles_for_account(base_dir: str, acct_dir(base_dir, nickname, domain) + '/following.txt' if not os.path.isfile(following_filename): return ctr - with open(following_filename, 'r') as fp_foll: + with open(following_filename, 'r', encoding='utf-8') as fp_foll: following_handles = fp_foll.readlines() for follow_handle in following_handles: follow_handle = follow_handle.strip("\n").strip("\r") @@ -129,7 +129,7 @@ def _update_moved_handle(base_dir: str, nickname: str, domain: str, following_filename = \ acct_dir(base_dir, nickname, domain) + '/following.txt' if os.path.isfile(following_filename): - with open(following_filename, 'r') as foll1: + with open(following_filename, 'r', encoding='utf-8') as foll1: following_handles = foll1.readlines() moved_to_handle = moved_to_nickname + '@' + moved_to_domain_full @@ -139,7 +139,7 @@ def _update_moved_handle(base_dir: str, nickname: str, domain: str, acct_dir(base_dir, nickname, domain) + '/refollow.txt' # unfollow the old handle - with open(following_filename, 'w+') as foll2: + with open(following_filename, 'w+', encoding='utf-8') as foll2: for follow_handle in following_handles: if follow_handle.strip("\n").strip("\r").lower() != \ handle_lower: @@ -157,22 +157,24 @@ def _update_moved_handle(base_dir: str, nickname: str, domain: str, # save the new handles to the refollow list if os.path.isfile(refollow_filename): - with open(refollow_filename, 'a+') as refoll: + with open(refollow_filename, 'a+', + encoding='utf-8') as refoll: refoll.write(moved_to_handle + '\n') else: - with open(refollow_filename, 'w+') as refoll: + with open(refollow_filename, 'w+', + encoding='utf-8') as refoll: refoll.write(moved_to_handle + '\n') followers_filename = \ acct_dir(base_dir, nickname, domain) + '/followers.txt' if os.path.isfile(followers_filename): - with open(followers_filename, 'r') as foll3: + with open(followers_filename, 'r', encoding='utf-8') as foll3: follower_handles = foll3.readlines() handle_lower = handle.lower() # remove followers who have moved - with open(followers_filename, 'w+') as foll4: + with open(followers_filename, 'w+', encoding='utf-8') as foll4: for follower_handle in follower_handles: if follower_handle.strip("\n").strip("\r").lower() != \ handle_lower: diff --git a/newsdaemon.py b/newsdaemon.py index 4c739925b..5019803b7 100644 --- a/newsdaemon.py +++ b/newsdaemon.py @@ -46,7 +46,7 @@ def _update_feeds_outbox_index(base_dir: str, domain: str, index_filename = base_path + '/outbox.index' if os.path.isfile(index_filename): - if post_id not in open(index_filename).read(): + if post_id not in open(index_filename, encoding='utf-8').read(): try: with open(index_filename, 'r+') as feeds_file: content = feeds_file.read() @@ -59,7 +59,7 @@ def _update_feeds_outbox_index(base_dir: str, domain: str, index_filename + ' ' + str(ex)) else: try: - with open(index_filename, 'w+') as feeds_file: + with open(index_filename, 'w+', encoding='utf-8') as feeds_file: feeds_file.write(post_id + '\n') except OSError: print('EX: unable to write ' + index_filename) @@ -70,7 +70,8 @@ def _save_arrived_time(base_dir: str, post_filename: str, """Saves the time when an rss post arrived to a file """ try: - with open(post_filename + '.arrived', 'w+') as arrived_file: + with open(post_filename + '.arrived', 'w+', + encoding='utf-8') as arrived_file: arrived_file.write(arrived) except OSError: print('EX: unable to write ' + post_filename + '.arrived') @@ -394,7 +395,7 @@ def _newswire_hashtag_processing(session, base_dir: str, post_json_object: {}, if not os.path.isfile(rules_filename): return True rules = [] - with open(rules_filename, 'r') as fp_rules: + with open(rules_filename, 'r', encoding='utf-8') as fp_rules: rules = fp_rules.readlines() domain_full = get_full_domain(domain, port) @@ -466,7 +467,7 @@ def _create_news_mirror(base_dir: str, domain: str, # no index for mirrors found return True removals = [] - with open(mirror_index_filename, 'r') as index_file: + with open(mirror_index_filename, 'r', encoding='utf-8') as index_file: # remove the oldest directories ctr = 0 while no_of_dirs > max_mirrored_articles: @@ -489,13 +490,15 @@ def _create_news_mirror(base_dir: str, domain: str, # remove the corresponding index entries if removals: index_content = '' - with open(mirror_index_filename, 'r') as index_file: + with open(mirror_index_filename, 'r', + encoding='utf-8') as index_file: index_content = index_file.read() for remove_post_id in removals: index_content = \ index_content.replace(remove_post_id + '\n', '') try: - with open(mirror_index_filename, 'w+') as index_file: + with open(mirror_index_filename, 'w+', + encoding='utf-8') as index_file: index_file.write(index_content) except OSError: print('EX: unable to write ' + mirror_index_filename) @@ -524,13 +527,15 @@ def _create_news_mirror(base_dir: str, domain: str, # append the post Id number to the index file if os.path.isfile(mirror_index_filename): try: - with open(mirror_index_filename, 'a+') as index_file: + with open(mirror_index_filename, 'a+', + encoding='utf-8') as index_file: index_file.write(post_id_number + '\n') except OSError: print('EX: unable to append ' + mirror_index_filename) else: try: - with open(mirror_index_filename, 'w+') as index_file: + with open(mirror_index_filename, 'w+', + encoding='utf-8') as index_file: index_file.write(post_id_number + '\n') except OSError: print('EX: unable to write ' + mirror_index_filename) diff --git a/newswire.py b/newswire.py index 8acd22364..f0360dcd9 100644 --- a/newswire.py +++ b/newswire.py @@ -116,7 +116,7 @@ def get_newswire_tags(text: str, max_tags: int) -> []: return tags -def limit_word_lengths(text: str, maxWordLength: int) -> str: +def limit_word_lengths(text: str, max_word_length: int) -> str: """Limits the maximum length of words so that the newswire column cannot become too wide """ @@ -125,8 +125,8 @@ def limit_word_lengths(text: str, maxWordLength: int) -> str: words = text.split(' ') result = '' for wrd in words: - if len(wrd) > maxWordLength: - wrd = wrd[:maxWordLength] + if len(wrd) > max_word_length: + wrd = wrd[:max_word_length] if result: result += ' ' result += wrd @@ -375,18 +375,18 @@ def load_hashtag_categories(base_dir: str, language: str) -> None: if not os.path.isfile(hashtag_categories_filename): return - with open(hashtag_categories_filename, 'r') as fp_cat: + with open(hashtag_categories_filename, 'r', encoding='utf-8') as fp_cat: xml_str = fp_cat.read() _xml2str_to_hashtag_categories(base_dir, xml_str, 1024, True) def _xml2str_to_hashtag_categories(base_dir: str, xml_str: str, - max_categories_feedItem_size_kb: int, + max_categories_feed_item_size_kb: int, force: bool = False) -> None: """Updates hashtag categories based upon an rss feed """ rss_items = xml_str.split('' + file.read() + '
\n' @@ -617,7 +621,7 @@ def html_new_post(css_cache: {}, media_instance: bool, translate: {}, translate['Citations'] + ':\n' citations_str += '' + file.read() + '
' css_filename = base_dir + '/epicyon-login.css' diff --git a/webapp_media.py b/webapp_media.py index 9a2625d9a..70a1c01ce 100644 --- a/webapp_media.py +++ b/webapp_media.py @@ -17,7 +17,8 @@ def load_peertube_instances(base_dir: str, peertube_instances: []) -> None: peertube_list = None peertube_instances_filename = base_dir + '/accounts/peertube.txt' if os.path.isfile(peertube_instances_filename): - with open(peertube_instances_filename, 'r') as fp_inst: + with open(peertube_instances_filename, 'r', + encoding='utf-8') as fp_inst: peertube_str = fp_inst.read() if peertube_str: peertube_str = peertube_str.replace('\r', '') diff --git a/webapp_minimalbutton.py b/webapp_minimalbutton.py index 740eb8797..38337d99d 100644 --- a/webapp_minimalbutton.py +++ b/webapp_minimalbutton.py @@ -40,7 +40,7 @@ def set_minimal(base_dir: str, domain: str, nickname: str, print('EX: set_minimal unable to delete ' + minimal_filename) elif not minimal and not minimal_file_exists: try: - with open(minimal_filename, 'w+') as fp_min: + with open(minimal_filename, 'w+', encoding='utf-8') as fp_min: fp_min.write('\n') except OSError: print('EX: unable to write minimal ' + minimal_filename) diff --git a/webapp_moderation.py b/webapp_moderation.py index 05ae31525..180bd40f3 100644 --- a/webapp_moderation.py +++ b/webapp_moderation.py @@ -394,7 +394,7 @@ def html_moderation_info(translate: {}, base_dir: str, suspended_filename = base_dir + '/accounts/suspended.txt' if os.path.isfile(suspended_filename): - with open(suspended_filename, 'r') as fp_sus: + with open(suspended_filename, 'r', encoding='utf-8') as fp_sus: suspended_str = fp_sus.read() info_form += '