Skip to content

Fixes #722 - Handle two sizes images #1266

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jan 6, 2017
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 35 additions & 15 deletions webcompat/api/uploads.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,19 @@
'''Flask Blueprint for image uploads.'''

import base64
import datetime
import io
import json
import os
import re
import uuid

from datetime import date
from flask import abort
from flask import Blueprint
from flask import request
from io import BytesIO
from PIL import Image
from werkzeug.datastructures import FileStorage
from werkzeug.exceptions import RequestEntityTooLarge
from uuid import uuid4

from webcompat import app

Expand All @@ -40,7 +40,16 @@ class Upload(object):

def __init__(self, imagedata):
self.image_object = self.to_image_object(imagedata)
# computing the parameters to be used
today = datetime.date.today()
self.year = str(today.year)
self.month = str(today.month)
self.image_id = str(uuid.uuid4())
self.file_ext = self.get_file_ext()
self.image_path = self.img_path(self.month, self.year, self.image_id,
thumb=False)
self.thumb_path = self.img_path(self.month, self.year, self.image_id,
thumb=True)

def to_image_object(self, imagedata):
'''Method to return a Pillow Image object from the raw imagedata.'''
Expand All @@ -53,12 +62,20 @@ def to_image_object(self, imagedata):
imagedata.startswith('data:image/')):
# Chop off 'data:image/.+;base64,' before decoding
imagedata = re.sub('^data:image/.+;base64,', '', imagedata)
return Image.open(BytesIO(base64.b64decode(imagedata)))
return Image.open(io.BytesIO(base64.b64decode(imagedata)))
raise TypeError('TypeError: Not a valid image format')
except TypeError:
# Not a valid format
abort(415)

def img_path(self, month, year, image_id, thumb=False):
'''Return the right image path.'''
thumb_string = ''
if thumb:
thumb_string = '-thumb'
image_name = image_id + thumb_string + '.' + self.file_ext
return os.path.join(year, month, image_name)

def get_file_ext(self):
'''Method to return the file extension, as determined by Pillow.

Expand All @@ -68,24 +85,22 @@ def get_file_ext(self):
return 'jpg'
return self.image_object.format.lower()

def get_filename(self):
def get_filename(self, image_path):
'''Method to return the uploaded filename (with extension).'''
return self.get_url().split('/')[-1]
return self.get_url(image_path).split('/')[-1]

def get_url(self):
def get_url(self, image_path):
'''Method to return a URL for the uploaded file.'''
return app.config['UPLOADS_DEFAULT_URL'] + self.file_path
return app.config['UPLOADS_DEFAULT_URL'] + image_path

def save(self):
'''Check that the file is allowed, then save to filesystem.'''
save_parameters = {}
if self.file_ext not in self.ALLOWED_FORMATS:
raise TypeError('Image file format not allowed')

today = date.today()
self.file_path = os.path.join(str(today.year), str(today.month),
str(uuid4()) + '.' + self.file_ext)
file_dest = app.config['UPLOADS_DEFAULT_DEST'] + self.file_path
# Paths of the images
file_dest = app.config['UPLOADS_DEFAULT_DEST'] + self.image_path
thumb_dest = app.config['UPLOADS_DEFAULT_DEST'] + self.thumb_path
dest_dir = os.path.dirname(file_dest)
if not os.path.exists(dest_dir):
os.makedirs(dest_dir)
Expand All @@ -100,6 +115,10 @@ def save(self):
save_parameters['save_all'] = True
# unpacking save_parameters
self.image_object.save(file_dest, **save_parameters)
# Creating the thumbnail
size = (320, 320)
self.image_object.thumbnail(size, Image.NEAREST)
self.image_object.save(thumb_dest, **save_parameters)


@uploads.route('/', methods=['POST'])
Expand All @@ -123,8 +142,9 @@ def upload():
upload = Upload(imagedata)
upload.save()
data = {
'filename': upload.get_filename(),
'url': upload.get_url()
'filename': upload.get_filename(upload.image_path),
'url': upload.get_url(upload.image_path),
'thumb_url': upload.get_url(upload.thumb_path)
}
return (json.dumps(data), 201, {'content-type': JSON_MIME})
except (TypeError, IOError):
Expand Down
6 changes: 4 additions & 2 deletions webcompat/static/js/lib/bugform.js
Original file line number Diff line number Diff line change
Expand Up @@ -428,8 +428,10 @@ function BugForm() {
copy over the URL of a newly uploaded image asset to the bug
description textarea.
*/
this.addImageURL = function(url) {
var imageURL = ['![Screenshot Description](', url, ')'].join('');
this.addImageURL = function(url) {
var file_ext = url.split('.').pop();
var thumb_url = url.replace('.' + file_ext, '-thumb.' + file_ext);

This comment was marked as abuse.

This comment was marked as abuse.

This comment was marked as abuse.

var imageURL = ['[![Screenshot Description](', thumb_url, ')](', url, ')'].join('');

This comment was marked as abuse.

This comment was marked as abuse.

This comment was marked as abuse.

This comment was marked as abuse.

this.descField.val(function(idx, value) {
return value + '\n\n' + imageURL;
});
Expand Down
7 changes: 5 additions & 2 deletions webcompat/static/js/lib/issues.js
Original file line number Diff line number Diff line change
Expand Up @@ -199,8 +199,11 @@ issues.ImageUploadView = Backbone.View.extend({
var DELIMITER = '\n\n';
var textarea = $('.js-Comment-text');
var textareaVal = textarea.val();
var imageURL = _.template('![Screenshot of the site issue](<%= url %>)');
var compiledImageURL = imageURL({url: response.url});
var img_url = response.url;
var file_ext = img_url.split('.').pop();
var thumb_url = img_url.replace('.' + file_ext, '-thumb.' + file_ext);

This comment was marked as abuse.

This comment was marked as abuse.

var imageURL = _.template('[![Screenshot Description](<%= thumb_url %>)](<%= img_url %>)');
var compiledImageURL = imageURL({thumb_url: thumb_url, img_url: img_url});

if (!$.trim(textareaVal)) {
textarea.val(compiledImageURL);
Expand Down