Esempio n. 1
0
class Photo(me.EmbeddedDocument):
    id = me.ObjectIdField(required=True, default=bson.ObjectId)

    caption = me.StringField(default='')

    created_date = me.DateTimeField(required=True,
                                    default=datetime.datetime.now)
    updated_date = me.DateTimeField(required=True,
                                    default=datetime.datetime.now)

    image = me.ImageField(
        collection_name='images',
        size=(1600, 1200, True),
        thumbnail_size=(320, 240, True),
    )

    comments = me.ListField(me.EmbeddedDocumentField(forums.Comment))
    license = me.StringField(required=True,
                             default='COPYRIGHT',
                             choices=LICENSE)

    user = me.ReferenceField("User", dbref=True, required=True)

    orientation = me.StringField(required=True,
                                 default='horizontal',
                                 choices=['vertical', 'horizontal'])

    def get_album(self):
        album = PhotoAlbum.objects(photos__id=self.id).first()
        return album
Esempio n. 2
0
class StudentUser(mongoengine.Document, UserMixin):
    meta = {'collection': 'students'}

    userID = mongoengine.StringField(required=True)

    # profile information -- server/users/students/forms.py
    #                     -- server/users/students/routes.py (createProfile)
    username = mongoengine.StringField(required=True)
    password = mongoengine.StringField(required=True)
    imageFile = mongoengine.ImageField()

    # contact information -- server/users/parents/forms.py
    #                     -- server/users/parents/routes.py (register)
    firstName = mongoengine.StringField(required=True)
    lastName = mongoengine.StringField(required=True)
    email = mongoengine.EmailField()

    # acquired from parents collection
    parent = mongoengine.ObjectIdField()

    def getResetToken(self, expiresSec=1800):
        s = Serializer(current_app.config['SECRET_KEY'], expiresSec)
        return s.dumps({'userID': self.userID}).decode('utf-8')

    @staticmethod
    def verifyResetToken(token):
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
            userID = s.loads(token)['userID']
        except:
            return None
        return db.students.find_one({"userID": userID})

    def __repr__(self):
        return f"User('{self.username}', '{self.email}', '{self.imageFile}')"
Esempio n. 3
0
class Liepin_overseas(mongoengine.Document):
    # 公司logo
    company_logo = mongoengine.ImageField()
    # 公司名
    company_title = mongoengine.StringField(max_length=100)
    # 职位一
    position1 = mongoengine.StringField(max_length=100)
    # 职位二
    position2 = mongoengine.StringField(max_length=100)
Esempio n. 4
0
class Pano(me.Document):
    location = me.StringField()
    longlat = me.PointField(auto_index=True) # note that the coordinates are (long, lat) pairs
    heading = me.FloatField(default=None)
    fov = me.FloatField(default=90)
    pitch = me.FloatField(default=0)
    pano_id = me.StringField()
    image = me.ImageField()

    meta = {
        'indexes': ['pano_id']
    }

    @property
    def size(self):
        return self.image.size

    @property
    def url(self):
        loc = self.location or self.longlat
        return generate_pano_url(loc, self.heading, self.fov, self.pitch, self.size, self.pano_id)
    
    @property
    def image_md5(self):
        '''return the md5 hash of the stored image'''
        if self.image:
            return self.image.md5
        return None

    @property
    def PIL_image(self):
        if hasattr(self, '_PIL_image'):
            return self._PIL_image
        self._PIL_image = Image.open(cStringIO.StringIO(self.image.read()))
        return self._PIL_image

    @property
    def has_image(self):
        '''return False if the image is a null image'''
        return self.image_md5 != no_image_md5

    def show_image(self):
        return self.PIL_image.show()

    def __unicode__(self):
        return 'location=%r, longlat=%r, image_md5=%r' % (self.location, self.longlat['coordinates'], self.image_md5)

    @staticmethod
    def new_pano(location=None, heading=None, fov=90, pitch=0, size=(640, 640), pano_id=None, key=None):
        image = cStringIO.StringIO(get_pano(location, heading, fov, pitch, size, pano_id, key))
        params = dict(heading=heading, fov=fov, pitch=pitch, size=size, pano_id=pano_id, image=image)
        if isinstance(location, str):
            pano = Pano(location=location, **params)
        else:
            # location is provided as a (long, lat) pair
            pano = Pano(longlat=location, **params)
        return pano
Esempio n. 5
0
class Box(mongoengine.Document):
    box_id = mongoengine.ObjectIdField()
    #   leader = mongoengine.ReferenceField(User, required=True)
    name = mongoengine.StringField(required=True)
    description = mongoengine.StringField(required=True)
    state = mongoengine.IntField(default=0)
    creation_date = mongoengine.DateTimeField(default=datetime.datetime.now)
    tags = mongoengine.ListField(mongoengine.StringField())
    box_image = mongoengine.ImageField()

    splits = mongoengine.ListField(mongoengine.ReferenceField(Split))

    meta = {'collection': 'boxes'}
Esempio n. 6
0
class MathExercises(me.Document):
    GRADE_CHOICES = (
        ('ONE', _('Grade One')),
        ('TWO', _('Grade Two')),
        ('THREE', _('Grade Three')),
        ('FOUR', _('Grade Four')),
        ('FIVE', _('Grade Five')),
    )
    STATUS_CHOICES = (
        ('A', _('APPROVED')),
        ('P', _('PENDING')),
        ('R', _('REJECTED')),
        ('D', _('DEPRECATED')),
    )
    TYPE_CHOICES = (('F', _('Fill in blank')), ('T', _('True or false')),
                    ('C', _('Choice')), ('CA', _('Calculation ')),
                    ('W', _('Word problems')))
    grade = me.StringField(max_length=8, choices=GRADE_CHOICES, required=True)
    knowledge_point = me.ReferenceField(KnowledgePoint)
    status = me.StringField(max_length=2, choices=STATUS_CHOICES, default='P')
    #type = me.StringField(max_length=2, choices=TYPE_CHOICES, default='W')
    question = me.StringField(max_length=1024, required=True)
    question_image = me.ImageField(size=(800, 600, True),
                                   thumbnail_size=(200, 150, False))
    question_in_perseus = me.StringField(max_length=2048, default='')
    answer_image = me.ImageField(size=(800, 600, True),
                                 thumbnail_size=(200, 150, False))
    answer_in_perseus = me.StringField(max_length=2048, default='')
    updated = me.DateTimeField(default=datetime.datetime.utcnow)
    created = me.DateTimeField(default=datetime.datetime.utcnow)
    creator = me.StringField(max_length=128, default='Qiujie Yao')

    meta = {
        'collection': 'math_exercises',
        'allow_inheritance': True,
        'ordering': ['-updated', '-created'],
    }
Esempio n. 7
0
class Image(db.EmbeddedDocument):
    img_id = db.UUIDField(db_field="audio", unqiue=True, default=uuid.uuid4())
    filename = db.StringField(required=True)
    date_upload = db.DateTimeField(default=datetime.utcnow)
    payload = db.ImageField(required=True, thumbnail_size=(100, 100, False))

    def json(self):
        user_dict = {
            "image_id": self.img_id,
            "filename": self.filename,
            "date_uploaded": self.date_upload,
            "payload": self.payload,
        }
        return json.dumps(user_dict)

    meta = {"indexes": [], "ordering": ["date_uploaded"]}
Esempio n. 8
0
class User(mongoengine.Document):

    full_name = mongoengine.StringField(required=True)

    photo = mongoengine.ImageField(required=False)

    user_name = mongoengine.StringField(required=True)

    password = mongoengine.StringField(required=True)

    user_type = mongoengine.StringField(required=True)

    email = mongoengine.EmailField(required=True)

    user_telegram = mongoengine.StringField(required=False)

    meta = {'db_alias': 'core', 'collection': 'users'}
Esempio n. 9
0
class Photo(me.EmbeddedDocument):
    id = me.ObjectIdField(required=True, default=bson.ObjectId)
    
    caption = me.StringField(default='')
    
    created_date = me.DateTimeField(required=True, default=datetime.datetime.now)
    updated_date = me.DateTimeField(required=True, default=datetime.datetime.now)

    image = me.ImageField(collection_name='images',
                          size=(1024, 786, True),
                          thumbnail_size=(320, 240, True),
                          )
    comments = me.ListField(me.EmbeddedDocumentField(forums.Comment))
    license = me.StringField(required=True, default='COPYRIGHT', choices=LICENSE)
    
    def get_album(self):
        album = PhotoAlbum.objects(photos__id = self.id).first()
        return album
Esempio n. 10
0
File: user.py Progetto: laik/leaf
class User(mongoengine.Document):
    """
    用户数据库模型:
        created: 创建时间 默认为utc时间
        disabled: 用户是否已被禁用
        groups: 用户被分配到的用户组信息
        indexs: 用户的索引信息列表
        informations: 用户的个人信息
    """

    created = mongoengine.IntField(default=time.now)
    disabled = mongoengine.BooleanField(default=False)
    groups = mongoengine.ListField(mongoengine.ReferenceField(
        Group, reverse_delete_rule=mongoengine.PULL), default=list)
    indexs = mongoengine.EmbeddedDocumentListField(UserIndex, default=list)
    avatar = mongoengine.ImageField(
        size=settings.User.AvatarSize,
        thumbnail_size=settings.User.AvatarThumbnailSize)
    informations = mongoengine.DictField()
Esempio n. 11
0
class Product(me.Document):
    title = me.StringField(required=True, max_length=256)
    description = me.StringField(max_length=500)
    in_stock = me.BooleanField(default=True)
    discount = me.IntField(min_value=0, max_value=100, default=0)
    price = me.FloatField(required=True)
    image = me.ImageField()
    category = me.ReferenceField(Category, required=True)
    parameters = me.EmbeddedDocumentField(Parameters)

    def get_description(self):
        if self.description:
            return f'{self.title}\n{self.description}\n{self.price}'
        else:
            return f'{self.title}\n{self.price}'

    @property
    def product_price(self):
        return (100 - self.discount) / 100 * self.price
Esempio n. 12
0
class Image(me.Document):
    # Basics
    filename = me.StringField(max_length=128, required=True)
    analysis_date = me.DateTimeField(default=dt.utcnow(), required=True)
    telescope = me.StringField(max_length=3, choices=['V5', 'V20'])
    compressed = me.BooleanField()
    # Header Info
    target = me.StringField(max_length=128)
    exptime = me.DecimalField(min_value=0, precision=1)
    date = me.DateTimeField()
    filter = me.StringField(max_length=15)
    header_RA = me.DecimalField(min_value=0, max_value=360, precision=4)
    header_DEC = me.DecimalField(min_value=-90, max_value=90, precision=4)
    alt = me.DecimalField(min_value=0, max_value=90, precision=2)
    az = me.DecimalField(min_value=0, max_value=360, precision=2)
    airmass = me.DecimalField(min_value=1, precision=3)
    moon_alt = me.DecimalField(min_value=-90, max_value=90, precision=1)
    moon_illumination = me.DecimalField(min_value=0,
                                        max_value=100,
                                        precision=1)
    moon_separation = me.DecimalField(min_value=0, max_value=180, precision=1)
    # Analysis Results
    analyzed = me.BooleanField()
    SIDREversion = me.StringField(max_length=12)
    FWHM_pix = me.DecimalField(min_value=0, precision=1)
    ellipticity = me.DecimalField(min_value=0, precision=2)
    RA = me.DecimalField(min_value=0, max_value=360, precision=4)
    DEC = me.DecimalField(min_value=-90, max_value=90, precision=4)
    perr_arcmin = me.DecimalField(min_value=0, precision=2)
    # JPEGs
    full_field_jpeg = me.ImageField(thumbnail_size=(128, 128, True))
    cropped_jpeg = me.ImageField(thumbnail_size=(128, 128, True))

    meta = {
        'collection': 'images',
        'indexes': ['telescope', 'date', 'filename']
    }

    def __str__(self):
        output = 'MongoEngine Document for: {}\n'.format(self.filename)
        output += '  Analysis Date: {}\n'.format(
            self.analysis_date.isoformat())
        if self.telescope: output += '  Telescope: {}\n'.format(self.telescope)
        if self.target: output += '  Target Field: {}\n'.format(self.target)
        if self.date:
            output += '  Image Date: {}\n'.format(self.date.isoformat())
        if self.exptime:
            output += '  Exposure Time: {:.1f}\n'.format(self.exptime)
        if self.filter: output += '  Filter: {}\n'.format(self.filter)
        if self.header_RA:
            output += '  Header RA: {:.4f}\n'.format(self.header_RA)
        if self.header_DEC:
            output += '  Header Dec: {:.4f}\n'.format(self.header_DEC)
        if self.alt: output += '  Altitude: {:.4f}\n'.format(self.alt)
        if self.az: output += '  Azimuth: {:.4f}\n'.format(self.az)
        if self.airmass: output += '  Airmass: {:.3f}\n'.format(self.airmass)
        if self.moon_illumination:
            output += '  moon_illumination: {:.2f}\n'.format(
                self.moon_illumination)
        if self.moon_separation:
            output += '  moon_separation: {:.0f}\n'.format(
                self.moon_separation)
        if self.SIDREversion:
            output += '  SIDREversion: {}\n'.format(self.SIDREversion)
        if self.FWHM_pix:
            output += '  FWHM_pix: {:.1f}\n'.format(self.FWHM_pix)
        if self.ellipticity:
            output += '  ellipticity: {:.2f}\n'.format(self.ellipticity)
        if self.RA: output += '  WCS RA: {:.4f}\n'.format(self.RA)
        if self.DEC: output += '  WCS DEC: {:.4f}\n'.format(self.DEC)
        if self.perr_arcmin:
            output += '  Pointing Error: {:.1f} arcmin\n'.format(
                self.perr_arcmin)
        return output

    def __repr__(self):
        return self.__str__()
class FamousQuote(me.Document):
    text=me.StringField()
    other_notes=me.FileField()
    icon=me.ImageField(size=(400,200,True),thumbnail_size=(20,20,True))
Esempio n. 14
0
class ImageFile(mongoengine.Document):
    file = mongoengine.ImageField()
Esempio n. 15
0
class MusicTrack(mdb.Document):
    track_id = mdb.StringField(required=True, unique=True)
    track_urls = mdb.DictField()
    main_artist = mdb.StringField()
    artists = mdb.ListField()
    album = mdb.StringField()
    genres = mdb.ListField()
    cover_image = mdb.ImageField()
    description = mdb.StringField()
    publisher = mdb.ReferenceField(BotUser)
    queue_sort_num = mdb.IntField()
    available = mdb.BooleanField(default=False)
    seen_by = mdb.ListField()
    comments = mdb.DictField()
    likes = mdb.ListField()
    dislikes = mdb.ListField()
    meta = {
        "indexes": ["track_id"],
        "ordering": ["-queue_sort_num"],
    }

    def add_link(self, link):
        is_set_info = len(self.track_urls) <= 1
        if "apple" in link:
            self.track_urls["Apple Music"] = link
            if self.track_id is None:
                self.track_id = link.split('/')[-2]
            if is_set_info:
                track_info = Spotify.query_track_info(self.track_id)
        elif "spotify" in link:
            query = self.track_urls["Spotify"] = link
            if is_set_info:
                track_info = Spotify.query_track_info(link)
        elif "deezer" in link:
            self.track_urls["Deezer"] = link
            if is_set_info:
                track_info = Deezer.query_track_info(link)
        elif "soundcloud" in link:
            self.track_urls["SoundCloud"] = link
            # if self.track_id is None:
            # 	self.track_id = link.split('/')[-1];
            if is_set_info:
                track_info = SoundCloud.query_track_info(link)
        elif "youtube" in link:
            self.track_urls["Youtube"] = link
            if is_set_info:
                track_info = YouTube.query_track_info(link)
        elif "play.google" in link:
            self.track_urls["Play Music"] = link
            self.track_id = link.split('t=')[-1].replace("_", " ")
            if is_set_info:
                track_info = Spotify.query_track_info(self.track_id)
        else:
            track_info = Spotify.query_track_info(link)
        if is_set_info and track_info:
            self.set_track_info(track_info)
        self.set_other_links(self.track_id, self.artists[0])

    def add_comment(self, user, comment):
        self.comment[user] = comment

    def set_track_info(self, track_info):
        self.track_id = track_info["track_id"]
        self.album = track_info["album"]
        self.main_artist = track_info["artists"][0]
        self.artists = track_info["artists"]
        self.genres = track_info["genres"]
        urllib.request.urlretrieve(track_info["cover_url"], "tmp.png")
        with open("tmp.png", "rb") as img:
            self.cover_image.put(img)
        os.remove("tmp.png")

    def set_other_links(self, track_id, artist):
        if "Spotify" not in self.track_urls:
            track_info = Spotify.query_track_info(f"{artist} {track_id}")
            if track_info:
                self.track_urls["Spotify"] = track_info["track_url"]
        if "Deezer" not in self.track_urls:
            track_info = Deezer.query_track_info(f"{artist} {track_id}")
            if track_info:
                self.track_urls["Deezer"] = track_info["track_url"]
        if "SoundCloud" not in self.track_urls:
            track_info = SoundCloud.query_track_info(f"{artist} {track_id}")
            if track_info:
                self.track_urls["SoundCloud"] = track_info["track_url"]
        if "YouTube" not in self.track_urls:
            pass

    @property
    def generate_message(self):
        artists = ", ".join(self.artists)
        genres = "-" if self.genres is None or not any(
            self.genres) else ", ".join(self.genres)
        description = "-" if self.description is None or self.description == "" else self.description
        seen_by = "-" if self.seen_by is None or not any(
            self.seen_by) else ", ".join([str(user) for user in self.seen_by])
        msgs = [
            f"Track Id: *{self.track_id}*", f"Artists: *{artists}*",
            f"Album: *{self.album}*", f"Genres: *{genres}*",
            f"Description: *{description}*", f"Seen by: *{seen_by}*"
        ]
        return "\n".join(msgs)

    @property
    def edit_menu(self):
        menu = telebot.types.InlineKeyboardMarkup()
        prefix = "Add" if any(self.artists) else "Set"
        artist_button = telebot.types.InlineKeyboardButton(
            text=f"{prefix} artists", callback_data=f"crud/artist/{self.pk}")
        prefix = "Set" if self.album is None or self.album == "" else "Edit"
        album_button = telebot.types.InlineKeyboardButton(
            text=f"{prefix} album", callback_data=f"crud/album/{self.pk}")
        prefix = "Add" if any(self.genres) else "Set"
        genres_button = telebot.types.InlineKeyboardButton(
            text=f"{prefix} genres",
            callback_data=f"crud/genres/choose/{self.pk}")
        prefix = "Set" if self.description is None or self.description == "" else "Edit"
        description_button = telebot.types.InlineKeyboardButton(
            text=f"{prefix} description",
            callback_data=f"crud/description/{self.pk}")
        link_button = telebot.types.InlineKeyboardButton(
            text="Add link", callback_data=f"crud/link/menu/{self.pk}")
        del_button = telebot.types.InlineKeyboardButton(
            text="Remove from collection",
            callback_data=f"crud/delete/ask/{self.pk}")
        if not self.available:
            publish_button = telebot.types.InlineKeyboardButton(
                text="Publish to shared collection",
                callback_data=f"crud/publish/{self.pk}")
        menu.row(artist_button, album_button)
        menu.row(genres_button, description_button)
        menu.row(link_button)
        menu.row(del_button)
        if not self.available:
            menu.row(publish_button)
        return menu
Esempio n. 16
0
class BotUser(mdb.Document):
    username = mdb.StringField(required=True, unique=True)
    chat_id = mdb.IntField(required=True, unique=True)
    first_name = mdb.StringField()
    last_name = mdb.StringField()
    profile_picture = mdb.ImageField()
    bio = mdb.StringField()
    genres = mdb.ListField()
    queue_sort_num = mdb.IntField()
    meta = {
        "indexes": ["username", "chat_id"],
        "ordering": ["-queue_sort_num"],
    }

    def __str__(self):
        return f"{self.first_name} {self.last_name}"

    def set_profile_info(self, message):
        token = config["telegram"]["token"]
        profile_photos = telebot.apihelper.get_user_profile_photos(
            token, message.from_user.id)
        file_id = profile_photos['photos'][0][2]['file_id']
        img_path = telebot.apihelper.get_file(token, file_id)["file_path"]
        img_url = f"https://api.telegram.org/file/bot{token}/{img_path}"
        urllib.request.urlretrieve(img_url, "tmp.png")
        with open("tmp.png", "rb") as img:
            self.profile_picture.put(img)
        os.remove("tmp.png")

    @property
    def generate_message(self):
        bio = "-" if self.bio is None or self.bio == "" else self.bio
        preferences = "-" if self.genres is None or not any(
            self.genres) else ", ".join(self.genres)
        msgs = [
            f"Username: *{self.username}*",
            f"Full name: *{self.first_name} {self.last_name}*",
            f"Bio: *{bio}*", f"Music preferences: *{preferences}*"
        ]
        return "\n".join(msgs)

    @property
    def edit_menu(self):
        menu = telebot.types.InlineKeyboardMarkup()
        firstname_button = telebot.types.InlineKeyboardButton(
            text="Change first name",
            callback_data=f"profile/firstname/{self.pk}")
        lastname_button = telebot.types.InlineKeyboardButton(
            text="Change last name",
            callback_data=f"profile/lastname/{self.pk}")
        bio_button = telebot.types.InlineKeyboardButton(
            text="Fill bio (optional)", callback_data=f"profile/bio/{self.pk}")
        preferences_button = telebot.types.InlineKeyboardButton(
            text="Set music preferences",
            callback_data=f"profile/genres/choose/{self.pk}")
        save_button = telebot.types.InlineKeyboardButton(
            text="Finish editing/checking",
            callback_data=f"profile/save/ask/{self.pk}")
        menu.row(firstname_button, lastname_button)
        menu.row(bio_button, preferences_button)
        menu.row(save_button)
        return menu
Esempio n. 17
0
class Image(mongoengine.Document):
    file = mongoengine.ImageField(required=True)
Esempio n. 18
0
class Image(mongoengine.Document):
    md5 = mongoengine.StringField(unique=True)
    gray = mongoengine.ImageField()
    width = mongoengine.IntField()
    height = mongoengine.IntField()
    create_at = mongoengine.DateTimeField(default=datetime.datetime.now)