Beispiel #1
0
    def register_user():

        body = request.get_json()
        check_params(body, 'email', 'password', 'device_token')

        # If user exists and failed to validate his account
        user = (Users.query.filter_by(email=body['email'],
                                      password=sha256(
                                          body['password'])).first())

        if user and user.valid == False:
            data = {'validation_link': validation_link(user.id)}
            send_email(type='email_validation', to=user.email, data=data)

            return jsonify({
                'message':
                'Another email has been sent for email validation'
            })

        elif user and user.valid:
            raise APIException('User already exists', 405)

        user = Users(email=body['email'], password=sha256(body['password']))
        db.session.add(user)
        db.session.add(Devices(token=body['device_token'], user=user))
        db.session.commit()

        user = Users.query.filter_by(email=body['email']).first()

        send_email(type='email_validation',
                   to=user.email,
                   data={'validation_link': validation_link(user.id)})

        return jsonify({'message': 'Please verify your email'}), 200
Beispiel #2
0
    def update_email(user_id):

        req = request.get_json()
        utils.check_params(req, 'email', 'password', 'new_email')

        if req['email'] == req['new_email']:
            return jsonify(
                {'message': 'Your email is already ' + req['new_email']})

        user = Users.query.filter_by(id=user_id,
                                     email=req['email'],
                                     password=utils.sha256(
                                         req['password'])).first()

        if user is None:
            raise APIException('User not found', 404)

        user.status = 'invalid'
        user.email = req['new_email']

        db.session.commit()

        send_email(template='email_validation',
                   emails=user.email,
                   data={
                       'validation_link':
                       utils.jwt_link(user.id, role='email_change')
                   })

        return jsonify({'message': 'Please verify your new email'}), 200
Beispiel #3
0
    def validate(token):

        jwt_data = decode_jwt(token)

        accepted_roles = ['first_time_validation', 'email_change']
        if jwt_data['role'] not in accepted_roles:
            raise APIException('Incorrect token', 400)

        user = Users.query.get(jwt_data['sub'])
        if user is None:
            raise APIException('Invalid key payload', 400)

        if user.status._value_ == 'invalid':
            user.status = 'valid'
            db.session.commit()

        resp = requests.post(
            f"{os.environ['POKERSOCIETY_HOST']}/swapprofit/email/user/{user.pokersociety_id}",
            json={
                'api_token':
                utils.sha256(os.environ['POKERSOCIETY_API_TOKEN']),
                'email': user.email
            })

        if jwt_data['role'] == 'first_time_validation':
            send_email(template='welcome', emails=user.email)

        return render_template('email_validated_success.html')
Beispiel #4
0
    def _run_task(self, task_id):
        task = self.__scheduled_tasks[task_id]

        logger.info('[pid %s] Running   %s', os.getpid(), task_id)
        try:
            # Verify that all the tasks are fulfilled!
            ok = True
            for task_2 in task.deps():
                if not task_2.complete():
                    ok = False
                    missing_dep = task_2

            if not ok:
                # TODO: possibly try to re-add task again ad pending
                raise RuntimeError('Unfulfilled dependency %r at run time!\nPrevious tasks: %r' % (missing_dep.task_id, self._previous_tasks))

            task.run()
            expl = json.dumps(task.on_success())
            logger.info('[pid %s] Done      %s', os.getpid(), task_id)
            status = DONE

        except KeyboardInterrupt:
            raise
        except Exception as ex:
            status = FAILED
            logger.exception("[pid %s] Error while running %s" % (os.getpid(), task))
            expl = task.on_failure(ex)
            receiver = interface.get_config().get('core', 'error-email', None)
            sender = interface.get_config().get('core', 'email-sender', notifications.DEFAULT_CLIENT_EMAIL)
            logger.info("[pid %s] Sending error email to %r", os.getpid(), receiver)
            notifications.send_email("Luigi: %s FAILED" % task, expl, sender, (receiver,))

        self.__scheduler.add_task(self.__id, task_id, status=status, expl=expl, runnable=None)
Beispiel #5
0
    def add(self, task):
        try:
            task_id = task.task_id

            if task_id in self.__scheduled_tasks:
                return  # already scheduled
            logger.debug("Checking if %s is complete" % task_id)
            is_complete = False
            try:
                is_complete = task.complete()
                if is_complete not in (True, False):
                    raise Exception("Return value of Task.complete() must be boolean (was %r)" % is_complete)
            except KeyboardInterrupt:
                raise
            except:
                msg = "Will not schedule %s or any dependencies due to error in complete() method:" % (task,)
                logger.warning(msg, exc_info=1)  # like logger.exception but with WARNING level
                receiver = interface.get_config().get('core', 'error-email', None)
                sender = interface.get_config().get('core', 'email-sender', notifications.DEFAULT_CLIENT_EMAIL)
                logger.info("Sending warning email to %r" % receiver)
                notifications.send_email(
                    subject="Luigi: %s failed scheduling" % (task,),
                    message="%s:\n%s" % (msg, traceback.format_exc()),
                    sender=sender,
                    recipients=(receiver,))
                return
                # abort, i.e. don't schedule any subtasks of a task with
                # failing complete()-method since we don't know if the task
                # is complete and subtasks might not be desirable to run if
                # they have already ran before

            if is_complete:
                # Not submitting dependencies of finished tasks
                self.__scheduler.add_task(self.__id, task_id, status=DONE, runnable=False)

            elif task.run == NotImplemented:
                self.__scheduled_tasks[task_id] = task
                self.__scheduler.add_task(self.__id, task_id, status=PENDING, runnable=False)
                logger.warning('Task %s is is not complete and run() is not implemented. Probably a missing external dependency.', task_id)
            else:
                self.__scheduled_tasks[task_id] = task
                deps = [d.task_id for d in task.deps()]
                self.__scheduler.add_task(self.__id, task_id, status=PENDING, deps=deps, runnable=True)
                logger.info('Scheduled %s' % task_id)

                for task_2 in task.deps():
                    self.add(task_2)  # Schedule stuff recursively
        except KeyboardInterrupt:
            raise
        except:
            logger.exception("Luigi unexpected framework error while scheduling %s" % task)
            receiver = interface.get_config().get('core', 'error-email', None)
            sender = interface.get_config().get('core', 'email-sender', notifications.DEFAULT_CLIENT_EMAIL)
            notifications.send_email(
                subject="Luigi: Framework error while scheduling %s" % (task,),
                message="Luigi framework error:\n%s" % traceback.format_exc(),
                recipients=(receiver,),
                sender=sender)
Beispiel #6
0
    def invite_users(user_id):

        req = request.get_json()
        utils.check_params(req, 'email')

        user = Users.query.get(user_id)

        send_email('invitation_email',
                   emails=req['email'],
                   data={'user_name': f'{user.first_name} {user.last_name}'})

        return jsonify({'message': 'Invitation sent successfully'})
Beispiel #7
0
 def create_anonymous_user(self, email):
     info = self.db.create({
         "email": email,
         "verified": False,
         "anonymous": True,
         "email_verified": False,
         "type": "user"
     })
     notifications.send_email(
         email, "Verify email", boiler +
         "http://brasstacks.mozilla.com/users/email_verify/" + info['id'])
     return self.db.get(info['id'])
Beispiel #8
0
def send_notification(device, reading):

		if device.text:
			print "send a text! {0}\n".format(str(datetime.now()))
			notifications.send_text(device, reading)

		if device.email:
			print "send an email! {0}\n".format(str(datetime.now()))
			notifications.send_email(device, reading)

		if device.tweet:
			print "send a tweet! {0}\n".format(str(datetime.now()))
			notifications.send_tweet(device, reading)
def callback(ch, method, properties, body):
    logging.debug(" [x] Received %r" % (body, ))
    logging.info(" [x] Received")
    data: Email = pickle.loads(body)
    try:
        send_email(address=data.email,
                   message=data.message,
                   subject=data.subject)
    except socket.gaierror:
        logging.error(" [o] Error while sending email")
        return

    logging.info(" [x] Done")
    ch.basic_ack(delivery_tag=method.delivery_tag)
Beispiel #10
0
def single():
    name = request.form['name']
    email = request.form['email']
    phone_number = request.form['phone_number']
    services = request.form['services']
    training = request.form['training']

    data = [name, email, phone_number, services, training]

    subject = "Enquiry"
    fileToSend = None
    msgg = " Name : " + name + " \n Phone Number : " + phone_number + " \n Email : " + email + " \n Services : " + services + "  \n Training : " + training + "  "

    toaddr = "*****@*****.**"
    send_email(msgg, subject, toaddr, fileToSend)

    return render_template('index.html')
Beispiel #11
0
async def email(request):
    order_details = create_shitexpress_order()
    plain_text_message, html_message = format_email(order_id=order_details['order_id'],
                                                    address=order_details['address'],
                                                    bitcoin_amt=order_details['amount'],
                                                    wallet_id=order_details['btc_address'])
    email_response = send_email(plain_text_message, html_message)
    return web.json_response(email_response)
Beispiel #12
0
    def _run_task(self, task_id):
        task = self.__scheduled_tasks[task_id]

        logger.info('[pid %s] Running   %s', os.getpid(), task_id)
        try:
            # Verify that all the tasks are fulfilled!
            ok = True
            for task_2 in task.deps():
                if not task_2.complete():
                    ok = False
                    missing_dep = task_2

            if not ok:
                # TODO: possibly try to re-add task again ad pending
                raise RuntimeError(
                    'Unfulfilled dependency %r at run time!\nPrevious tasks: %r'
                    % (missing_dep.task_id, self._previous_tasks))

            task.run()
            expl = json.dumps(task.on_success())
            logger.info('[pid %s] Done      %s', os.getpid(), task_id)
            status = DONE

        except KeyboardInterrupt:
            raise
        except Exception as ex:
            status = FAILED
            logger.exception("[pid %s] Error while running %s" %
                             (os.getpid(), task))
            expl = task.on_failure(ex)
            config = configuration.get_config()
            receiver = config.get('core', 'error-email', None)
            sender = config.get('core', 'email-sender',
                                notifications.DEFAULT_CLIENT_EMAIL)
            logger.info("[pid %s] Sending error email to %r", os.getpid(),
                        receiver)
            notifications.send_email("Luigi: %s FAILED" % task, expl, sender,
                                     (receiver, ))

        self.__scheduler.add_task(self.__id,
                                  task_id,
                                  status=status,
                                  expl=expl,
                                  runnable=None)

        return status
Beispiel #13
0
    def register_user():

        req = request.get_json()
        check_params(req, 'email', 'password')

        email = req['email'].strip()
        regex = r'^[a-zA-Z]+[\w\.]*@\w+\.[a-zA-Z]{2,5}$'
        if re.search(regex, email, re.IGNORECASE) is None:
            raise APIException('This is not a valid email', 401)

        if len( req['password'] ) < 6:
            raise APIException('Password must be at least 6 characters long', 401)

        # If user exists and failed to validate his account
        # user = (Users.query
        #         .filter_by( email=email, password=sha256(req['password']) )
        #         .first())
        user = (Users.query
                .filter_by( email=email )
                .first())
        print('user', user)
        if user and user.status._value_ == 'invalid':     
            data = {'validation_link': jwt_link(user.id)}
            send_email( template='email_validation', emails=user.email, data=data)
            
            return jsonify({'message':'Another email has been sent for email validation'})

        elif user and user.status._value_ == 'valid':
            print('should be ehreCCC')
            raise APIException('This email address is already taken', 400)
        print('should be ehreA')

        user = Users(
            email = email,
            password = sha256(req['password'])
        )
        print('should be ehreBBBB')

        db.session.add(user)
        db.session.commit()

        send_email( template='email_validation', emails=user.email, 
            data={'validation_link': jwt_link(user.id)} )

        return jsonify({'message': 'Please verify your email'}), 200
Beispiel #14
0
def get_balance():
    balanceinfo = None
    apitry = 0
    while not balanceinfo and apitry < apitrylimit:
        try:
            balanceinfo = binance.fetch_balance()
        except Exception as err:
            balanceinfo = None
            log.warning("Failed to get balance, trying again")
            log.warning(err)
            time.sleep(apisleep)
            apitry = apitry + 1
    log.info(f"Balance Info: {balanceinfo}")
    if apitry == apitrylimit:
        send_email("Failed to get balance, API tries exhausted!")
        return 0
    else:
        return balanceinfo
Beispiel #15
0
    def validate(token):

        jwt_data = decode_jwt(token)

        if jwt_data['role'] != 'validating':
            raise APIException('Incorrect token', 400)

        user = Users.query.filter_by(id=jwt_data['sub']).first()
        if user is None:
            raise APIException('Invalid key payload', 400)

        if user.valid == False:
            user.valid = True
            db.session.commit()

        send_email(type='account_created', to=user.email)

        return render_template('email_validated_success.html')
Beispiel #16
0
    def update_buyin_image(user_id, id):

        buyin = Buy_ins.query.filter_by(id=id, user_id=user_id).first()
        if buyin is None:
            raise APIException('Buy_in not found', 404)

        if 'image' not in request.files:
            raise APIException('Image property missing in the files array',
                               404)

        result = cloudinary.uploader.upload(request.files['image'],
                                            public_id='buyin' + str(buyin.id),
                                            crop='limit',
                                            width=450,
                                            height=450,
                                            eager=[{
                                                'width': 200,
                                                'height': 200,
                                                'crop': 'thumb',
                                                'gravity': 'face',
                                                'radius': 100
                                            }],
                                            tags=[
                                                'buyin_receipt',
                                                f'user_{str(buyin.user_id)}',
                                                f'buyin_{str(buyin.id)}'
                                            ])

        buyin.receipt_img_url = result['secure_url']

        db.session.commit()

        send_email(type='buyin_receipt',
                   to=buyin.user.user.email,
                   data={
                       'receipt_url': buyin.receipt_img_url,
                       'tournament_name': buyin.flight.tournament.name,
                       'start_date': buyin.flight.tournament.start_at,
                       'chips': buyin.chips,
                       'seat': buyin.seat,
                       'table': buyin.table
                   })

        return jsonify({'message': 'Image uploaded successfully'}), 200
Beispiel #17
0
    def reset_password():

        req = request.get_json()
        utils.check_params(req, 'email')

        # User forgot their password
        if request.args.get('forgot') == 'true':
            user = Users.query.filter_by(email=req['email']).first()
            if user is None:
                raise APIException('This email is not registered', 400)

            send_email('reset_password_link',
                       emails=req['email'],
                       data={
                           'link':
                           utils.jwt_link(user.id, 'users/reset_password/',
                                          req['email'])
                       })
            return jsonify({
                'message':
                'A link has been sent to your email to reset the password'
            }), 200

        # User knows their password
        utils.check_params(req, 'password', 'new_password')

        if req['password'] == req['new_password']:
            raise APIException(
                'Your new password is the same as the old password')
        if len(req['new_password']) < 6:
            raise APIException(
                'Your new password must be at least 6 characters long')

        user = Users.query.filter_by(email=req['email'],
                                     password=utils.sha256(
                                         req['password'])).first()
        if user is None:
            raise APIException('User not found', 404)

        user.password = utils.sha256(req['new_password'])

        db.session.commit()

        return jsonify({'message': 'Your password has been changed'}), 200
Beispiel #18
0
def single():
    if request.method == 'POST':
        name = request.form['name']
        email = request.form['email']
        phone_number = request.form['phone_number']
        message = request.form['message']

        data = [name, email, phone_number, message]

        subject = "Enquiry"
        fileToSend = None
        msgg = " Name : " + name + " \n  Email : " + email + " \n Phone Number : " + phone_number + " \n message : " + message + "  "

        toaddr = "*****@*****.**"
        send_email(msgg, subject, toaddr, fileToSend)

        return render_template('index.html')

    else:
        return render_template('index.html')
    def validate(token):

        jwt_data = decode_jwt(token)

        accepted_roles = ['first_time_validation', 'email_change']
        if jwt_data['role'] not in accepted_roles:
            raise APIException('Incorrect token', 400)

        user = Users.query.get(jwt_data['sub'])
        if user is None:
            raise APIException('Invalid key payload', 400)

        if user.status._value_ == 'invalid':
            user.status = 'valid'
            db.session.commit()

        if jwt_data['role'] == 'first_time_validation':
            send_email(template='welcome', emails=user.email)

        return render_template('email_validated_success.html')
Beispiel #20
0
    def update_email(user_id):

        body = request.get_json()
        check_params(body, 'email', 'password', 'new_email')

        user = Users.query.filter_by(id=user_id,
                                     email=body['email'],
                                     password=sha256(
                                         body['password'])).first()

        if user is None:
            raise APIException('User not found', 404)

        user.valid = False
        user.email = body['new_email']

        db.session.commit()

        send_email(type='email_validation',
                   to=user.email,
                   data={'validation_link': validation_link(user.id)})

        return jsonify({'message': 'Please verify your new email'}), 200
    def update_buy_in(user_id, id):

        req = request.get_json()
        utils.check_params(req)

        buyin = Buy_ins.query.get(id)
        if buyin is None:
            raise APIException('Buy-in not found', 404)

        buyin_status = buyin.status._value_

        if buyin_status in ['cashed', 'busted']:
            raise APIException('This buy-in can no longer be modified')

        if request.args.get('validate') == 'true':
            if buyin_status == 'pending':
                utils.check_params(req, 'chips', 'table', 'seat')

                # Update chips, table and seat
                if req['chips'] > 999999999:
                    raise APIException('Too many characters for chips')
                if len(req['table']) > 20:
                    raise APIException('Too many characters for table')
                if req['table'] == '':
                    raise APIException('Table can\'t be empty')
                if req['seat'] < 1:
                    raise APIException('Seat can\'t be smaller than 1')

                buyin.chips = req['chips']
                buyin.table = req['table']
                buyin.seat = req['seat']

                buyin.status = 'active'
                send_email(template='buyin_receipt',
                           emails=buyin.user.user.email,
                           data={
                               'receipt_url': buyin.receipt_img_url,
                               'tournament_date':
                               buyin.flight.tournament.start_at,
                               'tournament_name': buyin.flight.tournament.name
                           })

                db.session.commit()

                return jsonify({'buy_in': buyin.serialize()})

            elif buyin_status == 'active':
                raise APIException('Buy-in already validated')

        elif buyin_status == 'pending':
            raise APIException('This buy-in has not been validated', 406)

        # Update status
        if req.get('status') is not None:
            buyin.status = req['status']

        # Update chips, table and seat
        if req.get('chips') is not None:
            if req['chips'] > 999999999:
                raise APIException('Too many characters for chips')
            buyin.chips = req['chips']
        if req.get('table') is not None:
            if len(req['table']) > 20:
                raise APIException('Too many characters for table')
            buyin.table = req['table']
        if req.get('seat') is not None:
            buyin.seat = req['seat']

        db.session.commit()

        return jsonify({'buy_in': buyin.serialize()})
Beispiel #22
0
                    <div>{_5mins_ahead} _4mins_ahead</div>
                '''
                      })

    # Suspend account
    else:
        title = "Account Suspension"
        body = "You're account has been suspended until you pay your swaps"
        swap_rating = 0
        # user_account = session.query(m.Users).get( user.id )
        user.naughty = True
        print('Put on naughty list', user, user.id, user.naughty)
        session.commit()
        send_email(
            template='account_suspension',
            emails=user.email,
            # data={'validation_link': utils.jwt_link(user.id, role='email_change')}
        )

    proto = {
        "user_id": user.id,
        "trmnt_id": trmt_id,
        "title": title,
        "body": body,
        "update": user.result_update
    }
    print('Proto:', proto)

    if users_to_notify == []:
        users_to_notify.append(proto)
    else:
Beispiel #23
0
    def sendemailtest():
        msg = {'name': 'Hello Hernan'}
        r = send_email('account_suspension', '*****@*****.**', data=msg)

        return str(r)
    def get_results():
        '''
            {
                "api_token": "oidf8wy373apudk",
                "tournament_id": 45,
                "tournament_buyin": 150,
                "users": {
                    "*****@*****.**": {
                        "place": 11,
                        "winnings": 200
                    }
                }
            }
        '''
        print("GETTING RESULGX")
        r = request.get_json()
        print('r', r)
        print('Token here', r['api_token'])
        print(os.environ['SP_API_TOKEN_LIVE'])
        # Security token check
        if r['api_token'] != os.environ['SP_API_TOKEN_LIVE']:
            return jsonify({'error': r['api_token']})

        print('b')
        # print('Buyin ID', r['tournament_buyin'])
        trmnt = Tournaments.query.get(r['tournament_id'])
        if trmnt is None:
            return jsonify({
                'error':
                'Tournament not found with id: ' + r['tournament_id']
            })
        print('c')
        trmnt_buyin = r['tournament_buyin']
        trmnt.results_link = (os.environ['POKERSOCIETY_HOST'] +
                              '/results/tournament/' + str(r['tournament_id']))
        print('d')
        # Add all players that haven't won but have swaps in this trmnt
        all_swaps_in_trmnt = Swaps.query.filter_by( tournament_id=trmnt.id ) \
                                        .filter_by( status='agreed' )
        print('d')
        for swap in all_swaps_in_trmnt:
            email = swap.sender_user.user.email
            if email not in r['users']:
                r['users'][email] = {
                    'place': None,
                    'winnings': None,
                }

        print('e')
        # Variable to set swap due date
        due_date = datetime.utcnow() + timedelta(days=4)

        # Process each player's data.. update roi and swap rating.. send email
        for email, userdata in r['users'].items():
            print('userdata', userdata)
            user = Profiles.query.filter(
                Profiles.user.has(email=email)).first()
            if user is None:
                return jsonify(
                    {'error': 'User not found with email: ' + email})

            # Consolidate swaps if multiple with same user
            all_agreed_swaps = user.get_agreed_swaps(r['tournament_id'])
            swaps = {}

            # If user has no swaps, don't send email
            if len(all_agreed_swaps) == 0:
                continue

            print(all_agreed_swaps[0])
            for swap in all_agreed_swaps:
                print("SWAP IS", swap)
                '''
                    {
                        "2": {
                            "count": 2,
                            "counter_percentage": 11,
                            "percentage": 11,
                            "recipient_email": "*****@*****.**"
                        },
                        "4": {
                            "count": 1,
                            "counter_percentage": 7,
                            "percentage": 5,
                            "recipient_email": "*****@*****.**"
                        }
                    }
                '''
                id = str(swap.recipient_id)
                if id not in swaps:
                    swaps[id] = {
                        'count': 1,
                        'percentage': swap.percentage,
                        'counter_percentage': swap.counter_swap.percentage,
                        'recipient_email': swap.recipient_user.user.email
                    }
                else:
                    swaps[id]['count'] += 1
                    swaps[id]['percentage'] += swap.percentage
                    swaps[id][
                        'counter_percentage'] += swap.counter_swap.percentage

                # Set payment due date, swap_rating and result_winnings for each swap
                swap.due_at = due_date
                swap.swap_rating = 5
                swap.result_winnings = True if userdata[
                    'winnings'] != None else False

            db.session.commit()

            total_swap_earnings = 0
            total_amount_of_swaps = 0
            render_swaps = []

            # Go thru the consolidated swaps to create the email templates
            for recipient_id, swapdata in swaps.items():

                recipient = Profiles.query.get(recipient_id)
                if recipient is None:
                    return jsonify(
                        {'error': 'User not found with id: ' + recipient_id})

                # Tournament buyin could be "$200" "$0++" "Day 2"
                regex = re.search(r'\$\s*(\d+)', str(trmnt_buyin))
                entry_fee = int(regex.group(1)) if regex else 0

                # Winnings are integers, but in case they are a string, ex "Satellite"
                to_int = lambda x: x if isinstance(x, int) else 0

                profit_sender = to_int(userdata['winnings']) - entry_fee
                amount_owed_sender = profit_sender * swapdata[
                    'percentage'] / 100

                # recipient_winnings can be None
                recipient_winnings = r['users'][
                    swapdata['recipient_email']]['winnings'] or 0
                profit_recipient = to_int(recipient_winnings) - entry_fee
                amount_owed_recipient = profit_recipient * swapdata[
                    'counter_percentage'] / 100

                render_swaps.append({
                    'amount_of_swaps':
                    swapdata['count'],
                    'entry_fee':
                    entry_fee,
                    'sender_first_name':
                    user.first_name,
                    'total_earnings_sender':
                    '{:,}'.format(userdata['winnings']),
                    'swap_percentage_sender':
                    swapdata['percentage'],
                    'swap_profit_sender':
                    '{:,}'.format(profit_sender),
                    'amount_owed_sender':
                    '{:,}'.format(round(amount_owed_sender)),
                    'recipient_first_name':
                    recipient.first_name,
                    'recipient_last_name':
                    recipient.last_name,
                    'recipient_profile_pic_url':
                    recipient.profile_pic_url,
                    'total_earnings_recipient':
                    '{:,}'.format(recipient_winnings),
                    'swap_percentage_recipient':
                    swapdata['counter_percentage'],
                    'swap_profit_recipient':
                    '{:,}'.format(profit_recipient),
                    'amount_owed_recipient':
                    '{:,}'.format(round(amount_owed_recipient))
                })

                total_swap_earnings -= amount_owed_sender
                total_swap_earnings += amount_owed_recipient
                total_amount_of_swaps += swapdata['count']

            if total_swap_earnings >= 0:
                for swap in all_agreed_swaps:
                    a_swap = Swaps.query.get(swap.id)
                    a_swap.paid = True
                    a_swap.paid_at = datetime.utcnow()
                    a_swap.confirmed = True
                    a_swap.confirmed_at = datetime.utcnow()

            # Update user and buy ins
            user.roi_rating = user.calculate_roi_rating()

            buyin = Buy_ins.get_latest(user.id, trmnt.id)
            buyin.place = userdata['place']
            buyin.winnings = userdata['winnings']

            db.session.commit()

            sign = '-' if total_swap_earnings < 0 else '+'
            s = 's' if total_amount_of_swaps > 1 else ''
            # print('coming in')
            a_user = Profiles.query.get(user.id)
            # print('isr esult update true', a_user.result_update, user.id)
            if a_user.result_update == True:
                send_fcm(user_id=user.id,
                         title="Results Posted",
                         body=trmnt.name + " posted their results.",
                         data={
                             'id': trmnt.id,
                             'alert':
                             trmnt.name + " just posted their results.",
                             'type': 'result',
                             'initialPath': 'Event Results',
                             'finalPath': 'Swap Results'
                         })

            send_email(
                'swap_results',
                [email],  #'*****@*****.**','*****@*****.**'],
                data={
                    'tournament_date':
                    trmnt.start_at.strftime('%A, %B %d, %Y - %I:%M %p'),
                    'tournament_name':
                    trmnt.name,
                    'results_link':
                    trmnt.results_link,
                    'total_swaps':
                    f"{total_amount_of_swaps} swap{s}",
                    'total_swappers':
                    f"{len(swaps)} {'person' if len(swaps) == 1 else 'people'}",
                    'total_swap_earnings':
                    f'{sign}${"{:,.2f}".format( abs(total_swap_earnings) )}',
                    'render_swaps':
                    render_swaps,
                    'roi_rating':
                    round(user.roi_rating),
                    'swap_rating':
                    round(user.swap_rating, 1)
                })

        trmnt.status = 'closed'
        db.session.commit()

        return jsonify({'message': 'Results processed successfully'}), 200
Beispiel #25
0
    def update_swap(user_id, id):

        # Get sender user
        sender = Profiles.query.get(user_id)

        req = request.get_json()
        utils.check_params(req)

        # Get swaps
        swap = Swaps.query.get(id)
        if sender.id != swap.sender_id:
            raise APIException(
                'Access denied: You are not the sender of this swap', 401)
        current_percentage = swap.percentage
        if sender.get_coins() < swap.cost:
            raise APIException('Insufficient coins to see this swap', 402)

        if swap.status._value_ in ['canceled', 'rejected', 'agreed']:
            raise APIException('This swap can not be modified', 400)

        counter_swap_body = {}
        counter_swap = Swaps.query.get(swap.counter_swap_id)
        if swap is None or counter_swap is None:
            raise APIException('Swap not found', 404)

        # Get recipient user
        recipient = Profiles.query.get(swap.recipient_id)
        if recipient is None:
            raise APIException('Recipient user not found', 404)

        new_status = req.get('status')
        current_status = swap.status._value_

        if 'percentage' in req and new_status not in [
                'agreed', 'rejected', 'canceled'
        ]:

            percentage = req['percentage']
            counter = req.get('counter_percentage', percentage)
            if percentage < 1 or counter < 1:
                raise APIException('Cannot swap less than %1', 400)

            sender_availability = sender.available_percentage(
                swap.tournament_id)
            considering_this_swap = current_status == 'incoming'
            actions = percentage if considering_this_swap else (
                percentage - swap.percentage)
            if actions > sender_availability:
                raise APIException((
                    'Swap percentage too large. You can not exceed 50% per tournament. '
                    f'You have available: {sender_availability}%'), 400)

            recipient_availability = \
                recipient.available_percentage( swap.tournament_id )
            if (counter - counter_swap.percentage) > recipient_availability:
                raise APIException(
                    ('Swap percentage too large for recipient. '
                     f'He has available to swap: {recipient_availability}%'),
                    400)

            # Update percentages
            swap.percentage = percentage
            counter_swap.percentage = counter

        if current_status == 'pending':
            if new_status == 'agreed':
                raise APIException('Cannot agree a swap on a pending status',
                                   400)
            if new_status == 'rejected':
                raise APIException('Cannot reject this swap', 400)
        if current_status in ['incoming', 'counter_incoming'
                              ] and new_status == 'canceled':
            raise APIException('Cannot cancel this swap', 400)

        # Update status
        if new_status in ['agreed', 'rejected', 'canceled']:
            if new_status == 'agreed':
                if recipient.get_coins() < swap.cost:
                    raise APIException(
                        'Recipient has insufficient coins to process this swap'
                    )
                if current_status == 'incoming':
                    overdraft = current_percentage - sender.available_percentage(
                        swap.tournament_id)
                    if overdraft > 0:
                        raise APIException(
                            f'Cannot agree to this swap, you are overdrafting by {str(overdraft)}%',
                            400)
            swap.status = new_status
            counter_swap.status = Swaps.counter_status(new_status)
        # If current swap is pending, leave statuses as they are
        elif current_status != 'pending':
            swap.status = Swaps.counter_status(swap.status._value_)
            counter_swap.status = Swaps.counter_status(
                counter_swap.status._value_)
            # send_fcm('swap_incoming_notification', recipient.id)

        db.session.commit()

        if new_status == 'agreed':

            db.session.add(Transactions(user_id=user_id, coins=-swap.cost))
            db.session.add(Transactions(user_id=recipient.id,
                                        coins=-swap.cost))
            db.session.commit()

            # send_fcm('swap_agreed_notificatin', recipient.id)
            user1_receipt = Buy_ins.get_latest(sender.id, swap.tournament_id)
            user2_receipt = Buy_ins.get_latest(recipient.id,
                                               swap.tournament_id)

            send_email(template='swap_confirmation',
                       emails=[sender.user.email, recipient.user.email],
                       data={
                           'tournament_date':
                           swap.tournament.start_at,
                           'tournament_name':
                           swap.tournament.name,
                           'user1_name':
                           f'{sender.first_name} {sender.last_name}',
                           'user1_prof_pic':
                           sender.profile_pic_url,
                           'user1_percentage':
                           swap.percentage,
                           'user1_receipt_url':
                           user1_receipt and user1_receipt.receipt_img_url,
                           'user2_name':
                           f'{recipient.first_name} {recipient.last_name}',
                           'user2_prof_pic':
                           recipient.profile_pic_url,
                           'user2_percentage':
                           counter_swap.percentage,
                           'user2_receipt_url':
                           user2_receipt and user2_receipt.receipt_img_url
                       })

        return jsonify([
            swap.serialize(),
            counter_swap.serialize(),
        ])
Beispiel #26
0
    def create_swap(user_id):

        # get sender user
        sender = Profiles.query.get(user_id)

        body = request.get_json()
        check_params(body, 'tournament_id', 'recipient_id', 'percentage')

        percentage = abs(body['percentage'])

        # get recipient user
        recipient = Profiles.query.get(body['recipient_id'])
        if recipient is None:
            raise APIException('Recipient user not found', 404)

        if Swaps.query.get(
            (user_id, body['recipient_id'], body['tournament_id'])):
            raise APIException('Swap already exists, can not duplicate', 400)

        sender_availability = sender.available_percentage(
            body['tournament_id'])
        if percentage > sender_availability:
            raise APIException((
                'Swap percentage too large. You can not exceed 50% per tournament. '
                f'You have available: {sender_availability}%'), 400)

        recipient_availability = recipient.available_percentage(
            body['tournament_id'])
        if percentage > recipient_availability:
            raise APIException(
                ('Swap percentage too large for recipient. '
                 f'He has available to swap: {recipient_availability}%'), 400)

        db.session.add(
            Swaps(sender_id=user_id,
                  tournament_id=body['tournament_id'],
                  recipient_id=body['recipient_id'],
                  percentage=percentage))
        db.session.add(
            Swaps(sender_id=body['recipient_id'],
                  tournament_id=body['tournament_id'],
                  recipient_id=user_id,
                  percentage=percentage))
        db.session.commit()

        trmnt = Tournaments.query.get(body['tournament_id'])

        send_email(type='swap_created',
                   to=sender.user.email,
                   data={
                       'percentage': percentage,
                       'recipient_firstname': recipient.first_name,
                       'recipient_lastname': recipient.last_name,
                       'recipient_email': recipient.user.email
                   })
        send_email(type='swap_created',
                   to=recipient.user.email,
                   data={
                       'percentage': percentage,
                       'recipient_firstname': sender.first_name,
                       'recipient_lastname': sender.last_name,
                       'recipient_email': sender.user.email
                   })

        return jsonify({'message': 'Swap created successfully.'}), 200
Beispiel #27
0
    def add(self, task):
        if not isinstance(task, Task):
            raise TaskException('Can not schedule non-task %s' % task)

        if not task.initialized():
            # we can't get the repr of it since it's not initialized...
            raise TaskException('Task of class %s not initialized. Did you override __init__ and forget to call super(...).__init__?' % task.__class__.__name__)

        try:
            task_id = task.task_id

            if task_id in self.__scheduled_tasks:
                return  # already scheduled
            logger.debug("Checking if %s is complete" % task_id)
            is_complete = False
            try:
                is_complete = task.complete()
                if is_complete not in (True, False):
                    raise Exception("Return value of Task.complete() must be boolean (was %r)" % is_complete)
            except KeyboardInterrupt:
                raise
            except:
                msg = "Will not schedule %s or any dependencies due to error in complete() method:" % (task,)
                # like logger.exception but with WARNING level
                logger.warning(msg, exc_info=1)
                config = configuration.get_config()
                receiver = config.get('core', 'error-email', None)
                sender = config.get('core', 'email-sender',
                                    notifications.DEFAULT_CLIENT_EMAIL)
                logger.info("Sending warning email to %r" % receiver)
                notifications.send_email(
                    subject="Luigi: %s failed scheduling" % (task,),
                    message="%s:\n%s" % (msg, traceback.format_exc()),
                    sender=sender,
                    recipients=(receiver,))
                return
                # abort, i.e. don't schedule any subtasks of a task with
                # failing complete()-method since we don't know if the task
                # is complete and subtasks might not be desirable to run if
                # they have already ran before

            if is_complete:
                # Not submitting dependencies of finished tasks
                self.__scheduler.add_task(self.__id, task_id, status=DONE,
                                          runnable=False)

            elif task.run == NotImplemented:
                self.__scheduled_tasks[task_id] = task
                self.__scheduler.add_task(self.__id, task_id, status=PENDING,
                                          runnable=False)
                logger.warning('Task %s is not complete and run() is not implemented. Probably a missing external dependency.', task_id)
            else:
                self.__scheduled_tasks[task_id] = task
                deps = task.deps()
                for d in deps:
                    if isinstance(d, Target):
                        raise Exception('requires() can not return Target objects. Wrap it in an ExternalTask class')
                    elif not isinstance(d, Task):
                        raise Exception('requires() must return Task objects')
                deps = [d.task_id for d in task.deps()]
                self.__scheduler.add_task(self.__id, task_id, status=PENDING,
                                          deps=deps, runnable=True)
                logger.info('Scheduled %s' % task_id)

                for task_2 in task.deps():
                    self.add(task_2)  # Schedule stuff recursively
        except KeyboardInterrupt:
            raise
        except:
            logger.exception("Luigi unexpected framework error while scheduling %s" % task)
            config = configuration.get_config()
            receiver = config.get('core', 'error-email', None)
            sender = config.get('core', 'email-sender',
                                notifications.DEFAULT_CLIENT_EMAIL)
            notifications.send_email(
                subject="Luigi: Framework error while scheduling %s" % (task,),
                message="Luigi framework error:\n%s" % traceback.format_exc(),
                recipients=(receiver,),
                sender=sender)
    def check_swaps():
        swapsToBePaid = db.session.query(m.Swaps) \
            .filter( Swaps.due_at != None ) \
            .filter( Swaps.paid == False )

        swapsToBeConfirmed = db.session.query(m.Swaps) \
            .filter( m.Swaps.due_at != None ) \
            .filter( m.Swaps.paid == True ) \
            .filter(m.Swaps.confirmed == False) \
            .filter(m.Swaps.disputed == False)

        now = datetime.utcnow()
        users_to_update_swaprating = []
        users_to_notify = []

        # REMINDERS FOR SWAPS TO BE PAID (SEND ONE NOTIFICATION PER USER, PER TOURNAMENT ID)
        for swap in swapsToBePaid:
            user = db.session.query(m.Profiles).get(swap.sender_id)
            first_due = swap.due_at
            time_after_due_date = now - swap.due_at
            trmt_id = swap.tournament_id
            title = ''
            body = ''
            if now < swap.due_at:
                title = "5 Star Reminder"
                body = "Pay before Swap Due"
            elif time_after_due_date < timedelta(days=2):
                title = "4 Star Reminder"
                body = "Pay before 2 Days after Due Date"
            elif time_after_due_date < timedelta(days=4):
                title = "3 Star Reminder"
                body = "Pay before 4 Days after Due Date"
            elif time_after_due_date < timedelta(days=6):
                title = "2 Star Reminder"
                body = "Pay before 6 Days after Due Date"
            elif time_after_due_date < timedelta(days=8):
                title = "1 Star Reminder"
                body = "8 days after results"
            elif time_after_due_date < timedelta(days=9):
                title = "Warning: Account Suspension"
                body = "9 days after results"
                time = datetime.utcnow()
                # domain = os.environ['MAILGUN_DOMAIN']
                # requests.post(f'https://api.mailgun.net/v3/{domain}/messages',
                #     auth=(
                #         'api',
                #         os.environ.get('MAILGUN_API_KEY')),
                #     data={
                #         'from': f'{domain} <*****@*****.**>',
                #         'to': user.user.email,
                #         'subject': 'You are in Danger of being Suspended',
                #         'text': 'Sending text email',
                #         'html': f'''
                #             <div>trmnt.id {trmnt.id}</div><br />
                #             <div>{trmnt.start_at} trmnt.start_at</div>
                #             <div>{time} datetime.utcnow()</div>
                #             <div>{_5mins_ago} _4mins_ago</div>
                #             <div>{_5mins_ahead} _4mins_ahead</div>
                #         '''
                # })

            # Suspend account
            else:
                title = "Account Suspension"
                body = "You're account has been suspended until you pay your swaps"
                swap_rating = 0
                # user_account = session.query(m.Users).get( user.id )
                user.naughty = True
                print('Put on naughty list', user, user.id, user.naughty)
                db.session.commit()
                send_email(
                    template='account_suspension',
                    emails=user.email,
                    # data={'validation_link': utils.jwt_link(user.id, role='email_change')}
                )
            proto = {
                "user_id": user.id,
                "trmnt_id": trmt_id,
                "title": title,
                "body": body,
                "update": user.result_update
            }
            print('Proto:', proto)

            if users_to_notify == []:
                users_to_notify.append(proto)
            else:
                for obj in users_to_notify:
                    print('obj', obj)
                    if any(obj['user_id'] == user.id):
                        print("Success!")
                        index = -1
                        for i, obj in enumerate(users_to_notify):
                            if obj['user_id'] == user.id:
                                index = i
                                if users_to_notify[i]['trmnt_id'] != trmt_id:
                                    print("Sending to User Id:",
                                          proto['user_id'])
                                    users_to_notify.append(proto)
                                else:
                                    print("Same tournament")

        # REMINDERS FOR SWAPS TO BE CONFIRMED (SEND ONE NOTIFICATION PER USER, PER TOURNAMENT ID)
        for swap in swapsToBeConfirmed:
            user = db.session.query(m.Profiles).get(swap.sender_id)
            a_user = db.session.query(m.Profiles).get(swap.recipient_id)

            time_after_due_date = swap.paid_at - swap.due_at
            trmt_id = swap.tournament_id
            title = None
            body = None
            swap_rating = None

            #If User had failed to confirm paid swaps after 5 days
            if now >= swap.paid_at + timedelta(days=5):
                if time_after_due_date < timedelta(days=0):
                    swap_rating = 5
                elif time_after_due_date < timedelta(days=2):
                    swap_rating = 4
                elif time_after_due_date < timedelta(days=4):
                    swap_rating = 3
                elif time_after_due_date < timedelta(days=6):
                    swap_rating = 2
                elif time_after_due_date < timedelta(days=8):
                    swap_rating = 1
                else:
                    swap_rating = 0
                title = "Swap Confirmation Auto-Completed"
                body = "You Swap Rating has been updated accordingly."
                swap.confirmed = True

                # ADD TO SWAP RATINGS TO UPDATE
                if swap.swap_rating != swap_rating:
                    # print(f'Updating swap rating for swap {swap.id} from {swap.swap_rating} to {swap_rating}')
                    swap.swap_rating = swap_rating
                    db.session.commit()
                    users_to_update_swaprating.append(user)

                # ADD TO USERS TO UPDATE ( ONE PER PERSON SWAPPED WITH, PER TOURNAMENT)
                proto = {
                    "user_id": user.id,
                    "trmnt_id": trmt_id,
                    "title": title,
                    "body": body,
                    "update": user.result_update
                }
                if any(obj['user_id'] == user.id for obj in users_to_notify):
                    index = -1
                    for i, obj in enumerate(users_to_notify):
                        if obj['user_id'] == user.id:
                            index = i
                            if users_to_notify[i]['trmnt_id'] != trmt_id:
                                users_to_notify.append(proto)
                            else:
                                print("Same tournament")
            else:
                # if now < swap.paid_at + timedelta(days=2) and now > swap.paid_at + timedelta(days=1):
                if now > swap.paid_at:
                    title = "Confirm Swap Payment"
                    body = "Confirm the swap payment made to you"
                elif now > swap.paid_at + timedelta(
                        days=4) and now < swap.paid_at + timedelta(days=5):
                    title = "Your Confirmation will be Autocompleted"
                    body = "Confirm or Dispute before 5 days have pass after being paid"

                # ADD TO USERS TO UPDATE ( ONE PER PERSON SWAPPED WITH, PER TOURNAMENT)
                proto = {
                    "user_id": a_user.id,
                    "trmnt_id": trmt_id,
                    "title": title,
                    "body": body,
                    "update": user.result_update
                }
                print("Proto: ", proto)
                if users_to_notify == []:
                    users_to_notify.append(proto)
                else:
                    if any(obj['user_id'] == a_user.id
                           for obj in users_to_notify):
                        index = -1
                        for i, obj in enumerate(users_to_notify):
                            if obj['user_id'] == a_user.id:
                                index = i
                                if users_to_notify[i]['trmnt_id'] != trmt_id:
                                    users_to_notify.append(proto)
                                else:
                                    print("Same tournament")

        # # Helper function to calculate the swap rating, used below
        def calculate_swap_rating(user_id):
            swaps = db.session.query(m.Swaps) \
                .filter_by( sender_id=user_id ) \
                .filter( m.Swaps.due_at != None )
            total_swap_ratings = 0
            for swap in swaps:
                total_swap_ratings += swap.swap_rating
            return total_swap_ratings / swaps.count()

        for user in users_to_update_swaprating:
            user.swap_rating = calculate_swap_rating(user.id)
            # print(f'Updating swap rating for user {user.id} to {user.swap_rating}')
            db.session.commit()

        for a_user in users_to_notify:
            print("User being notified", a_user['user_id'], " about ",
                  a_user['body'])
            if a_user['update'] == True:
                send_fcm(user_id=a_user['user_id'],
                         title=a_user['title'],
                         body=a_user['body'],
                         data={
                             'id': a_user['trmnt_id'],
                             'alert': a_user['body'],
                             'type': 'result',
                             'initialPath': 'Event Results',
                             'finalPath': 'Swap Results'
                         })
        return "Swappers notified Successfully"
Beispiel #29
0
def hist_positive(exchgdata, tf):
    #  for the div detection
    (t, o, h, l, c, v) = exchgdata.get_split_tohlcv(tf, 34)
    exchgdata.dprint_last_candles(tf, 5)
    (kvo, signal) = klinger_kama(h, l, c, v)
    hist = kvo[-1] - signal[-1]
    log.info("hist is %.2f" % hist)
    positive = True
    if hist <= 0:
        positive = False
    return positive


sleeptime = 30
send_email('\nBot Active!')
hist_tf = '15m'

binance_data = ExchgData.ExchgData('binance')

last_hist_positive = hist_positive(binance_data, hist_tf)
curr_hist_positive = last_hist_positive

while [1]:
    log.debug("Main loop")
    orders.update_bracket_pct(config.sl, config.tp)

    curr_hist_positive = hist_positive(binance_data, hist_tf)

    shorts = orders.get_position_size('short')
    longs = orders.get_position_size('long')
Beispiel #30
0
def report_trade(action, ordersize, stacked, price):
    report_string = "action: %s\tordersize: %d\tstacked: %d\tprice: %.2f" % (
        action, ordersize, stacked, price)
    tl.info(report_string)
    log.debug(report_string)
    send_email(report_string)
Beispiel #31
0
    def add(self, task):
        if not isinstance(task, Task):
            raise TaskException('Can not schedule non-task %s' % task)

        if not task.initialized():
            # we can't get the repr of it since it's not initialized...
            raise TaskException(
                'Task of class %s not initialized. Did you override __init__ and forget to call super(...).__init__?'
                % task.__class__.__name__)

        try:
            task_id = task.task_id

            if task_id in self.__scheduled_tasks:
                return  # already scheduled
            logger.debug("Checking if %s is complete" % task_id)
            is_complete = False
            try:
                is_complete = task.complete()
                if is_complete not in (True, False):
                    raise Exception(
                        "Return value of Task.complete() must be boolean (was %r)"
                        % is_complete)
            except KeyboardInterrupt:
                raise
            except:
                msg = "Will not schedule %s or any dependencies due to error in complete() method:" % (
                    task, )
                logger.warning(
                    msg,
                    exc_info=1)  # like logger.exception but with WARNING level
                receiver = interface.get_config().get('core', 'error-email',
                                                      None)
                sender = interface.get_config().get(
                    'core', 'email-sender', notifications.DEFAULT_CLIENT_EMAIL)
                logger.info("Sending warning email to %r" % receiver)
                notifications.send_email(
                    subject="Luigi: %s failed scheduling" % (task, ),
                    message="%s:\n%s" % (msg, traceback.format_exc()),
                    sender=sender,
                    recipients=(receiver, ))
                return
                # abort, i.e. don't schedule any subtasks of a task with
                # failing complete()-method since we don't know if the task
                # is complete and subtasks might not be desirable to run if
                # they have already ran before

            if is_complete:
                # Not submitting dependencies of finished tasks
                self.__scheduler.add_task(self.__id,
                                          task_id,
                                          status=DONE,
                                          runnable=False)

            elif task.run == NotImplemented:
                self.__scheduled_tasks[task_id] = task
                self.__scheduler.add_task(self.__id,
                                          task_id,
                                          status=PENDING,
                                          runnable=False)
                logger.warning(
                    'Task %s is not complete and run() is not implemented. Probably a missing external dependency.',
                    task_id)
            else:
                self.__scheduled_tasks[task_id] = task
                deps = task.deps()
                for d in deps:
                    if isinstance(d, Target):
                        raise Exception(
                            'requires() can not return Target objects. Wrap it in an ExternalTask class'
                        )
                    elif not isinstance(d, Task):
                        raise Exception('requires() must return Task objects')
                deps = [d.task_id for d in task.deps()]
                self.__scheduler.add_task(self.__id,
                                          task_id,
                                          status=PENDING,
                                          deps=deps,
                                          runnable=True)
                logger.info('Scheduled %s' % task_id)

                for task_2 in task.deps():
                    self.add(task_2)  # Schedule stuff recursively
        except KeyboardInterrupt:
            raise
        except:
            logger.exception(
                "Luigi unexpected framework error while scheduling %s" % task)
            receiver = interface.get_config().get('core', 'error-email', None)
            sender = interface.get_config().get(
                'core', 'email-sender', notifications.DEFAULT_CLIENT_EMAIL)
            notifications.send_email(
                subject="Luigi: Framework error while scheduling %s" %
                (task, ),
                message="Luigi framework error:\n%s" % traceback.format_exc(),
                recipients=(receiver, ),
                sender=sender)
Beispiel #32
0
 def create_anonymous_user(self, email):
     info = self.db.create({"email":email, "verified":False, "anonymous":True, "email_verified":False, "type":"user"})
     notifications.send_email(email, "Verify email", boiler+"http://brasstacks.mozilla.com/users/email_verify/"+info['id'])
     return self.db.get(info['id'])
Beispiel #33
0
    def update_swap(user_id):

        # get sender user
        sender = Profiles.query.get(user_id)

        body = request.get_json()
        check_params(body, 'tournament_id', 'recipient_id')

        # get recipient user
        recipient = Profiles.query.get(body['recipient_id'])
        if recipient is None:
            raise APIException('Recipient user not found', 404)

        # get swap
        swap = Swaps.query.get((user_id, recipient.id, body['tournament_id']))
        counter_swap = Swaps.query.get(
            (recipient.id, user_id, body['tournament_id']))
        if swap is None or counter_swap is None:
            raise APIException('Swap not found', 404)

        if 'percentage' in body:

            percentage = abs(body['percentage'])
            counter = abs(body['counter_percentage']
                          ) if 'counter_percentage' in body else percentage

            sender_availability = sender.available_percentage(
                body['tournament_id'])
            if percentage > sender_availability:
                raise APIException((
                    'Swap percentage too large. You can not exceed 50% per tournament. '
                    f'You have available: {sender_availability}%'), 400)

            recipient_availability = recipient.available_percentage(
                body['tournament_id'])
            if counter > recipient_availability:
                raise APIException(
                    ('Swap percentage too large for recipient. '
                     f'He has available to swap: {recipient_availability}%'),
                    400)

            new_percentage = swap.percentage + percentage
            new_counter_percentage = counter_swap.percentage + counter

            # So it can be updated correctly with the update_table funcion
            body['percentage'] = new_percentage
            update_table(counter_swap, {'percentage': new_counter_percentage})

            send_email(type='swap_created',
                       to=sender.user.email,
                       data={
                           'percentage': new_percentage,
                           'counter_percentage': new_counter_percentage,
                           'recipient_firstname': recipient.first_name,
                           'recipient_lastname': recipient.last_name,
                           'recipient_email': recipient.user.email
                       })
            send_email(type='swap_created',
                       to=recipient.user.email,
                       data={
                           'percentage': new_counter_percentage,
                           'counter_percentage': new_percentage,
                           'recipient_firstname': sender.first_name,
                           'recipient_lastname': sender.last_name,
                           'recipient_email': sender.user.email
                       })

        update_table(swap,
                     body,
                     ignore=[
                         'tournament_id', 'recipient_id', 'paid',
                         'counter_percentage'
                     ])

        db.session.commit()

        return jsonify([swap.serialize(), counter_swap.serialize()])
Beispiel #34
0
sdk = looker_sdk.init31()

#Get A list of Users with Attributes    
looker_users = sdk.all_users()

today_for_db = datetime.date.today().strftime("%Y-%m-%d")
datetime_one_year_ago = datetime.date.today() - datetime.timedelta(days=365)

for user in looker_users:
    if(user.credentials_saml is not None and not(user.is_disabled)): 
        #Has not logged-in in a year        
        if(datetime.datetime.strptime(user.credentials_saml.logged_in_at.replace('Z', '').replace('T',' '), '%Y-%m-%d %H:%M:%S.%f').date() == datetime_one_year_ago ):
            #Email User with account disable warning
            email_subject = "Looker Account Disable Warning - " + user.email
            disable_email_body = email_body.disable_body_html(user.email)
            notifications.send_email("*****@*****.**", [user.email], ["*****@*****.**"], [], email_subject, disable_email_body)

            #Insert warning into log table
            mycursor = mydb.cursor()
            sql = "INSERT INTO user_downgrade_log VALUES (%s, %s, %s, %s)"
            val = (user.id, user.email, "Disable", today_for_db)
            mycursor.execute(sql, val)
            mydb.commit()
            print("Disable Log Record Inserted - " + user.email)

        else:
            #Email standard users without usage in last 3 months
            for group_id in user.group_ids:
                if(group_id) in [YOUR STANDARD GROUP IDS] and user.id not in standard_users_with_usage_list: #need to check db to make sure user did not get the email already
                    #Email User with account downgrade warning
                    #Need to save these users to a db to ensure they only get the email once