示例#1
0
def _check_code(uuid, code):
    if rd.hget(uuid, 'code').decode('utf8') != code:
        raise Forbidden('wrong captcha')
    rd.hmset(uuid, {
        'success': 1,
    })
    rd.expire(uuid, 60)
示例#2
0
def create_name():
    """Create nick name for user to join a room
    Add user info to session and redis

    Args:
        nick_name: the user's nick name
        room_id: the id of room

    Returns:
        uid: the user_id to identify the user
        nick_name: the user's nick_name
    """
    json_content = request.get_json()
    if 'uid' not in session:
        session['uid'] = str(uuid.uuid4())
    nick_name = json_content['nick_name']
    room_id = json_content['room_id']
    room = Room.query.get(room_id)
    if room is None:
        session.pop(room_id, None)
        return jsonify(api_format(status.HTTP_404_NOT_FOUND, "no such room"))
    session[room_id] = nick_name
    redis.hmset(room_id + ':' + session['uid'], {
        'uid': session['uid'],
        'nick_name': nick_name
    })
    return jsonify(
        api_format(status.HTTP_200_OK, "ok", {
            'uid': session['uid'],
            'nick_name': nick_name
        }))
示例#3
0
def update_session(user_id, next_filter=None, **kwargs):
    if next_filter is not None:
        redis.hset(user_id, 'next_filter', next_filter)
    params = {k: v for k, v in kwargs.items() if k in FILTERS}
    if params:
        redis.hmset(user_id, params)
    redis.expire(user_id, app.config['EXPIRE'])
示例#4
0
def redis_add():
    goodsTitles = request.get_json()
    redis.delete(goodsTitles['title'])

    address_id = Postgres.return_address_and_id(goodsTitles['title'])

    redis.hmset(goodsTitles['title'], address_id)
    return '.'
示例#5
0
def process_city(sender_id, message_text):
    res = get_restaurants(sender_id, city=message_text)
    ids = [r['id'] for r in res]
    if ids:
        show_results(sender_id, res)
        redis.hmset(sender_id, {'filtered_ids': ','.join([str(i) for i in ids]),
                                'filters_applied': '1',
                                'next_question': 2})
示例#6
0
def start_session(sender_id, message_text):
    # if 'hi' in message_text.lower():
    #     redis.set(sender_id, {'started_at': int(time.time())})
    #     send_text_message(sender_id, 'Hi! Nice to meet you!')
    # else:
    #     send_text_message(sender_id, 'Say hi!')
    redis.hmset(sender_id, {'started_at': int(time.time())})
    redis.expire(sender_id, 300)
    return process_city(sender_id, message_text)
示例#7
0
def pushtext():
    """ 推送文字信息 """
    form = TextForm()
    wechat = init_wechat_sdk()
    client = wechat['client']

    pushtext = Pushtext(author_id=current_user.id)
    content = current_app.config['CONFIRMED_WARNNING'] % form.textarea.data

    group_name = form.group.data
    to_group = Group.query.get(form.group.data)
    to_user = []
    to_user_id = []
    for u in to_group.wechatusers:
        to_user.append(u.openid)
        to_user_id.append(u.id)
    try:
        send_result = client.message.send_mass_text(to_user, content)
        current_app.logger.warning(u'send result:%s' % send_result)
        media_id = send_result['msg_id']
        mass_status = client.message.get_mass(media_id)

        pushtext.content = content
        pushtext.media_id = media_id
        pushtext.to_group = Group.query.get(form.group.data)
        pushtext.to_confirmed = json.dumps(to_user_id)
        pushtext.save()

        #  保存最新一条推送的时间
        #  FIXME 这两个是不是重复了
        redis.set("wechat:last_push_time", time.strftime('%Y-%m-%d %H:%M:%S'))
        redis.hmset(
            "wechat:last_push", {
                "create_time": time.strftime('%Y-%m-%d %H:%M:%S'),
                "to_confirmed": to_user_id,
                "media_id": media_id,
                "pushtype": 'text'
            })

        #  保存信息到redis
        redis_pushtext_prefix = "wechat:pushtext:" + media_id
        redis.hmset(
            redis_pushtext_prefix, {
                "media_id": media_id,
                "to_user": to_user,
                "create_time": time.strftime('%Y-%m-%d %H:%M:%S'),
                "to_confirmed": to_user_id
            })

        current_app.logger.warning('to_user_list:%s' % to_user)
        current_app.logger.warning(u'发送情况:%s' % mass_status)

    except Exception as e:
        print(e)
    return redirect(url_for('wechat.user'))
示例#8
0
def get_mail_captcha_api():
    form = MailForm().validate_for_api()
    uuid = 'M-' + _generate_uuid()
    code = _generate_code()
    rd.hmset(uuid, {
        'code': code,
        'success': 0,
    })
    rd.expire(uuid, 3600)
    send_verification_mail(form.mail.data, code)
    return jsonify({'code': 0, 'data': {'uuid': uuid}})
示例#9
0
def get_image_captcha_api():
    uuid = 'I-' + _generate_uuid()
    code = _generate_code()
    rd.hmset(uuid, {
        'code': code,
        'success': 0,
    })
    rd.expire(uuid, 300)
    img = ImageCaptcha()
    image = img.generate_image(code)
    base64_str = _image_to_base64(image)
    return jsonify({'code': 0, 'data': {'image': base64_str, 'uuid': uuid}})
示例#10
0
def make_cache_rate(rates, providers):
    ts_now = datetime.datetime.now().timestamp()

    payload = {
        'time_stamp': str(ts_now),
        'rates': json.dumps(rates),
        'providers': json.dumps([provider.url for provider in providers])
    }
    redis.hmset('rate_ten_mins', payload)
    redis.expire('rate_ten_mins', 10 * 60)
    redis.hmset('daily_ ' + str(ts_now), payload)
    redis.expire('daily_ ' + str(ts_now), 60 * 60 * 24)
示例#11
0
    def on_finish(self):
        if self.result:
            base_log = f"IP:{self.request.remote_ip},用户:{self.data['account']}"
            if self.result['status_code'] == 200:
                key = f"token:{self.result['data']['token']}"
                redis.hmset(key, {"url": self.data['url'], "account": self.data["account"]})
                redis.expire(key, 3600)

                # 获取用户信息
                user_client = self.school.get_auth_user(self.data['account'])['data']
                user_info = user_client.get_info()
                logger.info("%s,绑定成功:%s", base_log, user_info['real_name'])
                # TODO 保存用户信息
            else:
                logger.warning("%s,错误信息:%s", base_log, self.result['data'])
示例#12
0
def save_position(data):
    redisKey = 'device_{}'.format(data['device']['id'])

    ignition = data['position']['attributes'][
        'ignition'] if 'ignition' in data['position']['attributes'] else None
    alarm = data['position']['attributes']['alarm'] if 'alarm' in data[
        'position']['attributes'] else None
    io202 = data['position']['attributes']['io202'] if 'io202' in data[
        'position']['attributes'] else None
    fuel = data['position']['attributes']['fuel'] if 'fuel' in data[
        'position']['attributes'] else None
    totalDistance = data['position']['attributes'][
        'totalDistance'] if 'totalDistance' in data['position'][
            'attributes'] else None

    if data['device']['id'] == 10836:
        redis.rpush(
            'fuel_devices',
            json.dumps({
                'deviceid': data['device']['id'],
                'fuel': fuel,
                'serverTime': data['position']['serverTime'],
                'fixTime': data['position']['fixTime'],
                'temp': io202,
                'latitude': data['position']['latitude'],
                'longitude': data['position']['longitude'],
                'name': data['device']['name']
            }))

    redis.hmset(
        redisKey, {
            'id': data['device']['id'],
            'uniqueId': data['device']['uniqueId'],
            'name': data['device']['name'],
            'serverTime': data['position']['serverTime'],
            'fixTime': data['position']['fixTime'],
            'latitude': data['position']['latitude'],
            'longitude': data['position']['longitude'],
            'speed': data['position']['speed'],
            'course': data['position']['course'],
            'totalDistance': totalDistance,
            'lastUpdate': data['device']['lastUpdate'],
            'ignition': json.dumps(ignition),
            'alarm': json.dumps(alarm),
            'pushedtoServer': json.dumps(False),
            'geofenceIds': json.dumps(data['device']['geofenceIds']),
            'posAttr': json.dumps(data['position']['attributes'])
        })
示例#13
0
def set_user_library_info(openid, libraryid, librarypwd):
    """ 写入绑定的图书馆帐号 """
    redis_prefix = "wechat:user:"******"libraryid": libraryid,
        "librarypwd": librarypwd
    })
示例#14
0
def set_user_student_info(openid, studentid, studentpwd):
    """ 写入绑定的教务管理系统帐号 """
    redis_prefix = "wechat:user:"******"studentid": studentid,
        "studentpwd": studentpwd
    })
示例#15
0
    def set(cls, id, **fields):
        """
        set value for hash fields in {model}:{id} and add {id} to {model}:all
        """

        key = rkey(cls, id)
        cls._field_add('all', id)

        return redis.hmset(key, fields)
示例#16
0
def set_user_realname_and_classname(openid, realname, classname):
    """ 查询成绩(绑定)的时候可以写入用户的真实姓名和班级 """
    redis_prefix = "wechat:user:"******"realname": realname,
            "classname": classname
        })
示例#17
0
def get_user_library_info(openid):
    """ 获取绑定的图书馆帐号 """
    redis_prefix = "wechat:user:"******"libraryid": auth_info.libraryid,
                    "librarypwd": auth_info.librarypwd,
                })
            user_info_cache['libraryid'] = auth_info.libraryid
            user_info_cache['librarypwd'] = auth_info.librarypwd
            return user_info_cache
        else:
            return False
示例#18
0
def get_user_info(openid):
    """ 获取绑定的教务系统帐号 """
    redis_prefix = "wechat:user:"******"studentid": auth_info.studentid,
                    "studentpwd": auth_info.studentpwd,
                })
            user_info_cache['studentid'] = auth_info.studentid
            user_info_cache['studentpwd'] = auth_info.studentpwd
            return user_info_cache
        else:
            return False
示例#19
0
    def save(self):
        """
        Save the current alert to database.
        """
        email_sha = sha1(self.email).hexdigest()

        saved = bool(
            redis.sadd("sl:alert:ids", self.sha) and
            redis.sadd("sl:account:{}:alerts".format(email_sha), self.sha) and
            redis.hmset("sl:alert:{}".format(self.sha), self.to_dict())
        )

        if not saved:
            raise SleekException("Could not save current alert.")
示例#20
0
def create_name():
    """Create nick name for user to join a room
    Add user info to session and redis

    Args:
        nick_name: the user's nick name
        room_id: the id of room

    Returns:
        uid: the user_id to identify the user
        nick_name: the user's nick_name
    """
    json_content = request.get_json()
    if 'uid' not in session:
        session['uid'] = str(uuid.uuid4())
    nick_name = json_content['nick_name']
    room_id = json_content['room_id']
    room = Room.query.get(room_id)
    if room is None:
        session.pop(room_id, None)
        return jsonify(api_format(status.HTTP_404_NOT_FOUND, "no such room"))
    session[room_id] = nick_name
    redis.hmset(room_id + ':' + session['uid'], {'uid': session['uid'], 'nick_name': nick_name})
    return jsonify(api_format(status.HTTP_200_OK, "ok", {'uid': session['uid'], 'nick_name': nick_name}))
示例#21
0
文件: user.py 项目: volnt/sleekstatus
    def save(self, register=False):
        """
        Save the current user infos to database.
        """
        sha = sha1(self.email).hexdigest()
        infos = self.to_dict()
        infos["plan"] = infos["plan"]["id"] if infos["plan"] else None

        if not redis.hmset("sl:account:{}".format(sha), infos):
            raise SleekException("Could not save current user.", 401)
        
        if register:
            try:
                send_email.delay(
                    "*****@*****.**", "Welcome to sleekstatus !",
                    "Welcome message", [self.email]
                )
            except:
                pass # Cannot send email
示例#22
0
文件: score.py 项目: panye7606/wechat
def get_info(openid, studentid, studentpwd, check_login=False):
    """ 登录教务系统, 并保存必要信息"""
    redis_prefix = "wechat:user:score:"
    redis_auth_prefix = "wechat:user:auth:score:"
    user_score_cache = redis.get(redis_prefix + openid)
    if user_score_cache and not check_login:
        #  数据类型转换(把字符串转换成字典)
        content = ast.literal_eval(user_score_cache.decode())
        wechat_custom.send_news(openid, content)

    else:
        # 缓存不存在成绩信息, 建立会话, 模拟登录爬取信息
        session = requests.Session()
        session.headers.update({
            'User-Agent': random.choice(USER_AGENTS),
            'Content-Type': 'application/x-www-form-urlencoded',
            'Referer': current_app.config['JW_LOGIN_URL']
        })
        # 登录获取 cookie
        proxy = False
        login_url = current_app.config['JW_LOGIN_URL']
        score_url = current_app.config['JW_SCORE_URL']
        try:
            res = login(studentid, studentpwd, login_url, session, proxy)
        except Exception as e:
            # 外网查询超时,切换内网代理查询
            current_app.logger.warning(u'外网查询出错:%s' % e)
            proxy = True
            login_url = current_app.config['JW_LOGIN_URL_LAN']
            score_url = current_app.config['JW_SCORE_URL_LAN']
            session.headers.update({'Referer': login_url})
            try:
                res = login(studentid, studentpwd, login_url, session, proxy)
            except Exception as e:
                current_app.logger.warning(u'内网查询出错:%s' % e)
                res = None

        #  登录没东西返回可判定为超时
        if not res:
            if check_login:
                errmsg = u"教务系统连接超时,请稍后重试"
                redis.set(redis_auth_prefix + openid, errmsg, 20)
            else:
                content = u"教务系统连接超时\n\n请稍后重试"
                wechat_custom.send_text(openid, content)

        #  登录失败返回200
        elif res.status_code == 200 and 'alert' in res.text:
            if check_login:
                errmsg = u"用户名或密码不正确"
                redis.set(redis_auth_prefix + openid, errmsg, 20)
            else:
                url = current_app.config['HOST_URL'] + '/auth-score/' + openid
                content = u'用户名或密码不正确\n\n' +\
                    u'<a href="%s">点这里重新绑定学号</a>' % url +\
                    u'\n\n绑定后重试操作即可'
                wechat_custom.send_text(openid, content)

        #  否则就是登录成功, 顺便保存相关信息
        else:
            try:
                score_res = score_page(score_url, session, proxy)
                score_res.encoding = 'GBK'
                # 解析 HTML 内容
                soup = BeautifulSoup(score_res.text, "html.parser")
            except Exception as e:
                current_app.logger.warning(u'登录成功,但是在校成绩查询或解析出错:%s,%s' %
                                           (e, score_url))
                if check_login:
                    errmsg = u"教务系统连接超时,请稍后重试"
                    redis.set(redis_auth_prefix + openid, errmsg, 20)
                else:
                    content = u"学校的教务系统连接超时\n\n请稍后重试"
                    wechat_custom.send_text(openid, content)
            else:
                # 保存用户真实姓名和所在班级信息
                info_url = current_app.config['JW_INFO_URL']
                try:
                    info_res = session.get(info_url)
                    info_res.encoding = 'GBK'
                    pattern = re.compile(r'<p>(.*?)</p>')
                    items = re.findall(pattern, info_res.text)
                except Exception as e:
                    current_app.logger.warning('登录成功, 但获取个人信息出错')
                else:
                    realname = items[1][3:]
                    classname = items[2][3:]
                    #  school_term = items[4][3:]
                    #  TODO 最后的时候把这个改回来
                    school_term = '2016-2017_2'
                    set_user_realname_and_classname(openid, realname,
                                                    classname)
                    #  默认根据班级分组
                    set_user_group(openid, classname)

                # 提取当前学期的成绩
                content = u''
                score_info = []
                for idx, tr in enumerate(soup.find_all('tr')[:-1]):
                    if idx != 0:
                        tds = tr.find_all('td')
                        term = tds[0].contents[0]
                        lesson_name = tds[1].contents[0]
                        score = tds[3].contents[0]
                        if term == school_term:
                            # 组装当前学期成绩文本格式数据回复用户
                            content = content + u'课程名称:%s\n考试成绩:%s\n\n' % (
                                lesson_name, score)
                            score_info.append({
                                "term": term,
                                "lesson_name": lesson_name,
                                "score": score
                            })
                        else:
                            # 组装所有学期成绩数组格式的数据备用
                            score_info.append({
                                "term": term,
                                "lesson_name": lesson_name,
                                "score": score
                            })

                # 查询不到成绩
                if not content:
                    content = u'抱歉,没查询到结果, 可能还没公布成绩\n请稍候查询'
                    wechat_custom.send_text(openid, content)
                else:
                    url = current_app.config[
                        'HOST_URL'] + '/score-report/' + openid
                    data = [{
                        'title': u'%s - %s学期成绩 ' % (realname, school_term),
                        'description': '',
                        'url': url
                    }, {
                        'title': content,
                        'description': '',
                        'url': url
                    }, {
                        'title': '点击查看全部学期的成绩',
                        'description': '',
                        'url': url
                    }]

                    # 缓存结果 1 小时
                    redis.set(redis_prefix + openid, data, 3600)
                    #  发送微信
                    wechat_custom.send_news(openid, data)

                    # 更新缓存成绩,用于 Web 展示,不设置过期时间
                    redis.hmset(
                        'wechat:user:scoreforweb:' + openid, {
                            "real_name": realname,
                            "school_term": school_term,
                            "score_info": score_info,
                            "update_time": time.strftime('%Y-%m-%d %H:%M:%S')
                        })
                # 账号密码保存数据库
                if check_login:
                    # 加密密码
                    cipher = AESCipher(
                        current_app.config['PASSWORD_SECRET_KEY'])
                    studentpwd = cipher.encrypt(studentpwd)
                    set_user_student_info(openid, studentid, studentpwd)
                    redis.set(redis_auth_prefix + openid, 'ok', 20)
示例#23
0
def add_order():
    orders = request.get_json()
    shopToStocks = Neo.get_all(orders['id_shop'])
    new_order = []

    shopToStocks.sort(key=lambda x: x[1])

    for goods in orders['goods']:
        redisdata = redis.hgetall(goods)

        if redisdata == {}:
            update_redis()

        all_stocks = {k: int(v) for k, v in redisdata.items()}
        for i in range(len(shopToStocks)):
            id_stock = shopToStocks[i][0]

            if id_stock in all_stocks.values():
                try:
                    cur_order = next(item for item in new_order
                                     if item['id_stock'] == id_stock)
                except StopIteration:
                    cur_order = {}

                cur_quantity = Postgres.return_quantity(id_stock, goods)

                new_quantity = cur_quantity[0] - orders['goods'][goods]

                if new_quantity >= 0:
                    if cur_order == {}:
                        cur_order.update({'id_shop': orders['id_shop']})
                        cur_order.update({'id_stock': id_stock})
                        cur_order.update({'goods': {}})
                        cur_order['goods'].update(
                            {goods: orders['goods'][goods]})

                        new_order.append(cur_order)
                    else:
                        new_order.remove(cur_order)
                        cur_order['goods'].update(
                            {goods: orders['goods'][goods]})

                        new_order.append(cur_order)

                    if new_quantity == 0:
                        Postgres.delete_state_by_id(id_stock, goods)
                        redis.delete(goods)
                        address_id = Postgres.return_address_and_id(goods)
                        redis.hmset(goods, address_id)
                    else:
                        Postgres.update_quantity(goods, id_stock, new_quantity)

                    break
                else:
                    continue

    for order in new_order:
        id_order = Mongo.insert('orders', order, returned=True)
        body = {
            "date": f"{datetime.now():%Y-%m-%d}",
            "id_order": str(id_order)
        }
        es.index(index='orders', body=body)

    return '.'
示例#24
0
def set_user_info(openid):
    """ 保存用户信息 """
    redis_prefix = "wechat:user:"******"nickname": user_info.nickname,
                    "realname": user_info.realname,
                    "classname": user_info.classname,
                    "sex": user_info.sex,
                    "province": user_info.province,
                    "city": user_info.city,
                    "country": user_info.country,
                    "headimgurl": user_info.headimgurl,
                    "regtime": user_info.regtime
                })

    #  存在信息缓存, 每天更新用户个人信息
    else:
        timeout = int(time.time()) - int(get_user_last_interact_time(openid))
        if timeout > 24 * 60 * 60:
            try:
                client = WeChatClient(current_app.config['APPID'],
                                      current_app.config['APPSECRET'])
                user_info = client.user.get(openid)
                if 'nickname' not in user_info:
                    raise KeyError(user_info)
            except Exception as e:
                current_app.logger.warning('获取用户信息 API 出错: %s' % e)
            else:
                user = WechatUser.query.filter_by(openid=openid).first()
                user.nickname = user_info['nickname']
                user.sex = user_info['sex']
                user.province = user_info['province']
                user.city = user_info['city']
                user.country = user_info['country']
                user.headimgurl = user_info['headimgurl']
                user.update()

                redis.hmset(
                    redis_prefix + openid, {
                        "nickname": user_info['nickname'],
                        "sex": user_info['sex'],
                        "province": user_info['province'],
                        "city": user_info['city'],
                        "country": user_info['country'],
                        "headimgurl": user_info['headimgurl']
                    })
        return None
示例#25
0
def update_redis():
    goods = Postgres.return_goods()
    for g in goods:
        address_id = Postgres.return_address_and_id(g[0])
        redis.hmset(g[0], address_id)
示例#26
0
def push():
    """ 推送图文消息"""
    newsform = NewsForm()
    form = TextForm()
    wechat = init_wechat_sdk()
    client = wechat['client']
    pushnews = Pushnews(author_id=current_user.id)
    if request.method == 'POST':
        #  把推送保存到数据库, 并发送微信
        title = newsform.title.data
        body = newsform.body.data
        to_group = Group.query.get(newsform.group.data)
        to_user = []
        to_user_id = []
        for u in to_group.wechatusers:
            to_user.append(u.openid)
            to_user_id.append(u.id)

        try:
            #  添加到图文素材库
            pushnews.title = title
            pushnews.body = body
            pushnews.to_group = to_group
            pushnews.to_confirmed = json.dumps(to_user_id)
            pushnews.save()
            body_html = pushnews.body_html
            #  更新最新推送的通知缓存
            articles = [{
                'title':
                title,
                'show_cover_pic':
                0,
                'content':
                body_html,  # 看看是否需要处理html
                'author':
                current_user.name,
                'thumb_media_id':
                current_app.config['NEWS_THUMB_MEDIA_ID'],
                'digest':
                current_app.config['NEWS_DIGEST'],
                'content_source_url':
                current_app.config['NEWS_CONTENT_SOURCE_URL'],
                'need_open_comment':
                '1',
                'only_fans_can_comment':
                '1'
            }]
            res = client.material.add_articles(articles)
            #  XXX, 为什么没有保存到数据库, 但却发送成功了
            media_id = res['media_id']
            current_app.logger.warning('添加的图文的media_id: %s' % media_id)
            #  保存到数据库 TODO 多添加几个字段
            pushnews.media_id = media_id
            pushnews.update()
            redis.set("wechat:last_push_time",
                      time.strftime('%Y-%m-%d %H:%M:%S'))
            redis.hmset(
                "wechat:last_push", {
                    "create_time": time.strftime('%Y-%m-%d %H:%M:%S'),
                    "to_confirmed": to_user_id,
                    "media_id": media_id,
                    "pushtype": 'news'
                })
            redis_pushtext_prefix = "wechat:pushnews:" + media_id
            redis.hmset(
                redis_pushtext_prefix, {
                    "media_id": media_id,
                    "to_user": to_user,
                    "create_time": time.strftime('%Y-%m-%d %H:%M:%S'),
                    "to_confirmed": to_user_id
                })

        except Exception as e:
            print(e)
            current_app.logger.warning('添加图文到数据库和缓存失败')

        try:
            #  发送图文消息
            send_result = client.message.send_mass_article(to_user, media_id)
        except Exception as e:
            print(e)
        return redirect(url_for('wechat.user'))
    body_value = None
    return render_template('wechat/messagepush.html',
                           title=pushnews.title,
                           newsform=newsform,
                           form=form,
                           pushpost=pushnews,
                           body_value=body_value)
示例#27
0
def start_session(sender_id, message_text):
    redis.hmset(sender_id, {'started_at': int(time.time())})
    update_session(sender_id, next_filter=0)
    return continue_session(sender_id, redis.hgetall(sender_id), message_text)