Ejemplo n.º 1
0
def editarcomentario():
    sesion = Session()
    usuario = request.headers.get('username')
    token_angular = request.headers.get('Authorization')
    #Verificamos si el usuario tiene una sesión activa
    if token_angular:
        if sesion.exist_session(usuario, token_angular):
            comm = Comentarios()
            info = request.get_json()
            res = comm.get_comment(info['id_user'], info['id_comment'])
            if res == 0:
                respuesta = {'error': True, 'mensaje': 'Comentario no existe.'}
                return json.dumps(respuesta)
            else:
                comm.edit_comment(info['id_user'], info['id_comment'],
                                  info['comentario'], info['fecha'])
                db.session.commit()  #guardo los cammbios
                respuesta = {
                    'error': False,
                    'mensaje': 'Comentario editado exitosamente.'
                }
                return json.dumps(respuesta)

    respuesta = {'error': True, 'mensaje': 'Debes iniciar sesión.'}
    return json.dumps(respuesta)
Ejemplo n.º 2
0
def pagar(user):
    sesion = Session()
    usuario = request.headers.get('username')
    token_angular = request.headers.get('Authorization')
    #Verificamos si el usuario tiene una sesión activa
    if token_angular:
        if sesion.exist_session(usuario, token_angular):
            if user.isdigit():
                car = Carrito()
                res = car.all_prod(user)
                if res == 0:
                    respuesta = {
                        'error': True,
                        'mensaje': 'No hay productos en el carrito.'
                    }
                    return json.dumps(respuesta)
                else:
                    car.aumentar_vendido(user, res)
                    for prod in res:
                        db.session.delete(prod)

                db.session.commit()
                respuesta = {
                    'error': False,
                    'mensaje': 'Su compra ha sido exitosa.'
                }
                return json.dumps(respuesta)

            respuesta = {'error': True, 'mensaje': 'Usuario no existe.'}
            return json.dumps(respuesta)

    respuesta = {'error': True, 'mensaje': 'Debes iniciar sesión.'}
    return json.dumps(respuesta)
Ejemplo n.º 3
0
def deletecomentario(user, comment):
    sesion = Session()
    usuario = request.headers.get('username')
    token_angular = request.headers.get('Authorization')
    #Verificamos si el usuario tiene una sesión activa
    if token_angular:
        if sesion.exist_session(usuario, token_angular):
            if user.isdigit() and comment.isdigit():
                comm = Comentarios()
                oneComm = comm.delete_comment(comment, user)
                if oneComm == 0:
                    respuesta = {
                        'error': True,
                        'mensaje': 'Comentario no existe.'
                    }
                    return json.dumps(respuesta)
                else:
                    db.session.delete(oneComm)
                    db.session.commit()
                    respuesta = {
                        'error': False,
                        'mensaje': 'Comentario borrado exitosamente.'
                    }
                    return json.dumps(respuesta)

            respuesta = {
                'error': True,
                'mensaje': 'Comentario o Usuario no existe.'
            }
            return json.dumps(respuesta)

    respuesta = {'error': True, 'mensaje': 'Debes iniciar sesión.'}
    return json.dumps(respuesta)
Ejemplo n.º 4
0
def deletecarrito(user, prod):
    sesion = Session()
    usuario = request.headers.get('username')
    token_angular = request.headers.get('Authorization')
    #Verificamos si el usuario tiene una sesión activa
    if token_angular:
        if sesion.exist_session(usuario, token_angular):
            if user.isdigit() and prod.isdigit():
                car = Carrito()
                oneProd = car.delete_prod(prod, user)
                if oneProd == 0:
                    respuesta = {
                        'error': True,
                        'mensaje': 'Producto no existe.'
                    }
                    return json.dumps(respuesta)
                else:
                    db.session.delete(oneProd)
                    db.session.commit()
                    respuesta = {
                        'error': False,
                        'mensaje': 'Producto borrado del carrito.'
                    }
                    return json.dumps(respuesta)

            respuesta = {
                'error': True,
                'mensaje': 'Producto o Usuario no existe'
            }
            return json.dumps(respuesta)

    respuesta = {'error': True, 'mensaje': 'Debes iniciar sesión.'}
    return json.dumps(respuesta)
Ejemplo n.º 5
0
def check_session(*args, **kwargs):
    from app.models.session import Session
    from app.models.user import UserModel
    g.user = None
    header = current_app.config.get("SESSION_HEADER")
    session_id = request.headers.get(header)
    session = Session()
    session_data = session.read(session_id)
    if session_data:
        g.user = UserModel(session_id)
        g.user.load()
    if request.endpoint in ["session", "status"]:
        pass
    elif request.method == "POST" and request.endpoint == "user":
        if not validate_session(session_id):
            abort(403)
    else:
        if not validate_session(session_id):
            abort(403)
        if request.method in ["POST", "PUT", "PATCH", "DELETE"]:
            if request.endpoint == "auth":
                pass
            elif not g.user or not g.user.get_id():
                print("Request denied (no auth)", request.endpoint)
                abort(403)
    g.session_id = session_id
Ejemplo n.º 6
0
def agregarcarrito():
    sesion = Session()
    usuario = request.headers.get('username')
    token_angular = request.headers.get('Authorization')
    #Verificamos si el usuario tiene una sesión activa
    if token_angular:
        if sesion.exist_session(usuario, token_angular):
            car = Carrito()
            user = Users()
            datos_user = user.get_user(usuario)
            datos = request.get_json()
            res = car.exist_prod(datos_user['id'], datos['id_prod'])
            if res == 1:
                car.agg_prod(datos_user['id'], datos['id_prod'])
                db.session.add(car)
                respuesta = {
                    'error': False,
                    'mensaje': 'Producto agregado exitosamente.'
                }
            else:
                respuesta = {
                    'error': False,
                    'mensaje': 'Cantidad aumentada exitosamente.'
                }

            db.session.commit()
            return json.dumps(respuesta)

    respuesta = {'error': True, 'mensaje': 'Debes iniciar sesión.'}
    return json.dumps(respuesta)
Ejemplo n.º 7
0
def cantcarrito():
    sesion = Session()
    usuario = request.headers.get('username')
    token_angular = request.headers.get('Authorization')
    #Verificamos si el usuario tiene una sesión activa
    if token_angular:
        if sesion.exist_session(usuario, token_angular):
            info = request.get_json()
            car = Carrito()
            res = car.adm_cant(info['id_user'], info['id_prod'],
                               info['opcion'])
            if res == 0:
                #Eliminamos el producto del carrito debido a que se resto la cantidad que estaba en 1
                oneProd = car.delete_prod(info['id_prod'], info['id_user'])
                if oneProd != 0:
                    db.session.delete(oneProd)
                respuesta = {
                    'error': False,
                    'mensaje': 'Producto eliminado del carrito.'
                }
            else:
                respuesta = {
                    'error': False,
                    'mensaje': 'Cantidad editada exitosamente.'
                }

            db.session.commit()
            return jsonify(respuesta)

    respuesta = {'error': True, 'mensaje': 'Debes iniciar sesión.'}
    return json.dumps(respuesta)
Ejemplo n.º 8
0
def delete(ide):
    sesion = Session()
    usuario = request.headers.get('username')
    token_angular = request.headers.get('Authorization')
    #Verificamos si el usuario tiene una sesión activa
    if token_angular:
        if sesion.exist_session(usuario, token_angular):
            if ide.isdigit():
                _id = ide
                prod = productos()
                oneProd = prod.delete_prod(_id)
                if oneProd == 0:
                    respuesta = {
                        'error': True,
                        'mensaje': 'Producto no existe.'
                    }
                    return json.dumps(respuesta)
                else:
                    db.session.delete(oneProd)
                    db.session.commit()
                    respuesta = {
                        'error': False,
                        'mensaje': 'Producto borrado exitosamente.'
                    }
                    return json.dumps(respuesta)

            respuesta = {'error': True, 'mensaje': 'Producto no existe.'}
            return json.dumps(respuesta)

    respuesta = {'error': True, 'mensaje': 'Debes iniciar sesión.'}
    return json.dumps(respuesta)
Ejemplo n.º 9
0
def logout():
    sesion = Session()
    usuario = request.headers.get('username')
    token_angular = request.headers.get('Authorization')
    #Verificamos si el usuario tiene una sesión activa
    if token_angular:
        if sesion.exist_session(usuario, token_angular):
            deletesesion = sesion.delete_session(usuario)

            if deletesesion == 0:
                respuesta = {
                    'error': True,
                    'mensaje': 'No has iniciado sesión.'
                }
                return json.dumps(respuesta)
            else:
                db.session.delete(deletesesion)
                db.session.commit()
                respuesta = {
                    'error': False,
                    'mensaje': 'Cerraste sesión correctamente'
                }
                return json.dumps(respuesta)

    respuesta = {'error': True, 'mensaje': 'Ya has iniciado sesión.'}
    return json.dumps(respuesta)
Ejemplo n.º 10
0
def log_user():
    sesion = Session()
    new = request.get_json()
    usuario = new['username']
    token_angular = request.headers.get('Authorization')
    #Verificamos si el usuario tiene una sesión activa
    if token_angular:
        if sesion.exist_session(usuario, token_angular):
            respuesta = {'error': True, 'mensaje': 'Ya has iniciado sesión.'}
            return json.dumps(respuesta)

    user = Users()
    clave = new['password']

    if sesion.exist_sesion(usuario):
        deletesesion = sesion.delete_session(usuario)
        db.session.delete(deletesesion)
        db.session.commit()

    if user.login(usuario, clave):
        res = create_session(usuario, user.is_Admin(usuario))
        respuesta = {
            'error': False,
            'mensaje': 'Inicio de sesión exitoso.',
            'token': res
        }
        return json.dumps(respuesta)
    else:
        respuesta = {
            'error': True,
            'mensaje': 'Usuario o Contraseña incorrectos.'
        }
        return json.dumps(respuesta)
Ejemplo n.º 11
0
def validate_session(session_id):
    from app.models.session import Session
    session_model = Session()
    client_origin = (request.remote_addr or "0.0.0.0")
    client_agent = request.user_agent
    session_ok = (session_id and session_model.touch(session_id, client_agent,
                                                     client_origin))
    return session_ok
Ejemplo n.º 12
0
def create_session(username, admin):
    user = Users()
    token = user.create_password("secret")
    sesion = Session()
    sesion.create_session(username, token, admin)
    db.session.add(sesion)
    db.session.commit()
    return token
Ejemplo n.º 13
0
def handle_post(data):
    post = data['post']
    session_id = data['session_id']
    # save post
    session = Session().get(session_id)
    if session is not None:
        session.addPost(post)
    # broadcast post to other users in session
    emit("post", post, room=session_id)
Ejemplo n.º 14
0
 def _handle_regular_user(self, data):
     session_model = Session()
     session_id = g.get("session_id", None)
     model = UserModel(session_id)
     user = model.create(data)
     if user:
         session_model.update(session_id, user_id=user.id)
         return user
     return None
Ejemplo n.º 15
0
 def decorated(*args, **kwargs):
     user = g.get("user")
     if user and user.get_session_id():
         session_touched = g.get("session_touched", None)
         if not session_touched:
             session = Session()
             session_touched = session.touch(user.get_session_id(),
                                             request.user_agent,
                                             request.remote_addr)
         if session_touched:
             return f(*args, **kwargs)
     abort(401)
Ejemplo n.º 16
0
def perfil():
    sesion = Session()
    new = request.get_json()
    usuario = request.headers.get('username')
    token_angular = request.headers.get('Authorization')
    print(usuario)
    #Verificamos si el usuario tiene una sesión activa
    if token_angular:
        if sesion.exist_session(usuario, token_angular):
            user = Users()
            datos = user.get_user(usuario)
            return json.dumps(datos)

    respuesta = {'error': True, 'mensaje': 'No has iniciado sesión.'}
    return json.dumps(respuesta)
Ejemplo n.º 17
0
def login(email, password, remember: bool, next_url):
    """Login

    This is seperated into a function as this code is also needed during
    signup (see `user_api1.user_post`)
    Important: This function needs to be called within the context of an
    request. Otherwise, accessing `g` and `url_for` wont work.
    """
    try:
        user: User = db.session.query(User).filter(User.email == email).one()
        if user.check_password(password):
            g.session = Session(user, session_only=(not remember))
            g.session.browser = str(request.user_agent.browser or '?')
            g.session.platform = str(request.user_agent.platform or '?')

            db.session.add(g.session)
            db.session.commit()

            expiration_date = g.session.last_use + timedelta(days=60)
            tasks.remove_session.schedule(args=(g.session.id, ),
                                          eta=expiration_date)

            if user.status is Status.pending:
                next_url = url_for('auth.wait')
            if not user.email_confirmed:
                next_url = url_for('auth.confirm')
            return jsonify({
                'success': True,
                'redirect': next_url,
                'sid': g.session.token
            })
        else:
            raise Exception()
    except Exception as e:
        return jsonify({'success': False, 'reason': 'credentials'}), 401
 def test_my_session_unauthorized_access(self):
     with app.test_request_context():
         event = ObjectMother.get_event()
         user = ObjectMother.get_user()
         save_to_db(user, "User saved")
         save_to_db(event, "Event saved")
         speaker = Speaker(name="name",
                           email="*****@*****.**",
                           organisation="FOSSASIA",
                           event_id=event.id,
                           user=user,
                           country="India")
         save_to_db(speaker, "Speaker saved")
         session = Session(title='test',
                           long_abstract='dsad',
                           start_time=datetime(2003, 8, 4, 12, 30, 45),
                           end_time=datetime(2003, 8, 4, 12, 30, 45),
                           event_id=event.id,
                           speakers=[speaker],
                           state='pending')
         save_to_db(session, "Session saved")
         rv = self.app.get(url_for('my_sessions.display_session_view',
                                   session_id=session.id),
                           follow_redirects=True)
         self.assertEqual(rv.status_code, 404)
 def test_add_session_type_to_db(self):
     """Checks the one to many relationship between event and session_types and
             the many to one relationship between session and session_types"""
     self.app = Setup.create_app()
     with app.test_request_context():
         event = ObjectMother.get_event()
         session1 = ObjectMother.get_session()
         session_type1 = SessionType(name='Type1',
                                     length='30',
                                     event_id='1')
         session_type2 = SessionType(name='Type2',
                                     length='30',
                                     event_id='1')
         session2 = Session(title='test2',
                            long_abstract='dsadsd',
                            start_time=datetime(2003, 8, 4, 12, 30, 45),
                            end_time=datetime(2003, 8, 4, 12, 30, 45),
                            session_type=session_type1)
         save_to_db(event, "Event Saved")
         save_to_db(session1, "Session1 Saved")
         save_to_db(session2, "Session2 Saved")
         save_to_db(session_type1, "SessionType1 Saved")
         save_to_db(session_type2, "SessionType2 Saved")
         self.assertEqual(session_type1.event_id, 1)
         self.assertEqual(session_type2.event_id, 1)
         self.assertEqual(session2.session_type_id, 1)
         self.assertEqual(session1.session_type_id, None)
Ejemplo n.º 20
0
def create_app(config: Config):
    app = FastAPI(openapi_url="/openapi/spec.json",
                  docs_url="/swagger",
                  redoc_url="/redoc",
                  debug=True)
    app.include_router(router)

    # wire things up
    app.config = Config()
    app.session = SessionWrapper(s=Session())
    app.db = DB(app.config.DB_DSN.get_secret_value())
    app.repositories = lambda: None
    app.repositories.zipcodes = ZipCodeRepository(db=app.db)
    app.shutdown = lambda: __import__('os').kill(app.config.PID,
                                                 __import__('signal').SIGTERM)

    @app.on_event("startup")
    async def setup() -> None:
        logging.info(f"[APP_SETUP] {app} {app.config}")

        app.loop = asyncio.get_running_loop()
        await app.db.setup(app)
        await app.session.s.setup()

    @app.on_event("shutdown")
    async def teardown() -> None:
        logging.info(f"[APP_TEARDOWN] {app} {app.config}")

        await app.session.s.teardown()
        await app.db.teardown()

    return app
Ejemplo n.º 21
0
 def get_session(event_id=1):
     return Session(title='test',
                    long_abstract='dsad',
                    start_time=datetime(2003, 8, 4, 12, 30, 45),
                    end_time=datetime(2003, 8, 4, 12, 30, 45),
                    event_id=event_id,
                    state='pending')
Ejemplo n.º 22
0
    def post(self):
        # validate JSON data
        parser = reqparse.RequestParser()
        parser.add_argument('date', type=date, required=True, case_sensitive=False, location='json')
        parser.add_argument('exercises', type=self.parse_exercises, required=True, case_sensitive=False, location='json')
        data = parser.parse_args(strict=True)

        # create a gym session object
        gym_session = Session(date=data['date'], user_id=g.current_user.id)
        try:
            db.session.add(gym_session)
            db.session.commit()
        except IntegrityError as exn:
            current_app.logger.error(exn.args)
            db.session.rollback()
            return {'message': 'error: sessions must be unique across dates for each user'}, 409

        # create gym record objects and link the to the session
        try:
            for exercise in data['exercises']:
                exercise_id = db.session \
                                .query(Exercise.exercise_id) \
                                .filter_by(exercise_name = exercise['exercise name']) \
                                .scalar()
                for reps, weight in zip(exercise['reps'], exercise['weights']):
                    record = GymRecord(session_id=gym_session.session_id,
                                       exercise_id=exercise_id,
                                       reps=reps,
                                       weight=weight)
                    db.session.add(record)
                    db.session.commit()
            return {'Message': 'Record successfully created'}, 201
        except Exception as exn:
            current_app.logger.error(exn.args)
            abort(500)
Ejemplo n.º 23
0
class Session(Resource):
    cache = {}

    def __init__(self):
        self._model = SessionModel()

    def post(self):
        data = self._model.create((request.remote_addr or "0.0.0.0"),
                                  str(request.user_agent))
        if data:
            data = self._model.read(data.id)
            return jsonify(dict(data))
        abort(400)

    def get(self, session_id=None):
        response = self._model.read(session_id)
        if response:
            return jsonify(response)
        abort(404)

    def delete(self, session_id=None):
        self._model.destroy(session_id)
        return ""

    def put(self, session_id=None):
        data = self._model.update(session_id, data=json.dumps(request.json))
        if data:
            data = self._model.read(session_id)
            if data:
                return jsonify(dict(data))
        abort(400)
Ejemplo n.º 24
0
def totalcarrito(user):
    sesion = Session()
    usuario = request.headers.get('username')
    token_angular = request.headers.get('Authorization')
    #Verificamos si el usuario tiene una sesión activa
    if token_angular:
        if sesion.exist_session(usuario, token_angular):
            if user.isdigit():
                car = Carrito()
                total = car.get_total_price(user)
                respuesta = {'total': total}
                return json.dumps(respuesta)

            respuesta = {'error': True, 'mensaje': 'Usuario no existe.'}
            return json.dumps(respuesta)

    respuesta = {'error': True, 'mensaje': 'Debes iniciar sesión.'}
    return json.dumps(respuesta)
Ejemplo n.º 25
0
    def scrape_session(self, session_page):
        self.browser.get(session_page)

        speakers = self.speaker_dao.find_all()
        speakers_by_name = {
            speaker['speaker_name']: speaker
            for speaker in speakers
        }

        sessions = self.session_dao.find_all()
        sessions_by_session_id = {
            session['session_id']: session
            for session in sessions
        }

        self.wait_by_class_name("session")

        sessions = self.browser.find_elements_by_class_name("session")

        for session_element in sessions:
            session = Session()
            session.from_web_element(session_element)

            if session.session_id not in sessions_by_session_id:
                _id = self.session_dao.create(session)
                session._id = _id
                sessions_by_session_id[session.session_id] = session

        speaker_elements = self.browser.find_elements_by_xpath(
            "//*[@data-modal='user_profile']")

        for speaker_element in speaker_elements:
            speaker = Speaker()
            speaker.from_web_element(speaker_element)

            if speaker.speaker_name not in speakers_by_name:
                _id = self.speaker_dao.create(speaker)
                speaker._id = _id
                speakers_by_name[speaker.speaker_name] = speaker

        return len(sessions)
Ejemplo n.º 26
0
def carrito():
    sesion = Session()
    usuario = request.headers.get('username')
    token_angular = request.headers.get('Authorization')
    #Verificamos si el usuario tiene una sesión activa
    if token_angular:
        if sesion.exist_session(usuario, token_angular):
            car = Carrito()
            lista = car.all_car()
            if lista == 0:
                respuesta = {
                    'error': True,
                    'mensaje': 'No hay artículos en el carrito.'
                }
                return jsonify(respuesta)
            number = car.number_car()
            jsona = car.convert(lista, number)
            return jsonify(jsona)

    respuesta = {'error': True, 'mensaje': 'Debes iniciar sesión.'}
    return json.dumps(respuesta)
Ejemplo n.º 27
0
def create_services():
    track = Track.get_service_name()
    session = Session.get_service_name()
    speaker = Speaker.get_service_name()
    sponsor = Sponsor.get_service_name()
    microlocation = Microlocation.get_service_name()

    get_or_create(Service, name=track)
    get_or_create(Service, name=session)
    get_or_create(Service, name=speaker)
    get_or_create(Service, name=sponsor)
    get_or_create(Service, name=microlocation)
Ejemplo n.º 28
0
def agregarcomentario():
    sesion = Session()
    usuario = request.headers.get('username')
    token_angular = request.headers.get('Authorization')
    #Verificamos si el usuario tiene una sesión activa
    if token_angular:
        if sesion.exist_session(usuario, token_angular):
            comm = Comentarios()
            user = Users()
            user = user.get_user(usuario)
            datos = request.get_json()
            comm.agg_comment(user['id'], datos['comentario'], datos['fecha'])
            db.session.add(comm)
            db.session.commit()
            respuesta = {
                'error': False,
                'mensaje': 'Comentario agregado exitosamente.'
            }
            return json.dumps(respuesta)

    respuesta = {'error': True, 'mensaje': 'Debes iniciar sesión.'}
    return json.dumps(respuesta)
Ejemplo n.º 29
0
def create():
    sesion = Session()
    usuario = request.headers.get('username')
    token_angular = request.headers.get('Authorization')
    #Verificamos si el usuario tiene una sesión activa
    if token_angular:
        if sesion.exist_session(usuario, token_angular):
            oneProd = productos()
            product = request.get_json()
            oneProd.create_prod(product['name'], product['price'],
                                product['img'], product['description'],
                                product['category'], product['sell'])
            db.session.add(oneProd)
            db.session.commit()
            respuesta = {
                'error': False,
                'mensaje': 'Producto creado exitosamente.'
            }
            return json.dumps(respuesta)

    respuesta = {'error': True, 'mensaje': 'Debes iniciar sesión.'}
    return json.dumps(respuesta)
Ejemplo n.º 30
0
def comments():
    sesion = Session()
    usuario = request.headers.get('username')
    token_angular = request.headers.get('Authorization')
    #Verificamos si el usuario tiene una sesión activa
    if token_angular:
        if sesion.exist_session(usuario, token_angular):
            comm = Comentarios()
            lista = comm.all_comments()
            if lista == 0:
                respuesta = {
                    'error': True,
                    'mensaje': 'No hay notas almacenadas.'
                }
                return jsonify(respuesta)

            number = comm.number_comments()
            jsona = comm.convert(lista, number)
            return jsonify(jsona)

    respuesta = {'error': True, 'mensaje': 'Debes iniciar sesión.'}
    return json.dumps(respuesta)
Ejemplo n.º 31
0
    def add_session_to_event(request, event_id, state=None, use_current_user=True):
        """
        Session will be saved to database with proper Event id
        :param use_current_user:
        :param state:
        :param request: The request
        :param event_id: Session belongs to Event by event id
        """
        form = request.form
        slide_temp_url = form.get('slides_url')
        video_temp_url = form.get('video_url')
        audio_temp_url = form.get('audio_url')
        slide_file = ''
        video_file = ''
        audio_file = ''

        if slide_temp_url:
            slide_file = UploadedFile(get_path_of_temp_url(slide_temp_url), slide_temp_url.rsplit('/', 1)[1])

        if video_temp_url:
            video_file = UploadedFile(get_path_of_temp_url(video_temp_url), video_temp_url.rsplit('/', 1)[1])

        if audio_temp_url:
            audio_file = UploadedFile(get_path_of_temp_url(audio_temp_url), audio_temp_url.rsplit('/', 1)[1])

        if not state:
            state = form.get('state', 'draft')

        event = DataGetter.get_event(event_id)

        new_session = Session(title=form.get('title', ''),
                              subtitle=form.get('subtitle', ''),
                              long_abstract=form.get('long_abstract', ''),
                              start_time=event.start_time,
                              end_time=event.start_time + timedelta(hours=1),
                              event_id=event_id,
                              short_abstract=form.get('short_abstract', ''),
                              level=form.get('level', ''),
                              comments=form.get('comments', ''),
                              language=form.get('language', ''),
                              state=state)

        if form.get('track', None) != "":
            new_session.track_id = form.get('track', None)

        if form.get('session_type', None) != "":
            new_session.session_type_id = form.get('session_type', None)

        speaker = Speaker.query.filter_by(email=form.get('email', '')).filter_by(event_id=event_id).first()
        speaker = save_speaker(
            request,
            event_id=event_id,
            speaker=speaker,
            user=login.current_user if use_current_user else None
        )

        new_session.speakers.append(speaker)

        save_to_db(new_session, "Session saved")

        if state == 'pending':
            trigger_new_session_notifications(new_session.id, event=event)

        if slide_temp_url != "" and slide_file:
            slide_url = upload(
                slide_file,
                UPLOAD_PATHS['sessions']['slides'].format(
                    event_id=int(event_id), id=int(new_session.id)
                ))
            new_session.slides = slide_url
        if audio_temp_url != "" and audio_file:
            audio_url = upload(
                audio_file,
                UPLOAD_PATHS['sessions']['audio'].format(
                    event_id=int(event_id), id=int(new_session.id)
                ))
            new_session.audio = audio_url
        if video_temp_url != "" and video_file:
            video_url = upload(
                video_file,
                UPLOAD_PATHS['sessions']['video'].format(
                    event_id=int(event_id), id=int(new_session.id)
                ))
            new_session.video = video_url

        record_activity('create_session', session=new_session, event_id=event_id)
        update_version(event_id, False, 'sessions_ver')

        invite_emails = form.getlist("speakers[email]")
        for index, email in enumerate(invite_emails):
            if not string_empty(email):
                new_invite = Invite(event_id=event_id, session_id=new_session.id)
                hash = random.getrandbits(128)
                new_invite.hash = "%032x" % hash
                save_to_db(new_invite, "Invite saved")

                link = url_for('event_sessions.invited_view', session_id=new_session.id, event_id=event_id,
                               _external=True)
                Helper.send_email_invitation(email, new_session.title, link)
                # If a user is registered by the email, send a notification as well
                user = DataGetter.get_user_by_email(email, no_flash=True)
                if user:
                    cfs_link = url_for('event_detail.display_event_cfs', identifier=event.identifier)
                    Helper.send_notif_invite_papers(user, event.name, cfs_link, link)
Ejemplo n.º 32
0
    def import_data(file_path, creator_id, task_handle):

        with open(file_path, 'r') as xml_file:
            string = xml_file.read().replace('\n', '')

        update_status(task_handle, 'Parsing XML file')
        conference_object = PentabarfParser.parse(string)
        update_status(task_handle, 'Processing event')
        event = Event()
        event.start_time = conference_object.start
        event.end_time = conference_object.end
        event.has_session_speakers = True
        event.name = conference_object.title
        event.location_name = conference_object.venue  # + ', ' + conference_object.city
        event.searchable_location_name = conference_object.city
        event.state = 'Published'
        event.privacy = 'public'
        db.session.add(event)
        event_time_updated = False
        update_status(task_handle, 'Adding sessions')
        for day_object in conference_object.day_objects:
            for room_object in day_object.room_objects:
                microlocation, _ = get_or_create(Microlocation, event_id=event.id, name=room_object.name)
                for event_object in room_object.event_objects:
                    session_type_id = None
                    if event_object.type:
                        session_type, _ = get_or_create(SessionType, event_id=event.id,
                                                        name=event_object.type, length=str(30))  # TODO: hardcoded here
                        session_type_id = session_type.id
                    track_id = None
                    if event_object.track:
                        string_to_hash = event_object.track
                        seed = int('100'.join(list(str(ord(character)) for character in string_to_hash)))
                        random.seed(seed)
                        color = "#%06x" % random.randint(0, 0xFFFFFF)
                        track, _ = get_or_create(Track, event_id=event.id, name=event_object.track, color=color)
                        track_id = track.id

                    session = Session()
                    session.track_id = track_id
                    session.microlocation_id = microlocation.id
                    session.session_type_id = session_type_id
                    session.title = event_object.title
                    session.short_abstract = event_object.abstract
                    session.long_abstract = event_object.description
                    session.level = getattr(event_object, 'level', None)  # https://github.com/niranjan94/python-pentabarf-xml/issues/3
                    session.start_time = event_object.date + string_to_timedelta(event_object.start)
                    session.end_time = session.start_time + string_to_timedelta(event_object.duration)
                    session.slides = event_object.slides_url
                    session.video = event_object.video_url
                    session.audio = event_object.audio_url
                    session.signup_url = event_object.conf_url
                    session.event_id = event.id
                    session.state = 'accepted'
                    session.speakers = []
                    save_to_db(session, 'Session Updated')

                    if not event_time_updated:
                        event.start_time = None
                        event.end_time = None
                        event_time_updated = True

                    if not event.start_time or session.start_time < event.start_time:
                        event.start_time = session.start_time
                    if not event.end_time or session.end_time > event.end_time:
                        event.end_time = session.end_time

                    for person_object in event_object.person_objects:
                        name_mix = person_object.name + ' ' + conference_object.title
                        email = ''.join(x for x in name_mix.title() if not x.isspace()) + '@example.com'
                        speaker = Speaker(name=person_object.name, event_id=event.id, email=email,
                                          country='Earth',
                                          organisation='')
                        db.session.add(speaker)
                        session.speakers.append(speaker)
                        db.session.commit()

                    update_status(task_handle, 'Added session "' + session.title + '"')

        update_status(task_handle, 'Saving data')
        save_to_db(event)
        update_status(task_handle, 'Finalizing')
        own_event(event=event, user_id=creator_id)
        return event