From 3a4e14a96f399a29922840ca294303ee2e2465de Mon Sep 17 00:00:00 2001 From: Marcel Date: Thu, 1 Nov 2018 13:42:58 +0100 Subject: [PATCH] Social Posts image upload: Overwrite existing database entry and add image upload functionality to YouTube videos --- social_posts.py | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/social_posts.py b/social_posts.py index baf42d2..0baf460 100644 --- a/social_posts.py +++ b/social_posts.py @@ -31,16 +31,33 @@ def insertIntoDatabase(platform, title, url, author, authorUrl, published, image def generateImageName(): return random.getrandbits(128) - +# Reads image from entered url and uploads it to the own server while creating a corresponding entry in the database def uploadImage(imageUrl, originalName): + response = requests.get(imageUrl) img = Image.open(BytesIO(response.content)) name = '%032x' % generateImageName() + + # Checks if there is already an uploaded image with the same original name + # If so the previously generated random name is overwritten and the entry in the database deleted + try: + cur.execute("SELECT * FROM files WHERE original_name = %s", (originalName)) + result = cur.fetchone() + name = result[1] + + cur.execute("DELETE FROM files WHERE ID = %s", (result[0])) + db.commit() + except: + db.rollback() + + # Writes the image to the correct path path = 'files/userContent/%s.jpg' % name img.save(path) fileSize = os.path.getsize(path) + + # Adds a new entry to the database with all the data try: cur.execute( "INSERT INTO files (name, original_name, type, size, path, isUserData) VALUES (%s, %s, 'image/jpeg', %s, %s, 1)", @@ -50,6 +67,7 @@ def uploadImage(imageUrl, originalName): print('it didnt work') db.rollback() + # Returns the relative URL path for displaying the image later on return '/f/' + name def getYouTubeVideos(): @@ -69,6 +87,9 @@ def getYouTubeVideos(): else: thumbnail = snippet['thumbnails']['standard']['url'] + if thumbnail: + thumbnail = uploadImage(thumbnail, 'youtube_' + snippet['resourceId']['videoId']) + insertIntoDatabase('YouTube', title, url, author, authorUrl, published, thumbnail, 0) @@ -90,7 +111,7 @@ def getTwitterPosts(): image = '' if tweet.media: image = tweet.media[0].media_url - image = uploadImage(image, tweet.id_str) + image = uploadImage(image, 'twitter_' + tweet.id_str) insertIntoDatabase('Twitter', content, url, author, authorUrl, published, image, originalID)