Ejemplo n.º 1
0
    def test_can_fake_logged_in_user(self):
        admin = DBSession.query(User).filter(User.user_name == u"admin").one()
        assert_true(admin.has_permission(u"admin"))
        self.init_fake_request()
        self.set_authenticated_user(admin)

        assert_true(has_permission(u"admin"))
 def permissions_for_request(cls, environ, config):
     identity = environ.get('repoze.who.identity', {})
     user_id = identity.get('repoze.who.userid')
     user = None
     if user_id is not None:
         user = DBSession.query(User).filter(User.id==user_id).first()
     return cls.permissions_for_user(user, config)
Ejemplo n.º 3
0
    def index(self, page=1, **kwargs):
        """List storage engines with pagination.

        :rtype: Dict
        :returns:
            engines
                The list of :class:`~mediadrop.lib.storage.StorageEngine`
                instances for this page.

        """
        engines = DBSession.query(StorageEngine)\
            .options(orm.undefer('file_count'),
                     orm.undefer('file_size_sum'))\
            .all()
        engines = list(sort_engines(engines))
        existing_types = set(ecls.engine_type for ecls in engines)
        addable_engines = [
            ecls
            for ecls in StorageEngine
            if not ecls.is_singleton or ecls.engine_type not in existing_types
        ]

        return {
            'engines': engines,
            'addable_engines': addable_engines,
        }
Ejemplo n.º 4
0
def create_new_user(username, config):
    from mediadrop.model import DBSession, User, fetch_row, Group

    user = User.by_user_name(username)

    if user is None:
        try:
            print "MIDDLEWARE"
            print config
            l = ldap.initialize(config['ldap_url'])        
            l.simple_bind_s(config['ldap_binddn'], config['ldap_pw'])
            filter = '(samaccountname=%s)' % username
            r = l.search_s(config['ldap_base'],ldap.SCOPE_SUBTREE, filter, ['displayname', 'mail'])
            l.unbind_s()

            user_attrs = {}
            for dn, entry in r:
                for attr, v in entry.iteritems():
                    user_attrs[attr] = v[0]
        except ldap.LDAPError:
            l.unbind_s()

        new_user = fetch_row(User, "new")
        new_user.display_name = user_attrs['displayName']
        new_user.email_address = user_attrs['mail']
        new_user.user_name = username
        query = DBSession.query(Group).filter(Group.group_name.in_(['authenticated']))
        new_user.groups = list(query.all())

        DBSession.add(new_user)
        DBSession.commit()
 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))
Ejemplo n.º 6
0
 def _create_user_with_admin_permission_only(self):
     admin_perm = DBSession.query(Permission).filter(Permission.permission_name == u'admin').one()
     second_admin_group = Group.example(name=u'Second admin group')
     admin_perm.groups.append(second_admin_group)
     admin = User.example(groups=[second_admin_group])
     DBSession.commit()
     perm = MediaDropPermissionSystem.permissions_for_user(admin, config)
     assert_true(perm.contains_permission(u'admin'))
     assert_false(perm.contains_permission(u'edit'))
     return admin
Ejemplo n.º 7
0
    def _to_python(self, value, state):
        id = request.environ["pylons.routes_dict"]["id"]

        query = DBSession.query(Group).filter_by(group_name=value)
        if id != "new":
            query = query.filter(Group.group_id != id)

        if query.count() != 0:
            raise Invalid(_("Group name already exists"), value, state)
        return value
Ejemplo n.º 8
0
    def _to_python(self, value, state):
        id = request.environ['pylons.routes_dict']['id']

        query = DBSession.query(Group).filter_by(group_name=value)
        if id != 'new':
            query = query.filter(Group.group_id != id)

        if query.count() != 0:
            raise Invalid(_('Group name already exists'), value, state)
        return value
Ejemplo n.º 9
0
def update_enabled_players():
    """Ensure that the encoding status of all media is up to date with the new
    set of enabled players.

    The encoding status of Media objects is dependent on there being an
    enabled player that supports that format. Call this method after changing
    the set of enabled players, to ensure encoding statuses are up to date.
    """
    from mediadrop.model import DBSession, Media
    media = DBSession.query(Media)
    for m in media:
        m.update_status()
    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))
Ejemplo n.º 11
0
def update_enabled_players():
    """Ensure that the encoding status of all media is up to date with the new
    set of enabled players.

    The encoding status of Media objects is dependent on there being an
    enabled player that supports that format. Call this method after changing
    the set of enabled players, to ensure encoding statuses are up to date.
    """
    from mediadrop.model import DBSession, Media
    media = DBSession.query(Media)
    for m in media:
        m.update_status()
Ejemplo n.º 12
0
    def random(self, **kwargs):
        """Redirect to a randomly selected media item."""
        # TODO: Implement something more efficient than ORDER BY RAND().
        #       This method does a full table scan every time.
        random_query = Media.query.published().order_by(sql.func.random())
        media = viewable_media(random_query).first()

        if media is None:
            redirect(action='explore')
        if media.podcast_id:
            podcast_slug = DBSession.query(Podcast.slug).get(media.podcast_id)
        else:
            podcast_slug = None
        redirect(action='view', slug=media.slug, podcast_slug=podcast_slug)
Ejemplo n.º 13
0
    def random(self, **kwargs):
        """Redirect to a randomly selected media item."""
        # TODO: Implement something more efficient than ORDER BY RAND().
        #       This method does a full table scan every time.
        random_query = Media.query.published().order_by(sql.func.random())
        media = viewable_media(random_query).first()

        if media is None:
            redirect(action='explore')
        if media.podcast_id:
            podcast_slug = DBSession.query(Podcast.slug).get(media.podcast_id)
        else:
            podcast_slug = None
        redirect(action='view', slug=media.slug, podcast_slug=podcast_slug)
Ejemplo n.º 14
0
 class fields(WidgetsList):
     podcast_include = SingleSelectField(
         'podcast',
         label_text=N_('Include in the Podcast'),
         css_classes=['dropdown-select'],
         options=lambda: [(None, None)] + DBSession.query(
             Podcast.id, Podcast.title).all())
     title = TextField(validator=validators['title'],
                       label_text=N_('Title:'),
                       maxlength=255)
     description = XHTMLTextArea(validator=validators['description'],
                                 label_text=N_('Description:'),
                                 attrs=dict(rows=5, cols=25))
     file = FileField(validator=FieldStorageUploadConverter(
         if_missing=None,
         messages={'empty': N_('Oops! You forgot to enter a file.')}))
     submit = SubmitButton(default=N_('Submit'),
                           css_classes=['mcore-btn', 'btn-submit'])
Ejemplo n.º 15
0
class GroupForm(ListForm):
    template = 'admin/box-form.html'
    id = 'group-form'
    css_class = 'form'
    submit_text = None
    show_children_errors = True
    
    event = events.Admin.GroupForm
    
    fields = [
        TextField('display_name', label_text=N_('Display Name'), validator=TextField.validator(not_empty=True), maxlength=255),
        TextField('group_name', label_text=N_('Groupname'), validator=All(PlainText(not_empty=True), UniqueGroupname()), maxlength=16),
        CheckBoxList('permissions', label_text=N_('Group Permissions'), 
            css_classes=['details_fieldset'],
            options=lambda: DBSession.query(Permission.permission_id, Permission.description).all()
        ),
        SubmitButton('save', default=N_('Save'), named_button=True, css_classes=['btn', 'btn-save', 'blue', 'f-rgt']),
        SubmitButton('delete', default=N_('Delete'), named_button=True, css_classes=['btn', 'btn-delete']),
    ]
Ejemplo n.º 16
0
    def submit(self, **kwargs):
        """
        """
        kwargs.setdefault('name')
        name = request.perm.user.display_name
        email_X = request.perm.user.email_address
        podcasts = DBSession.query(Podcast.id).filter(Podcast.author_name == name)\
                                              .filter(Podcast.id == kwargs['podcast'])\
                                              .all()
        if not podcasts:
            redirect(action='failure')

        # Save the media_obj!
        media_obj = self.save_media_obj(name, email_X, kwargs['title'],
                                        kwargs['description'], None,
                                        kwargs['file'], kwargs['podcast'])
        email.send_media_notification(media_obj)

        # Redirect to success page!
        redirect(action='success')
Ejemplo n.º 17
0
    def index(self, **kwargs):
        """Display the upload form.

        :rtype: Dict
        :returns:
            legal_wording
                XHTML legal wording for rendering
            support_email
                An help contact address
            upload_form
                The :class:`~mediadrop.forms.uploader.UploadForm` instance
            form_values
                ``dict`` form values, if any

        """
        name = request.perm.user.display_name
        support_emails = request.settings['email_support_requests']
        support_emails = email.parse_email_string(support_emails)
        support_email = support_emails and support_emails[0] or None
        aux = DBSession.query(
            Podcast.id, Podcast.title).filter(Podcast.author_name == name)
        if 'podcast_include' in kwargs:
            aux = aux.filter(Podcast.id == kwargs['podcast_include']).all()
        else:
            aux = aux.all()

        s = SingleSelectField('podcast',
                              label_text=N_('Include in the Podcast'),
                              css_classes=['dropdown-select'],
                              options=lambda: aux)
        upload_form.children._widget_lst[0] = s
        return dict(
            legal_wording=request.settings['wording_user_uploads'],
            support_email=support_email,
            upload_form=upload_form,
            form_values=kwargs,
        )
Ejemplo n.º 18
0
    def perm(self):
        system = MediaDropPermissionSystem(self.pylons_config)
        system.policies = [self.policy]

        user = DBSession.query(User).filter(User.user_name == u'admin').one()
        return UserPermissions(user, system)
Ejemplo n.º 19
0
def setup_app(command, conf, vars):
    """Called by ``paster setup-app``.

    This script is responsible for:

        * Creating the initial database schema and loading default data.
        * Executing any migrations necessary to bring an existing database
          up-to-date. Your data should be safe but, as always, be sure to
          make backups before using this.
        * Re-creating the default database for every run of the test suite.

    XXX: All your data will be lost IF you run the test suite with a
         config file named 'test.ini'. Make sure you have this configured
         to a different database than in your usual deployment.ini or
         development.ini file because all database tables are dropped a
         and recreated every time this script runs.

    XXX: If you are upgrading from MediaCore v0.7.2 or v0.8.0, run whichever
         one of these that applies:
           ``python batch-scripts/upgrade/upgrade_from_v072.py deployment.ini``
           ``python batch-scripts/upgrade/upgrade_from_v080.py deployment.ini``

    XXX: For search to work, we depend on a number of MySQL triggers which
         copy the data from our InnoDB tables to a MyISAM table for its
         fulltext indexing capability. Triggers can only be installed with
         a mysql superuser like root, so you must run the setup_triggers.sql
         script yourself.

    """
    # paster just scans the source code for a "websetup.py". Due to our
    # compatibility module for the old "mediacore" namespace it actually finds
    # two modules (mediadrop.websetup and mediacore.websetup) even though both
    # actually point to the same source code.
    # Because of that "paster setup-app" actually runs "setup_app()" twice
    # which causes some bad stuff to happen (e.g. duplicate metadata
    # initialization. Until we get rid of the compat package we should make
    # sure the following code is only run once.
    global did_run_setup
    if did_run_setup:
        return
    config = load_environment(conf.global_conf, conf.local_conf)
    plugin_manager = config['pylons.app_globals'].plugin_mgr
    mediadrop_migrator = MediaDropMigrator.from_config(conf, log=log)
    
    engine = metadata.bind
    db_connection = engine.connect()
    # simplistic check to see if MediaDrop tables are present, just check for
    # the media_files table and assume that all other tables are there as well
    from mediadrop.model.media import media_files
    mediadrop_tables_exist = engine.dialect.has_table(db_connection, media_files.name)
    
    run_migrations = True
    if not mediadrop_tables_exist:
        head_revision = mediadrop_migrator.head_revision()
        log.info('Initializing new database with version %r' % head_revision)
        metadata.create_all(bind=DBSession.bind, checkfirst=True)
        mediadrop_migrator.init_db(revision=head_revision)
        run_migrations = False
        add_default_data()
        for migrator in plugin_manager.migrators():
            migrator.init_db()
        events.Environment.database_initialized()
    elif not mediadrop_migrator.alembic_table_exists():
        if not mediadrop_migrator.migrate_table_exists():
            log.error('No migration table found, probably your MediaDrop install '
                'is too old (< 0.9?). Please upgrade to MediaCore CE 0.9 first.')
            raise AssertionError('no migration table found')
        alembic_revision = mediadrop_migrator.map_migrate_version()
        mediadrop_migrator.stamp(alembic_revision)
    if run_migrations:
        mediadrop_migrator.migrate_db()
        for migrator in plugin_manager.migrators():
            migrator.migrate_db()
        events.Environment.database_migrated()
    
    cleanup_players_table(enabled=True)
    
    # Save everything, along with the dummy data if applicable
    DBSession.commit()
    events.Environment.database_ready()

    log.info('Generating appearance.css from your current settings')
    settings = DBSession.query(Setting.key, Setting.value)
    if settings.count() == 0:
        error_msg = (
            u"Unable to find any settings in the database. This may happen if a previous\n"
            u"setup did not complete successfully.\n"
            u"Please inspect your database contents. If you don't have any valuable data in\n"
            u"that db you can try to remove all tables and run the setup process again.\n"
            u"BE CAREFUL: REMOVING ALL TABLES MIGHT CAUSE DATA LOSS!\n"
        )
        sys.stderr.write(error_msg)
        log.error(error_msg.replace('\n', u' '))
        sys.exit(99)
    generate_appearance_css(settings, cache_dir=conf['cache_dir'])

    did_run_setup = True
    log.info('Successfully setup')
Ejemplo n.º 20
0
def setup_app(command, conf, vars):
    """Called by ``paster setup-app``.

    This script is responsible for:

        * Creating the initial database schema and loading default data.
        * Executing any migrations necessary to bring an existing database
          up-to-date. Your data should be safe but, as always, be sure to
          make backups before using this.
        * Re-creating the default database for every run of the test suite.

    XXX: All your data will be lost IF you run the test suite with a
         config file named 'test.ini'. Make sure you have this configured
         to a different database than in your usual deployment.ini or
         development.ini file because all database tables are dropped a
         and recreated every time this script runs.

    XXX: If you are upgrading from MediaCore v0.7.2 or v0.8.0, run whichever
         one of these that applies:
           ``python batch-scripts/upgrade/upgrade_from_v072.py deployment.ini``
           ``python batch-scripts/upgrade/upgrade_from_v080.py deployment.ini``

    XXX: For search to work, we depend on a number of MySQL triggers which
         copy the data from our InnoDB tables to a MyISAM table for its
         fulltext indexing capability. Triggers can only be installed with
         a mysql superuser like root, so you must run the setup_triggers.sql
         script yourself.

    """
    config = load_environment(conf.global_conf, conf.local_conf)
    plugin_manager = config['pylons.app_globals'].plugin_mgr
    mediadrop_migrator = MediaDropMigrator.from_config(conf, log=log)
    
    engine = metadata.bind
    db_connection = engine.connect()
    # simplistic check to see if MediaDrop tables are present, just check for
    # the media_files table and assume that all other tables are there as well
    from mediadrop.model.media import media_files
    mediadrop_tables_exist = engine.dialect.has_table(db_connection, media_files.name)
    
    run_migrations = True
    if not mediadrop_tables_exist:
        head_revision = mediadrop_migrator.head_revision()
        log.info('Initializing new database with version %r' % head_revision)
        metadata.create_all(bind=DBSession.bind, checkfirst=True)
        mediadrop_migrator.init_db(revision=head_revision)
        run_migrations = False
        add_default_data()
        for migrator in plugin_manager.migrators():
            migrator.init_db()
        events.Environment.database_initialized()
    elif not mediadrop_migrator.migrate_table_exists():
        log.error('No migration table found, probably your MediaDrop install '
            'is too old (< 0.9?). Please upgrade to MediaCore CE 0.9 first.')
        raise AssertionError('no migration table found')
    elif not mediadrop_migrator.alembic_table_exists():
        alembic_revision = mediadrop_migrator.map_migrate_version()
        mediadrop_migrator.stamp(alembic_revision)
    if run_migrations:
        mediadrop_migrator.migrate_db()
        for migrator in plugin_manager.migrators():
            migrator.migrate_db()
        events.Environment.database_migrated()
    
    cleanup_players_table(enabled=True)
    
    # Save everything, along with the dummy data if applicable
    DBSession.commit()
    events.Environment.database_ready()

    log.info('Generating appearance.css from your current settings')
    settings = DBSession.query(Setting.key, Setting.value)
    generate_appearance_css(settings, cache_dir=conf['cache_dir'])

    log.info('Successfully setup')
Ejemplo n.º 21
0
 def permissions(self):
     db_permissions = DBSession.query(Permission).all()
     return tuple([permission.permission_name for permission in db_permissions])
Ejemplo n.º 22
0
def enabled_engines():
    from mediadrop.model import DBSession
    engines = DBSession.query(StorageEngine)\
        .filter(StorageEngine.enabled == True)\
        .all()
    return list(sort_engines(engines))
Ejemplo n.º 23
0
def enabled_engines():
    from mediadrop.model import DBSession
    engines = DBSession.query(StorageEngine)\
        .filter(StorageEngine.enabled == True)\
        .all()
    return list(sort_engines(engines))
Ejemplo n.º 24
0
 def editor_group(self):
     return DBSession.query(Group).filter(Group.group_name == u'editors').one()
Ejemplo n.º 25
0
 def __before__(self, *args, **kwargs):
     """Load all our settings before each request."""
     BaseController.__before__(self, *args, **kwargs)
     from mediadrop.model import Setting
     tmpl_context.settings = dict(DBSession.query(Setting.key, Setting))
 def perm(self):
     system = MediaDropPermissionSystem(self.pylons_config)
     system.policies = [self.policy]
     
     user = DBSession.query(User).filter(User.user_name == u'admin').one()
     return UserPermissions(user, system)
Ejemplo n.º 27
0
class MediaForm(ListForm):
    template = 'admin/box-form.html'
    id = 'media-form'
    css_class = 'form'
    submit_text = None
    show_children_errors = True
    _name = 'media-form' # TODO: Figure out why this is required??
    
    event = events.Admin.MediaForm
    
    fields = [
        SingleSelectField('podcast', label_text=N_('Include in the Podcast'), css_classes=['dropdown-select'], help_text=N_('Optional'), options=lambda: [(None, None)] + DBSession.query(Podcast.id, Podcast.title).all()),
        TextField('slug', label_text=N_('Permalink'), maxlength=50),
        TextField('title', label_text=N_('Title'), validator=TextField.validator(not_empty=True), maxlength=255),
        TextField('author_name', label_text=N_('Author Name'), maxlength=50),
        TextField('author_email', label_text=N_('Author Email'), validator=email_validator(not_empty=True), maxlength=255),
        XHTMLTextArea('description', label_text=N_('Description'), attrs=dict(rows=5, cols=25)),
        CategoryCheckBoxList('categories', label_text=N_('Categories'), options=lambda: DBSession.query(Category.id, Category.name).all()),
        TextArea('tags', label_text=N_('Tags'), attrs=dict(rows=3, cols=15), help_text=N_(u'e.g.: puppies, great dane, adorable')),
        TextArea('notes',
            label_text=N_('Administrative Notes'),
            attrs=dict(rows=3, cols=25),
            container_attrs = lambda: ({'class': 'hidden'}, {})[bool(request.settings.get('wording_display_administrative_notes', ''))],
            default=lambda: request.settings['wording_administrative_notes']),
        SubmitButton('save', default=N_('Save'), named_button=True, css_classes=['btn', 'blue', 'f-rgt']),
        SubmitButton('delete', default=N_('Delete'), named_button=True, css_classes=['btn', 'f-lft']),
    ]
Ejemplo n.º 28
0
 def fetch_settings():
     from mediadrop.model import DBSession, Setting
     settings_dict = dict(DBSession.query(Setting.key, Setting.value))
     return settings_dict
Ejemplo n.º 29
0
    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)
Ejemplo n.º 30
0
 def __before__(self, *args, **kwargs):
     """Load all our settings before each request."""
     BaseController.__before__(self, *args, **kwargs)
     from mediadrop.model import Setting
     tmpl_context.settings = dict(DBSession.query(Setting.key, Setting))
Ejemplo n.º 31
0
 def editor_group(self):
     return DBSession.query(Group).filter(
         Group.group_name == u'editors').one()
Ejemplo n.º 32
0
 def fetch_settings():
     from mediadrop.model import DBSession, Setting
     settings_dict = dict(DBSession.query(Setting.key, Setting.value))
     return settings_dict
Ejemplo n.º 33
0
def setup_app(command, conf, vars):
    """Called by ``paster setup-app``.

    This script is responsible for:

        * Creating the initial database schema and loading default data.
        * Executing any migrations necessary to bring an existing database
          up-to-date. Your data should be safe but, as always, be sure to
          make backups before using this.
        * Re-creating the default database for every run of the test suite.

    XXX: All your data will be lost IF you run the test suite with a
         config file named 'test.ini'. Make sure you have this configured
         to a different database than in your usual deployment.ini or
         development.ini file because all database tables are dropped a
         and recreated every time this script runs.

    XXX: If you are upgrading from MediaCore v0.7.2 or v0.8.0, run whichever
         one of these that applies:
           ``python batch-scripts/upgrade/upgrade_from_v072.py deployment.ini``
           ``python batch-scripts/upgrade/upgrade_from_v080.py deployment.ini``

    XXX: For search to work, we depend on a number of MySQL triggers which
         copy the data from our InnoDB tables to a MyISAM table for its
         fulltext indexing capability. Triggers can only be installed with
         a mysql superuser like root, so you must run the setup_triggers.sql
         script yourself.

    """
    # paster just scans the source code for a "websetup.py". Due to our
    # compatibility module for the old "mediacore" namespace it actually finds
    # two modules (mediadrop.websetup and mediacore.websetup) even though both
    # actually point to the same source code.
    # Because of that "paster setup-app" actually runs "setup_app()" twice
    # which causes some bad stuff to happen (e.g. duplicate metadata
    # initialization. Until we get rid of the compat package we should make
    # sure the following code is only run once.
    global did_run_setup
    if did_run_setup:
        return
    config = load_environment(conf.global_conf, conf.local_conf)
    plugin_manager = config['pylons.app_globals'].plugin_mgr
    mediadrop_migrator = MediaDropMigrator.from_config(conf, log=log)

    engine = metadata.bind
    db_connection = engine.connect()
    # simplistic check to see if MediaDrop tables are present, just check for
    # the media_files table and assume that all other tables are there as well
    from mediadrop.model.media import media_files
    mediadrop_tables_exist = engine.dialect.has_table(db_connection,
                                                      media_files.name)

    run_migrations = True
    if not mediadrop_tables_exist:
        head_revision = mediadrop_migrator.head_revision()
        log.info('Initializing new database with version %r' % head_revision)
        metadata.create_all(bind=DBSession.bind, checkfirst=True)
        mediadrop_migrator.init_db(revision=head_revision)
        run_migrations = False
        add_default_data()
        for migrator in plugin_manager.migrators():
            migrator.init_db()
        events.Environment.database_initialized()
    elif not mediadrop_migrator.alembic_table_exists():
        if not mediadrop_migrator.migrate_table_exists():
            log.error(
                'No migration table found, probably your MediaDrop install '
                'is too old (< 0.9?). Please upgrade to MediaCore CE 0.9 first.'
            )
            raise AssertionError('no migration table found')
        alembic_revision = mediadrop_migrator.map_migrate_version()
        mediadrop_migrator.stamp(alembic_revision)
    if run_migrations:
        mediadrop_migrator.migrate_db()
        for migrator in plugin_manager.migrators():
            migrator.migrate_db()
        events.Environment.database_migrated()

    cleanup_players_table(enabled=True)

    # Save everything, along with the dummy data if applicable
    DBSession.commit()
    events.Environment.database_ready()

    log.info('Generating appearance.css from your current settings')
    settings = DBSession.query(Setting.key, Setting.value)
    if settings.count() == 0:
        error_msg = (
            u"Unable to find any settings in the database. This may happen if a previous\n"
            u"setup did not complete successfully.\n"
            u"Please inspect your database contents. If you don't have any valuable data in\n"
            u"that db you can try to remove all tables and run the setup process again.\n"
            u"BE CAREFUL: REMOVING ALL TABLES MIGHT CAUSE DATA LOSS!\n")
        sys.stderr.write(error_msg)
        log.error(error_msg.replace('\n', u' '))
        sys.exit(99)
    generate_appearance_css(settings, cache_dir=conf['cache_dir'])

    did_run_setup = True
    log.info('Successfully setup')