def create_event(): """ Create an event and return the created event for the user """ valid = verify_session() if not valid: return json.dumps({'success': False, 'error': 'Invalid session_token'}) success, session_token = extract_token(request) user = users_dao.get_user_by_session_token(session_token) if user is not None: post_body = json.loads(request.data) event = Event( title=post_body.get('title'), description=post_body.get('detail'), date=datetime.strptime(post_body.get('date'), '%Y-%m-%d').date(), # startTime=datetime.strptime(post_body.get('startTime'), '%b %d %Y %I:%M%p'), # endTime=datetime.strptime(post_body.get('endTime'), '%b %d %Y %I:%M%p'), location=post_body.get('location'), # reminder=datetime.strptime(post_body.get('reminder'), '%b %d %Y %I:%M%p'), priority=post_body.get('importance'), user_id=user.id) user.events.append(event) db.session.add(event) db.session.commit() return json.dumps({ 'success': True, 'data': event.serialize() }, default=to_serializable), 201 return json.dumps({'success': False, 'error': 'User not found!'}), 404
def create_event(user_id, club_id): club = Club.query.filter_by(id=club_id).first() user = User.query.filter_by(id=user_id).first() if club is None: return json.dumps({'success': False, 'error': 'Club not found'}), 404 if user is None: return json.dumps({'success': False, 'error': 'User not found'}), 404 content = json.loads(request.data) event = Event( club_id=club_id, description=content.get('description'), start_datetime=content.get('start_datetime'), end_datetime=content.get('end_datetime'), ) for users in club.officers: if users.id == user.id: # event = Event( # club_id=club_id, # description=content.get('description'), # start_datetime=content.get('start_datetime'), # end_datetime=content.get('end_datetime'), # ) db.session.add(event) db.session.commit() return json.dumps({ 'success': True, 'data': event.extended_serialize() }), 201 return json.dumps({'success': False, 'error': 'User not authorized.'}), 404
def create_event(habit_id): habit = Habit.query.filter_by(id=habit_id).first() if not habit: return json.dumps({'success': False, 'error': 'Invalid habit id'}), 404 post_body = json.loads(request.data) category = post_body.get('category') skip_note = post_body.get('skip_note', '') today = datetime.now().strftime(FORMAT) date = post_body.get('date', today) try: event = Event(category=category, date=date, habit_id=habit_id, skip_note=skip_note) if category == 'skip' and date == today: habit.set_done(True) db.session.add(event) db.session.commit() except: return json.dumps({ 'success': False, 'error': 'Error in creating event' }), 500 return json.dumps({'success': True, 'data': event.serialize()}), 201
def post_fb_events(): post_body = json.loads(request.data) if helpers.has_food(post_body.get('description')): name = post_body.get('name') location = post_body.get('place')['name'] starttime = post_body.get('start_time') start = re.split(r'T', starttime) datetime = start[0] + ' ' + re.match(r'\d{2}.\d{2}', start[1]).group() content = post_body.get('description') longitude = str(post_body.get('place')['location']['longitude']) latitude = str(post_body.get('place')['location']['latitude']) event = Event(name=name, location=location, datetime=datetime, content=content, longitude=longitude, latitude=latitude) db.session.add(event) db.session.commit() return json.dumps({'success': True, 'data': event.serialize()}) else: return json.dumps({ 'success': False, 'error': 'No food offered in event!' }), 406
def create_event(user_netid): creator = User.query.filter_by(netid=user_netid).first() if creator is None: return failure_response("User not found!") body = json.loads(request.data) title = body.get("title") location = body.get("location") time = body.get("time") description = body.get("description") publicity = body.get("publicity") tags = body.get("tag") if title is None or location is None or time is None or description is None: return failure_response("Invalid field!") new_event = Event(title=title, location=location, time=time, description=description, publicity=publicity) db.session.add(new_event) new_event.creator.append(creator) creator.event_created.append(new_event) if tags is not None: for i in tags: the_tag = Tag.query.filter_by(title=i).first() if the_tag is None: return failure_response("Invalid tag field!") new_event.tag.append(the_tag) the_tag.event.append(new_event) db.session.commit() return success_response(new_event.serialize(), 201)
def create_event(name, description, location, date): new_event = Event(name=name, description=description, location=location, date=date) db.session.add(new_event) db.session.commit() return new_event.serialize()
def create_event(name, club_id, time, description, link, industry, location, registered_users): event = Event(name=name, club_id=club_id, time=time, description=description, link=link, industry=industry, location=location, registered_users=registered_users) db.session.add(event) db.session.commit() return event.serialize()
def create_event(): post_body = json.loads(request.data) event = Event( title=post_body.get('title'), month=post_body.get('month'), day=post_body.get('day'), year=post_body.get('year'), time=post_body.get('time'), descr=post_body.get('descr'), location=post_body.get('location'), category=post_body.get('category'), image_url=post_body.get('image_url'), ) db.session.add(event) db.session.commit() return json.dumps({'success': True, 'data': event.serialize()}), 201
def create_event(title: str, organizer: int, start_date: 'datetime', end_date: 'datetime', servings: int, address: str, latitude, longitude, details: str = None, location: str = None, image: bool = False) -> EventData: with session_scope() as session: event = Event(title=title, organizer=organizer, start_date=start_date, end_date=end_date, details=details, servings=servings, address=address, location=location, latitude=latitude, longitude=longitude) if event is None: return None session.add(event) session.commit() session.refresh(event) if image: event_image = EventImage(event_id=event.id) session.add(event_image) return EventData(event, event_image.url) return EventData(event)
def scrape_event(cluster, event_dict, session, api, result): event = Event(cluster_id=event_dict["cluster_id"], timestamp=to_time(event_dict["timestamp"]), type=event_dict["type"], details=event_dict["details"]) session.merge(event) result.num_events += 1
def do_GET(self): with db_session: events = Event.select() response = "" for event in events: response = response + "{} {} {} {}".format( event.event, event.repo, event.branch, event.time) self._set_response() self.wfile.write(bytes(response, "utf-8"))
def create_event(list_id): success, user = check_session() if not success: return user public_list = PublicList.query.filter_by(id=list_id).first() if public_list is None: return failure_response('list not found!') body = json.loads(request.data.decode()) main_title = body.get('main_title') sub_title = body.get('sub_title') in_progress = body.get('in_progress') if main_title is None or sub_title is None or in_progress is None: return failure_response("missing field(s)!") new_event = Event(main_title=main_title, sub_title=sub_title, in_progress=in_progress, public_list_id = list_id) public_list.events.append(new_event) db.session.add(new_event) db.session.commit() return success_response(new_event.serialize(), 201)
def post_events(): post_body = json.loads(request.data) for data in post_body.get('data'): if helpers.has_food(data.get('content')): name = data.get('name') location = data.get('location') datetime = data.get('datetime') content = data.get('content') longitude = data.get('longitude') latitude = data.get('latitude') event = Event(name=name, location=location, datetime=datetime, content=content, longitude=longitude, latitude=latitude) db.session.add(event) db.session.commit() return json.dumps({'success': True, 'data': event.serialize()})
def do_POST(self): if self.path.startswith('/handler'): event = self.headers.get('X-GitHub-Event') ts = time.time() content_len = int(self.headers.get('Content-Length')) data = json.loads(self.rfile.read(content_len)) with db_session: Event(event=event, repo=data['repository']['full_name'], branch=data['ref']) self._set_response() self.wfile.write(bytes("ok", "utf-8"))
def get_active_by_user(user_id: int) -> List[EventViewData]: with session_scope() as session: # events = Event.get_all_active_by_user(session, user_id) user = User.get_by_id(session, user_id) events = Event.get_all_active(session) user_accepted = {event.id for event in user.accepted_events} user_recommended = {event.id for event in user.recommended_events} views = [ EventViewData(event, event.id in user_accepted, event.id in user_recommended) for event in events ] return views
def mark_done(habit_id): habit = Habit.query.filter_by(id=habit_id).first() if not habit: return json.dumps({'success': False, 'error': 'Habit not found'}), 404 habit.set_done(True) event = Event(category='done', date=datetime.now().strftime(FORMAT), habit_id=habit_id, skip_note='') db.session.add(event) db.session.commit() return json.dumps({'success': True, 'data': habit.serialize()}), 200
def create_dinner_event(user_id): user = User.query.filter_by(id=user_id).first() if not user: return json.dumps({'success': False, 'error': 'User not found!'}), 404 post_body = json.loads(request.data) name = post_body.get('name', '') time = post_body.get('time', '') location = post_body.get('location', '') event = Event( name=name, time=time, location=location, ) event.host.append(user) db.session.add(event) user.events_hosting.append(event) db.session.commit() return json.dumps({'success': True, 'data': event.serialize()}), 200
def create_event(user_id, trip_id): user = User.query.filter_by(id=user_id).first() if not user: return json.dumps({'success': False, 'error': 'User not found!'}), 404 trip = Trip.query.filter_by(id=trip_id).first() if not trip: return json.dumps({'success': False, 'error': 'Trip not found!'}), 404 if ((trip in user.trips) == False): return json.dumps({'success': False, 'error': 'Trip not found!'}), 404 post_body = json.loads(request.data) name = post_body.get('name', '') date = post_body.get('date', '') location = post_body.get('location', '') description = post_body.get('description', '') event = Event(name=name, date=date, location=location, description=description, trip_id=trip_id) trip.events.append(event) db.session.add(event) db.session.commit() return json.dumps({'success': True, 'data': event.serialize()}), 200
def post_test_events(): post_body = json.loads(request.data) print(post_body.get('content')) if helpers.has_food(post_body.get('content')): name = post_body.get('name') location = post_body.get('location') datetime = post_body.get('datetime') content = post_body.get('content') longitude = post_body.get('longitude') latitude = post_body.get('latitude') event = Event(name=name, location=location, datetime=datetime, content=content, longitude=longitude, latitude=latitude) db.session.add(event) db.session.commit() return json.dumps({'success': True, 'data': event.serialize()}) else: return json.dumps({ 'success': False, 'error': 'No food offered in event!' }), 406
def addEvent(did): if not Day.query.filter_by(id=did).first(): return json.dumps({ 'success': False, 'data': 'No such day exists' }), 404 post_body = json.loads(request.data) name = post_body['name'] location = post_body['location'] time = post_body['time'] directions = post_body['directions'] note = post_body['note'] event = Event(name=name, location=location, time=time, directions=directions, note=note, day_id=did) db.session.add(event) db.session.commit() return json.dumps({'success': True, 'data': event.serialize()})
def parse_topics(message: types.Message): topics = [x.strip() for x in message.get_args().split(',') if x.strip()] cmd = message.get_command() user = message.from_user chat = message.chat hub2_log.info( "%s (%s %s) (%s %s) %s", cmd, user.id, user.full_name, chat.id, chat.type, topics, ) event = Event(user, chat) # hub2_log.debug(event) return event, topics
def create_event(location, organiser_id, event_name): # returns the code session = Session() event = Event() if session.query(func.max(Event.eid)).first()[0] != None: event.eid = session.query(func.max(Event.eid)).first()[0] + 1 else: event_id = 1 code = random.randint(0, 1000000) while session.query(Event.code).filter_by(code=code).first() != None: code = random.randint(0, 1000000) event.code = code event.location = location event.organiser_id = organiser_id event.event_name = event_name event.participants = {} session.add(event) session.commit() session.close() return code
def _event_recommendation(event: Union[Event, 'EventData'], with_params: Dict[str, Any] = None) -> List[User]: recommendations = [] with session_scope() as session: users = list(User.get_all(session)) event = Event.get_by_id(session, event.id) capacity = len(users) if with_params is not None and 'avg_prob' in with_params: avprob = float(with_params['avg_prob']) capacity = event.servings / avprob if avprob > 0 else len(users) shuffle(users) pushed = 0 for user in users: if should_recommend(user, event) and pushed <= capacity: user_rec = UserRecommendedEvent(event.id, user.id) session.add(user_rec) session.expunge(user) recommendations.append(user) pushed += 1 elif pushed > capacity: break return recommendations
def create_event(): post_body = json.loads(request.data) v = validate_json(post_body, ['username', 'start_date', 'end_date']) if v is not None: return v user = User.query.filter_by(username=post_body.get('username')).first() v = validate_objects([user]) if v is not None: return v event = Event( event_name=post_body.get('event_name', ''), start_date=post_body.get('start_date'), end_date=post_body.get('end_date'), location=post_body.get('location', ''), is_private=post_body.get('is_private', False), ) db.session.add(event) db.session.flush() user_to_event = UserToEvent(user_id=user.id, event_id=event.id) db.session.add(user_to_event) db.session.commit() return json.dumps({'success': True, 'data': event.serialize()}), 200
async def on_message(ws, message: aiohttp.WSMessage): """ { "message": { "data": "hello", "extended_data": [], "captions": [], "type": "PLAIN" }, "topic": "global", "type": "MESSAGE" } """ from main import bot hub_log.info(message) msg = message.json() type = msg['type'] if type == 'MESSAGE': topic = msg['topic'] if topic: # ignore topic global if topic == 'global': return # render message innter_type = msg['message']['type'] innter_data = msg['message']['data'] extended_data = msg['message']['extended_data'] or [] caption = msg['message']['caption'] preview = msg['message']['preview'] group = False body = '' parse_mode = None disable_preview = not preview disable_notification = False # parse message type if innter_type == MESSAGE_TYPE.PLAIN.name: body = innter_data elif innter_type == MESSAGE_TYPE.MARKDOWN.name: body = innter_data parse_mode = "Markdown" elif innter_type == MESSAGE_TYPE.HTML.name: body = innter_data parse_mode = "HTML" elif innter_type == MESSAGE_TYPE.JSON.name: body = innter_data elif is_media(innter_type) or extended_data: body = [{ 'type': innter_type, 'data': innter_data, 'caption': caption }] + extended_data # type: list print(body) # check: all types must be photo or video if not all(is_media(x['type']) for x in body): hub_log.warning(f"not all types are media") return else: hub_log.warning(f"unprocessed type {innter_type}") if body: all_topics = DB.get_key_topics_map() for key, topics in all_topics.items(): user_id, username, chat_id = Event.parse_key(key) if topic in topics: try: if is_media(innter_type) or extended_data: # string in hub message maybe a base64 encoded bytes # or http url of a image media_group = [{ 'type': x['type'].lower(), 'media': x['data'] if x['data'].startswith('http') else BytesIO(base64.b64decode(x['data'])), 'caption': x['caption'], } for x in body] if len(media_group) > 1: await bot.send_media_group( chat_id, media_group, disable_notification= disable_notification, ) else: if user_id != chat_id: caption_default = f"# {topic} by {username}" else: caption_default = f'# {topic}' if caption: caption_default = ( f'{caption.rstrip()}\n\n{caption_default}' ) x = media_group[0] if x['type'] == 'photo': await bot.send_photo( chat_id, x['media'], caption=caption_default, parse_mode=parse_mode, disable_notification= disable_notification, ) else: await bot.send_video( chat_id, x['media'], caption=caption_default, parse_mode=parse_mode, disable_notification= disable_notification, ) else: body_with_topic = f"{body.rstrip()}\n\n# {topic}" # reply in group or private chat if user_id != chat_id: real_body = ( f"{body_with_topic} by {username}") disable_notification = True else: real_body = body_with_topic await bot.send_message( chat_id, real_body, parse_mode=parse_mode, disable_web_page_preview=disable_preview, disable_notification=disable_notification, ) except Exception as e: traceback.print_exc()
def __init__(self,**kw): self.EventVer = 2 self.CashCardSN = config.cash_card_sn self.CashASPPSN = ASPP10(config.cash_card_aspp) Event.__init__(self,**kw)
def __init__(self, card = None,value = None,**kw): if value != None: self.TransactionType = 3 if value < 0 else 0 self.Value = abs(value) if card: fill_event_from_card(self,card) Event.__init__(self,**kw)
def get_events() -> List[EventData]: with session_scope() as session: events = Event.get_all(session) return EventData.list(events)
def __init__(self,card=None,amount=None,**kw): if card: fill_event_from_card(self,card) if amount: self.TransactionType = 0 if amount >= 0 else 3 self.Amount = abs(amount) Event.__init__(self,**kw)
def from_new(cls, location, organiser_id, event_name, start_time, end_time, repeat): session = Session() code = random.randint(0, 1000000) while session.query(Event.code).filter_by(code=code).first() != None: code = random.randint(0, 1000000) event = Event() eid = next_id("event") event.eid = eid event.code = code event.location = location event.organiser_id = organiser_id event.event_name = event_name event.participants = {} event.start_time = start_time event.end_time = end_time event.repeat = repeat session.add(event) session.commit() session.close() return cls( eid, location, organiser_id, event_name, code, start_time, end_time, repeat, {}, )
def get_active() -> List[EventData]: with session_scope() as session: events = Event.get_all_active(session) return [EventData(e) for e in events]
def __init__(self, card = None, **kw): if card: fill_event_from_card(self,card) Event.__init__(self,**kw)
def get_event_by_user(id: int, user_id: int) -> Optional[EventViewData]: with session_scope() as session: event = Event.get_by_user(session, id, user_id) logging.info(f'got event {event}') event_image = EventImage.get_by_event(session, event.id) return EventViewData(*event, event_image.url)
def get_event(id: int) -> Optional[EventData]: with session_scope() as session: event = Event.get_by_id(session, id) return EventData(event)