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 # Set to false to disable registrations
allow_registration = true 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 ## Uncomment this to put some user-overriding templates here
# local_templates = %(here)s/user_dev/templates/ # 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 # link to source for this MediaGoblin site
source_link = string(default="https://gitorious.org/mediagoblin/mediagoblin") source_link = string(default="https://gitorious.org/mediagoblin/mediagoblin")
# Enabled media types
media_types = string_list(default=list("mediagoblin.media_types.image"))
# database stuff # database stuff
sql_engine = string(default="sqlite:///%(here)s/mediagoblin.db") sql_engine = string(default="sqlite:///%(here)s/mediagoblin.db")

View File

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

View File

@ -52,10 +52,6 @@ class DatabaseMaster(object):
def load_models(app_config): def load_models(app_config):
import mediagoblin.db.models 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(): for plugin in mg_globals.global_config.get('plugins', {}).keys():
_log.debug("Loading %s.models", plugin) _log.debug("Loading %s.models", plugin)
try: try:

View File

@ -42,7 +42,7 @@ class DatabaseData(object):
self.name, self.models, self.migrations, session) 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 Gather all database data relevant to the extensions we have
installed so we can do migrations and table initialization. installed so we can do migrations and table initialization.
@ -59,13 +59,6 @@ def gather_database_data(media_types, plugins):
DatabaseData( DatabaseData(
u'__main__', MAIN_MODELS, MAIN_MIGRATIONS)) 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: for plugin in plugins:
try: try:
models = import_component('{0}.models:MODELS'.format(plugin)) 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 # Gather information from all media managers / projects
dbdatas = gather_database_data( dbdatas = gather_database_data(
app_config['media_types'],
global_config.get('plugins', {}).keys()) global_config.get('plugins', {}).keys())
# Set up the database # Set up the database

View File

@ -15,12 +15,10 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
import os import os
import sys
import logging import logging
import tempfile import tempfile
from mediagoblin import mg_globals from mediagoblin.tools.pluginapi import hook_handle
from mediagoblin.tools.common import import_component
from mediagoblin.tools.translate import lazy_pass_to_ugettext as _ from mediagoblin.tools.translate import lazy_pass_to_ugettext as _
_log = logging.getLogger(__name__) _log = logging.getLogger(__name__)
@ -98,11 +96,10 @@ def sniff_media(media):
media_file.write(media.stream.read()) media_file.write(media.stream.read())
media.stream.seek(0) media.stream.seek(0)
for media_type, manager in get_media_managers(): media_type = hook_handle('sniff_handler', media_file, media=media)
_log.info('Sniffing {0}'.format(media_type)) if media_type:
if manager.sniff_handler(media_file, media=media):
_log.info('{0} accepts the file'.format(media_type)) _log.info('{0} accepts the file'.format(media_type))
return media_type, manager return media_type, hook_handle('get_media_managers', media_type)
else: else:
_log.debug('{0} did not accept the file'.format(media_type)) _log.debug('{0} did not accept the file'.format(media_type))
@ -111,27 +108,6 @@ def sniff_media(media):
_(u'Sorry, I don\'t support that file type :(')) _(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): def get_media_type_and_manager(filename):
''' '''
Try to find the media type based on the file name, extension 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 # Get the file extension
ext = os.path.splitext(filename)[1].lower() 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 # Omit the dot from the extension and match it against
# the media manager # the media manager
if ext[1:] in manager.accepted_extensions: if hook_handle('get_media_type_and_manager', ext[1:]):
return media_type, manager return hook_handle('get_media_type_and_manager', ext[1:])
else: else:
_log.info('File {0} has no file extension, let\'s hope the sniffers get it.'.format( _log.info('File {0} has no file extension, let\'s hope the sniffers get it.'.format(
filename)) filename))

View File

@ -13,12 +13,20 @@
# #
# You should have received a copy of the GNU Affero General Public License # 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/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
import datetime import datetime
from mediagoblin.media_types import MediaManagerBase from mediagoblin.media_types import MediaManagerBase
from mediagoblin.media_types.image.processing import process_image, \ from mediagoblin.media_types.image.processing import process_image, \
sniff_handler 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): class ImageMediaManager(MediaManagerBase):
@ -27,7 +35,7 @@ class ImageMediaManager(MediaManagerBase):
sniff_handler = staticmethod(sniff_handler) sniff_handler = staticmethod(sniff_handler)
display_template = "mediagoblin/media_displays/image.html" display_template = "mediagoblin/media_displays/image.html"
default_thumb = "images/media_thumbs/image.png" default_thumb = "images/media_thumbs/image.png"
accepted_extensions = ["jpg", "jpeg", "png", "gif", "tiff"]
media_fetch_order = [u'medium', u'original', u'thumb'] media_fetch_order = [u'medium', u'original', u'thumb']
def get_original_date(self): def get_original_date(self):
@ -52,4 +60,19 @@ class ImageMediaManager(MediaManagerBase):
return None 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, 'BICUBIC': Image.BICUBIC,
'ANTIALIAS': Image.ANTIALIAS} 'ANTIALIAS': Image.ANTIALIAS}
MEDIA_TYPE = 'mediagoblin.media_types.image'
def resize_image(proc_state, resized, keyname, target_name, new_size, def resize_image(proc_state, resized, keyname, target_name, new_size,
exif_tags, workdir): exif_tags, workdir):
@ -99,13 +101,14 @@ SUPPORTED_FILETYPES = ['png', 'gif', 'jpg', 'jpeg']
def sniff_handler(media_file, **kw): 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! if kw.get('media') is not None: # That's a double negative!
name, ext = os.path.splitext(kw['media'].filename) name, ext = os.path.splitext(kw['media'].filename)
clean_ext = ext[1:].lower() # Strip the . from ext and make lowercase clean_ext = ext[1:].lower() # Strip the . from ext and make lowercase
if clean_ext in SUPPORTED_FILETYPES: if clean_ext in SUPPORTED_FILETYPES:
_log.info('Found file extension in supported filetypes') _log.info('Found file extension in supported filetypes')
return True return MEDIA_TYPE
else: else:
_log.debug('Media present, extension not found in {0}'.format( _log.debug('Media present, extension not found in {0}'.format(
SUPPORTED_FILETYPES)) SUPPORTED_FILETYPES))
@ -113,7 +116,7 @@ def sniff_handler(media_file, **kw):
_log.warning('Need additional information (keyword argument \'media\')' _log.warning('Need additional information (keyword argument \'media\')'
' to be able to handle sniffing') ' to be able to handle sniffing')
return False return None
def process_image(proc_state): 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) 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( return render_to_response(
request, request,