Ejemplo n.º 1
0
 def get_last_message(self, id):
     last_message = Chat.query.filter(
         db.and_(Chat.sender == self.id, Chat.receiver == id)
         | db.and_(Chat.sender == id, Chat.receiver == self.id)).order_by(
             Chat.timestamp.desc()).first()
     if last_message is not None:
         last_message = last_message.serialize()
     return last_message
Ejemplo n.º 2
0
    def get_chat(self, id):
        try:
            chats = Chat.query.filter(
                db.and_(Chat.sender == self.id, Chat.receiver == id)
                | db.and_(Chat.sender == id, Chat.receiver == self.id)
            ).order_by(Chat.timestamp).all()
        except Exception as e:
            return False

        return [chat.serialize() for chat in chats]
Ejemplo n.º 3
0
    def get(self):
        args = reqparse.RequestParser() \
         .add_argument(
          'uno_id', type=str,
          location='args', required=False) \
         .add_argument(
          'uno_name', type=str,
          location='args', required=False) \
         .add_argument(
          'code_id', type=str,
          location='args', required=False) \
         .add_argument(
          'start_time', type=str,
          location='args', required=False) \
         .add_argument(
          'end_time', type=str,
          location='args', required=False) \
         .add_argument(
          'pageNum', type=str,
          location='args', required=False) \
         .add_argument(
          'pageSize', type=str,
          location='args', required=False) \
         .add_argument(
          'order', type=str,
          location='args', required=False) \
         .parse_args()

        condition = []
        if (args['uno_id'] is not None):
            condition.append(vEventLogM.uno_id.like('%' + args['uno_id'] +
                                                    '%'))
        if (args['uno_name'] is not None):
            condition.append(
                vEventLogM.uno_name.like('%' + args['uno_name'] + '%'))

        if (args['code_id'] is not None):
            condition.append(
                vEventLogM.code_id.like('%' + args['code_id'] + '%'))

        if (args['start_time'] is not None and args['end_time'] is not None):
            start_time = args['start_time']
            end_time = args['end_time']
            condition.append(
                db.between(vEventLogM.timestamp, start_time, end_time))
        elif (args['start_time'] is not None and args['end_time'] is None):
            start_time = args['start_time']
            end_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
            condition.append(
                db.between(vEventLogM.timestamp, start_time, end_time))
        elif (args['start_time'] is None and args['end_time'] is not None):
            end_time = args['end_time']
            condition.append(end_time >= vEventLogM.timestamp)

        pageNum = 1
        pageSize = 20
        if (args['pageNum'] is not None):
            pageNum = args['pageNum']
        if (args['pageSize'] is not None):
            pageSize = args['pageSize']

        ordering = {}
        if (args['order'] is not None):
            if (args['order'] == 'desc'):
                ordering = vEventLogM.timestamp.desc()
            elif (args['order'] == 'asc'):
                ordering = vEventLogM.timestamp.asc()
            else:
                ordering = vEventLogM.timestamp.desc()
        else:
            ordering = vEventLogM.timestamp.desc()

        grp = vEventLogM.query\
         .filter(db.and_(*condition))\
         .order_by(ordering)\
         .limit(pageSize).offset(str((int(pageNum)-1)*int(pageSize)))\
         .all()

        count = db.session\
         .query(func.count(vEventLogM.timestamp))\
         .filter(*condition).first()[0]

        return {
            "result": vEventLogM.serialize_list(grp),
            "pageNum": int(pageNum),
            "pageSize": int(pageSize),
            "count": int(count),
            "last_update": datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
        }, 200
Ejemplo n.º 4
0
class User(db.Model):
    """id, name, email-address, password_hash, about_me"""

    __tablename__ = 'user'

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

    username = db.Column(db.String(32),
                         unique=True,
                         nullable=False,
                         index=True)

    email = db.Column(db.String(80), unique=True, nullable=False, index=True)

    password_hash = db.Column(db.String(256))

    gender = db.Column(db.String(8), nullable=False)

    about_me = db.Column(db.String(160))

    verified = db.Column(db.Boolean, default=True)
    # in production make the default to false

    profile_picture = db.Column(db.String, nullable=True)

    last_seen = db.Column(db.DateTime, default=datetime.utcnow)

    # ---------------------------------------------

    received_requests = db.relationship(
        'User',
        secondary='friendship',
        primaryjoin=db.and_(Friendship.to_id == id,
                            Friendship.status == False),
        secondaryjoin=db.and_(Friendship.from_id == id,
                              Friendship.status == False),
        order_by=Friendship.updated.desc())

    sent_requests = db.relationship(
        'User',
        secondary='friendship',
        primaryjoin=db.and_(Friendship.from_id == id,
                            Friendship.status == False),
        secondaryjoin=db.and_(Friendship.to_id == id,
                              Friendship.status == False),
        order_by=Friendship.updated.desc())

    sent_friends = db.relationship(
        'User',
        secondary='friendship',
        primaryjoin=db.and_(Friendship.from_id == id,
                            Friendship.status == True),
        secondaryjoin=db.and_(Friendship.to_id == id,
                              Friendship.status == True),
        order_by=Friendship.updated.desc())

    received_friends = db.relationship(
        'User',
        secondary='friendship',
        primaryjoin=db.and_(Friendship.to_id == id, Friendship.status == True),
        secondaryjoin=db.and_(Friendship.from_id == id,
                              Friendship.status == True),
        order_by=Friendship.updated.desc())

    # ---------------------------------------------

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

    def __init__(self,
                 username,
                 email,
                 password,
                 gender,
                 about_me=None,
                 *args,
                 **kwargs):
        super(User, self).__init__(*args, **kwargs)
        self.username = username
        self.email = email
        self.set_password(password)
        self.gender = gender
        self.about_me = about_me
        if (gender == "female"):
            self.profile_picture = "../" + "female_default.png"
        else:
            self.profile_picture = "../" + "male_default.png"

    def serialize(self):
        return {
            "id": self.id,
            "username": self.username,
            "email": self.email,
            "gender": self.gender,
            "about_me": self.about_me,
            "verified": self.verified,
            "profile_picture": self.profile_picture,
            "last_seen": str(self.last_seen) + 'Z'
        }

    # ---------------------------------------------

    def check_relation(self, id):
        friend = Friendship.query.filter((Friendship.from_id == self.id)
                                         & (Friendship.to_id == id)).first()
        if friend is None:
            friend = Friendship.query.filter((Friendship.from_id == id) & (
                Friendship.to_id == self.id)).first()
        return friend

    def user_status(self, id):
        friend = self.check_relation(id)
        if friend is None:
            return 0
        elif friend.status == False:
            if friend.from_id == self.id:
                return 1
            else:
                return 2
        else:
            return 3

    def all_friends(self):
        friends = self.sent_friends.copy()
        friends.extend(self.received_friends)
        return [friend.serialize() for friend in friends]

    def send_request(self, id):
        check = self.user_status(id)
        if check == 0:
            try:
                db.session.add(Friendship(from_id=self.id, to_id=id))
                db.session.commit()
            except Exception as e:
                return False
            return True

        else:
            return False
        # elif check == 3:
        # 	return "Already Friends."
        # else:
        # 	return "Request is pending."

    def accept_request(self, id):
        friend = self.check_relation(id)
        if friend is None:
            return "Please send a request first!"
        elif friend.status == False:
            friend.status = True
            friend.updated = datetime.utcnow()
            try:
                db.session.commit()
            except Exception as e:
                return False
            return True
        else:
            return False
        # else:
        # 	return "Already Friends."

    def unfriend(self, id):
        # this same method is being used for delete request
        friend = self.check_relation(id)
        if friend is None:
            return False
            # return "Please send a request first!"
        else:
            try:
                db.session.delete(friend)
                db.session.commit()
            except Exception as e:
                return False
            return True

    # ---------------------------------------------

    def get_chat(self, id):
        try:
            chats = Chat.query.filter(
                db.and_(Chat.sender == self.id, Chat.receiver == id)
                | db.and_(Chat.sender == id, Chat.receiver == self.id)
            ).order_by(Chat.timestamp).all()
        except Exception as e:
            return False

        return [chat.serialize() for chat in chats]

    def get_last_message(self, id):
        last_message = Chat.query.filter(
            db.and_(Chat.sender == self.id, Chat.receiver == id)
            | db.and_(Chat.sender == id, Chat.receiver == self.id)).order_by(
                Chat.timestamp.desc()).first()
        if last_message is not None:
            last_message = last_message.serialize()
        return last_message

    def send_message(self, message, id):
        chat = Chat(message=message, sender_id=self.id, receiver_id=id)
        friend = self.check_relation(id)
        try:
            friend.updated = datetime.utcnow()
            db.session.add(chat)
            db.session.commit()
        except Exception as e:
            return False
        return chat.serialize()

    # ---------------------------------------------

    def get_token(self):
        return jwt.encode(
            {
                'token': self.id,
                'exp': time() + current_app.config['EMAIL_EXPIRY']
            },
            current_app.config['SECRET_KEY'],
            algorithm='HS256').decode('utf-8')

    @staticmethod
    def verify_token(token):
        try:
            id = jwt.decode(token,
                            current_app.config['SECRET_KEY'],
                            algorithms=['HS256'])['token']
        except:
            return
        return id

    # ---------------------------------------------

    def __repr__(self):
        return 'User object: id {} username {}'.format(self.id, self.username)