def save_media_obj(self, name, email, title, description, tags, uploaded_file, url): # create our media object as a status-less placeholder initially media_obj = Media() media_obj.author = Author(name, email) media_obj.title = title media_obj.slug = get_available_slug(Media, title) media_obj.description = description if request.settings['wording_display_administrative_notes']: media_obj.notes = request.settings['wording_administrative_notes'] media_obj.set_tags(tags) # Give the Media object an ID. DBSession.add(media_obj) DBSession.flush() # Create a MediaFile object, add it to the media_obj, and store the file permanently. media_file = add_new_media_file(media_obj, file=uploaded_file, url=url) # The thumbs may have been created already by add_new_media_file if not has_thumbs(media_obj): create_default_thumbs_for(media_obj) media_obj.update_status() DBSession.flush() return media_obj
def save(self, id, slug, title, author_name, author_email, description, notes, podcast, tags, categories, delete=None, **kwargs): """Save changes or create a new :class:`~mediacore.model.media.Media` instance. Form handler the :meth:`edit` action and the :class:`~mediacore.forms.admin.media.MediaForm`. Redirects back to :meth:`edit` after successful editing and :meth:`index` after successful deletion. """ media = fetch_row(Media, id) if delete: self._delete_media(media) DBSession.commit() redirect(action='index', id=None) if not slug: slug = title elif slug.startswith('_stub_'): slug = slug[len('_stub_'):] if slug != media.slug: media.slug = get_available_slug(Media, slug, media) media.title = title media.author = Author(author_name, author_email) media.description = description media.notes = notes media.podcast_id = podcast media.set_tags(tags) media.set_categories(categories) media.update_status() DBSession.add(media) DBSession.flush() if id == 'new' and not has_thumbs(media): create_default_thumbs_for(media) if request.is_xhr: status_form_xhtml = unicode(update_status_form.display( action=url_for(action='update_status', id=media.id), media=media)) return dict( media_id = media.id, values = {'slug': slug}, link = url_for(action='edit', id=media.id), status_form = status_form_xhtml, ) else: redirect(action='edit', id=media.id)
def get_videos_from_feed(feed): for entry in feed.entry: # Occasionally, there are issues with a video in a feed # not being available (region restrictions, etc) # If this happens, just move along. if not entry.media.player: log.debug('Video Feed Error: No player URL? %s' % entry) continue video_url = unicode(entry.media.player.url, "utf-8") if video_already_has_media_file(video_url): continue categories = kwargs.get('youtube.categories', None) tags = kwargs.get('youtube.tags', None) media = fetch_row(Media, u'new') user = request.environ['repoze.who.identity']['user'] media.author = Author(user.display_name, user.email_address) media.reviewed = True media.title = unicode(entry.media.title.text, "utf-8") if entry.media.description.text: encoded_description = unicode(entry.media.description.text, "utf-8") media.description = clean_xhtml(encoded_description) media.slug = get_available_slug(Media, media.title, media) if tags: media.set_tags(unicode(tags)) if categories: if not isinstance(categories, list): categories = [categories] media.set_categories(categories) try: media_file = add_new_media_file(media, url=video_url) except StorageError, e: log.debug('Video Feed Error: Error storing video: %s at %s' \ % e.message, video_url) continue if not has_thumbs(media): create_default_thumbs_for(media) media.title = media_file.display_name media.update_status() if auto_publish: media.reviewed = 1 media.encoded = 1 media.publishable = 1 media.created_on = datetime.now() media.modified_on = datetime.now() media.publish_on = datetime.now() DBSession.add(media) DBSession.flush()
def add_new_media_file(media, uploaded_file=None, url=None): """Create a new MediaFile for the provided Media object and File/URL and add it to that Media object's files list. Will also attempt to set up duration and thumbnails according to the 'use_embed_thumbnails' setting. :param media: The Media object to append the file to :type media: :class:`~mediacore.model.media.Media` instance :param uploaded_file: An object with 'filename' and 'file' properties. :type uploaded_file: Formencode uploaded file object. :param url: The URL to represent, if no file is given. :type url: unicode :returns: The created MediaFile (or None) """ if uploaded_file is not None: # Create a MediaFile object, add it to the video, and store the file permanently. media_file = media_file_from_filename(uploaded_file.filename) attach_and_store_media_file(media, media_file, uploaded_file.file) elif url is not None: # Looks like we were just given a URL. Create a MediaFile object with that URL. media_file, thumb_url, duration, title = media_file_from_url(url) media.files.append(media_file) if title and media.slug.startswith('_stub_'): media.title = title media.slug = get_available_slug(Media, title, media) # Do we have a useful duration? if duration and not media.duration: media.duration = duration # Do we need to create thumbs for an embedded media item? if thumb_url \ and asbool(app_globals.settings['use_embed_thumbnails']) \ and (not has_thumbs(media) or has_default_thumbs(media)): # Download the image into a buffer, wrap the buffer as a File-like # object, and create the thumbs. try: temp_img = urllib2.urlopen(thumb_url) file_like_img = StringIO(temp_img.read()) temp_img.close() create_thumbs_for(media, file_like_img, thumb_url) file_like_img.close() except urllib2.URLError, e: log.exception(e)
def add_new_media_file(media, file=None, url=None): """Create a MediaFile instance from the given file or URL. This function MAY modify the given media object. :type media: :class:`~mediacore.model.media.Media` instance :param media: The media object that this file or URL will belong to. :type file: :class:`cgi.FieldStorage` or None :param file: A freshly uploaded file object. :type url: unicode or None :param url: A remote URL string. :rtype: :class:`~mediacore.model.media.MediaFile` :returns: A newly created media file instance. :raises StorageError: If the input file or URL cannot be stored with any of the registered storage engines. """ engines = DBSession.query(StorageEngine)\ .filter(StorageEngine.enabled == True)\ .all() sorted_engines = list(sort_engines(engines)) for engine in sorted_engines: try: meta = engine.parse(file=file, url=url) log.debug('Engine %r returned meta %r', engine, meta) break except UnsuitableEngineError: log.debug('Engine %r unsuitable for %r/%r', engine, file, url) continue else: raise StorageError(_('Unusable file or URL provided.'), None, None) mf = MediaFile() mf.storage = engine mf.media = media mf.type = meta['type'] mf.display_name = meta.get('display_name', default_display_name(file, url)) mf.unique_id = meta.get('unique_id', None) mf.container = meta.get('container', None) mf.size = meta.get('size', None) mf.bitrate = meta.get('bitrate', None) mf.width = meta.get('width', None) mf.height = meta.get('height', None) media.files.append(mf) DBSession.flush() unique_id = engine.store(media_file=mf, file=file, url=url, meta=meta) if unique_id: mf.unique_id = unique_id elif not mf.unique_id: raise StorageError('Engine %r returned no unique ID.', engine) if not media.duration and meta.get('duration', 0): media.duration = meta['duration'] if not media.description and meta.get('description'): media.description = clean_xhtml(meta['description']) if not media.title: media.title = meta.get('title', None) or mf.display_name if media.type is None: media.type = mf.type if ('thumbnail_url' in meta or 'thumbnail_file' in meta) \ and (not has_thumbs(media) or has_default_thumbs(media)): thumb_file = meta.get('thumbnail_file', None) if thumb_file is not None: thumb_filename = thumb_file.filename else: thumb_url = meta['thumbnail_url'] thumb_filename = os.path.basename(thumb_url) # Download the image to a buffer and wrap it as a file-like object try: temp_img = urlopen(thumb_url) thumb_file = StringIO(temp_img.read()) temp_img.close() except URLError, e: log.exception(e) if thumb_file is not None: create_thumbs_for(media, thumb_file, thumb_filename) thumb_file.close()
def add_file(self, id, file=None, url=None, **kwargs): """Save action for the :class:`~mediacore.forms.admin.media.AddFileForm`. Creates a new :class:`~mediacore.model.media.MediaFile` from the uploaded file or the local or remote URL. :param id: Media ID. If ``"new"`` a new Media stub is created. :type id: :class:`int` or ``"new"`` :param file: The uploaded file :type file: :class:`cgi.FieldStorage` or ``None`` :param url: A URL to a recognizable audio or video file :type url: :class:`unicode` or ``None`` :rtype: JSON dict :returns: success bool message Error message, if unsuccessful media_id The :attr:`~mediacore.model.media.Media.id` which is important if new media has just been created. file_id The :attr:`~mediacore.model.media.MediaFile.id` for the newly created file. edit_form The rendered XHTML :class:`~mediacore.forms.admin.media.EditFileForm` for this file. status_form The rendered XHTML :class:`~mediacore.forms.admin.media.UpdateStatusForm` """ if id == 'new': media = Media() user = request.environ['repoze.who.identity']['user'] media.author = Author(user.display_name, user.email_address) # Create a temp stub until we can set it to something meaningful timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S') media.title = u'Temporary stub %s' % timestamp media.slug = get_available_slug(Media, '_stub_' + timestamp) media.reviewed = True DBSession.add(media) DBSession.flush() else: media = fetch_row(Media, id) media_file = add_new_media_file(media, file, url) if media.slug.startswith('_stub_'): media.title = media_file.display_name media.slug = get_available_slug(Media, '_stub_' + media.title) # The thumbs may have been created already by add_new_media_file if id == 'new' and not has_thumbs(media): create_default_thumbs_for(media) media.update_status() # Render some widgets so the XHTML can be injected into the page edit_form_xhtml = unicode(edit_file_form.display( action=url_for(action='edit_file', id=media.id), file=media_file)) status_form_xhtml = unicode(update_status_form.display( action=url_for(action='update_status', id=media.id), media=media)) data = dict( success = True, media_id = media.id, file_id = media_file.id, file_type = media_file.type, edit_form = edit_form_xhtml, status_form = status_form_xhtml, title = media.title, slug = media.slug, description = media.description, link = url_for(action='edit', id=media.id), duration = helpers.duration_from_seconds(media.duration), ) return data
if entry.media.description.text: encoded_description = unicode(entry.media.description.text, "utf-8") media.description = clean_xhtml(encoded_description) media.slug = get_available_slug(Media, media.title, media) if self.tags: media.set_tags(unicode(self.tags)) if self.categories: media.set_categories(self.categories) try: media_file = add_new_media_file(media, url=player_url) except StorageError, e: log.debug('Video Feed Error: Error storing video: %s at %s' \ % (e.message, player_url)) return None if not has_thumbs(media): create_default_thumbs_for(media) media.title = media_file.display_name media.update_status() if self.auto_publish: media.reviewed = 1 media.encoded = 1 media.publishable = 1 media.created_on = datetime.now() media.modified_on = datetime.now() media.publish_on = datetime.now() return media class ChannelImportState(object): def __init__(self, importer):
try: media_file = add_new_media_file(media, file, url) except Invalid, e: DBSession.rollback() data = dict( success = False, message = e.message, ) else: if media.slug.startswith('_stub_'): media.title = media_file.display_name media.slug = get_available_slug(Media, '_stub_' + media.title) # The thumbs may have been created already by add_new_media_file if id == 'new' and not has_thumbs(media): create_default_thumbs_for(media) # Render some widgets so the XHTML can be injected into the page edit_form_xhtml = unicode(edit_file_form.display( action=url_for(action='edit_file', id=media.id), file=media_file)) status_form_xhtml = unicode(update_status_form.display( action=url_for(action='update_status', id=media.id), media=media)) data = dict( success = True, media_id = media.id, file_id = media_file.id, file_type = media_file.type,