Exemple #1
0
 def get(history, user_id=False):
     close_time = utils.designated_trmnt_close_time()
     condition = Flights.start_at < close_time if history == True \
             else Flights.start_at > close_time
     flights = Flights.query.filter(condition)
     if user_id:
         flights = flights.filter(Flights.buy_ins.any(user_id=user_id))
     return flights if flights.count() > 0 else None
 def get_history(user_id=False):
     close_time = utils.designated_trmnt_close_time()
     trmnts = Tournaments.query \
                 .filter( Tournaments.flights.any(
                     db.not_( Flights.start_at > close_time )))
     if user_id:
         trmnts = trmnts.filter( Tournaments.flights.any(
                         Flights.buy_ins.any( user_id = user_id ))) \
                     .order_by( Tournaments.start_at.desc() )
     return trmnts if trmnts.count() > 0 else None
Exemple #3
0
    def update_buyin_image(user_id, id):

        close_time = utils.designated_trmnt_close_time()

        flight = Flights.query.get(id)
        if flight is None or flight.start_at < close_time:
            raise APIException(
                "Cannot buy into this flight. It either has ended, or does not exist"
            )

        buyin = Buy_ins(user_id=user_id, flight_id=id)
        db.session.add(buyin)
        db.session.flush()

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

        utils.resolve_google_credentials()

        result = utils.cloudinary_uploader(type='buyin',
                                           image=request.files['image'],
                                           public_id='buyin' + str(buyin.id),
                                           tags=[
                                               'buyin_receipt',
                                               'user_' + str(user_id),
                                               'buyin_' + str(buyin.id)
                                           ])

        def terminate_buyin():
            cloudinary.uploader.destroy('buyin' + str(buyin.id))
            db.session.rollback()
            raise APIException('Take another photo')

        ocr_data = utils.ocr_reading(result)
        if list(ocr_data) == []:
            terminate_buyin()

        regex_data = regex.hard_rock(ocr_data)
        nones = 0
        for val in regex_data.values():
            if val is None: nones += 1
        if nones > 2:
            terminate_buyin()

        buyin.receipt_img_url = result['secure_url']
        db.session.commit()

        return jsonify({'buyin_id': buyin.id, 'receipt_data': regex_data})
Exemple #4
0
    def get_history(user_id=False):
        close_time = utils.designated_trmnt_close_time()
                        # db.not_( Flights.start_at > close_time ))) \
        # print('close time', close_time)

        trmnts = Tournaments.query \
                    .filter( Tournaments.flights.any(Flights.start_at < close_time )) \
                    .order_by( Tournaments.start_at.desc() )
        # for trmnt in trmnts:
        #     print("YOU WERE IN HERE", trmnt)
        if user_id:
            trmnts = trmnts.filter( Tournaments.flights.any( 
                            Flights.buy_ins.any( user_id = user_id )))
                        
        return trmnts if trmnts.count() > 0 else None
    def update_buyin_image(user_id, id):

        close_time = utils.designated_trmnt_close_time()

        flight = Flights.query.get(id)
        # if flight is None or flight.start_at < close_time:
        #     raise APIException(
        #         "Cannot buy into this flight. It either has ended, or does not exist")

        buyin = Buy_ins(user_id=user_id, flight_id=id)
        db.session.add(buyin)
        db.session.flush()

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

        utils.resolve_google_credentials()

        result = cloudinary.uploader.upload(request.files['image'],
                                            public_id='buyin' + str(buyin.id),
                                            crop='limit',
                                            width=1000,
                                            height=1000,
                                            tags=[
                                                'buyin_receipt',
                                                'user_' + str(user_id),
                                                'buyin_' + str(buyin.id)
                                            ])

        def terminate_buyin():
            cloudinary.uploader.destroy('buyin' + str(buyin.id))
            db.session.rollback()
            raise APIException('Take another photo')

        ocr_data = utils.ocr_reading(result)
        if list(ocr_data) == []:
            terminate_buyin()

        regex_data = regex.hard_rock(ocr_data)
        nones = 0
        for val in regex_data.values():
            if val is None: nones += 1
        if nones > 2:
            terminate_buyin()

        if None in [regex_data['player_name'], regex_data['casino']]:
            terminate_buyin()

        #############################################
        # Verify regex data against tournament data

        # Check player name
        validation = {}
        user = Profiles.query.get(user_id)
        condition = user.first_name.lower() in regex_data['player_name'].lower(
        )
        validation['first_name'] = {
            'ocr': regex_data['player_name'],
            'database': user.first_name,
            'valid': True if condition else False
        }
        condition = user.last_name.lower() in regex_data['player_name'].lower()
        validation['last_name'] = {
            'ocr': regex_data['player_name'],
            'database': user.last_name,
            'valid': True if condition else False
        }
        condition = user.nickname.lower() in regex_data['player_name'].lower()
        validation['nickname'] = {
            'ocr': regex_data['player_name'],
            'database': user.nickname,
            'valid': True if condition else False
        }

        # Check casino name
        trmnt_casino = flight.tournament.casino
        validation['casino'] = {
            'ocr': regex_data['casino'],
            'database': trmnt_casino,
            'valid': True
        }
        casino_names = regex_data['casino'].split(' ')
        for name in casino_names:
            if name.lower() not in trmnt_casino.lower():
                validation['casino']['valid'] = False
                break

        # Check date
        regex_timestamp = regex_data['receipt_timestamp']
        try:
            dt = datetime.strptime(regex_timestamp, '%B %d, %Y %I:%M %p')
        except:
            dt = None

        valid = False
        if dt is not None:
            close = flight.start_at + hours_to_close_tournament
            if datetime.utcnow() < close:
                valid = True
        validation['datetime'] = {
            'ocr': regex_timestamp,
            'flight_start_time': flight.start_at,
            'valid': valid
        }

        buyin.receipt_img_url = result['secure_url']
        db.session.commit()

        return jsonify({
            'buyin_id': buyin.id,
            'receipt_data': regex_data,
            'validation': validation,
            'ocr_data': ocr_data
        })
    def check_tournaments():
        def get_all_players_from_trmnt(trmnte):
            the_users = []
            for flight in trmnte.flights:
                for a_buyin in flight.buy_ins:
                    if a_buyin.user not in the_users:  # no repeats
                        the_users.append(a_buyin.user)
            return the_users

        close_time = utils.designated_trmnt_close_time()

        # any tournaments that are open and latest flight start at isnt later close_time
        trmnts = db.session.query(m.Tournaments) \
            .filter( m.Tournaments.status == 'open') \
            .filter( m.Tournaments.flights.any(
                m.Flights.start_at < close_time
            ))

        if trmnts is not None:
            for trmnt in trmnts:
                latest_flight = trmnt.flights[-1]
                print(latest_flight.start_at.strftime("%c"))
                start_time = latest_flight.start_at + timedelta(hours=17)
                # lastTime = start_time.strftime("%b. %d %I:%M %p")
                if latest_flight.start_at < close_time:
                    # This tournament is over: change status and clean swaps
                    trmnt.status = 'waiting_results'
                    swaps = db.session.query(Swaps) \
                        .filter( Swaps.tournament_id == trmnt.id ) \
                        .filter( or_(
                            Swaps.status == 'pending',
                            Swaps.status == 'incoming',
                            Swaps.status == 'counter_incoming' ) )

                    if swaps is not None:
                        for swap in swaps:
                            print('Update swap status to "canceled", id:',
                                  swap.id)
                            swap.status = 'canceled'
                        db.session.commit()

                    eww = db.session.query(m.Tournaments).get(trmnt.id)

                    users = get_all_players_from_trmnt(eww)

                    print('Update tournament status to "waiting_results", id:',
                          trmnt.id)
                    # buyin = m.Buy_ins.get_latest(user_id=user.id, tournament_id=trmnt.id )

        ###############################################################################
        # Send fcm to all players when trmnt opens

        _5mins_ago = datetime.utcnow() - timedelta(minutes=5)
        _5mins_ahead = datetime.utcnow() + timedelta(minutes=5)

        trmnts = db.session.query(m.Tournaments) \
            .filter( m.Tournaments.start_at < _5mins_ahead) \
            .filter( m.Tournaments.start_at > _5mins_ago )

        if trmnts is not None:
            for trmnt in trmnts:
                users = get_all_players_from_trmnt(trmnt)
                for user in users:
                    # buyin = m.Buy_ins.get_latest(user_id=user.id, tournament_id=trmnt.id )
                    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':
                            'Event Started: ' + trmnt.name,
                            '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>
                            '''
                        })

                    my_buyin = db.session.query(m.Buy_ins) \
                        .filter( Buy_ins.flight.has( tournament_id=trmnt.id )) \
                        .filter( m.Buy_ins.user_id==user.id ) \
                        .order_by( m.Buy_ins.id.desc() ).first()

                    print('check if this correct', user, user.id,
                          user.event_update)

                    if user.event_update is True:

                        # start_time = est.strftime("%b. %d, %a. %I:%M %p")

                        send_fcm(user_id=user.id,
                                 title="Event Started",
                                 body=trmnt.name + '\nopened just now',
                                 data={
                                     'id': trmnt.id,
                                     'alert': trmnt.name + '\nopened just now',
                                     'buyin_id': my_buyin.id,
                                     'type': 'event',
                                     'initialPath': 'Event Listings',
                                     'finalPath': 'Event Lobby'
                                 })

        ###############################################################################
        # Delete buy-ins created before close time with status 'pending'

        buyins = db.session.query(m.Buy_ins) \
            .filter_by( status = 'pending' ) \
            .filter( m.Buy_ins.flight.has( m.Flights.start_at < close_time ))

        for buyin in buyins:
            print('Deleting buy-in', buyin.id)
            db.session.delete(buyin)

        db.session.commit()

        return 'Tournaments updated are on time'
import os
import utils
import models as m
from sqlalchemy import create_engine, func, asc, or_
from sqlalchemy.orm import sessionmaker
from datetime import datetime, timedelta

engine = create_engine(os.environ.get('DATABASE_URL'))
Session = sessionmaker(bind=engine)
session = Session()

# Set tournaments to waiting for results, cancel all pending swaps
close_time = utils.designated_trmnt_close_time()
trmnts = session.query(m.Tournaments) \
    .filter( m.Tournaments.status == 'open') \
    .filter( m.Tournaments.flights.any(
        m.Flights.start_at < close_time
    ))

if trmnts is not None:
    for trmnt in trmnts:
        latest_flight = trmnt.flights.pop()
        if latest_flight.start_at < close_time:

            # This tournament is over: change status and clean swaps
            print('update tournament status to "waiting_results", id:',
                  trmnt.id)
            trmnt.status = 'waiting_results'
            swaps = session.query(m.Swaps) \
                .filter_by( tournament_id = trmnt.id ) \
                .filter( or_(