def get_common_parameters(self): self.chunked_upload = True if not self.get_argument('resumableChunkSize', None): if self.get_argument('canvasName', None): self.base_leafname = self.get_argument('canvasName') else: self.base_leafname = self.request.files['file'][0]['filename'] self.chunked_upload = False return if not self.authenticate(author=True): raise tornado.web.HTTPError(400, "i call shenanigans") self.chunk_number = url_factory.clean_filename( self.get_argument('resumableChunkNumber')) self.chunk_size = int(self.get_argument('resumableChunkSize')) self.total_size = int(self.get_argument('resumableTotalSize')) self.identifier = self.get_argument('resumableIdentifier') self.filename = url_factory.clean_filename( self.get_argument('resumableFilename')) self.base_leafname = os.path.basename(self.filename) self.leafname = self.base_leafname + '_' + self.chunk_number.zfill(4) self.private_path = os.path.join( self.application.settings["private_path"], self.get_author_username()) self.tmp_dir = os.path.join(self.private_path, 'tmp') self.tmp_path = os.path.join(self.tmp_dir, self.leafname) if not os.path.isdir(self.tmp_dir): os.makedirs(self.tmp_dir)
def post(self): if not self.authenticate(author=True): return op = self.get_argument('op', None) if op == 'favorite': self.favorite() return self.user = self.get_author_user() access_token = json.loads(self.user.twitter) #thumb = self.get_argument('thumb', '') # XXX TODO multipart doesn't work for some reason right now... arrrgh thumb = None text_length = 79 if thumb else 99 title = self.get_argument('title', '') view = self.get_argument('view', '') status = (content_logic.ellipsize( content_remote.strip_html(title), 18, including_dots=True) + (': ' if title and view else '') + content_logic.ellipsize( content_remote.strip_html(view.replace('<br>', ' ')), text_length, including_dots=True) + (' ' if title or view else '') + self.get_argument('url')) if thumb: thumb = url_factory.clean_filename(thumb) thumb = thumb[len(url_factory.resource_url(self)) + 1:] thumb = url_factory.resource_directory(self, thumb) image = thumb basename = os.path.basename(thumb) dirname = os.path.dirname(thumb) if os.path.basename(dirname) == 'thumbs': parent_dir = os.path.dirname(dirname) original_dir = os.path.join(parent_dir, 'original') original_img = os.path.join(original_dir, basename) if (os.path.exists(original_img) and os.path.getsize(original_img) < 3145728): image = original_img f = open(image, 'r') image_data = f.read() f.close() self.twitter_request(self.UPDATE_WITH_MEDIA_URL, self.status_update_result, access_token=access_token, post_args={ "status": status, "media[]": image_data }) else: self.twitter_request("/statuses/update", self.status_update_result, access_token=access_token, post_args={"status": status})
def post(self): if not self.authenticate(author=True): return op = self.get_argument('op', None) if op == 'favorite': self.favorite() return self.user = self.get_author_user() access_token = json.loads(self.user.twitter) #thumb = self.get_argument('thumb', '') # XXX TODO multipart doesn't work for some reason right now... arrrgh thumb = None text_length = 79 if thumb else 99 title = self.get_argument('title', '') view = self.get_argument('view', '') status = (content_logic.ellipsize(content_remote.strip_html( title), 18, including_dots=True) + (': ' if title and view else '') + content_logic.ellipsize(content_remote.strip_html( view.replace('<br>', ' ')), text_length, including_dots=True) + (' ' if title or view else '') + self.get_argument('url')) if thumb: thumb = url_factory.clean_filename(thumb) thumb = thumb[len(url_factory.resource_url(self)) + 1:] thumb = url_factory.resource_directory(self, thumb) image = thumb basename = os.path.basename(thumb) dirname = os.path.dirname(thumb) if os.path.basename(dirname) == 'thumbs': parent_dir = os.path.dirname(dirname) original_dir = os.path.join(parent_dir, 'original') original_img = os.path.join(original_dir, basename) if (os.path.exists(original_img) and os.path.getsize(original_img) < 3145728): image = original_img f = open(image, 'r') image_data = f.read() f.close() self.twitter_request( self.UPDATE_WITH_MEDIA_URL, self.status_update_result, access_token=access_token, post_args={"status": status, "media[]": image_data }) else: self.twitter_request( "/statuses/update", self.status_update_result, access_token=access_token, post_args={"status": status})
def get_full_filename(handler, url=None): if not url: url = handler.prefix + handler.breadcrumbs['uri'] elif not url.startswith(handler.prefix): url = handler.prefix + url filename = url_factory.clean_filename(url) # TODO filename = handler.locale.code.replace('_', '-') + '/' + filename path = os.path.join(handler.application.settings["cache_path"], filename + '.' + EXTENSION) parent_directory = os.path.dirname(path) if not os.path.isdir(parent_directory): os.makedirs(parent_directory) return path
def get(self): if not self.authenticate(author=True): return if self.get_argument('preview', ''): self.preview() return self.display["user"] = self.get_author_user() parent_directory = url_factory.resource_directory(self) self.display["files"] = os.walk(parent_directory) self.display["initial_section"] = None initial_section_check = self.get_argument('initial_section', None) if initial_section_check and os.path.exists(os.path.join( url_factory.resource_directory(self), initial_section_check)): self.display["initial_section"] = initial_section_check self.display["basename"] = os.path.basename self.display["dirname"] = os.path.dirname self.display["join"] = os.path.join if not self.display.has_key('uploaded_file'): self.display["uploaded_file"] = None uploaded_file_check = self.get_argument('uploaded_file', None) if uploaded_file_check: uploaded_file_check = url_factory.clean_filename(uploaded_file_check) uploaded_file_check = os.path.join( self.application.settings["base_path"], uploaded_file_check) if not uploaded_file_check.startswith( url_factory.resource_directory(self)): raise tornado.web.HTTPError(400, "i call shenanigans") if os.path.exists(uploaded_file_check): self.display["uploaded_file"] = uploaded_file_check.replace( self.application.settings["base_path"] + '/', '') self.display["initial_section"] = os.path.dirname( self.display["uploaded_file"]) self.display["embedded"] = self.get_argument('embedded', '') if self.display["embedded"]: self.fill_template("media_standalone.html") else: self.fill_template("media.html") # disabled for now
def delete(self): if not self.authenticate(author=True): return files = json.loads(self.get_argument('files')) parent_leading_path = (self.application.settings["resource_url"] + "/" + self.get_author_username()) for f in files: f = url_factory.clean_filename(f).replace(parent_leading_path + '/', '') filename = os.path.join(url_factory.resource_directory(self), f) if os.path.isdir(filename): shutil.rmtree(filename) else: os.remove(filename)
def post(self): if not self.authenticate(author=True): return user = self.get_author_user() user.title = self.get_argument('title', '') user.description = self.get_argument('description', '') user.email = self.get_argument('email') user.name = self.get_argument('name', '') user.favicon = url_factory.clean_filename( self.get_argument('favicon', '')) user.currency = self.get_argument('currency', '') user.theme_title = self.get_argument('theme_title', '') user.theme_link = self.get_argument('theme_link', '') user.theme_author = self.get_argument('theme_author', '') user.theme_author_link = self.get_argument('theme_author_link', '') user.extra_head_html = self.get_argument('extra_head_html', '').replace('\\n', '\n') user.extra_body_end_html = self.get_argument('extra_body_end_html', '').replace('\\n', '\n') user.logo = url_factory.clean_filename(self.get_argument('logo', '')) user.google_analytics = self.get_argument('google_analytics', '') user.adult_content = int(self.get_argument('adult_content', 0)) user.tipjar = self.get_argument('tipjar', '') user.sidebar_ad = self.get_argument('sidebar_ad', '') user.newsletter_endpoint = self.get_argument('newsletter_endpoint', '') user.license = self.get_argument('license', '') default_stylesheet = self.get_argument('default_stylesheet', '') stylesheet = self.get_argument('stylesheet', '') theme = url_factory.clean_filename(self.get_argument('theme', '')) static_path = self.application.settings["static_path"] theme = os.path.join(static_path, os.path.dirname(theme)) user_path = os.path.join(self.application.settings["resource_path"], user.username) theme_path = os.path.join(user_path, 'themes') current_theme_path = os.path.join(theme_path, '_current_theme') compiled_stylesheet_path = os.path.join(current_theme_path, '_compiled_.css') default_stylesheet_path = os.path.join(current_theme_path, '_default_.css') if theme != current_theme_path: if os.path.exists(current_theme_path): shutil.rmtree(current_theme_path) shutil.copytree(theme, current_theme_path) f = open(compiled_stylesheet_path, 'w') f.write(stylesheet) f.close() f = open(default_stylesheet_path, 'w') f.write(default_stylesheet) f.close() user.theme = compiled_stylesheet_path[len(self.application. settings["static_path"]) + 1:] user.save() self.set_status(204)
def post(self): if not self.authenticate(author=True): return op = self.get_argument('op', None) if op == 'favorite': self.favorite() return access_token, tumblr_info = self.get_tumblr_info() title = content_remote.strip_html(self.get_argument('title', '')) body = url_factory.add_base_uris(self, self.get_argument('view', '')) \ + '\n' \ + self.get_argument('url') post_args = {"type": "text", "title": title, "body": body} # TODO, refactor out w FB logic thumb = self.get_argument('thumb', '') picture = None normal_picture = None if thumb: if not thumb.startswith('http://'): thumb = url_factory.clean_filename(thumb) thumb = thumb[len(url_factory.resource_url(self)) + 1:] thumb = url_factory.resource_directory(self, thumb) picture = thumb basename = os.path.basename(thumb) dirname = os.path.dirname(thumb) if os.path.basename(dirname) == 'thumbs': parent_dir = os.path.dirname(dirname) original_dir = os.path.join(parent_dir, 'original') original_img = os.path.join(original_dir, basename) if os.path.exists(original_img): picture = original_img normal_path = os.path.join(parent_dir, basename) if os.path.exists(normal_path): normal_picture = normal_path normal_picture = normal_picture[len( self.application.settings["static_path"]) + 1:] normal_picture = self.static_url(normal_picture, include_host=True, include_sig=False) picture = picture[len(self.application.settings["static_path"]) + 1:] picture = self.static_url(picture, include_host=True, include_sig=False) else: picture = thumb video = re.compile(r'<iframe[^>]*(youtube|vimeo)[^>]*>.*?</iframe>', re.M | re.S).search(body) if picture and normal_picture and not video: post_args["source"] = picture post_args["link"] = self.get_argument('url') post_args["caption"] = re.compile(r'(<figure>.*?<img.*?src="' + normal_picture + r'".*?>.*?</figure>)', re.M | re.U | re.S).sub( '', body) post_args["type"] = "photo" if video: video = video.group(0) post_args["embed"] = video post_args["caption"] = body.replace(video, '') post_args["type"] = "video" section = self.get_argument('section', '') album = self.get_argument('album', '') tags = re.compile(r'#(\w+)(?![^<&]*(?:[>;]))', re.M | re.U).findall(body) post_args["tags"] = "" if tags: post_args["tags"] += ','.join(tags) if section: post_args["tags"] += "," + section if album: post_args["tags"] += "," + album self.tumblr_request( "http://api.tumblr.com/v2/blog/" + tumblr_info['primary_blog'] + "/post", self.status_update_result, access_token=access_token, post_args=post_args,)
def post(self): if not self.authenticate(author=True): return user = self.get_author_user() user.title = self.get_argument('title', '') user.description = self.get_argument('description', '') user.email = self.get_argument('email') user.name = self.get_argument('name', '') user.favicon = url_factory.clean_filename(self.get_argument('favicon', '')) user.currency = self.get_argument('currency', '') user.theme_title = self.get_argument('theme_title', '') user.theme_link = self.get_argument('theme_link', '') user.theme_author = self.get_argument('theme_author', '') user.theme_author_link = self.get_argument('theme_author_link', '') user.extra_head_html = self.get_argument( 'extra_head_html', '').replace('\\n', '\n') user.extra_body_end_html = self.get_argument( 'extra_body_end_html', '').replace('\\n', '\n') user.logo = url_factory.clean_filename( self.get_argument('logo', '')) user.google_analytics = self.get_argument('google_analytics', '') user.adult_content = int(self.get_argument('adult_content', 0)) user.tipjar = self.get_argument('tipjar', '') user.sidebar_ad = self.get_argument('sidebar_ad', '') user.newsletter_endpoint = self.get_argument('newsletter_endpoint', '') user.license = self.get_argument('license', '') default_stylesheet = self.get_argument('default_stylesheet', '') stylesheet = self.get_argument('stylesheet', '') theme = url_factory.clean_filename(self.get_argument('theme', '')) static_path = self.application.settings["static_path"] theme = os.path.join(static_path, os.path.dirname(theme)) user_path = os.path.join( self.application.settings["resource_path"], user.username) theme_path = os.path.join(user_path, 'themes') current_theme_path = os.path.join(theme_path, '_current_theme') compiled_stylesheet_path = os.path.join( current_theme_path, '_compiled_.css') default_stylesheet_path = os.path.join( current_theme_path, '_default_.css') if theme != current_theme_path: if os.path.exists(current_theme_path): shutil.rmtree(current_theme_path) shutil.copytree(theme, current_theme_path) f = open(compiled_stylesheet_path, 'w') f.write(stylesheet) f.close() f = open(default_stylesheet_path, 'w') f.write(default_stylesheet) f.close() user.theme = compiled_stylesheet_path[len( self.application.settings["static_path"]) + 1:] user.save() self.set_status(204)
def post(self): if not self.authenticate(author=True): return op = self.get_argument('op', None) if op == 'favorite': self.favorite() return self.user = self.get_author_user() access_token = self.user.facebook title = self.get_argument('title', '') view = self.get_argument('view', '') status = (content_remote.strip_html(title) + ('\n' if title and view else '') + content_remote.strip_html(view.replace('<br>', ' ')) + ('\n' if title or view else '') + self.get_argument('url')) post_args = {"message": status} thumb = self.get_argument('thumb', '') picture = None if thumb: if not thumb.startswith('http://'): thumb = url_factory.clean_filename(thumb) thumb = thumb[len(url_factory.resource_url(self)) + 1:] thumb = url_factory.resource_directory(self, thumb) picture = thumb basename = os.path.basename(thumb) dirname = os.path.dirname(thumb) if os.path.basename(dirname) == 'thumbs': parent_dir = os.path.dirname(dirname) original_dir = os.path.join(parent_dir, 'original') original_img = os.path.join(original_dir, basename) if os.path.exists(original_img): picture = original_img picture = picture[len(self.application.settings["static_path"] ) + 1:] picture = self.static_url(picture, include_host=True) else: picture = thumb if picture: post_args['picture'] = picture video = re.compile(r'<iframe[^>]*(youtube|vimeo)[^>]*>.*?</iframe>', re.M | re.S).search(view) if video: video = video.group(0) is_youtube = re.compile(r'<iframe[^>]*(youtube)[^>]*>', re.M).search(view) if is_youtube: video_id = re.compile( r'<iframe[^>]*youtube.com/embed/([^\?]*)[^>]*>', re.M).search(view).group(1) source = 'http://www.youtube.com/e/' + video_id + '?autoplay=1' else: video_id = re.compile( r'<iframe[^>]*vimeo.com/video/([^\?"]*)[^>]*>', re.M).search(view).group(1) source = ('https://secure.vimeo.com/moogaloop.swf?clip_id=' + video_id + '&autoplay=1') post_args['source'] = source self.facebook_request( "/me/feed", self.status_update_result, access_token=access_token, post_args=post_args, )
def post(self): safe_user = False if self.authenticate(author=True): safe_user = True self.get_common_parameters() if safe_user: if media.detect_media_type(self.base_leafname) not in ('video', 'image', 'audio', 'web', 'zip'): raise tornado.web.HTTPError(400, "i call shenanigans") else: if media.detect_media_type(self.base_leafname) != 'image': raise tornado.web.HTTPError(400, "i call shenanigans") if self.get_argument('canvasImage', None): uploaded_file = self.get_argument('canvasImage') else: uploaded_file = self.request.files['file'][0] overwrite = True if self.get_argument('overwrite', False) else False if safe_user: self.media_section = url_factory.clean_filename( self.get_argument('section')) if self.media_section.startswith(url_factory.resource_url(self)): self.media_section = self.media_section[len( url_factory.resource_url(self)) + 1:] self.parent_directory = url_factory.resource_directory(self, self.media_section) self.parent_url = url_factory.resource_url(self, self.media_section) if self.media_section == 'themes': test_zip_path_name = os.path.join(self.parent_directory, self.base_leafname) split_path = os.path.splitext(test_zip_path_name) if os.path.exists(test_zip_path_name): os.remove(test_zip_path_name) if os.path.exists(split_path[0]) and os.path.isdir(split_path[0]): shutil.rmtree(split_path[0]) else: self.parent_directory = os.path.join( self.application.settings["resource_path"], 'remote') self.parent_url = os.path.join( self.application.settings["resource_url"], 'remote') self.full_path = os.path.join(self.parent_directory, self.base_leafname) if not overwrite: self.full_path = media.get_unique_name(self.full_path) if not os.path.isdir(self.parent_directory): os.makedirs(self.parent_directory) if self.chunked_upload and safe_user: f = open(self.tmp_path, 'w') f.write(uploaded_file['body']) f.close() total_chunks_uploaded = 0 for f in os.listdir(self.tmp_dir): if f.startswith(self.base_leafname): total_chunks_uploaded += 1 if total_chunks_uploaded == max(self.total_size / self.chunk_size, 1): final_file = open(self.full_path, 'w') for f in os.listdir(self.tmp_dir): if f.startswith(self.base_leafname): chunk_path = os.path.join(self.tmp_dir, f) chunk_file = open(chunk_path, 'r') final_file.write(chunk_file.read()) chunk_file.close() os.unlink(chunk_path) final_file.close() original_size_url, url, thumb_url = media.save_locally( self.parent_url, self.full_path, None, skip_write=True, overwrite=overwrite) else: return else: original_size_url, url, thumb_url = media.save_locally( self.parent_url, self.full_path, uploaded_file['body'], disallow_zip=(not safe_user), overwrite=overwrite) media_html = media.generate_full_html(self, url, original_size_url) self.set_header("Content-Type", "text/plain; charset=UTF-8") self.write(json.dumps({ 'original_size_url': original_size_url, \ 'url': url, \ 'thumb_url': thumb_url, \ 'html': media_html, }))
def post(self): if not self.authenticate(author=True): return op = self.get_argument('op', None) if op == 'favorite': self.favorite() return self.user = self.get_author_user() access_token = self.user.facebook title = self.get_argument('title', '') view = self.get_argument('view', '') status = (content_remote.strip_html(title) + ('\n' if title and view else '') + content_remote.strip_html(view.replace('<br>', ' ')) + ('\n' if title or view else '') + self.get_argument('url')) post_args = {"message": status} thumb = self.get_argument('thumb', '') picture = None if thumb: if not thumb.startswith('http://'): thumb = url_factory.clean_filename(thumb) thumb = thumb[len(url_factory.resource_url(self)) + 1:] thumb = url_factory.resource_directory(self, thumb) picture = thumb basename = os.path.basename(thumb) dirname = os.path.dirname(thumb) if os.path.basename(dirname) == 'thumbs': parent_dir = os.path.dirname(dirname) original_dir = os.path.join(parent_dir, 'original') original_img = os.path.join(original_dir, basename) if os.path.exists(original_img): picture = original_img picture = picture[len(self.application.settings["static_path"]) + 1:] picture = self.static_url(picture, include_host=True) else: picture = thumb if picture: post_args['picture'] = picture video = re.compile(r'<iframe[^>]*(youtube|vimeo)[^>]*>.*?</iframe>', re.M | re.S).search(view) if video: video = video.group(0) is_youtube = re.compile(r'<iframe[^>]*(youtube)[^>]*>', re.M).search( view) if is_youtube: video_id = re.compile(r'<iframe[^>]*youtube.com/embed/([^\?]*)[^>]*>', re.M).search(view).group(1) source = 'http://www.youtube.com/e/' + video_id + '?autoplay=1' else: video_id = re.compile(r'<iframe[^>]*vimeo.com/video/([^\?"]*)[^>]*>', re.M).search(view).group(1) source = ('https://secure.vimeo.com/moogaloop.swf?clip_id=' + video_id + '&autoplay=1') post_args['source'] = source self.facebook_request( "/me/feed", self.status_update_result, access_token=access_token, post_args=post_args,)
def post(self): if not self.authenticate(author=True): return op = self.get_argument('op', None) if op == 'favorite': self.favorite() return access_token, tumblr_info = self.get_tumblr_info() title = content_remote.strip_html(self.get_argument('title', '')) body = url_factory.add_base_uris(self, self.get_argument('view', '')) \ + '\n' \ + self.get_argument('url') post_args = {"type": "text", "title": title, "body": body} # TODO, refactor out w FB logic thumb = self.get_argument('thumb', '') picture = None normal_picture = None if thumb: if not thumb.startswith('http://'): thumb = url_factory.clean_filename(thumb) thumb = thumb[len(url_factory.resource_url(self)) + 1:] thumb = url_factory.resource_directory(self, thumb) picture = thumb basename = os.path.basename(thumb) dirname = os.path.dirname(thumb) if os.path.basename(dirname) == 'thumbs': parent_dir = os.path.dirname(dirname) original_dir = os.path.join(parent_dir, 'original') original_img = os.path.join(original_dir, basename) if os.path.exists(original_img): picture = original_img normal_path = os.path.join(parent_dir, basename) if os.path.exists(normal_path): normal_picture = normal_path normal_picture = normal_picture[ len(self.application.settings["static_path"]) + 1:] normal_picture = self.static_url(normal_picture, include_host=True, include_sig=False) picture = picture[len(self.application.settings["static_path"] ) + 1:] picture = self.static_url(picture, include_host=True, include_sig=False) else: picture = thumb video = re.compile(r'<iframe[^>]*(youtube|vimeo)[^>]*>.*?</iframe>', re.M | re.S).search(body) if picture and normal_picture and not video: post_args["source"] = picture post_args["link"] = self.get_argument('url') post_args["caption"] = re.compile( r'(<figure>.*?<img.*?src="' + normal_picture + r'".*?>.*?</figure>)', re.M | re.U | re.S).sub('', body) post_args["type"] = "photo" if video: video = video.group(0) post_args["embed"] = video post_args["caption"] = body.replace(video, '') post_args["type"] = "video" section = self.get_argument('section', '') album = self.get_argument('album', '') tags = re.compile(r'#(\w+)(?![^<&]*(?:[>;]))', re.M | re.U).findall(body) post_args["tags"] = "" if tags: post_args["tags"] += ','.join(tags) if section: post_args["tags"] += "," + section if album: post_args["tags"] += "," + album self.tumblr_request( "http://api.tumblr.com/v2/blog/" + tumblr_info['primary_blog'] + "/post", self.status_update_result, access_token=access_token, post_args=post_args, )
def save_locally(parent_url, full_path, data, skip_write=False, disallow_zip=False, overwrite=False): # check dupe if not skip_write and not overwrite: full_path = get_unique_name(full_path) media_type = detect_media_type(full_path) original_size_url = '' url = os.path.join(parent_url, os.path.split(full_path)[1]) thumb_url = '' if media_type == 'image': split_path = os.path.split(full_path) splitext_path = os.path.splitext(full_path) thumb_dir = os.path.join(split_path[0], 'thumbs') original_size_dir = os.path.join(split_path[0], 'original') leaf_name = os.path.split(full_path)[1] if not os.path.isdir(thumb_dir): os.makedirs(thumb_dir) if not os.path.isdir(original_size_dir): os.makedirs(original_size_dir) thumb_filename = os.path.join(thumb_dir, leaf_name) if not overwrite: thumb_filename = get_unique_name(thumb_filename) original_size_filename = os.path.join(original_size_dir, leaf_name) if not overwrite: original_size_filename = get_unique_name(original_size_filename) thumb_url = os.path.join(os.path.join(parent_url, 'thumbs'), os.path.split(thumb_filename)[1]) original_size_url = os.path.join(os.path.join(parent_url, 'original'), os.path.split(original_size_filename)[1]) if skip_write: os.rename(full_path, original_size_filename) else: f = open(original_size_filename, 'w+') f.write(data) f.close() is_animated = False if splitext_path[1] == '.apng': is_animated = True elif splitext_path[1] == '.gif': gif = Image.open(original_size_filename) try: gif.seek(1) except EOFError: is_animated = False else: is_animated = True if not is_animated: original_img = Image.open(original_size_filename) try: info = original_img._getexif() except: info = None exif = {} if info: for tag, value in info.items(): decoded = TAGS.get(tag, tag) exif[decoded] = value if 'Orientation' in exif: orientation = exif['Orientation'] changed = True if orientation == 1: changed = False elif orientation == 2: # Vertical Mirror original_img = original_img.transpose(Image.FLIP_LEFT_RIGHT) elif orientation == 3: # Rotation 180 original_img = original_img.transpose(Image.ROTATE_180) elif orientation == 4: # Horizontal Mirror original_img = original_img.transpose(Image.FLIP_TOP_BOTTOM) elif orientation == 5: # Horizontal Mirror + Rotation 270 original_img = original_img.transpose( Image.FLIP_TOP_BOTTOM).transpose(Image.ROTATE_270) elif orientation == 6: # Rotation 270 original_img = original_img.transpose(Image.ROTATE_270) elif orientation == 7: # Vertical Mirror + Rotation 270 original_img = original_img.transpose( Image.FLIP_LEFT_RIGHT).transpose(Image.ROTATE_270) elif orientation == 8: # Rotation 90 original_img = original_img.transpose(Image.ROTATE_90) if changed: original_img.save(original_size_filename, quality=95) thumb = Image.open(original_size_filename) thumb.thumbnail((content_logic.THUMB_WIDTH, content_logic.THUMB_HEIGHT), Image.ANTIALIAS) thumb.save(thumb_filename, quality=95) if not is_animated: normal = Image.open(original_size_filename) normal.thumbnail((content_logic.PHOTO_WIDTH, content_logic.PHOTO_HEIGHT), Image.ANTIALIAS) normal.save(full_path, quality=95) else: shutil.copyfile(original_size_filename, full_path) else: if not skip_write: f = open(full_path, 'w') f.write(data) f.close() splitext_path = os.path.splitext(full_path) if splitext_path[1] == '.zip' and not disallow_zip: z = zipfile.ZipFile(full_path) dir_path = os.path.join(os.path.dirname(full_path), splitext_path[0]) for f in z.namelist(): filename = url_factory.clean_filename(f) if f.endswith('/'): os.makedirs(os.path.join(dir_path, filename)) else: if detect_media_type(filename) not in ('video', 'image', 'audio', 'web', 'zip'): raise tornado.web.HTTPError(400, "i call shenanigans") z.extract(filename, dir_path) return original_size_url, url, thumb_url
def post(self): safe_user = False if self.authenticate(author=True): safe_user = True self.get_common_parameters() if safe_user: if media.detect_media_type( self.base_leafname) not in ('video', 'image', 'audio', 'web', 'zip'): raise tornado.web.HTTPError(400, "i call shenanigans") else: if media.detect_media_type(self.base_leafname) != 'image': raise tornado.web.HTTPError(400, "i call shenanigans") if self.get_argument('canvasImage', None): uploaded_file = self.get_argument('canvasImage') else: uploaded_file = self.request.files['file'][0] overwrite = True if self.get_argument('overwrite', False) else False if safe_user: self.media_section = url_factory.clean_filename( self.get_argument('section')) if self.media_section.startswith(url_factory.resource_url(self)): self.media_section = self.media_section[ len(url_factory.resource_url(self)) + 1:] self.parent_directory = url_factory.resource_directory( self, self.media_section) self.parent_url = url_factory.resource_url(self, self.media_section) if self.media_section == 'themes': test_zip_path_name = os.path.join(self.parent_directory, self.base_leafname) split_path = os.path.splitext(test_zip_path_name) if os.path.exists(test_zip_path_name): os.remove(test_zip_path_name) if os.path.exists(split_path[0]) and os.path.isdir( split_path[0]): shutil.rmtree(split_path[0]) else: self.parent_directory = os.path.join( self.application.settings["resource_path"], 'remote') self.parent_url = os.path.join( self.application.settings["resource_url"], 'remote') self.full_path = os.path.join(self.parent_directory, self.base_leafname) if not overwrite: self.full_path = media.get_unique_name(self.full_path) if not os.path.isdir(self.parent_directory): os.makedirs(self.parent_directory) if self.chunked_upload and safe_user: f = open(self.tmp_path, 'w') f.write(uploaded_file['body']) f.close() total_chunks_uploaded = 0 for f in os.listdir(self.tmp_dir): if f.startswith(self.base_leafname): total_chunks_uploaded += 1 if total_chunks_uploaded == max(self.total_size / self.chunk_size, 1): final_file = open(self.full_path, 'w') for f in os.listdir(self.tmp_dir): if f.startswith(self.base_leafname): chunk_path = os.path.join(self.tmp_dir, f) chunk_file = open(chunk_path, 'r') final_file.write(chunk_file.read()) chunk_file.close() os.unlink(chunk_path) final_file.close() original_size_url, url, thumb_url = media.save_locally( self.parent_url, self.full_path, None, skip_write=True, overwrite=overwrite) else: return else: original_size_url, url, thumb_url = media.save_locally( self.parent_url, self.full_path, uploaded_file['body'], disallow_zip=(not safe_user), overwrite=overwrite) media_html = media.generate_full_html(self, url, original_size_url) self.set_header("Content-Type", "text/plain; charset=UTF-8") self.write(json.dumps({ 'original_size_url': original_size_url, \ 'url': url, \ 'thumb_url': thumb_url, \ 'html': media_html, }))
def save_locally(parent_url, full_path, data, skip_write=False, disallow_zip=False, overwrite=False): # check dupe if not skip_write and not overwrite: full_path = get_unique_name(full_path) media_type = detect_media_type(full_path) original_size_url = '' url = os.path.join(parent_url, os.path.split(full_path)[1]) thumb_url = '' if media_type == 'image': split_path = os.path.split(full_path) splitext_path = os.path.splitext(full_path) thumb_dir = os.path.join(split_path[0], 'thumbs') original_size_dir = os.path.join(split_path[0], 'original') leaf_name = os.path.split(full_path)[1] if not os.path.isdir(thumb_dir): os.makedirs(thumb_dir) if not os.path.isdir(original_size_dir): os.makedirs(original_size_dir) thumb_filename = os.path.join(thumb_dir, leaf_name) if not overwrite: thumb_filename = get_unique_name(thumb_filename) original_size_filename = os.path.join(original_size_dir, leaf_name) if not overwrite: original_size_filename = get_unique_name(original_size_filename) thumb_url = os.path.join(os.path.join(parent_url, 'thumbs'), os.path.split(thumb_filename)[1]) original_size_url = os.path.join( os.path.join(parent_url, 'original'), os.path.split(original_size_filename)[1]) if skip_write: os.rename(full_path, original_size_filename) else: f = open(original_size_filename, 'w+') f.write(data) f.close() is_animated = False if splitext_path[1] == '.apng': is_animated = True elif splitext_path[1] == '.gif': gif = Image.open(original_size_filename) try: gif.seek(1) except EOFError: is_animated = False else: is_animated = True if not is_animated: original_img = Image.open(original_size_filename) try: info = original_img._getexif() except: info = None exif = {} if info: for tag, value in info.items(): decoded = TAGS.get(tag, tag) exif[decoded] = value if 'Orientation' in exif: orientation = exif['Orientation'] changed = True if orientation == 1: changed = False elif orientation == 2: # Vertical Mirror original_img = original_img.transpose( Image.FLIP_LEFT_RIGHT) elif orientation == 3: # Rotation 180 original_img = original_img.transpose(Image.ROTATE_180) elif orientation == 4: # Horizontal Mirror original_img = original_img.transpose( Image.FLIP_TOP_BOTTOM) elif orientation == 5: # Horizontal Mirror + Rotation 270 original_img = original_img.transpose( Image.FLIP_TOP_BOTTOM).transpose(Image.ROTATE_270) elif orientation == 6: # Rotation 270 original_img = original_img.transpose(Image.ROTATE_270) elif orientation == 7: # Vertical Mirror + Rotation 270 original_img = original_img.transpose( Image.FLIP_LEFT_RIGHT).transpose(Image.ROTATE_270) elif orientation == 8: # Rotation 90 original_img = original_img.transpose(Image.ROTATE_90) if changed: original_img.save(original_size_filename, quality=95) thumb = Image.open(original_size_filename) thumb.thumbnail( (content_logic.THUMB_WIDTH, content_logic.THUMB_HEIGHT), Image.ANTIALIAS) thumb.save(thumb_filename, quality=95) if not is_animated: normal = Image.open(original_size_filename) normal.thumbnail( (content_logic.PHOTO_WIDTH, content_logic.PHOTO_HEIGHT), Image.ANTIALIAS) normal.save(full_path, quality=95) else: shutil.copyfile(original_size_filename, full_path) else: if not skip_write: f = open(full_path, 'w') f.write(data) f.close() splitext_path = os.path.splitext(full_path) if splitext_path[1] == '.zip' and not disallow_zip: z = zipfile.ZipFile(full_path) dir_path = os.path.join(os.path.dirname(full_path), splitext_path[0]) for f in z.namelist(): filename = url_factory.clean_filename(f) if f.endswith('/'): os.makedirs(os.path.join(dir_path, filename)) else: if detect_media_type(filename) not in ('video', 'image', 'audio', 'web', 'zip'): raise tornado.web.HTTPError(400, "i call shenanigans") z.extract(filename, dir_path) return original_size_url, url, thumb_url