blueprints.dms: make sure no double dms happen

by first checking existance, then inserting if
none was found.
This commit is contained in:
Luna Mendes 2018-10-24 19:25:44 -03:00
parent 2605836790
commit 75a8e77a21
1 changed files with 33 additions and 27 deletions

View File

@ -38,12 +38,28 @@ async def try_dm_state(user_id: int, dm_id: int):
""", user_id, dm_id) """, user_id, dm_id)
async def jsonify_dm(dm_id: int, user_id: int):
dm_chan = await app.storage.get_dm(dm_id, user_id)
return jsonify(dm_chan)
async def create_dm(user_id, recipient_id): async def create_dm(user_id, recipient_id):
"""Create a new dm with a user, """Create a new dm with a user,
or get the existing DM id if it already exists.""" or get the existing DM id if it already exists."""
dm_id = get_snowflake()
try: dm_id = await app.db.fetchval("""
SELECT id
FROM dm_channels
WHERE (party1_id = $1 OR party2_id = $1) AND
(party1_id = $2 OR party2_id = $2)
""", user_id, recipient_id)
if dm_id:
return await jsonify_dm(dm_id, user_id)
# if no dm was found, create a new one
dm_id = get_snowflake()
await app.db.execute(""" await app.db.execute("""
INSERT INTO channels (id, channel_type) INSERT INTO channels (id, channel_type)
VALUES ($1, $2) VALUES ($1, $2)
@ -62,17 +78,7 @@ async def create_dm(user_id, recipient_id):
# until the user sends a message. # until the user sends a message.
await try_dm_state(user_id, dm_id) await try_dm_state(user_id, dm_id)
except UniqueViolationError: return await jsonify_dm(dm_id, user_id)
# the dm already exists
dm_id = await app.db.fetchval("""
SELECT id
FROM dm_channels
WHERE (party1_id = $1 OR party2_id = $1) AND
(party2_id = $2 OR party2_id = $2)
""", user_id, recipient_id)
dm = await app.storage.get_dm(dm_id, user_id)
return jsonify(dm)
@bp.route('/@me/channels', methods=['POST']) @bp.route('/@me/channels', methods=['POST'])