def _update_settings(self, values): """Modify the settings associated with the given dictionary.""" for name, value in values.iteritems(): if name in tmpl_context.settings: setting = tmpl_context.settings[name] else: setting = Setting(key=name, value=value) if value is None: value = u'' else: value = unicode(value) if setting.value != value: setting.value = value DBSession.add(setting) DBSession.flush() # Clear the settings cache unless there are multiple processes. # We have no way of notifying the other processes that they need # to clear their caches too, so we've just gotta let it play out # until all the caches expire. if not request.environ.get('wsgi.multiprocess', False): app_globals.settings_cache.clear() else: # uWSGI provides an automagically included module # that we can use to call a graceful restart of all # the uwsgi processes. # http://projects.unbit.it/uwsgi/wiki/uWSGIReload try: import uwsgi uwsgi.reload() except ImportError: pass
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 _create_user_without_groups(self): user = User() user.user_name = u"joe" user.email_address = u"*****@*****.**" user.display_name = u"Joe" user.groups = [] DBSession.add(user) DBSession.flush() return user
def test_can_restrict_query_if_user_does_not_have_the_required_permission(self): query = Media.query permission = u'view' perm = self.perm() view_permission = DBSession.query(Permission).filter(Permission.permission_name == permission).one() view_permission.groups = [] DBSession.flush() assert_none(self.policy.access_condition_for_query(query, permission, perm))
def _create_user_without_groups(self): user = User() user.user_name = u'joe' user.email_address = u'*****@*****.**' user.display_name = u'Joe' user.groups = [] DBSession.add(user) DBSession.flush() return user
def delete(self, id, **kwargs): """Delete a PlayerPref. After deleting the PlayerPref, cleans up the players table, ensuring that each Player class is represented--if the deleted PlayerPref is the last example of that Player class, creates a new disabled PlayerPref for that Player class with the default settings. :param id: Player ID. :type id: ``int`` :returns: Redirect back to :meth:`index` after successful delete. """ player = fetch_row(PlayerPrefs, id) DBSession.delete(player) DBSession.flush() cleanup_players_table() redirect(action='index', id=None)
def final_view(self, id, **kwargs): print('hello') try: csrf = kwargs['environ']['paste.cookies'][0]['csrftoken'].value # .filter(Views_Counter.csrftoken==csrf)\ temp = Views_Counter.query.filter(Views_Counter.media_id==id)\ .filter(Views_Counter.validated==False) print(csrf) if temp: temp = temp.one() media = fetch_row(Media, id=id) try: media.increment_views3() media.increment_views() DBSession.commit() except OperationalError: DBSession.rollback() return dict(success=False) temp.validated = True DBSession.flush() except: return dict(success=False) return dict(success=True)
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() DBSession.flush() engine.postprocess(mf) # Try to transcode the file. for engine in sorted_engines: try: engine.transcode(mf) log.debug('Engine %r has agreed to transcode %r', engine, mf) break except CannotTranscode: log.debug('Engine %r unsuitable for transcoding %r', engine, mf) continue return mf
def comment(self, slug, name='', email=None, body='', **kwargs): """Post a comment from :class:`~mediadrop.forms.comments.PostCommentForm`. :param slug: The media :attr:`~mediadrop.model.media.Media.slug` :returns: Redirect to :meth:`view` page for media. """ def result(success, message=None, comment=None): if request.is_xhr: result = dict(success=success, message=message) if comment: result['comment'] = render('comments/_list.html', {'comment_to_render': comment}, method='xhtml') return result elif success: return redirect(action='view') else: return self.view(slug, name=name, email=email, body=body, **kwargs) if request.settings['comments_engine'] != 'builtin': abort(404) akismet_key = request.settings['akismet_key'] if akismet_key: akismet = Akismet(agent=USER_AGENT) akismet.key = akismet_key akismet.blog_url = request.settings['akismet_url'] or \ url_for('/', qualified=True) akismet.verify_key() data = {'comment_author': name.encode('utf-8'), 'user_ip': request.environ.get('REMOTE_ADDR'), 'user_agent': request.environ.get('HTTP_USER_AGENT', ''), 'referrer': request.environ.get('HTTP_REFERER', 'unknown'), 'HTTP_ACCEPT': request.environ.get('HTTP_ACCEPT')} if akismet.comment_check(body.encode('utf-8'), data): return result(False, _(u'Your comment has been rejected.')) media = fetch_row(Media, slug=slug) request.perm.assert_permission(u'view', media.resource) c = Comment() name = filter_vulgarity(name) c.author = AuthorWithIP(name, email, request.environ['REMOTE_ADDR']) c.subject = 'Re: %s' % media.title c.body = filter_vulgarity(body) require_review = request.settings['req_comment_approval'] if not require_review: c.reviewed = True c.publishable = True media.comments.append(c) DBSession.flush() send_comment_notification(media, c) if require_review: message = _('Thank you for your comment! We will post it just as ' 'soon as a moderator approves it.') return result(True, message=message) else: return result(True, comment=c)
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:`~mediadrop.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:`~mediadrop.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. """ sorted_engines = enabled_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) from mediadrop.model import DBSession, MediaFile 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) mf.tags = "one, two, three" 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) #Read id3 tag and extract the details from there from mediadrop.lib.storage import LocalFileStorage if (isinstance(engine, LocalFileStorage)): mf.id3tags = engine.get_id3_tags(unique_id) mf.extracted_tags = engine.get_id3_user_tags(unique_id) print("ID3 tags: ", mf.id3tags) if (mf.id3tags != None): mf.display_name = mf.id3tags['title'][0] 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_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:`~mediadrop.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:`~mediadrop.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. """ sorted_engines = enabled_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) from mediadrop.model import DBSession, MediaFile 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 comment(self, slug, name='', email=None, body='', **kwargs): """Post a comment from :class:`~mediadrop.forms.comments.PostCommentForm`. :param slug: The media :attr:`~mediadrop.model.media.Media.slug` :returns: Redirect to :meth:`view` page for media. """ def result(success, message=None, comment=None): if request.is_xhr: result = dict(success=success, message=message) if comment: result['comment'] = render('comments/_list.html', {'comment_to_render': comment}, method='xhtml') return result elif success: return redirect(action='view') else: return self.view(slug, name=name, email=email, body=body, **kwargs) if request.settings['comments_engine'] != 'builtin': abort(404) akismet_key = request.settings['akismet_key'] if akismet_key: akismet = Akismet(agent=USER_AGENT) akismet.key = akismet_key akismet.blog_url = request.settings['akismet_url'] or \ url_for('/', qualified=True) akismet.verify_key() data = { 'comment_author': name.encode('utf-8'), 'user_ip': request.environ.get('REMOTE_ADDR'), 'user_agent': request.environ.get('HTTP_USER_AGENT', ''), 'referrer': request.environ.get('HTTP_REFERER', 'unknown'), 'HTTP_ACCEPT': request.environ.get('HTTP_ACCEPT') } if akismet.comment_check(body.encode('utf-8'), data): return result(False, _(u'Your comment has been rejected.')) media = fetch_row(Media, slug=slug) request.perm.assert_permission(u'view', media.resource) c = Comment() aux = DBSession.query(User).filter(User.display_name == name) require_review = request.settings['req_comment_approval'] if not require_review: c.reviewed = True c.publishable = True if request.perm.user.display_name != "Anonymous User": name = request.perm.user.display_name email = request.perm.user.email_address if aux: name = filter_vulgarity(name) c.author = AuthorWithIP(name, email, request.environ['REMOTE_ADDR']) c.subject = 'Re: %s' % media.title c.body = filter_vulgarity(body) media.comments.append(c) DBSession.flush() send_comment_notification(media, c) if require_review: message = _('Thank you for your comment! We will post it just as ' 'soon as a moderator approves it.') return result(True, message=message) else: return result(True, comment=c)