Exemplo n.º 1
0
def seed_transfers():
    transfer_one = Transfer(sender_id=1,
                            receiver_id=2,
                            coin_id=1,
                            coinamt=.5,
                            date=datetime.datetime.now())

    db.session.add(transfer_one)

    transfer_two = Transfer(sender_id=1,
                            receiver_id=3,
                            coin_id=1,
                            coinamt=.5,
                            date=datetime.datetime.now())

    db.session.add(transfer_two)

    transfer_three = Transfer(sender_id=4,
                              receiver_id=1,
                              coin_id=1,
                              coinamt=.5,
                              date=datetime.datetime.now())

    db.session.add(transfer_three)
    db.session.commit()
Exemplo n.º 2
0
def register():
    print('SESSION: ', session)
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = RegistrationForm()
    if form.validate_on_submit():
        address = get_from_bitcoind('getnewaddress', [])
        dumpPri = get_from_bitcoind('dumpprivkey', [address])
        impoPri = get_from_bitcoind('importprivkey', [dumpPri])

        user = User(first_name=form.first_name.data,
                    last_name=form.last_name.data,
                    username=form.username.data,
                    address=address)
        user.set_password(form.password.data)
        db.session.add(user)
        db.session.commit()
        transfer = Transfer(tx_type='Deposit',
                            amount=500000,
                            currency='USD',
                            confirmation_status=0,
                            user_id=user.id)
        balances = Balance(confirmed_balance_btc=0,
                           unconfirmed_balance_btc=0,
                           balance_usd=500000,
                           user_id=user.id)
        db.session.add_all([transfer, balances])
        db.session.commit()
        flash('You have successfully registered - please log in')
        return redirect(url_for('login'))
    return render_template('register.html', title='Register', form=form)
def transfer(hash, to_user):
    to_username = to_user
    file = File.query.filter_by(hash=hash).first()
    if file is None:
        abort(404, '文件不存在')

    to_user_entity = User.query.filter_by(username=to_username).first()
    if not to_user_entity:
        abort(400, '用户名有误')

    # 只能转让自己的的作品
    if file.owner_user != current_user:
        abort(403, '只能转让自己的作品')

    if file.owner_user == to_user_entity:
        abort(400, '不能转让给自己')

    if not ethereum_service.file_is_confirmed(file):
        abort(400, '作品尚未确认,不能转让')

    # 写入以太坊
    tx_hash = ethereum_service.transfer(current_user, to_user_entity, file)

    # 写入数据库
    transfer = Transfer(file_hash=file.hash,
                        from_username=current_user.username,
                        to_username=to_username,
                        txhash=tx_hash)
    file.owner = to_username

    db.session.add(transfer)
    db.session.add(file)

    return redirect(url_for('user.transfers'))
Exemplo n.º 4
0
 def test_transfer_creation(self):
     u = User(username="******", email="*****@*****.**")
     db.session.add(u)
     db.session.commit()
     t = Transfer(currency="GBP", amount=100, originator=u)
     transfers = Transfer.query.all()
     self.assertEqual(len(transfers), 1)
Exemplo n.º 5
0
def transfer():
    form = TransferForm()

    # Prefill form fields
    form.tdate.data = date.today()
    form.from_account_id.choices = active_accounts(True)
    form.to_account_id.choices = active_accounts(True)

    if form.validate_on_submit():
        tf = Transfer(from_account_id=form.from_account_id.data,
                      to_account_id=form.to_account_id.data,
                      tdate=form.tdate.data,
                      amount=round(float(form.amount.data), 2),
                      coef=float(form.coef.data),
                      user_id=current_user.id)
        f = Account.query.get(tf.from_account_id)
        t = Account.query.get(tf.to_account_id)

        f.balance = f.balance - tf.amount
        t.balance = t.balance + tf.amount * tf.coef

        db.session.add_all([tf, t, f])
        db.session.commit()
        flash('Transfer complete!', 'success')
        return redirect(url_for('main.index'))
    return render_template('transactions/transfer.html', form=form)
Exemplo n.º 6
0
def add_transfer(data):

    #print(data)

    pocket = Pocket.query.get(int(data['pocketid']))
    category = Category.query.get(int(data['categoryid']))
    category.last_active = datetime.utcnow()
    amount = category.type * abs(int(data['amount']))
    detail = str(data['detail'])

    pocket.balance += amount

    actual = Abalance()
    actual._pocket = pocket
    actual.balance = pocket.balance
    actual.timestamp = datetime.utcnow()

    transfer = Transfer()
    transfer._pocket = pocket
    transfer.amount = amount
    transfer.timestamp = datetime.utcnow()
    transfer._category = category
    transfer.detail = detail

    db.session.add(transfer)
    db.session.add(actual)
    db.session.commit()

    return True
Exemplo n.º 7
0
def transfer():
    body = request.get_json()
    sender_id = body.get('sender_id')
    coin_id = body.get('coin_id')
    coinamt = body.get('coinamt')
    coinamt = float(coinamt)
    receiver_email = body.get('receiver_identification')
    receiver = User.query.filter_by(email=receiver_email).first()
    print('#############################', receiver)
    if receiver == None:
        return {'errors': ['No such user']}
    # return {'errors': 'No such user'}
    receiver = receiver.to_dict()
    receiver_id = receiver['id']
    vault = Vault.query.filter_by(user_id=sender_id).first()
    vault = vault.to_dict()
    coin = VaultCoin.query.filter_by(vault_id=vault['id']).filter_by(coin_id=coin_id).first()
    coinAmount = coin.to_dict()
    if coinamt <= coinAmount['amount']:
        new_vault = Vault.query.filter_by(user_id=receiver_id).first()
        new_vault = new_vault.to_dict()
        newcoin = VaultCoin.query.filter_by(vault_id=new_vault['id']).filter_by(coin_id=coin_id).first()
        coin.amount = coin.amount - coinamt
        newcoin.amount = newcoin.amount + coinamt
        new_transfer = Transfer(
            sender_id=sender_id,
            receiver_id=receiver_id,
            coin_id= coin_id,
            coinamt= coinamt,
            date= datetime.datetime.now()
        )
        db.session.add(new_transfer)
        db.session.commit()
        new_transfer = new_transfer.to_dict()
        user = User.query.get(new_transfer['sender_id'])
        user2 = User.query.get(new_transfer['receiver_id'])
        user = user.to_dict()
        user2= user2.to_dict()
        new_transfer['sender'] = user
        new_transfer['receiver'] = user2
        return new_transfer
    return {'errors':['Insufficient tokens']}
Exemplo n.º 8
0
def transferProcess(request):
    data = json.loads(request.body)

    ref_id = data['ref_id']
    date = data['date']
    new_warehouse = data['new_warehouse']
    lines = data['lines']

    myUsername = request.session.get('username')
    user = User.objects.get(username=myUsername)

    if user.branch.transfer.filter(ref_id=ref_id).exists():
        tr = user.branch.transfer.latest('pk')

        listed_ref_id = tr.ref_id.split('-')
        listed_date = str(now.today()).split('-')

        current_code = int(listed_ref_id[3])

        if listed_ref_id[1] == listed_date[0] and listed_ref_id[2] == listed_date[1]:
            current_code += 1
            ref_id = 'T-{}-{}-{}'.format(listed_date[0], listed_date[1], str(current_code).zfill(4))

    tr = Transfer()

    tr.ref_id = ref_id
    tr.date = date
    tr.warehouse = Warehouse.objects.get(pk=new_warehouse)
    tr.approved = False
    tr.created_by = User.objects.get(username=myUsername)
    tr.save()

    user.branch.transfer.add(tr)

    for line in lines:
        ti = Transfer_Item()
  
        ti.product = Product.objects.get(pk=int(line['code']))
        ti.transfer = tr
        ti.remaining = int(line['remaining'])
        ti.transfer_quantity = int(line['quantity'])

        ti.save()
        sweetify.sweetalert(request, icon='success', title='Success!', persistent='Dismiss')

    return JsonResponse(0, safe=0)
Exemplo n.º 9
0
    def setUp(self):
        app.config['TESTING'] = True
        app.config['WTF_CSRF_ENABLED'] = False
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
        db.create_all()

        self.client = app.test_client()

        u = User(username="******", email="*****@*****.**")
        u.set_password("test")
        db.session.add(u)
        for _ in range(20):
            t = Transfer(currency="USD", amount=100, originator=u)
            db.session.add(t)
        db.session.commit()
Exemplo n.º 10
0
def register():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(first_name=form.first_name.data,
                    last_name=form.last_name.data, username=form.username.data)
        user.set_password(form.password.data)
        db.session.add(user)
        db.session.commit()
        transfer = Transfer(tx_type='Deposit', amount=500000, currency='USD',
                            user_id=user.id)
        balances = Balance(balance_btc=0, balance_usd=500000, user_id=user.id)
        db.session.add_all([transfer, balances])
        db.session.commit()
        flash('You have successfully registered - please log in')
        return redirect(url_for('login'))
    return render_template('register.html', title='Register', form=form)
Exemplo n.º 11
0
def transfer_funds(from_wallet, to_wallet, amount, comment):
    if from_wallet is not None:
        if from_wallet.balance < amount:
            raise BillingException('Not enough funds')

    if to_wallet is None:
        raise BillingException('Receiver cannot be null')

    if comment is None or comment == '':
        raise BillingException('Missing comment')

    try:
        amount = int(amount)
    except:
        raise BillingException('Incorrect transfer amount')

    if amount < 0:
        raise BillingException('Cannot transfer negative funds')

    try:
        with transaction.atomic():
            transfer = Transfer()
            transfer.amount = amount
            transfer.comment = comment
            transfer.sender = from_wallet
            transfer.receiver = to_wallet
            transfer.save()

            if from_wallet is not None:
                from_wallet.balance -= amount
                from_wallet.save()

            to_wallet.balance += amount
            to_wallet.save()
    except IntegrityError as e:
        raise BillingException('Transaction integrity error: {}'.format(e))

    return True
Exemplo n.º 12
0
def get_deposit():
    address = 'mqqHSBCp5873mK9WY3cR32KDx2pnEJBT2p'
    #address_balance_satoshis = blockcypher.get_total_balance(address, coin_symbol="btc-testnet", api_key="acb0b8a2fe3d479c8b05b415ded8021e")
    #address_balance = blockcypher.from_satoshis(address_balance_satoshis, 'btc')
    key = PrivateKeyTestnet('cPvDDZ8XREaxWnZNaZ2V8FeUrZYvwHk8kAMHVaFbFte1QZUuuTur')
    address_balance = float(key.get_balance('btc'))
    deposit = 'None'
    print("DEPOSIT ==> address_balance:", address_balance)
    print("        ==> session['address_balance']:", session['address_balance'])
    if address_balance > session['address_balance']:
        print(("\nNew address balance: {} Old address balance: {}\n").format(address_balance, session['address_balance']))
        amount = address_balance - session['address_balance']
        #address_txs = get_address_txs(address)
        address_txs = key.get_transactions()
        user = current_user
        balances = Balance.query.filter_by(user_id=user.id).first()
        latest_transfers = Transfer.query.filter_by(user_id=user.id).all()
        db_txs = []
        for transfer in latest_transfers:
            db_txs.append(transfer.tx_id)
        new_balance_btc = balances.balance_btc + amount
        #tx = address_txs[0]
        #txid = tx[1]
        txid = address_txs[0]
        # if tx not in session['address_txs'] and txid not in db_txs:
        if txid not in db_txs:
            if all(isinstance(i, float) for i in [amount, new_balance_btc, balances.balance_usd]):
                # print(("\ntxid: {}\nPrevious txs: {}\n").format(txid, session['address_txs']))
                db.session.delete(balances)
                db.session.commit()
                transfer = Transfer(tx_type='deposit', amount=amount, currency='BTC', tx_id=txid, user_id=user.id)
                new_balances = Balance(balance_btc=new_balance_btc, balance_usd=balances.balance_usd, user_id=user.id)
                db.session.add_all([transfer, new_balances])
                db.session.commit()
                print(("\nTransfer: {}\nNew balances: {}\n").format(transfer, new_balances))
                session['address_balance'] = address_balance
                # session['address_txs'] = address_txs
                deposit = txid
    return jsonify(result=deposit)
Exemplo n.º 13
0
def check_withdrawal_confirmed():
    withdrawal = 'None'
    user = current_user
    status = Transfer.query.filter_by(user_id=user.id).all()
    if status:
        confirmation_status = status[-1].confirmation_status
        tx_id = status[-1].tx_id
        tx_type = status[-1].tx_type

    transaction_info = get_from_bitcoind('gettransaction', [tx_id])
    confirmations = transaction_info['confirmations']

    balances = Balance.query.filter_by(user_id=user.id).first()
    balanceUsd = balances.balance_usd
    confirmedBalanceBTC = balances.confirmed_balance_btc
    unConfirmedBalanceBTC = balances.unconfirmed_balance_btc

    if confirmations >= 1 and confirmation_status == 0 and tx_type == 'withdrawal':
        confirmation_status = 1
        db.session.delete(balances)
        db.session.commit()
        new_confirmed_balance_btc = unConfirmedBalanceBTC
        unConfirmedBalanceBTC = 0.00
        new_balances = Balance(confirmed_balance_btc=new_confirmed_balance_btc,
                               unconfirmed_balance_btc=unConfirmedBalanceBTC,
                               balance_usd=balanceUsd,
                               user_id=user.id)
        transfer = Transfer(tx_type='withdrawal',
                            amount=new_confirmed_balance_btc,
                            currency='BTC',
                            tx_id=tx_id,
                            confirmation_status=confirmation_status,
                            user_id=user.id)
        db.session.add_all([transfer, new_balances])
        db.session.commit()
        withdrawal = tx_id

    return jsonify(result=withdrawal)
Exemplo n.º 14
0
def get_withdrawal():
    address = request.args.get('address', 0, type=str)
    amount = request.args.get('amount', 0, type=float)
    withdrawal = 'None'
    try:
        check = get_version(address)
        if check == 'test':
            if type(amount) is not float:
                withdrawal = 'error-amount'
            else:
                user = current_user
                balances = Balance.query.filter_by(user_id=user.id).first()
                latest_transfers = Transfer.query.filter_by(user_id=user.id).all()
                db_txs = []
                for transfer in latest_transfers:
                    db_txs.append(transfer.tx_id)
                new_balance_btc = balances.balance_btc - amount
                key = PrivateKeyTestnet('cPvDDZ8XREaxWnZNaZ2V8FeUrZYvwHk8kAMHVaFbFte1QZUuuTur')
                address_balance = key.get_balance()
                txid = key.send([(address, amount, 'btc')])
                if txid not in db_txs:
                    db.session.delete(balances)
                    db.session.commit()
                    transfer = Transfer(tx_type='withdrawal', amount=amount, currency='BTC', tx_id=txid, user_id=user.id)
                    new_balances = Balance(balance_btc=new_balance_btc, balance_usd=balances.balance_usd, user_id=user.id)
                    db.session.add_all([transfer, new_balances])
                    db.session.commit()
                    print(("\nTransfer: {}\nNew balances: {}\n").format(transfer, new_balances))
                    withdrawal = txid
        else:
            withdrawal = 'error-main'
    except ValueError:
        withdrawal = 'error-address'
    if withdrawal in ['error-main', 'error-address']:
        if type(amount) is not float:
            withdrawal = 'error-both'
    return jsonify(result=withdrawal)
Exemplo n.º 15
0
def get_deposit():
    user = current_user
    users = User.query.filter(User.username == user.username).first()
    balances = Balance.query.filter_by(user_id=user.id).first()
    confirmedBalanceBTC = balances.confirmed_balance_btc
    unConfirmedBalanceBTC = balances.unconfirmed_balance_btc
    deposit = 'None'
    balanceUsd = balances.balance_usd
    addresses = [users.address]
    unspentlist = get_from_bitcoind('listunspent',
                                    [0, 100, addresses])  #need to clear
    latest_transfers = Transfer.query.filter_by(user_id=user.id).all()
    db_txs = []
    for transfer in latest_transfers:
        db_txs.append(transfer.tx_id)
    for unspent in unspentlist:
        txid = unspent['txid']
        amount = unspent['amount']
        confirmations = unspent['confirmations']
        status = Transfer.query.filter_by(tx_id=txid).all()
        print("ststus............", status)
        if status:
            confirmation_status = status[-1].confirmation_status

        if txid not in db_txs:
            confirmation_status = 0
            db.session.delete(balances)
            db.session.commit()
            if unConfirmedBalanceBTC > 0:
                new_unconfirmed_balance_btc = '%.07f' % (
                    unConfirmedBalanceBTC + amount)
            else:
                new_unconfirmed_balance_btc = '%.07f' % (confirmedBalanceBTC +
                                                         amount)
            new_balances = Balance(
                confirmed_balance_btc=confirmedBalanceBTC,
                unconfirmed_balance_btc=new_unconfirmed_balance_btc,
                balance_usd=balanceUsd,
                user_id=user.id)
            transfer = Transfer(tx_type='deposit',
                                amount=amount,
                                currency='BTC',
                                tx_id=txid,
                                confirmation_status=confirmation_status,
                                user_id=user.id)
            print("new_balance_btc...........", new_balances)
            db.session.add_all([transfer, new_balances])
            db.session.commit()
            deposit = txid

        if confirmations >= 1 and confirmation_status == 0:
            print("confirmation greater than 6....")
            confirmation_status = 1
            db.session.delete(balances)
            db.session.commit()
            print("unConfirmedBalanceBTC..........", unConfirmedBalanceBTC)
            new_confirmed_balance_btc = unConfirmedBalanceBTC
            unConfirmedBalanceBTC = 0.00
            new_balances = Balance(
                confirmed_balance_btc=new_confirmed_balance_btc,
                unconfirmed_balance_btc=unConfirmedBalanceBTC,
                balance_usd=balanceUsd,
                user_id=user.id)
            transfer = Transfer(tx_type='deposit',
                                amount=amount,
                                currency='BTC',
                                tx_id=txid,
                                confirmation_status=confirmation_status,
                                user_id=user.id)
            db.session.add_all([transfer, new_balances])
            db.session.commit()
            deposit = txid

    return jsonify(result=deposit)
Exemplo n.º 16
0
def get_withdrawal():
    address = request.args.get('address', 0, type=str)
    amount = request.args.get('amount', 0, type=float)
    withdrawal = 'None'
    try:
        if type(amount) is not float:
            withdrawal = 'error-amount'
        else:
            print("In else.........................")
            user = current_user
            balances = Balance.query.filter_by(user_id=user.id).first()
            print(balances)
            balanceUsd = balances.balance_usd
            confirmedBalanceBTC = balances.confirmed_balance_btc
            unConfirmedBalanceBTC = balances.unconfirmed_balance_btc
            addresses = [address]
            latest_transfers = Transfer.query.filter_by(user_id=user.id).all()
            db_txs = []
            for transfer in latest_transfers:
                db_txs.append(transfer.tx_id)
                #tx_status[transfer.tx_id] = transfer.confirmation_status

            sendAmountTxID = get_from_bitcoind('sendtoaddress',
                                               [address, amount])
            print("sendAmount...................", sendAmountTxID)
            transaction_info = get_from_bitcoind('gettransaction',
                                                 [sendAmountTxID])
            fees_BTC = float('%.07f' % transaction_info['fee'])
            print("fees.......................", fees_BTC)
            status = Transfer.query.filter_by(tx_id=sendAmountTxID).first()
            if status != None:
                confirmation_status = status.confirmation_status

            confirmations = transaction_info['confirmations']
            if sendAmountTxID not in db_txs:
                confirmation_status = 0
                db.session.delete(balances)
                db.session.commit()
                new_unconfirmed_balance_btc = '%.07f' % (
                    confirmedBalanceBTC - amount + fees_BTC
                )  #since fees coming -
                if unConfirmedBalanceBTC > 0:
                    new_unconfirmed_balance_btc = '%.07f' % (
                        unConfirmedBalanceBTC + new_unconfirmed_balance_btc)
                new_balances = Balance(
                    confirmed_balance_btc=confirmedBalanceBTC,
                    unconfirmed_balance_btc=new_unconfirmed_balance_btc,
                    balance_usd=balanceUsd,
                    user_id=user.id)
                transfer = Transfer(tx_type='withdrawal',
                                    amount=amount,
                                    currency='BTC',
                                    tx_id=sendAmountTxID,
                                    confirmation_status=confirmation_status,
                                    user_id=user.id)
                db.session.add_all([transfer, new_balances])
                db.session.commit()
                withdrawal = sendAmountTxID

            # if confirmations >= 1 and confirmation_status == 0:
            #     confirmation_status = 1
            #     db.session.delete(balances)
            #     db.session.commit()
            #     new_confirmed_balance_btc = unConfirmedBalanceBTC
            #     unConfirmedBalanceBTC = 0.00
            #     new_balances = Balance(confirmed_balance_btc=new_confirmed_balance_btc, unconfirmed_balance_btc=unConfirmedBalanceBTC , balance_usd=balanceUsd, user_id=user.id)
            #     transfer = Transfer(tx_type='withdrawal', amount=amount, currency='BTC', tx_id=sendAmountTxID,confirmation_status=confirmation_status, user_id=user.id)
            #     db.session.add_all([transfer, new_balances])
            #     db.session.commit()
            #     withdrawal = sendAmountTxID

    except ValueError:
        withdrawal = 'error-address'
    if withdrawal in ['error-amount', 'error-address']:
        if type(amount) is not float:
            withdrawal = 'error-both'
    return jsonify(result=withdrawal)
Exemplo n.º 17
0
def treatment():
    token = str(uuid.uuid4())

    ### 1 - Get the AJAX request and create the variable storing the data and the one storing the binary
    dictionary_request = request.get_json()
    model = dictionary_request["model"] ## Save the model to apply
    distribution = dictionary_request["distribution"]
    datapoints = dictionary_request["datapoints"]
    grid = dictionary_request["grid"]
    orientation = dictionary_request["orientation"]
    ratio = dictionary_request["ratio"]

    ### 2 - Prepare the input image

    app.logger.info("treatment token={} : IMAGE-INPUT START".format(token))
    t_image_input_start = time.time()

    # A2B : Transform the image into binaries
    binary_data = a2b_base64(dictionary_request['image'].split('base64,')[1])

    # Transform binary data to PIL format (Step could be avoided if we find something like "Image.froma")
    dataBytesIO = BytesIO(binary_data)
    png = Image.open(dataBytesIO)

    # Work on background and remove the Alpha Channel
    background = Image.open('./app/static/style-images/'+re.sub('.pth','.jpg',model)) # Use the style image as background
    #background = Image.open('./app/static/style-images/'+"white-noise.jpg") # Use white noise as background
    background = background.resize((450,300),Image.ANTIALIAS) # Resize the background
    #background = background.filter(ImageFilter.FIND_EDGES) # Detect background edges
    background = background.filter(ImageFilter.GaussianBlur(radius=100)) # Blur the background
    # background = Image.new("RGB", png.size, (255, 255, 255)) # Add a white background to the image

    background.paste(png, mask=png.split()[3]) # 3 is the alpha channel

    t_image_input = time.time() - t_image_input_start
    app.logger.info("treatment token={} : IMAGE-INPUT END ({}s)".format(token,t_image_input))

    ### 3 - Run the style transfer using the GAN chosen in model

    app.logger.info("treatment token={} : GAN START".format(token))
    t_gan_start = time.time()

    image_after_gan = stylize({"content_image":background,"content_scale":None,"model":model,"cuda":0,"export_onnx":None})

    t_gan = time.time() - t_gan_start
    app.logger.info("treatment token={} : GAN END ({}s)".format(token,t_gan))

    ### 4 - Prepare the output image, transform image from PIL to bytes and then to image for the interface

    app.logger.info("treatment token={} : IMAGE-OUTPUT START".format(token))
    t_image_output_start = time.time()

    imgByteArr = BytesIO()
    image_after_gan.save("./app/static/output_images/{}.jpg".format(token), format='JPEG')
    image_after_gan.save(imgByteArr, format='JPEG')
    output_image = imgByteArr.getvalue()
    output_image = b2a_base64(output_image)

    t_image_output = t_image_output_start - time.time()
    app.logger.info("treatment token={} : IMAGE-OUTPUT END ({}s)".format(token,t_image_output))

    t = Transfer(token = token, model = model, distribution = distribution, datapoints = datapoints, grid = grid, orientation = orientation, ratio = ratio)
    db.session.add(t)
    db.session.commit()

    # Return the content of the output to the client with AJAX
    return(token)