Beispiel #1
0
def perfil():
    db_session = Session()
    usuario = db_session.query(Usuario).filter_by(
        id=session['usuario_id']).first()
    eventos = usuario.obtener_eventos_asignados()

    return render_template('perfil.html', usuario=usuario, eventos=eventos)
Beispiel #2
0
def nuevo_evento():
	form = EventoForm(request.form)
	db_session = Session()
	usuario = db_session.query(Usuario).filter_by(id=session['usuario_id']).first()
	if request.method == 'POST' and form.validate():
		usuario.asignar_evento(form)
		return redirect(url_for('perfil'))
	return render_template('nuevo_evento.html', form=form)
Beispiel #3
0
def nuevo_evento():
    form = EventoForm(request.form)
    db_session = Session()
    usuario = db_session.query(Usuario).filter_by(
        id=session['usuario_id']).first()
    if request.method == 'POST' and form.validate():
        usuario.asignar_evento(form)
        return redirect(url_for('perfil'))
    return render_template('nuevo_evento.html', form=form)
Beispiel #4
0
def get_times(date):
    time_dict = {
        tm: {
            ENABLED:
            check_is_past_time(date, tm) if check_date_range(date) else False,
            APPOINTMENT: None
        }
        for tm in range(MIN_TIME, MAX_TIME + 1)
    }

    session = Session()
    now = datetime.now()

    try:
        action = session.query(Action).filter(Action.name == LIST).one()

        appointments = session.query(Appointment).filter(
            and_(
                Appointment.date == date,
                Appointment.is_deleted == False,
            )).all()

        for appointment in appointments:
            time_dict[appointment.time][APPOINTMENT] = {
                ID: appointment.id,
                DATE: appointment.date.strftime(DATE_FORMAT),
                TIME: appointment.time,
                EMAIL: appointment.email,
            }

        log = Log(now, None, action, None, None, None, date, None, None)

        session.add(log)

        session.commit()

    except pymysqlOperationalError as poe:
        raise DWDBrokenPipeError(BROKEN_PIPE_ERROR_MESSAGE)
    except sqlalchemyOperationalError as soe:
        raise DWDBrokenPipeError(BROKEN_PIPE_ERROR_MESSAGE)
    except Exception as e:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
        message = '    '.join(line for line in lines)
        _log.error(message)
        raise DWDCantListAppointmentsException(
            CANT_LIST_APPOINTMENTS_MESSAGE.format(
                date=date.strftime(DATE_FORMAT), ))

    finally:
        session.close()

    return time_dict
Beispiel #5
0
def fetch_emails(creds, max_results, fetch_label):
    """
    Fetches a list of emails from the
    authenticated user's mail
    ----------------------------------

    arguments:
        - creds: oauth token object
        - fetch_label: label for filtered fetch 
    """
    service = build('gmail', 'v1', credentials=creds)
    include_spam_trash = False
    if ('SPAM' in fetch_label or 'TRASH' in fetch_label):
        include_spam_trash = True

    result = service.users().messages().list(
        userId='me',
        labelIds=fetch_label,
        maxResults=max_results,
        includeSpamTrash=include_spam_trash).execute()

    message_ids = result.get('messages', [])
    if not message_ids:
        print(f'No new {fetch_label} messages!')
    else:
        print(f'{len(message_ids)} {fetch_label} messages were fetched!')
        s = Session()
        count = 0
        for message_id in message_ids:
            result = service.users().messages().get(
                userId='me', id=message_id['id'], format='metadata').execute()
            headers = result['payload']['headers']
            record = {'message_id': result['id'], 'labels': result['labelIds']}
            for header in headers:
                if header['name'] == 'From':
                    record['sender'] = header['value']
                elif header['name'] == 'To':
                    record['recipient'] = header['value']
                elif header['name'] == 'Subject':
                    record['subject'] = header['value']
                elif header['name'] == 'Date':
                    record['date'] = parser.parse(header['value']).date()

            message = Message(**record)
            q = s.query(Message).filter_by(message_id=message.message_id)
            if not s.query(q.exists()).scalar():
                s.add(message)
                count += 1
        s.commit()
        s.close()
        print(f'{count} new {fetch_label} messages were added to the db!')
Beispiel #6
0
def exists_appointment(id):
    exists = True
    session = Session()

    appointment = session.query(Appointment).filter(
        Appointment.id == id).one_or_none()
    if appointment is None or appointment.is_deleted:
        exists = False

    session.close()

    if not exists:
        raise DWDAppointmentNotFoundException(
            APPOINTMENT_NOT_FOUND_MESSAGE.format(id=id, ))

    return True
Beispiel #7
0
    def create_session(self, user_id, jwt, timestamp):
        session = Session(
            key=generate_uuid(),
            user_id=user_id,
            jwt=jwt,
            created_at=timestamp,
            expires_at=(timestamp + 86400),
        )

        client_session['key'] = session.key
        client_session['user_id'] = session.user_id
        client_session['created_at'] = session.created_at
        client_session['expires_at'] = session.expires_at
        client_session['jwt'] = session.jwt

        session.save()
Beispiel #8
0
	def go_page2(self, event):
		name = self.inpt_name.GetValue()
		name = name.replace(' ', '')

		familia = self.inpt_familia.GetValue()
		if len(familia) == 0:
			self.empty_pole()
			return

		group = self.inpt_group.GetValue()
		if len(group) == 0:
			self.empty_pole()
			return
		zach_number = self.inpt_zachetka.GetValue()
		zach_number = zach_number.replace(' ', '')
		if len(zach_number) == 0:
			self.empty_pole()
			return

		fio = str(familia).lower() + ' ' + str(name).lower()
		new_session = Session()

		if new_session.query(exists().where(Student.fname == fio).
							where(Student.group == group).where(Student.zach_number == zach_number)).scalar():
			print("ЗАГРУЖАЮ ВАШЕ ЗАДАНИЕ")
		else:
			print("пора занести вас в базу и придумать для вас задание")
			student = Student(fname=fio, group=group, zach_number=zach_number)
			new_session.add(student)
			new_session.commit()

		from gui import SecondPage
		SecondPage.SecondPage.OnInit(SecondPage)
		self.Destroy()
Beispiel #9
0
def delete_appointment(id):
    try:
        session = Session()
        now = datetime.now()

        action = session.query(Action).filter(Action.name == DELETE).one()

        appointment = session.query(Appointment).filter(
            Appointment.id == id).one()

        date = appointment.date
        time = appointment.time

        if not check_is_past_time(date, time):
            raise DWDCantDeleteAppointmentBeforeException(
                CANT_DELETE_APPOINTMENT_BEFORE_MESSAGE.format(
                    appointment=appointment, ))

        log = Log(now, appointment, action, appointment.date, appointment.time,
                  appointment.email)

        appointment.is_deleted = True

        session.add(log)

        session.commit()

    except DanceWithDeathException as dwde:
        raise dwde

    except Exception as e:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
        message = '    '.join(line for line in lines)
        _log.error(message)

        raise DWDCantDeleteAppointmentException(
            CANT_DELETE_APPOINTMENT_MESSAGE.format(id=id, ))

    finally:
        session.close()

    return get_times(date), date.strftime(DATE_FORMAT)
Beispiel #10
0
    def is_valid_session(self, key):
        session = Session.get(key=key)
        if not session:
            return False

        if session.expires_at < time.time():
            self.destroy_session(key=key)
            return False

        return True
Beispiel #11
0
def process_emails(creds, rules_file):
    """
    Fetches emails from the database and performs
    actions, all based on set of rules in JSON format
    --------------------------------------------------

    arguments:
        - creds: oauth token object
        - rules_file: Json file path containing rules
    """
    service = build('gmail', 'v1', credentials=creds)
    with open(rules_file, 'r') as rf:
        rules = json.load(rf)

    session = Session()
    query_objects = []

    for rule in rules['rules']:
        if rule['field'].upper() == 'FROM':
            q = from_field_filter(session, rule)
            query_objects.append(q)
        elif rule['field'].upper() == 'SUBJECT':
            q = subject_field_filter(session, rule)
            query_objects.append(q)
        elif rule['field'].upper() == 'DATE':
            q = date_field_filter(session, rule)
            query_objects.append(q)

    if rules['globalPredicate'].upper() == 'ALL':
        messages = Query.intersect(*query_objects).all()
    elif rules['globalPredicate'].upper() == 'ANY':
        messages = Query.union(*query_objects).all()

    add_labels = []
    remove_labels = []

    for action in rules['actions']:
        if action['action'].upper() == 'MOVE':
            add_labels.append(action['value'].upper())
        elif (action['action'].upper() == 'MARK'
              and action['value'].upper() == 'UNREAD'):
            add_labels.append(action['value'].upper())
        elif (action['action'].upper() == 'MARK'
              and action['value'].upper() == 'READ'):
            remove_labels.append('UNREAD')

    for message in messages:
        result = service.users().messages().modify(userId='me',
                                                   id=message.message_id,
                                                   body={
                                                       'addLabelIds':
                                                       add_labels,
                                                       'removeLabelIds':
                                                       remove_labels
                                                   }).execute()
        message.labels = result['labelIds']
    session.commit()
    session.close()
    print(f'Actions performed on {len(messages)} matching messages')
Beispiel #12
0
def hacer_usuario_y_ejemplo():
    db_session = Session()
    usuario = Usuario(nombre="Cosme Fulanito")
    db_session.add(usuario)
    db_session.commit()
    print usuario.id
    evento1 = Evento(organizador=usuario.nombre,
                     nombre="Evento uno",
                     descripcion="Me gustaria poder organizar una juntada",
                     fecha=datetime.date.today(),
                     asistiran=0,
                     organizador_id=usuario.id)
    evento2 = Evento(organizador=usuario.nombre,
                     nombre="Evento dos",
                     descripcion="Hagamos tambien otra juntada mas",
                     fecha=datetime.date.today(),
                     asistiran=0,
                     organizador_id=usuario.id)
    print evento1.organizador_id
    db_session.add(evento1)
    db_session.add(evento2)
    db_session.commit()
    session['usuario_id'] = usuario.id
Beispiel #13
0
def hacer_usuario_y_ejemplo():
	db_session = Session()
	usuario = Usuario(nombre="Cosme Fulanito")
	db_session.add(usuario)
	db_session.commit()
	print usuario.id
	evento1 = Evento(organizador=usuario.nombre,
					nombre="Evento uno",
					descripcion="Me gustaria poder organizar una juntada", 
					fecha=datetime.date.today(), 
					asistiran=0, 
					organizador_id=usuario.id)
	evento2 = Evento(organizador=usuario.nombre,
					nombre="Evento dos",
					descripcion="Hagamos tambien otra juntada mas", 
					fecha=datetime.date.today(), 
					asistiran=0, 
					organizador_id=usuario.id)
	print evento1.organizador_id
	db_session.add(evento1)
	db_session.add(evento2)
	db_session.commit()
	session['usuario_id'] = usuario.id
Beispiel #14
0
def update_appointment(id, new_date, new_time, new_email):
    try:
        session = Session()
        now = datetime.now()

        action = session.query(Action).filter(Action.name == UPDATE).one()

        appointment = session.query(Appointment).filter(
            Appointment.id == id).one()

        old_date = appointment.date
        old_time = appointment.time
        old_email = appointment.email

        if not check_is_past_time(old_date, old_time):
            raise DWDCantUpdateAppointmentBeforeException(
                CANT_UPDATE_APPOINTMENT_BEFORE_MESSAGE.format(
                    appointment=appointment, ))

        if new_date is None:
            new_date = old_date

        if new_time is None:
            new_time = old_time

        if new_email is None:
            new_email = old_email

        previous_appointment = session.query(Appointment).filter(
            and_(
                Appointment.date == new_date,
                Appointment.time == new_time,
                Appointment.is_deleted == False,
            )).one_or_none()

        if previous_appointment is not None and previous_appointment != appointment:
            raise DWDDuplicateAppointmentException(
                DUPLICATE_APPOINTMENT_MESSAGE.format(
                    appointment=previous_appointment, ))

        log = Log(now, appointment, action, old_date, old_time, old_email,
                  new_date, new_time, new_email)

        appointment.date = new_date
        appointment.time = new_time
        appointment.email = new_email

        session.add(log)

        session.commit()

    except DanceWithDeathException as dwde:
        raise dwde

    except Exception as e:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
        message = '    '.join(line for line in lines)
        _log.error(message)

        raise DWDCantUpdateAppointmentException(
            CANT_UPDATE_APPOINTMENT_MESSAGE.format(
                id=id,
                date=new_date.strftime(DATE_FORMAT),
                time=time,
                email=email,
            ))

    finally:
        session.close()

    return get_times(new_date), new_date.strftime(DATE_FORMAT)
Beispiel #15
0
def create_appointment(date, time, email):
    try:
        session = Session()

        if not check_is_past_time(date, time):
            raise DWDCantCreateAppointmentBeforeException(
                CANT_CREATE_APPOINTMENT_BEFORE_MESSAGE.format(
                    date=date.strftime(DATE_FORMAT),
                    time=time,
                    email=email,
                ))

        previous_appointment = session.query(Appointment).filter(
            and_(
                Appointment.date == date,
                Appointment.time == time,
                Appointment.is_deleted == False,
            )).one_or_none()

        if previous_appointment is not None:
            raise DWDDuplicateAppointmentException(
                DUPLICATE_APPOINTMENT_MESSAGE.format(
                    appointment=previous_appointment, ))

        now = datetime.now()

        action = session.query(Action).filter(Action.name == CREATE).one()

        appointment = Appointment(date, time, email)

        log = Log(now, appointment, action, None, None, None, date, time,
                  email)

        session.add(appointment)
        session.add(log)

        session.commit()

    except DanceWithDeathException as dwde:
        raise dwde

    except Exception as e:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
        message = '    '.join(line for line in lines)
        _log.error(message)
        raise DWDCantCreateAppointmentException(
            CANT_CREATE_APPOINTMENT_MESSAGE.format(
                date=date.strftime(DATE_FORMAT),
                time=time,
                email=email,
            ))

    finally:
        session.close()

    return get_times(date), date.strftime(DATE_FORMAT)
Beispiel #16
0
def evento(evento):
	db_session = Session()
	evento = db_session.query(Evento).filter_by(id=evento).first()
	return render_template('evento.html',evento=evento)
Beispiel #17
0
def evento(evento):
    db_session = Session()
    evento = db_session.query(Evento).filter_by(id=evento).first()
    return render_template('evento.html', evento=evento)
def update_accounts_balances(tgbot):
    config_json_rpc_api_url = get_config_value('BLOCKCHAINPOLLER',
                                               'json_rpc_api_url')
    config_json_rpc_api_port = int(
        get_config_value('BLOCKCHAINPOLLER', 'json_rpc_api_port'))
    json_rpc_api_url = 'localhost' if config_json_rpc_api_url is None else config_json_rpc_api_url
    json_rpc_api_port = 8545 if config_json_rpc_api_port is None else config_json_rpc_api_port
    try:
        ether_stock_price_request = requests.get(
            'https://api.coinmarketcap.com/v1/ticker/ethereum/?convert=EUR')
        ether_stock_price = ether_stock_price_request.json()[0]
    except (requests.ConnectionError, IndexError):
        return
    else:
        if ether_stock_price_request.status_code != 200:
            # try next time if there is network error
            return
    session = Session()
    accounts_queryset = session.query(Account).options(eagerload(
        Account.chats)).all()
    for account in accounts_queryset:
        post_json = {
            'jsonrpc': '2.0',
            'method': 'eth_getBalance',
            'params': ['{}'.format(account.id), 'latest'],
            'id': 1
        }
        account_balance = requests.post('http://{}:{}'.format(
            json_rpc_api_url, json_rpc_api_port),
                                        json=post_json).json()
        old_balance = session.query(AccountBalance).filter_by(
            account_id=account.id).order_by(AccountBalance.id.desc()).first()
        if 'error' not in account_balance:
            new_balance = int(account_balance['result'], 16)
            if old_balance is None or new_balance != old_balance.balance:
                changed_value = new_balance if old_balance is None else (
                    new_balance - old_balance.balance) / 10**18
                changed_in_money = {
                    'EUR':
                    changed_value * float(ether_stock_price['price_eur']),
                    'USD':
                    changed_value * float(ether_stock_price['price_usd'])
                }
                new_account_balance = AccountBalance(
                    account_id=account.id,
                    balance=new_balance,
                    change_in_money=changed_in_money)
                session.add(new_account_balance)
                session.commit()
                if old_balance is not None:
                    for chat in account.chats:
                        if chat.subscription_active:
                            tgbot.send_message(
                                chat_id=chat.id,
                                text='{} UTC - 1 ETH = ${} / €{}\n'
                                'Account {} balance changed {} ETH.\n'
                                'Value ${} / €{}'.format(
                                    str(datetime.utcnow()),
                                    round(
                                        float(ether_stock_price['price_usd']),
                                        2),
                                    round(
                                        float(ether_stock_price['price_eur']),
                                        2), account.id, changed_value,
                                    round(changed_in_money["USD"], 3),
                                    round(changed_in_money["EUR"], 3)))
    session.close()
Beispiel #19
0
 def destroy_session(self, key):
     Session.delete(key=key)
     client_session.clear()
Beispiel #20
0
def perfil():
  db_session = Session()
  usuario = db_session.query(Usuario).filter_by(id=session['usuario_id']).first()
  eventos = usuario.obtener_eventos_asignados()

  return render_template('perfil.html', usuario=usuario, eventos=eventos)
 def __call__(self, form, field):
     db_session=Session()
     check = db_session.query(self.model).filter(self.field==field.data).first() 
     #check = self.model.query.filter(self.field == field.data).first()
     if check:
         raise ValidationError(self.message)