Exemplo n.º 1
0
class Timestamp(object):
    """Timestamp model mix-in with fractional seconds support.

    SQLAlchemy-Utils timestamp model does not have support for fractional
    seconds.
    """

    created = db.Column(db.DateTime().with_variant(mysql.DATETIME(fsp=6),
                                                   "mysql"),
                        default=datetime.utcnow,
                        nullable=False)
    updated = db.Column(db.DateTime().with_variant(mysql.DATETIME(fsp=6),
                                                   "mysql"),
                        default=datetime.utcnow,
                        nullable=False)
Exemplo n.º 2
0
class Timestamp(object):
    """Timestamp model mix-in with fractional seconds support.
    SQLAlchemy-Utils timestamp model does not have support for fractional
    seconds.
    """

    created = db.Column(
        db.DateTime(),
        default=datetime.utcnow,
        nullable=True,
    )
    updated = db.Column(
        db.DateTime(),
        default=datetime.utcnow,
        nullable=True,
    )
Exemplo n.º 3
0
class RecordMetadata(db.Model, RecordMetadataBase):
    """Model for mock module metadata."""

    __tablename__ = 'mock_metadata'

    expires_at = db.Column(db.DateTime(), nullable=True)

    bucket_id = db.Column(UUIDType, db.ForeignKey(Bucket.id))
    bucket = db.relationship(Bucket)
Exemplo n.º 4
0
class DraftMetadataBase(RecordMetadataBase):
    """Represent a base class for draft metadata."""

    fork_version_id = db.Column(db.Integer)
    """Version id of the record it is draft of."""

    expires_at = db.Column(db.DateTime().with_variant(mysql.DATETIME(fsp=6),
                                                      "mysql"),
                           default=datetime.utcnow,
                           nullable=True)
    """Specifies when the draft expires. If `NULL` the draft doesn't expire."""
Exemplo n.º 5
0
class DraftMetadataBase(Timestamp):
    """Represent a base class for draft metadata.

    The DraftMetadata object  contains a `created` and  a `updated`
    properties that are automatically updated.
    """

    # Enables SQLAlchemy-Continuum versioning
    __versioned__ = {}

    id = db.Column(
        UUIDType,
        primary_key=True,
        default=uuid.uuid4,
    )
    """Draft identifier."""

    fork_id = db.Column(UUIDType)
    """Draft identifier, it is the same than the record it is draft of"""

    fork_version_id = db.Column(db.Integer)
    """Version id of the record it is draft of."""

    version_id = db.Column(db.Integer, nullable=False)
    """Used by SQLAlchemy for optimistic concurrency control."""

    status = db.Column(db.String(255), default="draft", nullable=False)
    """Status for workflow management."""

    expiry_date = db.Column(db.DateTime().with_variant(mysql.DATETIME(fsp=6),
                                                       "mysql"),
                            default=datetime.utcnow,
                            nullable=True)
    """Specifies when the it expires. If `NULL` the draft does not expire"""

    json = db.Column(db.JSON().with_variant(
        postgresql.JSONB(none_as_null=True),
        'postgresql',
    ).with_variant(
        JSONType(),
        'sqlite',
    ).with_variant(
        JSONType(),
        'mysql',
    ),
                     default=lambda: dict(),
                     nullable=True)
    """Store metadata in JSON format.
    When you create a new `Record the `json field value should never be
    `NULL`. Default value is an empty dict. `NULL` value means that the
    record metadata has been deleted.
    """

    __mapper_args__ = {'version_id_col': version_id}
Exemplo n.º 6
0
class TestModel(db.Model):
    """Test model with just one column."""

    id = db.Column(db.Integer, primary_key=True)
    """Id of the model."""

    uuidcol = db.Column(UUIDType, default=uuid.uuid4)
    """UUID test column."""

    dt = db.Column(
        db.DateTime().with_variant(mysql.DATETIME(), "mysql"),
        nullable=True,
    )
Exemplo n.º 7
0
class Community(db.Model, Timestamp):
    """Represent a community."""

    __tablename__ = 'communities_community'

    id = db.Column(db.String(100), primary_key=True)
    """Id of the community."""

    id_user = db.Column(
        db.Integer,
        db.ForeignKey(User.id),
        nullable=False
    )
    """Owner of the community."""

    title = db.Column(db.String(length=255), nullable=False, default='')
    """Title of the community."""

    description = db.Column(db.Text, nullable=False, default='')
    """Short description of community, displayed in portal boxes."""

    page = db.Column(db.Text, nullable=False, default='')
    """Long description of community, displayed on an individual page."""

    curation_policy = db.Column(db.Text(), nullable=False, default='')
    """Community curation policy."""

    community_header = db.Column(db.Text, nullable=False, default='')
    """Header design of community, displayed in portal boxes."""

    community_footer = db.Column(db.Text, nullable=False, default='')
    """Footer design of community, displayed in portal boxes."""

    last_record_accepted = db.Column(
        db.DateTime(), nullable=False, default=datetime(2000, 1, 1, 0, 0, 0))
    """Last record acceptance datetime."""

    logo_ext = db.Column(db.String(length=4), nullable=True, default=None)
    """Extension of the logo."""

    ranking = db.Column(db.Integer, nullable=False, default=0)
    """Ranking of community. Updated by ranking deamon."""

    fixed_points = db.Column(db.Integer, nullable=False, default=0)
    """Points which will be always added to overall score of community."""

    deleted_at = db.Column(db.DateTime, nullable=True, default=None)
    """Time at which the community was soft-deleted."""

    # root_node_id = db.Column(db.Text, nullable=False, default='')

    root_node_id = db.Column(
        db.BigInteger,
        db.ForeignKey(Index.id),
        nullable=False
    )

    """Id of Root Node"""

    #
    # Relationships
    #
    owner = db.relationship(User, backref='communities',
                            foreign_keys=[id_user])
    """Relation to the owner (User) of the community."""

    index = db.relationship(Index, backref='index', foreign_keys=[root_node_id])
    """Relation to the owner (Index) of the community."""

    def __repr__(self):
        """String representation of the community object."""
        return '<Community, ID: {}>'.format(self.id)

    @classmethod
    def create(cls, community_id, user_id, root_node_id, **data):
        """Get a community."""
        with db.session.begin_nested():
            obj = cls(id=community_id, id_user=user_id, root_node_id=root_node_id, **data)
            db.session.add(obj)
        return obj

    def save_logo(self, stream, filename):
        """Get a community."""
        logo_ext = save_and_validate_logo(stream, filename, self.id)
        if logo_ext:
            self.logo_ext = logo_ext
            return True
        return False

    @classmethod
    def get(cls, community_id, with_deleted=False):
        """Get a community."""
        q = cls.query.filter_by(id=community_id)
        if not with_deleted:
            q = q.filter(cls.deleted_at.is_(None))
        return q.one_or_none()

    @classmethod
    def get_by_user(cls, user_id, with_deleted=False):
        """Get a community."""
        query = cls.query.filter_by(
            id_user=user_id
        )
        if not with_deleted:
            query = query.filter(cls.deleted_at.is_(None))

        return query.order_by(db.asc(Community.title))

    @classmethod
    def filter_communities(cls, p, so, with_deleted=False):
        """Search for communities.

        Helper function which takes from database only those communities which
        match search criteria. Uses parameter 'so' to set communities in the
        correct order.

        Parameter 'page' is introduced to restrict results and return only
        slice of them for the current page. If page == 0 function will return
        all communities that match the pattern.
        """
        query = cls.query if with_deleted else \
            cls.query.filter(cls.deleted_at.is_(None))

        if p:
            p = p.replace(' ', '%')
            query = query.filter(db.or_(
                cls.id.ilike('%' + p + '%'),
                cls.title.ilike('%' + p + '%'),
                cls.description.ilike('%' + p + '%'),
            ))

        if so in current_app.config['COMMUNITIES_SORTING_OPTIONS']:
            order = so == 'title' and db.asc or db.desc
            query = query.order_by(order(getattr(cls, so)))
        else:
            query = query.order_by(db.desc(cls.ranking))
        return query

    def add_record(self, record):
        """Add a record to the community.

        :param record: Record object.
        :type record: `invenio_records.api.Record`
        """
        key = current_app.config['COMMUNITIES_RECORD_KEY']
        record.setdefault(key, [])

        if self.has_record(record):
            current_app.logger.warning(
                'Community addition: record {uuid} is already in community '
                '"{comm}"'.format(uuid=record.id, comm=self.id))
        else:
            record[key].append(self.id)
            record[key] = sorted(record[key])
        if current_app.config['COMMUNITIES_OAI_ENABLED']:
            if not self.oaiset.has_record(record):
                self.oaiset.add_record(record)

    def remove_record(self, record):
        """Remove an already accepted record from the community.

        :param record: Record object.
        :type record: `invenio_records.api.Record`
        """
        if not self.has_record(record):
            current_app.logger.warning(
                'Community removal: record {uuid} was not in community '
                '"{comm}"'.format(uuid=record.id, comm=self.id))
        else:
            key = current_app.config['COMMUNITIES_RECORD_KEY']
            record[key] = [c for c in record[key] if c != self.id]

        if current_app.config['COMMUNITIES_OAI_ENABLED']:
            if self.oaiset.has_record(record):
                self.oaiset.remove_record(record)

    def has_record(self, record):
        """Check if record is in community."""
        return self.id in \
            record.get(current_app.config['COMMUNITIES_RECORD_KEY'], [])

    def accept_record(self, record):
        """Accept a record for inclusion in the community.

        :param record: Record object.
        """
        with db.session.begin_nested():
            req = InclusionRequest.get(self.id, record.id)
            if req is None:
                raise InclusionRequestMissingError(community=self,
                                                   record=record)
            req.delete()
            self.add_record(record)
            self.last_record_accepted = datetime.utcnow()

    def reject_record(self, record):
        """Reject a record for inclusion in the community.

        :param record: Record object.
        """
        with db.session.begin_nested():
            req = InclusionRequest.get(self.id, record.id)
            if req is None:
                raise InclusionRequestMissingError(community=self,
                                                   record=record)
            req.delete()

    def delete(self):
        """Mark the community for deletion.

        :param delete_time: DateTime after which to delete the community.
        :type delete_time: datetime.datetime
        :raises: CommunitiesError
        """
        if self.deleted_at is not None:
            raise CommunitiesError(community=self)
        else:
            self.deleted_at = datetime.utcnow()

    def undelete(self):
        """Remove the community marking for deletion."""
        if self.deleted_at is None:
            raise CommunitiesError(community=self)
        else:
            self.deleted_at = None

    @property
    def is_deleted(self):
        """Return whether given community is marked for deletion."""
        return self.deleted_at is not None

    @property
    def logo_url(self):
        """Get URL to collection logo.

        :returns: Path to community logo.
        :rtype: str
        """
        if self.logo_ext:
            return '/api/files/{bucket}/{key}'.format(
                bucket=current_app.config['COMMUNITIES_BUCKET_UUID'],
                key='{0}/logo.{1}'.format(self.id, self.logo_ext),
            )
        return None

    @property
    def community_url(self):
        """Get provisional URL."""
        return url_for(
            'invenio_communities.detail', community_id=self.id, _external=True)

    @property
    def community_provisional_url(self):
        """Get provisional URL."""
        return url_for(
            'invenio_communities.curate', community_id=self.id, _external=True)

    @property
    def upload_url(self):
        """Get provisional URL."""
        return url_for('invenio_deposit_ui.new', c=self.id, _external=True)

    @property
    def oaiset_spec(self):
        """Return the OAISet 'spec' name for given community.

        :returns: name of corresponding OAISet ('spec').
        :rtype: str
        """
        return current_app.config['COMMUNITIES_OAI_FORMAT'].format(
            community_id=self.id)

    @property
    def oaiset(self):
        """Return the corresponding OAISet for given community.

        If OAIServer is not installed this property will return None.

        :returns: returns OAISet object corresponding to this community.
        :rtype: `invenio_oaiserver.models.OAISet` or None
        """
        if current_app.config['COMMUNITIES_OAI_ENABLED']:
            from invenio_oaiserver.models import OAISet
            return OAISet.query.filter_by(spec=self.oaiset_spec).one()
        else:
            return None

    @property
    def oaiset_url(self):
        """Return the OAISet URL for given community.

        :returns: URL of corresponding OAISet.
        :rtype: str
        """
        return url_for(
            'invenio_oaiserver.response',
            verb='ListRecords',
            metadataPrefix='oai_dc', set=self.oaiset_spec, _external=True)

    @property
    def version_id(self):
        """Return the version of the community.

        :returns: hash which encodes the community id and its las update.
        :rtype: str
        """
        return hashlib.sha1('{0}__{1}'.format(
            self.id, self.updated).encode('utf-8')).hexdigest()
class Schema(db.Model):
    """Model defining analysis JSON schemas."""

    id = db.Column(db.Integer, primary_key=True)

    name = db.Column(db.String(128), unique=False, nullable=False)
    fullname = db.Column(db.String(128), unique=False, nullable=True)

    # version
    major = db.Column(db.Integer, unique=False, nullable=False, default=1)
    minor = db.Column(db.Integer, unique=False, nullable=False, default=0)
    patch = db.Column(db.Integer, unique=False, nullable=False, default=0)

    experiment = db.Column(db.String(128), unique=False, nullable=True)
    config = db.Column(json_type, default=lambda: dict(), nullable=False)

    deposit_schema = db.Column(json_type,
                               default=lambda: dict(),
                               nullable=True)

    deposit_options = db.Column(json_type,
                                default=lambda: dict(),
                                nullable=True)

    deposit_mapping = db.Column(json_type,
                                default=lambda: dict(),
                                nullable=True)

    record_schema = db.Column(json_type, default=lambda: dict(), nullable=True)

    record_options = db.Column(json_type,
                               default=lambda: dict(),
                               nullable=True)

    record_mapping = db.Column(json_type,
                               default=lambda: dict(),
                               nullable=True)

    use_deposit_as_record = db.Column(db.Boolean(create_constraint=False),
                                      unique=False,
                                      default=False)
    is_indexed = db.Column(db.Boolean(create_constraint=False),
                           unique=False,
                           default=False)

    created = db.Column(db.DateTime(), default=datetime.utcnow, nullable=False)
    updated = db.Column(db.DateTime(), default=datetime.utcnow, nullable=False)

    __tablename__ = 'schema'
    __table_args__ = (UniqueConstraint('name',
                                       'major',
                                       'minor',
                                       'patch',
                                       name='unique_schema_version'), )

    def __init__(self, *args, **kwargs):
        """Possible to set version from string."""
        version = kwargs.pop('version', None)
        if version:
            self.version = version

        super(Schema, self).__init__(*args, **kwargs)

    def __getattribute__(self, attr):
        """Map record attribute to deposit one,
        if use_deposit_as_record is ```True```."""

        if attr in SERVE_DEPOSIT_AS_RECORD_MAP.keys(
        ) and self.use_deposit_as_record:
            attr = SERVE_DEPOSIT_AS_RECORD_MAP.get(attr)

        return object.__getattribute__(self, attr)

    def __str__(self):
        """Stringify schema object."""
        return '{name}-v{version}'.format(name=self.name, version=self.version)

    @property
    def version(self):
        """Return stringified version."""
        return "{0}.{1}.{2}".format(self.major, self.minor, self.patch)

    @version.setter
    def version(self, string):
        """Set version."""
        matched = re.match(r"(\d+)\.(\d+)\.(\d+)", string)
        if matched is None:
            raise ValueError(
                'Version has to be passed as string <major>.<minor>.<patch>')

        self.major, self.minor, self.patch = matched.groups()

    @property
    def deposit_path(self):
        """Return deposit schema path."""
        prefix = current_app.config['SCHEMAS_DEPOSIT_PREFIX']
        path = urljoin(prefix, "{0}.json".format(self))
        return path

    @property
    def record_path(self):
        """Return record schema path."""
        prefix = current_app.config['SCHEMAS_RECORD_PREFIX']
        path = urljoin(prefix, "{0}.json".format(self))
        return path

    @property
    def deposit_index(self):
        """Get deposit index name."""
        path = urljoin(current_app.config['SCHEMAS_DEPOSIT_PREFIX'], str(self))
        return name_to_es_name(path)

    @property
    def record_index(self):
        """Get record index name."""
        path = urljoin(current_app.config['SCHEMAS_RECORD_PREFIX'], str(self))
        return name_to_es_name(path)

    @property
    def deposit_aliases(self):
        """Get ES deposits aliases."""
        name = name_to_es_name(self.name)
        return ['deposits', 'deposits-records', 'deposits-{}'.format(name)]

    @property
    def record_aliases(self):
        """Get ES records aliases."""
        name = name_to_es_name(self.name)
        return ['records', 'records-{}'.format(name)]

    @validates('name')
    def validate_name(self, key, name):
        """Validate if name is ES compatible."""
        if any(x in ES_FORBIDDEN for x in name):
            raise ValueError('Name cannot contain the following characters'
                             '[, ", *, \\, <, | , , , > , ?]')
        return name

    def serialize(self, resolve=False):
        """Serialize schema model."""
        serializer = resolved_schemas_serializer if resolve else schema_serializer  # noqa
        return serializer.dump(self).data

    def update(self, **kwargs):
        """Update schema instance."""
        for key, value in kwargs.items():
            setattr(self, key, value)

        return self

    def add_read_access_for_all_users(self):
        """Give read access to all authenticated users."""
        assert self.id

        db.session.add(
            ActionSystemRoles.allow(SchemaReadAction(self.id),
                                    role=authenticated_user))
        db.session.flush()

    def give_admin_access_for_user(self, user):
        """Give admin access for users."""
        assert self.id

        db.session.add(ActionUsers.allow(SchemaAdminAction(self.id),
                                         user=user))
        db.session.flush()

    @classmethod
    def get_latest(cls, name):
        """Get the latest version of schema with given name."""
        latest = cls.query \
            .filter_by(name=name) \
            .order_by(cls.major.desc(),
                      cls.minor.desc(),
                      cls.patch.desc()) \
            .first()

        if latest:
            return latest
        else:
            raise JSONSchemaNotFound(schema=name)

    @classmethod
    def get(cls, name, version):
        """Get schema by name and version."""
        matched = re.match(r"(\d+).(\d+).(\d+)", version)
        if matched is None:
            raise ValueError(
                'Version has to be passed as string <major>.<minor>.<patch>')

        major, minor, patch = matched.groups()

        try:
            schema = cls.query \
                .filter_by(name=name, major=major, minor=minor, patch=patch) \
                .one()

        except NoResultFound:
            raise JSONSchemaNotFound("{}-v{}".format(name, version))

        return schema
Exemplo n.º 9
0
class Index(db.Model, Timestamp):
    """
    Represent an index.

    The Index object contains a ``created`` and  a ``updated``
    properties that are automatically updated.
    """

    __tablename__ = 'index'

    __table_args__ = (db.UniqueConstraint('parent',
                                          'position',
                                          name='uix_position'), )

    id = db.Column(db.BigInteger, primary_key=True, unique=True)
    """Identifier of the index."""

    parent = db.Column(db.BigInteger, nullable=False, default=0)
    """Parent Information of the index."""

    position = db.Column(db.Integer, nullable=False, default=0)
    """Children position of parent."""

    index_name = db.Column(db.Text, nullable=True, default='')
    """Name of the index."""

    index_name_english = db.Column(db.Text, nullable=False, default='')
    """English Name of the index."""

    index_link_name = db.Column(db.Text, nullable=True, default='')
    """Name of the index link."""

    index_link_name_english = db.Column(db.Text, nullable=False, default='')
    """English Name of the index link."""

    harvest_spec = db.Column(db.Text, nullable=True, default='')
    """Harvest Spec."""

    index_link_enabled = db.Column(db.Boolean(name='index_link_enabled'),
                                   nullable=False,
                                   default=False)
    """Index link enable flag."""

    comment = db.Column(db.Text, nullable=True, default='')
    """Comment of the index."""

    more_check = db.Column(db.Boolean(name='more_check'),
                           nullable=False,
                           default=False)
    """More Status of the index."""

    display_no = db.Column(db.Integer, nullable=False, default=0)
    """Display number of the index."""

    harvest_public_state = db.Column(db.Boolean(name='harvest_public_state'),
                                     nullable=False,
                                     default=True)
    """Harvest public State of the index."""

    display_format = db.Column(db.Text, nullable=True, default='1')
    """The Format of Search Resault."""

    image_name = db.Column(db.Text, nullable=False, default='')
    """The Name of upload image."""

    public_state = db.Column(db.Boolean(name='public_state'),
                             nullable=False,
                             default=False)
    """Public State of the index."""

    public_date = db.Column(db.DateTime().with_variant(mysql.DATETIME(fsp=6),
                                                       "mysql"),
                            nullable=True)
    """Public Date of the index."""

    recursive_public_state = db.Column(db.Boolean(name='recs_public_state'),
                                       nullable=True,
                                       default=False)
    """Recursive Public State of the index."""

    coverpage_state = db.Column(db.Boolean(name='coverpage_state'),
                                nullable=True,
                                default=False)
    """PDF Cover Page State of the index."""

    recursive_coverpage_check = db.Column(
        db.Boolean(name='recursive_coverpage_check'),
        nullable=True,
        default=False)
    """Recursive PDF Cover Page State of the index."""

    browsing_role = db.Column(db.Text, nullable=True)
    """Browsing Role of the  ."""

    recursive_browsing_role = db.Column(db.Boolean(name='recs_browsing_role'),
                                        nullable=True,
                                        default=False)
    """Recursive Browsing Role of the index."""

    contribute_role = db.Column(db.Text, nullable=True)
    """Contribute Role of the index."""

    recursive_contribute_role = db.Column(
        db.Boolean(name='recs_contribute_role'), nullable=True, default=False)
    """Recursive Browsing Role of the index."""

    browsing_group = db.Column(db.Text, nullable=True)
    """Browsing Group of the  ."""

    recursive_browsing_group = db.Column(
        db.Boolean(name='recs_browsing_group'), nullable=True, default=False)
    """Recursive Browsing Group of the index."""

    contribute_group = db.Column(db.Text, nullable=True)
    """Contribute Group of the index."""

    recursive_contribute_group = db.Column(
        db.Boolean(name='recs_contribute_group'), nullable=True, default=False)
    """Recursive Browsing Group of the index."""

    owner_user_id = db.Column(db.Integer, nullable=True, default=0)
    """Owner user id of the index."""

    # item_custom_sort = db.Column(db.Text, nullable=True, default='')

    item_custom_sort = db.Column(db.JSON().with_variant(
        postgresql.JSONB(none_as_null=True),
        'postgresql',
    ).with_variant(
        JSONType(),
        'sqlite',
    ).with_variant(
        JSONType(),
        'mysql',
    ),
                                 default=lambda: dict(),
                                 nullable=True)
    """The sort of item by custom setting"""

    # index_items = db.relationship('IndexItems', back_populates='index', cascade='delete')

    def __iter__(self):
        """Iter."""
        for name in dir(Index):
            if not name.startswith('__') and not name.startswith('_') \
                    and name not in dir(Timestamp):
                value = getattr(self, name)
                if value is None:
                    value = ""
                if isinstance(value, str) or isinstance(value, bool) \
                        or isinstance(value, datetime) \
                        or isinstance(value, int):
                    yield (name, value)

    # format setting for community admin page

    def __str__(self):
        """Representation."""
        return 'Index <id={0.id}, index_name={0.index_name_english}>'.format(
            self)

    @classmethod
    def have_children(cls, id):
        """Have Children."""
        children = cls.query.filter_by(parent=id).all()
        return False if (children is None or len(children) == 0) else True
Exemplo n.º 10
0
class Index(db.Model, Timestamp, Serializer):
    """
    Represent an index.

    The Index object contains a ``created`` and  a ``updated``
    properties that are automatically updated.
    """

    __tablename__ = 'index'

    id = db.Column(db.BigInteger, primary_key=True, unique=True)
    """Identifier of the index."""

    parent = db.Column(db.BigInteger, nullable=False, default=0)
    """Parent Information of the index."""

    children = db.Column(db.Text, nullable=False, default='')
    """Children Information of the index."""

    index_name = db.Column(db.Text, nullable=False, default='')
    """Name of the index."""

    index_name_english = db.Column(db.Text, nullable=False, default='')
    """English Name of the index."""

    comment = db.Column(db.Text, nullable=True, default='')
    """Comment of the index."""

    contents = db.Column(db.Integer, nullable=True, default=0)
    """Contents of the index."""

    private_contents = db.Column(db.Integer, nullable=True, default=0)
    """Private Contents of the index."""

    public_state = db.Column(db.Boolean(name='public_state'),
                             nullable=True,
                             default=False)
    """Public State of the index."""

    public_date = db.Column(db.DateTime().with_variant(mysql.DATETIME(fsp=6),
                                                       "mysql"),
                            nullable=True)
    """Public Date of the index."""

    recursive_public_state = db.Column(db.Boolean(name='pubdate_recursive'),
                                       nullable=True,
                                       default=False)
    """Recursive Public State of the index."""

    rss_display = db.Column(db.Boolean(name='rss_display'),
                            nullable=True,
                            default=False)
    """RSS Display of the index."""

    create_cover_flag = db.Column(db.Boolean(name='create_cover_flag'),
                                  nullable=True,
                                  default=False)
    """Create pdf cover flag of the index."""

    create_cover_recursive = db.Column(
        db.Boolean(name='create_cover_recursive'),
        nullable=True,
        default=False)
    """Create pdf recursive cover flag of the index."""

    harvest_public_state = db.Column(db.Boolean(name='harvest_public_state'),
                                     nullable=True,
                                     default=False)
    """Harvest public state of the index."""

    online_issn = db.Column(db.Text, nullable=True, default='')
    """Online issn of the index."""

    biblio_flag = db.Column(db.Boolean(name='biblioFlag'),
                            nullable=True,
                            default=False)
    """Biblio flag of the index."""

    display_type = db.Column(db.Integer, nullable=True, default=0)
    """Display Type of the index."""

    select_index_list_display = db.Column(
        db.Boolean(name='select_index_list_display'),
        nullable=True,
        default=False)
    """Select Index List Display of the index."""

    select_index_list_name = db.Column(db.Text, nullable=True, default='')
    """Select Index List Name of the index."""

    select_index_list_name_english = db.Column(db.Text,
                                               nullable=True,
                                               default='')
    """Select Index List Name of the index."""

    exclusive_acl_role = db.Column(db.Text, nullable=True, default='')
    """Exclusive Acl Role of the index."""

    acl_role = db.Column(db.Text, nullable=True, default='')
    """Acl Role of the index."""

    exclusive_acl_room_auth = db.Column(db.Text, nullable=True, default='')
    """Exclusive Acl Room Auth of the index."""

    exclusive_acl_group = db.Column(db.Text, nullable=True, default='')
    """Exclusive Acl Group of the index."""

    acl_group = db.Column(db.Text, nullable=True, default='')
    """Acl Group of the index."""

    exclusive_access_role = db.Column(db.Text, nullable=True, default='')
    """Exclusive Access Role of the index."""

    access_role = db.Column(db.Text, nullable=True, default='')
    """Access Role of the index."""

    aclRoleIds_recursive = db.Column(db.Boolean(name='aclRoleIds'),
                                     nullable=True,
                                     default=False)
    """aclRoleIds of the index."""

    exclusive_tree_room_auth = db.Column(db.Text, nullable=True, default='')
    """Exclusive Tree Room Auth of the index."""

    aclRoomAuth_recursive = db.Column(db.Boolean(name='aclRoomAuth'),
                                      nullable=True,
                                      default=False)
    """Acl RoomAuth of the index."""

    exclusive_access_group = db.Column(db.Text, nullable=True, default='')
    """Exclusive Access Group of the index."""

    access_group = db.Column(db.Text, nullable=True, default='')
    """Access Group of the index."""

    aclGroupIds_recursive = db.Column(db.Boolean(name='aclGroupIds'),
                                      nullable=True,
                                      default=False)
    """Acl GroupIds of the index."""

    opensearch_uri = db.Column(db.Text, nullable=True, default='')
    """Open Search URI of the index."""

    thumbnail = db.Column(db.LargeBinary, nullable=True)
    """Thumbnail of the index."""

    thumbnail_name = db.Column(db.Text, nullable=True, default='')
    """Thumbnail Name of the index."""

    thumbnail_mime_type = db.Column(db.Text, nullable=True, default='')
    """Thumbnail MIME Type of the index."""

    owner_user_id = db.Column(db.Integer, nullable=True, default=0)
    """Owner user id of the index."""

    ins_user_id = db.Column(db.Integer, nullable=True, default=0)
    """Insert user id of the index."""

    mod_user_id = db.Column(db.Integer, nullable=True, default=0)
    """Modify user id of the index."""

    del_user_id = db.Column(db.Integer, nullable=True, default=0)
    """Delete user id of the index."""

    ins_date = db.Column(db.DateTime().with_variant(mysql.DATETIME(fsp=6),
                                                    "mysql"),
                         nullable=True,
                         default=datetime.utcnow)
    """Insert date of the index."""

    mod_date = db.Column(db.DateTime().with_variant(mysql.DATETIME(fsp=6),
                                                    "mysql"),
                         nullable=True)
    """Modify date of the index."""

    del_date = db.Column(db.DateTime().with_variant(mysql.DATETIME(fsp=6),
                                                    "mysql"),
                         nullable=True)
    """Delete date of the index."""

    is_delete = db.Column(db.Boolean(name='delete_flag'),
                          nullable=True,
                          default=False)
    """Delete flag of the index."""
    def serialize(self):
        """
        Serialize the object.

        :return: The dict of object.
        """
        obj = Serializer.serialize(self)
        del obj['is_delete']
        del obj['del_date']
        del obj['mod_date']
        del obj['ins_date']
        del obj['del_user_id']
        del obj['ins_user_id']
        del obj['owner_user_id']
        del obj['updated']
        del obj['created']
        del obj['thumbnail']
        return obj
Exemplo n.º 11
0
class RecordMetadata(db.Model, RecordMetadataBase):
    """Model for mock module metadata."""

    __tablename__ = 'mock_metadata'

    expires_at = db.Column(db.DateTime(), nullable=True)
Exemplo n.º 12
0
class Index(db.Model, Timestamp):
    """
    Represent an index.

    The Index object contains a ``created`` and  a ``updated``
    properties that are automatically updated.
    """

    __tablename__ = 'index'

    __table_args__ = (db.UniqueConstraint('parent',
                                          'position',
                                          name='uix_position'), )

    id = db.Column(db.BigInteger, primary_key=True, unique=True)
    """Identifier of the index."""

    parent = db.Column(db.BigInteger, nullable=False, default=0)
    """Parent Information of the index."""

    position = db.Column(db.Integer, nullable=False, default=0)
    """Children position of parent."""

    index_name = db.Column(db.Text, nullable=True, default='')
    """Name of the index."""

    index_name_english = db.Column(db.Text, nullable=False, default='')
    """English Name of the index."""

    comment = db.Column(db.Text, nullable=True, default='')
    """Comment of the index."""

    more_check = db.Column(db.Boolean(name='more_check'),
                           nullable=False,
                           default=False)
    """More Status of the index."""

    display_no = db.Column(db.Integer, nullable=False, default=0)
    """Display number of the index."""

    harvest_public_state = db.Column(db.Boolean(name='harvest_public_state'),
                                     nullable=False,
                                     default=True)
    """Harvest public State of the index."""

    display_format = db.Column(db.Text, nullable=True, default='1')
    """The Format of Search Resault."""

    image_name = db.Column(db.Text, nullable=False, default='')
    """The Name of upload image."""

    public_state = db.Column(db.Boolean(name='public_state'),
                             nullable=False,
                             default=False)
    """Public State of the index."""

    public_date = db.Column(db.DateTime().with_variant(mysql.DATETIME(fsp=6),
                                                       "mysql"),
                            nullable=True)
    """Public Date of the index."""

    recursive_public_state = db.Column(db.Boolean(name='recs_public_state'),
                                       nullable=True,
                                       default=False)
    """Recursive Public State of the index."""

    browsing_role = db.Column(db.Text, nullable=True)
    """Browsing Role of the  ."""

    recursive_browsing_role = db.Column(db.Boolean(name='recs_browsing_role'),
                                        nullable=True,
                                        default=False)
    """Recursive Browsing Role of the index."""

    contribute_role = db.Column(db.Text, nullable=True)
    """Contribute Role of the index."""

    recursive_contribute_role = db.Column(
        db.Boolean(name='recs_contribute_role'), nullable=True, default=False)
    """Recursive Browsing Role of the index."""

    browsing_group = db.Column(db.Text, nullable=True)
    """Browsing Group of the  ."""

    recursive_browsing_group = db.Column(
        db.Boolean(name='recs_browsing_group'), nullable=True, default=False)
    """Recursive Browsing Group of the index."""

    contribute_group = db.Column(db.Text, nullable=True)
    """Contribute Group of the index."""

    recursive_contribute_group = db.Column(
        db.Boolean(name='recs_contribute_group'), nullable=True, default=False)
    """Recursive Browsing Group of the index."""

    owner_user_id = db.Column(db.Integer, nullable=True, default=0)
    """Owner user id of the index."""

    # index_items = db.relationship('IndexItems', back_populates='index', cascade='delete')

    def __iter__(self):
        for name in dir(Index):
            if not name.startswith('__') and not name.startswith('_') \
                 and name not in dir(Timestamp):
                value = getattr(self, name)
                if value is None:
                    value = ""
                if isinstance(value, str) or isinstance(value, bool) \
                        or isinstance(value, datetime) \
                        or isinstance(value, int):
                    yield (name, value)

    # format setting for community admin page

    def __str__(self):
        """Representation."""
        return 'Index <id={0.id}, index_name={0.index_name_english}>'.format(
            self)