示例#1
0
def get_online_status():
    user_key = RedisClient.get_user_key(g.user_id)
    record_key = redis_cache_client.get(user_key)
    if record_key is None:
        return fail(HTTP_OK, u'当前用户没有上机信息', 0)

    charging = redis_cache_client.get(record_key)
    if charging is None:
        return fail(HTTP_OK, u'当前用户没有上机信息', 0)

    return success(WindowsService.get_current_time_charging(charging))
示例#2
0
def get_jsapi_signature():
    if not request.is_json:
        log.warn("参数错误...")
        return fail(HTTP_OK, u"need application/json!!")

    url = request.json.get('url')
    if url is None:
        log.warn("没有传入url 参数: {}".format(
            json.dumps(request.json, ensure_ascii=False)))
        return fail(HTTP_OK, u"没有传入url参数!")

    jsapi_ticket = redis_cache_client.get(WECHAT_JSAPI_TICKET_KEY)
    if jsapi_ticket is None:
        log.warn("没有jsapi_ticket: user_id = {}".format(g.user_id))
        return fail(HTTP_OK, u'没有jsapi_ticket')

    import time
    timestamp = int(time.time())
    nonceStr = wx_pay.nonce_str(31)
    signature = gen_jsapi_signature(timestamp, nonceStr, jsapi_ticket, url)
    config = {
        'debug': settings.DEBUG,
        'appId': settings.WECHAT_APP_ID,
        'timestamp': str(timestamp),
        'nonceStr': nonceStr,
        'signature': signature,
        'jsApiList': ['scanQRCode']
    }

    log.info("当前user_id获取的wx.config = {}".format(
        json.dumps(config, ensure_ascii=False)))
    return success(config)
示例#3
0
    def online(
            cls,
            openid,
            # 上线时间 self.ctime
            ctime,
            # 地址 结构体对象
            address,
            # 余额 分
            balance,
            # 计费 价格 分钟 / 分
            charge_mode):
        access_token = redis_cache_client.get(WECHAT_ACCESS_TOKEN_KEY)
        if access_token is None:
            log.error("access_token 为None,刷新token进程异常!!!")
            return
        online_time = ctime.strftime('%Y-%m-%d %H:%M:%S')
        address_str = address.get_full_address()

        account_url = url_for("wechat.menu", name="account", _external=True)
        log.info("当前用户中心地址: url = {}".format(account_url))
        if WechatTemplate.online(access_token,
                                 openid,
                                 online_time,
                                 address_str,
                                 balance,
                                 charge_mode,
                                 url=account_url):
            log.info("发送微信上机通知成功: openid = {}".format(openid))
        else:
            log.warn("发送微信上机通知失败: openid = {}".format(openid))
示例#4
0
def get_wechat_user_info(openid):
    # 默认设置是未关注状态
    subscribe, nick_name, head_img_url = 0, '', ''

    if openid is None:
        log.error("openid 为None,未知异常!!!")
        return subscribe, nick_name, head_img_url

    access_token = redis_cache_client.get(WECHAT_ACCESS_TOKEN_KEY)
    if access_token is None:
        log.error("access_token 为None,刷新token进程异常!!!")
        return subscribe, nick_name, head_img_url

    url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token={}&openid={}&lang=zh_CN'.format(
        access_token, openid)
    try:
        resp = requests.get(url, verify=False, timeout=30)
        if resp.status_code != 200:
            log.error("获取用户信息访问状态码不正确: status_code = {} url = {}".format(
                resp.status_code, url))
            return subscribe, nick_name, head_img_url

        log.info("当前获取的用户信息为: text = {}".format(resp.text))

        json_data = json.loads(resp.text)
        errcode = json_data.get('errcode')
        if errcode is not None:
            log.error("获取用户信息错误码不正常: {}".format(resp.text))
            return subscribe, nick_name, head_img_url

        subscribe = json_data.get('subscribe')
        if subscribe is None:
            log.error("获取用户信息关注状态不正常: {}".format(resp.text))
            return 0, nick_name, head_img_url

        # 如果用户关注了 才去获取昵称和头像信息
        if subscribe == 1:
            # 获得用户昵称 和头像信息
            nick_name = json_data.get('nickname', '')
            head_img_url = json_data.get('headimgurl', '')
            if isinstance(nick_name, basestring):
                nick_name = nick_name.strip()
            else:
                nick_name = ''
            if isinstance(head_img_url, basestring):
                head_img_url = head_img_url.strip()
            else:
                head_img_url = ''
            log.info(
                "当前用户关注了公众号, 能够获取昵称和头像: openid = {} nick_name = {} head_img_url = {}"
                .format(openid, nick_name, head_img_url))
        else:
            log.warn(
                "当前用户并没有关注公众号,无法获取用户信息: openid = {} subscribe = {}".format(
                    openid, subscribe))
    except Exception as e:
        log.error("访问微信用户链接失败: url = {}".format(url))
        log.exception(e)
    return subscribe, nick_name, head_img_url
示例#5
0
    def online_recharge(user_id, total_fee):
        # 先获得用户缓存的信息
        user_key = RedisClient.get_user_key(user_id)

        # todo 这里需要加锁, 否则扣费下机时会有影响
        lock = DistributeLock(user_key, redis_cache_client)

        try:
            lock.acquire()
            record_key = redis_cache_client.get(user_key)
            if record_key is None:
                log.info("当前用户没有在线 record_key = None, 不需要同步在线数据: user_id = {}".
                         format(user_id))
                return

            charge_str = redis_cache_client.get(record_key)
            if charge_str is None:
                log.info(
                    "当前用户没有在线 charging = None, 不需要同步在线数据: user_id = {}".format(
                        user_id))
                return

            try:
                charge_dict = json.loads(charge_str)
                if charge_dict is None:
                    log.error("解析json数据失败: {}".format(charge_str))
                    return

                balance_account = charge_dict.get('balance_account')
                if not isinstance(balance_account, int):
                    log.error(
                        "balance_account 数据类型不正确: {}".format(balance_account))
                    return

                charge_dict['balance_account'] = balance_account + total_fee
                redis_cache_client.set(record_key, json.dumps(charge_dict))

                log.info(
                    "同步修改redis中用户余额信息成功! user_id = {} account = {}".format(
                        user_id, balance_account + total_fee))
            except Exception as e:
                log.error("解析json数据失败: {}".format(charge_str))
                log.exception(e)
        finally:
            lock.release()
示例#6
0
    def do_offline_order_by_device_code(device_code):
        device_code_key = RedisClient.get_device_code_key(device_code)
        record_key = redis_cache_client.get(device_code_key)
        if record_key is None:
            log.error("当前通过device_code = {} 下机失败, 没有在redis中找到对应的上机信息".format(
                device_code))
            return False

        # 发送下机指令
        return WindowsService.do_offline_order(record_key)
示例#7
0
def wechat_offline():
    user_key = RedisClient.get_user_key(g.user_id)
    record_key = redis_cache_client.get(user_key)
    if record_key is None:
        return success({
            'status':
            0,
            'msg':
            "logout failed! reason: user device is already offline"
        })

    charging = redis_cache_client.get(record_key)
    if charging is None:
        return success({
            'status':
            0,
            'msg':
            "logout failed! reason: user device is already offline"
        })

    return WindowsService.do_offline(charging)
示例#8
0
    def recharge_remind(cls, openid, pay_time, account):
        access_token = redis_cache_client.get(WECHAT_ACCESS_TOKEN_KEY)
        if access_token is None:
            log.error("access_token 为None,刷新token进程异常!!!")
            return

        recharge_time = pay_time.strftime('%Y-%m-%d %H:%M:%S')
        if WechatTemplate.recharge_remind(access_token, openid, recharge_time,
                                          account):
            log.info("发送微信充值通知成功: openid = {}".format(openid))
        else:
            log.warn("发送微信充值通知失败: openid = {}".format(openid))
示例#9
0
def check_connect():
    if not request.is_json:
        log.warn("参数错误...")
        return fail(HTTP_OK, u"need application/json!!")

    device_code = request.json.get('device_code')
    if device_code is None:
        return fail(HTTP_OK, u"not have device_code!!!")

    # 获得设备使用状态
    device_status = DeviceService.get_device_status(device_code)
    if device_status is None:
        return success({
            'status': -1,
            'device_status': device_status,
            'msg': "not deploy"
        })

    # 保持心跳
    DeviceService.keep_device_heart(device_code)

    # 从维护状态跳转到空闲状态
    if device_status == DeviceStatus.STATUS_MAINTAIN:
        log.info("当前状态为维护状态,设备已经有心跳需要重新设置空闲状态!")
        DeviceService.status_transfer(device_code, device_status,
                                      DeviceStatus.STATUE_FREE)

        # 重新获得设备状态
        device_status = DeviceService.get_device_status(device_code)

    device_code_key = RedisClient.get_device_code_key(device_code)
    record_key = redis_cache_client.get(device_code_key)
    if record_key is None:
        return success({
            'status': 0,
            'device_status': device_status,
            'msg': "not login"
        })

    return success({
        "status": 1,
        "token": record_key,
        'device_status': device_status,
        "msg": "login successed!"
    })
示例#10
0
def windows_offline():
    if not request.is_json:
        log.warn("参数错误...")
        return fail(HTTP_OK, u"need application/json!!")

    token = request.json.get('token')
    if token is None:
        return fail(HTTP_OK, u"not have token!!!")

    charging = redis_cache_client.get(token)
    if charging is None:
        return success({
            'status':
            0,
            'msg':
            "logout failed! reason: user device is already offline"
        })

    return WindowsService.do_offline(charging)
示例#11
0
    def offline(
            cls,
            openid,
            record,
            # 余额 分
            balance):

        access_token = redis_cache_client.get(WECHAT_ACCESS_TOKEN_KEY)
        if access_token is None:
            log.error("access_token 为None,刷新token进程异常!!!")
            return

        offline_time = record.end_time.strftime('%Y-%m-%d %H:%M:%S')
        address_str = record.get_full_address()
        if WechatTemplate.offline(access_token, openid, offline_time,
                                  address_str, balance, record.cost_time):
            log.info("发送微信下机通知成功: openid = {}".format(openid))
        else:
            log.warn("发送微信下机通知失败: openid = {}".format(openid))
示例#12
0
def keep_alive():
    if not request.is_json:
        log.warn("参数错误...")
        return fail(HTTP_OK, u"need application/json!!")

    record_key = request.json.get('token')
    if record_key is None:
        return fail(HTTP_OK, u"not have token!!!")

    device_code = request.json.get('device_code')
    if device_code is None:
        log.error(
            "无法保持心跳, 没有传入device_code: record_key = {}".format(record_key))
        return fail(HTTP_OK, u"not have device_code!!!")

    # 保持心跳
    DeviceService.keep_device_heart(device_code)

    charging = redis_cache_client.get(record_key)
    if charging is None:
        return success({
            "status": 0,
            "msg": "keepalive failed!reason:token invalid"
        })

    # 获得keep_alive_key 更新最新存活时间
    user_online_key = RedisClient.get_user_online_key(record_key)

    # 设置最新存活时间 最多存在五分钟
    redis_cache_client.setex(user_online_key, settings.MAX_LOST_HEART_TIME,
                             int(time.time()))

    return success({
        "status": 1,
        "msg": "keepalive success",
        "data": WindowsService.get_current_time_charging(charging)
    })
示例#13
0
def qr_code_online(device_code):
    # # 当前用户没有登录
    # LOGIN_ERROR_BIND = -1
    # # 当前用户已经被删除
    # LOGIN_ERROR_DELETE = -2
    # # 当前用户被禁止使用
    # LOGIN_ERROR_FORBID = -3
    # # 当前设备不存在
    # LOGIN_ERROR_NOT_FIND = -4
    # # 用户余额不足
    # LOGIN_ERROR_NOT_SUFFICIENT_FUNDS = -5
    # # 上机失败 未知错误
    # LOGIN_ERROR_UNKNOW = -6
    # # 设备已经在使用了
    # LOGIN_ERROR_DEVICE_IN_USEING = -7
    # # 当前用户已经在使用上机了,但是不是当前设备在使用
    # LOGIN_ERROR_USER_IN_USEING = -8
    # # 当前设备不处于空闲状态,不能上机
    # LOGIN_ERROR_DEVICE_NOT_FREE = -9

    scan_from = request.args.get('from')
    # 登录链接
    login_url = url_for("wechat.menu", name="login")
    # 通过微信二维码扫描则需要判断当前用户是否已经关注公众号
    if scan_from != 'playing':
        # # 初始化用户关注信息
        # subscribe, nick_name, head_img_url = 0, '', ''

        openid = session.get('openid', None)
        # 如果不是微信二维码扫描 则跳转到登录界面
        if openid is None:
            log.info("当前扫描登录没有openid,需要跳转到登录界面..")
            return redirect(login_url)

        # 获得用户的关注状态 以及头像和昵称信息
        subscribe, nick_name, head_img_url = get_wechat_user_info(openid)
        # 如果用户没有关注微信号 直接跳转到关注页面
        if subscribe != 1:
            log.info("当前用户没有关注公众号: subscribe = {} openid = {}".format(
                subscribe, openid))
            return redirect(ATTENTION_URL)

        # 如果当前用户已经关注 则直接跳转到 祥基指定的链接 2017-10-13 15:26:00
        url = '#/playing?code={}'.format(device_code)
        log.info("当前用户已经关注了公众号,跳转链接: {}".format(url))
        return redirect(url)

    user_id_cookie = session.get('u_id')
    if user_id_cookie is None:
        log.warn("当前session中没有u_id 信息,需要登录...")
        return fail(HTTP_OK, u'当前用户没有登录', LOGIN_ERROR_BIND)

    user_id = decode_user_id(user_id_cookie)
    if user_id is None:
        log.warn(
            "当前用户信息被篡改,需要重新登录: user_id_cookie = {}".format(user_id_cookie))
        return fail(HTTP_OK, u'当前用户登录信息被篡改, 不能登录', LOGIN_ERROR_BIND)

    # 获得用户信息
    user = get_current_user(user_id)
    if user is None:
        log.warn("当前user_id还未绑定手机号码: user_id = {}".format(user_id))
        return fail(HTTP_OK, u"用户还绑定手机号码登录!", LOGIN_ERROR_BIND)

    # 如果当前用户 被禁用 则不能上机
    if user.deleted:
        log.warn("当前用户已经被删除了,无法上机: user_id = {}".format(user.id))
        return fail(HTTP_OK, u"当前用户已经被删除了,不能上机", LOGIN_ERROR_DELETE)

    # 判断当前用户是否已经被禁用了
    if user.state == 'unused':
        log.warn("当前用户已经被禁用了,无法上机: user_id = {}".format(user.id))
        return fail(HTTP_OK, u"当前用户已经被禁用了,不能上机", LOGIN_ERROR_FORBID)

    # 获得设备信息
    device = DeviceService.get_device_by_code(device_code=device_code)
    if device is None:
        log.warn("当前设备号没有对应的设备信息: device_code = {}".format(device_code))
        return fail(HTTP_OK, u"设备信息异常,设备不存在", LOGIN_ERROR_NOT_FIND)

    # 获得最新费率
    charge_mode = DeviceService.get_charge_mode(device)
    log.info("当前费率: charge_mode = {}".format(charge_mode))

    # 判断用户是否余额充足 如果小于一分钟不能上机
    if user.balance_account < charge_mode:
        log.info(
            "用户余额不足,不能上机: user_id = {} device_id = {} account = {}".format(
                user.id, device.id, user.balance_account))
        return fail(HTTP_OK, u"用户余额不足,不能上机!", LOGIN_ERROR_NOT_SUFFICIENT_FUNDS)

    # 判断是否已经在redis中进行记录
    record_key = RedisClient.get_record_key(user.id, device.id)
    # 获得用户上机key
    user_key = RedisClient.get_user_key(user.id)
    # 获得设备上机key
    device_key = RedisClient.get_device_key(device.id)

    # 判断是否已经登录了
    charging = redis_cache_client.get(record_key)
    if charging is None:

        # 判断当前设备是否已经在使用了
        if redis_cache_client.get(device_key):
            log.warn("当前设备{}已经在被使用,但是用户ID = {}又在申请".format(device.id, user.id))
            return fail(HTTP_OK, u"当前设备已经在使用上机了,但是不是当前用户在使用!",
                        LOGIN_ERROR_DEVICE_IN_USING)

        # 判断当前用户是否已经上机了
        if redis_cache_client.get(user_key):
            log.warn("当前用户{}已经在上机,但是又在申请当前设备ID = {}".format(
                user.id, device.id))
            return fail(HTTP_OK, u"当前用户已经在使用上机了,但是不是当前设备在使用!",
                        LOGIN_ERROR_USER_IN_USING)

        # 判断当前设备是否处于空闲状态 且设备必须处于在线状态
        device_status = DeviceService.get_device_status(device)
        device_alive = DeviceService.get_device_alive_status(device)
        if device_status != DeviceStatus.STATUE_FREE or device_alive != Device.ALIVE_ONLINE:
            log.warn("当前设备不处于空闲状态,不能上机: device_id = {} state = {} alive = {}".
                     format(device.id, device_status, device_alive))
            return fail(HTTP_OK, u"当前设备不处于空闲状态,或者当前设备不在线,不能上机!",
                        LOGIN_ERROR_DEVICE_NOT_FREE)

        # 判断当前设备是否正在更新 或者正在自检,这种状态下不能够登录上机
        current_update_state = DeviceService.get_update_state(device)
        if current_update_state == DeviceUpdateStatus.UPDATE_ING or \
                        current_update_state == DeviceUpdateStatus.UPDATE_CHECK:
            log.info(
                "当前设备正在更新或者自检中,不能登录: device_id = {} current_update_state = {}".
                format(device.id, current_update_state))
            return fail(HTTP_OK, u"当前设备处于自检或者更新中,不能上机!",
                        LOGIN_ERROR_DEVICE_NOT_FREE)

        log.info("用户还未上机可以进行上机: user_id = {} device_id = {}".format(
            user.id, device.id))
        if not WindowsService.do_online(user, device, charge_mode):
            log.warn("上机记录创建失败,上机失败: user_id = {} device_id = {}".format(
                user.id, device.id))
            return fail(HTTP_OK, u"上机异常!!", LOGIN_ERROR_UNKNOW)

    log.info("来自微信端游戏仓界面扫描: user_id = {} device_id = {}".format(
        user.id, device.id))
    return success()
示例#14
0
def user_offline():
    if not request.is_json:
        log.warn("参数错误...")
        return fail(HTTP_OK, u"need application/json!!")

    user_id = request.json.get('user_id')
    device_code = request.json.get('device_code')
    device_id = request.json.get('device_id')

    log.info("当前强制下机user_id = {}".format(user_id))
    log.info("当前强制下机device_code = {}".format(device_code))
    log.info("当前强制下机device_id = {}".format(device_id))

    if user_id is not None:
        user_key = RedisClient.get_user_key(user_id)
        record_key = redis_cache_client.get(user_key)
        if record_key is None:
            return success({
                'status':
                0,
                'msg':
                "logout failed! reason: user device is already offline"
            })

        charging = redis_cache_client.get(record_key)
        if charging is None:
            return success({
                'status':
                0,
                'msg':
                "logout failed! reason: user device is already offline"
            })
        log.info("通过user_id下机: user_id = {}".format(user_id))
        return WindowsService.do_offline(charging)

    if device_code is not None:
        device_code_key = RedisClient.get_device_code_key(device_code)
        record_key = redis_cache_client.get(device_code_key)
        if record_key is not None:
            charging = redis_cache_client.get(record_key)
            if charging is None:
                return success({
                    'status':
                    0,
                    'msg':
                    "logout failed! reason: user device is already offline"
                })
            log.info("通过device_code下机: device_code = {}".format(device_code))
            return WindowsService.do_offline(charging)

    if device_id is not None:
        device_key = RedisClient.get_device_key(device_id)

        record_key = redis_cache_client.get(device_key)
        if record_key is None:
            return success({
                'status':
                0,
                'msg':
                "logout failed! reason: user device is already offline"
            })

        charging = redis_cache_client.get(record_key)
        if charging is None:
            return success({
                'status':
                0,
                'msg':
                "logout failed! reason: user device is already offline"
            })
        log.info("通过device_id下机: device_id = {}".format(device_id))
        return WindowsService.do_offline(charging)

    return success(u'当前参数没有使任何机器或用户下机')
示例#15
0
    def do_offline(charging):

        # offline_lock_key = None
        lock = None
        if charging is None:
            log.error("charging is None 下机异常!!")
            return fail(HTTP_OK, u"下机异常!")

        try:
            charge_dict = json.loads(charging)
            record_id = charge_dict.get('id')
            user_id = charge_dict.get('user_id')
            device_id = charge_dict.get('device_id')
            charge_mode = charge_dict.get('charge_mode')
            device_code = charge_dict.get('device_code')
            openid = charge_dict.get('openid')
            log.info(
                "当前下线信息: user_id = {} device_id = {} charge_mode = {} device_code = {}"
                .format(user_id, device_id, charge_mode, device_code))

            # 获得用户上线key
            user_key = RedisClient.get_user_key(user_id)

            #  下机需要加锁
            lock = DistributeLock(user_key, redis_cache_client)

            log.info("开始加锁下机: user_key = {}".format(user_key))

            # 加锁下机
            lock.acquire()

            # 判断是否已经在redis中进行记录
            record_key = RedisClient.get_record_key(user_id, device_id)
            if redis_cache_client.get(record_key) is None:
                log.warn("当前用户或者设备已经下机: user_id = {} device_id = {}".format(
                    user_id, device_id))
                return success({'status': 1, 'msg': 'logout successed!'})

            # 结账下机
            result, record, user = WindowsService.cal_offline(
                user_id=user_id,
                device_id=device_id,
                record_id=record_id,
                charge_mode=charge_mode)
            if not result:
                log.error(
                    "下机扣费失败: user_id = {} device_id = {} charge_mode = {}".
                    format(user_id, device_id, charge_mode))
                return fail(HTTP_OK, u"下机失败!")

            # 获得设备上线key
            device_key = RedisClient.get_device_key(device_id)
            # 获得当前设备token
            device_code_key = RedisClient.get_device_code_key(device_code)
            # 获得keep_alive_key 更新最新存活时间
            user_online_key = RedisClient.get_user_online_key(record_key)

            # 从redis中删除上机记录
            redis_cache_client.delete(record_key)
            redis_cache_client.delete(user_key)
            redis_cache_client.delete(device_key)
            redis_cache_client.delete(device_code_key)
            redis_cache_client.delete(user_online_key)
            is_success = True
        except Exception as e:
            log.error("数据解析失败: {}".format(charging))
            log.exception(e)
            return fail(HTTP_OK, u"数据解析失败!!")
        finally:
            # 解锁
            if lock is not None:
                lock.release()
                log.info("下机完成: lock_key = {}".format(lock.lock_key))

        # 如果成功则进行下机提醒
        if is_success and openid is not None:
            TemplateService.offline(openid, record, user.balance_account)

        log.info("下机成功: user_id = {} device_id = {}".format(
            user_id, device_id))
        return success({'status': 1, 'msg': 'logout successed!'})