modified gmg to use plugin media_types and converted image media_type to new plugin style

This commit is contained in:
Rodney Ewing 2013-07-01 17:19:22 -07:00
parent e9f3306627
commit 58a947578c
9 changed files with 52 additions and 74 deletions

View File

@ -19,11 +19,6 @@ email_debug_mode = true
# Set to false to disable registrations
allow_registration = true
## Uncomment this to turn on video or enable other media types
## You may have to install dependencies, and will have to run ./bin/gmg dbupdate
## See http://docs.mediagoblin.org/siteadmin/media-types.html for details.
# media_types = mediagoblin.media_types.image, mediagoblin.media_types.video
## Uncomment this to put some user-overriding templates here
# local_templates = %(here)s/user_dev/templates/

View File

@ -5,9 +5,6 @@ html_title = string(default="GNU MediaGoblin")
# link to source for this MediaGoblin site
source_link = string(default="https://gitorious.org/mediagoblin/mediagoblin")
# Enabled media types
media_types = string_list(default=list("mediagoblin.media_types.image"))
# database stuff
sql_engine = string(default="sqlite:///%(here)s/mediagoblin.db")

View File

@ -29,15 +29,14 @@ real objects.
import uuid
import re
import datetime
from datetime import datetime
from werkzeug.utils import cached_property
from mediagoblin import mg_globals
from mediagoblin.media_types import get_media_managers, FileTypeNotSupported
from mediagoblin.media_types import FileTypeNotSupported
from mediagoblin.tools import common, licenses
from mediagoblin.tools.pluginapi import hook_handle
from mediagoblin.tools.text import cleaned_markdown_conversion
from mediagoblin.tools.url import slugify
@ -204,14 +203,12 @@ class MediaEntryMixin(GenerateSlugMixin):
Raises FileTypeNotSupported in case no such manager is enabled
"""
# TODO, we should be able to make this a simple lookup rather
# than iterating through all media managers.
for media_type, manager in get_media_managers():
if media_type == self.media_type:
return manager(self)
manager = hook_handle('get_media_manager', self.media_type)
if manager:
return manager
# Not found? Then raise an error
raise FileTypeNotSupported(
"MediaManager not in enabled types. Check media_types in config?")
"MediaManager not in enabled types. Check media_types in config?")
def get_fail_exception(self):
"""

View File

@ -52,10 +52,6 @@ class DatabaseMaster(object):
def load_models(app_config):
import mediagoblin.db.models
for media_type in app_config['media_types']:
_log.debug("Loading %s.models", media_type)
__import__(media_type + ".models")
for plugin in mg_globals.global_config.get('plugins', {}).keys():
_log.debug("Loading %s.models", plugin)
try:

View File

@ -42,7 +42,7 @@ class DatabaseData(object):
self.name, self.models, self.migrations, session)
def gather_database_data(media_types, plugins):
def gather_database_data(plugins):
"""
Gather all database data relevant to the extensions we have
installed so we can do migrations and table initialization.
@ -59,13 +59,6 @@ def gather_database_data(media_types, plugins):
DatabaseData(
u'__main__', MAIN_MODELS, MAIN_MIGRATIONS))
# Then get all registered media managers (eventually, plugins)
for media_type in media_types:
models = import_component('%s.models:MODELS' % media_type)
migrations = import_component('%s.migrations:MIGRATIONS' % media_type)
managed_dbdata.append(
DatabaseData(media_type, models, migrations))
for plugin in plugins:
try:
models = import_component('{0}.models:MODELS'.format(plugin))
@ -112,7 +105,6 @@ def run_dbupdate(app_config, global_config):
# Gather information from all media managers / projects
dbdatas = gather_database_data(
app_config['media_types'],
global_config.get('plugins', {}).keys())
# Set up the database

View File

@ -15,12 +15,10 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import sys
import logging
import tempfile
from mediagoblin import mg_globals
from mediagoblin.tools.common import import_component
from mediagoblin.tools.pluginapi import hook_handle
from mediagoblin.tools.translate import lazy_pass_to_ugettext as _
_log = logging.getLogger(__name__)
@ -56,7 +54,7 @@ class CompatMediaManager(object):
def __init__(self, mm_dict, entry=None):
self.mm_dict = mm_dict
self.entry = entry
def __call__(self, entry):
"So this object can look like a class too, somehow"
assert self.entry is None
@ -98,40 +96,18 @@ def sniff_media(media):
media_file.write(media.stream.read())
media.stream.seek(0)
for media_type, manager in get_media_managers():
_log.info('Sniffing {0}'.format(media_type))
if manager.sniff_handler(media_file, media=media):
_log.info('{0} accepts the file'.format(media_type))
return media_type, manager
else:
_log.debug('{0} did not accept the file'.format(media_type))
media_type = hook_handle('sniff_handler', media_file, media=media)
if media_type:
_log.info('{0} accepts the file'.format(media_type))
return media_type, hook_handle('get_media_managers', media_type)
else:
_log.debug('{0} did not accept the file'.format(media_type))
raise FileTypeNotSupported(
# TODO: Provide information on which file types are supported
_(u'Sorry, I don\'t support that file type :('))
def get_media_types():
"""
Generator, yields the available media types
"""
for media_type in mg_globals.app_config['media_types']:
yield media_type
def get_media_managers():
'''
Generator, yields all enabled media managers
'''
for media_type in get_media_types():
mm = import_component(media_type + ":MEDIA_MANAGER")
if isinstance(mm, dict):
mm = CompatMediaManager(mm)
yield media_type, mm
def get_media_type_and_manager(filename):
'''
Try to find the media type based on the file name, extension
@ -142,11 +118,10 @@ def get_media_type_and_manager(filename):
# Get the file extension
ext = os.path.splitext(filename)[1].lower()
for media_type, manager in get_media_managers():
# Omit the dot from the extension and match it against
# the media manager
if ext[1:] in manager.accepted_extensions:
return media_type, manager
# Omit the dot from the extension and match it against
# the media manager
if hook_handle('get_media_type_and_manager', ext[1:]):
return hook_handle('get_media_type_and_manager', ext[1:])
else:
_log.info('File {0} has no file extension, let\'s hope the sniffers get it.'.format(
filename))

View File

@ -13,12 +13,20 @@
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import datetime
from mediagoblin.media_types import MediaManagerBase
from mediagoblin.media_types.image.processing import process_image, \
sniff_handler
from mediagoblin.tools import pluginapi
ACCEPTED_EXTENSIONS = ["jpg", "jpeg", "png", "gif", "tiff"]
MEDIA_TYPE = 'mediagoblin.media_types.image'
def setup_plugin():
config = pluginapi.get_config('mediagoblin.pluginapi.media_types.image')
class ImageMediaManager(MediaManagerBase):
@ -27,9 +35,9 @@ class ImageMediaManager(MediaManagerBase):
sniff_handler = staticmethod(sniff_handler)
display_template = "mediagoblin/media_displays/image.html"
default_thumb = "images/media_thumbs/image.png"
accepted_extensions = ["jpg", "jpeg", "png", "gif", "tiff"]
media_fetch_order = [u'medium', u'original', u'thumb']
def get_original_date(self):
"""
Get the original date and time from the EXIF information. Returns
@ -52,4 +60,19 @@ class ImageMediaManager(MediaManagerBase):
return None
MEDIA_MANAGER = ImageMediaManager
def get_media_manager(media_type):
if media_type == MEDIA_TYPE:
return ImageMediaManager
def get_media_type_and_manager(ext):
if ext in ACCEPTED_EXTENSIONS:
return ImageMediaManager
hooks = {
'setup': setup_plugin,
'extensions': get_media_type_and_manager,
'sniff_handler': sniff_handler,
'get_media_manager': get_media_manager,
}

View File

@ -35,6 +35,8 @@ PIL_FILTERS = {
'BICUBIC': Image.BICUBIC,
'ANTIALIAS': Image.ANTIALIAS}
MEDIA_TYPE = 'mediagoblin.media_types.image'
def resize_image(proc_state, resized, keyname, target_name, new_size,
exif_tags, workdir):
@ -99,13 +101,14 @@ SUPPORTED_FILETYPES = ['png', 'gif', 'jpg', 'jpeg']
def sniff_handler(media_file, **kw):
_log.info('Sniffing {0}'.format(MEDIA_TYPE))
if kw.get('media') is not None: # That's a double negative!
name, ext = os.path.splitext(kw['media'].filename)
clean_ext = ext[1:].lower() # Strip the . from ext and make lowercase
if clean_ext in SUPPORTED_FILETYPES:
_log.info('Found file extension in supported filetypes')
return True
return MEDIA_TYPE
else:
_log.debug('Media present, extension not found in {0}'.format(
SUPPORTED_FILETYPES))
@ -113,7 +116,7 @@ def sniff_handler(media_file, **kw):
_log.warning('Need additional information (keyword argument \'media\')'
' to be able to handle sniffing')
return False
return None
def process_image(proc_state):

View File

@ -142,7 +142,7 @@ def media_home(request, media, page, **kwargs):
comment_form = user_forms.MediaCommentForm(request.form)
media_template_name = media.media_manager['display_template']
media_template_name = media.media_manager.display_template
return render_to_response(
request,