Пример #1
0
def get_accesstoken():
    try:
        from model.redisdb import RedisDB
        con = RedisDB().con
    except:
        from redis import Redis
        con = Redis('localhost')
    access_token = con.get('WECHAT_ACCESS_TOKEN')
    if access_token != None:
        return access_token

    from config import APP_KEY, APP_SECRET
    import requests
    import urllib, json
    url = "https://api.weixin.qq.com/cgi-bin/token?"
    data = {
        'grant_type':'client_credential',
        'appid':APP_KEY,
        'secret':APP_SECRET
    }
    res = requests.get(url + urllib.urlencode(data))
    res_data = json.loads(res.text)
    access_token = res_data['access_token']
    con.set('WECHAT_ACCESS_TOKEN', access_token)
    con.expire('WECHAT_ACCESS_TOKEN', 3600)
    return access_token
Пример #2
0
def router_register():
    '''
        路由器注册
    '''
    form = request.form
    if not 'token' in form:
        return 'error'
    token = form['token']
    if token != 'djqoidjqoq12e941nqdqnfhoho-==':
        return 'error'

    from lib.tools import generate_code
    routerid = generate_code()

    from model.redisdb import RedisDB
    con = RedisDB().con
    while con.exists('routerid2key:%s'%routerid):
        routerid = generate_code()

    routerkey = generate_code()

    con.set('routerid2key:%s'%routerid, routerkey)
    import os
    os.system("mkdir tmp/router/%s"%routerid)
    os.system("touch tmp/router/%s/ins.json"%routerid)
    return jsonify(routerid=routerid,routerkey=routerkey)
Пример #3
0
def setbind():
    form = request.form
    openid = form['openid']
    routerid = form['routerid']
    from model.redisdb import RedisDB
    con = RedisDB().con
    con.set('WECHAT_BIND:'+openid, routerid)
    return jsonify(res="ok")
Пример #4
0
def get_status(fromUser):
    from model.redisdb import RedisDB
    con = RedisDB().con

    if con.exists('WECHAT_STATUS:'+fromUser) == False:
        con.set('WECHAT_STATUS:'+fromUser, 0)

    return con.get('WECHAT_STATUS:'+fromUser)
Пример #5
0
def createcall():
    cookies = request.cookies
    weopenid = cookies["weopenid"]
    print weopenid
    form = request.form
    target = form["target"].encode("utf-8")
    print target

    from config import BAIDU_AK

    para = {"address": target, "output": "json", "ak": BAIDU_AK}
    import urllib

    url = "http://api.map.baidu.com/geocoder/v2/?" + urllib.urlencode(para)
    import requests

    res = requests.get(url)
    import json

    data = json.loads(res.text)
    location = data["result"]["location"]
    end_wei = location["lat"]  # weidu
    end_jing = location["lng"]  # jingdu

    from model.redisdb import RedisDB

    con = RedisDB().con
    geo = con.get("openid2geo:%s" % weopenid).split(":")
    start_wei = geo[0]
    start_jing = geo[1]

    access_token = con.get("weopenid2uber:%s" % weopenid)
    url = "https://sandbox-api.uber.com.cn/v1/requests"
    headers = {"Authorization": "Bearer " + access_token, "Content-Type": "application/json"}
    para = {
        "start_latitude": float(start_wei),
        "start_longitude": float(start_jing),
        "end_latitude": float(end_wei),
        "end_longitude": float(end_jing),
    }
    import json

    res = requests.post(url, data=json.dumps(para), headers=headers)
    data = json.loads(res.text)
    request_id = data["request_id"]
    driver = data["driver"]
    eta = data["eta"]
    surge_multiplier = data["surge_multiplier"]
    print request_id, driver, eta, surge_multiplier

    con.set("openid2requestid:%s" % weopenid, request_id)

    return jsonify(res="00000")
Пример #6
0
def add_pinid(pinid, code):
    from wechat.tools import get_accesstoken_by_code

    access_token, openid = get_accesstoken_by_code(code)

    from model.redisdb import RedisDB

    con = RedisDB().con
    openidlist = con.get("pinid2openid:%s" % pinid)
    openidlist = openidlist + ";" + openid
    con.set("pinid2openid:%s" % pinid, openidlist)

    return jsonify(res="00000")
Пример #7
0
def save_image(fromUser, picurl, mediaid):
    status = get_status(fromUser)
    from model.redisdb import RedisDB
    con = RedisDB().con
    routerid = con.get('WECHAT_BIND:'+fromUser)
    import time
    now_time = time.time()
    now_time = time.localtime(now_time)
    now_time = time.strftime('%Y-%m-%d-%H:%M:%S',now_time)
    if status == '1':
        filename = now_time + '.jpg'

        import os
        path = os.path.realpath(__file__)
        path = '/'.join(path.split('/')[:-2])

        os.system('wget -O %s/tmp/user/%s/recent/%s "%s" &'%(path, fromUser, filename, picurl))
        from model.redisdb import RedisDB
        con = RedisDB().con
        num = int(con.get('WECHAT_IMG_NUM:'+fromUser))
        con.set('WECHAT_IMG_NUM:'+fromUser, num+1)

        routerid = con.get('WECHAT_BIND:'+fromUser)
        if routerid != None:
            f = open('%s/tmp/router/%s/ins.json'%(path,routerid),'r')
            text = f.read()
            if text == '':
                text = '{"ins":[]}'
            import json
            data = json.loads(text)
            f.close()
            f = open('%s/tmp/router/%s/ins.json'%(path,routerid),'w')
            data['ins'].append({'type':'image','wechatid':fromUser,'url':'http://wull.me/user/%s/recent/%s'%(fromUser,filename)})
            f.write(json.dumps(data))
            f.close()
        return ''
    elif status == '201':
        import os
        path = os.path.realpath(__file__)
        path = '/'.join(path.split('/')[:-2])
        os.system("mkdir %s/tmp/user/%s"%(path,fromUser))
        os.system("mkdir %s/tmp/user/%s/sanguosha"%(path,fromUser))
        # os.system("mkdir /root/workplace/TI/tiplayer/image/%s/recent"%fromUser)
        os.system('wget -O %s/tmp/user/%s/sanguosha/pic.jpg "%s" &'%(path, fromUser, picurl))
        from model.redisdb import RedisDB
        con = RedisDB().con
        con.set('WECHAT_STATUS:'+fromUser, '202')
        return u'【step 1/6】发一下姓名过来,如“张三”,支持2~4个字'
Пример #8
0
def user_login(username, password, session):
    from model.mysql import MySQL
    sql = MySQL()
    cur = sql.cur
    cur.execute('select id from user where username="******" and password="******"'%(username, password))
    res = []
    if cur.rowcount == 0:
        sql.close()
        return False
    for item in cur:
        res.append(item[0])
    sql.close()

    from model.redisdb import RedisDB
    con = RedisDB().con
    con.set('session2username:%s'%session, res[0])

    return True
Пример #9
0
def user_auth(session, username, password, remember):
    '''
        验证username和password是否匹配,若是则将sessoin与username关联
        若remember为1,则将session放入redis中的记住登录表中
    '''
    from model.mongodb import MongoDB
    db = MongoDB().db
    user = db.user

    one = user.find_one({'username':username,'password':password})
    if one == None:
        return False

    from model.redisdb import RedisDB
    con = RedisDB().con
    key = 'session2username:'+session
    con.set(key, username)
    con.expire(key, 3600)

    return True
Пример #10
0
def bind_success():
    args = request.args
    if not "code" in args:
        return "error"

    code = args["code"]

    cookies = request.cookies
    if not "wecode" in cookies:
        return "error"
    wecode = cookies["wecode"]

    from wechat.tools import get_accesstoken_by_code

    we_access_token, openid = get_accesstoken_by_code(wecode)

    import requests
    from config import UBER_ID, UBER_SECRET

    url = "https://login.uber.com.cn/oauth/v2/token"
    para = {
        "client_secret": UBER_SECRET,
        "client_id": UBER_ID,
        "grant_type": "authorization_code",
        "redirect_uri": "https://wull.me/bind",
        "code": code,
    }
    res = requests.post(url, data=para)
    import json

    data = json.loads(res.text)
    access_token = data["access_token"]
    print wecode, access_token
    from model.redisdb import RedisDB

    con = RedisDB().con
    con.set("weopenid2uber:%s" % openid, access_token)
    con.expire("weopenid2uber:%s" % openid, 3600)

    return render_template("bind_success.html")
Пример #11
0
def createpin():
    cookies = request.cookies
    weopenid = cookies["weopenid"]
    form = request.form
    target = form["target"]
    time = form["time"]
    num = int(form["num"])

    from random import randint

    pin_id = randint(0, 100000)
    from model.redisdb import RedisDB

    con = RedisDB().con
    con.set("pinid2openid:%5d" % pin_id, weopenid)
    con.set("pinid2target:%5d" % pin_id, target)
    con.set("pinid2time:%5d" % pin_id, time)
    con.set("pinid2num:%5d" % pin_id, num)

    return jsonify(res="00000", pinid=pin_id)
Пример #12
0
def wechat_index():
    if request.method == 'GET':
        try:
            args = request.args
            signature = args.get('signature','')
            timestamp = args.get('timestamp','')
            nonce = args.get('nonce','')
            echostr = args.get('echostr')
            token = 'zengzhaoyang'
            list = [token,timestamp,nonce]
            list.sort()
            sha1 = hashlib.sha1()
            map(sha1.update,list)
            hashcode = sha1.hexdigest()
            if hashcode == signature:
                return echostr
            return 'wrong'
        except:
            return 'wrong'
    else:
        data = request.data
        re_touser = re.compile('<ToUserName><!\\[CDATA\\[(.*?)\\]\\]></ToUserName>')
        re_fromuser = re.compile('<FromUserName><!\\[CDATA\\[(.*?)\\]\\]></FromUserName>')
        re_msgType = re.compile('<MsgType><!\\[CDATA\\[(.*?)\\]\\]></MsgType>')
        re_content = re.compile('<Content><!\\[CDATA\\[(.*?)\\]\\]></Content>')
        re_event = re.compile('<Event><!\\[CDATA\\[(.*?)\\]\\]></Event>')
        re_eventkey = re.compile('<EventKey><!\\[CDATA\\[(.*?)\\]\\]></EventKey>')
        re_recognition = re.compile('<Recognition><!\\[CDATA\\[(.*?)\\]\\]></Recognition>')
        re_picurl = re.compile('<PicUrl><!\\[CDATA\\[(.*?)\\]\\]></PicUrl>')
        re_mediaid = re.compile('<MediaId><!\\[CDATA\\[(.*?)\\]\\]></MediaId>')
        re_scantype = re.compile('<ScanType><!\\[CDATA\\[(.*?)\\]\\]></ScanType>')
        re_scanresult = re.compile('<ScanResult><!\\[CDATA\\[(.*?)\\]\\]></ScanResult>')
        re_latitude = re.compile('<Latitude>(.*?)</Latitude>')
        re_longitude = re.compile('<Longitude>(.*?)</Longitude>')

        toUser = re_touser.findall(data)[0]
        fromUser = re_fromuser.findall(data)[0]
        msgType = re_msgType.findall(data)[0]

        if msgType == 'event':
            event = re_event.findall(data)[0]
            if event == 'CLICK':
                eventKey = re_eventkey.findall(data)[0]
                if eventKey == 'QUERY':
                    from model.redisdb import RedisDB
                    con = RedisDB().con
                    access_token = con.get('weopenid2uber:%s'%fromUser)
                    request_id = con.get('openid2requestid:%s'%fromUser)
                    url = 'https://sandbox-api.uber.com.cn/v1/requests/%s'%request_id
                    headers = {'Authorization':'Bearer '+access_token}#,'Content-Type': 'application/json'}
                    import json
                    import requests
                    res = requests.get(url, headers=headers)
                    print res.text
                    data = json.loads(res.text)
                    driver_name = 'null'
                    driver_phone = ''
                    driver_rating = ''
                    eta = ''
                    license_plate = ''
                    try:
                        driver = data['driver']
                        driver_phone = driver['phone_number']
                        driver_rating = driver['rating']
                        driver_name = driver['name']
                        eta = data['eta']
                        license_plate = data['vehicle']['license_plate']
                    except:
                        pass
                    word = '司机:%s\n手机号:%s\n星际:%s\n车牌:%s\n剩余时间:%s分钟\n'%(driver_name, driver_phone, driver_rating, license_plate, eta)
                    return reply_text%(fromUser, toUser, int(time.time()), word)
            if event == 'LOCATION':
                print 'hahaha'
                lat = re_latitude.findall(data)[0]  # weidu
                lng = re_longitude.findall(data)[0]  # jingdu
                print lat,lng
                from model.redisdb import RedisDB
                con = RedisDB().con
                con.set('openid2geo:%s'%fromUser,lat+':'+lng)
                return ''
    

        elif msgType == 'text':
            content = re_content.findall(data)[0]
            return reply_text%(fromUser, toUser, int(time.time()), content)

        elif msgType == 'voice':
            recognition = re_recognition.findall(data)[0]
            pass
Пример #13
0
def bind_user(openid, routeid):
    from redisdb import RedisDB
    con = RedisDB().con
    con.set('WECHAT_BIND:'+openid, routeid)
    return userinfo
Пример #14
0
def check_status(fromUser, content):
    status = get_status(fromUser)
    import os
    path = os.path.realpath(__file__)
    path = '/'.join(path.split('/')[:-2])
    from model.redisdb import RedisDB
    con = RedisDB().con
    print status
    if status == '202':
        length = len(content.decode('utf-8'))
        if length >= 2 and length <= 4:
            os.system("echo %s > %s/tmp/user/%s/sanguosha/config.txt"%(content, path, fromUser))
            con.set('WECHAT_STATUS:'+fromUser, '203')
            return 0, u'【step 2/6】发一下称号过来,如“大傻逼”,支持2~5个字'
        elif length > 4:
            return 0, u'。。哪有这么长的名字,重发一个吧'
        elif length < 2:
            return 0, u'。。哪有一个字的名字,重发一个吧'
    elif status == '203':
        length = len(content.decode('utf-8'))
        if length >= 2 and length <= 5:
            os.system("echo %s >> %s/tmp/user/%s/sanguosha/config.txt"%(content, path, fromUser))
            con.set('WECHAT_STATUS:'+fromUser, '204')
            return 0, u'【step 3/6】发一下血量,支持1~8'
        elif length > 5:
            return 0, u'哎称号太长了放不下,重发一个吧'
        elif length < 2:
            return 0, u'一个字的称号果断没有气势啊,重发一个吧'
    elif status == '204':
        try:
            num = int(content)
            res = ''
            if num > 8:
                num = 8
                res = u'血太多会撑死的,就给你8滴血啦'
            elif num < 1:
                num = 1
                res = u'0血就死了,勉强给你1滴血吧'
            os.system("echo %d >> %s/tmp/user/%s/sanguosha/config.txt"%(num, path, fromUser))
            con.set('WECHAT_STATUS:'+fromUser, '205')
            return 0, res + u'【step 4/6】发一下属性,如“神”,只支持单个文字'
        except:
            return 0, u'求发数字,,不然我识别不出来'
    elif status == '205':
        length = len(content.decode('utf-8'))
        if length == 1:
            os.system("echo %s >> %s/tmp/user/%s/sanguosha/config.txt"%(content, path, fromUser))
            con.set('WECHAT_STATUS:'+fromUser, '206')
            return 0, u'【step 5/6】发一下技能1的名字和描述吧,用空格隔开,如“天才 你在场上的时候所有人都会变成傻逼”,技能名字必须是两个字的,技能描述最多可支持60个汉字,且不能带有空格'
        else:
            return 0, u'属性只支持单个文字啦'
    elif status == '206':
        temp = content.decode('utf-8').split()
        if len(temp) != 2:
            return 0, u'技能名字和描述要用空格分开啦'
        if len(temp[0]) != 2:
            return 0, u'技能名字只支持两个字哦'
        if len(temp[1]) > 60:
            return 0, u'技能描述太长了啦,放不下了'
        os.system("echo %s >> %s/tmp/user/%s/sanguosha/config.txt"%(content, path, fromUser))
        con.set('WECHAT_STATUS:'+fromUser, '207')
        return 0, u'【step 6/6】发一下技能2的名字和描述吧,要求同技能1,此处回复“无”可只显示一个技能'
    elif status == '207':
        if content == '无':
            os.system("echo %s >> %s/tmp/user/%s/sanguosha/config.txt"%(content, path, fromUser))
            con.set('WECHAT_STATUS:'+fromUser, 0)
            os.system("python %s/wechat/s.py %s %s&"%(path,fromUser,get_accesstoken()))
            return 0, u'【pending......】静静等候10秒钟吧'
        temp = content.decode('utf-8').split()
        if len(temp) != 2:
            return 0, u'技能名字和描述要用空格分开啦'
        if len(temp[0]) != 2:
            return 0, u'技能名字只支持两个字哦'
        if len(temp[1]) > 60:
            return 0, u'技能描述太长了啦,放不下了'
        os.system("echo %s >> %s/tmp/user/%s/sanguosha/config.txt"%(content, path, fromUser))
        con.set('WECHAT_STATUS:'+fromUser, 0)
        os.system("python %s/wechat/s.py %s %s&"%(path,fromUser,get_accesstoken()))
        return 0, u'【pending......】静静等候10秒钟吧'
    return -1, 0
Пример #15
0
def set_status(fromUser, choice):
    from model.redisdb import RedisDB
    con = RedisDB().con
    if con.exists('WECHAT_STATUS:'+fromUser) == False:
        con.set('WECHAT_STATUS:'+fromUser, 0)
    if choice == 0:
        con.set('WECHAT_STATUS:'+fromUser, 0)
    elif choice == 1:
        if con.get('WECHAT_STATUS:'+fromUser) == '1':
            num = con.get('WECHAT_IMG_NUM:'+fromUser)
            con.set('WECHAT_STATUS:'+fromUser, 0)
            return int(num)
        else:
            con.set('WECHAT_STATUS:'+fromUser, 1)
            con.set('WECHAT_IMG_NUM:'+fromUser, 0)
            con.expire('WECHAT_STATUS:'+fromUser, 1800)
            import os
            path = os.path.realpath(__file__)
            path = '/'.join(path.split('/')[:-2])
            os.system("mkdir %s/tmp/user/%s"%(path,fromUser))
            os.system("mkdir %s/tmp/user/%s/recent"%(path,fromUser))
            os.system("mkdir %s/tmp/user/%s/sanguosha"%(path,fromUser))
            return -1
    elif choice == 2:
        con.set('WECHAT_STATUS:'+fromUser, '201')