Example #1
0
def update_user_inbox_for_reminders(uid):
    """
    Updates user's inbox with any reminders that should have arrived
    @param uid: user id
    @return: integer number of new expired reminders
    """
    now = convert_datestruct_to_datetext(localtime())
    reminder_status = CFG_WEBMESSAGE_STATUS_CODE['REMINDER']
    new_status = CFG_WEBMESSAGE_STATUS_CODE['NEW']
    expired_reminders = db.session.query(UserMsgMESSAGE.id_msgMESSAGE).\
        join(UserMsgMESSAGE.message).\
        filter(db.and_(
            UserMsgMESSAGE.id_user_to == uid,
            UserMsgMESSAGE.status.like(reminder_status),
            MsgMESSAGE.received_date <= datetime.now()
            # MsgMESSAGE.received_date<=db.func.current_timestamp()
        )).all()

    if len(expired_reminders):
        filter = db.and_(
            UserMsgMESSAGE.id_user_to == uid,
            UserMsgMESSAGE.id_msgMESSAGE.in_(
                [i for i, in expired_reminders]))

        res = UserMsgMESSAGE.query.filter(filter).\
            update({UserMsgMESSAGE.status: new_status},
                   synchronize_session='fetch')
        return res
 def expand(self, id_user):
     """Expand comment beloging to user."""
     CmtCOLLAPSED.query.filter(
         db.and_(CmtCOLLAPSED.id_bibrec == self.id_bibrec,
                 CmtCOLLAPSED.id_cmtRECORDCOMMENT == self.id,
                 CmtCOLLAPSED.id_user == id_user)).delete(
                     synchronize_session=False)
Example #3
0
 def get_session(self, name, expired=False):
     """Return an instance of :class:`Session`."""
     where = Session.session_key == name
     if expired:
         where = db.and_(
             where, Session.session_expiry >= db.func.current_timestamp())
     return self.query.filter(where).one()
Example #4
0
    def get_kbr_values(self, searchkey="", searchvalue="", searchtype='s'):
        """
        Return dicts of 'key' and 'value' from a knowledge base.

        :param kb_name the name of the knowledge base
        :param searchkey search using this key
        :param searchvalue search using this value
        :param searchtype s=substring, e=exact, sw=startswith
        :return a list of dictionaries [{'key'=>x, 'value'=>y},..]
        """
        import warnings
        warnings.warn("The function is deprecated. Please use the "
                      "`KnwKBRVAL.query_kb_mappings()` instead. "
                      "E.g. [(kval.m_value,) for kval in "
                      "KnwKBRVAL.query_kb_mappings(kb_id).all()]")
        # prepare filters
        if searchtype == 's':
            searchkey = '%' + searchkey + '%'
        if searchtype == 's' and searchvalue:
            searchvalue = '%' + searchvalue + '%'
        if searchtype == 'sw' and searchvalue:  # startswith
            searchvalue = searchvalue + '%'
        if not searchvalue:
            searchvalue = '%'
        # execute query
        return db.session.execute(
            db.select([KnwKBRVAL.m_value],
                      db.and_(KnwKBRVAL.id_knwKB.like(self.id),
                              KnwKBRVAL.m_value.like(searchvalue),
                              KnwKBRVAL.m_key.like(searchkey))))
Example #5
0
 def get_session(self, name, expired=False):
     """Return an instance of :class:`Session`."""
     where = Session.session_key == name
     if expired:
         where = db.and_(
             where, Session.session_expiry >= db.func.current_timestamp())
     return self.query.filter(where).one()
Example #6
0
    def get_kbr_values(self, searchkey="", searchvalue="", searchtype='s'):
        """
        Return dicts of 'key' and 'value' from a knowledge base.

        :param kb_name the name of the knowledge base
        :param searchkey search using this key
        :param searchvalue search using this value
        :param searchtype s=substring, e=exact, sw=startswith
        :return a list of dictionaries [{'key'=>x, 'value'=>y},..]
        """
        import warnings
        warnings.warn("The function is deprecated. Please use the "
                      "`KnwKBRVAL.query_kb_mappings()` instead. "
                      "E.g. [(kval.m_value,) for kval in "
                      "KnwKBRVAL.query_kb_mappings(kb_id).all()]")
        # prepare filters
        if searchtype == 's':
            searchkey = '%' + searchkey + '%'
        if searchtype == 's' and searchvalue:
            searchvalue = '%' + searchvalue + '%'
        if searchtype == 'sw' and searchvalue:  # startswith
            searchvalue = searchvalue + '%'
        if not searchvalue:
            searchvalue = '%'
        # execute query
        return db.session.execute(
            db.select([KnwKBRVAL.m_value],
                      db.and_(KnwKBRVAL.id_knwKB.like(self.id),
                              KnwKBRVAL.m_value.like(searchvalue),
                              KnwKBRVAL.m_key.like(searchkey))))
Example #7
0
def comments(recid):
    """Display comments."""
    from invenio_access.local_config import VIEWRESTRCOLL
    from invenio_access.mailcookie import \
        mail_cookie_create_authorize_action
    from .api import check_user_can_view_comments
    auth_code, auth_msg = check_user_can_view_comments(current_user, recid)
    if auth_code and current_user.is_guest:
        cookie = mail_cookie_create_authorize_action(VIEWRESTRCOLL, {
            'collection': g.collection})
        url_args = {'action': cookie, 'ln': g.ln, 'referer': request.referrer}
        flash(_("Authorization failure"), 'error')
        return redirect(url_for('webaccount.login', **url_args))
    elif auth_code:
        flash(auth_msg, 'error')
        abort(401)

    # FIXME check restricted discussion
    comments = CmtRECORDCOMMENT.query.filter(db.and_(
        CmtRECORDCOMMENT.id_bibrec == recid,
        CmtRECORDCOMMENT.in_reply_to_id_cmtRECORDCOMMENT == 0,
        CmtRECORDCOMMENT.star_score == 0
    )).order_by(CmtRECORDCOMMENT.date_creation).all()
    return render_template('comments/comments.html', comments=comments,
                           option='comments')
Example #8
0
 def __str__(self):
     uid = current_user.get_id()
     dbquery.update_user_inbox_for_reminders(uid)
     unread = db.session.query(db.func.count(UserMsgMESSAGE.id_msgMESSAGE)).\
         filter(db.and_(
             UserMsgMESSAGE.id_user_to == uid,
             UserMsgMESSAGE.status == cfg[
                 'CFG_WEBMESSAGE_STATUS_CODE']['NEW']
         )).scalar()
     return render_template_to_string(
         "messages/menu_item.html", unread=unread)
Example #9
0
def delete_all_messages(uid):
    """
    Delete all messages of a user (except reminders)
    @param uid: user id
    @return: the number of messages deleted
    """
    reminder_status = CFG_WEBMESSAGE_STATUS_CODE['REMINDER']
    msg_ids = map(
        lambda x1: x1[0],
        db.session.query(
            UserMsgMESSAGE.id_msgMESSAGE). filter(
            db.and_(
                UserMsgMESSAGE.id_user_to == uid,
                UserMsgMESSAGE.status != reminder_status)).all())
    nb_messages = UserMsgMESSAGE.query.\
        filter(db.and_(UserMsgMESSAGE.id_user_to == uid,
                       UserMsgMESSAGE.status != reminder_status)).\
        delete(synchronize_session=False)
    if len(msg_ids) > 0:
        check_if_need_to_delete_message_permanently(msg_ids)
    return nb_messages
Example #10
0
    def can_perform_action(self, action=None):
        cond = CmtACTIONHISTORY.id_user == self.uid \
            if self.uid > 0 else \
            CmtACTIONHISTORY.client_host == \
            socket.inet_aton(request.remote_addr)

        if action in cfg['CFG_WEBCOMMENT_ACTION_CODE']:
            cond = db.and_(cond, CmtACTIONHISTORY.action_code ==
                           cfg['CFG_WEBCOMMENT_ACTION_CODE'][action])

        return CmtACTIONHISTORY.query.filter(
            CmtACTIONHISTORY.id_cmtRECORDCOMMENT == self.id, cond).\
            count() == 0
Example #11
0
def menu():
    uid = current_user.get_id()

    dbquery.update_user_inbox_for_reminders(uid)
    # join: msgMESSAGE -> user_msgMESSAGE, msgMESSAGE -> users
    # filter: all messages from user AND filter form
    # order: sorted by one of the table column
    messages = db.session.query(MsgMESSAGE, UserMsgMESSAGE).\
        join(MsgMESSAGE.user_from, MsgMESSAGE.sent_to_users).\
        filter(db.and_(dbquery.filter_all_messages_from_user(uid))).\
        order_by(db.desc(MsgMESSAGE.received_date)).limit(5)

    # return dict(messages=messages.all())
    return render_template('messages/menu.html', messages=messages.all())
Example #12
0
def index(sort=False, filter=None):
    uid = current_user.get_id()

    dbquery.update_user_inbox_for_reminders(uid)
    # join: msgMESSAGE -> user_msgMESSAGE, msgMESSAGE -> users
    # filter: all messages from user AND filter form
    # order: sorted by one of the table column
    messages = db.session.query(MsgMESSAGE, UserMsgMESSAGE).\
        join(MsgMESSAGE.user_from, MsgMESSAGE.sent_to_users).\
        filter(db.and_(dbquery.filter_all_messages_from_user(uid), (filter))).\
        order_by(sort)

    return dict(messages=messages.all(),
                nb_messages=dbquery.count_nb_messages(uid),
                no_quota=is_no_quota_user(uid))
    def widget(self):
        uid = current_user.get_id()
        unread = db.session.query(db.func.count(UserMsgMESSAGE.id_msgMESSAGE)).\
            filter(db.and_(
                UserMsgMESSAGE.id_user_to == uid,
                UserMsgMESSAGE.status == current_app.config[
                    'CFG_WEBMESSAGE_STATUS_CODE']['NEW']
            )).scalar()

        total = db.session.query(db.func.count(UserMsgMESSAGE.id_msgMESSAGE)).\
            filter(
                UserMsgMESSAGE.id_user_to == uid
        ).scalar()

        template = """
{{  _("You have %(x_num_new)d new messages out of %(x_num_total)d messages.",
      x_num_new=unread, x_num_total=total) }}
"""
        return render_template_to_string(template, _from_string=True,
                                         unread=unread, total=total)
Example #14
0
def unsubscribe(recid=None):
    uid = current_user.get_id()
    if recid is None:
        recid = request.values.getlist('recid', type=int)
    else:
        recid = [recid]
    current_app.logger.info(recid)
    try:
        db.session.query(CmtSUBSCRIPTION).filter(db.and_(
            CmtSUBSCRIPTION.id_bibrec.in_(recid),
            CmtSUBSCRIPTION.id_user == uid
        )).delete(synchronize_session=False)
        db.session.commit()
        flash(_('You have been successfully unsubscribed'), 'success')
    except:
        flash(_('You are already unsubscribed'), 'error')
    if len(recid) == 1:
        return redirect(url_for('.comments', recid=recid[0]))
    else:
        return redirect(url_for('.subscriptions'))
Example #15
0
 def sent_to_group_names(self, value):
     old_group_names = self.group_names
     self._sent_to_group_names = value
     groups_to_add = set(self.group_names) - set(old_group_names)
     groups_to_del = set(old_group_names) - set(self.group_names)
     if len(groups_to_del):
         to_del = set([u.nickname for u in User.query.
                       join(User.groups).filter(
                           Group.name.in_(groups_to_del)).
                       all()]) - set(self.user_nicks)
         is_to_del = lambda u: u.nickname in to_del
         remove_old = filter(is_to_del, self.recipients)
         for u in remove_old:
             self.recipients.remove(u)
     if len(groups_to_add):
         for u in User.query.join(User.groups).filter(db.and_(
                 Group.name.in_(groups_to_add),
                 db.not_(User.nickname.in_(self.user_nicks)))).all():
             if u not in self.recipients:
                 self.recipients.append(u)
Example #16
0
class AccAuthorization(db.Model):

    """Represent an authorization."""

    __tablename__ = 'accROLE_accACTION_accARGUMENT'
    id = db.Column(db.Integer(15, unsigned=True), primary_key=True,
                   autoincrement=True)
    id_accROLE = db.Column(db.Integer(15, unsigned=True),
                           db.ForeignKey(AccROLE.id), nullable=True,
                           index=True)
    id_accACTION = db.Column(db.Integer(15, unsigned=True),
                             db.ForeignKey(AccACTION.id), nullable=True,
                             index=True)
    _id_accARGUMENT = db.Column(db.Integer(15), nullable=True,
                                name="id_accARGUMENT", index=True)
    argumentlistid = db.Column(db.MediumInteger(8), nullable=True)

    role = db.relationship(AccROLE, backref='authorizations')
    action = db.relationship(AccACTION, backref='authorizations')
    argument = db.relationship(
        AccARGUMENT, backref='authorizations',
        primaryjoin=db.and_(
            AccARGUMENT.id == _id_accARGUMENT,
            _id_accARGUMENT != -1,
            _id_accARGUMENT is not None
        ),
        foreign_keys=_id_accARGUMENT,
        uselist=False,
        cascade="all, delete",
    )

    @db.hybrid_property
    def id_accARGUMENT(self):
        """get id_accARGUMENT."""
        return self._id_accARGUMENT

    @id_accARGUMENT.setter
    def id_accARGUMENT(self, value):
        """set id_accARGUMENT."""
        self._id_accARGUMENT = value or None
Example #17
0
    id_user = db.Column(db.Integer(15, unsigned=True), db.ForeignKey(User.id),
                        nullable=False, primary_key=True)
    id_accROLE = db.Column(db.Integer(15, unsigned=True),
                           db.ForeignKey(AccROLE.id), nullable=False,
                           primary_key=True)
    expiration = db.Column(db.DateTime, nullable=False,
                           server_default='9999-12-31 23:59:59')

    user = db.relationship(User, backref='roles')
    role = db.relationship(AccROLE, backref='users')

User.active_roles = db.relationship(
    UserAccROLE,
    lazy="dynamic",
    primaryjoin=db.and_(
        User.id == UserAccROLE.id_user,
        UserAccROLE.expiration >= db.func.now()
    )
)

User.has_admin_role = property(
    lambda self:
    self.has_super_admin_role or db.object_session(self).query(
        db.func.count(User.id) > 0
    ).join(
        User.active_roles,
        UserAccROLE.role,
        AccROLE.authorizations
    ).filter(
        AccAuthorization.id_accACTION.in_(
            db.select([AccACTION.id]).where(
                AccACTION.name.in_(CFG_ACC_ACTIVITIES_URLS.keys())
 def is_collapsed(self, id_user):
     """Return true if the comment is collapsed by user."""
     return CmtCOLLAPSED.query.filter(
         db.and_(CmtCOLLAPSED.id_bibrec == self.id_bibrec,
                 CmtCOLLAPSED.id_cmtRECORDCOMMENT == self.id,
                 CmtCOLLAPSED.id_user == id_user)).count() > 0
Example #19
0
 def expand(self, id_user):
     """Expand comment beloging to user."""
     CmtCOLLAPSED.query.filter(db.and_(
         CmtCOLLAPSED.id_bibrec == self.id_bibrec,
         CmtCOLLAPSED.id_cmtRECORDCOMMENT == self.id,
         CmtCOLLAPSED.id_user == id_user)).delete(synchronize_session=False)
Example #20
0
 def is_collapsed(self, id_user):
     """Return true if the comment is collapsed by user."""
     return CmtCOLLAPSED.query.filter(db.and_(
         CmtCOLLAPSED.id_bibrec == self.id_bibrec,
         CmtCOLLAPSED.id_cmtRECORDCOMMENT == self.id,
         CmtCOLLAPSED.id_user == id_user)).count() > 0