fixes to ekimekim's suggestions

pull/46/head
Christopher Usher 6 years ago
parent c81d538a79
commit 1d09e28b1e

@ -38,9 +38,9 @@ def thrimshim(ident):
"""Comunicate between Thrimbletrimmer and the Wubloader database.""" """Comunicate between Thrimbletrimmer and the Wubloader database."""
try: try:
uuid.UUID(ident, version=4) uuid.UUID(ident)
except ValueError: except ValueError:
return 'Invalid formate for id', 400 return 'Invalid format for id', 400
if flask.request.method == 'POST': if flask.request.method == 'POST':
row = flask.request.json row = flask.request.json
@ -53,17 +53,22 @@ def thrimshim(ident):
def get_row(ident): def get_row(ident):
"""Gets the row from the database with id == ident.""" """Gets the row from the database with id == ident."""
conn = app.db_manager.get_conn() conn = app.db_manager.get_conn()
with database.transaction(conn): results = database.query(conn, """
results = database.query(conn, """ SELECT *
SELECT * FROM events
FROM events WHERE id = %s""", ident)
WHERE id = %s;""", ident)
row = results.fetchone() row = results.fetchone()
if row is None: if row is None:
return 'Row id = {} not found'.format(ident), 404 return 'Row id = {} not found'.format(ident), 404
assert row.id == ident assert row.id == ident
response = row._asdict() response = row._asdict()
response = {key:(response[key].isoformat() if isinstance(response[key], datetime.datetime) else response[key]) for key in response.keys()}
response = {
key: (
value.isoformat() if isinstance(value, datetime.datetime)
else value
) for key, value in response.items()
}
return json.dumps(response) return json.dumps(response)
@ -72,26 +77,32 @@ def update_row(ident, new_row):
"""Updates row of database with id = ident with the edit columns in """Updates row of database with id = ident with the edit columns in
new_row. new_row.
If a 'video_link' is provided in uodate, interperate this as a manual video If a 'video_link' is provided in update, interperet this as a manual video
upload and set state to 'DONE'""" upload and set state to 'DONE'"""
edit_columns = ['allow_holes', 'uploader_whitelist', 'upload_location', edit_columns = ['allow_holes', 'uploader_whitelist', 'upload_location',
'video_start', 'video_end', 'video_title', 'video_description', 'video_start', 'video_end', 'video_title', 'video_description',
'video_channel', 'video_quality'] 'video_channel', 'video_quality']
state_columns = ['state', 'uploader', 'error', 'video_link'] state_columns = ['state', 'uploader', 'error', 'video_link']
columns = edit_columns + state_columns #these have to be set before a video can be set as 'EDITED'
non_null_columns = ['upload_location', 'video_start', 'video_end',
#check edit columns are in new_row 'video_channel', 'video_quality']
row_keys = new_row.keys()
for column in edit_columns + ['state']: #check vital edit columns are in new_row
if column not in row_keys: wanted = set(non_null_columns + ['state'])
return 'Missing field {} in JSON'.format(column), 400 missing = wanted - set(new_row)
if missing:
return 'Fields missing in JSON: {}'.format(', '.join(missing)), 400
#get rid of irrelevant columns
extras = set(new_row) - set(edit_columns + state_columns)
for extra in extras:
del new_row[extra]
conn = app.db_manager.get_conn() conn = app.db_manager.get_conn()
#check a row with id = ident is in the database #check a row with id = ident is in the database
with database.transaction(conn): with database.transaction(conn):
results = database.query(conn, """ results = database.query(conn, """
SELECT id, state SELECT id, state
FROM events FROM events
WHERE id = %s;""", ident) WHERE id = %s;""", ident)
old_row = results.fetchone() old_row = results.fetchone()
@ -100,7 +111,7 @@ def update_row(ident, new_row):
assert old_row.id == ident assert old_row.id == ident
if old_row.state not in ['UNEDITED', 'EDITED', 'CLAIMED']: if old_row.state not in ['UNEDITED', 'EDITED', 'CLAIMED']:
return 'Video already published', 400 return 'Video already published', 403
# handle state columns # handle state columns
# handle non-empty video_link as manual uploads # handle non-empty video_link as manual uploads
@ -109,27 +120,42 @@ def update_row(ident, new_row):
new_row['state'] = 'DONE' new_row['state'] = 'DONE'
new_row['upload_location'] = 'manual' new_row['upload_location'] = 'manual'
else: else:
new_row['video_link'] = None if new_row['state'] == 'EDITED':
new_row['upload_location'] = None missing = []
if new_row['state'] not in ['EDITED']: for column in non_null_columns:
new_row['state'] = 'UNEDITED' if not new_row[column] or new_row[column] is None:
missing.append(column)
if missing:
return 'Fields {} must be non-null for video to be cut'.format(', '.join(missing)), 400
elif new_row['state'] != 'UNEDITED':
return 'Invalid state {}'.format(new_row['state']), 400
new_row['uploader'] = None new_row['uploader'] = None
new_row['error'] = None new_row['error'] = None
# actually update database # actually update database
build_query = sql.SQL(""" build_query = sql.SQL("""
UPDATE events UPDATE events
set {} SET {}
WHERE id = %(id)s""").format(sql.SQL(", ").join( WHERE id = %(id)s
AND state IN ('UNEDITED', 'EDITED', 'CLAIMED')"""
).format(sql.SQL(", ").join(
sql.SQL("{} = {}").format( sql.SQL("{} = {}").format(
sql.Identifier(column), sql.Placeholder(column), sql.Identifier(column), sql.Placeholder(column),
) for column in columns ) for column in new_row.keys()
)) ))
kwargs = {column:new_row[column] for column in columns}
kwargs['id'] = ident
with database.transaction(conn): with database.transaction(conn):
result = database.query(conn, build_query, **kwargs) result = database.query(conn, build_query, id=ident, **new_row)
if result.rowcount != 1: if result.rowcount != 1:
if result.rowcount == 0.:
with database.transaction(conn):
check_result = database.query(conn, """
SELECT id, state
FROM events
WHERE id = %s;""", ident)
current_row = check_result.fetchone()
if current_row.state not in ['UNEDITED', 'EDITED', 'CLAIMED']:
return 'Video already published', 403
raise Exception('Database consistancy error for id = {}'.format(ident)) raise Exception('Database consistancy error for id = {}'.format(ident))
logging.info('Row {} updated to state {}'.format(ident, new_row['state'])) logging.info('Row {} updated to state {}'.format(ident, new_row['state']))

Loading…
Cancel
Save