Exemplo n.º 1
0
def create_hp_containers(iSortCol_0=None, sSortDir_0=None):
    """
    Looks for related HPItems and groups them together in HPContainers

    @type hpitems: list
    @return: A list containing all the HPContainers.
    """
    from invenio.bibworkflow_model import BibWorkflowObject

    print '-----------------------Setting up HPCONTAINERS!'

    if iSortCol_0:
        iSortCol_0 = int(iSortCol_0)

    if iSortCol_0 == 6:
        column = 'created'
        if sSortDir_0 == 'desc':
            bwobject_list = BibWorkflowObject.query.order_by(
                db.desc(column)).all()
        elif sSortDir_0 == 'asc':
            bwobject_list = BibWorkflowObject.query.order_by(
                db.asc(column)).all()

        return bwobject_list
    else:
        return BibWorkflowObject.query.filter(
            BibWorkflowObject.id_parent != 0).all()
Exemplo n.º 2
0
def mycollections_ctx(uid):
    """
    Helper method for return ctx used by many views
    """
    return {
        'mycollections': UserCollection.query.filter_by(
            id_user=uid).order_by(db.asc(UserCollection.title)).all()
    }
Exemplo n.º 3
0
def mycollections_ctx(uid):
    """
    Helper method for return ctx used by many views
    """
    return {
        'mycollections':
        UserCollection.query.filter_by(id_user=uid).order_by(
            db.asc(UserCollection.title)).all()
    }
Exemplo n.º 4
0
class CollectionCollection(db.Model):
    """Represents a CollectionCollection record."""
    __tablename__ = 'collection_collection'
    id_dad = db.Column(db.MediumInteger(9, unsigned=True),
                       db.ForeignKey(Collection.id),
                       primary_key=True)
    id_son = db.Column(db.MediumInteger(9, unsigned=True),
                       db.ForeignKey(Collection.id),
                       primary_key=True)
    type = db.Column(db.Char(1), nullable=False, server_default='r')
    score = db.Column(db.TinyInteger(4, unsigned=True),
                      nullable=False,
                      server_default='0')
    son = db.relationship(
        Collection,
        primaryjoin=id_son == Collection.id,
        backref='dads',
        #FIX collection_class=db.attribute_mapped_collection('score'),
        order_by=db.asc(score))
    dad = db.relationship(Collection,
                          primaryjoin=id_dad == Collection.id,
                          backref='sons',
                          order_by=db.asc(score))
Exemplo n.º 5
0
 def most_specific_dad(self):
     return db.object_session(self).query(Collection).\
         join(Collection.sons).\
         filter(CollectionCollection.id_son == self.id).\
         order_by(db.asc(Collection.nbrecs)).\
         first()
Exemplo n.º 6
0
class Collection(db.Model):
    """Represents a Collection record."""
    def __repr__(self):
        return "%s(%s)" % (self.__class__.__name__, self.id)

    __tablename__ = 'collection'
    id = db.Column(db.MediumInteger(9, unsigned=True), primary_key=True)
    name = db.Column(db.String(255), unique=True, index=True, nullable=False)
    dbquery = db.Column(db.Text(20), nullable=True, index=True)
    nbrecs = db.Column(db.Integer(10, unsigned=True), server_default='0')
    #FIXME read only!!!
    reclist = db.Column(
        db.PickleType(pickler=IntbitsetPickle(), comparator=IntbitsetCmp))
    _names = db.relationship(
        lambda: Collectionname,
        backref='collection',
        collection_class=attribute_mapped_collection('ln_type'),
        cascade="all, delete, delete-orphan")

    names = association_proxy(
        '_names',
        'value',
        creator=lambda k, v: Collectionname(ln_type=k, value=v))

    _formatoptions = association_proxy('formats', 'format')

    #@cache.memoize(make_name=lambda fname: fname + '::' + g.ln)
    def formatoptions(self):
        if len(self._formatoptions):
            return [dict(f) for f in self._formatoptions]
        else:
            return [{
                'code': 'hb',
                'name': "HTML %s" % g._("brief"),
                'content_type': 'text/html'
            }]

    formatoptions = property(formatoptions)

    _examples_example = association_proxy('_examples', 'example')

    @property
    #@cache.memoize(make_name=lambda fname: fname + '::' + g.ln)
    def examples(self):
        return list(self._examples_example)

    @property
    def name_ln(self):
        from invenio.search_engine import get_coll_i18nname
        return get_coll_i18nname(self.name, g.ln).decode('utf-8')
        # Another possible implementation with cache memoize
        # @cache.memoize
        #try:
        #    return db.object_session(self).query(Collectionname).\
        #        with_parent(self).filter(db.and_(Collectionname.ln==g.ln,
        #            Collectionname.type=='ln')).first().value
        #except:
        #    return self.name

    @property
    #@cache.memoize(make_name=lambda fname: fname + '::' + g.ln)
    def portalboxes_ln(self):
        return db.object_session(self).query(CollectionPortalbox).\
            with_parent(self).\
            options(db.joinedload_all(CollectionPortalbox.portalbox)).\
            filter(CollectionPortalbox.ln == g.ln).\
            order_by(db.desc(CollectionPortalbox.score)).all()

    @property
    def most_specific_dad(self):
        return db.object_session(self).query(Collection).\
            join(Collection.sons).\
            filter(CollectionCollection.id_son == self.id).\
            order_by(db.asc(Collection.nbrecs)).\
            first()

    @property
    #@cache.memoize(make_name=lambda fname: fname + '::' + g.ln)
    def is_restricted(self):
        from invenio.search_engine import collection_restricted_p
        return collection_restricted_p(self.name)

    @property
    def type(self):
        p = re.compile("\d+:.*")
        if self.dbquery is not None and \
            p.match(self.dbquery.lower()):
            return 'r'
        else:
            return 'v'

    _collection_children = db.relationship(
        lambda: CollectionCollection,
        #collection_class=OrderedList,
        collection_class=ordering_list('score'),
        primaryjoin=lambda: Collection.id == CollectionCollection.id_dad,
        foreign_keys=lambda: CollectionCollection.id_dad,
        order_by=lambda: db.asc(CollectionCollection.score))
    _collection_children_r = db.relationship(
        lambda: CollectionCollection,
        #collection_class=OrderedList,
        collection_class=ordering_list('score'),
        primaryjoin=lambda: db.and_(
            Collection.id == CollectionCollection.id_dad, CollectionCollection.
            type == 'r'),
        foreign_keys=lambda: CollectionCollection.id_dad,
        order_by=lambda: db.asc(CollectionCollection.score))
    _collection_children_v = db.relationship(
        lambda: CollectionCollection,
        #collection_class=OrderedList,
        collection_class=ordering_list('score'),
        primaryjoin=lambda: db.and_(
            Collection.id == CollectionCollection.id_dad, CollectionCollection.
            type == 'v'),
        foreign_keys=lambda: CollectionCollection.id_dad,
        order_by=lambda: db.asc(CollectionCollection.score))
    collection_parents = db.relationship(
        lambda: CollectionCollection,
        #collection_class=OrderedList,
        collection_class=ordering_list('score'),
        primaryjoin=lambda: Collection.id == CollectionCollection.id_son,
        foreign_keys=lambda: CollectionCollection.id_son,
        order_by=lambda: db.asc(CollectionCollection.score))
    collection_children = association_proxy('_collection_children', 'son')
    collection_children_r = association_proxy(
        '_collection_children_r',
        'son',
        creator=lambda son: CollectionCollection(id_son=son.id, type='r'))
    collection_children_v = association_proxy(
        '_collection_children_v',
        'son',
        creator=lambda son: CollectionCollection(id_son=son.id, type='v'))

    #
    _externalcollections = db.relationship(
        lambda: CollectionExternalcollection,
        #            backref='collection',
        cascade="all, delete, delete-orphan")

    #
    #    externalcollections = association_proxy(
    #        '_externalcollections',
    #        'externalcollection')

    def _externalcollections_type(type):
        return association_proxy(
            '_externalcollections_' + str(type),
            'externalcollection',
            creator=lambda ext: CollectionExternalcollection(
                externalcollection=ext, type=type))

    externalcollections_0 = _externalcollections_type(0)
    externalcollections_1 = _externalcollections_type(1)
    externalcollections_2 = _externalcollections_type(2)

    externalcollections = db.relationship(
        lambda: CollectionExternalcollection,
        #backref='collection',
        collection_class=external_collection_mapper,
        cascade="all, delete, delete-orphan")

    # Search options
    _make_field_fieldvalue = lambda type: db.relationship(
        lambda: CollectionFieldFieldvalue,
        primaryjoin=lambda: db.and_(
            Collection.id == CollectionFieldFieldvalue.id_collection,
            CollectionFieldFieldvalue.type == type),
        order_by=lambda: CollectionFieldFieldvalue.score)

    _search_within = _make_field_fieldvalue('sew')
    _search_options = _make_field_fieldvalue('seo')

    @property
    #@cache.memoize(make_name=lambda fname: fname + '::' + g.ln)
    def search_within(self):
        """
        Collect search within options.
        """
        from invenio.search_engine_config import CFG_WEBSEARCH_SEARCH_WITHIN
        default = [('', g._('any field'))]
        found = [(o.field.code, o.field.name_ln) for o in self._search_within]
        if not found:
            found = [(f.name.replace(' ', ''), f.name_ln)
                     for f in Field.query.filter(
                         Field.name.in_(CFG_WEBSEARCH_SEARCH_WITHIN)).all()]
        return default + sorted(found, key=itemgetter(1))

    @property
    #@cache.memoize(make_name=lambda fname: fname + '::' + g.ln)
    def search_options(self):
        return self._search_options

    @property
    #@cache.memoize(make_name=lambda fname: fname + '::' + g.ln)
    def ancestors_ids(self):
        """Get list of parent collection ids."""
        output = intbitset([self.id])
        for c in self.dads:
            ancestors = c.dad.ancestors_ids
            if self.id in ancestors:
                raise
            output |= ancestors
        return output

    @property
    #@cache.memoize(make_name=lambda fname: fname + '::' + g.ln)
    def descendants_ids(self):
        """Get list of child collection ids."""
        output = intbitset([self.id])
        for c in self.sons:
            descendants = c.son.descendants_ids
            if self.id in descendants:
                raise
            output |= descendants
        return output

    # Gets the list of localized names as an array
    collection_names = db.relationship(
        lambda: Collectionname,
        primaryjoin=lambda: Collection.id == Collectionname.id_collection,
        foreign_keys=lambda: Collectionname.id_collection)

    # Gets the translation according to the lang code
    def translation(self, lang):
        try:
            return db.object_session(self).query(Collectionname).\
                with_parent(self).filter(db.and_(Collectionname.ln == lang,
                    Collectionname.type == 'ln')).first().value
        except:
            return ""

    portal_boxes_ln = db.relationship(
            lambda: CollectionPortalbox,
            #collection_class=OrderedList,
            collection_class=ordering_list('score'),
            primaryjoin=lambda: \
                Collection.id == CollectionPortalbox.id_collection,
            foreign_keys=lambda: CollectionPortalbox.id_collection,
            order_by=lambda: db.asc(CollectionPortalbox.score))

    #@db.hybrid_property
    #def externalcollections(self):
    #    return self._externalcollections

    #@externalcollections.setter
    #def externalcollections(self, data):
    #    if isinstance(data, dict):
    #        for k, vals in data.iteritems():
    #            for v in list(vals):
    #                self._externalcollections[k] = v
    #    else:
    #        self._externalcollections = data

    def breadcrumbs(self, builder=None, ln=CFG_SITE_LANG):
        """Retunds breadcrumbs for collection."""
        breadcrumbs = []
        # Get breadcrumbs for most specific dad if it exists.
        if self.most_specific_dad is not None:
            breadcrumbs = self.most_specific_dad.breadcrumbs(builder=builder,
                                                             ln=ln)

        if builder is not None:
            crumb = builder(self)
        else:
            crumb = (self.name_ln, 'search.collection', dict(name=self.name))
        breadcrumbs.append(crumb)
        return breadcrumbs