diasporadiaries

a platform for writing stories with personal accounts and messages
git clone git://parazyd.org/diasporadiaries.git
Log | Files | Refs | Submodules | README | LICENSE

commit 4f88568de443e6e0d1bb64982f0e980a96cfe396
parent b007b707e3ddc20499c6f450f291a8f44a26556c
Author: parazyd <parazyd@dyne.org>
Date:   Tue, 22 Jan 2019 23:53:21 +0100

Simplify message sending.

Diffstat:
Mutils.py | 38++++++++++++++------------------------
1 file changed, 14 insertions(+), 24 deletions(-)

diff --git a/utils.py b/utils.py @@ -19,7 +19,7 @@ Utility functions. """ import json from os import makedirs, listdir, remove -from os.path import join +from os.path import join, isfile from random import SystemRandom, shuffle from shutil import rmtree from string import ascii_lowercase, digits @@ -273,7 +273,7 @@ def get_latest_messages(user_id): ppl = listdir(msgpath) latest = [] for i in ppl: - try: + if isfile(join(msgpath, i)): with open(join(msgpath, i)) as msgfile: data = json.load(msgfile) user = find_user_by_email(i) @@ -281,8 +281,6 @@ def get_latest_messages(user_id): continue data[-1]['message'] = data[-1]['message'][:64] + "..." latest.append([user['name'], user['id'], data[-1]]) - except json.decoder.JSONDecodeError: - continue sorted_latest = [] for i in sorted(latest, key=lambda x: x[2]['time'], reverse=True): @@ -305,14 +303,12 @@ def get_messages(user_id, id_from): msgpath = join('messages', user_id, email) data = [] - try: + if isfile(msgpath): with open(msgpath) as msgfile: - try: - data = json.load(msgfile) - except json.decoder.JSONDecodeError: - data = [] - except FileNotFoundError: - open(msgpath, 'w').close() + data = json.load(msgfile) + else: + with open(msgpath, 'w') as msgfile: + json.dump(data, msgfile) return [] messages = [] @@ -330,14 +326,13 @@ def send_message(id_to, msg, id_us): if not id_to or not msg or not id_us: return ours = find_user_by_id(id_us) - if not ours: - return them = find_user_by_id(id_to) - if not them: + if not ours or not them: return + makedirs(join('messages', ours['email']), exist_ok=True) - our_msgpath = join('messages', ours['email'], them['email']) makedirs(join('messages', them['email']), exist_ok=True) + our_msgpath = join('messages', ours['email'], them['email']) their_msgpath = join('messages', them['email'], ours['email']) msgdict = { @@ -347,26 +342,21 @@ def send_message(id_to, msg, id_us): } ourdata = [] - try: + theirdata = [] + + if isfile(our_msgpath): with open(our_msgpath) as ourmsgs: ourdata = json.load(ourmsgs) - except json.decoder.JSONDecodeError: - ourdata = [] ourdata.append(msgdict) - with open(our_msgpath, 'w') as ourmsgs: json.dump(ourdata, ourmsgs) - theirdata = [] - try: + if isfile(their_msgpath): with open(their_msgpath) as theirmsgs: theirdata = json.load(theirmsgs) - except json.decoder.JSONDecodeError: - theirdata = [] theirdata.append(msgdict) - with open(their_msgpath, 'w') as theirmsgs: json.dump(theirdata, theirmsgs)