コード例 #1
0
ファイル: image_helper.py プロジェクト: dodotdo/youngs-server
def save_json_image(save_path_config, url_image_raw):
    try:
        up = urllib.parse.urlparse(url_image_raw)
        head, data = up.path.split(',', 1)
        bits = head.split(';')
        mime_type = bits[0] if bits[0] else 'text/plain'
        charset, b64 = 'ASCII', False
        for bit in bits:
            if bit.startswith('charset='):
                charset = bit[8:]
            elif bit == 'base64':
                b64 = True

        image_file = str.encode(data)
        log.info(image_file[:10])

        hash_mod.update(str(ptime.time()).encode('utf-8'))
        image_filename = hash_mod.hexdigest()[:10]
        filedir = current_app.config[save_path_config]
        if not os.path.exists(filedir):
            os.makedirs(filedir)

        ext = 'jpg'
        filename = secure_filename(image_filename) + '.' + ext

        filepath = os.path.join(filedir, filename)
        # not exist
        if not os.path.exists(filepath):
            with open(filepath, "wb") as message_file:
                message_file.write(base64.decodebytes(image_file))

        file_dir, filename = os.path.split(filepath)
        return filename
    except ValueError as e:
        abort(406, message='wrong image')
コード例 #2
0
def save_json_image(save_path_config, url_image_raw):
    try:
        up = urllib.parse.urlparse(url_image_raw)
        head, data = up.path.split(',', 1)
        bits = head.split(';')
        mime_type = bits[0] if bits[0] else 'text/plain'
        charset, b64 = 'ASCII', False
        for bit in bits:
            if bit.startswith('charset='):
                charset = bit[8:]
            elif bit == 'base64':
                b64 = True

        image_file = str.encode(data)
        log.info(image_file[:10])

        hash_mod.update(str(ptime.time()).encode('utf-8'))
        image_filename = hash_mod.hexdigest()[:10]
        filedir = current_app.config[save_path_config]
        if not os.path.exists(filedir):
            os.makedirs(filedir)

        ext = 'jpg'
        filename = secure_filename(image_filename) + '.' + ext

        filepath = os.path.join(filedir, filename)
        # not exist
        if not os.path.exists(filepath):
            with open(filepath, "wb") as message_file:
                message_file.write(base64.decodebytes(image_file))

        file_dir, filename = os.path.split(filepath)
        return filename
    except ValueError as e:
        abort(406, message='wrong image')
コード例 #3
0
    def post(self):
        args = self.member_post_parser.parse_args()
        email = args.email

        if email is None:
            abort(406, message="needs email")
        if re.match("^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$", email) is None:
            abort(406, message="email wrong formatted")
        abort_if_member_email_exist(email)

        member = Member(
                email=email,
                nickname=args.nickname
        )
        member.hash_password(args.password)

        if args.profile_img is not None:

            profile_filename = save_json_image('PROFILE_IMAGE_FOLDER', args.profile_img)
            member.profile_filename = profile_filename
            member.profile_url = generate_image_url('profile', profile_filename)

        db.session.add(member)
        db.session.commit()

        # Redis init
        p = youngs_redis.pipeline()
        for each_member in Member.query.all():
            log.info(each_member.email)
            p.set('member:'+each_member.email, {
                'id': each_member.id,
            })
        p.execute()
        return marshal(member, member_fields['normal'], envelope='results')
コード例 #4
0
    def post(self):
        args = self.member_post_parser.parse_args()
        email = args.email

        if email is None:
            abort(406, message="needs email")
        if re.match("^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$",
                    email) is None:
            abort(406, message="email wrong formatted")
        abort_if_member_email_exist(email)

        member = Member(email=email, nickname=args.nickname)
        member.hash_password(args.password)

        if args.profile_img is not None:

            profile_filename = save_json_image('PROFILE_IMAGE_FOLDER',
                                               args.profile_img)
            member.profile_filename = profile_filename
            member.profile_url = generate_image_url('profile',
                                                    profile_filename)

        db.session.add(member)
        db.session.commit()

        # Redis init
        p = youngs_redis.pipeline()
        for each_member in Member.query.all():
            log.info(each_member.email)
            p.set('member:' + each_member.email, {
                'id': each_member.id,
            })
        p.execute()
        return marshal(member, member_fields['normal'], envelope='results')
コード例 #5
0
    def delete(self, lecture_id):
        abort_if_lecture_not_exist(lecture_id)
        current_userid = current_id(request)
        res = youngs_redis.sismember(Constants.redis_youngs_live_lecture_listener_key(lecture_id), current_userid)
        if res is False:
            abort(403, message="Not a listener")

        res = youngs_redis.get(Constants.redis_youngs_live_lecture_occupy_key(lecture_id))
        youngs_redis.delete(Constants.redis_youngs_live_lecture_occupy_key(lecture_id))
        return jsonify({'results': 'success'})
コード例 #6
0
    def get(self):
        question_type = request.args.get('type')
        if question_type is None:
            abort(406, message="type is required")

        question_list = Question.query.filter_by(type=question_type).order_by(Question.id).all()
        print(question_list)
        shuffle(question_list)
        print(question_list)

        return marshal({'results': question_list}, question_list_fields)
コード例 #7
0
    def get(self):
        """
        :return: lecture list
        """
        order_by = request.args.get('order_by')
        num = request.args.get('num', default=10)
        type = request.args.get('type')
        start = request.args.get('start', default=0)
        status = request.args.get('status', type=str)
        is_attended = request.args.get('is_attended', type=bool)
        is_teaching = request.args.get('is_teaching', type=bool)


        # lecture_all = Lecture.query.all()
        # for each_lecture in lecture_all:
        #     listeners = youngs_redis.smembers(Constants.redis_youngs_live_lecture_listener_key(each_lecture.id))

        current_userid = current_id(request)
        lecture_filter_query = []
        if type is not None:
            try:
                type = ast.literal_eval(type)
            except:
                abort(406, message="type wrong formed. it should be like type=['TOEIC','FREE']")
            lecture_filter_query.append(Lecture.type.in_(type))
        if status is not None:
            lecture_filter_query.append(Lecture.status == status)
        if is_teaching is not None:
            lecture_filter_query.append(Lecture.member_id == current_userid)
        if is_attended is True:
            # sorry for durty code haha
            lecture_list = Lecture.query.outerjoin(Attend).filter(Attend.member_id == current_userid)
            return marshal({'results': lecture_list}, lecture_list_fields['normal'])

        lecture_order_query = []
        if order_by is not None:
            if order_by == 'type':
                lecture_order_query.append(desc(Lecture.type))
            elif order_by == 'point':
                lecture_order_query.append(desc(Lecture.point_avg))
            lecture_order_query.append(desc(Lecture.register_timestamp))


        lecture_query = Lecture.query.filter(*lecture_filter_query).group_by(Lecture).\
            order_by(*lecture_order_query)

        lecture_list = lecture_query.offset(start).limit(num).all()
        return marshal({'results': lecture_list}, lecture_list_fields['normal'])
コード例 #8
0
ファイル: decorator.py プロジェクト: dodotdo/youngs-server
    def wrapper(*args, **kwargs):
        if 'application/json' not in request.headers['Content-Type']:
            return abort(406, message='Wrong Content-Type')

        # func_args = inspect.getfullargspec(f, *args, **kwargs)
        # print(func_args.__dict__)
        return f(*args, **kwargs)
コード例 #9
0
ファイル: decorator.py プロジェクト: dodotdo-d/youngs-server
    def wrapper(*args, **kwargs):
        if 'application/json' not in request.headers['Content-Type']:
            return abort(406, message='Wrong Content-Type')

        # func_args = inspect.getfullargspec(f, *args, **kwargs)
        # print(func_args.__dict__)
        return f(*args, **kwargs)
コード例 #10
0
    def put(self, lecture_id):
        """
        :return: lecture
        """
        status = request.json.get('status')
        if status is None:
            abort(406, message="status attribute required")
        abort_if_lecture_not_exist(lecture_id)
        lecture = Lecture.query.filter_by(id=lecture_id).one()
        lecture.status = status
        db.session.commit()
        if status == 'STANDBY':
            redis_res = youngs_redis.sadd(Constants.REDIS_YOUNGS_LIVE_LECTURE_KEY, lecture.id)
            print(redis_res)
        elif status == 'FINISH':
            redis_res = youngs_redis.srem(Constants.REDIS_YOUNGS_LIVE_LECTURE_KEY, lecture.id)
            print(redis_res)

        return marshal(lecture, lecture_fields['normal'], envelope='results')
コード例 #11
0
    def post(self, lecture_id):
        lecture = Lecture.query.filter_by(id=lecture_id).one()
        if lecture.status not in ['STANDBY', 'READY']:
            abort(403, message="Lecture is not attendable")
        current_userid = current_id(request)
        res = youngs_redis.smembers(Constants.redis_youngs_live_lecture_listener_key(lecture_id))
        if res is not None:
            for each_listener in res:
                listener = int(each_listener.decode('utf-8'))
                if Member.query.filter_by(id=listener).first() is None:
                    # User removed
                    youngs_redis.srem(Constants.redis_youngs_live_lecture_listener_key(lecture_id), listener)

                if current_userid == lecture.member_id:
                    continue

                if listener != current_userid and listener != lecture.member_id:
                    abort(409, message="Someone is already listening the lecture")

        if Attend.query.filter_by(member_id=current_userid, lecture_id=lecture_id).first() is None:

            attend = Attend(
                member_id=current_userid,
                lecture_id=lecture_id
            )
            db.session.add(attend)

        if current_userid != lecture.member_id:
            # student attended
            print(current_userid)
            print(lecture.member_id)
            lecture.status = 'ONAIR'
        else:
            lecture.status = 'STANDBY'
        db.session.commit()
        token = request.headers.get('Authorization').replace('JWT ', '', 1)
        youngs_redis.sadd(Constants.redis_youngs_live_lecture_listener_key(lecture_id), current_userid)
        # youngs_redis.expire(Constants.redis_youngs_live_lecture_listener_key(lecture_id), 600)
        youngs_redis.hset('auth:token:' + token, 'lecture_id', lecture_id)

        return jsonify({'results': 'success'})
コード例 #12
0
    def post(self):
        """ login function """

        if 'application/json' in request.headers['Content-Type']:
            args = self.auth_post_parser.parse_args()
            email = args.email
            password = args.password

        else:
            raise abort(406, message='server cannot understand')
        # TODO get device type from headers

        member = Member.query.filter_by(email=email).one()

        if not member.verify_password(password):
            raise abort(401, message='id or pw is invalid')

        login_user(member)

        member.recent_login_timestamp = datetime.utcnow()
        db.session.commit()

        token_payload = {
            'id': member.id,
            'exp': datetime.utcnow() + timedelta(days=7)
        }
        token = jwt.encode(token_payload,
                           current_app.config['SECRET_KEY'],
                           algorithm='HS256').decode('utf-8')
        session_ttl = int(current_app.config['SESSION_ALIVE_MINUTES'] * 60)
        p = youngs_redis.pipeline()
        if youngs_redis.exists('auth:token:' + token) is False:
            p.hmset('auth:token:' + token, {'id': member.id})
        p.expire('auth:token:' + token, session_ttl)
        p.execute()
        session['token'] = token
        member.token = token

        log.info('Login : '******'results')
コード例 #13
0
ファイル: decorator.py プロジェクト: dodotdo-d/youngs-server
    def decorated_function(*args, **kwargs):
        # print session
        # temp

        token = request.headers.get('Authorization')
        if (token is None) or (len(token) < 7):
            abort(403, message='token invalid')
        token = token[6:]
        if token == '1':
            session['userid'] = 'admin'
            session['id'] = 1
            session['token'] = '1'
        elif youngs_redis.get('token-' + token) is None:
            log.error('token invalid : token [' + token + ']')
            abort(403, message='token invalid')
        else:
            userinfo = ast.literal_eval(youngs_redis.get('token-' + token))
            session['userid'] = userinfo['userid']
            session['id'] = userinfo['id']
            session['token'] = token
        log.info('token valid : user [' + session['userid'] + ']')
        return f(*args, **kwargs)
コード例 #14
0
ファイル: decorator.py プロジェクト: dodotdo/youngs-server
    def decorated_function(*args, **kwargs):
        # print session
        # temp

        token = request.headers.get('Authorization')
        if (token is None) or (len(token) < 7):
            abort(403, message='token invalid')
        token = token[6:]
        if token == '1':
            session['userid'] = 'admin'
            session['id'] = 1
            session['token'] = '1'
        elif youngs_redis.get('token-'+token) is None:
            log.error('token invalid : token [' + token + ']')
            abort(403, message='token invalid')
        else:
            userinfo = ast.literal_eval(youngs_redis.get('token-'+token))
            session['userid'] = userinfo['userid']
            session['id'] = userinfo['id']
            session['token'] = token
        log.info('token valid : user [' + session['userid'] + ']')
        return f(*args, **kwargs)
コード例 #15
0
    def post(self):
        args = self.lecture_post_parser.parse_args()
        current_userid = current_id(request)
        lecture = Lecture(
            member_id=current_userid,
            title=args.title,
            description=args.description,
            type=args.type
        )
        if args.img is not None:
            img_filename = save_json_image('LECTURE_IMAGE_FOLDER', args.img)
            lecture.img_filename = img_filename
            lecture.img_url = generate_image_url('lecture', img_filename)
        else:
            abort(406, message="img required")
        db.session.add(lecture)
        member = Member.query.filter_by(id=current_userid).one()
        member.lecture_num += 1

        db.session.commit()

        return marshal(lecture, lecture_fields['normal'], envelope='results')
コード例 #16
0
    def post(self):
        """ login function """

        if 'application/json' in request.headers['Content-Type']:
            args = self.auth_post_parser.parse_args()
            email = args.email
            password = args.password

        else:
            raise abort(406, message='server cannot understand')
        # TODO get device type from headers

        member = Member.query.filter_by(email=email).one()

        if not member.verify_password(password):
            raise abort(401, message='id or pw is invalid')

        login_user(member)

        member.recent_login_timestamp = datetime.utcnow()
        db.session.commit()

        token_payload = {
            'id': member.id,
            'exp': datetime.utcnow() + timedelta(days=7)
        }
        token = jwt.encode(token_payload, current_app.config['SECRET_KEY'], algorithm='HS256').decode('utf-8')
        session_ttl = int(current_app.config['SESSION_ALIVE_MINUTES'] * 60)
        p = youngs_redis.pipeline()
        if youngs_redis.exists('auth:token:'+token) is False:
            p.hmset('auth:token:'+token, {'id': member.id})
        p.expire('auth:token:'+token, session_ttl)
        p.execute()
        session['token'] = token
        member.token = token

        log.info('Login : '******'results')
コード例 #17
0
ファイル: views.py プロジェクト: dodotdo/youngs-server
def get_signage_image(filename):
    try:
        return send_file(os.path.join(current_app.config['SIGNAGE_IMAGE_FOLDER'], filename))

    except HTTPException as e:
        log.error({"code": e.code, "description": e.description})
        raise
    except IOError as e:
        log.critical('voice file problem : ' + e)
        return jsonify({'message': 'IO Error'}), 404
    except exc.SQLAlchemyError as e:
        log.error({"code": e.code, "description": e.description})
        db.session.rollback()
        return abort(403, message='Wrong Token')
    except Exception as e:
        log.critical('Unexpected Error : ' + e)
        return jsonify({'message': str(e)}), 500
コード例 #18
0
ファイル: views.py プロジェクト: dodotdo-d/youngs-server
def get_signage_image(filename):
    try:
        return send_file(
            os.path.join(current_app.config['SIGNAGE_IMAGE_FOLDER'], filename))

    except HTTPException as e:
        log.error({"code": e.code, "description": e.description})
        raise
    except IOError as e:
        log.critical('voice file problem : ' + e)
        return jsonify({'message': 'IO Error'}), 404
    except exc.SQLAlchemyError as e:
        log.error({"code": e.code, "description": e.description})
        db.session.rollback()
        return abort(403, message='Wrong Token')
    except Exception as e:
        log.critical('Unexpected Error : ' + e)
        return jsonify({'message': str(e)}), 500
コード例 #19
0
    def post(self, lecture_id):
        lecture = Lecture.query.filter_by(id=lecture_id).one()
        current_userid = current_id(request)
        if lecture.status != 'ONAIR':
            abort(403, message="Lecture is not in ONAIR")

        res = youngs_redis.sismember(Constants.redis_youngs_live_lecture_listener_key(lecture_id), current_userid)
        if res is False:
            abort(403, message="Not a listener")

        # request occupy
        redis_res = youngs_redis.get(Constants.redis_youngs_live_lecture_occupy_key(lecture_id))
        if redis_res is not None and redis_res.decode('utf-8') != current_userid:
            abort(409, message="Someone speacking")

        # Occupy
        pipe = youngs_redis.pipeline()
        pipe.set(Constants.redis_youngs_live_lecture_occupy_key(lecture_id), current_userid)
        pipe.expire(Constants.redis_youngs_live_lecture_occupy_key(lecture_id), 10)
        pipe.execute()
        return jsonify({'results': 'success'})