Skip to content

Commit

Permalink
code + tests
Browse files Browse the repository at this point in the history
  • Loading branch information
ishirav committed Nov 18, 2015
1 parent 3a85e82 commit 3c4bf68
Show file tree
Hide file tree
Showing 16 changed files with 282 additions and 0 deletions.
57 changes: 57 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]

# C extensions
*.so

# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*,cover

# Translations
*.mo
*.pot

# Django stuff:
*.log

# Sphinx documentation
docs/_build/

# PyBuilder
target/
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2015 Thumbor Community Extensions

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
2 changes: 2 additions & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[metadata]
description-file = README.md
34 changes: 34 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# -*- coding: utf-8 -*-

from setuptools import setup


setup(
name='tc_video',
version='0.1.0',
url='http://github.com/thumbor_community/video',
license='MIT',
author='Thumbor Community',
description='Thumbor community video extensions',
packages=['tc_video'],
include_package_data=True,
zip_safe=False,
platforms='any',
install_requires=[
'thumbor>=5.0.6',
],
extras_require={
'tests': [
'pyvows',
'coverage',
],
},
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
Empty file added tc_video/__init__.py
Empty file.
Empty file added tc_video/loaders/__init__.py
Empty file.
84 changes: 84 additions & 0 deletions tc_video/loaders/file_loader.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
# coding: utf-8

# Copyright (c) 2015, thumbor-community
# Use of this source code is governed by the MIT license that can be
# found in the LICENSE file.

from thumbor.loaders import LoaderResult
from datetime import datetime
from os import fstat
from os.path import join, exists, abspath
from urllib import unquote
from tornado.concurrent import return_future


@return_future
def load(context, path, callback):
"""
Loads a file. In case the requested file is a video, instead of loading
its contents this method extracts a frame from the video using ffmpeg,
and returns the image.
:param Context context: Thumbor's context
:param string url: Path to load
:param callable callback: Callback method once done
"""
file_path = join(context.config.FILE_LOADER_ROOT_PATH.rstrip('/'), unquote(path).lstrip('/'))
file_path = abspath(file_path)
inside_root_path = file_path.startswith(context.config.FILE_LOADER_ROOT_PATH)

result = LoaderResult()

if inside_root_path and exists(file_path):

# If this is a video, extract a frame and load it instead
if is_video(file_path):
file_path = get_video_frame(context, file_path)

with open(file_path, 'r') as f:
stats = fstat(f.fileno())

result.successful = True
result.buffer = f.read()

result.metadata.update(
size=stats.st_size,
updated_at=datetime.utcfromtimestamp(stats.st_mtime)
)
else:
result.error = LoaderResult.ERROR_NOT_FOUND
result.successful = False

callback(result)


def is_video(file_path):
"""
Checks whether the file is a video.
"""
import mimetypes
type = mimetypes.guess_type(file_path)[0]
return type and type.startswith('video')


def get_video_frame(context, file_path):
"""
Extracts a single frame out of a video file and stores it
in a temporary file. Returns the path of the temporary file.
Depends on FFMPEG_PATH from Thumbor's configuration.
"""
import subprocess, tempfile, os
f, image_path = tempfile.mkstemp('.jpg')
os.close(f)
cmd = [
context.config.FFMPEG_PATH,
'-i', file_path,
'-ss', '00:00:01.000',
'-vframes', '1',
'-y',
'-nostats',
'-loglevel', 'error',
image_path
]
subprocess.call(cmd)
print image_path
return image_path
Empty file added tests/__init__.py
Empty file.
Binary file added tests/fixtures/images/image.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added tests/fixtures/videos/small.3gp
Binary file not shown.
Binary file added tests/fixtures/videos/small.flv
Binary file not shown.
Binary file added tests/fixtures/videos/small.mp4
Binary file not shown.
Binary file added tests/fixtures/videos/small.ogv
Binary file not shown.
Binary file added tests/fixtures/videos/small.webm
Binary file not shown.
Empty file added tests/loaders/__init__.py
Empty file.
84 changes: 84 additions & 0 deletions tests/loaders/test_file_loader.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-

# thumbor imaging service
# https://github.com/thumbor/thumbor/wiki

# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com [email protected]

from os.path import abspath, join, dirname

from unittest import TestCase
from preggy import expect
import imghdr

from thumbor.context import Context
from thumbor.config import Config
from tc_video.loaders.file_loader import load
from thumbor.loaders import LoaderResult

IMAGE_STORAGE_PATH = abspath(join(dirname(__file__), '../fixtures/images/'))
VIDEO_STORAGE_PATH = abspath(join(dirname(__file__), '../fixtures/videos/'))


class FileLoaderImageTestCase(TestCase):
def setUp(self):
config = Config(
FILE_LOADER_ROOT_PATH=IMAGE_STORAGE_PATH
)
self.ctx = Context(config=config)

def load_file(self, file_name):
return load(self.ctx, file_name, lambda x: x).result()

def test_should_load_file(self):
result = self.load_file('image.jpg')
expect(result).to_be_instance_of(LoaderResult)
expect(result.buffer).to_equal(open(join(IMAGE_STORAGE_PATH, 'image.jpg')).read())
expect(result.successful).to_be_true()

def test_should_fail_when_inexistent_file(self):
result = self.load_file('image_NOT.jpg')
expect(result).to_be_instance_of(LoaderResult)
expect(result.buffer).to_equal(None)
expect(result.successful).to_be_false()

def test_should_fail_when_outside_root_path(self):
result = self.load_file('../__init__.py')
expect(result).to_be_instance_of(LoaderResult)
expect(result.buffer).to_equal(None)
expect(result.successful).to_be_false()


class FileLoaderVideoTestCase(TestCase):
def setUp(self):
config = Config(
FILE_LOADER_ROOT_PATH=VIDEO_STORAGE_PATH,
FFMPEG_PATH = '/usr/bin/ffmpeg'
)
self.ctx = Context(config=config)

def load_file(self, file_name):
return load(self.ctx, file_name, lambda x: x).result()

def test_should_load_jpeg(self):
for ext in ('mp4', 'flv', '3gp', 'ogv', 'webm'):
result = self.load_file('small.' + ext)
expect(result).to_be_instance_of(LoaderResult)
expect(result.buffer[:2]).to_equal('\xFF\xD8') # look for jpeg header
expect(result.successful).to_be_true()

def test_should_fail_when_inexistent_file(self):
result = self.load_file('not_there.mp4')
expect(result).to_be_instance_of(LoaderResult)
expect(result.buffer).to_equal(None)
expect(result.successful).to_be_false()

def test_should_fail_when_outside_root_path(self):
result = self.load_file('../__init__.py')
expect(result).to_be_instance_of(LoaderResult)
expect(result.buffer).to_equal(None)
expect(result.successful).to_be_false()

0 comments on commit 3c4bf68

Please sign in to comment.