Ejemplo n.º 1
0
def get(id):
    """Получить файл по id"""
    content = Content.get_or_none(Content.id == id)
    if content is not None:
        return send_file(content.path, add_etags=False, conditional=True)
    else:
        return errors.not_found()
Ejemplo n.º 2
0
def current_user():
    """Получить текущего пользователя или отредактировать профиль"""
    user = get_user_from_request()

    if request.method == "POST":
        json = request.get_json()

        user.email = json.get("email", user.email)
        user.name = json.get("name", user.name)
        user.about = sanitize(json.get("about", user.about))
        user.birthday = json.get("birthday", user.birthday)
        if "avatar" in json:
            content = Content.get_or_none(Content.id == json["avatar"])
            if content:
                if not content.is_image:
                    return errors.user_avatar_is_not_image()
                elif content.size > 1024 * 500:  # 500kb
                    return errors.user_avatar_too_large()
                else:
                    user.avatar = content

        user.save()

    user = User.get(User.id == user.id)

    return jsonify({"success": 1, "user": user.to_json_with_email()})
Ejemplo n.º 3
0
def convert():
    create_app()

    print("Replacing content")

    for c in Content.select():
        c.path = c.path.replace("/home/service/kolenka-backend/",
                                "/home/service/kolenka-beta-backend/")
        print("New path " + c.path)
        c.save()
Ejemplo n.º 4
0
def fill_blog_from_json(blog, json):
    if json is not None:
        blog.title = json.get("title", blog.title)
        blog.description = sanitize(json.get("description", blog.description))
        blog.url = json.get("url", blog.url)
        blog.blog_type = json.get("blog_type", blog.blog_type)
        if "image" in json:
            blog.image = Content.get_or_none(Content.id == json["image"])

    blog.updated_date = datetime.datetime.now()
Ejemplo n.º 5
0
def edit_blog_for_jam(blog, title, url, image=None):
    blog.title = title
    blog.description = f'Это блог для джема "{title}"'
    # blog.url = url
    if image:
        blog.image = Content.get_or_none(Content.id == image)

    blog.updated_date = datetime.datetime.now()
    blog.save()

    return blog
Ejemplo n.º 6
0
def avatar():
    avatar = Content.create(user=1,
                            path="/some/path",
                            mime="image/jpeg",
                            size=1)

    from src.model import db

    db.db_wrapper.database.close()

    return avatar
Ejemplo n.º 7
0
def edit_my_entry(url):
    """Редактировать заявку на джем от текущего пользователя"""
    user = get_user_from_request()
    jam = Jam.get_or_none(Jam.url == url)

    if jam is None:
        return errors.not_found()

    entry = JamEntry.get_or_none(jam=jam, creator=user)
    if entry is None:
        return errors.not_found()

    json = request.json

    title = json.get("title", entry.title)
    url = json.get("url", entry.url)
    description = json.get("info", entry.info)
    short_description = json.get("short_info", entry.short_info)
    links = json.get("links", [])

    has_entry_with_same_url = False
    entries_with_same_url = JamEntry.select().where((JamEntry.url == url)
                                                    & (JamEntry.jam == jam))
    for e in entries_with_same_url:
        if e.id != entry.id:
            has_entry_with_same_url = True

    if has_entry_with_same_url:
        return errors.jam_entry_url_already_taken()

    image = None
    if "logo" in json:
        image = json["logo"]

    entry.title = title
    entry.url = url
    entry.info = sanitize(description)
    entry.short_info = sanitize(short_description)

    if image:
        entry.logo = Content.get_or_none(Content.id == image)

    JamEntryLink.delete().where(JamEntryLink.entry == entry).execute()
    for link in links:
        JamEntryLink.create(
            entry=entry,
            title=link["title"],
            href=link["href"],
            order=link["order"],
        )

    entry.save()

    return jsonify({"success": 1, "entry": _entry_to_json(entry)})
Ejemplo n.º 8
0
def get_owned():
    query = Content.get_user_files(get_user_from_request())
    limit = max(1, min(int(request.args.get("limit") or 20), 100))
    paginated = PaginatedQuery(query, paginate_by=limit)

    return jsonify({
        "success": 1,
        "files": [p.to_json() for p in paginated.get_object_list()],
        "meta": {
            "page_count": paginated.get_page_count()
        },
    })
Ejemplo n.º 9
0
def upload():
    """Загрузить файл"""

    import magic

    if "file" not in request.files:
        return errors.content_no_file()

    uploaded_file = request.files["file"]
    if uploaded_file.filename == "":
        return errors.content_no_file()

    if not allowed_file(uploaded_file.filename):
        return errors.content_forbidden_extension()

    file_content = uploaded_file.read(MAX_FILE_SIZE + 1)

    size = len(file_content)
    if size > MAX_FILE_SIZE:
        return errors.content_file_size_exceeded()

    uploaded_file.seek(0)
    name = hashlib.md5(uploaded_file.read()).hexdigest()
    uploaded_file.seek(0)

    _, ext = ntpath.splitext(uploaded_file.filename)

    today = datetime.date.today()

    user = get_user_from_request()

    filename = os.path.join(
        current_app.config["UPLOAD_FOLDER"],
        str(user.id) + "/" + str(today.year) + "/" + str(today.month) + "/",
    )

    os.makedirs(filename, exist_ok=True)

    new_path = filename + name + ext
    uploaded_file.save(new_path)

    full_path = os.path.abspath(new_path)

    mime = magic.from_file(full_path, mime=True)

    content = Content.create(user=user.id,
                             path=full_path,
                             size=size,
                             mime=mime)

    return jsonify({"success": 1, "file": content.to_json()})
Ejemplo n.º 10
0
def create_jam():
    """Создать джем"""
    user = get_user_from_request()

    json = request.json
    required_fields = ["title", "url", "description", "short_description"]
    missed_fields = []
    for field in required_fields:
        if field not in json:
            missed_fields.append(field)
    if len(missed_fields) > 0:
        return errors.wrong_payload(missed_fields)

    title = json["title"]
    url = json["url"]
    description = json["description"]
    short_description = json["short_description"]
    image = json.get("logo", None)
    start_date = json.get("start_date", None)
    end_date = json.get("end_date", None)
    criterias = json.get("criterias", [])

    if Jam.get_or_none(Jam.url == url) is not None:
        return errors.jam_url_already_taken()

    blog = create_blog_for_jam(user, title, url, image)

    jam = Jam.create(
        created_date=datetime.datetime.now(),
        updated_date=datetime.datetime.now(),
        creator=user,
        blog=blog,
        title=title,
        url=url,
        short_description=sanitize(short_description),
        description=sanitize(description),
        start_date=start_date,
        end_date=end_date,
    )

    if image:
        jam.logo = Content.get_or_none(Content.id == image)

    jam.save()

    for criteria in criterias:
        JamCriteria.create(jam=jam,
                           title=criteria["title"],
                           order=criteria["order"])

    return jsonify({"success": 1, "jam": jam.to_json()})
Ejemplo n.º 11
0
def migration_v3(db, migrator: SchemaMigrator):
    import magic

    from src.model.models import Content

    with db.atomic():
        migrate(
            migrator.add_column("content", "mime", CharField(default="")),
            migrator.add_column("content", "size", BigIntegerField(default=0)),
        )
    query = Content.select()

    for c in query:
        c.mime = magic.from_file(c.path, mime=True)
        c.size = os.stat(c.path).st_size
        c.save()
Ejemplo n.º 12
0
def edit_jam(url):
    """Редактировать джем"""
    user = get_user_from_request()
    jam = Jam.get_or_none(Jam.url == url)

    if jam is None:
        return errors.not_found()

    if jam.creator != user:
        return errors.no_access()

    json = request.json

    title = json.get("title", jam.title)
    # url = json.get("url", jam.url)
    description = json.get("description", jam.description)
    short_description = json.get("short_description", jam.short_description)
    start_date = json.get("start_date", jam.start_date)
    end_date = json.get("end_date", jam.end_date)
    criterias = json.get("criterias", [])

    image = None
    if "image" in json:
        image = json["image"]

    edit_blog_for_jam(jam.blog, title, url, image)

    jam.title = title
    # jam.url = url
    jam.description = sanitize(description)
    jam.short_description = sanitize(short_description)
    jam.start_date = start_date
    jam.end_date = end_date

    if image:
        jam.logo = Content.get_or_none(Content.id == image)

    jam.updated_date = datetime.datetime.now()
    jam.save()

    JamCriteria.delete().where(JamCriteria.jam == jam).execute()
    for criteria in criterias:
        JamCriteria.create(jam=jam,
                           title=criteria["title"],
                           order=criteria["order"])

    return jsonify({"success": 1, "jam": jam.to_json()})
Ejemplo n.º 13
0
def create_blog_for_jam(user, title, url, image=None):
    blog = Blog.create(
        created_date=datetime.datetime.now(),
        updated_date=datetime.datetime.now(),
        creator=user,
    )
    BlogParticipiation.create(blog=blog, user=user, role=1)

    blog.title = title
    blog.description = f'Это блог для джема "{title}"'
    blog.url = url
    blog.blog_type = 1
    if image:
        blog.image = Content.get_or_none(Content.id == image)

    blog.updated_date = datetime.datetime.now()
    blog.save()

    return blog
Ejemplo n.º 14
0
def upload_image(user_id, year, month, path):
    if path:
        if not os.path.isfile(path):
            print("Can't find file at path " + path)
            return None
        name = md5(path)
        _, ext = ntpath.splitext(path)
        filename = os.path.join(
            "uploads/",
            str(user_id) + "/" + str(year) + "/" + str(month) + "/")
        os.makedirs(filename, exist_ok=True)
        # filename = secure_filename(filename)
        new_path = filename + name + ext

        copyfile(path, new_path)

        c_mime = magic.from_file(new_path, mime=True)
        c_size = os.stat(new_path).st_size

        return Content.create(user=user_id,
                              path=os.path.abspath(new_path),
                              mime=c_mime,
                              size=c_size)
    return None
Ejemplo n.º 15
0
def add_achievement():
    user = get_user_from_request()

    if not user.is_admin:
        return errors.no_access()

    json = request.get_json()

    if "title" not in json or "image" not in json:
        return errors.wrong_payload("title", "image")

    if len(json["title"]) == 0:
        return errors.wrong_payload("title")

    content = Content.get_or_none(Content.id == json["image"])
    if content:
        if not content.is_image:
            return errors.achievement_is_not_image()
        elif not content.is_small_image:
            return errors.achievement_too_large()

    achievement = Achievement.create(title=json["title"], image=content)

    return jsonify({"success": 1, "achievement": achievement.to_json()})