예제 #1
0
def create_folder(user):
    try:
        name = request.json["name"]
        path = request.json["path"]
        if path.startswith("/"):
            path = path[1:]
        if path.endswith("/"):
            path = path[:-1]
        fullPath = os.path.join(app.root_path, app.config["UPLOAD_FOLDER"],
                                path, name)
        os.makedirs(fullPath)
        appPath = os.path.join(path, name)
        folder = Folder(name, appPath, user)
        owner = Account.query.filter(Account.email == user).first()
        owner.folders.append(folder)
        parent = (Folder.query.filter(Folder.userId == owner.id).filter(
            Folder.path == path).first())
        if parent is not None:
            folder.parent = parent
        db.session.add(folder)
        db.session.add(owner)
        db.session.commit()
        db.engine.dispose()
        app.logger.info("Created folder %s.", folder.path)
        return jsonify({"success": True})
    except FileExistsError:
        app.logger.info("Trying to create existing directory")
        error = "Folder already exists"
        return jsonify({"success": False, "error": error}), 409
    except Exception as e:
        app.logger.info("Error in making a directory: %s", e)
        return jsonify({"success": False, "error": "Internal Server Error"})
예제 #2
0
def create_folder():
    form = NewFolderForm()
    form["csrf_token"].data = request.cookies["csrf_token"]

    if form.validate_on_submit():
        folder = Folder(
            name=form.data['name'],
            user_id=int(form.data['user_id']),
            category_id=int(form.data['category_id']),
        )
        db.session.add(folder)
        db.session.commit()
        return folder.to_dict()
    return {'errors': form_errors(form.errors)}
예제 #3
0
def create_new_user(first_name, last_name, email, password):
    """ Creates a new user and sets up any links database entries. """
    
    new_user = User(first_name, last_name, email, password)
    db.session.add(new_user)
    db.session.commit()
 
    # link a root storage folder to the user
    root_folder = Folder()
    db.session.add(root_folder)
    db.session.commit()
    new_user.storage_root_id = root_folder.id
    new_user.storage_root = root_folder
    db.session.commit()

    # link usage tracking to the user
    usage = Usage()
    usage.user_id = new_user.id
    new_user.usage = usage
    db.session.add(usage)
    db.session.commit()

    # link a billing address to the user
    billing_address = BillingAddress()
    billing_address.user_id = new_user.id
    new_user.billing_address = billing_address
    db.session.add(billing_address)
    db.session.commit()

    # link settings to the User
    settings = Settings()
    settings.user_id = new_user.id
    new_user.settings = settings
    db.session.add(settings)
    db.session.commit()
예제 #4
0
 def create_folder(user_id, name, parent_id=None):
     user = User.objects.filter(id=user_id).first()
     parent = None
     if not user:
         return None
     if parent_id:
         parent = Folder.objects.filter(id=parent_id).first()
         if not parent:
             return None
     existing_folder = Folder.objects.filter(
         name=name, owner=user, parent=parent).first()
     if existing_folder:
         return None
     new_folder = Folder(name=name, owner=user, parent=parent)
     new_folder.save()
     return FolderRepo.to_json(new_folder)
예제 #5
0
def create_user():
    """"
    This endpoint is for creating new user
    """
    form = request.json["email"]

    email = form["username"]

    existing = Account.query.filter_by(email=email).first()
    if existing:
        response = jsonify({"success": False, "error": "User already exists"})
        return jsonify({"success": False, "error": "User already exists"}), 409

    password = form["password"]
    account = Account(email, password)
    home = Folder("home", email, account.id)
    account.folders.append(home)
    db.session.add(account)
    db.session.commit()
    db.engine.dispose()

    registered = Account.query.filter_by(email=email).first()
    if not registered:
        response = jsonify({"success": False, "error": "Failed to save user"})
        app.logger.error("Failed to create account %s.", account.email)
        return response, 500

    login_user(registered)
    app.logger.info("Account: %s created", account.email)

    return jsonify({"success": True, "user_id": registered.id})
예제 #6
0
def folder_add(request):
    context = {
        "profile": Profile.objects.get(user=request.user),
        "bot_api_key": BotKey.objects.get(user=request.user).key
    }
    if request.method == "POST":
        folder_form = FolderAddForm(request.POST)
        if folder_form.is_valid():
            try:
                folder = Folder.objects.get(name=folder_form.data['name'],
                                            user=request.user)
                messages.error(
                    request,
                    f"Вы уже создали подборку \"{folder_form.data['name']}\". Выберите другое название."
                )
                context["form"] = FolderAddForm(request.POST)
                return render(request, "folder/add.html", context)
            except Folder.DoesNotExist:
                ok = check_blacklist(folder_form.data['name'])
                if ok is not None:
                    messages.error(
                        request,
                        f"Название подборки не должно содержать \"{ok}\"")
                    return render(request, "folder/add.html", context)
                folder = Folder(name=folder_form.data['name'],
                                user=request.user)
                private = "Публичная"
                if not request.POST.get("public", None):
                    folder.public = False
                    private = "Приватная"
                folder.save()
                messages.success(
                    request,
                    f"{private} подборка \"{folder_form.data['name']}\" создана"
                )
                return redirect(reverse('link_add'))
        else:
            messages.error(request, f"Неправильные данные")
            context["form"] = FolderAddForm(request.POST)
    else:
        context["form"] = FolderAddForm()
    return render(request, "folder/add.html", context)
예제 #7
0
def currentPath(path):
    form = CreateFolder()
    user = User.query.get(current_user.id)
    indexToSuppress = []
    currentFolder = Folder.query.get(path)
    currentFiles = []
    for i in range(len(user.files)):
        f = user.files[i]
        currentFiles.append(f)
        if f.parent.name != currentFolder.name:
            indexToSuppress.append(i)
    for i in range(len(indexToSuppress)):
        currentFiles.pop(indexToSuppress[i] - i)
    indexToSuppress = []
    currentFolders = []
    for i in range(len(user.folders)):
        f = user.folders[i]
        currentFolders.append(f)
        if f.parent.name != currentFolder.name:
            indexToSuppress.append(i)
    for i in range(len(indexToSuppress)):
        currentFolders.pop(indexToSuppress[i] - i)
    if form.validate_on_submit():
        dirName = returnPathOfFolder(
            currentFolder.id) + "/" + form.folderName.data
        if not os.path.exists(dirName):
            os.mkdir(dirName)
            flash("Directory " + form.folderName.data + " Created ")
        else:
            flash("Directory " + form.folderName.data + " already exists")
        newFolder = Folder(name=form.folderName.data, parent=currentFolder)
        newFolder.AccessFolder.append(user)
        db.session.add(newFolder)
        db.session.commit()
        return redirect(
            url_for("currentPath", title="Home", path=currentFolder.id))
    return render_template('home/home.html',
                           title="Home",
                           user=user,
                           files=currentFiles,
                           folders=currentFolders,
                           form=form,
                           parent=currentFolder.parent,
                           path=path)
예제 #8
0
def seed_folders():

    db.session.add(Folder(name="Linux 101",
                          user_id=1,
                          category_id=2))
    db.session.add(Folder(name="Org Mode > Markdown",
                          user_id=1,
                          category_id=2))
    db.session.add(Folder(name="Project Ideas",
                          user_id=1,
                          category_id=8))
    db.session.add(Folder(name="JavaScript",
                          user_id=1,
                          category_id=6))
    db.session.add(Folder(name="Python",
                          user_id=1,
                          category_id=6))
    db.session.add(Folder(name="Daily Thoughts",
                          user_id=1,
                          category_id=1))

    db.session.commit()