Exemple #1
0
class Show(db.Model, TimestampMixin):
    __tablename__ = "Show"

    id = db.Column(db.Integer, primary_key=True)
    start_time = db.Column(db.DateTime)
    end_time = db.Column(db.DateTime)
    venue_id = db.Column(db.Integer,
                         db.ForeignKey("Venue.id", ondelete="CASCADE"))
    artist_id = db.Column(db.Integer,
                          db.ForeignKey("Artist.id", ondelete="CASCADE"))
    duration = db.Column(db.Integer)
Exemple #2
0
class Conversation(db.Model):
    __tablename__ = "conversations"
    id = db.Column(db.Integer, primary_key=True)
    circle_id = db.Column(db.Integer, db.ForeignKey("circles.id"))
    name = db.Column(db.String(120))
    created = db.Column(db.DateTime)
    updated = db.Column(db.DateTime)
    device_access = db.Column(db.Boolean)

    circle = db.relationship("Circle", back_populates="conversations")
    links = db.relationship("UserToConversation",
                            back_populates="conversation")
    messages = db.relationship("Message",
                               back_populates="conversation",
                               order_by="Message.id",
                               cascade="all, delete-orphan")

    def __repr__(self):
        return "<Conversation(id='%d' name='%s' created='%s' updated='%s')>" % (
            self.id, self.name, str(self.created), str(self.updated))

    def __init__(self,
                 name=None,
                 created=datetime.datetime.now(),
                 updated=datetime.datetime.now(),
                 device_access=False,
                 circle=None):
        if created is not None:
            if type(created) is str:
                self.created = DateParser.parse(created)
            else:
                self.created = created
        if updated is not None:
            if type(updated) is str:
                self.updated = DateParser.parse(updated)
            else:
                self.updated = updated
        if name is not None and name != "":
            self.name = name
        else:
            self.name = "Conversation"
        if circle is not None:
            self.circle = circle
        self.device_access = device_access
        db.session.add(self)
        db.session.flush()
        logger.debug(
            "Database add: conversations%s", {
                "id": self.id,
                "name": self.name,
                "circle_id": self.circle_id,
                "device_access": self.device_access
            })

    def mobile_notification(self, title, body):
        for link in self.links:
            #ios.send_notification(link.user, alert)
            android.send_notification(link.user, title=title, body=body)

    def has_members(self, *args):
        for member in args:
            tf = False
            for link in self.links:
                if link.user_id == member.id:
                    tf = True
            if tf is False:
                return False
        return True

    def update_content(self,
                       created=None,
                       updated=datetime.datetime.now(),
                       name=None,
                       device_access=None):
        if created is not None:
            if type(created) is str:
                self.created = DateParser.parse(created)
            else:
                self.created = created
        if updated is not None:
            if type(updated) is str:
                self.updated = DateParser.parse(updated)
            else:
                self.updated = updated
        if name is not None and name != "":
            self.name = name
        if device_access is not None:
            self.device_access = device_access
        db.session.commit()
        db.session.flush()
        logger.debug(
            "Database update: conversations%s", {
                "id": self.id,
                "name": self.name,
                "circle_id": self.circle_id,
                "device_access": self.device_access
            })

    def notify_users(self, p1='conversation', p2=None):
        if p2 is None:
            p2 = {}
        p2['conversation_id'] = self.id
        emit(p1, p2, room='conversation_' + str(self.id), namespace='/')

    def set_other_admin(self):
        for link in self.links:
            link.update_content(privilege="ADMIN")
            return True

    def check_validity(self):
        if (len(self.links) + (1 if self.device_access else 0)) <= 1:
            for link in self.links:
                db.session.delete(link)
            db.session.delete(self)
            return False
        return True

    def get_content(self):
        return {
            "id": self.id,
            "name": self.name,
            "created": self.created,
            "updated": self.updated,
            "circle": self.circle.get_simple_content(),
            "links": [link.get_content() for link in self.links],
            "messages":
            [message.get_simple_content() for message in self.messages],
            "device_access": self.device_access
        }

    def get_simple_content(self):
        return {
            "id": self.id,
            "name": self.name,
            "created": self.created,
            "updated": self.updated,
            "circle_id": self.circle_id,
            "device_access": self.device_access
        }
Exemple #3
0
class Message(db.Model):
    __tablename__ = "messages"
    id = db.Column(db.Integer, primary_key=True)
    conversation_id = db.Column(db.Integer, db.ForeignKey("conversations.id"))
    link_id = db.Column(db.Integer,
                        db.ForeignKey("user_to_conversation.id"),
                        nullable=True)
    device_id = db.Column(db.Integer,
                          db.ForeignKey("devices.id"),
                          nullable=True)
    sent = db.Column(db.DateTime)
    read = db.Column(db.DateTime)
    text_content = db.Column(db.String(8192))
    is_user = db.Column(db.Boolean)

    link = db.relationship("UserToConversation", back_populates="messages")
    conversation = db.relationship("Conversation", back_populates="messages")
    media_links = db.relationship("MessageToMedia",
                                  back_populates="message",
                                  order_by="MessageToMedia.id",
                                  cascade="all, delete-orphan")
    device = db.relationship("Device", back_populates="messages")

    def __repr__(self):
        return "<NeoMessage(id='%d' sent='%s' read='%s')>" % (
            self.id, str(self.sent), str(self.read))

    def __init__(self,
                 sent=datetime.datetime.now(),
                 read=None,
                 content=None,
                 is_user=True,
                 link=None,
                 conversation=None):
        if sent is not None:
            if type(sent) is str:
                self.sent = DateParser.parse(sent)
            else:
                self.sent = sent
        if read is not None:
            if type(read) is str:
                self.read = DateParser.parse(read)
            else:
                self.reed = read
        if content is not None:
            self.text_content = content
        if link is not None:
            self.link = link
        if conversation is not None:
            self.conversation = conversation
        self.is_user = is_user
        db.session.add(self)
        db.session.flush()
        logger.debug("Database add: messages%s", self.get_simple_content())

    def update_content(self,
                       sent=None,
                       read=datetime.datetime.now(),
                       content=None,
                       is_user=None):
        if sent is not None:
            if type(sent) is str:
                self.sent = DateParser.parse(sent)
            else:
                self.sent = sent
        if read is not None:
            if type(read) is str:
                self.read = DateParser.parse(read)
            else:
                self.reed = read
        if content is not None:
            self.text_content = content
        if is_user is not None:
            self.is_user = is_user
        db.session.commit()
        db.session.flush()
        logger.debug("Database update: messages%s", self.get_simple_content())

    def get_content(self):
        if self.is_user:
            return {
                "id": self.id,
                "link": self.link.get_simple_content()
                if self.link is not None else {},
                "sent": self.sent,
                "read": self.read,
                "content": self.text_content,
                "medias": [media.get_content() for media in self.media_links]
            }
        else:
            return {
                "id": self.id,
                "sent": self.sent,
                "read": self.read,
                "content": self.text_content,
                "medias": [media.get_content() for media in self.media_links],
                "device": self.device.get_simple_content()
            }

    def get_simple_json_compliant_content(self):
        if self.is_user:
            return {
                "id":
                self.id,
                "link_id":
                self.link_id,
                "sent":
                None if self.sent is None else self.sent.isoformat(),
                "read":
                None if self.read is None else self.read.isoformat(),
                "content":
                self.text_content,
                "medias":
                len(self.media_links) if self.media_links is not None else 0
            }
        else:
            return {
                "id":
                self.id,
                "device_id":
                self.device_id,
                "sent":
                None if self.sent is None else self.sent.isoformat(),
                "read":
                None if self.read is None else self.read.isoformat(),
                "content":
                self.text_content,
                "medias":
                len(self.media_links) if self.media_links is not None else 0
            }

    def get_simple_content(self):
        if self.is_user:
            return {
                "id":
                self.id,
                "link_id":
                self.link_id,
                "sent":
                self.sent,
                "read":
                self.read,
                "content":
                self.text_content,
                "medias":
                len(self.media_links) if self.media_links is not None else 0
            }
        else:
            return {
                "id":
                self.id,
                "device_id":
                self.device_id,
                "sent":
                self.sent,
                "read":
                self.read,
                "content":
                self.text_content,
                "medias":
                len(self.media_links) if self.media_links is not None else 0
            }
Exemple #4
0
class Order(db.Model):
    id = db.Column(db.String(32), nullable=True)
    oid = db.Column(db.String(32), primary_key=True, nullable=False)
    # 设置外键
    uid = db.Column(db.Integer, db.ForeignKey('user.id'))
    user_phone = db.Column(db.String(20), nullable=False)
    user = relationship("User", backref="order_of_user")
    good_id = db.Column(db.String(32), nullable=False)
    count = db.Column(db.Integer, default=1)
    unit_price = db.Column(db.Float)
    total_price = db.Column(db.Float)
    discount_info = db.Column(db.String(100))
    create_time = db.Column(db.Integer)
    change_time = db.Column(db.Integer)
    status = db.Column(db.Integer, default=1)
    is_del = db.Column(db.Boolean, default=False)
    store_id = db.Column(db.String(32), default='0')

    phoneNum = db.Column(db.String(20), nullable=False)
    name = db.Column(db.String(10))
    address = db.Column(db.String(100))

    paymethod = db.Column(db.String(32))
    actual_price = db.Column(db.Float)
    paytime = db.Column(db.Integer)

    express = db.Column(db.String(32))
    delivery_time = db.Column(db.Integer)
    group_time = db.Column(db.Integer)
    confirm_time = db.Column(db.Integer)
    cancel_time = db.Column(db.Integer)
    text = db.Column(db.String(100))
    is_group = db.Column(db.Boolean, default=False, nullable=True)

    coupon_id = db.Column(db.String(32))
    coupon_name = db.Column(db.String(32))
    coupon_discount = db.Column(db.Float)

    integral_count = db.Column(db.Integer)
    integral_discount = db.Column(db.Float)

    def __init__(self, *args):
        self.id = args[0]
        self.oid = args[0]
        self.uid = args[1]
        self.user_phone = args[2]
        self.good_id = args[3]
        self.count = args[4]
        self.unit_price = args[5]
        self.total_price = args[6]
        self.create_time = args[7]
        self.status = args[8]
        self.store_id = args[9]
        self.phoneNum = args[10]
        self.name = args[11]
        self.address = args[12]

    __mapper_args__ = {"order_by": change_time.desc()}

    def to_dict(self):
        return {c.name: getattr(self, c.name) for c in self.__table__.columns}

    def __repr__(self):
        return '<Order %r>' % self.oid
Exemple #5
0
    @classmethod
    def choices(cls):
        return [(choice.value, str(choice).replace("WeekDays.", ""))
                for choice in cls]

    @classmethod
    def coerce(cls, item):
        return item if isinstance(item, WeekDays) else WeekDays[item]


genre_venue = db.Table(
    "genre_venue",
    db.Column("genre_id",
              db.Integer,
              db.ForeignKey("Genre.id"),
              primary_key=True),
    db.Column("venue_id",
              db.Integer,
              db.ForeignKey("Venue.id"),
              primary_key=True),
)

genre_artist = db.Table(
    "genre_artist",
    db.Column("genre_id",
              db.Integer,
              db.ForeignKey("Genre.id"),
              primary_key=True),
    db.Column("artist_id",
              db.Integer,
Exemple #6
0
class UserToConversation(db.Model):
    __tablename__ = "user_to_conversation"
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey("users.id"))
    conversation_id = db.Column(db.Integer, db.ForeignKey("conversations.id"))
    privilege = db.Column(db.String(10))
    created = db.Column(db.DateTime)
    updated = db.Column(db.DateTime)

    messages = db.relationship("Message",
                               back_populates="link",
                               order_by="Message.sent")
    conversation = db.relationship("Conversation", back_populates="links")
    user = db.relationship("User", back_populates="conversation_links")

    def __repr__(self):
        return "<UserToConversation(id='%d' user_id='%d' conversation_id='%d' privilege='%s')>" % (
            self.id, self.user_id, self.conversation_id, self.privilege)

    def __init__(self,
                 created=datetime.datetime.now(),
                 updated=datetime.datetime.now(),
                 privilege=None,
                 user=None,
                 conversation=None):
        if created is not None:
            if type(created) is str:
                self.created = DateParser.parse(created)
            else:
                self.created = created
        if updated is not None:
            if type(updated) is str:
                self.updated = DateParser.parse(updated)
            else:
                self.updated = updated
        if privilege is not None and privilege != "":
            self.privilege = privilege
        else:
            self.privilege = "STANDARD"
        if user is not None:
            self.user = user
        if conversation is not None:
            self.conversation = conversation
        db.session.add(self)
        db.session.flush()
        logger.debug(
            "Database add: user_to_conversation%s", {
                "id":
                self.id,
                "privilege":
                self.privilege,
                "user_id":
                self.user_id,
                "conversation_id":
                None if self.conversation is None else self.conversation.id,
                "circle_id":
                None
                if self.conversation is None else self.conversation.circle_id
            })

    def update_content(self,
                       created=None,
                       updated=datetime.datetime.now(),
                       privilege=None):
        if created is not None:
            if type(created) is str:
                self.created = DateParser.parse(created)
            else:
                self.created = created
        if updated is not None:
            if type(updated) is str:
                self.updated = DateParser.parse(updated)
            else:
                self.updated = updated
        if privilege is not None and privilege != "":
            self.privilege = privilege
        db.session.commit()
        db.session.flush()
        logger.debug(
            "Database update: user_to_conversation%s", {
                "id":
                self.id,
                "privilege":
                self.privilege,
                "user_id":
                self.user_id,
                "conversation_id":
                None if self.conversation is None else self.conversation.id,
                "circle_id":
                None
                if self.conversation is None else self.conversation.circle_id
            })

    def get_simple_content(self):
        return {
            "id":
            self.id,
            "created":
            self.created,
            "updated":
            self.updated,
            "privilege":
            self.privilege,
            "user_id":
            self.user_id,
            "conversation_id":
            self.conversation_id,
            "circle_id":
            None if self.conversation is None else self.conversation.circle_id
        }

    def get_content(self):
        return {
            "id": self.id,
            "created": self.created,
            "updated": self.updated,
            "privilege": self.privilege,
            "user_id": self.user.get_simple_content(),
            "conversation_id": self.conversation.get_simple_content(),
            "circle_id":
            None if self.conversation is None else self.conversation.circle_id,
            "messages":
            [message.get_simple_content() for message in self.messages]
        }

    def get_messages(self):
        return {
            "id": self.id,
            "messages": [message.get_content() for message in self.messages]
        }
Exemple #7
0
class UserToCircle(db.Model):
    __tablename__ = "user_to_circle"
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey("users.id"))
    circle_id = db.Column(db.Integer, db.ForeignKey("circles.id"))
    created = db.Column(db.DateTime)
    updated = db.Column(db.DateTime)
    privilege = db.Column(db.String(10))

    user = db.relationship("User", back_populates="circle_link")
    circle = db.relationship("Circle", back_populates="user_link")

    def __repr__(self):
        return "<UserToCircle(id='%d' user_id='%d' circle_id='%d' created='%s' updated='%s' privilege='%s')>"\
               % (self.id, self.user_id, self.circle_id, str(self.created), str(self.updated), self.privilege)

    def __init__(self, created=datetime.datetime.now(), updated=datetime.datetime.now(), privilege="DEFAULT",
                 user=None, circle=None):
        if created is not None:
            if type(created) is str:
                self.created = DateParser.parse(created)
            else:
                self.created = created
        if updated is not None:
            if type(updated) is str:
                self.updated = DateParser.parse(updated)
            else:
                self.updated = updated
        if privilege is not None:
            self.privilege = privilege
        if user is not None:
            self.user = user
        if circle is not None:
            self.circle = circle
        db.session.add(self)
        db.session.flush()
        logger.debug("Database add: user_to_circle%s", {"id": self.id,
                                                        "user_id": self.user_id,
                                                        "circle_id": self.circle_id,
                                                        "privilege": self.privilege})

    def update_content(self, created=None, updated=datetime.datetime.now(), privilege=None):
        if created is not None:
            if type(created) is str:
                self.created = DateParser.parse(created)
            else:
                self.created = created
        if updated is not None:
            if type(updated) is str:
                self.updated = DateParser.parse(updated)
            else:
                self.updated = updated
        if privilege is not None and privilege != "":
            self.privilege = privilege
        db.session.commit()
        db.session.flush()
        logger.debug("Database update: user_to_circle%s", {"id": self.id,
                                                           "user_id": self.user_id,
                                                           "circle_id": self.circle_id,
                                                           "privilege": self.privilege})

    def get_content(self, user=True):
        if user:
            return {
                "id": self.id,
                "user": self.user_id,
                "circle": self.circle.get_simple_content(),
                "created": self.created,
                "updated": self.updated,
                "privilege": self.privilege
            }
        else:
            return {
                "id": self.id,
                "user": self.user.get_simple_content(),
                "circle": self.circle_id,
                "created": self.created,
                "updated": self.updated,
                "privilege": self.privilege
            }
Exemple #8
0
class DeviceToMedia(db.Model):
    __tablename__ = "device_to_media"
    id = db.Column(db.Integer, primary_key=True)
    device_id = db.Column(db.Integer, db.ForeignKey('devices.id'))
    media_id = db.Column(db.Integer, db.ForeignKey('medias.id'))
    upload_time = db.Column(db.DateTime)
    purpose = db.Column(db.String(16))

    device = db.relationship("Device", back_populates="media_links")
    media = db.relationship("Media", back_populates="device_link")

    def __repr__(self):
        return "<DeviceToMedia(id=%d, device_id=%d, media_id=%d)>" % (
            self.id, self.device_id, self.media_id)

    def __init__(self,
                 device=None,
                 media=None,
                 upload_time=datetime.datetime.now(),
                 purpose="default"):
        if device is not None:
            self.device = device
        if media is not None:
            self.media = media
        if upload_time is not None:
            if type(upload_time) is str:
                self.upload_time = DateParser.parse(upload_time)
            else:
                self.upload_time = upload_time
        if purpose is not None:
            self.purpose = purpose
        db.session.add(self)
        db.session.flush()
        logger.debug(
            "Database add: device_to_media%s", {
                "id": self.id,
                "device_id": self.device_id,
                "media_id": self.media_id,
                "purpose": self.purpose
            })

    def update_content(self,
                       device=None,
                       media=None,
                       upload_time=None,
                       purpose=None):
        if device is not None:
            self.device = device
        if media is not None:
            self.media = media
        if upload_time is not None:
            if type(upload_time) is str:
                self.upload_time = DateParser.parse(upload_time)
            else:
                self.upload_time = upload_time
        if purpose is not None:
            self.purpose = purpose
        db.session.commit()
        db.session.flush()
        logger.debug(
            "Database update: device_to_media%s", {
                "id": self.id,
                "device_id": self.device_id,
                "media_id": self.media_id,
                "purpose": self.purpose
            })

    def get_content(self):
        return {
            "id": self.id,
            "device": self.device.get_simple_content(),
            "media": self.media.get_simple_content(),
            "upload_time": self.upload_time,
            "purpose": self.purpose
        }

    def get_simple_content(self):
        return {
            "id": self.id,
            "device_id": self.device_id,
            "media_id": self.media_id,
            "upload_time": self.upload_time,
            "purpose": self.purpose
        }
Exemple #9
0
class CircleInvite(db.Model):
    __tablename__ = "circle_invites"
    id = db.Column(db.Integer, primary_key=True)
    circle_id = db.Column(db.Integer, db.ForeignKey("circles.id"))
    user_id = db.Column(db.Integer, db.ForeignKey("users.id"))
    created = db.Column(db.DateTime)
    updated = db.Column(db.DateTime)

    user = db.relationship("User", back_populates="circle_invite")
    circle = db.relationship("Circle", back_populates="circle_invite")

    def __repr__(self):
        return "<CircleInvite(id='%d' circle_id='%d' user_id='%d' created='%s' updated='%s')>" % (
            self.id, self.circle_id, self.user_id, str(
                self.created), str(self.updated))

    def __init__(self,
                 created=datetime.datetime.now(),
                 updated=datetime.datetime.now()):
        if created is not None:
            if type(created) is str:
                self.created = DateParser.parse(created)
            else:
                self.created = created
        if updated is not None:
            if type(updated) is str:
                self.updated = DateParser.parse(updated)
            else:
                self.updated = updated
        db.session.add(self)
        db.session.flush()
        logger.debug("Database add: circle_invites%s", {
            "id": self.id,
            "circle_id": self.circle_id,
            "user_id": self.user_id
        })

    def update_content(self, created=None, updated=datetime.datetime.now()):
        if created is not None:
            if type(created) is str:
                self.created = DateParser.parse(created)
            else:
                self.created = created
        if updated is not None:
            if type(updated) is str:
                self.updated = DateParser.parse(updated)
            else:
                self.updated = updated
        db.session.commit()
        db.session.flush()
        logger.debug("Database update: circle_invites%s", {
            "id": self.id,
            "circle_id": self.circle_id,
            "user_id": self.user_id
        })

    def notify_user(self, p1='circle_invite', p2=None):
        if p2 is None:
            p2 = {}
        p2['circle_invite_id'] = self.id
        return sockets.notify_user(self.user, False, p1, p2)

    def get_simple_content(self):
        return {
            "id": self.id,
            "circle_id": self.circle_id,
            "user_id": self.user_id,
            "created": self.created,
            "updated": self.updated
        }

    def get_content(self, user=True):
        if user:
            return {
                "id": self.id,
                "updated": self.updated,
                "created": self.created,
                "user": self.user_id,
                "circle": self.circle.get_simple_content()
            }
        else:
            return {
                "id": self.id,
                "updated": self.updated,
                "created": self.created,
                "user": self.user.get_simple_content(),
                "circle": self.circle_id
            }
Exemple #10
0
class Device(db.Model):
    __tablename__ = "devices"
    id = db.Column(db.Integer, primary_key=True)
    circle_id = db.Column(db.Integer, db.ForeignKey('circles.id'))
    key = db.Column(db.String(20))
    activated = db.Column(db.Boolean)
    username = db.Column(db.String(120), unique=True)
    password = db.Column(db.String(2048))
    json_token = db.Column(db.String(2048))
    name = db.Column(db.String(120))
    created = db.Column(db.DateTime)
    updated = db.Column(db.DateTime)
    is_online = db.Column(db.Boolean)

    # RELATIONS
    circle = db.relationship("Circle", back_populates="device")
    messages = db.relationship("Message", back_populates="device")
    media_links = db.relationship("DeviceToMedia", back_populates="device", order_by="DeviceToMedia.id",
                                  cascade="all, delete-orphan")

    def __init__(self, created=datetime.datetime.now(), updated=datetime.datetime.now(),
                 username=None, name=None, activated=False, is_online=None):
        if type(created) is str:
            self.created = DateParser.parse(created)
        else:
            self.created = datetime.datetime.now()
        if type(updated) is str:
            self.updated = DateParser.parse(updated)
        else:
            self.updated = datetime.datetime.now()
        if name is not None and name != "":
            self.name = name
        else:
            self.name = "My Device %d" % self.id
        if activated is not None:
            self.activated = activated
        if is_online is not None:
            self.is_online = is_online
        else:
            self.is_online = False
        # USERNAME / PASSWORD AND KEY GENERATION
        # NEED TO INSTALL pycrypto and cypher the password for the storage before activation
        if username is not None:
            self.username = username
        else:
            c = True
            while c:
                username = ''.join(random.choice(string.ascii_uppercase) for _ in range(12))
                if db.session.query(Device).filter(Device.username == username).first() is None:
                    c = False
            self.username = username
        password = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10))
        self.password = base64.b64encode(str.encode(password)).decode('utf-8')
        self.key = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(20))
        db.session.add(self)
        db.session.flush()
        logger.debug("Database add: devices%s", {"id": self.id,
                                                 "name": self.name,
                                                 "circle_id": self.circle.id if self.circle is not None else -1,
                                                 "activated": self.activated,
                                                 "username": self.username,
                                                 "is_online": self.is_online})

    def set_password(self, password):
        self.password = base64.b64encode(str.encode(password)).decode('utf-8')

    def __repr__(self):
        return "<Device(id='%s' name='%s' created='%s' updated='%s')>" % \
               (self.id, self.name, str(self.created), str(self.updated))

    def update_content(self, created=None, updated=datetime.datetime.now(), name=None, activated=None, is_online=None):
        if type(created) is str:
            self.created = DateParser.parse(created)
        elif created is not None:
            self.created = created
        if type(updated) is str:
            self.updated = DateParser.parse(updated)
        elif updated is not None:
            self.updated = updated
        if name is not None and name != "":
            self.name = name
        if activated is not None:
            self.activated = activated
        if is_online is not None:
            self.is_online = is_online
        db.session.commit()
        db.session.flush()
        logger.debug("Database update: devices%s", {"id": self.id,
                                                    "name": self.name,
                                                    "circle_id": self.circle.id if self.circle is not None else -1,
                                                    "activated": self.activated,
                                                    "username": self.username,
                                                    "is_online": self.is_online})

    def disconnect(self):
        self.json_token = ""
        db.session.commit()

    @staticmethod
    def decode_auth_token_old(auth_token):
        try:
            payload = jwt.decode(auth_token, SECRET_KEY)
            device = db.session.query(Device).filter(Device.id == payload['sub']).first()
            if device is not None:
                if device.json_token == "" or device.json_token is None:
                    return False, "Device non authentifié"
                if not device.activated:
                    return False, "Device non activé"
                return True, device
            else:
                return False, "Device Neo introuvable"
        except jwt.ExpiredSignatureError:
            return False, "La session a expiré, authentifiez vous a nouveau"
        except jwt.InvalidTokenError:
            return False, 'Token invalide, authentifiez vous a nouveau'
        except Exception as e:
            return False, 'Une erreur est survenue : ' + str(e)

    def decode_auth_token(auth_token):
        try:
            payload = jwt.decode(auth_token, SECRET_KEY)
            device = db.session.query(Device).filter(Device.id == payload['sub']).first()
            if device is None:
                raise TokenNotBoundToDevice
            if device.json_token is None:
                raise UnauthenticatedDevice
            if not device.activated:
                raise UnactivatedDevice
            return device
        except jwt.ExpiredSignatureError:
            raise ExpiredUserSession
        except jwt.InvalidTokenError:
            raise InvalidJwtToken
        return None

    def encode_auth_token(self):
        try:
            payload = {
                'exp': datetime.datetime.utcnow() + datetime.timedelta(days=30, seconds=1),
                'iat': datetime.datetime.utcnow(),
                'sub': self.id
            }
            token = jwt.encode(payload, SECRET_KEY, algorithm="HS256")
            self.json_token = token.decode()
            db.session.commit()
            return token.decode()
        except Exception as e:
            print(e)
            return None

    def check_password(self, password=None):
        if password is not None and password != "":
            if self.password == hashlib.sha512(password.encode("utf-8")).hexdigest():
                return True
        return False

    def authenticate(self, password=None):
        if self.password != hashlib.sha512(password.encode('utf-8')).hexdigest():
            raise InvalidPassword
        if self.json_token is not None:
            try:
                jwt.decode(self.json_token, SECRET_KEY)
                return self.json_token
            except jwt.ExpiredSignature:
                pass
        return self.encode_auth_token()

    def update_password(self, password=None):
        if password is not None and password != "":
            self.password = hashlib.sha512(password.encode('utf-8')).hexdigest()
            db.session.commit()

    def activate(self, activation_key):
        if self.key == activation_key:
            self.activated = True
            pw = base64.b64decode(str.encode(self.password))
            self.password = hashlib.sha512(pw).hexdigest()
            db.session.commit()
        return self.activated

    def get_pre_activation_password(self):
        if self.activated is False:
            return base64.b64decode(str.encode(self.password)).decode('utf-8')
        raise Exception("Ce device est active")

    def get_simple_content(self):
        return {
            "id": self.id,
            "name": self.name,
            "created": self.created,
            "updated": self.updated,
            "circle_id": self.circle.id if self.circle is not None else -1,
            "activated": self.activated,
            "username": self.username,
            "is_online": self.is_online
        }

    def get_simple_json_compliant_content(self):
        return {
            "id": self.id,
            "name": self.name,
            "created": None if self.created is None else self.created.isoformat(),
            "updated": None if self.updated is None else self.updated.isoformat(),
            "circle_id": self.circle.id if self.circle is not None else -1,
            "activated": self.activated,
            "username": self.username,
            "is_online": self.is_online
        }

    def get_content(self):
        return {
            "id": self.id,
            "name": self.name,
            "created": self.created,
            "updated": self.updated,
            "activated": self.activated,
            "username": self.username,
            "circle": self.circle.get_simple_content() if self.circle is not None else {},
            "messages": [message.get_simple_content() for message in self.messages],
            "medias": [link.get_content() for link in self.media_links],
            "is_online": self.is_online
        }