예제 #1
0
 def get_summary(thisDayStart, thisDayEnd, thisMonthStart, thisMonthEnd):
     newUserToday = UserService.get_newuser_amount(thisDayStart, thisDayEnd)
     totalUser = UserService.get_user_amount()
     membershipDAU = KService.get_user_DAU('102', thisDayStart, thisDayEnd)
     VipDAU = KService.get_user_DAU('103', thisDayStart, thisDayEnd)
     incomeDay = OrderService.get_paidOrder_sum(thisDayStart, thisDayEnd)
     incomeMonth = OrderService.get_paidOrder_sum(thisMonthStart,
                                                  thisMonthEnd)
     data = {
         "newUserToday": newUserToday,
         "totalUser": totalUser,
         "membershipDAU": membershipDAU,
         "VipDAU": VipDAU,
         "incomeDay": incomeDay,
         "incomeMonth": incomeMonth
     }
     return data
예제 #2
0
    def process(self):
        user_body = self.parameters.get('body')

        if self.check_registed_user_by_email(user_body.get('email')):
            return {
                "code": 4010,
                "message": returncode['4010'],
            }, 400
        logging.info("AddUserView. {}".format(user_body))
        UserService.add_user(user_body.get('name'), user_body.get('email'),
                             user_body.get('password'),
                             user_body.get('appkey'),
                             user_body.get('email_verified'), int(time.time()))
        db.session.commit()
        if not user_body.get('email_verified'):
            logging.error(
                "email_verified false, So we need send an verify email to {}".
                format(user_body['email']))

        # get user service info again, active it.
        user = UserService.get_user_by_email(user_body.get('email'))
        UserService.active_thunderservice(user.id, user.thunderservice_id,
                                          user.thunderservice_starttime,
                                          user.thunderservice_endtime)
        db.session.commit()

        source = user_body.get('appkey') if user_body.get(
            'appkey') else 'Unknown'
        KService_action = '101'
        KService.add_record(action=KService_action,
                            parameter1=user.id,
                            parameter2=source,
                            timestamp=int(time.time()))

        return {
            "code": 200,
            "message": "add user success",
        }
예제 #3
0
    def process(self):
        from application.services.user_service import UserService
        data = self.parameters.get('body')
        print("AddOrderView:")
        print(data)
        user_info = UserService.get_user(data['user_id'])
        if user_info:
            OrderService.add_order(data['user_id'], data['thunderservice_id'],\
                                   time.time()*1000,data['coupon'],data['amount'],data['emailNotification'])
            db.session.commit()

            # 增加记录到K线图
            KService_action = '201'
            KService.add_record(action=KService_action,parameter1=data['amount'],parameter2='New',timestamp=int(time.time()))

            return {
                "code":200,
                "message":"Add order success"
            }
        else:
            return {
                "code": 4011,
                "message": returncode['4011']
            },200
예제 #4
0
    def process(self):
        from application.services.user_service import UserService
        data = self.parameters.get('body')

        logging.info(f"addExpressorder(POST /app/expressorder):{data}")

        user_info = UserService.get_user(data.get('user_id'))
        if user_info:

            thunderserviceFufeiList = GetThunderservice.get_fufei_thunderservice()
            thunderserviceList = []
            if len(thunderserviceFufeiList):
                for item in thunderserviceFufeiList:
                    temp = {
                        "thunderserviceID":item.id,
                        "price":item.price,
                        "currency":"USD",
                        "duration":item.duration
                    }
                    thunderserviceList.append(temp)

            #生成order_id
            thunderServiceID = data.get('thunderserviceID') if data.get('thunderserviceID') else '3'
            if str(thunderServiceID) not in thunder_service_for_expressorderID['FUFEI']:
                logging.error(f"ERROR: addExpressorder: 5005")
                return {
                           "code": 5005,
                           "message": returncode['5005']
                       },200

            # order_id = 'EX'+time.strftime("%Y%m%d%H%M%S",time.localtime())+'U'+user_info.email[:1]+'P'+str(thunderServiceID)

            ts = time.time()
            ts_ms = int(ts*1000-int(ts)*1000)
            order_id = 'EX'+time.strftime("%Y%m%d%H%M%S",time.localtime(ts))+'S'+str(ts_ms)+'U'+user_info.email[:1]+'P'+str(thunderServiceID)

            #取出定价,根据coupon,调整amount
            thunderservice_selected = GetThunderservice.get_thunderservice(thunderServiceID)
            amount = thunderservice_selected.price if thunderservice_selected else 0
            coupon = data.get('coupon')
            # TODO coupon
            amount = amount

            #expressorder不需要发送订单邮件
            emailNotification = False

            #取到thunderservice中对应的desc
            description = thunderservice_selected.description if thunderservice_selected else None

            #添加订单记录
            OrderService.add_order(order_id,data['user_id'], thunderServiceID, \
                                   time.time()*1000,coupon,amount,emailNotification,description)
            db.session.commit()

            # 增加记录到K线图
            KService_action = '201'
            KService.add_record(action=KService_action,parameter1=amount,parameter2='New',timestamp=int(time.time()))

            resp = {
                "code":200,
                "thunderserviceList":thunderserviceList,
                "selectedThunderServiceID":thunderServiceID,
                "orderID":order_id,
                "qrsource":"/app/expressorder_view?orderID="+order_id
            }

            logging.info(f"addExpressorder, response:{resp}")
            return resp,200
        else:
            logging.error(f"ERROR: addExpressorder: 4011")
            return {
                       "code": 4011,
                       "message": returncode['4011']
                   },200
예제 #5
0
    def process(self):
        # TODO 用于多语言及切换货币
        Country = "cn"

        data = request.args
        logging.info(f"appPopupHtmlQRcode(GET: /app/app_popup/qrcode):{data}")

        # 检查入参及取到用户信息
        try:
            token = data['token']
            thunderServiceID = data['thunderserviceID']
            data = jwt.decode(token, config.settings.SECRET_KEY)
            user_info = UserService.get_user(data['user_id'])
        except:
            # invalid token or no thunderServiceID input
            return "Token expired or no thunderServiceID find, please try again", 200

        # 生成order_id
        if str(thunderServiceID) not in thunder_service_ID['FUFEI']:
            logging.error(f"ERROR: addExpressorder: 5005")
            return {
                       "code": 5005,
                       "message": returncode['5005']
                   },200

        ts = time.time()
        ts_ms = int(ts*1000-int(ts)*1000)
        order_id = 'EX'+time.strftime("%Y%m%d%H%M%S",time.localtime(ts))+'S'+str(ts_ms)+'U'+user_info.email[:1]+'P'+str(thunderServiceID)

        # 取出定价,根据coupon,调整amount
        thunderservice_selected = GetThunderservice.get_thunderservice(thunderServiceID)
        amount = thunderservice_selected.price_cn if Country == 'cn' else thunderservice_selected.price
        coupon = data.get('coupon')
        # TODO coupon
        amount = amount

        # 取到thunderservice中对应的desc
        description = thunderservice_selected.description if thunderservice_selected else None

        # expressorder不需要发送订单邮件
        emailNotification = False

        # 添加订单记录
        OrderService.add_order(order_id,user_info.id, thunderServiceID,time.time()*1000,coupon,amount,emailNotification,description)
        db.session.commit()

        # 增加记录到K线图
        KService_action = '201'
        KService.add_record(action=KService_action,parameter1=amount,parameter2='New',timestamp=int(time.time()))

        # 取到要拼接的跳转域名
        website_proxy = SettingService.get_setting_by_name('api_gateway_0')
        if website_proxy:
            url = website_proxy.value
            if url[-1:] != '/':
                url += '/'
            url = url+"app/passwordreset?key="+password_reset
        else:
            raise Exception('5007')

        url = 'lasdjfljdslkasjflkasjflkjdslkfjlksdjafkljdasfkljkljdfkljsdklfjalfkjdlskfj'

        # 生成qrcode
        qr = qrcode.QRCode(
            version=4,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=5,
            border=1
        )
        qr.add_data(url)
        qr.make(fit=True)
        qrimage = qr.make_image()

        byte_io=BytesIO()
        qrimage.save(byte_io, 'png')
        byte_io.seek(0)

        # 方法1:返回base64以后的字符串
        # return {"qr":base64.b64encode(byte_io.getvalue()).decode()}

        # 方法2:或者返回图片字节,可以在浏览器直接加载显示
        res = make_response(byte_io.getvalue()) # 设置响应体
        res.status = '200' # 设置http返回状态码
        res.headers['Content-Type'] = "image/png" # 设置响应头,必要步骤
        # return res

        # 方法3:结合2试试看
        # return u"data:image/png;base64," + base64.b64encode(byte_io.getvalue()).decode('ascii')

        logging.info(f"appPopupHtmlQRcode, response:{res}")
        return res
예제 #6
0
    def process(self):
        trackinginput = self.parameters.get('body')
        user_body = self.parameters.get('body')
        user = UserService.get_user_by_email(user_body['email'])

        logging.info(f"AppUserLoginView,request:{user_body}")
        if not user:
            logging.error("ERROR: AppUserLoginView: 4001")
            return {
                "code": 4001,
                "message": returncode['4001'],
            }, 200

        if (user_body['password'] == user.password):
            # if user.check_password(user_body['password']):
            token = jwt.encode(
                {
                    'user_id':
                    user.id,
                    'exp':
                    datetime.datetime.utcnow() +
                    datetime.timedelta(minutes=300)
                }, flask_app.config['SECRET_KEY'])
            refreshToken = jwt.encode(
                {
                    'user_id':
                    user.id,
                    'type':
                    'refresh',
                    'exp':
                    datetime.datetime.utcnow() +
                    datetime.timedelta(minutes=14400)
                }, flask_app.config['SECRET_KEY'])
            UserService.save_token(user.id, token, refreshToken)
            db.session.commit()

            pwresource = UserService.get_user_service_password(user.id)

            if pwresource:
                thunderservice_password = pwresource.oripassword
            else:
                thunderservice_password = '******'  # 万一没有,就拿这个顶
                logging.info(
                    "AppUserLoginView. This user :{} do not have thunderservice password, use reserved insteed"
                    .format(user_body['email']))

            if str(user.thunderservice_id) not in thunder_service_ID['FUFEI']:
                thunderservice_password = '******'

            routes = RouteService.get_routes_by_group_ID(user.usergroup_id)

            routes_info = list()
            for route in routes:
                routes_info.append({
                    'id': route.id,
                    'servernameEN': route.servernameEN,
                    'servernameCN': route.servernameCN,
                    'remoteAddr': route.domain,
                    'remotePort': route.port,
                    'password': thunderservice_password,
                    "ipv6": route.ipv6,
                    "statusCN": "正常",
                    "statusEN": "Available",
                    "isValid": route.online
                })

            trackingoutput = "成功"
            TrackingService.tracking(trackinginput, trackingoutput, user.id)

            device = user_body.get('deviceType') if user_body.get(
                'deviceType') else 'Unknown'
            thunderservice = user.thunderservice_id
            # if thunderservice in (thunder_service_ID['LOW_SPEED'] or thunder_service_ID['TRIAL']):
            KService_action = '102'
            # thunderservice exits and is a VIP
            if thunderservice and str(
                    thunderservice) in thunder_service_ID['FUFEI']:
                KService_action = '103'
            KService.add_record(action=KService_action,
                                parameter1=user.id,
                                parameter2=device,
                                timestamp=int(time.time()))

            thunderservice_name = thunder_service_name[str(thunderservice)]

            user_info = {
                "user_id":
                user.id,
                "name":
                user.email,
                "period":
                time.strftime("%Y-%m-%d",
                              time.localtime(user.thunderservice_endtime)),
                "invitationcode":
                user.individual_coupon,
                "client_group_id":
                user.thunderservice_id,
                "vip":
                thunderservice_name,
                "vip_en":
                thunder_service_nameEN[str(thunderservice)],
                "vip_level":
                user.usergroup_id,
                "validtime":
                2
            }

            user_mqtt = UserService.gen_user_mqtt(user_id=user.id)

            resp = {
                "code": 200,
                "message": "login success",
                "results": {
                    "user_info": user_info,
                    "mqtt": user_mqtt,
                    "ips": routes_info,
                    "credential": {
                        "token": token.decode('UTF-8'),
                        "refreshToken": refreshToken.decode('UTF-8')
                    }
                }
            }

            logging.info(f"AppUserLoginView success. response:{resp}")
            return resp

        logging.error("ERROR: AppUserLoginView: 4002")
        return {
            "code": 4002,
            "message": returncode['4002'],
        }, 200
예제 #7
0
    def process(self):
        trackinginput = self.parameters.get('body')
        user_body = self.parameters.get('body')
        user = UserService.get_user_by_email(user_body['email'])

        logging.info("UserLoginView,email:{}".format(user_body['email']))
        if not user:
            return {
                "code": 4001,
                "message": returncode['4001'],
            }, 401

        if (user_body['password'] == user.password):
            # if user.check_password(user_body['password']):
            token = jwt.encode(
                {
                    'user_id':
                    user.id,
                    'exp':
                    datetime.datetime.utcnow() +
                    datetime.timedelta(minutes=300)
                }, flask_app.config['SECRET_KEY'])
            refreshToken = jwt.encode(
                {
                    'user_id':
                    user.id,
                    'type':
                    'refresh',
                    'exp':
                    datetime.datetime.utcnow() +
                    datetime.timedelta(minutes=14400)
                }, flask_app.config['SECRET_KEY'])
            UserService.save_token(user.id, token, refreshToken)
            db.session.commit()

            pwresource = UserService.get_user_service_password(user.id)
            if pwresource:
                thunderservice_password = pwresource.oripassword
            else:
                thunderservice_password = '******'  # 万一没有,就拿这个顶
                logging.info(
                    "UserLoginView. This user :{} do not have thunderservice password, use reserved insteed"
                    .format(user_body['email']))

            routes = RouteService.get_routes_by_group_ID(user.usergroup_id)

            routes_info = list()
            for route in routes:
                routes_info.append({
                    'id': route.id,
                    # 'usergroup_id': route.usergroup_id,
                    'sequence': route.sequence,
                    # 'online': route.online,
                    'domain': route.domain,
                    'port': route.port,
                    # 'ipaddress': route.ipaddress,
                    'servernameEN': route.servernameEN,
                    'servernameCN': route.servernameCN,
                    # 'routeStarttime': route.routeStarttime,
                    # 'trafficLimit': route.trafficLimit,
                    # 'trafficUsed': route.trafficUsed,
                    # 'trafficResetDay': route.trafficResetDay,
                    'password': thunderservice_password
                })
            trackingoutput = "成功"
            TrackingService.tracking(trackinginput, trackingoutput, user.id)

            device = user_body.get('device') if user_body.get(
                'device') else 'Unknown'
            thunderservice = user.thunderservice_id
            # if thunderservice in (thunder_service_ID['LOW_SPEED'] or thunder_service_ID['TRIAL']):
            KService_action = '102'
            # thunderservice exits and is a VIP
            if thunderservice and str(
                    thunderservice) in thunder_service_ID['FUFEI']:
                KService_action = '103'
            KService.add_record(action=KService_action,
                                parameter1=user.id,
                                parameter2=device,
                                timestamp=int(time.time()))

            thunderservice_name = thunder_service_name[str(thunderservice)]

            return {
                "code": 200,
                "message": "login success",
                "results": {
                    "user_info": {
                        "user_id": user.id,
                        "thunderservice_id": user.thunderservice_id,
                        "thunderservice_name": thunderservice_name,
                        "thunderservice_endtime": user.thunderservice_endtime,
                        "usergroup_id": user.usergroup_id
                    },
                    "routes": routes_info,
                    "credential": {
                        "token": token.decode('UTF-8'),
                        "refreshToken": refreshToken.decode('UTF-8')
                    }
                }
            }

        return {
            "code": 4002,
            "message": returncode['4002'],
        }, 401
예제 #8
0
    def make_fulfill(order_id):
        from application.services.user_service import UserService
        order = OrderModel.query.filter(OrderModel.id == order_id).first()
        user = UserService.get_user(order.user_id)
        if user:
            from application.models.thunderservice_model import ThunderserviceModel
            if user.thunderservice_id == order.thunderservice_id:

                # 相同的thunderservice,只修改到期时间
                thunderservice = ThunderserviceModel.query.filter(
                    ThunderserviceModel.id == order.thunderservice_id).first()
                duration = thunderservice.duration * 86400
                user.thunderservice_endtime = user.thunderservice_endtime + duration

                # 标记本order已经完成了
                order.thunderserviceStatus = '1'
                db.session.commit()

                # 增加记录到K线图
                KService_action = '201'
                KService.add_record(action=KService_action,
                                    parameter1=order.amount,
                                    parameter2='Paid',
                                    timestamp=int(time.time()))

                return True
            else:
                #取user当前的thunderservice是否是付费service,如果是,记录还剩多少时间。
                timeLeft = 0
                if str(user.thunderservice_id) in thunder_service_ID['FUFEI']:
                    timeLeft = user.thunderservice_endtime - int(time.time())
                if timeLeft < 0:
                    timeLeft = 0

                thunderservice = ThunderserviceModel.query.filter(
                    ThunderserviceModel.id == order.thunderservice_id).first()
                user_updatedata = {
                    "thunderservice_id":
                    order.thunderservice_id,
                    "thunderservice_client_amount":
                    thunderservice.defaultClientAmount,
                    "thunderservice_traffic_amount":
                    thunderservice.defaultTrafficAmount,
                }
                thunderservice_starttime = time.time()
                thunderservice_endtime = time.time()
                if thunderservice.id != 1:
                    thunderservice_endtime = thunderservice_endtime + thunderservice.duration * 86400 + timeLeft

                UserService.modify_user_by_id(order.user_id,
                                              update_data=user_updatedata)
                db.session.commit()

                UserService.active_thunderservice(order.user_id,
                                                  order.thunderservice_id,
                                                  thunderservice_starttime,
                                                  thunderservice_endtime)
                db.session.commit()

                order.thunderserviceStatus = '1'
                db.session.commit()

                # 增加记录到K线图
                KService_action = '201'
                KService.add_record(action=KService_action,
                                    parameter1=order.amount,
                                    parameter2='Paid',
                                    timestamp=int(time.time()))
                return True
        else:
            return False