Esempio n. 1
0
def fakeLiveEvents(sport):
    events = []
    event1 = Event("id-1-2747587", "real madrid", "away team", "1", "0",
                   "link",
                   Header("La liga", "link", "stage", "stage_link", "date"))
    event2 = Event(
        "id-2-276543", "real madrid2", "away team2", "2", "0", "link",
        Header("La liga2", "link2", "stage2", "stage_link2", "date"))
    events.append(event1)
    events.append(event2)
    return jsonify([x.to_dict() for x in events])
def getAllEvent():
    for event in getEventsInformations():
        eventName=Utils.encode(event['name']['text'])
        eventDescription=Utils.encode(event['description']['text'])
        startEventTime=Utils.encode(event['start']['local'])
        endEventTime=Utils.encode(event['end']['local'])
        eventCategoryId=event['category_id']
        if eventCategoryId is not None:
            event=Event(eventName,eventDescription,startEventTime,endEventTime,getCategory(eventCategoryId),"Turkey")
        else:
            event=Event(eventName,eventDescription,startEventTime,endEventTime,"Genel","Turkey")
        eventList.append(event)
Esempio n. 3
0
def createEvent(date, name, location, duff_value, active=True):
    event = Event(date=date,
                  name=name,
                  location=location,
                  duff_value=duff_value,
                  active=active)
    db.session.add(event)
    dummy_passport = Passport(user_id=1, event=event)
    db.session.add(dummy_passport)
    db.session.commit()
    event.dummy_passport = dummy_passport.id
    db.session.commit()
Esempio n. 4
0
def machine_post_order_completed(event_key):
    """
    header Authorization: Token Authentication_machine_token
    """
    if g.get('current_machine', None) is None:
        return json_error('No machine found might have been a user token',
                          status=401)
    if g.current_machine.selected_order is None:
        return json_error('Machine has no order to finsih',
                          'Machine has no order to finish', 403)
    order = Order.find_by_id(g.current_machine.selected_order)
    if order is None:
        return json_error('Order not found', 'Order not found', 404)
    if order.machine_id is None:
        return json_error('Order does not have machine id, it should have one',
                          'Order does not have machine_id', 403)
    event = Event.find(event_key)
    if event is None:
        return json_error('Event not found', 'Event not found', 404)
    try:
        event.machine_finished_order(order)
    except Order_Process_Exception:
        return json_error(
            'Order: ' + str(order._id) +
            ' was not found in the new_orders of event: ' + str(event._id),
            'Order was not found in event new order', 404)
    g.current_machine.set_selected_order_done()
    order.set_done()
    return json_response(json.dumps(order.to_dict()), status=200)
Esempio n. 5
0
def machine_get_order(event_key, order_key):
    """
    header Authorization: Token Authentication_machine_token
    """
    if g.get('current_machine', None) is None:
        return json_error('No machine found might have been a user token',
                          status=401)
    if g.current_machine.selected_order is not None:
        return json_error('Machine has not finished its selected order',
                          'Machine not finished selected order', 403)
    order = Order.find(order_key)
    if order is None:
        return json_error('Order not found', 'Order not found', 404)
    if order.machine_id is not None:
        return json_error('Order already has an associated machine',
                          'Order already has an associated machine', 403)
    event = Event.find(event_key)
    if event is None:
        return json_error('Event not found', 'Event not found', 404)
    try:
        event.machine_get_order(order)
    except Order_Process_Exception:
        return json_error(
            'Order: ' + str(order._id) +
            ' was not found in the new_orders of event: ' + str(event._id),
            'Order was not found in event new order', 404)
    g.current_machine.set_selected_order(order)
    order.assigne_machine(g.current_machine._id)
    return json_response(json.dumps(order.to_dict()), status=200)
Esempio n. 6
0
def post_order():
    """
    header Authorization: Token Authentication_user_token
    {
      "event_key": "y37jsnks",
      "drinks": [{
          "mixer_type": "coke",
          "alcohol_type": "rhum",
          "double": True
      }],
    }
    """
    if request.content_type != JSON_MIME_TYPE:
        return json_error('Invalid Content Type', 'Invalid Content Type', 400)
    if g.get('current_user', None) is None:
        return json_error('No user found might have been a machine token',
                          status=401)
    data = request.json
    event = Event.find(data.get('event_key'))
    if event is None:
        return json_error('Event not found', 'Event not found', 404)
    drinks = [
        Drink(drink.get('mixer_type'), drink.get('alcohol_type'),
              drink.get('double')) for drink in data.get('drinks')
    ]
    # total_price = Order.get_price_from_drinks(drinks)
    # TODO process transation, for now assume the trasaction always passes
    new_order = Order(g.current_user._id, drinks, payed=True)
    new_order.create()
    event.add_new_order(new_order)
    g.current_user.add_order(new_order)
    return json_response(json.dumps(new_order.to_dict()), status=200)
Esempio n. 7
0
def attend(event_id):
    schema = EventSchema()
    event = Event.get(id=event_id)
    event.attended_by.add(g.current_user.id)
    db.commit()

    return schema.dumps(event)
Esempio n. 8
0
    def post(self):
        json_data = request.get_json(force=True)
        if not json_data:
            return {'message': 'No input data provided'}, 400

        # Validate and deserialize input
        data, errors = event_schema.load(json_data)
        if errors:
            return errors, 422

        # Checking data duplicate
        # event = Event.query.filter_by(name=data['name']).first()
        # if category:
        # 	return {'message': 'Event already exists'}, 400

        event = Event(user_id=json_data['user_id'],
                      description=json_data['description'],
                      longitude=json_data['longitude'],
                      latitude=json_data['latitude'],
                      location=json_data['location'],
                      image=json_data['image'],
                      created_at=now.strftime("%Y-%m-%d %H:%M:%S"),
                      updated_at=now.strftime("%Y-%m-%d %H:%M:%S"),
                      deleted_at=None)

        db.session.add(event)
        db.session.commit()

        result = event_schema.dump(event).data

        return {"status": 'success', 'data': result}, 201
Esempio n. 9
0
def getEvents(user):
		query = "WHERE dateStart >= :1 "
		# if not user.verified:
			# query+="AND verified = TRUE "
		#query += "Limit " +(str)(limit*pageNum)+", " + (str)(limit)
		events = Event.gql(query, datetime.now()-timedelta(hours=2)).run()
		events = sorted(events, key=lambda event: event.dateStart) 
		return events
Esempio n. 10
0
def show(event_id):
    schema = EventSchema()
    event = Event.get(id=event_id)

    if not event:
        abort(404)

    return schema.dumps(event)
Esempio n. 11
0
def get_field_op_links(event):
    events = json.loads(event)
    urls = []
    for item in events:
        event = Event(item)
        if event.eventTypeId == "fieldOperation":
            urls.append(event.targetResource)

    return urls
Esempio n. 12
0
def delete(event_id):
    event = Event.get(id=event_id)

    if not event:
        abort(404)

    event.delete()
    db.commit()

    return '', 204
Esempio n. 13
0
def getDetailOfEvent(url, eventName, eventSubCategorie):
    detailUrl = requests.get(url)
    detail = BeautifulSoup(detailUrl.text, 'html.parser')
    eventDescription = detail.find('div', attrs={'class': 'readmore'}).text
    eventStartTime = detail.find('p', attrs={'class', 'has-text-grey'}).text
    eventLocation = detail.find('p', attrs={
        'class': 'has-text-grey mt-05'
    }).text
    event = Event(eventName, eventDescription, eventStartTime, None,
                  eventSubCategorie, eventLocation)
    eventList.append(event)
Esempio n. 14
0
def create():
    schema = EventSchema()
    try:
        data = schema.load(request.get_json())
        event = Event(**data, created_by=g.current_user)
        db.commit()
    except ValidationError as err:
        return jsonify({
            'message': 'Validation failed',
            'errors': err.messages
        }), 422
    return schema.dumps(event), 201
Esempio n. 15
0
def post_event():
    """
    header Authorization: Token Authentication_user_token
    {
      "name":"your moms a hoe",
      "location":"ur moms house"
    }
    """
    if g.get('current_user', None) is None:
        return json_error('No user found might have been a machine token',
                          status=401)
    if g.current_user.admin is False:
        return json_error('User ' + g.current_user._id +
                          ' cannot perform this action',
                          status=401)
    if request.content_type != JSON_MIME_TYPE:
        return json_error('Invalid Content Type', 'Invalid Content Type', 400)
    data = request.json
    new_event = Event(name=data['name'], location=data['location'])
    new_event.create()
    return json_response(json.dumps(new_event.to_dict()), status=201)
Esempio n. 16
0
def post_machine_to_event(event_key):
    """
    header Authorization: Token Authentication_machine_token
    /api/v1/user/event/<string:event_key>
    """
    if g.get('current_machine', None) is None:
        return json_error('No machine found might have been a user token',
                          status=401)
    event = Event.find(event_key)
    if event is None:
        return json_error('Event not found', 'Event not found', 404)
    event.add_machine(g.current_machine)
    return json_response(json.dumps(event.to_dict()), status=200)
Esempio n. 17
0
 def set_event_details(self, name, date, time, add, descr, own):
     event1 = Event()
     event1.name = name
     event1.date = date
     event1.time = time
     event1.address = add
     event1.description = descr
     event1.owner = own
     self.ev_list.append(event1)
     print self.ev_list
     return self.ev_list
Esempio n. 18
0
	def post(self):
		user = AppUser.getUser()
		eventName=getString("name", self)
		loc=getString("location", self)
		date = getDate("date", self)
		start=getDateTime("start",date, self)
		event = Event(creator=user,name=eventName, location=loc, dateStart=start)
		event.dateEnd=getDateTime("end",date, self)
		event.description=getString("description", self)
		event.host=getString("host", self)
		event.attending=0
		event.put()

		if user.verified:
			event.verify();
			# Auto-verified if the user is, and thanks the user.
			self.redirect('/?' + urllib.urlencode({'message':'''Thanks, yum!'''}))
		self.redirect('/?' + urllib.urlencode({'message':'''Event Created! You'll need to wait for someone to verify it.'''}))
		# redirect message if the user isn't verified.
Esempio n. 19
0
def json_to_event(data):
    try:
        return Event(name=data['name'],
                     description=data['description'],
                     category=data['category'],
                     location=data['location'],
                     start=data['start'],
                     end=data['end'],
                     volunteers=data['volunteers'],
                     points=data['points'],
                     organization_id=data['organization_id'],
                     available=True)
    except Exception as e:
        print(getattr(e, 'message', str(e)))
        raise e
Esempio n. 20
0
def update(event_id):
    schema = EventSchema()
    event = Event.get(id=event_id)
    if not event:
        return jsonify({'message': 'Event not found'}), 404
    if not event.user.id == g.current_user.id:
        return jsonify({'message': 'User not authorized'}), 404
    try:
        data = schema.load(request.get_json())
        event.set(**data)
        db.commit()
    except ValidationError as err:
        return jsonify({
            'message': 'Validation failed',
            'errors': err.messages
        }), 422

    return schema.dumps(event)
Esempio n. 21
0
def update(event_id):
    schema = EventSchema()
    event = Event.get(id=event_id)

    if not event:
        abort(404)

    try:
        data = schema.load(request.get_json())
        event.set(**data)
        db.commit()
    except ValidationError as err:
        return jsonify({
            'message': 'Validation failed',
            'errors': err.messages
        }), 422

    return schema.dumps(event)
Esempio n. 22
0
def add_new_event():
    new_event_data = request.json
    for field in ["name", "paidBy", "amount", "users"]:
        if field not in new_event_data:
            return f"Missing field {field} in Request body", 400
    try:
        new_event = Event(
            name=new_event_data.get("name"),
            paid_by=new_event_data.get("paidBy"),
            amount=new_event_data.get("amount"),
            users=new_event_data.get("users"),
        )
        return event_service.new_event(new_event)

    except EventExists:
        return "An event already exists with this name", 409

    except Exception as e:
        return str(e), 500
Esempio n. 23
0
def getAllEvent():
    for event in listOfEvents:
        eventStartDateDay = event.find('time', attrs={
            'class': 'variant-day'
        }).text
        eventInformations = event.findAll(
            'div', attrs={'class': 'table-cell description'})
        for eventSingle in eventInformations:
            eventStartDateTime = eventSingle.find('time').text
            eventTime = eventStartDateDay + " " + eventStartDateTime
            eventName = eventSingle.find('h6').text
            eventLocation = eventSingle.find('p').text
            eventSubCategorie = "Arts "
            eventDetailPage = eventSingle.find('a')['href']
            eventDescription = getDetailOfEvent(
                Utils.getWithOutBaseUrlEventNumber('/Basket/Index/',
                                                   eventDetailPage))
            event = Event(eventName, eventDescription, eventTime, None,
                          eventSubCategorie, eventLocation)
            eventList.append(event)
    def get_international_competition_events(self,
                                             international_competition_link):
        self.driver.get(international_competition_link)

        headers = self.driver.find_elements_by_css_selector(
            css_selector="div.row.row-tall")
        contents = self.driver.find_elements_by_css_selector(
            css_selector="div.row-gray.even")
        live_events = []
        for header, content in zip(headers, contents):
            try:
                country = header.find_element_by_tag_name(name="strong").text
                league = header.find_element_by_css_selector(
                    css_selector="a:last-child").text

                date = header.find_element_by_class_name("right").text
                min = content.find_element_by_class_name(name="min").text

                team_names = content.find_elements_by_class_name("name")
                home_team = team_names[0].text
                away_team = team_names[1].text

                home_team_goals = content.find_element_by_class_name(
                    name="hom").text
                away_team_goals = content.find_element_by_class_name(
                    name="awy").text

                event_id = content.get_attribute("data-id")
                score_link = content.find_element_by_class_name(
                    "scorelink").get_attribute("href")

                event = Event(event_id, home_team, away_team, home_team_goals,
                              away_team_goals, score_link)
                live_events.append(event)
            except Exception:
                continue

        return live_events
Esempio n. 25
0
from models.Venue import Venue
from models.User import User, UserSchema

db.drop_all_tables(with_all_data=True)
db.create_tables()

with db_session():
    schema = UserSchema()
    current_user = User(
        username='******',
        email='*****@*****.**',
        password_hash=schema.generate_hash('pass'),
    )
    gen_pub1 = Venue(name='Generic pub', )
    gen_pub2 = Venue(name='Generic pub2', )
    gen_pub3 = Venue(name='Generic pub3', )

    Event(date=datetime.date(2019, 6, 14).strftime("%d/%m/%Y"),
          start='17:00',
          end='22:00',
          venue=gen_pub1,
          created_by=current_user)

    Event(date=datetime.date(2019, 7, 12).strftime("%d/%m/%Y"),
          start='15:00',
          end='18:00',
          venue=gen_pub1,
          created_by=current_user)

    db.commit()
    def get_competition_events(self, url):
        self.driver.get(url)
        rows = self.driver.find_elements_by_css_selector(
            "div[data-type=\"container\"]>div")
        sport = url.split("/")[3]
        events = []

        current_header = None
        for row in rows:
            data_type = row.get_attribute("data-type")
            if data_type == "stg":
                # header
                try:
                    left = row.find_element_by_class_name("left")
                    right = row.find_element_by_class_name("right")

                    links = left.find_elements_by_tag_name("a")
                    current_header = Header(links[0].text,
                                            links[0].get_attribute("href"),
                                            links[1].text,
                                            links[1].get_attribute("href"),
                                            right.text)
                except Exception as e:
                    # same competition with different date
                    right = row.find_element_by_class_name("right")
                    current_header.set_date(right.text)
            elif data_type == "evt":
                # event
                team_names = row.find_elements_by_class_name(
                    self.name_selector[sport] + "ply")
                home_team = team_names[0].text
                away_team = team_names[1].text

                minute = row.find_element_by_css_selector(
                    self.minute_selector[sport]).text

                if sport != "football" and sport != "soccer":
                    scores = row.find_elements_by_class_name(
                        self.score_selector[sport])
                    home_team_goals = scores[0].text
                    away_team_goals = scores[1].text
                else:
                    home_team_goals = row.find_element_by_class_name(
                        name="hom").text
                    away_team_goals = row.find_element_by_class_name(
                        name="awy").text

                event_id = row.get_attribute("data-id")
                try:
                    score_link = row.find_element_by_class_name(
                        "scorelink").get_attribute("href")
                except Exception as e:
                    score_link = ""
                event = Event(event_id, home_team, away_team, home_team_goals,
                              away_team_goals, score_link,
                              copy.deepcopy(current_header), minute)
                events.append(event)
            else:
                print("Div inside container with unknown data-type:{}".format(
                    data_type))

        return events
Esempio n. 27
0
def index():
    schema = EventSchema(many=True)
    events = Event.select()
    return schema.dumps(events)
Esempio n. 28
0
    bowles = Artist(name='Sasha Bowles')
    martelli = Artist(name='Gibson/Martelli')
    pizzani = Artist(name='Lucia Pizzani')
    six = Artist(name='Kato Six')
    morris = Artist(name='Sarah Morris')
    wood = Artist(name='Juliet Wood')
    henri = Artist(name='Adrian Henri')
    rako = Artist(name='Michael Rakowitz')

    Event(
        name='Van Gogh in Britain',
        start_date=datetime.date(2019, 3, 27).strftime("%d/%m/%Y"),
        end_date=datetime.date(2019, 11, 8).strftime("%d/%m/%Y"),
        venue='Tate Britain',
        area='Central',
        keywords=[post_impressionism, dutch, painting],
        entry_fee=22,
        concession_fee=20,
        user=gabe,
        image=
        "https://www.tate.org.uk/sites/default/files/styles/width-600/public/van_gogh_self_portrait.jpg",
        artists=van_gogh)

    Event(
        name='Block Universe 2019',
        start_date=datetime.date(2019, 5, 25).strftime("%d/%m/%Y"),
        end_date=datetime.date(2019, 6, 2).strftime("%d/%m/%Y"),
        venue='Somerset House',
        area='Central',
        keywords=[performance_art],
        entry_fee=22,
Esempio n. 29
0
        username='******',
        image='https://i.imgur.com/w7qm5UP.png',
        email='*****@*****.**',
        password_hash=schema.generate_hash('pineapples')
    )


    five_a_side = Format(name='5-a-side')
    seven_a_side = Format(name='7-a-side')


    Event(
        name='Planet Futsal',
        image='https://i.imgur.com/jWd3gQb.jpg',
        venue='38 IBM Haruna St, Utako, Abuja',
        user=sensei,
        format=five_a_side,
        latitude=9.062720,
        longitude=7.439199
    )

    Event(
        name='City Bridge Sportsplex',
        image='http://mydonate.bt.com/images/events/B263704_1521542545510.jpg',
        venue='Citybridge Sportsplex, Abuja Nigeria',
        user=sensei,
        format=seven_a_side,
        latitude=9.077825,
        longitude=7.476195
    )
Esempio n. 30
0
def getEvents(page_data):
    json_data = json.loads(page_data)
    all_plays = json_data['liveData']['plays']['allPlays']
    game_id = json_data['gamePk']

    event_ids = [event['about']['eventId'] for event in all_plays]
    db_events = Event.query.filter_by(game_id=game_id).filter(
        Event.id.in_(event_ids))
    for event in all_plays:
        db_hit = False
        for ev in db_events:
            if ev.game_id == game_id and ev.event_id == event['about'][
                    'eventId']:
                db_hit = True
        if db_hit:
            new_event = event
        else:
            if 'x' in event['coordinates'].keys():
                x_coord = event['coordinates']['x']
                y_coord = event['coordinates']['y']
            else:
                x_coord = None
                y_coord = None
            if 'team' in event.keys():
                team_id = event['team']['id']
            else:
                team_id = None
            params = {
                'game_id':
                game_id,
                'event':
                event['result']['event'],
                'event_type_id':
                event['result']['eventTypeId'],
                'event_code':
                event['result']['eventCode'],
                'event_idx':
                event['about']['eventIdx'],
                'event_id':
                event['about']['eventId'],
                'period':
                event['about']['period'],
                'period_type':
                event['about']['periodType'],
                'period_time':
                event['about']['periodTime'],
                'date_time':
                datetime.strptime(event['about']['dateTime'],
                                  '%Y-%m-%dT%H:%M:%SZ'),
                'home_goals':
                event['about']['goals']['home'],
                'away_goals':
                event['about']['goals']['away'],
                'x_coord':
                x_coord,
                'y_coord':
                y_coord,
                'team_id':
                team_id
            }
            new_event = Event(params)
            db.session.add(new_event)
            db.session.commit(
            )  #TODO: Fix inserting the wrong event_id into playerevents

            for player in event['players']:
                params = {
                    'event_id': new_event.id,
                    'player_id': player['player']['id'],
                    'player_type': player['playerType']
                }
                new_player_event = PlayerEvent(params)
                db.session.add(new_player_event)

    db.session.commit()